text:
package org.jwat.arc;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import junit.framework.Assert;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.jwat.common.DiagnosisType;

@RunWith(JUnit4.class)
public class TestArcRecord {

    @Test
    public void test_arcrecord() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in;
        ArcReader reader;
        ArcRecordBase record;

        String arcData;
        String payloadData;
        try {
            Object[][] test_cases = new Object[][] {
                    /*
                     * ArchiveLength=0, HTTP payload.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/html ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            return "0";
                        }
                    }, new Object[][] {
                            {DiagnosisType.ERROR_EXPECTED, ArcConstants.ARC_FILE, 1}
                    }, new Object[][] {}},
                    /*
                     * ArchiveLength=0, HTTP payload, no-type.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 no-type ",
                        "", new TestHeaderCallback() {
                            public String getArchiveLength(Object[] test_case) {
                                return "0";
                            }
                    }, new Object[][] {
                            {DiagnosisType.ERROR_EXPECTED, ArcConstants.ARC_FILE, 1}
                    }, new Object[][] {}},
                    /*
                     * ArchiveLength=0, TNT payload.
                     */
                    {"tnt://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/explosive ",
                        "", new TestHeaderCallback() {
                            public String getArchiveLength(Object[] test_case) {
                                return "0";
                                }
                    }, new Object[][] {}, new Object[][] {}},
                    /*
                     * ArchiveLength=0, TNT payload, no-type.
                     */
                    {"tnt://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 no-type ",
                        "", new TestHeaderCallback() {
                            public String getArchiveLength(Object[] test_case) {
                                return "0";
                            }
                    }, new Object[][] {}, new Object[][] {}},
                    /*
                     * ArchiveLength=invalid, HTTP payload.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/html ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            return "invalid";
                        }
                    }, new Object[][] {
                            {DiagnosisType.INVALID_EXPECTED, "'" + ArcConstants.FN_ARCHIVE_LENGTH + "' value", 2},
                            {DiagnosisType.ERROR_EXPECTED, ArcConstants.ARC_FILE, 1}
                    }, new Object[][] {}},
                    /*
                     * ArchiveLength=payload length, HTTP response.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/html ",
                    "GET / HTTP/1.1\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            int archiveLength = ((String)(test_case[1])).length();
                            return Integer.toString(archiveLength);
                        }
                    }, new Object[][] {
                            {DiagnosisType.ERROR, "http header", 1}
                    }, new Object[][] {}},
                    /*
                     * ArchiveLength=payload length.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/html ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            int archiveLength = ((String)(test_case[1])).length();
                            return Integer.toString(archiveLength);
                        }
                    }, new Object[][] {}, new Object[][] {}},
                    /*
                     * ArchiveLength=payload length, no-type.
                     */
                    {"http://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 no-type ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            int archiveLength = ((String)(test_case[1])).length();
                            return Integer.toString(archiveLength);
                        }
                    }, new Object[][] {}, new Object[][] {}},
                    /*
                     * ArchiveLength=payload length.
                     */
                    {"gopher://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 text/html ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            int archiveLength = ((String)(test_case[1])).length();
                            return Integer.toString(archiveLength);
                        }
                    }, new Object[][] {}, new Object[][] {}},
                    /*
                     * ArchiveLength=payload length.
                     */
                    {"gopher://cctr.umkc.edu:80/user/jbenz/tst.htm 134.193.4.1 19970417175710 no-type ",
                    "HTTP/1.0 200 Sending document\r\n"
                    + "MIME-version: 1.0\r\n"
                    + "Server: OSU/1.8\r\n"
                    + "Content-type: text/html\r\n"
                    + "Content-transfer-encoding: 8bit\r\n"
                    + "Last-Modified: Tuesday, 21-Aug-96 05:14:05 GMT\r\n"
                    + "\r\n", new TestHeaderCallback() {
                        public String getArchiveLength(Object[] test_case) {
                            int archiveLength = ((String)(test_case[1])).length();
                            return Integer.toString(archiveLength);
                        }
                    }, new Object[][] {}, new Object[][] {}},
            };
            for (int i=0; i<test_cases.length; ++i) {
                out.reset();
                out.write(filedesc());
                TestHeaderCallback archiveLengthCB = (TestHeaderCallback)test_cases[i][2];
                Assert.assertNotNull(archiveLengthCB);
                payloadData = (String)test_cases[i][1];
                arcData = (String)test_cases[i][0];
                arcData += archiveLengthCB.getArchiveLength(test_cases[i]);
                arcData += "\n";
                arcData += payloadData;
                arcData += "\n";
                out.write(arcData.getBytes());
                out.close();

                // debug
                //System.out.println(out);

                // Save testfile.
                SaveArcTestFiles.saveTestArcRecord(out.toByteArray(),
                        ((Object[][])test_cases[i][3]).length == 0 && ((Object[][])test_cases[i][4]).length == 0);

                in = new ByteArrayInputStream(out.toByteArray());
                reader = ArcReaderFactory.getReader(in, 1024);
                record = reader.getNextRecord();
                Assert.assertNotNull(record);
                Assert.assertFalse(record.diagnostics.hasErrors());
                Assert.assertFalse(record.diagnostics.hasWarnings());
                record = reader.getNextRecord();
                Assert.assertNotNull(record);
                TestBaseUtils.compareDiagnoses((Object[][])test_cases[i][3], record.diagnostics.getErrors());
                TestBaseUtils.compareDiagnoses((Object[][])test_cases[i][4], record.diagnostics.getWarnings());
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail("Unexpected exception!");
        }
    }

    public abstract class TestHeaderCallback {
        public abstract String getArchiveLength(Object[] test_case);
    }

    public byte[] filedesc() {
        String arcData;
        String vbData;
        String mdData;
        mdData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n";
        mdData += "<arcmetadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:arc=\"http://archive.org/arc/1.0/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://archive.org/arc/1.0/\" xsi:schemaLocation=\"http://archive.org/arc/1.0/ http://www.archive.org/arc/1.0/arc.xsd\">\r\n";
        mdData += "<arc:software>Heritrix @VERSION@ http://crawler.archive.org</arc:software>\r\n";
        mdData += "<arc:hostname>blackbook</arc:hostname>\r\n";
        mdData += "<arc:ip>192.168.1.13</arc:ip>\r\n";
        mdData += "<dcterms:isPartOf>archive.org-shallow</dcterms:isPartOf>\r\n";
        mdData += "<dc:description>archive.org shallow</dc:description>\r\n";
        mdData += "<arc:operator>Admin</arc:operator>\r\n";
        mdData += "<ns0:date xmlns:ns0=\"http://purl.org/dc/elements/1.1/\" xsi:type=\"dcterms:W3CDTF\">2008-04-30T20:48:24+00:00</ns0:date>\r\n";
        mdData += "<arc:http-header-user-agent>Mozilla/5.0 (compatible; heritrix/1.14.0 +http://crawler.archive.org)</arc:http-header-user-agent>\r\n";
        mdData += "<arc:http-header-from>archive-crawler-agent@lists.sourceforge.net</arc:http-header-from>\r\n";
        mdData += "<arc:robots>classic</arc:robots>\r\n";
        mdData += "<dc:format>ARC file version 1.1</dc:format>\r\n";
        mdData += "<dcterms:conformsTo xsi:type=\"dcterms:URI\">http://www.archive.org/web/researcher/ArcFileFormat.php</dcterms:conformsTo>\r\n";
        mdData += "</arcmetadata>\r\n";
        vbData = "1 1 InternetArchive\n";
        vbData += "URL IP-address Archive-date Content-type Archive-length\n";
        arcData = "filedesc://BNF-FS-072076.arc.gz 0.0.0.0 20060305082251 text/plain " + (vbData.length() + mdData.length()) + "\n";
        arcData += vbData;
        arcData += mdData;
        arcData += "\n";
        return arcData.getBytes();
    }

}


text:
begin
  $KCODE = 'u' if RUBY_VERSION < '1.9'

  require 'rubygems'
  require 'active_support'
rescue LoadError
end

module Railslove
  module Plugins
    module FindByParam
      def self.enable # :nodoc:
        return if ActiveRecord::Base.kind_of?(self::ClassMethods)

        ActiveRecord::Base.class_eval do
          if respond_to? :class_attribute
            class_attribute :permalink_options
          else
            class_inheritable_accessor :permalink_options
          end

          self.permalink_options = {:param => :id}

          #default finders these are overwritten if you use make_permalink in
          # your model
          def self.find_by_param(value,args={}) # :nodoc:
            find_by_id(value,args)
          end
          def self.find_by_param!(value,args={}) # :nodoc:
            find(value,args)
          end
        end
        ActiveRecord::Base.extend(self::ClassMethods)
      end

      module ClassMethods

=begin rdoc

This method initializes find_by_param

  class Post < ActiveRecord::Base
    make_permalink :with => :title, :prepend_id => true
  end

The only required parameter, is <tt>:with</tt>.

If you want to use a non URL-save attribute as permalink your model should have a permalink-column to save the escaped permalink value. This field is then used for search.

If your you can just say make_permalink :with => :login and you're done.

You can use for example User.find_by_param(params[:id], args) to find the user by the defined permalink.

== Available options

<tt>:with</tt>:: (required) The attribute that should be used as permalink
<tt>:field</tt>:: The name of your permalink column. make_permalink first checks if there is a column, default is 'permalink'.
<tt>:prepend_id</tt>:: [true|false] Do you want to prepend the ID to the permalink? for URLs like: posts/123-my-post-title - find_by_param uses the ID column to search, default is false.
<tt>:param_size</tt>:: [Number] Desired maximum size of the permalink, default is 50.
<tt>:escape</tt>:: [true|false] Do you want to escape the permalink value? (strip chars like öä?&) - actually you must do that, default is true.
<tt>:validate</tt>:: [true|false] Don't validate the :with field - set this to false if you validate it on your own, default is true.
<tt>:forbidden</tt>:: [Regexp|String|Array of Strings] Define which values should be forbidden. This is useful when combining user defined values to generate permalinks in combination with restful routing. <b>Make sure, especially in the case of a Regexp argument, that values may become valid by adding or incrementing a trailing integer.</b>
=end
        def make_permalink(options={})
          options[:field] ||= "permalink"
          options[:param] = options[:with] # :with => :login - but if we have a spcific permalink column we need to set :param to the name of that column
          options[:escape] ||= true
          options[:prepend_id] ||= false
          options[:param_size] ||= 50
          options[:validate] = true if options[:validate].nil?

          # validate if there is something we can use as param. you can overwrite the validate_param_is_not_blank method to customize the validation and the error messge.
          if !options[:prepend_id] || !options[:validate]
            validate :validate_param_is_not_blank
          end

          if forbidden = options.delete(:forbidden)
            if forbidden.is_a? Regexp
              options[:forbidden_match] = forbidden
            else
              options[:forbidden_strings] = Array(forbidden).map(&:to_s)
            end
          end

          if self.column_names.include?(options[:field].to_s)
            options[:param] = options[:field]
            before_save :save_permalink
          end

          self.permalink_options = options
          extend Railslove::Plugins::FindByParam::SingletonMethods
          include Railslove::Plugins::FindByParam::InstanceMethods
        rescue ActiveRecord::ActiveRecordError
          puts "[find_by_param error] database not available?"
        end
      end

      module SingletonMethods

=begin rdoc

Search for an object by the defined permalink column. Similar to
+find_by_login+. Returns +nil+ if nothing is found. Accepts an options hash as
second parameter which is passed on to the rails finder.
=end
        def find_by_param(value, args={})
          if permalink_options[:prepend_id]
            param = "id"
            value = value.to_i
          else
            param = permalink_options[:param]
          end
          self.send("find_by_#{param}".to_sym, value, args)
        end

=begin rdoc

Like +find_by_param+ but raises an <tt>ActiveRecord::RecordNotFound</tt> error
if nothing is found - similar to find().

Accepts an options hash as second parameter which is passed on to the rails
finder.
=end
        def find_by_param!(value, args={})
          param = permalink_options[:param]
          obj = find_by_param(value, args)
          raise ::ActiveRecord::RecordNotFound unless obj
          obj
        end
      end

      module InstanceMethods
        def to_param
          value = self.send(permalink_options[:param]).dup.to_s.downcase rescue ""
          ''.tap do |param|
            if value.blank?
              param << id.to_s
            else
              param << "#{id}-" if permalink_options[:prepend_id]
              param << escape_and_truncate_permalink(value)
            end
          end
        end

        protected

        def save_permalink
          return unless self.class.column_names.include?(permalink_options[:field].to_s)
          counter = 0
          base_value = escape_and_truncate_permalink(send(permalink_options[:with])).downcase
          permalink_value = base_value.to_s

          conditions = ["#{self.class.table_name}.#{permalink_options[:field]} = ?", permalink_value]
          unless new_record?
            conditions.first << " and #{self.class.table_name}.#{self.class.primary_key} != ?"
            conditions       << self.send(self.class.primary_key.to_sym)
          end
          while is_forbidden?(permalink_value) or
                self.class.count(:all, :conditions => conditions) > 0
            counter += 1
            permalink_value = "#{base_value}-#{counter}"

            if permalink_value.size > permalink_options[:param_size]
              length = permalink_options[:param_size] - counter.to_s.size - 2
              truncated_base = base_value[0..length]
              permalink_value = "#{truncated_base}-#{counter}"
            end

            conditions[1] = permalink_value
          end
          write_attribute(permalink_options[:field], permalink_value)
          true
        end

        def validate_param_is_not_blank
          if self.escape_and_truncate_permalink(self.send(permalink_options[:with])).blank?
            errors.add(permalink_options[:with],
                       "must have at least one non special character (a-z 0-9)")
          end
        end

        def escape_permalink(value)
          value.to_s.parameterize
        end

        def is_forbidden?(permalink_value)
          is_forbidden_string?(permalink_value) ||
            matches_forbidden_regexp?(permalink_value)
        end

        def is_forbidden_string?(permalink_value)
          permalink_options[:forbidden_strings] &&
            permalink_options[:forbidden_strings].include?(permalink_value)
        end

        def matches_forbidden_regexp?(permalink_value)
          permalink_options[:forbidden_match] &&
            permalink_options[:forbidden_match] =~ permalink_value
        end

        def escape_and_truncate_permalink(value)
          p = self.escape_permalink(value)[0...self.permalink_options[:param_size]]
          p.ends_with?('-') ? p.chop : p
        end
      end

    end
  end
end

if defined?(ActiveRecord)
  Railslove::Plugins::FindByParam.enable
end

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}

{% load i18n %}

{% block head_title %}{% trans "Frequently Asked Questions" %}{% endblock %}

{% block body %}

Frequently Asked Questions

Who maintains this site?

This website was created and is maintained by Krzysztof "noisy" Szumny. In most cases, he is the one, who introduce new features, which are so good-looking only thanks to work of Andrej Cibík - lead designer of this project.

How can I contribute?

This website was prepared in a way, that it could be maintained mostly by the community. This project is open-source, what means that everyone can contribute, by creating a pull request. Even if you are not a programmer, you can still help by adding information about new projects, which should be listed on {{ SITE_TITLE }} or you can help by creating Comparision Grids.

What are grids?

Grids let you compare {{ FRAMEWORK_NAME }} projects to each other. A grid comes with a number of default items compared, but you can add more features in order to get a more specific comparison.

For now, we are trying out {{ SITE_TITLE }} without the traditional tagging system, because we think that
          grids give us a lot more specificity.

What are categories?

Categories are broad groups of {{ FRAMEWORK_NAME }} projects into something more granular than Grids. A project can only have one category. Changing then requires backend work, and is not done lightly. This is intentional, done in order to make searching easier.

Which source control sites do you support?

Github and Bitbucket are supported.

{#
What about RSS & Atom Syndication?
#}
{##}
{#
The Syndication page has more details.
#}

{% endblock %}


text:
id: 587d7fa8367417b2b2512bcc
title: Exibir formas com o SVG
challengeType: 6
forumTopicId: 301485
dashedName: display-shapes-with-svg
---

# --description--

O último desafio criou um elemento `svg` com uma determinada largura e altura, que era visível porque tinha uma `background-color` aplicada a ele na tag `style`. O código criou espaço para a largura e altura fornecidas.

O próximo passo é criar uma forma para colocar na área do `svg`. Há várias formas suportadas no SVG, como retângulos e círculos. Elas são usadas para exibir dados. Por exemplo, a forma do retângulo (`<rect>`) do SVG pode criar uma barra em um gráfico de barras.

Quando você coloca uma forma na área do `svg`, você pode especificar onde ela vai com as coordenadas `x` e `y`. O ponto de origem (0, 0) está no canto superior esquerdo. Valores positivos para `x` empurram a forma para a direita, enquanto valores positivos para `y` empurram a forma para baixo do ponto de origem.

Para colocar uma forma no meio do `svg` de 500 (largura) x 100 (altura) do último desafio, a coordenada `x` seria 250 e a coordenada `y` seria 50.

Uma forma `rect` do SVG tem quatro atributos. Existem as coordenadas `x` e `y`, para onde elas são colocadas na área do `svg`. Ela também tem `height` e `width` para especificar o tamanho.

# --instructions--

Adicione uma forma `rect` ao `svg` usando `append()`. Dê a ele um atributo `width` de `25` e uma `height` de `100`. Além disso, dê aos atributos de `rect`, `x` e `y`, o valor de `0`.

# --hints--

O documento deve ter 1 elemento `rect`.

```js
assert($('rect').length == 1);
```

O elemento `rect` deve ter um atributo `width` com o valor de `25`.

```js
assert($('rect').attr('width') == '25');
```

O elemento `rect` deve ter um atributo `height` com o valor de `100`.

```js
assert($('rect').attr('height') == '100');
```

O elemento `rect` deve ter um atributo `x` com o valor de `0`.

```js
assert($('rect').attr('x') == '0');
```

O elemento `rect` deve ter um atributo `y` com o valor de `0`.

```js
assert($('rect').attr('y') == '0');
```

# --seed--

## --seed-contents--

```html
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h)
                  // Add your code below this line

                  // Add your code above this line
  </script>
</body>
```

# --solutions--

```html
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

    const svg = d3.select("body")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h)
                  .append("rect")
                  .attr("width", 25)
                  .attr("height", 100)
                  .attr("x", 0)
                  .attr("y", 0);
  </script>
</body>
```


text:
namespace tb {

PreferredSize TBImageWidget::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
{
	return PreferredSize(m_image.Width(), m_image.Height());
}

void TBImageWidget::OnPaint(const PaintProps &paint_props)
{
	if (TBBitmapFragment *fragment = m_image.GetBitmap())
		g_renderer->DrawBitmap(GetPaddingRect(), TBRect(0, 0, m_image.Width(), m_image.Height()), fragment);
}

}; // namespace tb

#endif // TB_IMAGE


text:
$(document).ready(() => {
    var config: DataTables.Settings = {
        // Select extension options
        select: {
            blurable: true,
            className: "selectClass",
            info: true,
            items: "row",
            selector: "td:first-child",
            style: "os"
        }
    };
});


text:
Shoreditch EshwariAI
=====================

This AI has been built to compete in SiliconMilkRoundabout Competition

Get it running
==============

To get the AI running it's easiest to set up a virtualenv, install the requirements, then run player.py, like so:
	virtualenv ve
	source ve/bin/activate
	pip install -r requirements
	python player.py

The AI runs on 8099
Logic behind the AI
-------------------

The main objective is to understand the previous actions of the opponents to make calculate better trades.

Basic overview
--------------

When a game is started, the `start_game` method will be called.

When it's your turn to take a turn, the `start_turn` method will be called. the `actions` parameter includes a list of actions taken by other players since your last turn. All turn actions should be taken in this method, and the method should end with game.end_turn().

If the turn runs out the `time_up` method will be called. When this is called it also sets game.turn to be False, which can be checked in the `start_turn` method.

`end_game` will be called when a game is over. Error will be set if there was a problem (e.g. another player doesn't exist), otherwise it will be None. This method can be used to clean up temporary data from the game.

`incoming_trade` will be called when a trade is offered from another player. `player` is the ID of the player offering the trade, `offering` is resource -> number of what is being offered for trade, `requestings` is resource -> number of what the other person wants for trade. Return True to accept the offer and False to reject.

game
-----
The object "game" is passed in all calls, and it represents the game in progress.

a Game has the following attributes:

* `game` which is the unique id of the game
* `resources` which is resource -> number for every resource the player has
* `generators` which is resource -> number for every basic generator the player has
* `improved_generators` which is resource -> number for every improved generator the player has
* `pr` which is the amount of PR the player has
* `customers` which is the amount of customers the player has
* `turn` which indicates if it's the player's turn or not

and the following methods:

* `can_purchase_pr` returns True if the player has enough resources to purchase PR
* `can_purchase_generator` returns true if the player has enough resources to purchase a generator and doesn't have more than the maximum limit
* `can_upgrade_generator` returns true if the player has enough resources to upgrade a generator, doesn't have more than the maximum limit, and has at least one generator to be upgraded
* `purchase_pr` will purchase 1 PR, returning True if the player now has the most PR in the game (and a 2 customer bonus), and false if they do not.
* `purchase_generator` will purchase 1 random generator, returning the generator type purchased. If you cannot purchase a generator it will return False
* `upgrade_generator` will upgrade either the generator type passed as the first parameter, or a random generator. If it is able to upgrade the generator it will return the type of the generator upgraded, otherwise it will return False.
* `trade` should be called with `offering` and `requesting` as resource -> number indicating what is being offered/requested. This will return the id of the user who accepted, if it is accepted (or "bank" if accepted by the bank), and False if it is rejected.
* `end_turn` will end then turn.

db
----

The object "db" is passed in all calls, and it can be used to store information across requests. It supports the following calls:
* db.save(doc) - Save a document to the store (with a unique 'id' key) - if no id is present in the document, one is generated and returned.
* db.get(id) - Get a doc from the store by its id
* db.exists(id) - Does a document with the given id exist?
* db.get_by_keys([keys]) - Get a number of documents by keys


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="es.rpallas.gestionalumnos"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GestorActivity"
            android:label="@string/title_activity_gestor"
            android:screenOrientation="landscape" >
        </activity>
    </application>

</manifest>


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using KUtils;
using System.Diagnostics;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace KFrameWork
{

    public abstract class BaseBundleLoader : PoolCls<BaseBundleLoader>, IPool, IDisposable
    {
        private static uint Counter = 0;
        protected bool isABMode
        {
            get
            {
#if UNITY_EDITOR
                if (Application.isPlaying && MainLoop.getInstance().OpenABMode)
                    return true;
                return false;
#elif UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID
                return true;
#endif
            }
        }

        protected bool isSceneLoad
        {
            get
            {
                return this is SceneAsyncLoader || this is SceneSyncLoader;
            }
        }

        public uint UID { get; private set; }

        protected string LoadResPath;

        protected BundlePkgInfo loadingpkg;

        protected UnityEngine.Object _BundleMainObject;

        protected IBundleRef _BundleRef;

        protected SceneOperation _AsyncOpation;

        protected GameObject PreParedGameObject;

        protected GameObject LoaderInsObject;
#if UNITY_EDITOR
        private Stopwatch _timer = new Stopwatch();
#endif
        private BundleLoadState _state;

        public BundleLoadState LoadState
        {
            get
            {
                return this._state;
            }
            protected set
            {
                BundleLoadState old = this._state;
                this._state = value;
                if (old == BundleLoadState.Prepared && value == BundleLoadState.Running)
                {
#if UNITY_EDITOR
                    if (FrameWorkConfig.Open_DEBUG)
                    {
                        _timer.Reset();
                        _timer.Start();
                    }

#endif
                    this.OnStart();
                }

                if (old == BundleLoadState.Running && value == BundleLoadState.Paused)
                    this.OnPaused();

                if (old == BundleLoadState.Paused && value == BundleLoadState.Running)
                    this.OnResume();

                if (old == BundleLoadState.Running && value == BundleLoadState.Finished)
                {
#if UNITY_EDITOR
                    string filename = loadingpkg != null ? this.loadingpkg.BundleName : "";
#endif
                    this.OnFinish();
                    this.OnProgressHandler = null;
#if UNITY_EDITOR
                    if (FrameWorkConfig.Open_DEBUG)
                    {
                        _timer.Stop();
                        LogMgr.LogFormat("{0} cost {1}", filename, _timer.Elapsed.TotalSeconds.ToString());
                        if (_timer.Elapsed.TotalSeconds > 0.5f)
                        {
                            LogMgr.LogError("cost large");
                        }
                    }

#endif
                }

                if (old != BundleLoadState.Error && value == BundleLoadState.Error)
                {
#if UNITY_EDITOR
                    string filename = loadingpkg != null ? this.loadingpkg.BundleName : "";
#endif
                    this.OnError();
                    this.OnProgressHandler = null;

#if UNITY_EDITOR
                    if (FrameWorkConfig.Open_DEBUG)
                    {
                        _timer.Stop();
                        LogMgr.LogFormat("{0} cost {1}", filename, _timer.Elapsed.TotalSeconds.ToString());
                        if (_timer.Elapsed.TotalSeconds > 0.5f)
                        {
                            LogMgr.LogError("cost large");
                        }
                    }
#endif
                }
            }
        }

        public Action<bool, AssetBundleResult> onComplete;

        public Action<BaseBundleLoader, int, int> OnProgressHandler;

        #region events
        protected abstract void OnStart();
        /// <summary>
        /// 通常在异步加载中
        /// </summary>
        protected abstract void OnPaused();

        protected abstract void OnResume();

        protected virtual void OnError()
        {
            this.InvokeHandler(false);
        }

        protected virtual void OnFinish()
        {
            if (LoaderInsObject == null && this.PreParedGameObject != null)
            {
                if (this._BundleMainObject is GameObject)
                {
                    GameObject gameobject = GameObject.Instantiate(this._BundleMainObject) as GameObject;
                    this.LoaderInsObject = PreParedGameObject.AddInstance(gameobject);
                }
                else
                {
                    LogMgr.LogErrorFormat("{0} 类型错误非gameobject ", _BundleMainObject);
                }
            }

            this.InvokeHandler(true);
        }

        #endregion

        public BaseBundleLoader()
        {
            this.UID = ++Counter;
        }

        #region interface
        public virtual void Load(string name)
        {
            this.LoadResPath = name;
            if (this.LoadState == BundleLoadState.Prepared)
            {
                this.LoadState = BundleLoadState.Running;
            }
        }

        public virtual void Load(string name, GameObject Parent)
        {
            this.PreParedGameObject = Parent;
            this.Load(name);
        }

        public virtual void DownLoad(string url)
        {
            if (this.LoadState == BundleLoadState.Prepared)
            {
                this.LoadState = BundleLoadState.Running;
            }
        }

        public virtual void Pause()
        {
            if (this.LoadState != BundleLoadState.Paused
                && this.LoadState != BundleLoadState.Finished
                && this.LoadState != BundleLoadState.Error
                && this.LoadState != BundleLoadState.Stopped)
            {
                this.LoadState = BundleLoadState.Paused;
            }
        }

        public virtual void Stop()
        {
            if (this.LoadState != BundleLoadState.Finished && this.LoadState != BundleLoadState.Error
                && this.LoadState != BundleLoadState.Stopped)
            {
                this.LoadState = BundleLoadState.Stopped;
            }
        }

        public virtual void Resume()
        {
            if (this.LoadState != BundleLoadState.Error && this.LoadState != BundleLoadState.Stopped
                && this.LoadState != BundleLoadState.Finished)
            {
                this.LoadState = BundleLoadState.Running;
            }
        }

        public AssetBundleResult GetABResult()
        {
            AssetBundleResult result = new AssetBundleResult(this._BundleRef, this._BundleMainObject, this.PreParedGameObject, this.LoaderInsObject, this.LoadResPath);
            result.SceneAsyncResult = this._AsyncOpation as SceneOperation;
            return result;
        }

        public virtual void Dispose()
        {

            if (KObjectPool.mIns != null)
            {
                KObjectPool.mIns.Push(this);
            }
        }

        #endregion

        #region POOL

        public static T CreateLoader<T>() where T : BaseBundleLoader, new()
        {
            T t = TrySpawn<T>();
            if (t != null)
                t.UID = ++Counter;
            return t;
        }

        public virtual void RemoveToPool()
        {
            this._BundleMainObject = null;
            this._BundleRef = null;
            this.loadingpkg = null;
            this.LoadResPath = null;
            this.LoadState = BundleLoadState.Prepared;
            this.onComplete = null;
            this.LoaderInsObject = null;
            this.PreParedGameObject = null;
            this._AsyncOpation = null;
        }

        #endregion

        protected void InvokeHandler(bool bvalue)
        {
            ResBundleMgr.mIns.Cache.RemoveLoading(this.LoadResPath);

            if (this.onComplete != null)
            {
                this.onComplete(bvalue, GetABResult());
            }
        }

        protected void InvokeProgressHandler(int current, int total)
        {
            //LogMgr.LogError("cur "+ current+" t "+ total +" res "+ LoadResPath);
            if (this.OnProgressHandler != null)
            {
                this.OnProgressHandler(this, current, total);
            }
        }

        protected bool isRunning()
        {
            return this.LoadState == BundleLoadState.Running;
        }

        protected bool isPaused()
        {
            return this.LoadState == BundleLoadState.Paused;
        }

        protected BundlePkgInfo _SeekPkgInfo(string name)
        {
            BundlePkgInfo pkginfo = ResBundleMgr.mIns.BundleInformation.SeekInfo(name);

            if (pkginfo == null)
            {
                this.LoadState = BundleLoadState.Error;
                throw new FrameWorkException(string.Format("Not Found {0}", name), ExceptionType.Higher_Excetpion);
            }

            return pkginfo;
        }

        protected AssetBundle LoadAssetBundle(string path)
        {
            if (MainLoop.getInstance().OpenABMode)
            {
#if UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID
                AssetBundle ab = KAssetBundle.LoadFromFile(path);
                return ab;
#else
                return null;
#endif
            }
            else
            {
                return null;
            }
        }

        protected IBundleRef LoadFullAssetToMem(BundlePkgInfo pkginfo)
        {
            IBundleRef bundle = null;
            if (ResBundleMgr.mIns.Cache.Contains(pkginfo))
            {
                bundle = ResBundleMgr.mIns.Cache.TryGetValue(pkginfo);
                return bundle;
            }

#if UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID
            if (GameApplication.isPlaying && MainLoop.getInstance().OpenABMode)
            {
                AssetBundle ab = null;
                using (gstring.Block())
                {
                    ab = this.LoadAssetBundle(BundlePathConvert.GetRunningPath(pkginfo.AbFileName));
                }

                if (ab == null)
                    this.ThrowAssetMissing(this.LoadResPath);

                bundle = ResBundleMgr.mIns.Cache.PushAsset(pkginfo, ab);
                return bundle;
            }
            else
#endif
            {
                UnityEngine.Object target = AssetDatabaseLoad(pkginfo.EditorPath);
                if (target == null)
                {
                    if (BundleConfig.SAFE_MODE)
                    {
                        this.ThrowAssetMissing(pkginfo.BundleName);
                    }
                    else
                    {
                        this.LoadState = BundleLoadState.Error;
                        LogMgr.LogErrorFormat("Asset {0} Missing", pkginfo.BundleName);
                    }
                }
                else
                {
#if UNITY_EDITOR
                    bundle = ResBundleMgr.mIns.Cache.PushEditorAsset(pkginfo, target);
#endif
                }
                return bundle;
            }
        }

        private UnityEngine.Object AssetDatabaseLoad(string path)
        {
#if UNITY_EDITOR
            return AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
#else
            return null;
#endif
        }

        protected AssetBundleCreateRequest LoadFullAssetToMemAsync(BundlePkgInfo pkginfo)
        {
            if (Application.isPlaying && MainLoop.getInstance())
            {
                AssetBundleCreateRequest abRequst = null;
                using (gstring.Block())
                {
                    abRequst = KAssetBundle.LoadFromFileAsync(BundlePathConvert.GetRunningPath(pkginfo.AbFileName));
                }

                return abRequst;
            }
            else
            {
                return null;
            }
        }

        protected bool CreateFromAsset(IBundleRef bundle, out UnityEngine.Object asset)
        {
            if (isSceneLoad)
            {
                asset = null;
                return true;
            }

            bool ret = bundle.LoadAsset(out asset);
            if (!ret)
            {
                this.ThrowAssetMissing(this.LoadResPath);
            }

            return ret;
        }

        protected void AddDepends(BundlePkgInfo pkginfo, IBundleRef bundle)
        {
            if (!isABMode)
                return;

            if (bundle != null)
            {
                for (int i = 0; i < pkginfo.Depends.Length; ++i)
                {
                    IBundleRef depbund = ResBundleMgr.mIns.Cache.TryGetValue(pkginfo.Depends[i]);
                    if (depbund != null)
                    {
                        bundle.NeedThis(depbund);
                    }
                    else
                    {
                        this.ThrowBundleMissing(pkginfo.Depends[i]);
                    }
                }
            }
            else
            {
                this.ThrowBundleMissing(pkginfo.BundleName);
            }
        }

        protected void ThrowLogicError(string info = null)
        {
            ResBundleMgr.mIns.Cache.RemoveLoading(this.LoadResPath);
            this.LoadState = BundleLoadState.Error;
            throw new FrameWorkException(string.Format("{0} 逻辑异常", info), ExceptionType.Higher_Excetpion);
        }

        protected void ThrowBundleMissing(string resname)
        {
            ResBundleMgr.mIns.Cache.RemoveLoading(resname);
            ResBundleMgr.mIns.Cache.RemoveLoading(this.LoadResPath);
            if (BundleConfig.SAFE_MODE)
                throw new FrameWorkResMissingException(string.Format("Bundle {0} Missing", resname));
            else
            {
                this.LoadState = BundleLoadState.Error;
                LogMgr.LogErrorFormat("Bundle {0} Missing", resname);
            }
        }

        protected void ThrowAssetMissing(string resname)
        {
            ResBundleMgr.mIns.Cache.RemoveLoading(resname);
            ResBundleMgr.mIns.Cache.RemoveLoading(this.LoadResPath);
            if (BundleConfig.SAFE_MODE)
                throw new FrameWorkResMissingException(string.Format("Asset =》{0} Missing", resname));
            else
            {
                this.LoadState = BundleLoadState.Error;
                LogMgr.LogErrorFormat("Asset =》{0} Missing", resname);
            }
        }
    }

}


text:
#ifndef B2_POLYGON_H
#define B2_POLYGON_H

#include <cstring>
#include <cfloat>
#include <cstdio>
//#include "Box2D.h"
#include "b2Triangle.h"

class b2Polygon;

int32 remainder(int32 x, int32 modulus);
int32 TriangulatePolygon(float32* xv, float32* yv, int32 vNum, b2Triangle* results);
bool IsEar(int32 i, float32* xv, float32* yv, int32 xvLength); //Not for external use
int32 PolygonizeTriangles(b2Triangle* triangulated, int32 triangulatedLength, b2Polygon* polys, int32 polysLength);
int32 DecomposeConvex(b2Polygon* p, b2Polygon* results, int32 maxPolys);
//void DecomposeConvexAndAddTo(b2Polygon* p, b2Body* bd, b2FixtureDef* prototype);
b2Polygon ConvexHull(b2Vec2* v, int nVert);
b2Polygon ConvexHull(float32* cloudX, float32* cloudY, int32 nVert);
void ReversePolygon(float32* x, float32* y, int n);

b2Polygon TraceEdge(b2Polygon* p); //For use with self-intersecting polygons, finds outline

class b2Polygon {

public:
    const static int32 maxVerticesPerPolygon = 8;//b2_maxPolygonVertices;

    float32* x; //vertex arrays
    float32* y;
    int32 nVertices;

	float32 area;
	bool areaIsSet;

    b2Polygon(float32* _x, float32* _y, int32 nVert);
    b2Polygon(b2Vec2* v, int32 nVert);
	b2Polygon();
    ~b2Polygon();

	float32 GetArea();

	void MergeParallelEdges(float32 tolerance);
    b2Vec2* GetVertexVecs();
    b2Polygon(b2Triangle& t);
    void Set(const b2Polygon& p);
    bool IsConvex();
	bool IsCCW();
	bool IsUsable(bool printError);
	bool IsUsable();
    bool IsSimple();
    //void AddTo(b2FixtureDef& pd);

    b2Polygon* Add(b2Triangle& t);

	void print(){
		printFormatted();
//		for (int32 i=0; i<nVertices; ++i){
//			printf("i: %d, x:%f, y:%f\n",i,x[i],y[i]);
//		}
	}

	void printFormatted(){
		printf("float xv[] = {");
		for (int32 i=0; i<nVertices; ++i){
			printf("%ff,",x[i]);
		}
		printf("};\nfloat yv[] = {");
		for (int32 i=0; i<nVertices; ++i){
			printf("%ff,",y[i]);
		}
		printf("};\n");
	}

	b2Polygon(const b2Polygon& p){
		nVertices = p.nVertices;
		area = p.area;
		areaIsSet = p.areaIsSet;
		x = new float32[nVertices];
		y = new float32[nVertices];
		memcpy(x, p.x, nVertices * sizeof(float32));
		memcpy(y, p.y, nVertices * sizeof(float32));
	}

};

const int32 MAX_CONNECTED = 32;
const float32 COLLAPSE_DIST_SQR = FLT_EPSILON*FLT_EPSILON;//0.1f;//1000*FLT_EPSILON*1000*FLT_EPSILON;

class b2PolyNode{
public:
	b2Vec2 position;
	b2PolyNode* connected[MAX_CONNECTED];
	int32 nConnected;
	bool visited;

	b2PolyNode(b2Vec2& pos);
	b2PolyNode();
	void AddConnection(b2PolyNode& toMe);
	void RemoveConnection(b2PolyNode& fromMe);
	void RemoveConnectionByIndex(int32 index);
	bool IsConnectedTo(b2PolyNode& me);
	b2PolyNode* GetRightestConnection(b2PolyNode* incoming);
	b2PolyNode* GetRightestConnection(b2Vec2& incomingDir);
};

#endif


text:
#ifndef HB_H_IN
#error "Include <hb.h> instead."
#endif

#ifndef HB_DEPRECATED_H
#define HB_DEPRECATED_H

#include "hb-common.h"
#include "hb-unicode.h"
#include "hb-font.h"

HB_BEGIN_DECLS

#ifndef HB_DISABLE_DEPRECATED

#define HB_SCRIPT_CANADIAN_ABORIGINAL		HB_SCRIPT_CANADIAN_SYLLABICS

#define HB_BUFFER_FLAGS_DEFAULT			HB_BUFFER_FLAG_DEFAULT
#define HB_BUFFER_SERIALIZE_FLAGS_DEFAULT	HB_BUFFER_SERIALIZE_FLAG_DEFAULT

typedef hb_bool_t (*hb_font_get_glyph_func_t) (hb_font_t *font, void *font_data,
					       hb_codepoint_t unicode, hb_codepoint_t variation_selector,
					       hb_codepoint_t *glyph,
					       void *user_data);

HB_EXTERN void
hb_font_funcs_set_glyph_func (hb_font_funcs_t *ffuncs,
			      hb_font_get_glyph_func_t func,
			      void *user_data, hb_destroy_func_t destroy);

#endif

HB_END_DECLS

#endif /* HB_DEPRECATED_H */


text:
package org.royrusso.app;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import org.royrusso.actor.SimpleActor;
import org.royrusso.command.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Main runtime class.
 */
public class System {

    public static final Logger log = LoggerFactory.getLogger(System.class);

    public static void main(String... args) throws Exception {

        final ActorSystem actorSystem = ActorSystem.create("actor-system");

        Thread.sleep(5000);

        final ActorRef actorRef = actorSystem.actorOf(Props.create(SimpleActor.class), "simple-actor");

        actorRef.tell(new Command("CMD 1"), null);
        actorRef.tell(new Command("CMD 2"), null);
        actorRef.tell(new Command("CMD 3"), null);
        actorRef.tell(new Command("CMD 4"), null);
        actorRef.tell(new Command("CMD 5"), null);

        Thread.sleep(5000);

        log.debug("Actor System Shutdown Starting...");

        actorSystem.shutdown();
    }
}


text:
var title = "Explore The Seams";
var desc = "Visit 3 \"Seam Streets\" located behind key-locked doors around the world. Hint: You will \"Finds\" the entrance to one of the seam streets on the west side of <a href=\"event:location|89\">Andra<\/a>. (To find the rest, you'll need to ask around, or go exploring!)";
var offer = "Ancient lore tells of locations made from the dreamy goo that act as \"seams\" between the fully-imagined regions of the world.<split butt_txt=\"Whoa.\">You will not find them on any map, and to be worthy of entering, you will need the correct key.<split butt_txt=\"Sounds exciting!\">Go forth, and visit 3 locations that act as \"seams\" between various regions of the world.";
var completion = "Congratulations, worthy glitch. You have visited 3 of the seam streets in the world.<split butt_txt=\"Hooray!\">The giants smile upon you!";

var auto_complete = 0;
var familiar_turnin = 1;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = [];
var prerequisites = [{
		"not"		:0,
		"condition":	"has_achievement",
		"value":	"senior_ok_explorer"
}];
var end_npcs = [];
var locations = {};
var requirements = {
	"r433"	: {
		"type"		: "counter",
		"name"		: "visit_seam_street",
		"num"		: 3,
		"desc"		: "Visit 3 Seam Streets"
	}
};

function onComplete(pc){ // generated from rewards
	var xp=0;
	var currants=0;
	var mood=0;
	var energy=0;
	var favor=0;
	var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
	multiplier += pc.imagination_get_quest_modifier();
	xp = pc.stats_add_xp(round_to_5(650 * multiplier), true, {type: 'quest_complete', quest: this.class_tsid});
	currants = pc.stats_add_currants(round_to_5(300 * multiplier), {type: 'quest_complete', quest: this.class_tsid});
	energy = pc.metabolics_add_energy(round_to_5(100 * multiplier));
	favor = pc.stats_add_favor_points("lem", round_to_5(150 * multiplier));
	apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
	if(pc.buffs_has('gift_of_gab')) {
		pc.buffs_remove('gift_of_gab');
	}
	else if(pc.buffs_has('silvertongue')) {
		pc.buffs_remove('silvertongue');
	}
}
var rewards = {
	"xp"		: 650,
	"currants"	: 300,
	"energy"	: 100,
	"favor"		: {
		"0"	: {
			"giant"		: "lem",
			"points"	: 150
		}
	}
};

function isNewVisit(location_tsid){
	if (!this.seams_visited) this.seams_visited = {};
	if (this.seams_visited[location_tsid]) return false;

	this.seams_visited[location_tsid] = time();
	return true;
}

function onAccepted(pc){
	this.seams_visited = {};
}

// generated ok (NO DATE)


text:
=================================
Hive Connector with Azure Storage
=================================

The :doc:`hive` can be configured to query
Azure Standard Blob Storage and Azure Data Lake Storage Gen2 (ABFS). Azure Blobs
are accessed via the Windows Azure Storage Blob (WASB). This layer is built on
top of the HDFS APIs and is what allows for the separation of storage from the
cluster.

Presto supports both ADLS Gen1 and Gen2. With ADLS Gen2 now generally available,
we recommend using ADLS Gen2. Learn more from `the official documentation
<https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-overview>`_.

Hive Connector Configuration
----------------------------

All configuration for the Azure storage driver is stored in the Hadoop
``core-site.xml`` configuration file. The path to the file needs to be
configured in the the catalog properties file:

.. code-block:: none

    hive.config.resources=<path_to_hadoop_core-site.xml>

Configuration for Azure Storage credentials
-------------------------------------------

If you do not want to rely on Hadoop's ``core-site.xml`` and want to have Presto
configured independently with the storage credentials, you can use the following
properties in the catalog configuration.

We suggest to use this kind of configuration when you only have the Primary
Storage account linked to the cluster. When there are secondary storage accounts
involved, it is recommended to configure Presto using
``hive.config.resources=<path_to_hadoop_core-site.xml>``, provided
``core-site.xml`` has the all storage account credentials.

.. list-table:: **WASB properties**
  :widths: 30, 70
  :header-rows: 1

  * - Property name
    - Description
  * - ``hive.azure.wasb-storage-account``
    - Storage account name of Azure Blob Storage
  * - ``hive.azure.wasb-access-key``
    - The decrypted access key for the Azure Blob Storage

If you choose to use ADLS Gen2, you need to add the following properties:

.. list-table:: **ADLS Gen2 properties**
  :widths: 30, 70
  :header-rows: 1

  * - Property name
    - Description
  * - ``hive.azure.abfs-storage-account``
    - Storage account name of Azure Data Lake Storage Gen2
  * - ``hive.azure.abfs-access-key``
    - The decrypted access key for the Azure Data Lake Storage Gen2ß

While it is advised to migrate to ADLS Gen2 whenever possible, if you still
choose to use ADLS Gen1 you need to add the following properties.

.. note::

    Credentials for the filesystem can be configured using ``ClientCredential``
    type. To authenticate with ADLS Gen1 you must create a new application
    secret for your ADLS Gen1 account's App Registration, and save this value
    because you won't able to retrieve the key later. Refer to the Azure
    `documentation
    <https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-service-to-service-authenticate-using-active-directory>`_
    for details.

.. list-table:: **ADLS properties**
  :widths: 30, 70
  :header-rows: 1

  * - Property name
    - Description
  * - ``hive.azure.adl-client-id``
    - Client (Application) ID from the App Registrations for your storage
      account
  * - ``hive.azure.adl-credential``
    - Value of the new client (application) secret created
  * - ``hive.azure.adl-refresh-url``
    - OAuth 2.0 token endpoint url

Accessing Azure Storage data
----------------------------

URI scheme to reference data
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Consistent with other FileSystem implementations within Hadoop, the Azure
Standard Blob and Azure Data Lake Storage Gen2 (ABFS) drivers define their own
URI scheme so that resources (directories and files) may be distinctly
addressed. You can access both primary and secondary storage accounts linked to
the cluster with the same URI scheme. Following are example URIs for the
different systems.

ABFS URI:

.. code-block:: none

    abfs[s]://file_system@account_name.dfs.core.windows.net/<path>/<path>/<file_name>

ADLS Gen1 URI:

.. code-block:: none

    adl://<data_lake_storage_gen1_name>.azuredatalakestore.net/<path>/<file_name>

Azure Standard Blob URI:

.. code-block:: none

    wasb[s]://container@account_name.blob.core.windows.net/<path>/<path>/<file_name>

Querying Azure Storage
^^^^^^^^^^^^^^^^^^^^^^

You can query tables already configured in your Hive metastore used in your Hive
catalog. To access Azure Storage data that is not yet mapped in the Hive
metastore, you need to provide the schema of the data, the file format, and the
data location.

For example, if you have ORC or Parquet files in an ABFS ``file_system``, you
need to execute a query::

    -- select schema in which the table is to be defined, must already exist
    USE hive.default;

    -- create table
    CREATE TABLE orders (
         orderkey bigint,
         custkey bigint,
         orderstatus varchar(1),
         totalprice double,
         orderdate date,
         orderpriority varchar(15),
         clerk varchar(15),
         shippriority integer,
         comment varchar(79)
    ) WITH (
         external_location = 'abfs[s]://file_system@account_name.dfs.core.windows.net/<path>/<path>/<file_name>`',
         format = 'ORC' -- or 'PARQUET'
    );

Now you can query the newly mapped table::

    SELECT * FROM orders;

Writing data
------------

Prerequisites
^^^^^^^^^^^^^

Before you attempt to write data to Azure Storage, make sure you have configured
everything necessary to read data from the storage.

Create a write schema
^^^^^^^^^^^^^^^^^^^^^

If the Hive metastore contains schema(s) mapped to Azure storage filesystems,
you can use them to write data to Azure storage.

If you don't want to use existing schemas, or there are no appropriate schemas
in the Hive metastore, you need to create a new one::

    CREATE SCHEMA hive.abfs_export
    WITH (location = 'abfs[s]://file_system@account_name.dfs.core.windows.net/<path>');

Write data to Azure Storage
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Once you have a schema pointing to a location where you want to write the data,
you can issue a ``CREATE TABLE AS`` statement and select your desired file
format. The data will be written to one or more files within the
``abfs[s]://file_system@account_name.dfs.core.windows.net/<path>/my_table``
namespace. Example::

    CREATE TABLE hive.abfs_export.orders_abfs
    WITH (format = 'ORC')
    AS SELECT * FROM tpch.sf1.orders;


text:
package play.data;

import java.math.BigDecimal;

public class Money {

  @Formats.Currency private BigDecimal amount;

  public BigDecimal getAmount() {
    return this.amount;
  }

  public void setAmount(BigDecimal amount) {
    this.amount = amount;
  }
}


text:
"""This Apache Beam pipeline processes Landsat 8 satellite images and renders
them as JPEG files.

A Landsat 8 image consists of 11 bands. Each band contains the data for a
specific range of the electromagnetic spectrum.

A JPEG image consists of three channels: Red, Green, and Blue. For Landsat 8
images, these correspond to Band 4 (red), Band 3 (green), and Band 2 (blue).

These bands contain the raw pixel data directly from the satellite sensors. The
values in each band can go from 0 to unbounded positive values. For a JPEG image
we need to clamp them into integers between 0 and 255 for each channel.

For this, we supply visualization parameters, commonly called `vis_params`.
These visualization parameters include:

- The bands for the RGB cannels, typically [B4, B3, B2] for Landsat 8.
- The minimum value in each band, typically 0 for Landsat 8.
- The maximum value in each band, this varies depending on the light exposure.
- A gamma value for gamma correction.

The Landsat data is read from the Landsat public dataset in Cloud Storage.
For more information on the Landsat dataset:
    https://cloud.google.com/storage/docs/public-datasets/landsat

The overall workflow of the pipeline is the following:

- Parse one or more Landsat scene IDs from user-provided flags..
- Get the Cloud Storage paths of all the RGB bands.
- Load the pixel values for each band from Cloud Storage.
- Preprocess pixels: clamp values and apply gamma correction.
- Create a JPEG image and save it to Cloud Storage.
"""

import argparse
import logging
import os
import re
from typing import Any, Dict, List, Optional, Tuple

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import numpy as np
from PIL import Image
import rasterio
import tensorflow as tf

DEFAULT_RGB_BAND_NAMES = ["B4", "B3", "B2"]
DEFAULT_MIN_BAND_VALUE = 0.0
DEFAULT_MAX_BAND_VALUE = 12000.0
DEFAULT_GAMMA = 0.5

DEFAULT_SCENES = [
    "LC08_L1TP_001067_20200727_20200807_01_T1",  # Brazil-Bolivia boundary
    "LC08_L1TP_019024_20190621_20190704_01_T1",  # Nottaway river delta, Quebec
    "LC08_L1TP_019046_20191214_20191226_01_T1",  # Yucatan peninsula
    "LC08_L1TP_037035_20191212_20191212_01_T1",  # Grand canyon, Arizona
    "LC08_L1TP_045031_20200715_20200722_01_T1",  # Mount Shasta, California
    "LC08_L1TP_064011_20200618_20200625_01_T1",  # Mackenzie river delta, Canada
    "LC08_L1TP_073087_20200516_20200527_01_T1",  # Mt. Taranaki, New Zealand
    "LC08_L1TP_083074_20180805_20180814_01_T1",  # Nouvelle-Calédonie
    "LC08_L1TP_098063_20200703_20200708_01_T1",  # Manam volcano, Papua New Guinea
    "LC08_L1TP_109078_20200411_20200422_01_T1",  # Lake Carnegie, West Australia
    "LC08_L1TP_110036_20191009_20191018_01_T1",  # Osaka 大阪市, Japan
    "LC08_L1TP_115078_20200608_20200625_01_T1",  # Sediment deposits, West Australia
    "LC08_L1TP_119038_20191109_20191115_01_T1",  # Lake Tai 太湖, China
    "LC08_L1TP_135040_20190314_20190325_01_T1",  # Arunachal Pradesh, India
    "LC08_L1TP_137045_20200211_20200225_01_T1",  # Ganges river delta, India
    "LC08_L1TP_166075_20180608_20180615_01_T1",  # Bazaruto island, Mozambique
    "LC08_L1TP_169034_20200720_20200807_01_T1",  # Lake Urmia دریاچه ارومیه, Iran
    "LC08_L1TP_170059_20200101_20200113_01_T1",  # Mount Elgon, Uganda
    "LC08_L1TP_175079_20200511_20200526_01_T1",  # Sand dunes, South Africa
    "LC08_L1TP_178069_20200804_20200821_01_T1",  # Angola
    "LC08_L1TP_178078_20200804_20200821_01_T1",  # Sand dunes, Namibia
    "LC08_L1TP_191020_20200815_20200822_01_T1",  # Phytoplankton at Gotland, Sweden
    "LC08_L1TP_195028_20200116_20200127_01_T1",  # Swiss Alps
    "LC08_L1TP_203045_20200108_20200114_01_T1",  # Eye of the Sahara, Mauritania
    "LC08_L1TP_231094_20190906_20190917_01_T1",  # Patagonia, South America
]

SCENE_RE = re.compile(
    r"(?P<sensor>L[COTEM]0[78])_"
    r"(?P<correction_level>L1TP|L1GT|L1GS)_"
    r"(?P<wrs_path>\d\d\d)"
    r"(?P<wrs_row>\d\d\d)_"
    r"(?P<year>\d\d\d\d)"
    r"(?P<month>\d\d)"
    r"(?P<day>\d\d)_"
    r"(?P<processing_year>\d\d\d\d)"
    r"(?P<processing_month>\d\d)"
    r"(?P<processing_day>\d\d)_"
    r"(?P<collection>\d\d)_"
    r"(?P<category>RT|T1|T2)"
)

def check_gpus(_: None, gpus_optional: bool = False) -> None:
    """Validates that we are detecting GPUs, otherwise raise a RuntimeError."""
    gpu_devices = tf.config.list_physical_devices("GPU")
    if gpu_devices:
        logging.info(f"Using GPU: {gpu_devices}")
    elif gpus_optional:
        logging.warning("No GPUs found, defaulting to CPU.")
    else:
        raise RuntimeError("No GPUs found.")

def get_band_paths(scene: str, band_names: List[str]) -> Tuple[str, List[str]]:
    """Gets the Cloud Storage paths for each band in a Landsat scene.

    Args:
        scene: Landsat 8 scene ID.
        band_names: List of the band names corresponding to [Red, Green, Blue] channels.

    Returns:
        A (scene, band_paths) pair.

    Raises:
        ValueError: If the scene or a band does not exist.
    """
    # Extract the metadata from the scene ID using a regular expression.
    m = SCENE_RE.match(scene)
    if not m:
        raise ValueError(f"invalid scene ID: {scene}")

    g = m.groupdict()
    scene_dir = f"gs://gcp-public-data-landsat/{g['sensor']}/{g['collection']}/{g['wrs_path']}/{g['wrs_row']}/{scene}"

    band_paths = [f"{scene_dir}/{scene}_{band_name}.TIF" for band_name in band_names]

    for band_path in band_paths:
        if not tf.io.gfile.exists(band_path):
            raise ValueError(f"failed to load: {band_path}")

    return scene, band_paths

def load_values(scene: str, band_paths: List[str]) -> Tuple[str, np.ndarray]:
    """Loads a scene's bands data as a numpy array.

    Args:
        scene: Landsat 8 scene ID.
        band_paths: A list of the [Red, Green, Blue] band paths.

    Returns:
        A (scene, values) pair.

        The values are stored in a three-dimensional float32 array with shape:
            (band, width, height)
    """

    def read_band(band_path: str) -> np.array:
        # Use rasterio to read the GeoTIFF values from the band files.
        with tf.io.gfile.GFile(band_path, "rb") as f, rasterio.open(f) as data:
            return data.read(1)

    logging.info(f"{scene}: load_values({band_paths})")
    values = [read_band(band_path) for band_path in band_paths]
    return scene, np.array(values, np.float32)

def preprocess_pixels(
    scene: str,
    values: np.ndarray,
    min_value: float = 0.0,
    max_value: float = 1.0,
    gamma: float = 1.0,
) -> Tuple[str, tf.Tensor]:
    """Prepares the band data into a pixel-ready format for an RGB image.

    The input band values come in the shape (band, width, height) with
    unbounded positive numbers depending on the sensor's exposure.
    The values are reshaped into (width, height, band), the values are clamped
    to integers between 0 and 255, and a gamma correction value is applied.

    Args:
        scene: Landsat 8 scene ID.
        values: Band values in the shape (band, width, height).
        min_value: Minimum band value.
        max_value: Maximum band value.
        gamma: Gamma correction value.

    Returns:
        A (scene, pixels) pair. The pixels are Image-ready values.
    """
    logging.info(
        f"{scene}: preprocess_pixels({values.shape}:{values.dtype}, min={min_value}, max={max_value}, gamma={gamma})"
    )

    # Reshape (band, width, height) into (width, height, band).
    pixels = tf.transpose(values, (1, 2, 0))

    # Rescale to values from 0.0 to 1.0 and clamp them into that range.
    pixels -= min_value
    pixels /= max_value
    pixels = tf.clip_by_value(pixels, 0.0, 1.0)

    # Apply gamma correction.
    pixels **= 1.0 / gamma

    # Return the pixel values as int8 in the range from 0 to 255,
    # which is what PIL.Image expects.
    return scene, tf.cast(pixels * 255.0, dtype=tf.uint8)

def save_to_gcs(
    scene: str, image: Image.Image, output_path_prefix: str, format: str = "JPEG"
) -> None:
    """Saves a PIL.Image as a JPEG file in the desired path.

    Args:
        scene: Landsat 8 scene ID.
        image: A PIL.Image object.
        output_path_prefix: Path prefix to save the output files.
        format: Image format to save files.
    """
    filename = os.path.join(output_path_prefix, scene + "." + format.lower())
    with tf.io.gfile.GFile(filename, "w") as f:
        image.save(f, format)

def run(
    scenes: List[str],
    output_path_prefix: str,
    vis_params: Dict[str, Any],
    beam_args: Optional[List[str]] = None,
) -> None:
    """Load multiple Landsat scenes and render them as JPEG files.

    Args:
        scenes: List of Landsat 8 scene IDs.
        output_path_prefix: Path prefix to save the output files.
        vis_params: Visualization parameters including {rgb_bands, min, max, gamma}.
        beam_args: Optional list of arguments for Beam pipeline options.
    """
    rgb_band_names = vis_params["rgb_band_names"]
    min_value = vis_params["min"]
    max_value = vis_params["max"]
    gamma = vis_params["gamma"]

    beam_options = PipelineOptions(beam_args, save_main_session=True)
    pipeline = beam.Pipeline(options=beam_options)
    (
        pipeline
        | "Create scene IDs" >> beam.Create(scenes)
        | "Check GPU availability"
        >> beam.Map(
            lambda x, unused_side_input: x,
            unused_side_input=beam.pvalue.AsSingleton(
                pipeline | beam.Create([None]) | beam.Map(check_gpus)
            ),
        )
        | "Get RGB band paths" >> beam.Map(get_band_paths, rgb_band_names)
        | "Load RGB band values" >> beam.MapTuple(load_values)
        | "Preprocess pixels"
        >> beam.MapTuple(preprocess_pixels, min_value, max_value, gamma)
        | "Convert to image"
        >> beam.MapTuple(
            lambda scene, rgb_pixels: (
                scene,
                Image.fromarray(rgb_pixels.numpy(), mode="RGB"),
            )
        )
        | "Save to Cloud Storage" >> beam.MapTuple(save_to_gcs, output_path_prefix)
    )
    pipeline.run()

if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--output-path-prefix",
        required=True,
        help="Path prefix for output image files. "
        "This can be a Google Cloud Storage path.",
    )
    parser.add_argument(
        "--scene",
        dest="scenes",
        action="append",
        help="One or more Landsat scene IDs to process, for example "
        "LC08_L1TP_109078_20200411_20200422_01_T1. "
        "They must be in the format: "
        "https://www.usgs.gov/faqs/what-naming-convention-landsat-collections-level-1-scenes",
    )
    parser.add_argument(
        "--rgb-band-names",
        nargs=3,
        default=DEFAULT_RGB_BAND_NAMES,
        help="List of three band names to be mapped to the RGB channels.",
    )
    parser.add_argument(
        "--min",
        type=float,
        default=DEFAULT_MIN_BAND_VALUE,
        help="Minimum value of the band value range.",
    )
    parser.add_argument(
        "--max",
        type=float,
        default=DEFAULT_MAX_BAND_VALUE,
        help="Maximum value of the band value range.",
    )
    parser.add_argument(
        "--gamma", type=float, default=DEFAULT_GAMMA, help="Gamma correction factor."
    )
    args, beam_args = parser.parse_known_args()

    scenes = args.scenes or DEFAULT_SCENES
    vis_params = {
        "rgb_band_names": args.rgb_band_names,
        "min": args.min,
        "max": args.max,
        "gamma": args.gamma,
    }
    run(scenes, args.output_path_prefix, vis_params, beam_args)


text:
'use strict';

var fs = require('fs');
var Filter = require('broccoli-filter');
var markdown = require("marked");
var yamlFront = require('yaml-front-matter');

// set up the basic deck layout for rendering
var Handlebars = require('handlebars');
var layout = fs.readFileSync(__dirname + '/../templates/deck.html.hbs')
var render = Handlebars.compile(layout.toString());

markdown.setOptions({
  sanitize: false,
  smartypants: true
});

var SECTION_DELIMITER = /^={3,}$/mg
var SUBSECTION_DELIMITER = /^-{3,}$/mg

function slideFilter(inputTree, options) {
	if (!(this instanceof slideFilter)) {
		return new slideFilter(inputTree, options);
	}

	this.inputTree = inputTree;
}

function renderSection(content) {
  var lines = content.trim().split("\n");
  var meta = "";
  if (lines[0].indexOf('!') === 0) {
    meta = lines[0].substr(1,lines[0].length);
    lines.splice(0,1);
  }
  content = lines.join("\n").trim();
  return "
\n" + markdown(content) + "\n
\n\n";
}

slideFilter.prototype = Object.create(Filter.prototype);
slideFilter.prototype.constructor = slideFilter;

slideFilter.prototype.extensions = ['md'];
slideFilter.prototype.targetExtension = 'html';

slideFilter.prototype.processString = function (str) {
  var deck = yamlFront.loadFront(str);
  var sections = deck.__content.split(SECTION_DELIMITER);

  deck.theme = deck.theme || 'default';
  if (deck.theme.indexOf('.css') < 0) {
    deck.theme = "/bower_components/reveal.js/css/theme/" + deck.theme + ".css";
  }
  deck.title = deck.title || "Presentation Deck";

  for(var i in sections) {
    sections[i] = sections[i].trim();
    if (sections[i].match(SUBSECTION_DELIMITER)) {
      sections[i] = sections[i].split(SUBSECTION_DELIMITER);
      for (var j in sections[i]) {
        sections[i][j].trim();
      }
    }
  }

  deck.content = "";

  sections.forEach(function(section) {
    if (typeof section === 'object') {
      deck.content += "
\n";
      section.forEach(function(subsection) {
        deck.content += "  " + renderSection(subsection);
      });
      deck.content += "
\n\n";
    } else {
      deck.content += renderSection(section);
    }
  });

  return render(deck);
};

module.exports = slideFilter;


text:
/**
 * @file /kobuki_node/src/node/odometry.cpp
 *
 * @brief File comment
 *
 * File comment
 *
 **/

/*****************************************************************************
** Includes
*****************************************************************************/

#include "../../include/kobuki_node/odometry.hpp"

/*****************************************************************************
** Namespaces
*****************************************************************************/

namespace kobuki {

/*****************************************************************************
** Implementation
*****************************************************************************/

Odometry::Odometry () :
  odom_frame("odom"),
  base_frame("base_footprint"),
  use_imu_heading(true),
  publish_tf(true)
{};

void Odometry::init(ros::NodeHandle& nh, const std::string& name) {
  double timeout;
  nh.param("cmd_vel_timeout", timeout, 0.6);
  cmd_vel_timeout.fromSec(timeout);
  ROS_INFO_STREAM("Kobuki : Velocity commands timeout: " << cmd_vel_timeout << " seconds [" << name << "].");

  if (!nh.getParam("odom_frame", odom_frame)) {
    ROS_WARN_STREAM("Kobuki : no param server setting for odom_frame, using default [" << odom_frame << "][" << name << "].");
  } else {
    ROS_INFO_STREAM("Kobuki : using odom_frame [" << odom_frame << "][" << name << "].");
  }

  if (!nh.getParam("base_frame", base_frame)) {
    ROS_WARN_STREAM("Kobuki : no param server setting for base_frame, using default [" << base_frame << "][" << name << "].");
  } else {
    ROS_INFO_STREAM("Kobuki : using base_frame [" << base_frame << "][" << name << "].");
  }

  if (!nh.getParam("publish_tf", publish_tf)) {
    ROS_WARN_STREAM("Kobuki : no param server setting for publish_tf, using default [" << publish_tf << "][" << name << "].");
  } else {
    if ( publish_tf ) {
      ROS_INFO_STREAM("Kobuki : publishing transforms [" << name << "].");
    } else {
      ROS_INFO_STREAM("Kobuki : not publishing transforms (see robot_pose_ekf) [" << name << "].");
    }
  }

  if (!nh.getParam("use_imu_heading", use_imu_heading)) {
    ROS_WARN_STREAM("Kobuki : no param server setting for use_imu_heading, using default [" << use_imu_heading << "][" << name << "].");
  } else {
    if ( use_imu_heading ) {
      ROS_INFO_STREAM("Kobuki : using imu data for heading [" << name << "].");
    } else {
      ROS_INFO_STREAM("Kobuki : using encoders for heading (see robot_pose_ekf) [" << name << "].");
    }
  }

  odom_trans.header.frame_id = odom_frame;
  odom_trans.child_frame_id = base_frame;

  pose.setIdentity();

  odom_publisher = nh.advertise<nav_msgs::Odometry>("odom", 50); // topic name and queue size
}

bool Odometry::commandTimeout() const {
  if ( (!last_cmd_time.isZero()) && ((ros::Time::now() - last_cmd_time) > cmd_vel_timeout) ) {
    return true;
  } else {
    return false;
  }
}

void Odometry::update(const ecl::LegacyPose2D<double> &pose_update, ecl::linear_algebra::Vector3d &pose_update_rates,
                      double imu_heading, double imu_angular_velocity) {
  pose *= pose_update;

  if (use_imu_heading == true) {
    // Overwite with gyro heading data
    pose.heading(imu_heading);
    pose_update_rates[2] = imu_angular_velocity;
  }

  //since all ros tf odometry is 6DOF we'll need a quaternion created from yaw
  geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(pose.heading());

  if ( ros::ok() ) {
    publishTransform(odom_quat);
    publishOdometry(odom_quat, pose_update_rates);
  }
}

/*****************************************************************************
** Private Implementation
*****************************************************************************/

void Odometry::publishTransform(const geometry_msgs::Quaternion &odom_quat)
{
  if (publish_tf == false)
    return;

  odom_trans.header.stamp = ros::Time::now();
  odom_trans.transform.translation.x = pose.x();
  odom_trans.transform.translation.y = pose.y();
  odom_trans.transform.translation.z = 0.0;
  odom_trans.transform.rotation = odom_quat;
  odom_broadcaster.sendTransform(odom_trans);
}

void Odometry::publishOdometry(const geometry_msgs::Quaternion &odom_quat,
                               const ecl::linear_algebra::Vector3d &pose_update_rates)
{
  // Publish as shared pointer to leverage the nodelets' zero-copy pub/sub feature
  nav_msgs::OdometryPtr odom(new nav_msgs::Odometry);

  // Header
  odom->header.stamp = ros::Time::now();
  odom->header.frame_id = odom_frame;
  odom->child_frame_id = base_frame;

  // Position
  odom->pose.pose.position.x = pose.x();
  odom->pose.pose.position.y = pose.y();
  odom->pose.pose.position.z = 0.0;
  odom->pose.pose.orientation = odom_quat;

  // Velocity
  odom->twist.twist.linear.x = pose_update_rates[0];
  odom->twist.twist.linear.y = pose_update_rates[1];
  odom->twist.twist.angular.z = pose_update_rates[2];

  // Pose covariance (required by robot_pose_ekf) TODO: publish realistic values
  // Odometry yaw covariance must be much bigger than the covariance provided
  // by the imu, as the later takes much better measures
  odom->pose.covariance[0]  = 0.1;
  odom->pose.covariance[7]  = 0.1;
  odom->pose.covariance[35] = use_imu_heading ? 0.05 : 0.2;

  odom->pose.covariance[14] = 1e10; // set a non-zero covariance on unused
  odom->pose.covariance[21] = 1e10; // dimensions (z, pitch and roll); this
  odom->pose.covariance[28] = 1e10; // is a requirement of robot_pose_ekf

  odom_publisher.publish(odom);
}

} // namespace kobuki


text:
[![Build Status](https://travis-ci.org/bripkens/json-template-generator.svg?branch=master)](https://travis-ci.org/bripkens/json-template-generator)
![Dependency Status](https://david-dm.org/bripkens/json-template-generator.png)

[![browser support](https://ci.testling.com/bripkens/json-template-generator.png)
](https://ci.testling.com/bripkens/json-template-generator)

JSON schema can be used to validate input and to document JSON-consuming APIs.
The `json-schenma-generator` aims to generate JavaScript objects which match a
provided JSON schema. These JavaScript objects can be used to provide
users of API exploration tools such as
[Swagger](https://helloreverb.com/developers/swagger) and
[RAML](http://raml.org/) with request body samples.

See the following example which shows a RAML console integration. Note the
selected `application/json` content type, the
*Prefill with schema based template* link and the body input field which has
been filled out with the help of `json-template-generator`.
![Documentation of a very simple RAML API endpoing](raml-example.png)

## Installation

 - Bower: `bower install --save bripkens/json-template-generator`
 - Node / NPM: `npm install --save bripkens/json-template-generator`
 - Download:
   - [Development](https://raw.githubusercontent.com/bripkens/json-template-generator/master/dist/json-template-generator.js)
   - [Production](https://raw.githubusercontent.com/bripkens/json-template-generator/master/dist/json-template-generator.min.js)

## Usage

You can generally run `json-template-generator` in both a browser and Node.js
context. To do so you can access the global `jsonTemplateGenerator` variable
or `require('json-template-generator')`. Now you simply need to call the
function with a JSON schema in order to create a template from this schema.

```
var template = jsonTemplateGenerator({
  'title': 'Example Schema',
  'type': 'object',
  'properties': {
    'firstName': {
      'type': 'string'
    },
    'lastName': {
      'type': 'string'
    },
    'age': {
      'description': 'Age in years',
      'type': 'integer',
      'minimum': 0
    }
  },
  'required': ['firstName', 'lastName']
});

// Results in the following object:
{
  'firstName': 'TODO',
  'lastName': 'TODO',
  'age': 0
}
```

Further examples can be seen in the
[tests](https://github.com/bripkens/json-template-generator/blob/master/test/_test.js).

## Known Limitations

 - validation rules are not taken into account
 - JSON references (`$ref`) are not followed

## Executing the tests

```
npm install -g gulp testling

# Run unit tests in a node context
gulp

# Run tests in a browser context
testling
```

## License (MIT)

    The MIT License

    Copyright (c) 2014 Ben Ripkens http://bripkens.de

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.


text:
import java.util.ArrayList;

public class Definition {

  private static ArrayList<Definition> instances = new ArrayList<Definition>();

  private String mMeaning;
  private int mId;

  public Definition(String meaning) {
    mMeaning = meaning;
    instances.add(this);
    mId = instances.size();
  }

  public String getMeaning() {
    return mMeaning;
  }

  public int getId() {
    return mId;
  }

  public static ArrayList<Definition> all() {
    return instances;
  }

  public static Definition find(int id) {
    try {
      return instances.get(id-1);
    } catch (IndexOutOfBoundsException exception) {
      return null;
    }
  }

  public static void clear() {
    instances.clear();
  }
}


text:
DBFILE="$HOME/public_html/pol2rna/browser/database.sqlite"

rm -f "$DBFILE"

#    python insert_supplementary_data.py -t 0 -f "$f" -c 2 --tf="$reg" database.sqlite "ischip"

SUPPFILE="results/pol2max_and_meddelays_final.txt"
SUPPFILE2="../R/gene_structures.txt"

FIGNAME_POL2="http://www.cs.helsinki.fi/u/ahonkela/pol2rna/hmc_plots/\${probe_name}_hmc_final.png"

ORIGRESULTFILE="results/hmc_results_to_browser_final.txt"
GENEFILE="../R/analysed_genes.txt"
RESULTFILE="results/hmc_results_to_browser_final.filtered.txt"
FIGNAME=$FIGNAME_POL
REGNAME="pol2"

grep -f $GENEFILE $ORIGRESULTFILE > $RESULTFILE

insert_results.py -f $RESULTFILE --log-likelihood-column=2 "$DBFILE" "pol2rnaseq" "delay 2.5% quantile" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=3 "$DBFILE" "pol2rnaseq" "delay 25% quantile" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=4 "$DBFILE" "pol2rnaseq" "delay 50% quantile" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=5 "$DBFILE" "pol2rnaseq" "delay 75% quantile" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=6 "$DBFILE" "pol2rnaseq" "delay 97.5% quantile" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=7 "$DBFILE" "pol2rnaseq" "D index" "$REGNAME"
insert_results.py -f $RESULTFILE --log-likelihood-column=8 "$DBFILE" "pol2rnaseq" "delay IQR" "$REGNAME"
#insert_results.py -f "$SUPPFILE" --log-likelihood-column=5 "$DBFILE" "pol2rnaseq" "corr" "$REGNAME"
insert_results.py -f "$SUPPFILE" --log-likelihood-column=3 "$DBFILE" "pol2rnaseq" "pol-II peak time" "$REGNAME"
insert_results.py -f "$SUPPFILE2" --log-likelihood-column=2 "$DBFILE" "pol2rnaseq" "max pre-mRNA length" "$REGNAME"
insert_results.py -f "$SUPPFILE2" --log-likelihood-column=3 "$DBFILE" "pol2rnaseq" "last intron proportion" "$REGNAME"
insert_figures.py -d ',' "$DBFILE" "pol-II peak time" "$REGNAME" "pol2rnaseq" <<EOF
http://www.cs.helsinki.fi/u/ahonkela/pol2rna/hmc_plots/\${probe_name}_hmc_final.png, Pol II model, , 2
http://www.cs.helsinki.fi/u/ahonkela/pol2rna/premrna_plots/\${probe_name}_premrna.png, pre-mRNA data, , 1
EOF

insert_aliases.py -f $HOME/projects/pol2rnaseq/data/ensembl68_aliases.txt "$DBFILE" "HGNC" "pol2rnaseq"

chmod 444 "$DBFILE"


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Functions and function expressions</title>
</head>
<body>
    <script src="task-1.js"></script>
    <script src="task-2.js"></script>
</body>
</html>


text:
Public Class Timeout
    Inherits AspectAttribute

    Private dueTime As Integer
    Private timercb As TimerCallback

    Public Sub New(ByVal dueTime As Integer)
        Me.dueTime = dueTime
        Me.timercb = New TimerCallback(AddressOf Me.TimerCallback)
    End Sub

    <IncludeAll(), [Call](Advice.AfterThrowing)> _
    Public Function Fail(Of T)(<JPContext()> ByVal ctx As Context, <JPException()> ByVal ex As Exception, ByVal ParamArray args As Object()) As T
        If TypeOf ex Is ThreadAbortException Then
            Thread.ResetAbort()
            Throw New TimeoutException
        End If
        Throw ex
    End Function

    <IncludeAll(), [Call](Advice.AfterReturning)> _
    Public Sub Finish(<JPContext()> ByVal ctx As Context, ByVal ParamArray args As Object())
        DirectCast(ctx.Tag, Timer).Dispose()
    End Sub

    <IncludeAll(), [Call](Advice.Before)> _
    Public Sub InitTimer(<JPContext()> ByVal ctx As Context, ByVal ParamArray args As Object())
        ctx.Tag = New Timer(Me.timercb, Thread.CurrentThread, Me.dueTime, -1)
    End Sub

    Private Sub TimerCallback(ByVal thread As Object)
        DirectCast(thread, Thread).Abort()
    End Sub

End Class


text:
package com.amazonaws.services.alexaforbusiness.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.alexaforbusiness.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DeviceDataMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeviceDataMarshaller {

    private static final MarshallingInfo<String> DEVICEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("DeviceArn").build();
    private static final MarshallingInfo<String> DEVICESERIALNUMBER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceSerialNumber").build();
    private static final MarshallingInfo<String> DEVICETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceType").build();
    private static final MarshallingInfo<String> DEVICENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceName").build();
    private static final MarshallingInfo<String> SOFTWAREVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SoftwareVersion").build();
    private static final MarshallingInfo<String> MACADDRESS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MacAddress").build();
    private static final MarshallingInfo<String> DEVICESTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceStatus").build();
    private static final MarshallingInfo<String> NETWORKPROFILEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NetworkProfileArn").build();
    private static final MarshallingInfo<String> NETWORKPROFILENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NetworkProfileName").build();
    private static final MarshallingInfo<String> ROOMARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("RoomArn").build();
    private static final MarshallingInfo<String> ROOMNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("RoomName").build();
    private static final MarshallingInfo<StructuredPojo> DEVICESTATUSINFO_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeviceStatusInfo").build();

    private static final DeviceDataMarshaller instance = new DeviceDataMarshaller();

    public static DeviceDataMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DeviceData deviceData, ProtocolMarshaller protocolMarshaller) {

        if (deviceData == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(deviceData.getDeviceArn(), DEVICEARN_BINDING);
            protocolMarshaller.marshall(deviceData.getDeviceSerialNumber(), DEVICESERIALNUMBER_BINDING);
            protocolMarshaller.marshall(deviceData.getDeviceType(), DEVICETYPE_BINDING);
            protocolMarshaller.marshall(deviceData.getDeviceName(), DEVICENAME_BINDING);
            protocolMarshaller.marshall(deviceData.getSoftwareVersion(), SOFTWAREVERSION_BINDING);
            protocolMarshaller.marshall(deviceData.getMacAddress(), MACADDRESS_BINDING);
            protocolMarshaller.marshall(deviceData.getDeviceStatus(), DEVICESTATUS_BINDING);
            protocolMarshaller.marshall(deviceData.getNetworkProfileArn(), NETWORKPROFILEARN_BINDING);
            protocolMarshaller.marshall(deviceData.getNetworkProfileName(), NETWORKPROFILENAME_BINDING);
            protocolMarshaller.marshall(deviceData.getRoomArn(), ROOMARN_BINDING);
            protocolMarshaller.marshall(deviceData.getRoomName(), ROOMNAME_BINDING);
            protocolMarshaller.marshall(deviceData.getDeviceStatusInfo(), DEVICESTATUSINFO_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
Returns path to globally installed package.

## System requirements
In order to use this package you need:
 - Node.js 4.0.0 or later
 - npm 2.0.0 or later added to your PATH environment variable (you should be able to execute `npm --version` from your default terminal).

## Usage
The module has a single public method called `getPath`. It requires at least one argument - the name of the globally installed package that you need.
In case the package is not installed, `getPath` will return null.
`getPath` will throw error in case the OS is **NOT** supported. Supported OS are:
 - Windows (`process.platform` returns `win32`)
 - macOS (`process.platform` returns `darwin`)
 - Linux (`process.platform` returns `linux`)

### Using getPath with single argument
Example:
```
let pathToPackage = require("global-modules-path").getPath("packageName");
```

The method returns the path to globally installed package or null. The code constructs the path based on the result of `npm config get prefix` and checks if the package exists.

### Using getPath with package name and executable name.
Example:
```
let pathToPackage = require("global-modules-path").getPath("packageName", "executableName");
```
The method returns the path to globally installed package or null. The code constructs the path based on the result of `npm config get prefix` and checks if the package exists. In case the package cannot be found in this way, the `executableName` is used to determine if the package is globally installed.
- On Windows the package spawns `where executableName` command and parses the result.
- On macOS and Linux the package spawns `ls -l executableName` and `which executableName` and parses the results.

>NOTE: In some cases the executable name is not the same as the package name.


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Users::Command::Account::Group::Save;

### Command module to save group details edited by the logged in admin
### @author hr5

use strict;
use warnings;

use EnsEMBL::Users::Messages qw(MESSAGE_GROUP_NOT_FOUND);

use parent qw(EnsEMBL::Users::Command::Account);

sub csrf_safe_process {
  my $self        = shift;
  my $object      = $self->object;
  my $hub         = $self->hub;
  my $r_user      = $hub->user->rose_object;
  my $group_id    = $hub->param('id');

  # if no id given, it's a request to create a new group
  my $membership  = $group_id
    ? $object->fetch_accessible_membership_for_user($r_user, $group_id)
    : $r_user->create_new_membership_with_group
    or return $self->ajax_redirect($hub->url({'action' => 'Groups', 'function' => '', 'err' => MESSAGE_GROUP_NOT_FOUND}));

  my $group       = $membership->group;
  my $new_values  = { map {$_ => $hub->param($_)} $hub->param }; # get all the new values from CGI

  # changes only admin can make
  if ($membership->level eq 'administrator') {

    # original values
    my $group_columns   = $group_id && $group->status eq 'inactive' ? [ qw(status) ] : [ qw(name type blurb status) ]; # for an inactive group, only status can be changed
    my $original_values = $group_id ? { map { $_ => $group->$_ } @$group_columns } : {};

    # default values if creating a new group
    unless ($group_id) {
      $new_values->{'name'}   ||= sprintf q(%s's group), $r_user->name;
      $new_values->{'blurb'}  ||= sprintf q(%s's group), $r_user->name;
      $new_values->{'type'}   ||= 'restricted';
      $new_values->{'status'}   = 'active';
    }

    # validation
    $new_values->{'type'}   = $new_values->{'type'}   && $new_values->{'type'}    =~ /^(open|private)$/ ? $new_values->{'type'} : 'restricted'  if exists $new_values->{'type'};
    $new_values->{'status'} = $new_values->{'status'} && $new_values->{'status'}  eq 'inactive'         ? 'inactive'            : 'active'      if exists $new_values->{'status'};

    # only change the column values if new values exist (ie if a GET param is set for that column name)
    exists $new_values->{$_} and $group->$_($new_values->{$_}) for @$group_columns;
    $group->save('user' => $r_user);

    # do we need to notify anyone about the changes?
    $self->send_group_editing_notification_email($group, $original_values, { map { $_ => $group->$_ } @$group_columns }) if $group_id;

    # Changes to membership object
    exists $new_values->{$_} and $membership->$_($new_values->{$_}) for qw(notify_join notify_edit notify_share);

  # changes any member can make
  } else {
    $membership->notify_share($new_values->{'notify_share'}) if exists $new_values->{'notify_share'};
  }

  $membership->group_id($group->group_id);
  $membership->save('user' => $r_user);

  return $self->ajax_redirect($hub->url({'action' => 'Groups', 'function' => 'View', 'id' => $group->group_id}));
}

1;