text:
[![Build Status](https://travis-ci.org/rcdexta/hash19.svg)](https://travis-ci.org/rcdexta/hash19)
[![Gem Version](https://badge.fury.io/rb/hash19.svg)](http://badge.fury.io/rb/hash19)
[![Coverage Status](https://img.shields.io/coveralls/rcdexta/hash19.svg)](https://coveralls.io/r/rcdexta/hash19)

![Hash-19](https://s3-us-west-1.amazonaws.com/rcdexta/hash-19-droid.png)

>*Hash-19 is as an assassin droid in the Star Wars Universe. These are durasteel drones uploaded with only the most archaic kill programs* <sup>[Wookieepedia]</sup>

Ahem.. Ahem.. So about this gem itself.. When I was writing an aggregation API that had to talk to multiple services each with their own REST end-points and JSON schema, when mashing up multiple hashes and transforming it to a structure acceptable to the consumer, I ended up writing lot of boiler plate code. I could see patterns and there was clearly scope for optimisation.

A [detailed writeup](https://medium.com/@rcdexta/hash19-a-json-aggregation-library-f2ef43d64a86) explaining the need is available for reading.

Hash19 is an attempt at offering a DSL to tame the JSON manipulation and help in dealing with common use-cases. The features include

* whitelisting attributes
* attribute aliasing and keying
* `has_one` and `has_many` associations
* lazy loading associations via triggers
* mass injection of associations using bulk APIs

## Installation
Add this line to your application's Gemfile:

```ruby
gem 'hash19'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install hash19

### One example for all
```ruby
class Jedi
    include Hash19
    attributes :name, :saber, :padawan_id
    attribute :master, key: :trained_by
    has_one :padawan, using: :padawan_id, trigger: ->(id) { Padawan.find id }
    has_many :killings
end

class Padawan
    include Hash19
    attributes :id, :name
    def find(id)..end #implementation hidden
    def find_all(ids)..end #implementation hidden
end

json = '[{"name": "Anakin Skywalker", "saber": "Single Blade Blue",  "trained_by": "Obi Wan",
         "padawan": {"id": 201, "name": "Ahsoka Tano"}},
        {"name": "Mace Windu", "saber": "Single Blade Violet", "padawan_id": 132, "trained_by": "Yoda"}]'

jedis = JSON.parse(json)
Jedi.new(jedis.first).to_h #{"name"=>"Anakin Skywalker", "saber"=>"Single Blade Blue", "master"=>"Obi Wan",
                           #"padawan"=>{"id"=>201, "name"=>"Ahsoka Tano"}}

Jedi.new(jedis.last).to_h #{"name"=>"Mace Windu", "saber"=>"Single Blade Violet", "master"=>"Yoda",
                           #"padawan"=>{"id"=>132, "name"=>"Depa Billaba["}}

```
All aspects of the code are explained with detailed examples below. This gives a quick snapshot of what the gem can do. Ergo...
* the attributes `name`, `saber` and `padawan_id` have been whitelisted. Any other attribute in the JSON will be ignored
* the attributes can have aliases in the actual JSON
* there can be an inline relationship within the JSON with another entity. For example, each `Jedi` entity can contain a `padawan` object. If the association already exists, it will be transformed. This is true for the first Jedi in the example
* If the association is not present in the JSON, it is lazy loaded. The first call to the attribute will call the trigger to fetch the association, if not present. In this case, for the second Jedi, a call `Padawan#find` will be triggered and the association fetched.

Now, this immediately raises the question about firing multiple calls to Padawan#find when there are many entries without the association populated. And that's where injection is recommended:

```ruby
class Jedis
    include Hash19
    contains :jedi
    inject at: '$', using: :padawan_id, reference: :id,
           trigger: lambda { |ids| Padawan.find_all ids }, as: 'padawan'
end
```
This is like a wrapper class for the Jedi collection. It collects all `padawan_ids` from the complete JSON, calls `Padawan#find_all` once, the bulk-api equivalent of `find`, with a list of ids and injects the content back to the main collection at appropriate places as defined by the json_path in `at`

## Usage

To get started, include the Hash19 module in the target class and you are good.

A detailed documentation of all features can be found below:

1. Whitelisting attributes
```ruby
 class SuperHero
	 include Hash19
	 attributes :name, :strength
	 attribute :universe, key: :comic
 end
 ```
 Assume a JSON payload has many more attributes
 ```json
 [{"name": "Flash", "strength": "Speed", "last_seen": "never", "comic": "DC"},
  {"name": "Magneto", "strength": "Magnetism Control", "first_seen": 1963, "comic": "Marvel"},
  {"name": "Hulk", "strength": "Super Strength", "weakness": "temper", "comic": "Marvel"}]
  ```
  When this JSON is thrown at a Hash19 class...
  ```ruby
    payload = JSON.parse(json)
    results = payload.map { |hash| SuperHero.new(hash).to_h }
    print results #[{"name"=>"Flash", "strength"=>"Speed", "universe"=>"DC"},
                  # {"name"=>"Magneto", "strength"=>"Magnetism Control", "universe"=>"Marvel"},
                  # {"name"=>"Hulk", "strength"=>"Super Strength", "universe"=>"Marvel"}]
  ```
  Note that only the whitelisted attributes are accepted and keys can be aliased. The `to_h` method converts the native hash19 object into a ruby hash.

2. Still a hash
The Hash19 object acts as a wrapper to Ruby Hash. All hash operations are supported by the wrapper. But, finally `to_h` should be called to retrieve the underlying hash.
``` ruby
 hero = SuperHero.new(name: "Flash", strength: "Speed", comic: "DC")
 hero[:name] #Flash
 hero[:nick_name] = "Scarlet Speedster"
 hero.keys #["name", "strength", "universe", "nick_name"]
 hero.to_h #{"name"=>"Flash", "strength"=>"Speed", "universe"=>"DC", "nick_name"=>"Scarlet Speedster"}
```
3. Associations
One-to-one and One-to-many relationships are supported. All associations are lazy loaded unless present directly in the root JSON.
```ruby
class Hashable
    include Hash19
end
class SuperVillain < Hashable
    attribute :name
    has_many :minions
    has_one :doctor
end
class Minion < Hashable
  attributes :name, :sound
end
class Doctor < Hashable
  attribute :name
end
```
Now, a JSON of the following structure
```json
{"name": "Gru", "doctor": {"name": "Nefario"},
"minions": [{"name": "Poppadom", "sound": "Weebaa"},{"name": "Gelato", "sound": "Ooojaa"}]
```
can be parsed with all associations loaded when calling `SuperVillain.new(json_as_hash)`

If the parent JSON does not contain the associations and they are powered by separate API calls, we can specify triggers to load them.
```ruby
class SuperVillain < Hashable
    attribute :name, doctor_id
    has_one :doctor, using: :doctor_id, trigger: ->(id) { Error.find id }
end
```
If you notice the trigger, the `using` parameter denotes the attribute to use to fetch the association and the lambda passed to `trigger` will be invoked to fetch the association. This is lazy loaded, in the sense when a call is made to `.doctor` or `.to_h`, the trigger is fired.

Associations also support alternate keys and aliasing... The below code snippet illustrates use of a different key in source json, the class to use to construct the object and the alias key in the target.

```ruby
has_one :child, key: :offspring, alias: :junior
{offspring: {name: 'Luke Skywalker'}} # will be parsed as {'junior' => {'name' => 'Luke Skywalker'}}
```

4. Bulk Injections

Left to itself with associations, when the root JSON is a large collection with none of the associations populated in the first place, there will be several triggers fired for each item in the collection. This is the HTTP equivalent of `N+1` in the ORM world. To avoid this, Hash19 supports association injections. Let's dive into an example:

```ruby
class SuperHeroes < Hashable
    contains :super_heroes
    inject at: '$', using: :weapon_id, reference: :id, trigger: lambda { |ids| Weapon.find_all ids }
  end

  class SuperHero < Hashable
    attributes :name, :power, :weapon_id
    has_one :weapon, using: :weapon_id, trigger: lambda { |id| Weapon.find id }
  end

  class Weapon < Hashable
    attributes :name, :id
    def find_all(ids)..end #calls bulk API across wire. Implementation hidden
  end
```
If you notice, `SuperHeroes` is a wrapper class around `SuperHero`. This is the object equivalent of a JSON collection. The `inject` method will extract `weapon_id` from all items in the collection based on the json-path specified by `at` and call the `trigger` and put back the resultant entities joining `superhero.weapon_id` and `weapon.id`

So, a json like below
```ruby
super_heros = SuperHeroes.new([{name: 'iron man', power: 'none', weapon_id: 1},
				{name: 'thor', power: 'class 100', weapon_id: 2},
				{name: 'hulk', power: 'bulk', weapon_id: 3}])
```

will lead to one call to `Weapon#find_all` with params `[1,2,3]` to fetch all weapon details. And the final collection will be of the form:
```ruby
super_heroes.to_h #[{'name' => 'iron man', 'power' => 'none', 'weapon' => {'name' => 'jarvis', 'id' => 1}},
                  #{'name' => 'thor', 'power' => 'class 100', 'weapon' => {'name' => 'hammer', 'id' => 2}},
                  #{'name' => 'hulk', 'power' => 'bulk', 'weapon' => {'name' => 'hands', 'id' => 3}}
```

Note that `injection` always overrides the association trigger since the former is eager loaded and latter is lazy loaded thus avoiding the `N+1` calls.

One other important thing to remember is that all the injections will happen in parallel. Hash19 uses [eldritch](https://github.com/beraboris/eldritch) gem to trigger multiple injections concurrently. If one inject is dependent on another or if you want the injections to happen in sequence add `async: false` to make calls synchronously.

Please refer to the [tests](https://github.com/rcdexta/hash19/tree/master/spec/hash19) for more examples and documentation.

## Contributing

1. Fork it ( https://github.com/rcdexta/hash19/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
date: '2011-08-17'
title: Mini Presentations
location: Lone Star College - Montgomery
---
Join us as some of our members take a turn giving 15 minute presentations.  Topics will include WebOS, Data Warehousing, and Location Aware apps.

redpajama_set_name: RedPajamaGithub


text:
package org.priha;

import java.util.Random;

import javax.jcr.*;

public class TestUtil
{

    public static void emptyRepo(Repository repository) throws LoginException, RepositoryException
    {
        Session anonSession = repository.login();

        try
        {
            String[] workspaces = anonSession.getWorkspace().getAccessibleWorkspaceNames();

            for( String ws : workspaces )
            {
                //System.out.println("Emptying repo "+ws);
                Session s = repository.login(new SimpleCredentials("username","password".toCharArray()),ws);

                try
                {
                    s.refresh(false);
                    deleteTree( s.getRootNode() );
                    s.save();
                }
                finally
                {
                    s.logout();
                }
            }
        }
        catch( Exception e )
        {
            e.printStackTrace( System.err );
        }
        finally
        {
            anonSession.logout();
        }
    }

    public static void deleteTree( Node start ) throws RepositoryException
    {
        for( NodeIterator i = start.getNodes(); i.hasNext(); )
        {
            Node n = i.nextNode();
            if( !n.getDefinition().isProtected() && !n.getPath().equals("/jcr:system"))
                n.remove();
        }
    }

    public static void printSpeed( String msg, int iters, long start, long end )
    {
        long time = end - start;
        float itersSec = iters / ((float)time/1000);

        String itersSecString = "";
        if( itersSec < 1000.0 )   itersSecString = String.format( "%.0f", itersSec );
        else if( itersSec < 1e6 ) itersSecString = String.format( "%.2fk", itersSec/1000 );
        else if( itersSec < 1e9 ) itersSecString = String.format( "%.2fM", itersSec/1e6 );

        System.out.println( msg + ":" + iters + " iterations in "+time+" ms ("+itersSecString+" iterations/second)");
    }

    /**
     *  Returns a random string of sixteen uppercase characters.
     *
     *  @return A random string
     */
    public static String getUniqueID(int length)
    {
        StringBuffer sb = new StringBuffer();
        Random rand = new Random();

        for( int i = 0; i < length; i++ )
        {
            char x = (char)('A'+rand.nextInt(26));

            sb.append(x);
        }

        return sb.toString();
    }
}


text:
package org.apache.lucene.util;

import java.text.ParseException;
import java.util.Locale;

/**
 * Use by certain classes to match version compatibility
 * across releases of Lucene.
 *
 *
WARNING: When changing the version parameter
 * that you supply to components in Lucene, do not simply
 * change the version at search-time, but instead also adjust
 * your indexing code to match, and re-index.
 */
public final class Version {

  /**
   * Match settings and bugs in Lucene's 4.0.0-ALPHA release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_0_0_ALPHA = new Version(4, 0, 0, 0);

  /**
   * Match settings and bugs in Lucene's 4.0.0-BETA release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_0_0_BETA = new Version(4, 0, 0, 1);

  /**
   * Match settings and bugs in Lucene's 4.0.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_0_0 = new Version(4, 0, 0, 2);

  /**
   * Match settings and bugs in Lucene's 4.1.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_1_0 = new Version(4, 1, 0);

  /**
   * Match settings and bugs in Lucene's 4.2.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_2_0 = new Version(4, 2, 0);

  /**
   * Match settings and bugs in Lucene's 4.2.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_2_1 = new Version(4, 2, 1);

  /**
   * Match settings and bugs in Lucene's 4.3.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_3_0 = new Version(4, 3, 0);

  /**
   * Match settings and bugs in Lucene's 4.3.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_3_1 = new Version(4, 3, 1);

  /**
   * Match settings and bugs in Lucene's 4.4.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_4_0 = new Version(4, 4, 0);

  /**
   * Match settings and bugs in Lucene's 4.5.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_5_0 = new Version(4, 5, 0);

  /**
   * Match settings and bugs in Lucene's 4.5.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_5_1 = new Version(4, 5, 1);

  /**
   * Match settings and bugs in Lucene's 4.6.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_6_0 = new Version(4, 6, 0);

  /**
   * Match settings and bugs in Lucene's 4.6.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_6_1 = new Version(4, 6, 1);

  /**
   * Match settings and bugs in Lucene's 4.7.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_7_0 = new Version(4, 7, 0);

  /**
   * Match settings and bugs in Lucene's 4.7.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_7_1 = new Version(4, 7, 1);

  /**
   * Match settings and bugs in Lucene's 4.7.2 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_7_2 = new Version(4, 7, 2);

  /**
   * Match settings and bugs in Lucene's 4.8.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_8_0 = new Version(4, 8, 0);

  /**
   * Match settings and bugs in Lucene's 4.8.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_8_1 = new Version(4, 8, 1);

  /**
   * Match settings and bugs in Lucene's 4.9.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_9_0 = new Version(4, 9, 0);

  /**
   * Match settings and bugs in Lucene's 4.9.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_9_1 = new Version(4, 9, 1);

  /**
   * Match settings and bugs in Lucene's 4.10.0 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_10_0 = new Version(4, 10, 0);

  /**
   * Match settings and bugs in Lucene's 4.10.1 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_10_1 = new Version(4, 10, 1);

  /**
   * Match settings and bugs in Lucene's 4.10.2 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_10_2 = new Version(4, 10, 2);

  /**
   * Match settings and bugs in Lucene's 4.10.3 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_10_3 = new Version(4, 10, 3);

  /**
   * Match settings and bugs in Lucene's 4.10.4 release.
   * @deprecated (5.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_4_10_4 = new Version(4, 10, 4);

  /** Match settings and bugs in Lucene's 5.0 release.
   *

   *  Use this to get the latest & greatest settings, bug
   *  fixes, etc, for Lucene.
   * @deprecated (5.1.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_0_0 = new Version(5, 0, 0);

  /**
   * Match settings and bugs in Lucene's 5.1.0 release.
   * @deprecated (5.2.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_1_0 = new Version(5, 1, 0);

  /**
   * Match settings and bugs in Lucene's 5.2.0 release.
   * @deprecated (5.3.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_2_0 = new Version(5, 2, 0);

  /**
   * Match settings and bugs in Lucene's 5.2.1 release.
   * @deprecated Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_2_1 = new Version(5, 2, 1);

  /**
   * Match settings and bugs in Lucene's 5.3.0 release.
   * @deprecated (5.4.0) Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_3_0 = new Version(5, 3, 0);

  /**
   * Match settings and bugs in Lucene's 5.3.1 release.
   * @deprecated Use latest
   */
  @Deprecated
  public static final Version LUCENE_5_3_1 = new Version(5, 3, 1);

  /**
   * Match settings and bugs in Lucene's 5.4.0 release.
   */
  public static final Version LUCENE_5_4_0 = new Version(5, 4, 0);

  // To add a new version:
  //  * Only add above this comment
  //  * If the new version is the newest, change LATEST below and deprecate the previous LATEST

  /**
   *
WARNING: if you use this setting, and then
   * upgrade to a newer release of Lucene, sizable changes
   * may happen.  If backwards compatibility is important
   * then you should instead explicitly specify an actual
   * version.
   *

   * If you use this constant then you  may need to
   * re-index all of your documents when upgrading
   * Lucene, as the way text is indexed may have changed.
   * Additionally, you may need to re-test your entire
   * application to ensure it behaves as expected, as
   * some defaults may have changed and may break functionality
   * in your application.
   */
  public static final Version LATEST = LUCENE_5_4_0;

  /**
   * Constant for backwards compatibility.
   * @deprecated Use {@link #LATEST}
   */
  @Deprecated
  public static final Version LUCENE_CURRENT = LATEST;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_0_0} instead (this constant actually points to {@link #LUCENE_4_0_0_ALPHA} to match whole 4.0 series). */
  @Deprecated
  public static final Version LUCENE_4_0 = LUCENE_4_0_0_ALPHA;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_1_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_1 = LUCENE_4_1_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_2_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_2 = LUCENE_4_2_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_3_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_3 = LUCENE_4_3_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_4_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_4 = LUCENE_4_4_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_5_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_5 = LUCENE_4_5_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_6_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_6 = LUCENE_4_6_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_7_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_7 = LUCENE_4_7_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_8_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_8 = LUCENE_4_8_0;

  /** @deprecated Bad naming of constant; use {@link #LUCENE_4_9_0} instead. */
  @Deprecated
  public static final Version LUCENE_4_9 = LUCENE_4_9_0;

  /**
   * Parse a version number of the form {@code "major.minor.bugfix.prerelease"}.
   *
   * Part {@code ".bugfix"} and part {@code ".prerelease"} are optional.
   * Note that this is forwards compatible: the parsed version does not have to exist as
   * a constant.
   *
   * @lucene.internal
   */
  public static Version parse(String version) throws ParseException {

    StrictStringTokenizer tokens = new StrictStringTokenizer(version, '.');
    if (tokens.hasMoreTokens() == false) {
      throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0);
    }

    int major;
    String token = tokens.nextToken();
    try {
      major = Integer.parseInt(token);
    } catch (NumberFormatException nfe) {
      ParseException p = new ParseException("Failed to parse major version from \"" + token + "\" (got: " + version + ")", 0);
      p.initCause(nfe);
      throw p;
    }

    if (tokens.hasMoreTokens() == false) {
      throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0);
    }

    int minor;
    token = tokens.nextToken();
    try {
      minor = Integer.parseInt(token);
    } catch (NumberFormatException nfe) {
      ParseException p = new ParseException("Failed to parse minor version from \"" + token + "\" (got: " + version + ")", 0);
      p.initCause(nfe);
      throw p;
    }

    int bugfix = 0;
    int prerelease = 0;
    if (tokens.hasMoreTokens()) {

      token = tokens.nextToken();
      try {
        bugfix = Integer.parseInt(token);
      } catch (NumberFormatException nfe) {
        ParseException p = new ParseException("Failed to parse bugfix version from \"" + token + "\" (got: " + version + ")", 0);
        p.initCause(nfe);
        throw p;
      }

      if (tokens.hasMoreTokens()) {
        token = tokens.nextToken();
        try {
          prerelease = Integer.parseInt(token);
        } catch (NumberFormatException nfe) {
          ParseException p = new ParseException("Failed to parse prerelease version from \"" + token + "\" (got: " + version + ")", 0);
          p.initCause(nfe);
          throw p;
        }
        if (prerelease == 0) {
          throw new ParseException("Invalid value " + prerelease + " for prerelease; should be 1 or 2 (got: " + version + ")", 0);
        }

        if (tokens.hasMoreTokens()) {
          // Too many tokens!
          throw new ParseException("Version is not in form major.minor.bugfix(.prerelease) (got: " + version + ")", 0);
        }
      }
    }

    try {
      return new Version(major, minor, bugfix, prerelease);
    } catch (IllegalArgumentException iae) {
      ParseException pe = new ParseException("failed to parse version string \"" + version + "\": " + iae.getMessage(), 0);
      pe.initCause(iae);
      throw pe;
    }
  }

  /**
   * Parse the given version number as a constant or dot based version.
   *
This method allows to use {@code "LUCENE_X_Y"} constant names,
   * or version numbers in the format {@code "x.y.z"}.
   *
   * @lucene.internal
   */
  public static Version parseLeniently(String version) throws ParseException {
    String versionOrig = version;
    version = version.toUpperCase(Locale.ROOT);
    switch (version) {
      case "LATEST":
      case "LUCENE_CURRENT":
        return LATEST;
      case "LUCENE_4_0_0":
        return LUCENE_4_0_0;
      case "LUCENE_4_0_0_ALPHA":
        return LUCENE_4_0_0_ALPHA;
      case "LUCENE_4_0_0_BETA":
        return LUCENE_4_0_0_BETA;
      default:
        version = version
          .replaceFirst("^LUCENE_(\\d+)_(\\d+)_(\\d+)$", "$1.$2.$3")
          .replaceFirst("^LUCENE_(\\d+)_(\\d+)$", "$1.$2.0")
          .replaceFirst("^LUCENE_(\\d)(\\d)$", "$1.$2.0");
        try {
          return parse(version);
        } catch (ParseException pe) {
          ParseException pe2 = new ParseException("failed to parse lenient version string \"" + versionOrig + "\": " + pe.getMessage(), 0);
          pe2.initCause(pe);
          throw pe2;
        }
    }
  }

  /** Returns a new version based on raw numbers
   *
   *  @lucene.internal */
  public static Version fromBits(int major, int minor, int bugfix) {
    return new Version(major, minor, bugfix);
  }

  /** Major version, the difference between stable and trunk */
  public final int major;
  /** Minor version, incremented within the stable branch */
  public final int minor;
  /** Bugfix number, incremented on release branches */
  public final int bugfix;
  /** Prerelease version, currently 0 (alpha), 1 (beta), or 2 (final) */
  public final int prerelease;

  // stores the version pieces, with most significant pieces in high bits
  // ie:  | 1 byte | 1 byte | 1 byte |   2 bits   |
  //         major   minor    bugfix   prerelease
  private final int encodedValue;

  private Version(int major, int minor, int bugfix) {
    this(major, minor, bugfix, 0);
  }

  private Version(int major, int minor, int bugfix, int prerelease) {
    this.major = major;
    this.minor = minor;
    this.bugfix = bugfix;
    this.prerelease = prerelease;

    // NOTE: do not enforce major version so we remain future proof, except to
    // make sure it fits in the 8 bits we encode it into:
    if (major > 255 || major < 0) {
      throw new IllegalArgumentException("Illegal major version: " + major);
    }
    if (minor > 255 || minor < 0) {
      throw new IllegalArgumentException("Illegal minor version: " + minor);
    }
    if (bugfix > 255 || bugfix < 0) {
      throw new IllegalArgumentException("Illegal bugfix version: " + bugfix);
    }
    if (prerelease > 2 || prerelease < 0) {
      throw new IllegalArgumentException("Illegal prerelease version: " + prerelease);
    }
    if (prerelease != 0 && (minor != 0 || bugfix != 0)) {
      throw new IllegalArgumentException("Prerelease version only supported with major release (got prerelease: " + prerelease + ", minor: " + minor + ", bugfix: " + bugfix + ")");
    }

    encodedValue = major << 18 | minor << 10 | bugfix << 2 | prerelease;

    assert encodedIsValid();
  }

  /**
   * Returns true if this version is the same or after the version from the argument.
   */
  public boolean onOrAfter(Version other) {
    return encodedValue >= other.encodedValue;
  }

  @Override
  public String toString() {
    if (prerelease == 0) {
      return "" + major + "." + minor + "." + bugfix;
    }
    return "" + major + "." + minor + "." + bugfix + "." + prerelease;
  }

  @Override
  public boolean equals(Object o) {
    return o != null && o instanceof Version && ((Version)o).encodedValue == encodedValue;
  }

  // Used only by assert:
  private boolean encodedIsValid() {
    assert major == ((encodedValue >>> 18) & 0xFF);
    assert minor == ((encodedValue >>> 10) & 0xFF);
    assert bugfix == ((encodedValue >>> 2) & 0xFF);
    assert prerelease == (encodedValue & 0x03);
    return true;
  }

  @Override
  public int hashCode() {
    return encodedValue;
  }
}


text:
import * as mongoose from 'mongoose';
import * as bcrypt from 'bcrypt';
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: {
    type: String,
    required: 'Name is required'
  },
  email: {type: String,
    unique: true,
    required: 'Email is required',
    match: [/.+\@.+\..+/, "Please enter a valid email"]
  },
  password: {
    type: String,
    required: 'Password is required'
  }
});

UserSchema.methods.hashPassword = function(password) {
  this.password = bcrypt.hashSync(password, bcrypt.genSaltSync(8));
};

UserSchema.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.password);
};

const User = mongoose.model('User', UserSchema);

export default User;


text:
import React, { PropsWithChildren, useMemo } from 'react';

import { SelectableValue } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';

import { VariableSelectField } from '../editor/VariableSelectField';
import { VariableRefresh } from '../types';

interface Props {
  onChange: (option: SelectableValue<VariableRefresh>) => void;
  refresh: VariableRefresh;
}

const REFRESH_OPTIONS = [
  { label: 'On dashboard load', value: VariableRefresh.onDashboardLoad },
  { label: 'On time range change', value: VariableRefresh.onTimeRangeChanged },
];

export function QueryVariableRefreshSelect({ onChange, refresh }: PropsWithChildren<Props>) {
  const value = useMemo(() => REFRESH_OPTIONS.find((o) => o.value === refresh) ?? REFRESH_OPTIONS[0], [refresh]);

  return (
    <VariableSelectField
      name="Refresh"
      value={value}
      options={REFRESH_OPTIONS}
      onChange={onChange}
      labelWidth={10}
      testId={selectors.pages.Dashboard.Settings.Variables.Edit.QueryVariable.queryOptionsRefreshSelectV2}
      tooltip="When to update the values of this variable."
    />
  );
}


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>
Uses of Interface gr.forth.ics.util.Factory (FlexiGraph Reference)
</TITLE>

<META NAME="date" CONTENT="2010-10-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
gr.forth.ics.util.Factory

Packages that use Factory

gr.forth.ics.graph

gr.forth.ics.util

Uses of Factory in gr.forth.ics.graph

Constructors in gr.forth.ics.graph with parameters of type Factory

FoldingGraph(Graph graph,
             Factory<Graph> graphFactory)

Uses of Factory in gr.forth.ics.util

Classes in gr.forth.ics.util that implement Factory

 class
ClassInstanceFactory<T>

Constructors in gr.forth.ics.util with parameters of type Factory

DVMap(Factory<V> factory)

DVMap(java.util.Map<K,V> delegate,
      Factory<V> factory)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package test;

import static org.junit.Assert.assertEquals;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import concursantes.Concursante;
import concursantes.Malabarista;
import concursantes.Musico;

//indicamos que vamos a corre un clase utilizando spring y junit4
@RunWith(SpringJUnit4ClassRunner.class)
//indicamos la localizacion de nuestro archivo de la fabrica de spring
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestConcursoTalentos {

	Log logger = LogFactory.getLog("Iniciando TestConcursoTalentos");

	//recuperamos los beans utilizando las anotaciones
	@Autowired
	@Qualifier("solei")
	private Concursante malabarista1;
	@Autowired
	@Qualifier("soleiRecitador")
	private Concursante malabarista2;
	@Autowired
	@Qualifier("jasonPiano")
	private Concursante musico1;
	@Autowired
	@Qualifier("jasonSax")
	private Concursante musico2;

	@Test
	public void test() {
		logger.info("Inicio de ejecutar Malabarista");
		int noPelotas = 10;
		malabarista1.ejecutar();
		assertEquals(noPelotas, ((Malabarista) malabarista1).getPelotas());
		logger.info("Fin de Malabarista");

		logger.info("Inicio de Malabarista Recitador");
		noPelotas = 15;
		malabarista2.ejecutar();
		assertEquals(noPelotas, ((Malabarista) malabarista2).getPelotas());
		logger.info("Fin de Malabarista Recitador");

		logger.info("Inicio de ejecutar Pianista");
		String cancion = "Noche de Paz";
		musico1.ejecutar();
		assertEquals(cancion, ((Musico) musico1).getCancion());
		logger.info("Fin de Pianista");

		logger.info("Inicio de ejecutar Saxofonista");
		cancion = "Equinox";
		musico2.ejecutar();
		assertEquals(cancion,((Musico) musico2).getCancion());
		logger.info("Fin de Saxofonista");

	}

}


text:
        <button class="navbar-toggle" type="button" data-ng-click="toggleCollapsibleMenu()">
            Toggle navigation

        </button>
        TrafficUpdate

                            Edit Profile

                            Change Password

                            Signout


text:
#include "tensorflow/compiler/xla/service/gpu/gpu_executable.h"

#include <set>
#include <utility>
#include <vector>

#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/logical_buffer.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/compiler/xla/service/transfer_manager.h"
#include "tensorflow/compiler/xla/shape_tree.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"

namespace se = ::perftools::gputools;

namespace xla {
namespace gpu {
namespace {

// A helper class for profiling HLO in the course of GPU program execution.
// All of the profiling is guarded internally, to avoid the caller needing to
// have lots of conditionals sprinkled around.
class HloExecutionProfiler {
 public:
  // If profiling is enabled, start an execution timer running.
  explicit HloExecutionProfiler(bool do_profile, HloExecutionProfile* profile,
                                se::Stream* stream,
                                const HloComputation* computation)
      : do_profile_(do_profile),
        profile_(profile),
        stream_(stream),
        computation_(computation) {
    if (do_profile_) {
      clock_rate_ghz_ =
          stream->parent()->GetDeviceDescription().clock_rate_ghz();
      execution_timer_.reset(new se::Timer(stream->parent()));
      per_op_timer_.reset(new se::Timer(stream->parent()));
      stream->InitTimer(execution_timer_.get())
          .ThenStartTimer(execution_timer_.get());
      stream->InitTimer(per_op_timer_.get());
    }
  }

  // If profiling is enabled, sets the total cycle count on the profile from the
  // execution timer.
  ~HloExecutionProfiler() {
    if (do_profile_) {
      stream_->ThenStopTimer(execution_timer_.get());
      stream_->BlockHostUntilDone();
      profile_->set_total_cycles_executed(
          *computation_, execution_timer_->Nanoseconds() * clock_rate_ghz_);
    }
  }

  // If profiling is enabled, starts the per-operation timer.
  void StartOperation() {
    if (do_profile_) {
      stream_->ThenStartTimer(per_op_timer_.get());
    }
  }

  // If profiling is enabled, stops the per-operation timer and records the time
  // that the hlo_instruction took to execute in the profile.
  void FinishOperation(const HloInstruction* hlo_instruction) {
    if (do_profile_) {
      stream_->ThenStopTimer(per_op_timer_.get());
      stream_->BlockHostUntilDone();
      profile_->AddProfileResult(
          hlo_instruction, per_op_timer_->Nanoseconds() * clock_rate_ghz_);
    }
  }

 private:
  const bool do_profile_;
  double clock_rate_ghz_;
  HloExecutionProfile* profile_;
  se::Stream* stream_;
  const HloComputation* computation_;
  std::unique_ptr<se::Timer> execution_timer_;
  std::unique_ptr<se::Timer> per_op_timer_;
};

}  // namespace

// Implementation note: HLO profiling is always enabled for GPU executables,
// since we can use timers around thunks.
GpuExecutable::GpuExecutable(tensorflow::StringPiece ptx,
                             std::unique_ptr<ThunkSchedule> thunk_schedule,
                             std::unique_ptr<HloModule> hlo_module,
                             std::unique_ptr<HloModuleConfig> module_config,
                             std::unique_ptr<BufferAssignment> assignment)
    : Executable(std::move(hlo_module), std::move(module_config)),
      ptx_(ptx),
      thunk_schedule_(std::move(thunk_schedule)),
      assignment_(std::move(assignment)) {}

Status GpuExecutable::ExecuteThunks(
    const ServiceExecutableRunOptions* run_options,
    const BufferAllocations& buffer_allocations,
    HloExecutionProfile* hlo_execution_profile) {
  se::Stream* main_stream = run_options->stream();

  bool do_profile = hlo_execution_profile != nullptr;
  if (do_profile) {
    LOG(WARNING) << "PROFILING: profiling is enabled";
  }
  HloExecutionProfiler profiler(do_profile, hlo_execution_profile, main_stream,
                                hlo_module_->entry_computation());

  // Stream 0 indicates `main_stream` and substreams start from stream 1.
  std::vector<Pool<se::Stream>::SmartPtr> sub_streams;
  while (sub_streams.size() + 1 < thunk_schedule_->StreamCount()) {
    sub_streams.emplace_back();
    TF_ASSIGN_OR_RETURN(
        sub_streams.back(),
        run_options->BorrowStream(main_stream->parent()->device_ordinal()));
  }

  std::map<const Thunk*, std::unique_ptr<se::Event>> thunk_to_finish_event;
  for (Thunk* thunk : thunk_schedule_->TotalOrder()) {
    TF_RETURN_IF_ERROR(thunk->Initialize(*this));
    int32 stream_no =
        thunk_schedule_->StreamNumberForHlo(*thunk->hlo_instruction());
    se::Stream* stream =
        (stream_no == 0 ? main_stream : sub_streams[stream_no - 1].get());

    for (const Thunk* dependency : thunk_schedule_->DependsOn(thunk)) {
      stream->ThenWaitFor(FindOrDie(thunk_to_finish_event, dependency).get());
    }

    profiler.StartOperation();
    VLOG(2) << "Executing the thunk for "
            << thunk->hlo_instruction()->ToString();
    TF_RETURN_IF_ERROR(thunk->ExecuteOnStream(buffer_allocations, stream));
    if (thunk_schedule_->Depended(thunk)) {
      auto finish_event = MakeUnique<se::Event>(main_stream->parent());
      finish_event->Init();
      stream->ThenRecordEvent(finish_event.get());
      thunk_to_finish_event[thunk] = std::move(finish_event);
    }
    profiler.FinishOperation(thunk->hlo_instruction());
  }

  main_stream->ThenWaitFor(&sub_streams);
  // Make sure kernels are completed before deallocating temporary buffers.
  // TODO(b/30100571): we could potentially postpone deallocating the temp
  // buffers until a different computation is executed.
  if (!main_stream->BlockHostUntilDone()) {
    return InternalError("Failed to complete all kernels launched on stream %p",
                         main_stream);
  }

  return Status::OK();
}

StatusOr<se::DeviceMemoryBase> GpuExecutable::ExecuteOnStream(
    const ServiceExecutableRunOptions* run_options,
    tensorflow::gtl::ArraySlice<se::DeviceMemoryBase> arguments,
    HloExecutionProfile* hlo_execution_profile) {
  se::Stream* stream = run_options->stream();
  DeviceMemoryAllocator* memory_allocator = run_options->allocator();
  // This ExecuteOnStream overload should only be called if has_hybrid_result is
  // false.
  TF_RET_CHECK(!module_config().has_hybrid_result());

  BufferAllocations::Builder buffer_allocations_builder;
  for (BufferAllocation::Index i = 0; i < assignment_->Allocations().size();
       ++i) {
    const BufferAllocation& allocation = assignment_->GetAllocation(i);
    if (allocation.is_entry_computation_parameter()) {
      buffer_allocations_builder.RegisterBuffer(
          i, arguments[allocation.parameter_number()]);
    }
  }
  se::StreamExecutor* executor = stream->parent();
  TF_ASSIGN_OR_RETURN(
      auto buffer_allocations,
      buffer_allocations_builder.Build(*assignment_, executor->device_ordinal(),
                                       memory_allocator));

  TF_RETURN_IF_ERROR(
      ExecuteThunks(run_options, *buffer_allocations, hlo_execution_profile));

  HloInstruction* root = hlo_module_->entry_computation()->root_instruction();
  TF_ASSIGN_OR_RETURN(const BufferAllocation::Slice output_slice,
                      assignment_->GetUniqueTopLevelOutputSlice());
  se::DeviceMemoryBase output_buffer_address =
      buffer_allocations->GetDeviceAddress(output_slice.index());

  if (ShapeUtil::IsTuple(root->shape())) {
    std::set<se::DeviceMemoryBase> referred_by_output;
    if (GetRootPointsToSet().IsAmbiguous()) {
      // The points-to set of the root is ambiguous so we need to examine the
      // result data to determine which buffers are contained in the result.
      TF_ASSIGN_OR_RETURN(
          TransferManager * transfer_manager,
          TransferManager::GetForPlatform(executor->platform()));
      TF_ASSIGN_OR_RETURN(referred_by_output,
                          transfer_manager->GatherBufferPointersFromTuple(
                              executor, output_buffer_address, root->shape()));
    } else {
      // The points-to set of the root is unambiguous so it's known statically
      // which buffers are in the result. Gather these buffers using the root's
      // points-to set.
      TF_RETURN_IF_ERROR(GetRootPointsToSet().ForEachElement(
          [&referred_by_output, &buffer_allocations, this](
              const ShapeIndex& /*index*/, bool /*is_leaf*/,
              const std::vector<const LogicalBuffer*>& buffers) {
            // The points to set is unambiguous so the set should be a
            // singleton. That is, we know exactly which instruction produced
            // the array at this element.
            CHECK_EQ(1, buffers.size());
            HloInstruction* hlo = buffers[0]->instruction();
            TF_ASSIGN_OR_RETURN(
                const BufferAllocation::Slice slice,
                this->assignment_->GetUniqueSlice(hlo, buffers[0]->index()));
            CHECK(!slice.allocation()->is_entry_computation_parameter());
            referred_by_output.insert(
                buffer_allocations->GetDeviceAddress(slice.index()));
            return Status::OK();
          }));
    }
    TF_RETURN_IF_ERROR(
        buffer_allocations->TearDown(referred_by_output, *assignment_));
  } else {
    // If the computation result is not a tuple, we can delete all temporary
    // buffers that are not the output.
    TF_RETURN_IF_ERROR(
        buffer_allocations->TearDown({output_buffer_address}, *assignment_));
  }
  return output_buffer_address;
}

StatusOr<std::unique_ptr<ShapedBuffer>> GpuExecutable::ExecuteOnStream(
    const ServiceExecutableRunOptions* run_options,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    HloExecutionProfile* hlo_execution_profile) {
  DeviceMemoryAllocator* memory_allocator = run_options->allocator();
  // This ExecuteOnStream overload should only be called by the LocalService
  // which sets has_hybrid_result to true.
  TF_RET_CHECK(module_config().has_hybrid_result());

  if (GetRootPointsToSet().IsAmbiguous()) {
    return Unimplemented("Points-to set of root instruction is ambiguous");
  }

  BufferAllocations::Builder buffer_allocations_builder;
  for (BufferAllocation::Index i = 0; i < assignment_->Allocations().size();
       ++i) {
    const BufferAllocation& allocation = assignment_->GetAllocation(i);
    if (allocation.is_entry_computation_parameter()) {
      auto param_no = allocation.parameter_number();
      if (ShapeUtil::IsTuple(arguments[param_no]->shape())) {
        return Unimplemented("Tuple ShapedBuffer arguments not supported");
      }
      buffer_allocations_builder.RegisterBuffer(
          i, arguments[param_no]->buffer(/*index=*/{}));
    }
  }
  se::StreamExecutor* executor = run_options->stream()->parent();
  TF_ASSIGN_OR_RETURN(
      auto buffer_allocations,
      buffer_allocations_builder.Build(*assignment_, executor->device_ordinal(),
                                       memory_allocator));

  TF_RETURN_IF_ERROR(
      ExecuteThunks(run_options, *buffer_allocations, hlo_execution_profile));

  HloInstruction* root = hlo_module_->entry_computation()->root_instruction();
  auto device_ordinal = executor->device_ordinal();
  TF_ASSIGN_OR_RETURN(auto shaped_buffer,
                      ShapedBuffer::MakeShapedBuffer(
                          root->shape(), executor->platform(), device_ordinal));

  // Copy DeviceMemoryBase values which contain the array(s) of the result into
  // the respective location in ShapedBuffer.
  std::set<se::DeviceMemoryBase> buffers_in_result;
  TF_RETURN_IF_ERROR(
      shaped_buffer->mutable_shape_index_to_buffer_entry()
          ->ForEachMutableElement(
              [&buffer_allocations, &buffers_in_result, &shaped_buffer, this](
                  const ShapeIndex& index, bool is_leaf, size_t* buffer_entry) {
                if (is_leaf) {
                  const std::vector<const LogicalBuffer*>& sources =
                      this->GetRootPointsToSet().element(index);
                  // The points to set is unambiguous so the set should be a
                  // singleton. That is, we know exactly which instruction
                  // produced the array at this element.
                  CHECK_EQ(1, sources.size());
                  auto src_hlo = sources[0]->instruction();

                  VLOG(4) << "Looking at: " << sources[0];

                  // The source instruction should have a non-parameter buffer
                  // assigned.
                  TF_ASSIGN_OR_RETURN(const BufferAllocation::Slice slice,
                                      this->assignment_->GetUniqueSlice(
                                          src_hlo, sources[0]->index()));
                  CHECK(!slice.allocation()->is_entry_computation_parameter());

                  perftools::gputools::DeviceMemoryBase src_base =
                      buffer_allocations->GetDeviceAddress(slice.index());
                  CHECK(!src_base.is_null() || src_base.size() == 0);
                  shaped_buffer->mutable_buffers()->push_back(src_base);
                  *buffer_entry = shaped_buffer->mutable_buffers()->size() - 1;

                  buffers_in_result.insert(src_base);
                }
                return Status::OK();
              }));
  TF_RETURN_IF_ERROR(
      buffer_allocations->TearDown(buffers_in_result, *assignment_));

  return std::move(shaped_buffer);
}

Status GpuExecutable::ExecuteOnStream(
    const ServiceExecutableRunOptions* run_options,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    ShapedBuffer* result_buffer, HloExecutionProfile* hlo_execution_profile) {
  se::Stream* stream = run_options->stream();
  DeviceMemoryAllocator* memory_allocator = run_options->allocator();
  // This ExecuteOnStream overload should only be called by the LocalService
  // which sets has_hybrid_result to true.
  TF_RET_CHECK(module_config().has_hybrid_result());

  // Every array element in the result of the computation must be unambiguously
  // produced by a single instruction.
  // This ensures that the buffers inside result_buffer can be assigned without
  // conflict to the respective instructions because there is a one-to-one
  // correspondence between hlo instructions and array buffers in the result.
  if (GetRootPointsToSet().IsAmbiguous()) {
    return Unimplemented(
        "Points-to set of root instruction is ambiguous or not distinct");
  }

  DCHECK(ShapeUtil::Compatible(result_buffer->shape(), result_shape()));

  BufferAllocations::Builder buffer_allocations_builder;
  for (BufferAllocation::Index i = 0; i < assignment_->Allocations().size();
       ++i) {
    const BufferAllocation& allocation = assignment_->GetAllocation(i);
    if (allocation.is_entry_computation_parameter()) {
      auto param_no = allocation.parameter_number();
      if (ShapeUtil::IsTuple(arguments[param_no]->shape())) {
        return Unimplemented("Tuple ShapedBuffer arguments not supported");
      }
      buffer_allocations_builder.RegisterBuffer(
          i, arguments[param_no]->buffer(/*index=*/{}));
    }
  }

  // If two tuple elements point to the same buffer, one of the results in the
  // result buffer is considered the canonical location while the other result
  // points to it (instead of, say, making a copy of the result).
  // buffer_index_to_shape_index maps a buffer index to its canonical location
  // in the result buffer.
  std::unordered_map<BufferAllocation::Index, size_t>
      buffer_index_to_shape_index;

  // Register DeviceMemoryBase values in result_buffer to their corresponding
  // buffer indices. These buffers will not be allocated in the call to
  // BufferAllocationsBuilder::Build.
  std::set<se::DeviceMemoryBase> buffers_in_result;
  TF_RETURN_IF_ERROR(
      result_buffer->mutable_shape_index_to_buffer_entry()
          ->ForEachMutableElement(
              [&buffer_allocations_builder, &buffers_in_result,
               &buffer_index_to_shape_index, result_buffer, this](
                  const ShapeIndex& index, bool is_leaf, size_t* buffer_entry) {
                if (is_leaf) {
                  const std::vector<const LogicalBuffer*>& sources =
                      this->GetRootPointsToSet().element(index);
                  // The points to set is unambiguous so the set should be a
                  // singleton. That is, we know exactly which instruction
                  // produced the array at this element.
                  CHECK_EQ(1, sources.size());
                  auto src_hlo = sources[0]->instruction();

                  VLOG(4) << "Looking at: " << sources[0];

                  // The source instruction should have a non-parameter buffer
                  // assigned.
                  TF_ASSIGN_OR_RETURN(const BufferAllocation::Slice slice,
                                      this->assignment_->GetUniqueSlice(
                                          src_hlo, sources[0]->index()));
                  CHECK(!slice.allocation()->is_entry_computation_parameter());

                  auto insert_result = buffer_index_to_shape_index.emplace(
                      slice.index(), *buffer_entry);
                  if (insert_result.second) {
                    // The points-to set is distinct so this buffer should not
                    // have been assigned in a previous invocation of this
                    // lambda.
                    perftools::gputools::DeviceMemoryBase memory_base =
                        result_buffer->buffer(index);
                    CHECK(!memory_base.is_null());
                    buffer_allocations_builder.RegisterBuffer(slice.index(),
                                                              memory_base);
                    buffers_in_result.insert(memory_base);
                  } else {
                    // Record the fact that this tuple element is identical to
                    // some
                    // prior result.
                    *buffer_entry = insert_result.first->second;
                  }
                }
                return Status::OK();
              }));

  se::StreamExecutor* executor = stream->parent();
  auto device_ordinal = executor->device_ordinal();
  TF_ASSIGN_OR_RETURN(auto buffer_allocations,
                      buffer_allocations_builder.Build(
                          *assignment_, device_ordinal, memory_allocator));

  TF_RETURN_IF_ERROR(
      ExecuteThunks(run_options, *buffer_allocations, hlo_execution_profile));

  return buffer_allocations->TearDown(buffers_in_result, *assignment_);
}

StatusOr<se::DeviceMemoryBase> GpuExecutable::ExecuteAsyncOnStream(
    const ServiceExecutableRunOptions* run_options,
    tensorflow::gtl::ArraySlice<se::DeviceMemoryBase> arguments) {
  // TODO(b/30671675): Implement asynchronous execution mode.
  return Unimplemented(
      "Asynchronous execution on stream is not yet supported on GPU.");
}

const PointsToSet& GpuExecutable::GetRootPointsToSet() const {
  return assignment_->points_to_analysis().GetPointsToSet(
      module().entry_computation()->root_instruction());
}

}  // namespace gpu
}  // namespace xla


text:
var apn = require("../");
var fs = require("fs");

describe("Connection", function() {
	describe('constructor', function () {
		var originalEnv;

		before(function() {
			originalEnv = process.env.NODE_ENV;
		});

		after(function() {
			process.env.NODE_ENV = originalEnv;
		})

		beforeEach(function() {
			process.env.NODE_ENV = "";
		})

		// Issue #50
		it("should use gateway.sandbox.push.apple.com as the default connection address", function () {
			apn.Connection().options.address.should.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			apn.Connection().options.address.should.equal("gateway.push.apple.com");
		});

		it("should give precedence to production flag over NODE_ENV=production", function () {
			process.env.NODE_ENV = "production";
			apn.Connection({ production: false }).options.address.should.equal("gateway.sandbox.push.apple.com");
		});

		it("should use gateway.push.apple.com when production:true", function () {
			apn.Connection({production:true}).options.address.should.equal("gateway.push.apple.com");
		});

		it("should use a custom address when passed", function () {
			apn.Connection({address: "testaddress"}).options.address.should.equal("testaddress");
		});
	});

	describe('#initialize', function () {
		it("should be fulfilled", function () {
			return apn.Connection({ pfx: "test/support/initializeTest.pfx" })
					  .initialize().should.be.fulfilled;
		});
	});
});


text:
import { log } from "../../../lib/logger/log";

/* tslint:disable:ban-types */
export function init(): Profiler
{
    const defaults = {
        data: {},
        total: 0,
    };

    if (!Memory.profiler) { Memory.profiler = defaults; }

    const cli: Profiler = {
        clear()
        {
            const running = isEnabled();
            Memory.profiler = defaults;
            if (running) { Memory.profiler.start = Game.time; }
            return "Profiler Memory cleared";
        },

        output()
        {
            outputProfilerData();
            return "Done";
        },

        start()
        {
            Memory.profiler.start = Game.time;
            return "Profiler started";
        },

        status()
        {
            if (isEnabled())
            {
                return "Profiler is running";
            }
            return "Profiler is stopped";
        },

        stop()
        {
            if (!isEnabled()) { return; }
            const timeRunning = Game.time - Memory.profiler.start!;
            Memory.profiler.total += timeRunning;
            delete Memory.profiler.start;
            return "Profiler stopped";
        },

        // toString() {
        //    return "Profiler.start() - Starts the profiler\n" +
        //       "Profiler.stop() - Stops/Pauses the profiler\n" +
        //       "Profiler.status() - Returns whether is profiler is currently running or not\n" +
        //       "Profiler.output() - Pretty-prints the collected profiler data to the console\n" +
        //       this.status();
        //  },
    };

    return cli;
}

function wrapFunction(obj: object, key: PropertyKey, className?: string)
{
    log.info("In wrapFunction 1");
    const descriptor = Reflect.getOwnPropertyDescriptor(obj, key);
    if (!descriptor || descriptor.get || descriptor.set) { return; }
    log.info("In wrapFunction 2");

    if (key === "constructor") { return; }
    log.info("In wrapFunction 3");

    const originalFunction = descriptor.value;
    if (!originalFunction || typeof originalFunction !== "function") { return; }

    // set a key for the object in memory
    if (!className) { className = obj.constructor ? `${obj.constructor.name}` : ""; }
    const keyStr = key.toString();
    const memKey = className + `:${keyStr}`;

    // set a tag so we don't wrap a function twice
    const savedName = `__${keyStr}__`;
    log.info("In wrapFunction 4 " +
        " memKey=" + memKey +
        " savedName=" + savedName +
        " Has:" + Reflect.has(obj, savedName)
    );

    // let t = {x:0, y:'1'};
    // log.info("Test " + Reflect.has(t, 'x'));
    // log.info("Test " + Reflect.has(t, 'y'));
    // Reflect.set(t, 'y', '5');
    // log.info("Test " + t.y);

    if (Reflect.has(obj, savedName)) { return; }

    log.info("In wrapFunction 5 ");
    // let x = Reflect.set(obj, savedName, originalFunction);
    // log.info("In wrapFunction 6 x=" + x + " memKey=" + memKey + " key=" + key);

    ///////////

    Reflect.set(obj, key, function (this: any, ...args: any[])
    {
        log.info("In wrapFunction 7");
        if (isEnabled())
        {
            log.info("In wrapFunction 8");
            const start = Game.cpu.getUsed();
            const result = originalFunction.apply(this, args);
            const end = Game.cpu.getUsed();
            record(memKey, end - start);
            return result;
        }
        return originalFunction.apply(this, args);
    });
}

export function profile(target: Function): void;
export function profile(target: object, key: string | symbol, _descriptor: TypedPropertyDescriptor<Function>): void;
export function profile(
    target: object | Function,
    key?: string | symbol,
    _descriptor?: TypedPropertyDescriptor<Function>,
): void
{
    if (!__PROFILER_ENABLED__) { return; }

    if (key)
    {
        // case of method decorator
        wrapFunction(target, key);
        return;
    }

    // case of class decorator

    const ctor = target as any;
    if (!ctor.prototype) { return; }

    const className = ctor.name;
    Reflect.ownKeys(ctor.prototype).forEach((k) =>
    {
        wrapFunction(ctor.prototype, k, className);
    });

}

function isEnabled(): boolean
{
    return Memory.profiler.start !== undefined;
}

export function profileRecord(key: string | symbol, isStart: boolean)
{
    if (isEnabled())
    {
        if (isStart)
        {
            Memory.profiler.lastStart = Game.cpu.getUsed();
        }
        else
        {
            const end = Game.cpu.getUsed();
            if (Memory.profiler.lastStart !== undefined)
            {
                record(key, end - Memory.profiler.lastStart);
            }
        }
    }
}

export function record(key: string | symbol, time: number)
{
    const keyStr = key.toString();
    if (!Memory.profiler.data[keyStr])
    {
        Memory.profiler.data[keyStr] = {
            calls: 0,
            time: 0,
        };
    }
    Memory.profiler.data[keyStr].calls++;
    Memory.profiler.data[keyStr].time += time;
}

interface OutputData
{
    name: string;
    calls: number;
    cpuPerCall: number;
    callsPerTick: number;
    cpuPerTick: number;
}

function outputProfilerData()
{
    let totalTicks = Memory.profiler.total;
    if (Memory.profiler.start)
    {
        totalTicks += Game.time - Memory.profiler.start;
    }

    ///////
    // Process data
    let totalCpu = 0;  // running count of average total CPU use per tick
    let calls: number;
    let time: number;
    let result: Partial<OutputData>;
    const data = Reflect.ownKeys(Memory.profiler.data).map((key) =>
    {
        const keyStr = key.toString();
        calls = Memory.profiler.data[keyStr].calls;
        time = Memory.profiler.data[keyStr].time;
        result = {};
        result.name = `${keyStr}`;
        result.calls = calls;
        result.cpuPerCall = time / calls;
        result.callsPerTick = calls / totalTicks;
        result.cpuPerTick = time / totalTicks;
        totalCpu += result.cpuPerTick;
        return result as OutputData;
    });

    data.sort((lhs, rhs) => rhs.cpuPerTick - lhs.cpuPerTick);

    ///////
    // Format data
    let output = "";

    // get function name max length
    const longestName = 32; //(_.max(data, (d) => d.name.length)).name.length + 2;

    //// Header line
    output += _.padRight("Function", longestName);
    output += _.padLeft("Tot Calls", 12);
    output += _.padLeft("CPU/Call", 12);
    output += _.padLeft("Calls/Tick", 12);
    output += _.padLeft("CPU/Tick", 12);
    output += _.padLeft("% of Tot\n", 12);

    ////  Data lines
    data.forEach((d) =>
    {
        output += _.padRight(`${d.name}`, longestName);
        output += _.padLeft(`${d.calls}`, 12);
        output += _.padLeft(`${d.cpuPerCall.toFixed(2)}ms`, 12);
        output += _.padLeft(`${d.callsPerTick.toFixed(2)}`, 12);
        output += _.padLeft(`${d.cpuPerTick.toFixed(2)}ms`, 12);
        output += _.padLeft(`${(d.cpuPerTick / totalCpu * 100).toFixed(0)} %\n`, 12);
    });

    //// Footer line
    output += `${totalTicks} total ticks measured`;
    output += `\t\t\t${totalCpu.toFixed(2)} average CPU profiled per tick`;
    console.log(output);
}

// debugging
// function printObject(obj: object) {
//   const name = obj.constructor ? obj.constructor.name : (obj as any).name;
//   console.log("  Keys of :", name, ":");
//   Reflect.ownKeys(obj).forEach((k) => {
//     try {
//       console.log(`    ${k}: ${Reflect.get(obj, k)}`);
//     } catch (e) {
//       // nothing
//     }
//   });
// }


text:
from django.contrib.auth.decorators import login_required
from QueueDB.models import Job
from django.shortcuts import render


text:
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema orobudget
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `orobudget` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `orobudget` ;

-- -----------------------------------------------------
-- Table `orobudget`.`budget`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`budget` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `budgethead` VARCHAR(200) NULL,
  `status` VARCHAR(200) NULL,
  `datecreated` DATETIME NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`unit`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`unit` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`month`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`month` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`budget_has_month`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`budget_has_month` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `budget_id` INT NOT NULL,
  `month_id` INT NOT NULL,
  PRIMARY KEY (`id`, `budget_id`, `month_id`),
  INDEX `fk_budget_has_month_month1_idx` (`month_id` ASC),
  INDEX `fk_budget_has_month_budget1_idx` (`budget_id` ASC),
  CONSTRAINT `fk_budget_has_month_budget1`
    FOREIGN KEY (`budget_id`)
    REFERENCES `orobudget`.`budget` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_budget_has_month_month1`
    FOREIGN KEY (`month_id`)
    REFERENCES `orobudget`.`month` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`budget_has_unit`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`budget_has_unit` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `budget_id` INT NOT NULL,
  `unit_id` INT NOT NULL,
  PRIMARY KEY (`id`, `budget_id`, `unit_id`),
  INDEX `fk_budget_has_unit_unit1_idx` (`unit_id` ASC),
  INDEX `fk_budget_has_unit_budget1_idx` (`budget_id` ASC),
  CONSTRAINT `fk_budget_has_unit_budget1`
    FOREIGN KEY (`budget_id`)
    REFERENCES `orobudget`.`budget` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_budget_has_unit_unit1`
    FOREIGN KEY (`unit_id`)
    REFERENCES `orobudget`.`unit` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(45) NULL,
  `phone` VARCHAR(45) NULL,
  `username` VARCHAR(45) NULL,
  `password` VARCHAR(45) NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`budget_has_user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`budget_has_user` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `budget_id` INT NOT NULL,
  `user_id` INT NOT NULL,
  PRIMARY KEY (`id`, `budget_id`, `user_id`),
  INDEX `fk_budget_has_user_user1_idx` (`user_id` ASC),
  INDEX `fk_budget_has_user_budget1_idx` (`budget_id` ASC),
  CONSTRAINT `fk_budget_has_user_budget1`
    FOREIGN KEY (`budget_id`)
    REFERENCES `orobudget`.`budget` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_budget_has_user_user1`
    FOREIGN KEY (`user_id`)
    REFERENCES `orobudget`.`user` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`timestamps`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`timestamps` (
  `create_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` TIMESTAMP NULL);

-- -----------------------------------------------------
-- Table `orobudget`.`ledger`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`ledger` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `budget_id` INT NOT NULL,
  `fullname` VARCHAR(125) NULL,
  `description` VARCHAR(225) NULL,
  `debit` DOUBLE NULL,
  `credit` DOUBLE NULL,
  `datecreated` DATETIME NULL,
  PRIMARY KEY (`id`, `budget_id`),
  INDEX `fk_Income_budget1_idx` (`budget_id` ASC),
  CONSTRAINT `fk_Income_budget1`
    FOREIGN KEY (`budget_id`)
    REFERENCES `orobudget`.`budget` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `orobudget`.`ledger_has_month`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `orobudget`.`ledger_has_month` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `ledger_id` INT NOT NULL,
  `ledger_budget_id` INT NOT NULL,
  `month_id` INT NOT NULL,
  PRIMARY KEY (`id`, `ledger_id`, `ledger_budget_id`, `month_id`),
  INDEX `fk_ledger_has_month_month1_idx` (`month_id` ASC),
  INDEX `fk_ledger_has_month_ledger1_idx` (`ledger_id` ASC, `ledger_budget_id` ASC),
  CONSTRAINT `fk_ledger_has_month_ledger1`
    FOREIGN KEY (`ledger_id` , `ledger_budget_id`)
    REFERENCES `orobudget`.`ledger` (`id` , `budget_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_ledger_has_month_month1`
    FOREIGN KEY (`month_id`)
    REFERENCES `orobudget`.`month` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.5.4.20-4-49
description: >
    String.prototype.trim handles whitepace and lineterminators
    (abc\u2028)
---*/

assert.sameValue("abc\u2028".trim(), "abc", '"abc\u2028".trim()');


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace PdfSharp.Charting.Demo
{
  public class Charting
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.Run(new MainForm());
    }
  }
}


text:
namespace BarracksFactory.Models.Units
{
    public class Archer : Unit
    {
        private const int DefaultHealth = 25;
        private const int DefaultDamage = 7;

        public Archer()
            : base(DefaultHealth, DefaultDamage)
        {
        }
    }
}


text:
#ifndef CAMERA_SOURCE_H_

#define CAMERA_SOURCE_H_

#include <deque>
#include <media/MediaSource.h>
#include <media/stagefright/MediaBuffer.h>
#include <camera/android/hardware/ICamera.h>
#include <camera/ICameraRecordingProxy.h>
#include <camera/ICameraRecordingProxyListener.h>
#include <camera/CameraParameters.h>
#include <gui/BufferItemConsumer.h>
#include <utils/List.h>
#include <utils/RefBase.h>
#include <utils/String16.h>
#include <media/hardware/MetadataBufferType.h>

namespace android {

class IMemory;
class Camera;
class Surface;

class CameraSource : public MediaSource, public MediaBufferObserver {
public:
    /**
     * Factory method to create a new CameraSource using the current
     * settings (such as video size, frame rate, color format, etc)
     * from the default camera.
     *
     * @param clientName The package/process name of the client application.
     *    This is used for permissions checking.
     * @return NULL on error.
     */
    static CameraSource *Create(const String16 &clientName);

    /**
     * Factory method to create a new CameraSource.
     *
     * @param camera the video input frame data source. If it is NULL,
     *          we will try to connect to the camera with the given
     *          cameraId.
     *
     * @param cameraId the id of the camera that the source will connect
     *          to if camera is NULL; otherwise ignored.
     * @param clientName the package/process name of the camera-using
     *          application if camera is NULL; otherwise ignored. Used for
     *          permissions checking.
     * @param clientUid the UID of the camera-using application if camera is
     *          NULL; otherwise ignored. Used for permissions checking.
     * @param clientPid the PID of the camera-using application if camera is
     *          NULL; otherwise ignored. Used for permissions checking.
     * @param videoSize the dimension (in pixels) of the video frame
     * @param frameRate the target frames per second
     * @param surface the preview surface for display where preview
     *          frames are sent to
     * @param storeMetaDataInVideoBuffers true to request the camera
     *          source to store meta data in video buffers; false to
     *          request the camera source to store real YUV frame data
     *          in the video buffers. The camera source may not support
     *          storing meta data in video buffers, if so, a request
     *          to do that will NOT be honored. To find out whether
     *          meta data is actually being stored in video buffers
     *          during recording, call isMetaDataStoredInVideoBuffers().
     *
     * @return NULL on error.
     */
    static CameraSource *CreateFromCamera(const sp<hardware::ICamera> &camera,
                                          const sp<ICameraRecordingProxy> &proxy,
                                          int32_t cameraId,
                                          const String16& clientName,
                                          uid_t clientUid,
                                          pid_t clientPid,
                                          Size videoSize,
                                          int32_t frameRate,
                                          const sp<IGraphicBufferProducer>& surface,
                                          bool storeMetaDataInVideoBuffers = true);

    virtual ~CameraSource();

    virtual status_t start(MetaData *params = NULL);
    virtual status_t stop() { return reset(); }
    virtual status_t read(
            MediaBufferBase **buffer, const ReadOptions *options = NULL);
    virtual status_t setStopTimeUs(int64_t stopTimeUs);

    /**
     * Check whether a CameraSource object is properly initialized.
     * Must call this method before stop().
     * @return OK if initialization has successfully completed.
     */
    virtual status_t initCheck() const;

    /**
     * Returns the MetaData associated with the CameraSource,
     * including:
     * kKeyColorFormat: YUV color format of the video frames
     * kKeyWidth, kKeyHeight: dimension (in pixels) of the video frames
     * kKeySampleRate: frame rate in frames per second
     * kKeyMIMEType: always fixed to be MEDIA_MIMETYPE_VIDEO_RAW
     */
    virtual sp<MetaData> getFormat();

    /**
     * Tell whether this camera source stores meta data or real YUV
     * frame data in video buffers.
     *
     * @return a valid type if meta data is stored in the video
     *      buffers; kMetadataBufferTypeInvalid if real YUV data is stored in
     *      the video buffers.
     */
    MetadataBufferType metaDataStoredInVideoBuffers() const;

    virtual void signalBufferReturned(MediaBufferBase* buffer);

protected:

    /**
     * The class for listening to BnCameraRecordingProxyListener. This is used to receive video
     * buffers in VIDEO_BUFFER_MODE_DATA_CALLBACK_YUV and VIDEO_BUFFER_MODE_DATA_CALLBACK_METADATA
     * mode. When a frame is available, CameraSource::dataCallbackTimestamp() will be called.
     */
    class ProxyListener: public BnCameraRecordingProxyListener {
    public:
        ProxyListener(const sp<CameraSource>& source);
        virtual void dataCallbackTimestamp(int64_t timestampUs, int32_t msgType,
                const sp<IMemory> &data);
        virtual void recordingFrameHandleCallbackTimestamp(int64_t timestampUs,
                native_handle_t* handle);
        virtual void recordingFrameHandleCallbackTimestampBatch(
                const std::vector<int64_t>& timestampsUs,
                const std::vector<native_handle_t*>& handles);

    private:
        sp<CameraSource> mSource;
    };

    /**
     * The class for listening to BufferQueue's onFrameAvailable. This is used to receive video
     * buffers in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode. When a frame is available,
     * CameraSource::processBufferQueueFrame() will be called.
     */
    class BufferQueueListener : public Thread,  public BufferItemConsumer::FrameAvailableListener {
    public:
        BufferQueueListener(const sp<BufferItemConsumer> &consumer,
                const sp<CameraSource> &cameraSource);
        virtual void onFrameAvailable(const BufferItem& item);
        virtual bool threadLoop();
    private:
        static const nsecs_t kFrameAvailableTimeout = 50000000; // 50ms

        sp<BufferItemConsumer> mConsumer;
        sp<CameraSource> mCameraSource;

        Mutex mLock;
        Condition mFrameAvailableSignal;
        bool mFrameAvailable;
    };

    // isBinderAlive needs linkToDeath to work.
    class DeathNotifier: public IBinder::DeathRecipient {
    public:
        DeathNotifier() {}
        virtual void binderDied(const wp<IBinder>& who);
    };

    enum CameraFlags {
        FLAGS_SET_CAMERA = 1L << 0,
        FLAGS_HOT_CAMERA = 1L << 1,
    };

    int32_t  mCameraFlags;
    Size     mVideoSize;
    int32_t  mNumInputBuffers;
    int32_t  mVideoFrameRate;
    int32_t  mColorFormat;
    int32_t  mEncoderFormat;
    int32_t  mEncoderDataSpace;
    status_t mInitCheck;

    sp<Camera>   mCamera;
    sp<ICameraRecordingProxy>   mCameraRecordingProxy;
    sp<DeathNotifier> mDeathNotifier;
    sp<IGraphicBufferProducer>  mSurface;
    sp<MetaData> mMeta;

    int64_t mStartTimeUs;
    int32_t mNumFramesReceived;
    int64_t mLastFrameTimestampUs;
    bool mStarted;
    int32_t mNumFramesEncoded;

    // Time between capture of two frames.
    int64_t mTimeBetweenFrameCaptureUs;

    CameraSource(const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy,
                 int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid,
                 Size videoSize, int32_t frameRate,
                 const sp<IGraphicBufferProducer>& surface,
                 bool storeMetaDataInVideoBuffers);

    virtual status_t startCameraRecording();
    virtual void releaseRecordingFrame(const sp<IMemory>& frame);
    virtual void releaseRecordingFrameHandle(native_handle_t* handle);
    // stagefright recorder not using this for now
    virtual void releaseRecordingFrameHandleBatch(const std::vector<native_handle_t*>& handles);

    // Returns true if need to skip the current frame.
    // Called from dataCallbackTimestamp.
    virtual bool skipCurrentFrame(int64_t /*timestampUs*/) {return false;}

    // Callback called when still camera raw data is available.
    virtual void dataCallback(int32_t /*msgType*/, const sp<IMemory>& /*data*/) {}

    virtual void dataCallbackTimestamp(int64_t timestampUs, int32_t msgType,
            const sp<IMemory> &data);

    virtual void recordingFrameHandleCallbackTimestamp(int64_t timestampUs,
            native_handle_t* handle);

    virtual void recordingFrameHandleCallbackTimestampBatch(
            const std::vector<int64_t>& timestampsUs,
            const std::vector<native_handle_t*>& handles);

    // Process a buffer item received in BufferQueueListener.
    virtual void processBufferQueueFrame(BufferItem& buffer);

    void releaseCamera();

private:
    friend struct CameraSourceListener;

    Mutex mLock;
    Condition mFrameAvailableCondition;
    Condition mFrameCompleteCondition;
    List<sp<IMemory> > mFramesReceived;
    List<sp<IMemory> > mFramesBeingEncoded;
    List<int64_t> mFrameTimes;

    int64_t mFirstFrameTimeUs;
    int64_t mStopSystemTimeUs;
    int32_t mNumFramesDropped;
    int32_t mNumGlitches;
    int64_t mGlitchDurationThresholdUs;
    bool mCollectStats;

    // The mode video buffers are received from camera. One of VIDEO_BUFFER_MODE_*.
    int32_t mVideoBufferMode;

    static const uint32_t kDefaultVideoBufferCount = 32;

    /**
     * The following variables are used in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode.
     */
    static const size_t kConsumerBufferCount = 8;
    static const nsecs_t kMemoryBaseAvailableTimeoutNs = 200000000; // 200ms
    // Consumer and producer of the buffer queue between this class and camera.
    sp<BufferItemConsumer> mVideoBufferConsumer;
    sp<IGraphicBufferProducer> mVideoBufferProducer;
    // Memory used to send the buffers to encoder, where sp<IMemory> stores VideoNativeMetadata.
    sp<IMemoryHeap> mMemoryHeapBase;
    List<sp<IMemory>> mMemoryBases;
    // The condition that will be signaled when there is an entry available in mMemoryBases.
    Condition mMemoryBaseAvailableCond;
    // A mapping from ANativeWindowBuffer sent to encoder to BufferItem received from camera.
    // This is protected by mLock.
    KeyedVector<ANativeWindowBuffer*, BufferItem> mReceivedBufferItemMap;
    sp<BufferQueueListener> mBufferQueueListener;

    Mutex mBatchLock; // protecting access to mInflightXXXXX members below
    // Start of members protected by mBatchLock
    std::deque<uint32_t> mInflightBatchSizes;
    std::vector<native_handle_t*> mInflightReturnedHandles;
    std::vector<const sp<IMemory>> mInflightReturnedMemorys;
    // End of members protected by mBatchLock

    void releaseQueuedFrames();
    void releaseOneRecordingFrame(const sp<IMemory>& frame);
    void createVideoBufferMemoryHeap(size_t size, uint32_t bufferCount);

    status_t init(const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy,
                  int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid,
                  Size videoSize, int32_t frameRate, bool storeMetaDataInVideoBuffers);

    status_t initWithCameraAccess(
                  const sp<hardware::ICamera>& camera, const sp<ICameraRecordingProxy>& proxy,
                  int32_t cameraId, const String16& clientName, uid_t clientUid, pid_t clientPid,
                  Size videoSize, int32_t frameRate, bool storeMetaDataInVideoBuffers);

    // Initialize the buffer queue used in VIDEO_BUFFER_MODE_BUFFER_QUEUE mode.
    status_t initBufferQueue(uint32_t width, uint32_t height, uint32_t format,
                  android_dataspace dataSpace, uint32_t bufferCount);

    status_t isCameraAvailable(const sp<hardware::ICamera>& camera,
                               const sp<ICameraRecordingProxy>& proxy,
                               int32_t cameraId,
                               const String16& clientName,
                               uid_t clientUid,
                               pid_t clientPid);

    status_t isCameraColorFormatSupported(const CameraParameters& params);
    status_t configureCamera(CameraParameters* params,
                    int32_t width, int32_t height,
                    int32_t frameRate);

    status_t checkVideoSize(const CameraParameters& params,
                    int32_t width, int32_t height);

    status_t checkFrameRate(const CameraParameters& params,
                    int32_t frameRate);

    // Check if this frame should be skipped based on the frame's timestamp in microsecond.
    // mLock must be locked before calling this function.
    bool shouldSkipFrameLocked(int64_t timestampUs);

    void stopCameraRecording();
    status_t reset();

    CameraSource(const CameraSource &);
    CameraSource &operator=(const CameraSource &);
};

}  // namespace android

#endif  // CAMERA_SOURCE_H_


text:
"""
    author: Kaio Cesar
    Email: tecnico.kaio@gmail.com

    Exercicio da Lista I exercícios 3
    Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário.
    Calcule o total em segundos.
"""

dias=int(raw_input("Digite a quantidade de dias? "))
horas=int(raw_input("Digite a quantidade de horas? "))
minutos=int(raw_input("Digite a quantide de minutos? "))
segundos=int(raw_input("Digite a quantidade de segundos? "))

s_dias=dias*86400 # ou 24*3600
s_horas=horas*3600
s_minutos=minutos*60
total=s_dias+s_horas+s_minutos+segundos

print "Total é igua a ", int(total)


text:
Redoop is a tool to help Data Architects to understand Relational Database workloads and make decisions based on data patterns.
It is been developed mainly to help offloading Oracle databases to Hadoop/Hive clusters

Install dependencies:
- cx_Oracle (> 5.2)
- Python 2.7.x

Usage:
./redoop.py -d oracle -o teste.txt

-d means database type (supported: Oracle)
-o output file

It generates a simple tabular text file with the result of specific querys.
Supported querys for Oracle:
* Analyze tables with full Scans
* Analyze tables subject to most DML
* Analyze cold range partition tables


text:
package extrabiomes.meadow.stuff;

import java.util.List;

import com.google.common.collect.Lists;

import extrabiomes.meadow.biomes.BiomeMeadow;
import extrabiomes.lib.settings.BiomeSettings;
import extrabiomes.lib.worldgen.ExtrabiomeGenBase;

public enum BiomeCollection {
	MEADOW(43, BiomeMeadow.class);

	public final BiomeSettings settings;

	private BiomeCollection(int defaultID, Class<? extends ExtrabiomeGenBase> biomeClass) {
		settings = new BiomeSettings(this.name().toLowerCase(), defaultID, biomeClass);
	}

	public static final List<BiomeSettings> allSettings = Lists.newArrayList();
	public static void init() {
		if( allSettings.isEmpty() ) {
			for( BiomeCollection coll : BiomeCollection.values() ) {
				allSettings.add(coll.settings);
			}
		}
	}
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="robots" content="noindex, nofollow">

  <title>Book club favourites #6 – Suffolk Libraries</title>

  <link rel="stylesheet" href="/css/style.css">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-regular.woff2">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-italic.woff2">
	<link rel="preload" as="font" type="font/woff2" href="/fonts/source-sans-pro-v11-latin-700.woff2">

Skip to content

Skip to navigation menu

💳 You can now pay online.
	Pay charges now →

Donate

Join

Login

Search

Home

eLibrary

Online events

Help

Contact

    Home

      → New suggestions

      → Book club

      → Book club favourites #6

Book club favourites #6

  Written by Brandon King · Published Jun 5, 2015

Beyond black by Hilary Mantel

While most of us know Mantel for her Booker Prize-winning Wolf Hall and Bring Up the Bodies, this novel is a modern-day, fantastical and mysterious tale of men long-dead and the terrors of the next life. We follow Alison Hart, a travelling medium whose waking hours are plagued by spirits.

The ruby slippers by Keir Alexander

Old Rosa, the bag lady, shuffles along the streets of New York, stinking, silent and shunned by all. Time and again her nephew, Michael Marcinkus, has tried to help – but she remains unknowable, hushed inside her hulk. On the day of the St. Patrick's Day Parade, she is in a terrible accident. As she lies in a coma, Mr. Marcinkus visits her squalid flat and unearths something remarkable from the monstrous piles of junk: two glittering pieces of Hollywood history.

Love and freindship and other delusions by Beth Andrews

Isabel and her daughter Marianne attend the theatre in Bury St Edmunds and encounter Isabel's old friend, Laura Lindsay, who gives her journal to Marianne to read. It is a revelation to the younger woman as she reads of one hilarious madcap romantic escapade after another. There is love at first sight, marriage the same day, the befriending of another young woman as romantic as Laura herself, exaggerated sentiment and complete disregard for the feelings of others. Havoc inevitably ensues. This is Jane Austen retold by retaining her huge capacity for laughter and enjoyment of the absurd.

Aren't we sisters? by Patricia Ferguson

Lettie teaches married women about contraception. Her job is technically legal, but the things that the typed, unsigned letters that arrive at Lettie's office ask her to do certainly aren't.

The quickening maze by Adam Foulds

Booker Prize-shortlisted book inspired by the discovery that Septimus Tennyson and John Clare were both incarcerated in Epping Forest's High Beach Asylum, its lyricism points to the significance of nature for both Clare and Foulds himself.

The diary of a nobody by George and Weedon Grossmith

Anxious, accident-prone and occasionally waspish, Charles Pooter has come to be seen as an epitome of English suburban life. The world he inhabits is hilariously and painfully familiar in its small-mindedness and essential decency.

Me talk pretty one day by David Sedaris

David Sedaris moved from New York to Paris where he attempted to learn French. His teacher, a sadist, declared that every day spent with him was like giving birth the Caesarean way! These hilarious essays were inspired by that move.

The last days of Rabbit Hayes by Anna McPartlin

Moving and funny. This is a book that will make you laugh and make you cry.

Miss Carter's war by Sheila Hancock

Through deep friendships and love lost and found, from the peace marches of the fifties and the flowering of the swinging sixties, to the rise of Thatcher and the battle for gay rights, to the spectre of a new war, this is a powerful portrait of Britain through the life of one very singular woman.

Brandon King

I work in the Suffolk Libraries Stock Team

More Book club favourites

Book club favourites #21

Book club favourites #20

Book club favourites #19

Book club favourites #18

Book club favourites #17

Book club favourites #16

Book club favourites #15

Book club favourites #14

Book club favourites #13

Book club favourites #12

More suggestions

Fiction

Audiobooks

Films & DVDs

eLibrary picks

Children's books

Young adult

Non-fiction

Music

Meet the Author interviews

Articles

 Health and wellbeing

Reviews

Book club favourites

Keep updated

Get the latest suggestions, releases and reviews delivered straight to you.

Email newsletter

Facebook

Twitter

Instagram

Do it online

Search & reserve

Login & renew

eLibrary

Get a library card

Support your library

We're a charity that makes life in Suffolk better for thousands of people.

Donate

Contact us

01473 351249

help@suffolklibraries.co.uk

Social media

Facebook

YouTube

Twitter

Instagram

LinkedIn

Email newsletter

Sections

eLibrary

Libraries

Mobile & home service

Help using the service

Recommendations & reviews

Events & activities

Research & reference

Parents, carers & children

Teachers & home educators

Health & wellbeing

Help with reading & literacy

Work & benefits

Business & room hire

BLOC

Music & Drama Library

News

Jobs

Volunteering

About us

Privacy & cookies

Find out what cookies we use and how we use your data: our privacy policies.

Privacy notice for job applicants

Suffolk Libraries HMRC charity number XT34476. Registered company number IP031542.


text:
package comparison.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

public abstract class Attributes {

    @Target(ElementType.METHOD)
    public @interface Anno {
        int a() default 0;
        int b();
    }

    @Anno(a = 1, b = 2)
    @Deprecated
    public abstract void m(int i);
}


text:
'use strict';

const baAsn1 = require('../../lib/asn1');

describe('bacstack - ASN1 layer', () => {
  describe('decodeUnsigned', () => {
    it('should fail if unsuport length', () => {
      expect(() => baAsn1.decodeUnsigned(Buffer.from([0xFF, 0xFF]), 0, 5)).toThrow('outside buffer bounds');
    });

    it('should successfully decode 8-bit unsigned integer', () => {
      const result = baAsn1.decodeUnsigned(Buffer.from([0x00, 0xFF, 0xFF, 0xFF, 0xFF]), 1, 1);
      expect(result).toEqual({len: 1, value: 255});
    });

    it('should successfully decode 16-bit unsigned integer', () => {
      const result = baAsn1.decodeUnsigned(Buffer.from([0x00, 0xFF, 0xFF, 0xFF, 0xFF]), 1, 2);
      expect(result).toEqual({len: 2, value: 65535});
    });

    it('should successfully decode 24-bit unsigned integer', () => {
      const result = baAsn1.decodeUnsigned(Buffer.from([0x00, 0xFF, 0xFF, 0xFF, 0xFF]), 1, 3);
      expect(result).toEqual({len: 3, value: 16777215});
    });

    it('should successfully decode 32-bit unsigned integer', () => {
      const result = baAsn1.decodeUnsigned(Buffer.from([0x00, 0xFF, 0xFF, 0xFF, 0xFF]), 1, 4);
      expect(result).toEqual({len: 4, value: 4294967295});
    });
  });

  describe('encodeBacnetObjectId', () => {
    it('should successfully encode with object-type > 512', () => {
      const buffer = {buffer: Buffer.alloc(4), offset: 0};
      baAsn1.encodeBacnetObjectId(buffer, 600, 600);
      expect(buffer).toEqual({buffer: Buffer.from([150, 0, 2, 88]), offset: 4});
    });
  });
});


text:
import { resolve } from 'redux-simple-promise';
import { TOPIC_FILTER_BY_SNAPSHOT, FETCH_TOPIC_SUMMARY }
  from '../../../actions/topicActions';
import { createAsyncReducer } from '../../../lib/reduxHelpers';
import { snapshotDateToMoment } from '../../../lib/dateUtil';
import { parseId } from '../../../lib/numberUtil';

export const TOPIC_SNAPSHOT_STATE_QUEUED = 'queued';
export const TOPIC_SNAPSHOT_STATE_RUNNING = 'running';
export const TOPIC_SNAPSHOT_STATE_COMPLETED = 'completed';
export const TOPIC_SNAPSHOT_STATE_ERROR = 'error';
// catch an error state that is happening but we don't know why yet!
export const TOPIC_SNAPSHOT_STATE_CREATED_NOT_QUEUED = 'created but not queued';

export const snapshotIsUsable = s => (s.state === TOPIC_SNAPSHOT_STATE_COMPLETED) && (s.searchable === true);

const snapshotsByDateDesc = list => list.sort((f1, f2) => {
  if (f1.snapshot_date < f2.snapshot_date) {
    return 1;
  }
  return -1;
});

const jobsByDateDesc = list => list.sort((f1, f2) => {
  if (f1.last_updated < f2.last_updated) {
    return 1;
  }
  return -1;
});

export function latestUsableSnapshot(snapshots) {
  const usableSnapshots = snapshotsByDateDesc(snapshots).filter(s => snapshotIsUsable(s));
  if (usableSnapshots.length > 0) {
    return usableSnapshots[0];
  }
  return null;
}

function getSnapshotFromListById(list, id) {
  const result = list.find(element => element.snapshots_id === id);
  return (result === undefined) ? null : result;
}

function cleanUpSnapshotList(rawList, jobList) {
  return snapshotsByDateDesc(rawList).map((s, idx) => ({
    ...s,
    job_states: jobList.filter(job => s.snapshots_id === job.snapshots_id),
    snapshotDate: snapshotDateToMoment(s.snapshot_date),
    isUsable: snapshotIsUsable(s),
    isLatest: idx === 0,
  }));
}

export const latestSnapshotByDate = (list) => {
  const orderedList = snapshotsByDateDesc(list);
  if (orderedList && orderedList.length > 0) {
    return orderedList[0];
  }
  return null;
};

const latestJobByDate = (list) => {
  const orderedList = jobsByDateDesc(list);
  if (orderedList && orderedList.length > 0) {
    return orderedList[0];
  }
  return null;
};

function isLatestVersionRunning(snapshotList, jobList) {
  if (snapshotList.length === 0) {
    return false;
  }
  const latestSnapshot = snapshotList[0];
  // check Job statuses also
  const latestJob = latestJobByDate(jobList);
  if (latestJob === null) {
    return false;
  }
  return (latestSnapshot.state === TOPIC_SNAPSHOT_STATE_RUNNING
  || latestJob.state === TOPIC_SNAPSHOT_STATE_RUNNING
  || latestSnapshot.state === TOPIC_SNAPSHOT_STATE_QUEUED
  || latestJob.state === TOPIC_SNAPSHOT_STATE_QUEUED
  || (((latestJob.state === TOPIC_SNAPSHOT_STATE_COMPLETED) || (latestSnapshot.state === TOPIC_SNAPSHOT_STATE_COMPLETED)) && (latestSnapshot.searchable === 0)));
}

const usingLatestSnapshot = (list, selectedId) => {
  const latest = latestSnapshotByDate(list);
  if (latest) {
    return selectedId === latest.snapshots_id;
  }
  return false;
};

const latestSnaphostIsUsable = (list) => {
  const latest = latestSnapshotByDate(list);
  if (latest) {
    return snapshotIsUsable(latest);
  }
  return false;
};

const snapshots = createAsyncReducer({
  initialState: {
    list: [],
    latest: null,
    usingLatest: false,
    latestUsableSnapshot: null,
    latestVersionRunning: false,
    selectedId: null,
    selected: null,
  },
  [resolve(FETCH_TOPIC_SUMMARY)]: (payload, state) => ({ // topic summary includes list of snapshots
    list: cleanUpSnapshotList(payload.snapshots.list, payload.job_states),
    latest: latestSnapshotByDate(payload.snapshots.list),
    usingLatest: usingLatestSnapshot(payload.snapshots.list, state.selectedId),
    latestIsUsable: latestSnaphostIsUsable(payload.snapshots.list),
    latestUsableSnapshot: latestUsableSnapshot(payload.snapshots.list),
    latestVersionRunning: isLatestVersionRunning(payload.snapshots.list, payload.job_states),
  }),
  [TOPIC_FILTER_BY_SNAPSHOT]: (payload, state) => ({
    selectedId: parseId(payload),
    usingLatest: usingLatestSnapshot(state.list, parseId(payload)),
    selected: getSnapshotFromListById(state.list, parseId(payload)),
  }),
});

export default snapshots;


text:
@echo off
cd %~dp0

::csc.exe文件所在目录
set msvs_path=C:\Windows\Microsoft.NET\Framework\v4.0.30319\

::输出文件
set out_dll=U3DClientData.dll

::应用到的dll文件
set LitJson_dll=../../Plugin/LitJson.dll
set UnityEngine_dll="D:\Program Files (x86)\Unity\Editor\Data\Managed\UnityEngine.dll"

"%msvs_path%csc.exe" /out:%out_dll% /r:%LitJson_dll%;%UnityEngine_dll% /t:library *.cs

copy /y %out_dll% ..\..\Plugin\

del %out_dll%

echo build %out_dll% ok!

pause.


text:
#ifndef PRECOMPILED_FILEPERSISTENCE_H_
#define PRECOMPILED_FILEPERSISTENCE_H_

// Include here the precompiled headers of other plug-ins that use this plug-in uses. Only the "public" part of
// those headers will be included here
#include "ModelBase/src/precompiled.h"
#include "Logger/src/precompiled.h"
#include "SelfTest/src/precompiled.h"
#include "Core/src/precompiled.h"

#if defined __cplusplus
// Add C++ includes here

// Put here includes which appear in header files. This will also be visible to other plug-in which depend on this one
// and will be included in their precompiled headers
#include <QtXml/QDomDocument>

#include <QtCore/QDir>
#include <QtCore/QMutex>

#if defined(FILEPERSISTENCE_LIBRARY)
// Put here includes which only appear in compilation units and do not appear in headers. Precompiled headers of
// plug-ins which depend on this one will not include these headers.
#include <QtGui/QClipboard>

#include <QtCore/QFile>

#endif

#endif

#endif /* PRECOMPILED_FILEPERSISTENCE_H_ */