text:
Ansible I: Simplest Example
===========================

Prerequisite
------------

In order to conduct this lesson:

-   You can install Ubuntu 16.04 virtual machine on VirtualBox

-   You can install software packages via 'apt-get' tool in Ubuntu
    virtual host

-   You already reserved a virtual cluster (with at least 1 virtual
    machine in it) on some cloud. OR you can use VMs installed in
    VirtualBox instead.

-   You set up SSH credentials and can login to your virtual machines.

What can you do with Ansible?
-----------------------------

Humans do maintenance and configurations on computers. Essentially, we
specify a list of operations and a list of target machines where the
operations apply to. After defining these two critical lists, the
creative works are done, and the rest labour can be automated. And this
is what Ansible is used for.

Let us develop a sample from scratch, based on this paradigm.

A sample use case
-----------------

In this example, we are going to use Ansible to install Apache server on
our VMs.

-   install Ansible tool on your machine first

    $ sudo apt-get update
    $ sudo apt-get install ansible

-   prepare a working environment for your Ansible

<!-- -->

    $ mkdir}ansible-apache
    $ cd ansible-apache

-   next, we are going to create a local configuration file for Ansible.

When you execute Ansible within this folder, this local configuration
file is always going to overwrite a system level Ansible configuration.
It is in general beneficial to keep custom configurations locally unless
you absolutely believe it should be applied system wide. Create a file
'ansible.cfg' in this folder, and fill:

    [defaults]
    hostfile = hosts

This local configuration file simple tells that the target machines'
names are given in a file named 'hosts'

In your assignments, we choose to use `inventory` instead of
`ansible.cfg`. More details will be given when we introduce
`ansible-galaxy` in following chapters. At this moment, getting yourself
familiar with some concepts of configuring the Ansible environment is
good enough.

-   specify hosts in the file

You should have accesses to all VMs listed in this file as part of our
prerequisites. Create and edit file 'hosts':

    [apache]
    <server_ip> ansible_ssh_user=<server_username>

The name 'apache' in the brackets defines the server group name. We will
use this name to refer to all server items in this group next. Fill in
IP addresses of the virtual machines you launched in your VirtualBox and
fire up these VMs in you VirtualBox.

-   compose a playbook

A playbook tells Ansible what to do. it uses YAML Markup syntax. Create
and edit a file with a proper name e.g. apache.yml as follow:

    ---
    - hosts: apache #comment: apache is the group name we just defined
      become: yes #comment: this operation needs privilege access
      tasks:
        - name: install apache2 # text description
          apt: name=apache2 update_cache=yes state=latest

This block defines the target VMs and operations(tasks) need to apply.
you may wonder what 'apt' means. here comes the concept of Ansible
modules in next paragraph.

The concept of modules
----------------------

'apt' is the module used in our sample playbook. it installs packages on
Ubuntu for us.

Ansible relies on various kinds of modules to fulfil tasks on the remote
servers. These modules are developed for particular tasks and take in
related arguments. For instance, when we use 'apt' module, we certainly
need to tell which package we intend to install. That is why we provide
a value for the 'name' argument.

Run you playbook
----------------

In the same folder, execute

    ansible-playbook apache.yml --ask-sudo-pass

After a successful run, open a browser and fill in your server IP. you
should se a 'It works!' Apache2 Ubuntu default page. Make sure the
security policy on your cloud opens port 80 to let the HTTP traffic go
through.

Ansible playbook can have more complex and fancy structure and syntaxes.
Go explore! this sample is based on:
<https://www.digitalocean.com/community/tutorials/how-to-configure-apache-using-ansible-on-ubuntu-14-04>

We are going to offer an advanced Ansible in next chapter.

Ansible II: Roles
=================

In this example, we are going to install R package onto your cloud VMs.
R is a useful statistic programing language commonly used in many
scientific and statistics computing projects, maybe also the one you
chose for this class.

In addition to last basic example, we are going to illustrate the
concept of Ansible Roles, install source code through Github, and make
use of variables. These are key features you will find useful in your
project deployments.

We are going to use a top-down fashion in this example. We first start
from a playbook that is already good to go. You can execute this
playbook (don't do it yet) to get R installed in your remote hosts. We
then further complicate this concise playbook by introducing
functionalities to do the same tasks but in different ways. Although
these detours are not necessary in this simply case, it helps you grasp
the power of Ansible and ease your life when they are needed in your
real projects.

Prerequisite
------------

-   Finished Ansible Lesson I

-   Have VMs reserved on cloud and SSH Key setup

A completed playbook
--------------------

From the earlier example, we already can compose a playbook
'example.yml' that install a software package, for example:

    ---
    - hosts: R_hosts
      become: yes
      tasks:
        - name: install the R package
          apt: name=r-base update_cache=yes state=latest

the hosts are defined in a file 'hosts', which we configured in
'ansible.cfg':

    [R_hosts]
    <cloud_server_ip> ansible_ssh_user=<cloud_server_username>

In your assignments, we choose to use `inventory` instead of
`ansible.cfg`. More details will be given when we introduce
`ansible-galaxy` in following chapters. At this moment, getting yourself
familiar with some concepts of configuring the Ansible environment is
good enough.

This should get the installation job done. But we are going to extend it
via new features next.

Introducing Roles
-----------------

Role is an important concept used very often in large Ansible projects.
You divide a series of tasks into different groups. Each group
corresponds to certain role of the whole project.

For example, if your project is to deploy a web site, you may need to
install the back end database, the web server that responses HTTP
requests and the web application itself. They are three different roles
and should carry out their own installation and configuration tasks.

Even though we only need to install the R package in this example, we
can still do it by defining a role 'r'. Modify your 'example.yml' to be:

    ---
    - hosts: R_hosts

      roles:
        - r

and create directory structure in your top project directory:

    $ mkdir -p roles/r/tasks
    $ touch roles/r/tasks/main.yml

edit this 'main.yml' to be:

    ---
    - name: install the R package
      apt: name=r-base update_cache=yes state=latest
      become: yes

You probably already get the point. We take the 'tasks' section out of
the one-for-all example.yml and re-organize them into roles. Each role
specified in example.yml should have its own directory under roles/ and
the tasks need be done by this role is listed in a file 'tasks/main.yml'
as above.

Install source code from Github
-------------------------------

Although R can be installed through the OS package manager (apt-get
etc.), the software used in your projects may not. Many research
projects are available by Git instead. Here we are going to show you how
to install packages from their Git repositories. Instead of directly
executing the module 'apt', we pretend Ubuntu does not provide this
package and you have to find it on Git. The source code of R can be
found at <https://github.com/wch/r-source.git>. We are going to clone it
to a remote VM's hard drive, build the package and install the binary
there.

To do so, we need a few new Ansible modules. You may remember from last
example that Ansible modules assist us to do various kinds of jobs when
fed correct arguments. No surprise, Ansible has a module 'git' to take
care of git-related works, and a 'command' module to run shell commands.
Let's modify 'roles/r/tasks/main.yml' to be:

    ---
    - name: get R package source
      git:
        repo: https://github.com/wch/r-source.git
        dest: /tmp/R

    - name: build and install R
      become: yes
      command: chdir=/tmp/R "{{ item }}"
      with_items:
        - ./configure
        - make
        - make install

The role 'r' carries out its two tasks now. One to clone the R source
code into /tmp/R, the other uses a series of shell commands to build and
install the packages.

Note that the commands executed by the second task may not be available
on a fresh VM image. But the point of this example is to show an
alternative way to install packages, so we conveniently assume
conditions are all met.

Using variables in a separate file
----------------------------------

We typed several string constants in our Ansible scripts so far. In
general, it is a good practice to give these values names and use them
by referring to their names. This way, you complex Ansible project can
be less error prone. Create a file in the same directory, and name it
'vars.yml':

    ---
    repository: https://github.com/wch/r-source.git
    tmp: /tmp/R

Accordingly, we will update our 'example.yml':

    ---
    - hosts: R_hosts
      vars_files:
        - vars.yml
      roles:
        - r

As shown, we specify a 'vars\_files' telling the script that the file
'vars.yml' is going to supply variable values, whose keys are denoted by
Double curly brackets like in 'roles/r/tasks/main.yml':

    ---
    - name: get R package source
      git:
        repo: "{{ repository }}"
        dest: "{{ tmp }}"

    - name: build and install R
      become: yes
      command: chdir="{{ tmp }}" "{{ item }}"
      with_items:
        - ./configure
        - make
        - make install

Summarize
---------

Now, just edit the 'hosts' file with your target VMs' IP addresses and
execute the playbook.

You should be able to extend the Ansible playbook for your project.
Configuration tools like Ansible are important components to master the
cloud environment. There is much to explore and it's worth it.

Ansible III: Ansible Galaxy
===========================

By finishing the first two chapters, you should be able to compose
Ansible projects to install, configure or do other maintenances on your
software packages. We introduced the powerful component `Roles` in the
previous chapters, and emphasized the concepts of modularize and
re-usability. With these preparations, we are ready to start working on
Ansible Galaxy.

Think Ansible Galaxy as of an marketplace, where developers can share
Ansible Roles to complete their system administration tasks. Roles
exchanged in Ansible Galaxy community need to follow common conventions
so that all participants know what to expect. We will illustrate details
in this chapter.

It is good to follow the Ansible Galaxy standard during your development
assignment as much as possible, however, you will submit your
assignments to this class's repository not the global Galaxy community.

Ansible Galaxy helloworld
-------------------------

Let us start with a simplest case: We will build an Ansible Galaxy
project. This project will install the Emacs software package on your
localhost as the target host. It is a "helloworld" project only meant to
get us familiar with Ansible Galaxy project structures.

### create the directory

Setup your submission directory after you clone and rebased with
<https://github.com/cloudmesh/sp17-i524>:

    $ git rebase upstream/master
    $ ./setup galaxy <your HID>

It will create a folder named after your HID inside directory galaxy/.
Your Galaxy related assignments will be completed and submitted there.
Go ahead and create files `README.md`, `playbook.yml`, `inventory` and a
subdirectory `roles/` then. playbook.yml is your project playbook. It
should perform the Emacs installation task by executing the
corresponding role you will develop in the folder 'roles/'. The only
difference is that we will construct the role with the help of
ansible-galaxy this time.

Now, let ansible-galaxy initialize the directory structure for you:

    $ cd roles
    $ ansible-galaxy init <to-be-created-role-name>

The naming convention is to concatenate your name and the role name by a
dot. Here is how it looks like:

![image](/images/ansible-galaxy-init-structure.png)

### fill in information

Let us fill in information to our project. There are several `main.yml`
files in different folders, and we will illustrate their usages.

defaults and vars:

:   These folders should hold variables key-value pairs for your
    playbook scripts. We will leave them empty in this example.

files:

:   This folder is for files need to be copied to the target hosts. Data
    files or configuration files can be specified if needed. We will
    leave it empty too.

templates:

:   Similar missions to files/, templates is allocated for template
    files. Keep empty for a simple Emacs installation.

handlers:

:   This is reserved for services running on target hosts. For example,
    to restart a service under certain circumstance.

tasks:

> This file is the actual script for all tasks. You can use the role you
> built previously for Emacs installation here:
>
>     ---
>     - name: install Emacs on Ubuntu 16.04
>       become: yes
>       package: name=emacs state=present

meta:

:   Provide necessary metatdata for our Ansible Galaxy project for
    shipping:

        ---
        galaxy_info:
          author: <you name>
          description: emacs installation on Ubuntu 16.04
          license:
            - MIT
          min_ansible_version: 2.0
          platforms:
            - name: Ubuntu
              versions:
                - xenial
          galaxy_tags:
            - development

        dependencies: []

### Test it out

You have your Ansible Galaxy role ready now. To test it as a user, go to
your HID directory and edit the other two files `inventory` and
`playbook.yml`, which are already generated for you in directory `tests`
by the script:

    $ ansible-playbook -i ./hosts playbook.yml

After running this playbook, you should have Emacs installed on
localhost.

A Complete Ansible Galaxy Project
---------------------------------

We are going to use ansible-galaxy to setup a sample project. This
sample project will:

-   use a cloud cluster with multiple VMs

-   deploy Apache Spark on this cluster

-   install a particular HPC application

-   prepare raw data for this cluster to process

-   run the experiment and collect results

Ansible: Write a Playbooks for MongoDB
======================================

Ansible Playbooks are automated scripts written in YAML data format.
Instead of using manual commands to setup multiple remote machines, you
can utilize Ansible Playbooks to configure your entire systems. YAML
syntax is easy to read and express the data structure of certain Ansible
functions. You simply write some tasks, for example, installing
software, configuring default settings, and starting the software, in a
Ansible Playbook. With a few examples in this tutorial, you will
understand how it works and how to write your own Playbooks.

There are also several examples of using Ansible [Playbooks](http://docs.ansible.com/playbooks.html) from the official site. It covers

:   from basic usage of Ansible Playbooks to advanced usage such as
    applying patches and updates with different roles and groups.

Tutorial: Writing Ansible Playbook
----------------------------------

In this tutorial, we are going to write a basic playbook of Ansible
software. Keep in mind that `Ansible` is a main program and `playbook`
is a template that you would like to use. You may have several playbooks
in your Ansible.

### First playbook for MongoDB Installation

As a first example, we are going to write a playbook which installs
MongoDB server. It includes the following tasks:

-   Import the public key used by the package management system

-   Create a list file for MongoDB

-   Reload local package database

-   Install the MongoDB packages

-   Start MongoDB

This tutorial is based on the manual installation of MongoDB from the
official site:
<http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/*>

We also assume that we install MongoDB on Ubuntu 15.10.

### Enabling Root SSH Access

Some setups of managed nodes may not allow you to log in as root. As
this may be problematic later, let us create a playbook to resolve this.
Create a `enable-root-access.yaml` file with the following contents:

    ---
    - hosts: ansible-test
      remote_user: ubuntu
      tasks:
        - name: Enable root login
          shell: sudo cp ~/.ssh/authorized_keys /root/.ssh/

Explanation:

-   `hosts` specifies the name of a group of machines in the inventory

-   `remote_user` specifies the username on the managed nodes to log in
    as

-   `tasks` is a list of tasks to accomplish having a `name` (a
    description) and modules to execute. In this case we use the `shell`
    module.

We can run this playbook like so:

    $ ansible-playbook -i inventory.txt -c ssh enable-root-access.yaml

    PLAY [ansible-test] ***********************************************************

    GATHERING FACTS ***************************************************************
    ok: [10.23.2.105]
    ok: [10.23.2.104]

    TASK: [Enable root login] *****************************************************
    changed: [10.23.2.104]
    changed: [10.23.2.105]

    PLAY RECAP ********************************************************************
    10.23.2.104                : ok=2    changed=1    unreachable=0    failed=0
    10.23.2.105                : ok=2    changed=1    unreachable=0    failed=0

### Hosts and Users

First step is choosing hosts to install MongoDB and a user account to
run commands (tasks). We start with the following lines in the example
filename of `mongodb.yaml`:

    ---
    - hosts: ansible-test
      remote_user: root
      become: yes

In a previous tutorial, we setup two machines with `ansible-test` group
name. This tutorial uses that two machines for MongoDB installation.
Also, we use `root` account to complete Ansible tasks.

Indentation is important in YAML format. Do not ignore spaces start

:   with in each line.

### Tasks

A list of tasks contains commands or configurations to be executed on
remote machines in a sequential order. Each task comes with a `name` and
a `module` to run your command or configuration. You provide a
description of your task in `name` section and choose a `module` for
your task. There are several modules that you can use, for example,
`shell` module simply executes a command without considering a return
value. You may use `apt` or `yum` module which is one of the packaging
modules to install software. You can find an entire list of modules
here: <http://docs.ansible.com/list_of_all_modules.html>

### Module apt\_key: add repository keys

We need to import the MongoDB public GPG Key. This is going to be a
first task in our playbook.:

    tasks:
      - name: Import the public key used by the package management system
        apt_key: keyserver=hkp://keyserver.ubuntu.com:80 id=7F0CEB10 state=present

### Module apt\_repository: add repositories

Next add the MongoDB repository to apt:

    - name: Add MongoDB repository
      apt_repository: repo='deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' state=present

### Module apt: install packages

We use `apt` module to install `mongodb-org` package. `notify` action is
added to start `mongod` after the completion of this task. Use the
`update_cache=yes` option to reload the local package database.:

    - name: install mongodb
      apt: pkg=mongodb-org state=latest update_cache=yes
      notify:
      - start mongodb

### Module service: manage services

We use `handlers` here to start or restart services. It is similar to
`tasks` but will run only once.:

    handlers:
      - name: start mongodb
        service: name=mongod state=started

### The Full Playbook

Our first playbook looks like this:

    ---
    - hosts: ansible-test
      remote_user: root
      become: yes
      tasks:
      - name: Import the public key used by the package management system
        apt_key: keyserver=hkp://keyserver.ubuntu.com:80 id=7F0CEB10 state=present
      - name: Add MongoDB repository
        apt_repository: repo='deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' state=present
      - name: install mongodb
        apt: pkg=mongodb-org state=latest update_cache=yes
        notify:
        - start mongodb
      handlers:
        - name: start mongodb
          service: name=mongod state=started

### Running a Playbook

We use `ansible-playbook` command to run our playbook:

    $ ansible-playbook -i inventory.txt -c ssh mongodb.yaml

    PLAY [ansible-test] ***********************************************************

    GATHERING FACTS ***************************************************************
    ok: [10.23.2.104]
    ok: [10.23.2.105]

    TASK: [Import the public key used by the package management system] ***********
    changed: [10.23.2.104]
    changed: [10.23.2.105]

    TASK: [Add MongoDB repository] ************************************************
    changed: [10.23.2.104]
    changed: [10.23.2.105]

    TASK: [install mongodb] *******************************************************
    changed: [10.23.2.104]
    changed: [10.23.2.105]

    NOTIFIED: [start mongodb] *****************************************************
    ok: [10.23.2.105]
    ok: [10.23.2.104]

    PLAY RECAP ********************************************************************
    10.23.2.104                : ok=5    changed=3    unreachable=0    failed=0
    10.23.2.105                : ok=5    changed=3    unreachable=0    failed=0

If you rerun the playbook, you should see that nothing changed:

    $ ansible-playbook -i inventory.txt -c ssh mongodb.yaml

    PLAY [ansible-test] ***********************************************************

    GATHERING FACTS ***************************************************************
    ok: [10.23.2.105]
    ok: [10.23.2.104]

    TASK: [Import the public key used by the package management system] ***********
    ok: [10.23.2.104]
    ok: [10.23.2.105]

    TASK: [Add MongoDB repository] ************************************************
    ok: [10.23.2.104]
    ok: [10.23.2.105]

    TASK: [install mongodb] *******************************************************
    ok: [10.23.2.105]
    ok: [10.23.2.104]

    PLAY RECAP ********************************************************************
    10.23.2.104                : ok=4    changed=0    unreachable=0    failed=0
    10.23.2.105                : ok=4    changed=0    unreachable=0    failed=0

### Sanity Check: Test MongoDB

Let's try to run 'mongo' to enter mongodb shell.:

    $ ssh ubuntu@$IP
    $ mongo
    MongoDB shell version: 2.6.9
    connecting to: test
    Welcome to the MongoDB shell.
    For interactive help, type "help".
    For more comprehensive documentation, see
            http://docs.mongodb.org/
    Questions? Try the support group
            http://groups.google.com/group/mongodb-user
    >

### Terms

-   Module: Ansible library to run or manage services, packages, files
    or commands.

-   Handler: A task for notifier.

-   Task: Ansible job to run a command, check files, or update
    configurations.

-   Playbook: a list of tasks for Ansible nodes. YAML format used.

-   YAML: Human readable generic data serialization.

### Reference

The main tutorial from Ansible is here:
<http://docs.ansible.com/playbooks_intro.html>

You can also find an index of the ansible modules here:
<http://docs.ansible.com/modules_by_category.html>

Ansible Assignment
==================

We have shown a couple of examples of using Ansible tools. Before you
apply it in you final project, we will practice it in this assignment.

Requirements
------------

-   use the `galaxy` directory in the class assignment repository

-   set up the project structure similar to Ansible Galaxy example

-   install MongoDB from the package manager (apt in this class)

-   configure your MongoDB installation to start the service
    automatically

-   use default port and let it serve local client connections only


text:
#ifndef TENSORFLOW_GRAPPLER_GRAPPLER_ITEM_BUILDER_H_
#define TENSORFLOW_GRAPPLER_GRAPPLER_ITEM_BUILDER_H_

#include <memory>
#include <string>
#include "tensorflow/core/grappler/grappler_item.h"

namespace tensorflow {

class MetaGraphDef;

namespace grappler {

struct ItemConfig {
  // If true, ignore all user specified node placement.
  bool ignore_user_placement = true;
  // If true, ignore all user specified colocation attributes.
  bool ignore_colocation = true;
  // Dimension to use if a placeholder node has an _output_shapes attribute with
  // a dimension of -1.
  int placeholder_unknown_output_shape_dim = -1;
};

// Factory method for creating a GrapplerItem from a MetaGraphDef.
// Returns nullptr if the given meta_graph cannot be converted.
std::unique_ptr<GrapplerItem> GrapplerItemFromMetaGraphDef(
    const string& id, const MetaGraphDef& meta_graph, const ItemConfig& cfg);

}  // end namespace grappler
}  // end namespace tensorflow

#endif  // TENSORFLOW_GRAPPLER_GRAPPLER_ITEM_BUILDER_H_

redpajama_set_name: RedPajamaGithub


text:
class CreateNotifications < ActiveRecord::Migration[5.0]
  def change
    create_table :notifications do |t|
      t.integer :user_id
      t.integer :event_type
      t.integer :event_id
      t.integer :status

      t.timestamps

      t.index ["user_id"], name: "index_notifications_on_user_id",  using: :btree
    end
  end
end


text:
namespace _02.Static_Members_And_Namespaces.Interfaces
{
	interface ICollectible
	{
	}
}


text:
#include "src/traced/probes/ftrace/ftrace_print_filter.h"

#include "protos/perfetto/config/ftrace/ftrace_config.gen.h"

#include "test/gtest_and_gmock.h"

namespace perfetto {
namespace {

using perfetto::protos::gen::FtraceConfig;

TEST(FtracePrintFilterTest, EmptyConfigDefaultAllows) {
  FtraceConfig::PrintFilter conf;
  FtracePrintFilter filter(conf);

  EXPECT_TRUE(filter.IsAllowed("word", 4));
}

TEST(FtracePrintFilterTest, OneRuleMatchesAllows) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("w");
  rule->set_allow(true);
  FtracePrintFilter filter(conf);

  EXPECT_TRUE(filter.IsAllowed("word", 4));
}

TEST(FtracePrintFilterTest, OneRuleMatchesDenies) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("w");
  rule->set_allow(false);
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("word", 4));
}

TEST(FtracePrintFilterTest, OneRuleMatchesLongSize) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("w");
  rule->set_allow(false);
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("word", 120));
}

TEST(FtracePrintFilterTest, OneRuleMatchesShortSize) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("w");
  rule->set_allow(false);
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("word", 1));
}

TEST(FtracePrintFilterTest, OneRuleDoesntMatchLongSize) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("verylongprefix");
  rule->set_allow(false);
  FtracePrintFilter filter(conf);

  EXPECT_TRUE(filter.IsAllowed("short", 120));
}

TEST(FtracePrintFilterTest, OneRuleWildcard) {
  FtraceConfig::PrintFilter conf;
  auto* rule = conf.add_rules();
  rule->set_prefix("");
  rule->set_allow(false);
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("anything", 8));
}

TEST(FtracePrintFilterTest, TwoRulesMatchFirst) {
  FtraceConfig::PrintFilter conf;
  {
    auto* rule = conf.add_rules();
    rule->set_prefix("word");
    rule->set_allow(false);
  }
  {
    auto* rule = conf.add_rules();
    rule->set_prefix("doesntmatch");
    rule->set_allow(true);
  }
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("word", 120));
}

TEST(FtracePrintFilterTest, TwoRulesMatchesSecond) {
  FtraceConfig::PrintFilter conf;
  {
    auto* rule = conf.add_rules();
    rule->set_prefix("doesntmatch");
    rule->set_allow(true);
  }
  {
    auto* rule = conf.add_rules();
    rule->set_prefix("word");
    rule->set_allow(false);
  }
  FtracePrintFilter filter(conf);

  EXPECT_FALSE(filter.IsAllowed("word", 120));
}

}  // namespace
}  // namespace perfetto


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

Add an image

          <form class="" method="post" enctype="multipart/form-data">
            {% csrf_token %}

Title{{ form.title }}

Description{{ form.description }}

How Secret?{{ form.published }}

Give'er{{ form.photo }}

            <button type="submit" name="button" value="Submit">Get that Cat on the Internet</button>
          </form>

    {% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using Shape = Microsoft.Office.Interop.PowerPoint.Shape;

namespace PptAlbumGenerator
{
    [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
    internal sealed class ClosureOperationAttribute : Attribute
    {
    }

    internal class Closure
    {
        public Closure(Closure parent)
        {
            Parent = parent;
        }

        public Closure Parent { get; }

        public void NotifyLeavingClosure()
        {
            OnLeavingClosure();
        }

        public T Ancestor<T>() where T : Closure
        {
            return Ancestor<T>(false);
        }

        public T Ancestor<T>(bool errorIfNotFound) where T : Closure
        {
            var c = this.Parent;
            while (c != null)
            {
                var ancestor = c as T;
                if (ancestor != null) return ancestor;
                c = c.Parent;
            }
            if (errorIfNotFound)
                throw new ArgumentException($"在当前作用域找不到{typeof (T)}类型的域。");
            return null;
        }

        public Closure InvokeOperation(string operationName, params string[] operationExpressions)
        {
            var method = GetType().GetMethod(operationName,
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (method == null) throw new ArgumentException($"在{this}中找不到操作"{operationName}"。");
            var arguments = new List<object>();
            var paramInfo = method.GetParameters();
            if (operationExpressions.Length > paramInfo.Length)
                throw new ArgumentException(
                    $"提供了{operationExpressions.Length}个参数,但函数{method}仅需 要{paramInfo.Length}个参数。");
            for (int i = 0; i < paramInfo.Length; i++)
            {
                if (i >= operationExpressions.Length ||
                    string.IsNullOrEmpty(operationExpressions[i]) && paramInfo[i].IsOptional)
                {
                    arguments.Add(Type.Missing);
                }
                else if (paramInfo[i].ParameterType.IsEnum)
                {
                    arguments.Add(Enum.Parse(paramInfo[i].ParameterType, operationExpressions[i], true));
                }
                else
                {
                    arguments.Add(Convert.ChangeType(operationExpressions[i], paramInfo[i].ParameterType));
                }
            }
            var c = (Closure) method.Invoke(this, arguments.ToArray());
            Debug.Assert(c != null);
            return c;
        }

        protected virtual void OnLeavingClosure()
        {

        }
    }

    /// <summary>
    /// 根。
    /// </summary>
    internal class DocumentClosure : Closure
    {
        private float _SlideWidth;
        private float _SlideHeight;

        public Presentation Presentation { get; }

        public Application Application { get; }

        public float SlideWidth => _SlideWidth;

        public float SlideHeight => _SlideHeight;

        public string WorkPath { get; set; }

        public bool IsDebug { get; set; }

        public SlideTransitionPoolClosure SlideTransitionPool { get; }

        private void UpdateCache()
        {
            _SlideWidth = Presentation.PageSetup.SlideWidth;
            _SlideHeight = Presentation.PageSetup.SlideHeight;
        }

        public void Initialize()
        {
            UpdateCache();
        }

        [ClosureOperation]
        public Closure Dir(string path)
        {
            WorkPath = Path.Combine(WorkPath, path);
            return this;
        }

        [ClosureOperation]
        public Closure Debug(bool value)
        {
            IsDebug = value;
            return this;
        }

        [ClosureOperation]
        public Closure Page(string imagePath = "", string primaryText = "")
        {
            var closure = new PageClosure(this, Presentation.Slides.Add(
                Presentation.Slides.Count + 1, PpSlideLayout.ppLayoutBlank));
            if (!string.IsNullOrEmpty(imagePath)) imagePath = Path.Combine(WorkPath, imagePath);
            closure.Initialize(imagePath, primaryText);
            return closure;
        }

        [ClosureOperation]
        public Closure Transitions()
        {
            return SlideTransitionPool;
        }

        public DocumentClosure(Closure parent, Presentation presentation, Application application) : base(parent)
        {
            Presentation = presentation;
            Application = application;
            SlideTransitionPool = new SlideTransitionPoolClosure(this);
            UpdateCache();
        }
    }

    internal enum PrimaryImageAnimation
    {
        None = 0,
        Fit,
        /// <summary>
        /// 视图从右向左,或从下向上。
        /// </summary>
        ScrollNear,
        /// <summary>
        /// 视图从左向右,或从上向下。
        /// </summary>
        ScrollFar,
        Expand,
        Shrink,
        ExpandOrShink,
    }

    internal class PageClosure : Closure
    {
        const float MinImageAnimationDuration = 4; //Minimum

        public Slide Slide { get; }

        public Shape PrimaryImage { get; set; }

        public float PrimaryImageAnimationDuration { get; set; }

        public Shape PrimaryTextBox { get; set; }

        public float PagePersistTime { get; set; } = 1;

        private DocumentClosure Document => Ancestor<DocumentClosure>();

        private const int SubtitleFontSize = 24;
        private const int SecondarySubtitleFontSize = 20;

        private Effect primaryImageAnimation;

        private bool isPrimaryImageVertical;

        /// <summary>
        /// 由用户注册的所有动画。
        /// </summary>
        public List<AnimationInfo> Animations { get; } = new List<AnimationInfo>();

        public void Initialize(string imagePath, string primaryText)
        {
            PrimaryImageAnimationDuration = MinImageAnimationDuration;
            var ppEntryEffect = Document.SlideTransitionPool.RandomEntryEffect();
            Slide.SlideShowTransition.EntryEffect = ppEntryEffect;
            Slide.SlideShowTransition.Duration = 1;
            if (!string.IsNullOrEmpty(imagePath))
            {
                PrimaryImage = Slide.Shapes.AddPicture(imagePath,
                    MsoTriState.msoTrue, MsoTriState.msoTrue, 0, 0);
                //宽 / 高
                var sizeRatio = PrimaryImage.Width/PrimaryImage.Height;
                var screenRatio = Document.SlideWidth/Document.SlideHeight;
                // 图片比屏幕更高一些,纵向。
                isPrimaryImageVertical = sizeRatio < screenRatio;
                // 先尝试放大图片,使其一边超出屏幕。
                if (isPrimaryImageVertical)
                    PrimaryImage.Width = Document.SlideWidth;
                else
                    PrimaryImage.Height = Document.SlideHeight;
                // 计算超出的部分。
                var scrollOffsetRelative = isPrimaryImageVertical
                    ? PrimaryImage.Height/Document.SlideHeight
                    : PrimaryImage.Width/Document.SlideWidth; // > 1.0
                if (scrollOffsetRelative < 1.2)
                {
                    switch (rnd.Next(0, 3))
                    {
                        case 0:
                            ImageAnimation(PrimaryImageAnimation.Fit);
                            break;
                        case 1:
                            ImageAnimation(PrimaryImageAnimation.Expand);
                            break;
                        default:
                            ImageAnimation(PrimaryImageAnimation.Shrink);
                            break;
                    }
                }
                else if (isPrimaryImageVertical)
                    ImageAnimation(PrimaryImageAnimation.ScrollNear);
                else
                    ImageAnimation(PrimaryImageAnimation.ScrollFar);
                if (Document.IsDebug)
                {
                    var tb = Slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 0, 0, 50, 50);
                    tb.TextFrame.AutoSize = PpAutoSize.ppAutoSizeShapeToFitText;
                    tb.TextFrame.WordWrap = MsoTriState.msoFalse;
                    tb.TextFrame.TextRange.Font.Size = 9;
                    tb.TextFrame.TextRange.Text = imagePath;
                }
            }
            if (!string.IsNullOrEmpty(primaryText))
            {
                PrimaryTextBox = CreateTextBox(primaryText, 0);
                PrimaryTextBox.TextFrame.TextRange.Font.Size = 24;
                PrimaryTextBox.Top = Document.SlideHeight - PrimaryTextBox.Height;
            }
        }

        public AnimationInfo AddAnimation(Shape shape, MsoAnimEffect effect,
            TimeSpan delay, TimeSpan duration, AnimationOptions options)
        {
            var e = Slide.TimeLine.MainSequence.AddEffect(shape, effect,
                trigger: MsoAnimTriggerType.msoAnimTriggerWithPrevious);
            e.Exit = (options & AnimationOptions.Exit) == AnimationOptions.Exit
                ? MsoTriState.msoTrue
                : MsoTriState.msoFalse;
            var ani =
                new AnimationInfo((((options & AnimationOptions.WithPrevious) == AnimationOptions.WithPrevious
                    ? Animations.LastOrDefault()?.StartAt
                    : Animations.LastOrDefault()?.EndAt) ?? TimeSpan.Zero) + delay,
                    duration);
            ani.ApplyTiming(e.Timing);
            if ((options & AnimationOptions.ByCharacter) == AnimationOptions.ByCharacter)
            {
                e = Slide.TimeLine.MainSequence.ConvertToTextUnitEffect(e,
                    MsoAnimTextUnitEffect.msoAnimTextUnitEffectByCharacter);
            }
            if ((options & AnimationOptions.ByParagraph) == AnimationOptions.ByParagraph)
            {
                const MsoAnimateByLevel BuildLevel = MsoAnimateByLevel.msoAnimateTextByAllLevels;
                e = Slide.TimeLine.MainSequence.ConvertToBuildLevel(e, BuildLevel);
                //此时 e 指向第一个段落的动画。
                var paragrahAnimations = new List<Effect>();
                for (int i = e.Index, j = Slide.TimeLine.MainSequence.Count; i <= j; i++)
                {
                    var subEffect = Slide.TimeLine.MainSequence[i];
                    if (subEffect.Shape != shape
                        || subEffect.EffectInformation.BuildByLevelEffect != BuildLevel)
                        break;
                    paragrahAnimations.Add(subEffect);
                }
                //为每一个段落动画应用相同的触发模式。
                ani.ApplyTiming(paragrahAnimations.Select(e1 => e1.Timing));
            }
            Animations.Add(ani);
            return ani;
        }

        public Shape CreateTextBox(string content, float y)
        {
            var textBox = Slide.Shapes.AddTextbox(
                MsoTextOrientation.msoTextOrientationHorizontal,
                0, y, Document.SlideWidth, 100);
            textBox.TextFrame.AutoSize = PpAutoSize.ppAutoSizeShapeToFitText;
            textBox.TextFrame.WordWrap = MsoTriState.msoTrue;
            textBox.TextFrame.TextRange.Text = content;
            textBox.TextFrame.TextRange.ParagraphFormat.Alignment = PpParagraphAlignment.ppAlignCenter;
            textBox.TextFrame.TextRange.Font.Size = SubtitleFontSize;
            textBox.TextFrame.TextRange.Font.Bold = MsoTriState.msoTrue;
            textBox.TextFrame.TextRange.Font.Shadow = MsoTriState.msoTrue;
            textBox.TextFrame2.TextRange.Font.Shadow.Transparency = 0;
            textBox.TextFrame2.TextRange.Font.Line.Visible = MsoTriState.msoTrue;
            textBox.TextFrame2.TextRange.Font.Line.ForeColor.RGB = 0;
            textBox.TextFrame2.TextRange.Font.Line.Weight = 1;
            return textBox;
        }

        protected override void OnLeavingClosure()
        {
            base.OnLeavingClosure();
            Slide.SlideShowTransition.AdvanceOnTime = MsoTriState.msoTrue;
            var animationTime = Animations.Count > 0 ? Animations.Last().EndAt : TimeSpan.Zero;
            Slide.SlideShowTransition.AdvanceTime = Math.Max(PrimaryImageAnimationDuration, (float)animationTime.TotalSeconds) +
                                                    PagePersistTime;
        }

        private string GenerateScrollMotionPath(bool scrollFar)
        {
            if (PrimaryImage == null) return null;
            if (isPrimaryImageVertical)
            {
                // 纵向
                PrimaryImage.Width = Document.SlideWidth;
                var scrollOffsetRelative = (PrimaryImage.Height - Document.SlideHeight) / Document.SlideHeight;
                if (scrollFar) scrollOffsetRelative = -scrollOffsetRelative;
                PrimaryImage.Top = scrollFar
                    ? 0
                    : Document.SlideHeight - PrimaryImage.Height;
                return $"M 0 0 L 0 {scrollOffsetRelative}";
            }
            else
            {
                // 横向
                PrimaryImage.Height = Document.SlideHeight;
                var scrollOffsetRelative = (PrimaryImage.Width - Document.SlideWidth) / Document.SlideWidth;
                if (scrollFar) scrollOffsetRelative = -scrollOffsetRelative;
                PrimaryImage.Left = scrollFar
                    ? 0
                    : Document.SlideWidth - PrimaryImage.Width;
                return $"M 0 0 L {scrollOffsetRelative} 0";
            }
        }

        /// <summary>
        /// 以图形的中心为参考点,放大/缩小图形。
        /// </summary>
        public static void ScaleFromCenter(Shape shape, float ratio)
        {
            if (shape == null) throw new ArgumentNullException(nameof(shape));
            shape.Left -= shape.Width*(ratio - 1)/2;
            shape.Top -= shape.Width*(ratio - 1)/2;
            shape.Width *= ratio;
            shape.Height *= ratio;
        }

        public Closure Persist(float persistTime)
        {
            PagePersistTime = persistTime;
            return this;
        }

        private void AlignImage(bool allowCrop, bool alignCenter)
        {
            // allowCrop == true 放大图片,使其一边超出屏幕。
            // allowCrop == false 放大图片,但不要使其超出屏幕。
            if (isPrimaryImageVertical ^ !allowCrop)
                PrimaryImage.Width = Document.SlideWidth;
            else
                PrimaryImage.Height = Document.SlideHeight;
            if (alignCenter)
            {
                PrimaryImage.Left = (Document.SlideWidth - PrimaryImage.Width)/2;
                PrimaryImage.Top = (Document.SlideHeight - PrimaryImage.Height)/2;
            }
            else
            {
                PrimaryImage.Left = 0;
                PrimaryImage.Top = 0;
            }
        }

        private void SubstitutePrimaryImageAnimation(MsoAnimEffect? effect)
        {
            if (effect == null)
            {
                if (primaryImageAnimation != null)
                {
                    primaryImageAnimation.Delete();
                    primaryImageAnimation = null;
                }
                return;
            }
            if (primaryImageAnimation == null)
            {
                primaryImageAnimation = Slide.TimeLine.MainSequence.AddEffect(PrimaryImage,
                    effectId: effect.Value,
                    trigger: MsoAnimTriggerType.msoAnimTriggerWithPrevious, Index: 1);
            }
            else
            {
                primaryImageAnimation.EffectType = effect.Value;
            }
            primaryImageAnimation.Timing.Duration = PrimaryImageAnimationDuration;
            primaryImageAnimation.Timing.SmoothEnd = MsoTriState.msoTrue;
        }

        private readonly Random rnd = new Random();

        [ClosureOperation]
        public Closure ImageAnimation(PrimaryImageAnimation animation)
        {
            if (PrimaryImage == null) return this;
            if (animation == PrimaryImageAnimation.ExpandOrShink)
                animation = rnd.Next(0, 2) == 0 ? PrimaryImageAnimation.Expand : PrimaryImageAnimation.Shrink;
            switch (animation)
            {
                case PrimaryImageAnimation.None:
                    AlignImage(false, true);
                    SubstitutePrimaryImageAnimation(null);
                    break;
                case PrimaryImageAnimation.Fit:
                    AlignImage(true, true);
                    SubstitutePrimaryImageAnimation(null);
                    break;
                case PrimaryImageAnimation.Expand:
                    AlignImage(true, true);
                    PrimaryImageAnimationDuration = MinImageAnimationDuration;
                    SubstitutePrimaryImageAnimation(MsoAnimEffect.msoAnimEffectGrowShrink);
                    var b = primaryImageAnimation.Behaviors[1];
                    b.ScaleEffect.ByX = b.ScaleEffect.ByY = 105; //注意单位是%
                    break;
                case PrimaryImageAnimation.Shrink:
                    AlignImage(true, true);
                    ScaleFromCenter(PrimaryImage, 1.05f);
                    PrimaryImageAnimationDuration = MinImageAnimationDuration;
                    SubstitutePrimaryImageAnimation(MsoAnimEffect.msoAnimEffectGrowShrink);
                    b = primaryImageAnimation.Behaviors[1];
                    b.ScaleEffect.ByX = b.ScaleEffect.ByY = 100/1.05f; //注意单位是%
                    break;
                case PrimaryImageAnimation.ScrollNear:
                case PrimaryImageAnimation.ScrollFar:
                    AlignImage(true, false);
                    // 滚动过长的图片。
                    // 计算超出的部分。
                    var scrollOffsetRelative = isPrimaryImageVertical
                        ? PrimaryImage.Height / Document.SlideHeight
                        : PrimaryImage.Width / Document.SlideWidth; // > 1.0
                    if (Math.Abs(scrollOffsetRelative) > 2)
                    {
                        // 如果超出屏幕的区域太长……
                        PrimaryImageAnimationDuration = MinImageAnimationDuration*Math.Abs(scrollOffsetRelative);
                    }
                    else
                    {
                        PrimaryImageAnimationDuration = MinImageAnimationDuration;
                    }
                    SubstitutePrimaryImageAnimation(MsoAnimEffect.msoAnimEffectCustom);
                    b = primaryImageAnimation.Behaviors.Add(MsoAnimType.msoAnimTypeMotion);
                    b.MotionEffect.Path = GenerateScrollMotionPath(animation == PrimaryImageAnimation.ScrollFar);
                    primaryImageAnimation.Timing.Duration = PrimaryImageAnimationDuration;
                    primaryImageAnimation.Timing.SmoothEnd = MsoTriState.msoCTrue;
                    break;
            }
            return this;
        }

        [ClosureOperation]
        public Closure Text(string text = "")
        {
            var closure = new TextClosure(this) { TextBox = CreateTextBox(text, 0) };
            //closure.EnterAnimation = Slide.TimeLine.MainSequence.AddEffect(closure.TextBox,
            //    effectId: MsoAnimEffect.msoAnimEffectFade,
            //    trigger: MsoAnimTriggerType.msoAnimTriggerAfterPrevious);
            //closure.EnterAnimation.Timing.Duration = TEXT_ADVANCE_TIME;
            return closure;
        }

        [ClosureOperation]
        public Closure Subtitle2(string text = "")
        {
            var closure = new TextClosure(this) { TextBox = CreateTextBox(text, 0) };
            closure.FontSize(SecondarySubtitleFontSize);
            closure.Bottom();
            return closure;
        }

        /// <summary>
        /// 插入BGM,注意,此功能仅用作打样。建议后期手动合成音轨。
        /// </summary>
        [ClosureOperation]
        public Closure Music(string path = "", int stopAfterSlides = 999)
        {
            var media = Slide.Shapes.AddMediaObject2(Path.Combine(Document.WorkPath, path));
            var effectIndex = Slide.TimeLine.MainSequence.AddEffect(media, MsoAnimEffect.msoAnimEffectMediaPlay,
                trigger: MsoAnimTriggerType.msoAnimTriggerWithPrevious).Index;
            media.Left = -media.Width;
            media.Top = -media.Height;
            Func<Effect> effect = () => Slide.TimeLine.MainSequence[effectIndex];
            ////注意下面两行的顺序不能反。
            //effect().EffectInformation.PlaySettings.HideWhileNotPlaying = MsoTriState.msoTrue;
            effect().EffectInformation.PlaySettings.StopAfterSlides = stopAfterSlides;
            return this;
        }

        [ClosureOperation]
        public Closure Transition(PpEntryEffect effect = PpEntryEffect.ppEffectNone)
        {
            Slide.SlideShowTransition.EntryEffect = effect;
            return this;
        }

        public PageClosure(Closure parent, Slide slide) : base(parent)
        {
            Slide = slide;
        }
    }

    internal class TextClosure : Closure
    {
        public const float TextAnimationDuration = 0.5f;

        public Shape TextBox { get; set; }

        public Effect EnterAnimation { get; set; }

        private DocumentClosure Document => Ancestor<DocumentClosure>();

        private PageClosure Page => Ancestor<PageClosure>();

        [ClosureOperation]
        public Closure Left(float value = 0)
        {
            TextBox.Left = value * Document.SlideWidth;
            return this;
        }

        [ClosureOperation]
        public Closure Top(float value = 0)
        {
            TextBox.Top = value * Document.SlideHeight;
            return this;
        }

        [ClosureOperation]
        public Closure Bottom(float value = 0)
        {
            TextBox.Top = Document.SlideHeight - (Page.PrimaryTextBox?.Height ?? 0)
                          - TextBox.Height + value * Document.SlideHeight;
            return this;
        }

        [ClosureOperation]
        public Closure VCenter(float offset = 0)
        {
            TextBox.Top = (Document.SlideHeight - TextBox.Height) / 2 + offset * Document.SlideHeight;
            return this;
        }

        [ClosureOperation]
        public Closure Animation(MsoAnimEffect effect = MsoAnimEffect.msoAnimEffectFade,
            AnimationOptions options = AnimationOptions.None, float delay = 0)
        {
            Page.AddAnimation(TextBox, effect, TimeSpan.FromSeconds(delay), TimeSpan.FromSeconds(TextAnimationDuration), options);
            return this;
        }

        [ClosureOperation]
        public Closure FontSize(float size = 24)
        {
            TextBox.TextFrame.TextRange.Font.Size = size;
            return this;
        }

        [ClosureOperation]
        public Closure Paragraph(string text = "")
        {
            if (TextBox.TextFrame.HasText == MsoTriState.msoTrue)
                TextBox.TextFrame.TextRange.InsertAfter("\r\n");
            TextBox.TextFrame.TextRange.InsertAfter(text);
            return this;
        }

        public TextClosure(Closure parent) : base(parent)
        {
        }
    }

    internal class AnimationInfo
    {
        public AnimationInfo(TimeSpan startAt, TimeSpan duration)
        {
            StartAt = startAt;
            Duration = duration;
        }

        public TimeSpan StartAt { get; set; }

        public TimeSpan Duration { get; set; }

        public TimeSpan EndAt => StartAt + Duration;

        public void ApplyTiming(Timing t)
        {
            if (t == null) throw new ArgumentNullException(nameof(t));
            t.TriggerDelayTime = (float)StartAt.TotalSeconds;
            t.Duration = (float)Duration.TotalSeconds;
        }

        public void ApplyTiming(IEnumerable<Timing> timings)
        {
            var lastEndAt = StartAt;
            foreach (var t in timings)
            {
                t.TriggerDelayTime = (float)lastEndAt.TotalSeconds;
                t.Duration = (float)Duration.TotalSeconds;
                lastEndAt += Duration;
            }
            Duration = lastEndAt - StartAt;
        }
    }

    [Flags]
    public enum AnimationOptions
    {
        None = 0,
        Exit = 1,
        ByParagraph = 2,
        ByCharacter = 4,
        WithPrevious = 8,
    };

    /// <summary>
    /// 一张图片的滚动方向(视图滚动方向)。
    /// </summary>
    public enum ImageScrollDirection
    {
        LeftUp,
        RightDown
    }
}


text:
package org.apache.qpid.protonj2.test.driver.codec.messaging;

import java.util.List;

import org.apache.qpid.protonj2.test.driver.codec.ListDescribedType;
import org.apache.qpid.protonj2.test.driver.codec.primitives.Symbol;
import org.apache.qpid.protonj2.test.driver.codec.primitives.UnsignedLong;
import org.apache.qpid.protonj2.test.driver.codec.transport.DeliveryState;

public class Received extends ListDescribedType implements DeliveryState, Outcome {

    public static final Symbol DESCRIPTOR_SYMBOL = Symbol.valueOf("amqp:received:list");
    public static final UnsignedLong DESCRIPTOR_CODE = UnsignedLong.valueOf(0x0000000000000023L);

    /**
     * Enumeration which maps to fields in the Received Performative
     */
    public enum Field {
        SECTION_NUMBER,
        SECTION_OFFSET,
    }

    public Received() {
        super(Field.values().length);
    }

    @SuppressWarnings("unchecked")
    public Received(Object described) {
        super(Field.values().length, (List<Object>) described);
    }

    public Received(List<Object> described) {
        super(Field.values().length, described);
    }

    @Override
    public Symbol getDescriptor() {
        return DESCRIPTOR_SYMBOL;
    }

    public Received setSectionNumber(Object o) {
        getList().set(Field.SECTION_NUMBER.ordinal(), o);
        return this;
    }

    public Object getSectionNumber() {
        return getList().get(Field.SECTION_NUMBER.ordinal());
    }

    public Received setSectionOffset(Object o) {
        getList().set(Field.SECTION_OFFSET.ordinal(), o);
        return this;
    }

    public Object getSectionOffset() {
        return getList().get(Field.SECTION_OFFSET.ordinal());
    }

    @Override
    public DeliveryStateType getType() {
        return DeliveryStateType.Received;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Text;
using System.Threading.Tasks;
using EntityFramework.Caching;

namespace EntityFramework.Extensions
{
    /// <summary>
    /// Extension methods for query cache.
    /// </summary>
    public static class CacheExtensions
    {
        /// <summary>
        /// Returns the result of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>
        /// The result of the query.
        /// </returns>
        public static IEnumerable<TEntity> FromCache<TEntity>(this IQueryable<TEntity> query, CachePolicy cachePolicy = null, IEnumerable<string> tags = null)
            where TEntity : class
        {
            string key = query.GetCacheKey();
            var cacheKey = new CacheKey(key,
                tags ?? Enumerable.Empty<string>());

            // allow override of CacheManager
            var manager = Locator.Current.Resolve<CacheManager>();

            var result = manager.GetOrAdd(
                cacheKey,
                k => query.AsNoTracking().ToList(),
                cachePolicy ?? CachePolicy.Default
            ) as IEnumerable<TEntity>;

            return result;
        }

#if NET45
        /// <summary>
        /// Returns the result of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized asynchronously and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>
        /// The result of the query.
        /// </returns>
        public static async Task<IEnumerable<TEntity>> FromCacheAsync<TEntity>(this IQueryable<TEntity> query, CachePolicy cachePolicy = null, IEnumerable<string> tags = null)
            where TEntity : class
        {
            string key = query.GetCacheKey();
            var cacheKey = new CacheKey(key,
                tags ?? Enumerable.Empty<string>());

            // allow override of CacheManager
            var manager = Locator.Current.Resolve<CacheManager>();

            var result = await manager
                .GetOrAddAsync(
                    cacheKey,
                    async k => await query.AsNoTracking().ToListAsync().ConfigureAwait(false),
                    cachePolicy ?? CachePolicy.Default
                )
                .ConfigureAwait(false) as IEnumerable<TEntity>;

            return result;
        }

#endif

        /// <summary>
        /// Returns the first element of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>default(T) if source is empty; otherwise, the first element in source.</returns>
        public static TEntity FromCacheFirstOrDefault<TEntity>(this IQueryable<TEntity> query, CachePolicy cachePolicy = null, IEnumerable<string> tags = null)
            where TEntity : class
        {
            return query
                .Take(1)
                .FromCache(cachePolicy, tags)
                .FirstOrDefault();
        }

#if NET45
        /// <summary>
        /// Returns the first element of the <paramref name="query"/>; if possible from the cache,
        /// otherwise the query is materialized asynchronously and the result cached before being returned.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="cachePolicy">The cache policy for the query.</param>
        /// <param name="tags">The list of tags to use for cache expiration.</param>
        /// <returns>default(T) if source is empty; otherwise, the first element in source.</returns>
        public static async Task<TEntity> FromCacheFirstOrDefaultAsync<TEntity>(this IQueryable<TEntity> query, CachePolicy cachePolicy = null, IEnumerable<string> tags = null)
            where TEntity : class
        {
            var q = await query
                .Take(1)
                .FromCacheAsync(cachePolicy, tags)
                .ConfigureAwait(false);

            return q.FirstOrDefault();
        }

#endif

        /// <summary>
        /// Removes the cached query from cache.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <returns>
        /// The original <paramref name="query"/> for fluent chaining.
        /// </returns>
        public static IQueryable<TEntity> RemoveCache<TEntity>(this IQueryable<TEntity> query)
            where TEntity : class
        {
            IEnumerable<TEntity> removed;
            return RemoveCache(query, out removed);
        }

        /// <summary>
        /// Removes the cached query from cache.
        /// </summary>
        /// <typeparam name="TEntity">The type of the data in the data source.</typeparam>
        /// <param name="query">The query to be materialized.</param>
        /// <param name="removed">The removed items for cache.</param>
        /// <returns>
        /// The original <paramref name="query"/> for fluent chaining.
        /// </returns>
        public static IQueryable<TEntity> RemoveCache<TEntity>(this IQueryable<TEntity> query, out IEnumerable<TEntity> removed)
            where TEntity : class
        {
            string key = query.GetCacheKey();

            // allow override of CacheManager
            var manager = Locator.Current.Resolve<CacheManager>();

            removed = manager.Remove(key) as IEnumerable<TEntity>;
            return query;
        }
    }
}


text:
package com.example.android.sunshine.app;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import com.example.android.sunshine.app.data.WeatherContract;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import com.patloew.rxwear.RxWear;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import rx.functions.Action1;

/**
 * Created by ahmedrizwan on 12/03/2016.
 */
public class DataLayerListenerService extends WearableListenerService
    implements Loader.OnLoadCompleteListener<Cursor> {
  public static final String START_ACTIVITY_PATH = "/start-activity";
  GoogleApiClient mGoogleApiClient;
  private CursorLoader mCursorLoader;

  public static DataLayerListenerService instance;

  @Override public void onCreate() {
    super.onCreate();
    instance = this;
    RxWear.init(this);
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
    mGoogleApiClient.connect();
  }

  public static DataLayerListenerService getInstance(){
    return instance;
  }

  @Override public void onMessageReceived(MessageEvent messageEvent) {
    // Check to see if the message is to start an activity
    Log.e("Mobile", "onMessageReceived");
    if (messageEvent.getPath().equals(START_ACTIVITY_PATH)) {
      syncWithWear();
    }
  }

  public void syncWithWear() {
    String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";

    String locationSetting = Utility.getPreferredLocation(this);
    Uri weatherForLocationUri =
        WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
            System.currentTimeMillis());
    mCursorLoader =
        new CursorLoader(this, weatherForLocationUri, ForecastFragment.FORECAST_COLUMNS, null,
            null, sortOrder);
    mCursorLoader.registerListener(0, this);
    mCursorLoader.startLoading();
  }

  @Override public void onDestroy() {
    // Stop the cursor loader
    if (mCursorLoader != null) {
      mCursorLoader.unregisterListener(this);
      mCursorLoader.cancelLoad();
      mCursorLoader.stopLoading();
    }
  }

  @Override public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
    // Read high temperature from cursor
    try {
      data.moveToFirst();
      sendWeatherData(data);
      sendPhoto(data);
    } catch (Exception e) {
      RxWear.Data.PutDataMap.to("/error")
          .putString("message", "Unable to fetch weather!")
          .toObservable()
          .subscribe(new Action1<DataItem>() {
            @Override public void call(DataItem dataItem) {
              Log.e("Mobile", "Sent to Wear");
            }
          });
    }
  }

  private void sendPhoto(Cursor data) {
    PutDataMapRequest dataMap = PutDataMapRequest.create("/image");
    dataMap.getDataMap().putAsset("icon", getWeatherAsset(data));
    dataMap.getDataMap().putLong("time", new Date().getTime());
    PutDataRequest request = dataMap.asPutDataRequest();
    request.setUrgent();

    Wearable.DataApi.putDataItem(mGoogleApiClient, request)
        .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
          @Override public void onResult(DataApi.DataItemResult dataItemResult) {
            Log.e("App", "Sending image was successful: " + dataItemResult.getStatus().isSuccess());
          }
        });
  }

  private void sendWeatherData(Cursor data) {
    double high = data.getDouble(ForecastFragment.COL_WEATHER_MAX_TEMP);
    String highString = Utility.formatTemperature(this, high);
    double low = data.getDouble(ForecastFragment.COL_WEATHER_MIN_TEMP);
    String lowString = Utility.formatTemperature(this, low);

    //Toast.makeText(DataLayerListenerService.this, "Sending Data", Toast.LENGTH_SHORT).show();

    RxWear.Data.PutDataMap.to("/weather")
        .putString("temp_high", highString)
        .putString("temp_low", lowString)
        .putDouble("time", new Date().getTime())
        .toObservable()
        .subscribe(new Action1<DataItem>() {
          @Override public void call(DataItem dataItem) {
            Log.e("Mobile", "Sent to Wear");
          }
        });
  }

  private Asset getWeatherAsset(Cursor data) {
    int weatherId = data.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID);
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_clear);
    ;
    if (weatherId >= 200 && weatherId <= 232) {
      //send storm image
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_storm);
    } else if (weatherId >= 300 && weatherId <= 321) {
      //send light rain
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_light_rain);
    } else if (weatherId >= 500 && weatherId <= 504) {
      //send rain
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_rain);
    } else if (weatherId == 511) {
      //send snow
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_snow);
    } else if (weatherId >= 520 && weatherId <= 531) {
      //send rain
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_rain);
    } else if (weatherId >= 600 && weatherId <= 622) {
      //send snow
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_snow);
    } else if (weatherId >= 701 && weatherId <= 761) {
      //send fog
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_fog);
    } else if (weatherId == 761 || weatherId == 781) {
      //send storm
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_storm);
    } else if (weatherId == 800) {
      //send clear
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_clear);
    } else if (weatherId == 801) {
      //send light clouds
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_light_clouds);
    } else if (weatherId >= 802 && weatherId <= 804) {
      //send clouds
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.art_clouds);
    }
    return createAssetFromBitmap(bitmap);
  }

  private static Asset createAssetFromBitmap(Bitmap bitmap) {
    final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 50, byteStream);
    return Asset.createFromBytes(byteStream.toByteArray());
  }
}


text:
require('buzz')

-- Create and register a handler for /
function index(request)
  print('index request')
  buzz.response(request, '
Hello, World!
\n')
end
buzz.get('^/$', index)

-- Create a handler that takes one argument
function testarg(request, args)
  print('arg request (arg=\''..args[1]..'\')')
  buzz.response(request, '
arg='..args[1]..'
\n')
end
buzz.get('^/testarg/([^/]*)/?$', testarg)

-- Create a handler for two arguments, define the handler inline
buzz.get('^/test2args/([^/]*)/([^/]*)/?$',
		 function(request, args)
		   print('test2args (arg1=\''..args[1]..'\', arg2=\''..args[2]..'\')')
		   buzz.response(request, '
arg1=\''..args[1]..'\', arg2=\''..args[2]..'\'
\n')
		 end)

function static_file(request, args)
  print("Static: ".. args[1])
  -- Probably not a sufficient security check.  Don't allow any path
  -- that contains a ./, to at least avoid, say,
  -- '../../../../etc/passwd' type things.
  -- TODO: find a library written by someone smart to do this
  -- TODO2: Complain to someone about chroot requiring root privileges!
  -- TODO3: luajit has problems parsing '\./' as a pattern, but [.]/ works.  lua 5.1 likes either just fine
  if string.find(args[1], '[.]/') then
	buzz.error(request, 404, 'Invalid path')
	return
  end

  local file = io.open('static/'..args[1])
  buzz.response(request, file:read('*a'))
end
buzz.get('^/static/(.*)$', static_file)

function post(request, args)
  print('post data: '..request.data)
end
buzz.post('^/post/(.*)$', post)

buzz.run()


text:
/*
 *  (c) 2017 Michael A. Beck, Sebastian Henningsen
 *  		disco | Distributed Computer Systems Lab
 *  		University of Kaiserslautern, Germany
 *  All Rights Reserved.
 *
 * This software is work in progress and is released in the hope that it will
 * be useful to the scientific community. It is provided "as is" without
 * express or implied warranty, including but not limited to the correctness
 * of the code or its suitability for any particular purpose.
 *
 * This software is provided under the MIT License, however, we would
 * appreciate it if you contacted the respective authors prior to commercial use.
 *
 * If you find our software useful, we would appreciate if you mentioned it
 * in any publication arising from the use of this software or acknowledge
 * our work otherwise. We would also like to hear of any fixes or useful
 */
package unikl.disco.calculator.network;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import unikl.disco.calculator.symbolic_math.Arrival;
import unikl.disco.calculator.gui.Displayable;
import unikl.disco.calculator.symbolic_math.Service;

/**
 * This class represents a node in the network. It knows about its
 * incoming arrivals, their priorities at this node and their
 * flow_ids. This is done by the two HashSets priorities
 *  and incoming. The first contains all flows
 * arriving at the node and their priorities. The latter contains
 * all flows, for which an arrival description is given. Further
 * the vertex can determine, which flow is the next to serve.
 * The most important method in this class is serve().
 * It is called to calculate the leftover service of this node,
 * after serving the current flow (in expression the flow, which
 * has the highest priority and was not served yet). Further it
 * returns the output bound of the served flow.
 * @author Michael Beck
 * @author Sebastian Henningsen
 * @see Flow
 * @see Arrival
 * @see Service
 *
 */
public class Vertex implements Serializable, Displayable {

	private static final long serialVersionUID = -8696545130808777213L;
	private String alias;
	private int ID;

	private Service service;
	private int prioritizedFlowID;
	private Map<Integer, Integer> priorities;
	private int highest_priority;
	private Map<Integer, Arrival> incoming;
        private Network nw;

	//Constructor

	/**
	 * Creates an empty node.
     * @param vertex_ID The ID the vertex will have in the network
     * @param alias An optional alias of the node, empty string if alias is null
     * @param nw The corresponding network in which this node exists
	 */

	protected Vertex(int vertex_ID, String alias, Network nw){
		service = new Service(nw);
		prioritizedFlowID = 0;
		highest_priority = 0;
		priorities = new HashMap<>();
		incoming = new HashMap<>();
		this.ID = vertex_ID;
		service.addServiceDependency(vertex_ID);
		this.alias = alias == null ? "" : alias;
                this.nw = nw;
	}

	/**
	 * Creates a node with a given service
     * @param vertex_ID
	 * @param service the service, which is associated with this
	 * node
     * @param alias An optional alias of the node, empty string if alias is null
     * @param nw The corresponding network in which this node exists
	 */

	public Vertex(int vertex_ID, Service service, String alias, Network nw){
		this.service = service;
		prioritizedFlowID = 0;
		highest_priority = 0;
		priorities = new HashMap<>();
		incoming = new HashMap<>();
		this.ID = vertex_ID;
		service.addServiceDependency(vertex_ID);
		this.alias = alias == null ? "" : alias;
                this.nw = nw;
	}

	//Methods

	/**
	 * Adds an arrival to this node.
	 * @param priority the priority this arrival has at this node
	 * @param flow_id the flow-id to which this arrival belongs
	 * @param arrival the arrival bound
	 */
	public void addArrival(int priority, int flow_id, Arrival arrival){

		priorities.put(flow_id, priority);
		incoming.put(flow_id, arrival);

		//Checks for a change in the highest priority
		if(priority > highest_priority){
			prioritizedFlowID = flow_id;
			highest_priority = priority;
		}
	}

	/**
	 * Adds a non-established arrival to this node.
	 * @param priority the priority of the arrival
	 * @param flow_id the flow-id to which the arrival belongs
	 */
	public void addUnknownArrival(int priority, int flow_id){
		priorities.put(flow_id, priority);
		if(priority > highest_priority){
			prioritizedFlowID = flow_id;
			highest_priority = priority;
		}
	}

	/**
	 * Changes a (non-established) arrival to an established
	 * arrival. If the arrival was already established before, it is
	 * overwritten by this method.
	 * @param flow_id the flow-id to which the arrival belongs
	 * @param arrival the arrival bound
	 * @throws ArrivalNotAvailableException
	 */
	public void learnArrival(int flow_id, Arrival arrival) throws ArrivalNotAvailableException{

		if(priorities.containsKey(flow_id)){
			incoming.put(flow_id, arrival);
		}
		else throw new ArrivalNotAvailableException("The given arrival-flow-id does not appear in the priority list.",this);
	}

	//Serves the prioritized flow, returns the output to the calling procedure. After this the
	//leftover service is calculated and written into service. The served flow is removed from
	//the priority and established_flows HashMaps. Further the next flow to be served is determined.
	//Invoking serve() without any flows in established_incoming will result in an error.
	//Further the invoking analysis is informed via newHoelderCoefficient about new Hölder coefficients
	// rising. Also the dependency sets of service and the involved arrivals are updated.

	/**
	 * Serves the prioritized flow and returns the output to the
	 * calling procedure. After this the leftover service is
	 * calculated and written into service. The served flow is
	 * removed from the priority and established_flows HashMaps.
	 * Further the next flow to be served is determined. Invoking
	 * serve() without any flows in established_incoming will
	 * result in an error.
	 * After serving the current flow this also determines, which
	 * flow is the next one to serve.
	 * @return the output bound
	 * @throws ArrivalNotAvailableException
	 */
	public Arrival serve() throws ArrivalNotAvailableException{
		//TODO: Removing this check seems to break "Simple Analysis"?
		//Checks if non-established arrivals exist (number of priority entries larger > arrival entries)
/*
 * 		if(incoming.size() != priorities.size()){
 *			throw new ArrivalNotAvailableException("Not all arrivals had been established",this);
 *		}
 *
 *		else{
 */
			//Calculates the output-bound
			Arrival arrival = incoming.get(prioritizedFlowID);
			Arrival output = arrival.output(arrival, service);

			//Calculates the leftover service
			service = service.leftover(arrival, service);

                        // Remove this vertex from the flow
                        Flow f = nw.getFlow(prioritizedFlowID);

                        //This causes trouble as learnArrival is called in SimpleAnalysis already. Further this might not be needed for
                        //other Analyses like LadderAnalysis, in which we are only interested in the leftover-service and do not care what
                        //happens with the crossflows afterwards.
                        //f.learnArrival(output);

                        f.removeVertex(this.ID);

			//Removes the served flow from the arrival-list
			priorities.remove(prioritizedFlowID);
			incoming.remove(prioritizedFlowID);

			//System.out.println("Flow with flow_id "+prioritizedFlowID+" and priority "+highest_priority+" served at node "+vertex_ID);

			//Determines the next flow to serve
			prioritizedFlowID = calculatePriority();
			if(prioritizedFlowID > 0)	highest_priority = priorities.get(prioritizedFlowID);

			//Returns the output-bound
			return output;
		}
//	}

	/**
	 * Determines which flow has the highest priority.
	 * @return the flow-id of the flow with the highest priority
	 */
	public int calculatePriority(){
		int high = 0;
		int higher_priority_id =0;
		for(Map.Entry<Integer,Integer> entry : priorities.entrySet()){
			if(high < entry.getValue()){
				higher_priority_id = entry.getKey();
				high = entry.getValue();
			}
		}
		return higher_priority_id;
	}

    /**
     *
     * @return
     */
    public int getPrioritizedFlow() {
            return prioritizedFlowID;
        }

	/**
	 * Determines if there is at least one non-established flow
     * @return true, if there are only established flows and at least one non-established flow, false otherwise
	 */
	public boolean canServe(){
            return !priorities.isEmpty() && priorities.size()==incoming.size();
	}

	/**
	 * Removes a flow from the vertex. This means, its id is
	 * deleted from priorities and incoming.
	 * After this the highest priority is calculated, since the
	 * removed flow, might have been the one with the highest
	 * priority.
	 * @param id the id of the flow to be removed.
	 */
	public void removeFlow(int id){
		priorities.remove(id);
		incoming.remove(id);
		prioritizedFlowID = calculatePriority();
		if(prioritizedFlowID > 0)	highest_priority = priorities.get(prioritizedFlowID);

	}

	//Copy-Operator

    /**
     *
     * @return
     */

	public Vertex copy(){
		Vertex copy = new Vertex(ID, service, alias, nw);
		for(Entry<Integer, Integer> entry : priorities.entrySet()){
			if(incoming.containsKey(entry.getKey())) copy.addArrival(entry.getValue(), entry.getKey(), incoming.get(entry.getKey()));
			else copy.addUnknownArrival(entry.getValue(), entry.getKey());
		}
		return copy;
	}
	//Getter and Setter

    /**
     *
     * @param service
     */
    public void setMGFService(Service service) {
		this.service = service;
	}

    /**
     *
     * @return
     */
    public Service getService(){
		return service;
	}

    /**
     *
     * @return
     */
    @Override
	public String getAlias() {
		return alias;
	}

    /**
     *
     * @return
     */
    @Override
	public int getID(){
		return ID;
	}

    /**
     *
     * @return
     */
    public Map<Integer, Integer> getAllFlowPriorities() {
		return priorities;
	}

    /**
     *
     * @return
     */
    public Set<Integer> getAllFlowIDs() {
            return incoming.keySet();
        }

    /**
     *
     * @param flowID
     * @return
     */
    public Arrival getArrivalOfFlow(int flowID) {
            return incoming.get(flowID);
        }

    /**
     *
     * @param flowID
     * @return
     */
    public int getPriorityOfFlow(int flowID) {
            return priorities.get(flowID);
        }

    /**
     *
     * @return
     */
    @Override
        public String toString() {
            return (this.alias != null ? this.alias : String.valueOf(this.ID));
        }
}


text:
<?php
namespace GetuiSDK\IGeTui\Utils;

class GTConfig
{
    public static function isPushSingleBatchAsync()
    {
        return "true" == GTConfig::getProperty("gexin_pushSingleBatch_needAsync", null, "false");
    }

    public static function isPushListAsync()
    {
        return "true" == GTConfig::getProperty("gexin_pushList_needAsync", null, "false");
    }

    public static function isPushListNeedDetails()
    {
        return "true" == GTConfig::getProperty("gexin_pushList_needDetails", "needDetails", "false");
    }

    public static function getHttpProxyIp()
    {
        return GTConfig::getProperty("gexin_http_proxy_ip", "gexin.rp.sdk.http.proxyHost");
    }

    public static function getHttpProxyPort()
    {
        return (int)GTConfig::getProperty("gexin_http_proxy_port", "gexin.rp.sdk.http.proxyPort", 80);
    }

    public static function getSyncListLimit()
    {
        return (int)GTConfig::getProperty("gexin_pushList_syncLimit", null, 1000);
    }

    public static function getAsyncListLimit()
    {
        return (int)GTConfig::getProperty("gexin_pushList_asyncLimit", null, 10000);
    }

    public static function getHttpConnectionTimeOut()
    {
        return (int)GTConfig::getProperty("gexin_http_connecton_timeout", "gexin.rp.sdk.http.connection.timeout", 60000);
    }

    public static function getHttpInspectInterval()
    {
        return (int)GTConfig::getProperty("gexin_inspect_interval", "gexin.rp.sdk.http.inspect.timeout", 300000);
    }

    public static function getHttpSoTimeOut()
    {
        return (int)GTConfig::getProperty("gexin_http_so_timeout", "gexin.rp.sdk.http.so.timeout", 30000);
    }

    public static function getHttpTryCount()
    {
        return (int)GTConfig::getProperty("gexin_http_tryCount", "gexin.rp.sdk.http.gexinTryCount", 3);
    }

    public static function getDefaultDomainUrl()
    {
        $urlStr = GTConfig::getProperty("gexin_default_domainurl", null);
        if ($urlStr == null || "".equals(trim($urlStr)))
        {
            $hosts = array("http://sdk.open.api.igexin.com/serviceex","http://sdk.open.api.gepush.com/serviceex","http://sdk.open.api.getui.net/serviceex");
            for($i = 0;$i < 3;$i++)
            {
                array_push($hosts,"http://sdk".$i.".open.api.igexin.com/serviceex");
            }
            return $hosts;
        }
        return explode(",",$urlStr);
    }

    private static function getProperty($key, $oldKey, $defaultValue = null)
    {
        $value = getenv($key);
        if($value != null)
        {
            return $value;
        }
        else

            if($oldKey != null)
            {
                $value = getenv($oldKey);
            }
        if($value == null)
        {
            return $defaultValue;
        }else
        {
            return $value;
        }
    }

    public static function getSDKVersion()
    {
        return "4.0.0.1";
    }
}


text:
import asyncio
import ssl
import sys
import signal
import os
import json
import time
import logging
import tempfile
from utils import settings

import zmq
import zmq.asyncio
import irc.client_aio
import jaraco.stream

class PluginInterface:
    def __init__(self, name, bot, pid):

        logging.info("PluginInterface.__init__ %s", "ipc://ipc_plugin_" + name)
        self.name = name
        self.bot = bot
        self.pid = pid
        socket_path = os.path.join(self.bot.temp_folder, "ipc_plugin_" + name)

        context = zmq.asyncio.Context()

        self._socket_plugin = context.socket(zmq.PAIR)
        self._socket_plugin.bind("ipc://" + os.path.abspath(socket_path))

        self._poller = zmq.asyncio.Poller()
        self._poller.register(self._socket_plugin, zmq.POLLIN)

        self.bot.plugin_started(self)

    def _recieve(self, data):
        logging.info("PluginInterface._recieve %s", data)
        if data["function"] == "_save_settings":
            new_plugin_settings = json.loads(data["params"][0])
            self.bot.settings["plugins"][self.name] = new_plugin_settings
            settings.save_settings(self.bot.settings)
            return

        server = data["params"][0]
        if server not in self.bot.servers:
            logging.error("PluginInterface._recieve %s not found", server)
            return

        if data["function"] in [
            "action",
            "admin",
            "cap",
            "ctcp",
            "ctcp_reply",
            "globops",
            "info",
            "invite",
            "ison",
            "join",
            "kick",
            "links",
            "list",
            "lusers",
            "mode",
            "motd",
            "names",
            "nick",
            "notice",
            "oper",
            "part",
            "pass_",
            "ping",
            "pong",
            "privmsg",
            "quit",
            "squit",
            "stats",
            "time",
            "topic",
            "trace",
            "user",
            "userhost",
            "users",
            "version",
            "wallops",
            "who",
            "whois",
            "whowas",
        ]:
            try:
                getattr(self.bot.servers[server], data["function"])(*data["params"][1:])
            except (irc.client.InvalidCharacters, irc.client.MessageTooLong):
                logging.exception("Failed to call function from plugin %r", data)
        else:
            logging.error(
                "Undefined function %s called with %r", data["function"], data["params"]
            )

    def _call(self, function, *args):
        self._socket_plugin.send_json({"function": function, "params": args})

    async def run(self):
        while True:
            socks = dict(await self._poller.poll())

            if self._socket_plugin in socks:
                logging.info("PluginInterface.update %s", self._socket_plugin)
                self._recieve(await self._socket_plugin.recv_json())

    def __getattr__(self, name):
        if name in ["started", "update"]:

            def call(*args, **kwarg):
                self._call(name, *args)

            return call
        else:
            raise AttributeError(self, name)

class Bot:
    def __init__(self, temp_folder):
        logging.basicConfig(filename="Bot.log", level=logging.DEBUG)

        self.settings = settings.load_settings()
        if not settings.validate_settings(self.settings):
            logging.error("Error parsing settings")
            sys.exit(1)
        self.plugins = list()
        self.servers = dict()
        self.temp_folder = temp_folder

    async def reconnect(self, connection):
        while not connection.is_connected():
            logging.error("Waiting 30 seconds to reconnect")
            await asyncio.sleep(30)
            await connection.connect(
                connection.server,
                connection.port,
                connection.nickname,
                password=connection.password,
                username=connection.username,
                ircname=connection.ircname,
                connect_factory=connection.connect_factory,
            )

    def _dispatcher(self, connection, event):
        if event.type == "all_raw_messages":
            return

        if event.type == "disconnect":
            asyncio.create_task(self.reconnect(connection))

        for plugin in self.plugins:
            plugin._call(
                "on_" + event.type,
                connection.name,
                event.source,
                event.target,
                *event.arguments
            )

    def load_plugin(self, name, settings):
        logging.info("Bot.plugin_load %s, %s", name, settings)
        file_name = "plugins/" + name + "/" + name + ".py"
        if not os.path.isfile(file_name):
            logging.error("Unable to load plugin %s", name)
        else:
            logging.info(
                "Bot.plugin_load plugin %s, %s, %s, %s",
                name,
                self,
                sys.executable,
                [sys.executable, file_name],
            )
            environment = os.environ
            environment.update(PYTHONPATH=os.getcwd())
            pid = os.spawnvpe(
                os.P_NOWAIT,
                sys.executable,
                args=[sys.executable, file_name, "--socket_path", self.temp_folder],
                env=environment,
            )
            self.plugins.append(PluginInterface(name, self, pid))

    def plugin_started(self, plugin):
        logging.info("Bot.plugin_started %s, %s", plugin, self.settings)

        for plugin_name, plugin_settings in self.settings["plugins"].items():
            if plugin_name == plugin.name:
                plugin.started(json.dumps(plugin_settings))
                self.loop.create_task(self.plugin_update(plugin))
                self.loop.create_task(plugin.run())
                # self.reactor.scheduler.execute_every(1.0, plugin.update)
                logging.debug("Bot.plugin_started, settings %r", plugin_settings)
                break

    async def plugin_update(self, plugin):
        while True:
            plugin.update()
            await asyncio.sleep(1)

    def run(self):

        self.loop = asyncio.get_event_loop()
        self.reactor = irc.client_aio.AioReactor(loop=self.loop)
        self.reactor.add_global_handler("all_events", self._dispatcher, -10)

        # Load plugins
        if "plugins" in self.settings:
            for plugin_name, plugin_settings in self.settings["plugins"].items():
                self.load_plugin(plugin_name, plugin_settings)

        # Connect to servers
        servers = self.settings["servers"]
        for server_name, server_settings in servers.items():
            logging.info("Connecting to %r %r", server_name, server_settings)
            server = self.reactor.server()
            self.servers[server_name] = server
            server.name = server_name
            server.buffer_class = jaraco.stream.buffer.LenientDecodingLineBuffer
            use_ssl = "ssl" in server_settings and server_settings["ssl"]
            factory = irc.connection.AioFactory(ssl=use_ssl)
            self.loop.run_until_complete(
                server.connect(
                    server_settings["host"],
                    server_settings["port"],
                    nickname=self.settings["nickname"],
                    ircname=self.settings["realname"],
                    username=self.settings["username"],
                    connect_factory=factory,
                )
            )

        try:
            self.reactor.process_forever()
        except:
            logging.exception("Bot.run aborted")

        # Request termination of plugins
        for plugin in self.plugins:
            os.kill(plugin.pid, signal.SIGTERM)

        self.loop.close()
        sys.exit(1)

def main():
    with tempfile.TemporaryDirectory(prefix="platinumshrimp_") as temp_folder:
        bot = Bot(temp_folder)
        bot.run()

if __name__ == "__main__":
    main()


text:
import { LightningElement } from 'lwc';
import { hello } from 'e-exampleLib';

export default class Example1 extends LightningElement {
    text = hello;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Writ. 15 (1906)

#### Original name
Tulostoma macalpinianum Lloyd

### Remarks
null