text:
ifvisible.js
------------

Crossbrowser & lightweight way to check if user is looking at the page or interacting with it.

#### Check out the [Demo](http://serkanyersen.github.com/ifvisible.js/demo.html) or read below for code example or Check [Annotated Source](http://serkanyersen.github.com/ifvisible.js/docs/ifvisible.html)

## Installation
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fserkanyersen%2Fifvisible.js.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fserkanyersen%2Fifvisible.js?ref=badge_shield)

From npm
```
npm install ifvisible.js --save
```

From Bower
```
bower install ifvisible.js
```

For Meteor
```
mrt add ifvisible
```
> meteor package is provided by [@frozeman](https://github.com/frozeman/meteor-ifvisible.js) via [Atmosphere](https://atmosphere.meteor.com/package/ifvisible)

## Examples

```javascript

// If page is visible right now
if( ifvisible.now() ){
	// Display pop-up
	openPopUp();
}

// You can also check the page status
// using `now` method
if( !ifvisible.now('hidden') ){
  // Display pop-up if page is not hidden
  openPopUp();
}

// Possible statuses are:
// idle: when user has no interaction
// hidden: page is not visible
// active: page is visible and user is active

```

Handle tab switch or browser minimize states

```javascript

ifvisible.on("blur", function(){
	// example code here..
	animations.pause();
});

ifvisible.on("focus", function(){
	// resume all animations
	animations.resume();
});

```

ifvisible.js can handle activity states too, such as being IDLE or ACTIVE on the page

```javascript

ifvisible.on("idle", function(){
	// Stop auto updating the live data
	stream.pause();
});

ifvisible.on("wakeup", function(){
	// go back updating data
	stream.resume();
});

```

Default idle duration is 60 seconds but you can change it with `setIdleDuration` method

```javascript

ifvisible.setIdleDuration(120); // Page will become idle after 120 seconds

```

You can manually trigger status events by calling them directly or you can set events with their names by giving first argument as a callback

```javascript

ifvisible.idle(); // will put page in a idle status

ifvisible.idle(function(){
	// This code will work when page goes into idle status
});

// other methods are
ifvisible.blur(); // will trigger idle event as well
ifvisible.idle();

ifvisible.focus(); // Will trigger wakeup event as well
ifvisible.wakeup();
```

You can use ifvisible.off() to remove event triggers:

```javascript

ifvisible.off('idle', triggeredFunction); // will remove only triggeredFunction from being tiggered on idle
ifvisible.off('idle'); // will remove all events triggered on idle

// works with other events:
ifvisible.off('blur');
ifvisible.off('wakeup');
ifvisible.off('focus');

```

You can set your smart intervals with ifvisible.js, if user is IDLE or not seeing the page the interval will automatically stop itself

```javascript

// If page is visible run this function on every half seconds
ifvisible.onEvery(0.5, function(){
    // Do an animation on the logo only when page is visible
	animateLogo();

});

```

### License
It's MIT, Go crazy.

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fserkanyersen%2Fifvisible.js.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fserkanyersen%2Fifvisible.js?ref=badge_large)


text:
package io.bunting.cli4j.parser.args;

import io.bunting.cli4j.parser.Parameter;
import io.bunting.cli4j.parser.internal.Lists;

import java.util.List;

/**
 *
 * @author Andy Law <andy.law@roslin.ed.ac.uk>
 */
public class AlternateNamesForListArgs {

    @Parameter(names = {"-s", "--servers"}, description = "blah")
    public List<String> serverNames = Lists.newLinkedList();
}

redpajama_set_name: RedPajamaGithub


text:
.. _getting-started:

.. Defined for inline java code highlighting
.. role:: java(code)
  :language: java

.. toctree::
  :name: getting_started_toc
   :includehidden:

Getting Started
===============

Here we will go through the basic steps on setting up a Beadledom project. We will go over
the key components needed to make sure your new service is bootstrapped and running correctly;
additionally, we will highlight the major pieces of the service so that you can extend it to
fit your needs. Finally we will point to some additional resources that will show some of the
additional functionality that you can get with the Beadledom framework.

Before we Start
---------------

We know there are a lot of different build tools available for Java, and we think that is great.
However for Beadledom we currently use `maven <https://maven.apache.org/>`_ as our build tool and
dependency manager. The script we will install to help us create our first Beadledom project is
really just a wrapper around `maven archetypes <https://maven.apache.org/archetype/index.html>`_ that let us
remove a lot of the boilerplate around project creation.

Installing the Installer
------------------------

Before we create our first Beadledom project we need to download the
`beadledom installer <https://github.com/cerner/beadledom/blob/main/archetype/bootstrap/>`_ utility.
If you would like to take a look at the installer source code before running it you can find it
`here install.sh script <https://github.com/cerner/beadledom/blob/main/archetype/bootstrap/bin/>`_.

Then to install execute in your shell

.. code-block:: bash

  curl -L ${beadledom.url}/beadledom-archetype/downloads/install.sh | sh

Once the download has completed you should be greeted by some sort of success message and now be
able to run

.. code-block:: bash

  beadledom --help

which should print the usage details to the screen.

Creating Our First Project
--------------------------

We are going to use the default archetype `simple-service <https://github.com/cerner/beadledom/blob/main/archetype/simple-service/>`_
in our example because it is fairly basic while
doing a good job at showing off a fair amount of the base feature set that Beadledom offers. In order to
kick off our project creation we just need to run

.. code-block:: bash

  beadledom new

or

.. code-block:: bash

  beadledom new simple-service

You will be prompted for several things many of which will have some relatively sane defaults. For
our example we are going to choose the following values

:Package Name: com.example
:Project Name: AwesomeThing
:Artifact Id: awesome-thing
:Group Id: com.example
:Beadledom Version: (whatever the default)

Feel free to choose whatever you like, we are just calling it out here to make it easier to references
pieces of the service later.

Running Our Service
-------------------

After a successful project creation we can go ahead and build our project and start the service

.. code-block:: bash

  > cd awesome-thing
  awesome-thing> mvn clean install
  . . .
  [INFO] BUILD SUCCESS
  . . .
  awesome-thing> cd service
  awesome-thing/service> mvn tomcat7:run-war

Once the service has started we can navigate to our swagger resource to retrieve the swagger
specification of the default ``api``.

.. code-block:: html

  http://localhost:8080/awesome-thing-service/api-docs

The Breakdown
-------------

Our project has three maven sub-modules: ``api``, ``client`` and ``service``. We will go through each
of these and talk about the classes they contain.

API sub-module
~~~~~~~~~~~~~~

This module contains the the models defining your ``requests`` and ``responses``. The code living
here ends up being used by both the ``client`` and the ``service``.

HelloWorldResource
++++++++++++++++++

.. code-block:: java

  @Api(value = "/hello", description = "Retrieve hello world data")
  @Path("/hello")
  public interface HelloWorldResource {

    @ApiOperation(
        value = "Retrieves hello world data.",
        response = HelloWorldDto.class)
    @ApiResponse(code = 200, message = "Success")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public GenericResponse<HelloWorldDto> getHelloWorld();
  }

This is the definition for the ``/hello`` resource (and by resource we are talking about an api
resource). There is a lot going on here so we will add some comments to explain what each of these
lines are doing.

.. code-block:: java

  /**
   * Swagger annotation defining the base resource for the generated swagger documentation.
   */
  @Api(value = "/hello", description = "Retrieve hello world data")

  /**
   * JAX-RS annotation defining the base URI path for the resource.
   */
  @Path("/hello")
  public interface HelloWorldResource {

  /**
   * Swagger annotation defining the documentation for the HTTP verb this method provides. It
   * also includes the Dto class that is used for the response.
   */
    @ApiOperation(
        value = "Retrieves hello world data.",
        response = HelloWorldDto.class)

    /**
     * Swagger annotation for the different status codes our resource can
     * return (500 is often omitted).
     */
    @ApiResponse(code = 200, message = "Success")

    /**
     * JAX-RS annotation for the HTTP verb this method is providing functionality for.
     */
    @GET

    /**
     * JAX-RS annotation for the media type our service returns.
     */
    @Produces(MediaType.APPLICATION_JSON)

    /**
     * Method definition for the resource. The GenericResponse is an implementation provided
     * by Beadledom. It allows consumers (mostly of the client) to get a type safe response
     * from the server instead of having to do the casting or deserialization of the Json
     * payload themselves.
     */
    public GenericResponse<HelloWorldDto> getHelloWorld();
  }

And that's pretty much all that is needed to define an end-point. To learn more about how to
extend your path and about additional annotations that can be used in defining a resource we
suggest taking a look at `RESTEasy's documentation <http://resteasy.jboss.org/docs.html>`_ to
get started (RESTEasy is the current implementation of the JAX-RS standard that Beadledom is using).

HelloWorldDto
+++++++++++++

.. code-block:: java

  @ApiModel(value = "HelloWorldDto")
  public class HelloWorldDto {

    @ApiModelProperty(required = true, value = "name of the message author")
    private String name;
    @ApiModelProperty(required = true, value = "message content")
    private String helloWorldMessage;

    private HelloWorldDto(String name, String message) {
      this.name = Preconditions.checkNotNull(name);
      this.helloWorldMessage = Preconditions.checkNotNull(message);
    }

    /**
     * Creates a new {@link HelloWorldDto} instance.
     *
     * @param name author to be associated with the message
     * @param message the message to be returned
     * @return {@link HelloWorldDto} encapsulating a name and message
     */
    public static HelloWorldDto create(String name, String message) {
      return new HelloWorldDto(name, message);
    }

    /** Returns name. */
    public String getName() {
      return name;
    }

    /** Returns hello world message. */
    public String getHelloWorldMessage() {
      return helloWorldMessage;
    }
  }

This class defines the JSON response from the service. The few things to note here are the
Swagger annotations. :java:`@ApiModel(value = "HelloWordDto")` defines the high level API model,
and as we are sure you have already guessed :java:`@ApiModelProperty` allows us to add some documentation
around the various fields that are going to be a part of our response.

Service sub-module
~~~~~~~~~~~~~~~~~~

Now that we have defined our ``api`` lets dive into the implementation and how this all gets
wired together. You'll notice that within our ``service`` sub-module we have not only our source
code directory we also have a resources and webapp directory. Lets spend just a short amount of
time going over what is in our non source code directories.

webapp/META-INF
+++++++++++++++

:Files:
  - **web.xml** - deployment descriptor that loads our context listener class as our servlets entry point

resources
+++++++++

:Files:
  - **log4j.properties** - configuration for our logger
  - **build-info.properties** - properties from the current build used in health checks

All of the above mentioned configuration files are pretty standard. There are lots of other options
that can be tinkered with but we suggest you head to the developers pages for the various libraries
to learn more.

AwesomeThingContextListener
+++++++++++++++++++++++++++

.. Note:: Your class names might be slightly different depending on what you choose for your
  ``Project Name``.

.. code-block:: java

  public class AwesomeThingContextListener extends ResteasyContextListener {
    @Override
    protected List<? extends Module> getModules(ServletContext context) {
      return Lists.newArrayList(new AwesomeThingModule(), new ResteasyBootstrapModule());
    }
  }

There isn't a lot going on in this file, but it is very important. This is the entry point to
our service and where we define our base Guice modules and configuration. We won't dive much
into the configuration component if you want to learn more about it (and we recommend you do)
you can find more documentation `here <https://github.com/cerner/beadledom/tree/main/configuration>`_.

The method we are overriding here is providing our ``AwesomeThingModule``, which is our service module and ``ResteasyBootstrapModule``, which bootstraps ``ResteasyModule`` for our service.

so Let's take a look at the ``ResteasyBootstrapModule`` next.

ResteasyBootstrapModule
+++++++++++++++++++++++

.. code-block:: java

  public class ResteasyBootstrapModule extends AbstractModule {

    protected void configure() {
      install(new ResteasyModule());
      install(new Swagger2Module());

      BuildInfo buildInfo = BuildInfo.load(getClass().getResourceAsStream("build-info.properties"));
      bind(BuildInfo.class).toInstance(buildInfo);
      bind(ServiceMetadata.class).toInstance(ServiceMetadata.create(buildInfo));
    }

    @Provides
    @Singleton
    Info provideSwagger2Info(ServiceMetadata serviceMetadata) {
     return new Info()
        .title("Your Service Name")
        .version(serviceMetadata.getBuildInfo().getVersion());
    }
  }

This is where we install the main Beadledom module :java:`install(new ResteasyModule());`. Inside
this module is where Beadledom is going to install and bootstrap the various features it needs
in order to make our service tick. Below are some of the many awesome features that we get just by installing `ResteasyModule` without any extra efforts

- `Configuration <https://github.com/cerner/beadledom/tree/main/configuration#beadledom-configuration>`_ - lets us access all the configuration through a consistent API.
- `Health <https://github.com/cerner/beadledom/tree/main/health#beadledom-health>`_ - Health checks for the services
- `Jackson <https://github.com/cerner/beadledom/tree/main/jackson#beadledom-jackson>`_ - Serialization-DeSerialization for the payload
- `Swagger <https://github.com/cerner/beadledom/tree/main/swagger2#beadledom-swagger2>`_ - Enables the `Open API <https://openapis.org/specification>`_ documentation and `Swagger UI <http://swagger.io/swagger-ui/>`_

The next chunk of code

.. code-block:: java

    BuildInfo buildInfo = BuildInfo.load(getClass().getResourceAsStream("build-info.properties"));
    bind(BuildInfo.class).toInstance(buildInfo);
    bind(ServiceMetadata.class).toInstance(ServiceMetadata.create(buildInfo));

We pull in the properties from the ``build-info.properties`` and make them available to the service
and more importantly the healthcheck.

AwesomeThingModule
++++++++++++++++++

.. code-block:: java

  public class AwesomeThingModule extends PrivateModule {
    protected void configure() {
      bind(HelloWorldResource.class);

      // Note: All clients that will be used should be installed in this module to avoid registering
      // client JAX-RS resources with the server. The Correlation ID header name for clients could
      // also be configured/overridden here if this is the only PrivateModule that is used.

      expose(HelloWorldResource.class);
    }
  }

``AwesomeThingModule`` is a private module, which contains configuration information for our service.
The PrivateModule encapsulates the service's environment and only exposes objects needed for
JAX-RS/Resteasy(ex: resource classes, providers and features). It also prevents dependency issues
with any configuration bound to Guice globally.

As noted by the comment in the generated code, all bindings necessary to setup your JAX-RS resource
class should be bound here, but only expose the JAX-RS resources and filters that you want to run
as part of the server. By doing this, you can use Beadledom client modules here to have them injected
into your classes, but prevent them from being picked up and scanned by Beadledom/JAX-RS as part
of the service.

By binding :java:`bind(HelloWorldResource.class);` we are making this available to Beadledom and
JAX-RS which will scan it to fine the JAX-RS annotations and make it available for the proper URL
path. And the next line :java:`expose(HelloWorldResource.class);`, exposes `HelloWorldResource`_ to modules that install `AwesomeThingModule`_.

That's it! There are additional Beadledom modules that we can install for other functionality, and
we could even create our own modules or bindings to provide additional classes our service will need
to operate. We recommend that you take some time and become familiar with `Guice <https://github.com/google/guice/wiki/GettingStarted>`_
so that you will know all it enables you to do.

HelloWorldResource
++++++++++++++++++

Last but not least, we have our ``/hello`` endpoint implementation.

.. code-block:: java

  @Api(value = "/hello", description = "Retrieve hello world data")
  @Path("/hello")
  public class HelloWorldResource {

    @ApiOperation(
        value = "Retrieves hello world data.",
        response = HelloWorldDto.class)
    @ApiResponse(code = 200, message = "Success")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public GenericResponse<HelloWorldDto> getHelloWorld() {
      return GenericResponses
          .ok(HelloWorldDto.create("Beadledom", "Hello World!"))
          .build();
    }
  }

That's it. Not very impressive we know, but it is just a starter service after all! More realistic
services will implement whatever sort of business logic, parameter validation, reading and writing
from databases here that they need to back their apis.

Client sub-module
~~~~~~~~~~~~~~~~~

There is a lot going on in the client sub-module, and none of it really has anything to do with
the implementation of your service. What we are able to do is build a client whose api is based
on the same JAX-RS annotations you use for your server. That makes it really easy to make clients
for your Java consumers; however, it won't help you much with consumers of other languages. Instead
of trying to explain all the concepts that are going on within the client we recommend you take a
look at our `client documentation <https://github.com/cerner/beadledom/tree/main/client>`_..

HelloWorldResource
++++++++++++++++++

.. code-block:: java

  @Path("/hello")
  public interface HelloWorldResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    GenericResponse<HelloWorldDto> getHelloWorld();
  }

This is the definition for the ``/hello`` resource from a client-side perspective. This interface
allows automatically generating a client implementation via a Java proxy object.

.. code-block:: java

  /**
   * JAX-RS annotation defining the path for the resource.
   */
  @Path("/hello")
  public interface HelloWorldResource {

    /**
     * JAX-RS annotation for the HTTP verb this method is providing functionality for.
     */
    @GET

    /**
     * JAX-RS annotation for the media type our service returns.
     */
    @Produces(MediaType.APPLICATION_JSON)

    /**
     * Method definition for the resource. The GenericResponse is an implementation provided
     * by Beadledom. It allows consumers (mostly of the client) to get a type safe response
     * from the server instead of having to do the casting or deserialization of the Json
     * payload themselves.
     *
     * For responses that will not include a body in the response (ie. DELETE) it's best to
     * continue using the regular JAX-RS Response class.
     */
    public GenericResponse<HelloWorldDto> getHelloWorld();
  }

Where to go now
---------------

The service we just created and went through is just using a subset of features that Beadledom
can provide. If you would like to learn more about what Beadledom has to offer take a look at our
`table of contents <https://github.com/cerner/beadledom/tree/main>`_ and the related
documentation and code. If you find a bug or have an idea of a feature Beadledom is lacking open
an issue or pull request we are always happy to collaborate to help everyone get to a better place.

Now go build something awesome!


text:
package persist;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityIndex;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.Persistent;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.SecondaryKey;
import static com.sleepycat.persist.model.DeleteAction.NULLIFY;
import static com.sleepycat.persist.model.Relationship.ONE_TO_ONE;
import static com.sleepycat.persist.model.Relationship.ONE_TO_MANY;
import static com.sleepycat.persist.model.Relationship.MANY_TO_ONE;
import static com.sleepycat.persist.model.Relationship.MANY_TO_MANY;

public class PersonExample {

    /* An entity class. */
    @Entity
    static class Person {

        @PrimaryKey
        String ssn;

        String name;
        Address address;

        @SecondaryKey(relate=MANY_TO_ONE, relatedEntity=Person.class)
        String parentSsn;

        @SecondaryKey(relate=ONE_TO_MANY)
        Set<String> emailAddresses = new HashSet<String>();

        @SecondaryKey(relate=MANY_TO_MANY,
                      relatedEntity=Employer.class,
                      onRelatedEntityDelete=NULLIFY)
        Set<Long> employerIds = new HashSet<Long>();

        Person(String name, String ssn, String parentSsn) {
            this.name = name;
            this.ssn = ssn;
            this.parentSsn = parentSsn;
        }

        private Person() {} // For deserialization
    }

    /* Another entity class. */
    @Entity
    static class Employer {

        @PrimaryKey(sequence="ID")
        long id;

        @SecondaryKey(relate=ONE_TO_ONE)
        String name;

        Address address;

        Employer(String name) {
            this.name = name;
        }

        private Employer() {} // For deserialization
    }

    /* A persistent class used in other classes. */
    @Persistent
    static class Address {
        String street;
        String city;
        String state;
        int zipCode;
        private Address() {} // For deserialization
    }

    /* The data accessor class for the entity model. */
    static class PersonAccessor {

        /* Person accessors */
        PrimaryIndex<String,Person> personBySsn;
        SecondaryIndex<String,String,Person> personByParentSsn;
        SecondaryIndex<String,String,Person> personByEmailAddresses;
        SecondaryIndex<Long,String,Person> personByEmployerIds;

        /* Employer accessors */
        PrimaryIndex<Long,Employer> employerById;
        SecondaryIndex<String,Long,Employer> employerByName;

        /* Opens all primary and secondary indices. */
        public PersonAccessor(EntityStore store)
            throws DatabaseException {

            personBySsn = store.getPrimaryIndex(
                String.class, Person.class);

            personByParentSsn = store.getSecondaryIndex(
                personBySsn, String.class, "parentSsn");

            personByEmailAddresses = store.getSecondaryIndex(
                personBySsn, String.class, "emailAddresses");

            personByEmployerIds = store.getSecondaryIndex(
                personBySsn, Long.class, "employerIds");

            employerById = store.getPrimaryIndex(
                Long.class, Employer.class);

            employerByName = store.getSecondaryIndex(
                employerById, String.class, "name");
        }
    }

    public static void main(String[] args)
        throws DatabaseException {

        if (args.length != 2 || !"-h".equals(args[0])) {
            System.err.println
                ("Usage: java " + PersonExample.class.getName() +
                 " -h <envHome>");
            System.exit(2);
        }
        PersonExample example = new PersonExample(new File(args[1]));
        example.run();
        example.close();
    }

    private Environment env;
    private EntityStore store;
    private PersonAccessor dao;

    private PersonExample(File envHome)
        throws DatabaseException {

        /* Open a transactional Berkeley DB engine environment. */
        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(true);
        env = new Environment(envHome, envConfig);

        /* Open a transactional entity store. */
        StoreConfig storeConfig = new StoreConfig();
        storeConfig.setAllowCreate(true);
        storeConfig.setTransactional(true);
        store = new EntityStore(env, "PersonStore", storeConfig);

        /* Initialize the data access object. */
        dao = new PersonAccessor(store);
    }

    private void run()
        throws DatabaseException {

        /*
         * Add a parent and two children using the Person primary index.
         * Specifying a non-null parentSsn adds the child Person to the
         * sub-index of children for that parent key.
         */
        dao.personBySsn.put
            (new Person("Bob Smith", "111-11-1111", null));
        dao.personBySsn.put
            (new Person("Mary Smith", "333-33-3333", "111-11-1111"));
        dao.personBySsn.put
            (new Person("Jack Smith", "222-22-2222", "111-11-1111"));

        /* Print the children of a parent using a sub-index and a cursor. */
        EntityCursor<Person> children =
            dao.personByParentSsn.subIndex("111-11-1111").entities();
        try {
            for (Person child : children) {
                System.out.println(child.ssn + ' ' + child.name);
            }
        } finally {
            children.close();
        }

        /* Get Bob by primary key using the primary index. */
        Person bob = dao.personBySsn.get("111-11-1111");
        assert bob != null;

        /*
         * Create two employers if they do not already exist.  Their primary
         * keys are assigned from a sequence.
         */
        Employer gizmoInc = dao.employerByName.get("Gizmo Inc");
        if (gizmoInc == null) {
            gizmoInc = new Employer("Gizmo Inc");
            dao.employerById.put(gizmoInc);
        }
        Employer gadgetInc = dao.employerByName.get("Gadget Inc");
        if (gadgetInc == null) {
            gadgetInc = new Employer("Gadget Inc");
            dao.employerById.put(gadgetInc);
        }

        /* Bob has two jobs and two email addresses. */
        bob.employerIds.add(gizmoInc.id);
        bob.employerIds.add(gadgetInc.id);
        bob.emailAddresses.add("bob@bob.com");
        bob.emailAddresses.add("bob@gmail.com");

        /* Update Bob's record. */
        dao.personBySsn.put(bob);

        /* Bob can now be found by both email addresses. */
        bob = dao.personByEmailAddresses.get("bob@bob.com");
        assert bob != null;
        bob = dao.personByEmailAddresses.get("bob@gmail.com");
        assert bob != null;

        /* Bob can also be found as an employee of both employers. */
        EntityIndex<String,Person> employees;
        employees = dao.personByEmployerIds.subIndex(gizmoInc.id);
        assert employees.contains("111-11-1111");
        employees = dao.personByEmployerIds.subIndex(gadgetInc.id);
        assert employees.contains("111-11-1111");

        /*
         * When an employer is deleted, the onRelatedEntityDelete=NULLIFY for
         * the employerIds key causes the deleted ID to be removed from Bob's
         * employerIds.
         */
        dao.employerById.delete(gizmoInc.id);
        bob = dao.personBySsn.get("111-11-1111");
        assert bob != null;
        assert !bob.employerIds.contains(gizmoInc.id);
    }

    private void close()
        throws DatabaseException {

        store.close();
        env.close();
    }
}


text:
class GURL;

namespace blink {
enum class WebAutofillState;

class WebDocument;
class WebElement;
class WebFormControlElement;
class WebFormElement;
class WebInputElement;
class WebLocalFrame;
class WebNode;
}  // namespace blink

namespace content {
class RenderFrame;
}  // namespace content

namespace autofill {

struct FormData;
struct FormFieldData;

class FieldDataManager;

namespace form_util {

// Mapping from a form element's render id to results of button titles
// heuristics for a given form element.
using ButtonTitlesCache = base::flat_map<FormRendererId, ButtonTitleList>;

// A bit field mask to extract data from WebFormControlElement.
// Copied to components/autofill/ios/browser/resources/autofill_controller.js.
enum ExtractMask {
  EXTRACT_NONE = 0,
  EXTRACT_VALUE = 1 << 0,        // Extract value from WebFormControlElement.
  EXTRACT_OPTION_TEXT = 1 << 1,  // Extract option text from
                                 // WebFormSelectElement. Only valid when
                                 // |EXTRACT_VALUE| is set.
                                 // This is used for form submission where
                                 // human readable value is captured.
  EXTRACT_OPTIONS = 1 << 2,      // Extract options from
                                 // WebFormControlElement.
  EXTRACT_BOUNDS = 1 << 3,       // Extract bounds from WebFormControlElement,
                                 // could trigger layout if needed.
  EXTRACT_DATALIST = 1 << 4,     // Extract datalist from WebFormControlElement,
                                 // the total number of options is up to
                                 // kMaxListSize and each option has as far as
                                 // kMaxDataLength.
};

// Autofill supports assigning <label for=x> tags to inputs if x its id/name,
// or the id/name of a shadow host element containing the input.
// This enum is used to track how often each case occurs in practise.
enum class AssignedLabelSource {
  kId = 0,
  kName = 1,
  kShadowHostId = 2,
  kShadowHostName = 3,
  kMaxValue = kShadowHostName,
};
// This temporary histogram is emitted inline, because browser files like
// AutofillMetrics cannot be included here.
// TODO(crbug.com/1339277): Remove.
inline constexpr char kAssignedLabelSourceHistogram[] =
    "Autofill.LabelInference.AssignedLabelSource";

// Indicates if an iframe |element| is considered actually visible to the user.
//
// This function is not intended to implement a perfect visibility check. It
// rather aims to strike balance between cheap tests and filtering invisible
// frames, which can then be skipped during parsing.
//
// The current visibility check requires focusability and a sufficiently large
// bounding box. Thus, particularly elements with "visibility: invisible",
// "display: none", and "width: 0; height: 0" are considered invisible.
//
// Future potential improvements include:
// * Detect potential visibility of elements with "overflow: visible".
//   (See WebElement::GetScrollSize().)
// * Detect invisibility of elements with
//   - "position: absolute; {left,top,right,bottol}: -100px"
//   - "opacity: 0.0"
//   - "clip: rect(0,0,0,0)"
//
// Exposed for testing purposes.
bool IsVisibleIframe(const blink::WebElement& iframe_element);

// Returns the topmost <form> ancestor of |node|, or an IsNull() pointer.
//
// Generally, WebFormElements must not be nested [1]. When parsing HTML, Blink
// ignores nested form tags; the inner forms therefore never make it into the
// DOM. Howevery, nested forms can be created and added to the DOM dynamically,
// in which case Blink associates each field with its closest ancestor.
//
// For some elements, Autofill determines the associated form without Blink's
// help (currently, these are only iframe elements). For consistency with
// Blink's behaviour, we associate them with their closest form element
// ancestor.
//
// [1] https://html.spec.whatwg.org/multipage/forms.html#the-form-element
blink::WebFormElement GetClosestAncestorFormElement(blink::WebNode node);

// Returns true if a DOM traversal (pre-order, depth-first) visits `x` before
// `y`.
// As a performance improvement, `ancestor_hint` can be set to a suspected
// ancestor of `x` and `y`. Otherwise, `ancestor_hint` can be arbitrary.
//
// This function is a simplified/specialised version of Blink's private
// Node::compareDocumentPosition().
//
// Exposed for testing purposes.
bool IsDOMPredecessor(const blink::WebNode& x,
                      const blink::WebNode& y,
                      const blink::WebNode& ancestor_hint);

// Gets up to kMaxListSize data list values (with corresponding label) for the
// given element, each value and label have as far as kMaxDataLength.
void GetDataListSuggestions(const blink::WebInputElement& element,
                            std::vector<std::u16string>* values,
                            std::vector<std::u16string>* labels);

// Extract FormData from the form element and return whether the operation was
// successful.
bool ExtractFormData(const blink::WebFormElement& form_element,
                     const FieldDataManager& field_data_manager,
                     FormData* data);

// Returns true if at least one element from |control_elements| is visible.
bool IsSomeControlElementVisible(
    blink::WebLocalFrame* frame,
    const std::set<FieldRendererId>& control_elements);

// Helper functions to assist in getting the canonical form of the action and
// origin. The action will proplerly take into account <BASE>, and both will
// strip unnecessary data (e.g. query params and HTTP credentials).
GURL GetCanonicalActionForForm(const blink::WebFormElement& form);
GURL GetDocumentUrlWithoutAuth(const blink::WebDocument& document);

// Returns true if |element| is a month input element.
bool IsMonthInput(const blink::WebInputElement& element);

// Returns true if |element| is a text input element.
bool IsTextInput(const blink::WebInputElement& element);

// Returns true if |element| is a select element.
bool IsSelectElement(const blink::WebFormControlElement& element);

// Returns true if |element| is a textarea element.
bool IsTextAreaElement(const blink::WebFormControlElement& element);

// Returns true if `element` is a textarea element or a text input element.
bool IsTextAreaElementOrTextInput(const blink::WebFormControlElement& element);

// Returns true if |element| is a checkbox or a radio button element.
bool IsCheckableElement(const blink::WebInputElement& element);

// Returns true if |element| is one of the input element types that can be
// autofilled. {Text, Radiobutton, Checkbox}.
bool IsAutofillableInputElement(const blink::WebInputElement& element);

// Returns true if |element| is one of the element types that can be autofilled.
// {Text, Radiobutton, Checkbox, Select, TextArea}.
bool IsAutofillableElement(const blink::WebFormControlElement& element);

// True if this node can take focus. If the layout is blocked, then the function
// checks if the element takes up space in the layout, i.e., this element or a
// descendant has a non-empty bounding client rect.
bool IsWebElementFocusable(const blink::WebElement& element);

// A heuristic visibility detection. See crbug.com/1335257 for an overview of
// relevant aspects.
//
// Note that WebElement::BoundsInWidget(), WebElement::GetClientSize(),
// and WebElement::GetScrollSize() include the padding but do not include the
// border and margin. BoundsInWidget() additionally scales the
// dimensions according to the zoom factor.
//
// It seems that invisible fields on websites typically have dimensions between
// 0 and 10 pixels, before the zoom factor. Therefore choosing `kMinPixelSize`
// is easier without including the zoom factor. For that reason, this function
// prefers GetClientSize() over BoundsInWidget().
//
// This function does not check the position in the viewport because fields in
// iframes commonly are visible despite the body having height zero. Therefore,
// `e.GetDocument().Body().BoundsInWidget().Intersects(
//      e.BoundsInWidget())` yields false negatives.
//
// Exposed for testing purposes.
//
// TODO(crbug.com/1335257): Can input fields or iframes actually overflow?
bool IsWebElementVisible(const blink::WebElement& element);

// Returns the form's |name| attribute if non-empty; otherwise the form's |id|
// attribute.
std::u16string GetFormIdentifier(const blink::WebFormElement& form);

// Returns the FormRendererId of a given WebFormElement. If
// WebFormElement::IsNull(), returns a null form renderer id, which is the
// renderer id of the unowned form.
FormRendererId GetFormRendererId(const blink::WebFormElement& form);

// Returns the FieldRendererId of a given WebFormControlElement.
FieldRendererId GetFieldRendererId(const blink::WebFormControlElement& field);

// Returns text alignment for |element|.
base::i18n::TextDirection GetTextDirectionForElement(
    const blink::WebFormControlElement& element);

// Returns all the auto-fillable form control elements in |control_elements|.
std::vector<blink::WebFormControlElement> ExtractAutofillableElementsFromSet(
    const blink::WebVector<blink::WebFormControlElement>& control_elements);

// Returns all the auto-fillable form control elements in |form_element|.
std::vector<blink::WebFormControlElement> ExtractAutofillableElementsInForm(
    const blink::WebFormElement& form_element);

struct ShadowFieldData;

// Fills out a FormField object from a given WebFormControlElement.
// |extract_mask|: See the enum ExtractMask above for details. Field properties
// will be copied from |field_data_manager|, if the argument is not null and
// has entry for |element| (see properties in FieldPropertiesFlags).
void WebFormControlElementToFormField(
    FormRendererId form_renderer_id,
    const blink::WebFormControlElement& element,
    const FieldDataManager* field_data_manager,
    ExtractMask extract_mask,
    FormFieldData* field,
    ShadowFieldData* shadow_data = nullptr);

// Fills |form| with the FormData object corresponding to the |form_element|.
// If |field| is non-NULL, also fills |field| with the FormField object
// corresponding to the |form_control_element|. |extract_mask| controls what
// data is extracted. Returns true if |form| is filled out.  Also returns false
// if there are no fields or too many fields in the |form|. Field properties
// will be copied from |field_data_manager|, if the argument is not null and
// has entry for |element| (see properties in FieldPropertiesFlags).
bool WebFormElementToFormData(
    const blink::WebFormElement& form_element,
    const blink::WebFormControlElement& form_control_element,
    const FieldDataManager* field_data_manager,
    ExtractMask extract_mask,
    FormData* form,
    FormFieldData* field);

// Get all form control elements from |elements| that are not part of a form.
// If |fieldsets| is not NULL, also append the fieldsets encountered that are
// not part of a form.
std::vector<blink::WebFormControlElement> GetUnownedFormFieldElements(
    const blink::WebDocument& document,
    std::vector<blink::WebElement>* fieldsets);

// A shorthand for filtering the results of GetUnownedFormFieldElements with
// ExtractAutofillableElementsFromSet.
std::vector<blink::WebFormControlElement>
GetUnownedAutofillableFormFieldElements(
    const blink::WebDocument& document,
    std::vector<blink::WebElement>* fieldsets);

// Returns the <iframe> elements that are not in the scope of any <form>.
std::vector<blink::WebElement> GetUnownedIframeElements(
    const blink::WebDocument& document);

// Returns false iff the extraction fails because the number of fields exceeds
// |kMaxParseableFields|, or |field| and |element| are not nullptr but
// |element| is not among |control_elements|.
bool UnownedFormElementsAndFieldSetsToFormData(
    const std::vector<blink::WebElement>& fieldsets,
    const std::vector<blink::WebFormControlElement>& control_elements,
    const std::vector<blink::WebElement>& iframe_elements,
    const blink::WebFormControlElement* element,
    const blink::WebDocument& document,
    const FieldDataManager* field_data_manager,
    ExtractMask extract_mask,
    FormData* form,
    FormFieldData* field);

// Finds the form that contains |element| and returns it in |form|.  If |field|
// is non-NULL, fill it with the FormField representation for |element|.
// |additional_extract_mask| control what to extract beside the default mask
// which is EXTRACT_VALUE | EXTRACT_OPTIONS. Returns false if the form is not
// found or cannot be serialized.
bool FindFormAndFieldForFormControlElement(
    const blink::WebFormControlElement& element,
    const FieldDataManager* field_data_manager,
    ExtractMask additional_extract_mask,
    FormData* form,
    FormFieldData* field);

// Same as above but with default ExtractMask.
bool FindFormAndFieldForFormControlElement(
    const blink::WebFormControlElement& element,
    const FieldDataManager* field_data_manager,
    FormData* form,
    FormFieldData* field);

// Fills or previews the form represented by |form|.  |element| is the input
// element that initiated the auto-fill process. Returns the filled fields.
std::vector<blink::WebFormControlElement> FillOrPreviewForm(
    const FormData& form,
    const blink::WebFormControlElement& element,
    mojom::RendererFormDataAction action);

// Clears the suggested values in |control_elements|. The state of
// |initiating_element| is set to |old_autofill_state|; all other fields are set
// to kNotFilled.
void ClearPreviewedElements(
    std::vector<blink::WebFormControlElement>& control_elements,
    const blink::WebFormControlElement& initiating_element,
    blink::WebAutofillState old_autofill_state);

// Indicates if |node| is owned by |frame| in the sense of
// https://dom.spec.whatwg.org/#concept-node-document. Note that being owned by
// a frame does not require being attached to its DOM.
bool IsOwnedByFrame(const blink::WebNode& node, content::RenderFrame* frame);

// Checks if the webpage is empty.
// This kind of webpage is considered as empty:
// <html>
//    <head>
//    </head>
//    <body>
//    </body>
// </html>
// Meta, script and title tags don't influence the emptiness of a webpage.
bool IsWebpageEmpty(const blink::WebLocalFrame* frame);

// This function checks whether the children of |element|
// are of the type <script>, <meta>, or <title>.
bool IsWebElementEmpty(const blink::WebElement& element);

// Previews |suggestion| in |input_element| and highlights the suffix of
// |suggestion| not included in the |input_element| text. |input_element| must
// not be null. |user_input| should be the text typed by the user into
// |input_element|. Note that |user_input| cannot be easily derived from
// |input_element| by calling value(), because of http://crbug.com/507714.
void PreviewSuggestion(const std::u16string& suggestion,
                       const std::u16string& user_input,
                       blink::WebFormControlElement* input_element);

// Returns the aggregated values of the descendants of |element| that are
// non-empty text nodes.  This is a faster alternative to |innerText()| for
// performance critical operations.  It does a full depth-first search so can be
// used when the structure is not directly known.  However, unlike with
// |innerText()|, the search depth and breadth are limited to a fixed threshold.
// Whitespace is trimmed from text accumulated at descendant nodes.
std::u16string FindChildText(const blink::WebNode& node);

// Returns the button titles for |web_form| (or unowned buttons in |document| if
// |web_form| is null). |button_titles_cache| can be used to spare recomputation
// if called multiple times for the same form. Button titles computation for
// unowned buttons is enabled only in Dev and Canary (crbug.com/1086446),
// otherwise the method returns an empty list.
ButtonTitleList GetButtonTitles(const blink::WebFormElement& web_form,
                                const blink::WebDocument& document,
                                ButtonTitlesCache* button_titles_cache);

// Exposed for testing purposes.
std::u16string FindChildTextWithIgnoreListForTesting(
    const blink::WebNode& node,
    const std::set<blink::WebNode>& divs_to_skip);
bool InferLabelForElementForTesting(const blink::WebFormControlElement& element,
                                    std::u16string& label,
                                    FormFieldData::LabelSource& label_source);

// Returns the form element by unique renderer id. Returns the null element if
// there is no form with the |form_renderer_id|.
blink::WebFormElement FindFormByUniqueRendererId(
    const blink::WebDocument& doc,
    FormRendererId form_renderer_id);

// Returns the form control element by unique renderer id. It searches the
// |form_to_be_searched| if specified, otherwise the whole document. Returns the
// null element if there is no element with the |queried_form_control| renderer
// id.
blink::WebFormControlElement FindFormControlElementByUniqueRendererId(
    const blink::WebDocument& doc,
    FieldRendererId queried_form_control,
    absl::optional<FormRendererId> form_to_be_searched = absl::nullopt);

// Note: The vector-based API of the following two functions is a tax for
// limiting the frequency and duration of retrieving a lot of DOM elements.
// Alternative solutions have been discussed on https://crrev.com/c/1108201.

// Returns form control elements identified by the given unique renderer IDs.
// The result has the same number of elements as |queried_form_controls| and
// the i-th element of the result corresponds to the i-th element of
// |queried_form_controls|. The call of this function might be time
// expensive, because it retrieves all DOM elements.
std::vector<blink::WebFormControlElement>
FindFormControlElementsByUniqueRendererId(
    const blink::WebDocument& doc,
    const std::vector<FieldRendererId>& queried_form_controls);

// Returns form control elements by unique renderer id from the form with
// |form_renderer_id|. The result has the same number elements as
// |queried_form_controls| and the i-th element of the result corresponds to
// the i-th element of |queried_form_controls|. This function is faster than
// the previous one, because it only retrieves form control elements from a
// single form.
std::vector<blink::WebFormControlElement>
FindFormControlElementsByUniqueRendererId(
    const blink::WebDocument& doc,
    FormRendererId form_renderer_id,
    const std::vector<FieldRendererId>& queried_form_controls);

// Returns the ARIA label text of the elements denoted by the aria-labelledby
// attribute of |element| or the value of the aria-label attribute of
// |element|, with priority given to the aria-labelledby attribute.
std::u16string GetAriaLabel(const blink::WebDocument& document,
                            const blink::WebElement& element);

// Returns the ARIA label text of the elements denoted by the aria-describedby
// attribute of |element|.
std::u16string GetAriaDescription(const blink::WebDocument& document,
                                  const blink::WebElement& element);

}  // namespace form_util
}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CONTENT_RENDERER_FORM_AUTOFILL_UTIL_H_


text:
package com.google.android.exoplayer2.audio;

import static com.google.android.exoplayer2.RendererCapabilities.ADAPTIVE_NOT_SEAMLESS;
import static com.google.android.exoplayer2.RendererCapabilities.FORMAT_HANDLED;
import static com.google.android.exoplayer2.RendererCapabilities.TUNNELING_NOT_SUPPORTED;
import static com.google.android.exoplayer2.RendererCapabilities.TUNNELING_SUPPORTED;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import androidx.annotation.Nullable;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.RendererConfiguration;
import com.google.android.exoplayer2.decoder.DecoderException;
import com.google.android.exoplayer2.decoder.DecoderInputBuffer;
import com.google.android.exoplayer2.decoder.SimpleDecoder;
import com.google.android.exoplayer2.decoder.SimpleOutputBuffer;
import com.google.android.exoplayer2.drm.ExoMediaCrypto;
import com.google.android.exoplayer2.testutil.FakeSampleStream;
import com.google.android.exoplayer2.util.MimeTypes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;

/** Unit test for {@link DecoderAudioRenderer}. */
@RunWith(AndroidJUnit4.class)
public class DecoderAudioRendererTest {

  private static final Format FORMAT =
      new Format.Builder().setSampleMimeType(MimeTypes.AUDIO_RAW).build();

  @Mock private AudioSink mockAudioSink;
  private DecoderAudioRenderer audioRenderer;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    audioRenderer =
        new DecoderAudioRenderer(null, null, mockAudioSink) {
          @Override
          public String getName() {
            return "TestAudioRenderer";
          }

          @Override
          @FormatSupport
          protected int supportsFormatInternal(Format format) {
            return FORMAT_HANDLED;
          }

          @Override
          protected SimpleDecoder<
                  DecoderInputBuffer, ? extends SimpleOutputBuffer, ? extends DecoderException>
              createDecoder(Format format, @Nullable ExoMediaCrypto mediaCrypto) {
            return new FakeDecoder();
          }

          @Override
          protected Format getOutputFormat() {
            return FORMAT;
          }
        };
  }

  @Config(sdk = 19)
  @Test
  public void supportsFormatAtApi19() {
    assertThat(audioRenderer.supportsFormat(FORMAT))
        .isEqualTo(ADAPTIVE_NOT_SEAMLESS | TUNNELING_NOT_SUPPORTED | FORMAT_HANDLED);
  }

  @Config(sdk = 21)
  @Test
  public void supportsFormatAtApi21() {
    // From API 21, tunneling is supported.
    assertThat(audioRenderer.supportsFormat(FORMAT))
        .isEqualTo(ADAPTIVE_NOT_SEAMLESS | TUNNELING_SUPPORTED | FORMAT_HANDLED);
  }

  @Test
  public void immediatelyReadEndOfStreamPlaysAudioSinkToEndOfStream() throws Exception {
    audioRenderer.enable(
        RendererConfiguration.DEFAULT,
        new Format[] {FORMAT},
        new FakeSampleStream(FORMAT, /* eventDispatcher= */ null, /* shouldOutputSample= */ false),
        /* positionUs= */ 0,
        /* joining= */ false,
        /* mayRenderStartOfStream= */ true,
        /* offsetUs= */ 0);
    audioRenderer.setCurrentStreamFinal();
    when(mockAudioSink.isEnded()).thenReturn(true);
    while (!audioRenderer.isEnded()) {
      audioRenderer.render(0, 0);
    }
    verify(mockAudioSink, times(1)).playToEndOfStream();
    audioRenderer.disable();
    audioRenderer.reset();
    verify(mockAudioSink, times(1)).reset();
  }

  private static final class FakeDecoder
      extends SimpleDecoder<DecoderInputBuffer, SimpleOutputBuffer, DecoderException> {

    public FakeDecoder() {
      super(new DecoderInputBuffer[1], new SimpleOutputBuffer[1]);
    }

    @Override
    public String getName() {
      return "FakeDecoder";
    }

    @Override
    protected DecoderInputBuffer createInputBuffer() {
      return new DecoderInputBuffer(DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DIRECT);
    }

    @Override
    protected SimpleOutputBuffer createOutputBuffer() {
      return new SimpleOutputBuffer(this::releaseOutputBuffer);
    }

    @Override
    protected DecoderException createUnexpectedDecodeException(Throwable error) {
      return new DecoderException("Unexpected decode error", error);
    }

    @Override
    protected DecoderException decode(
        DecoderInputBuffer inputBuffer, SimpleOutputBuffer outputBuffer, boolean reset) {
      if (inputBuffer.isEndOfStream()) {
        outputBuffer.setFlags(C.BUFFER_FLAG_END_OF_STREAM);
      }
      return null;
    }

  }

}


text:
package org.spongepowered.api.event.entity.living.humanoid;

import org.spongepowered.api.data.type.HandType;
import org.spongepowered.api.event.action.InteractEvent;

public interface HandInteractEvent extends InteractEvent {

    /**
     * Gets the {@link HandType} used for interaction.
     *
     * @return The hand type
     */
    HandType getHandType();
}


text:
$(function () {
    $('#searchbox').keyup(function () {
        var searchTerm = $(this).val().toLowerCase();
        $(`.card[data-meta*='${searchTerm}']`).show();
        $('.card').not(`[data-meta*='${searchTerm}']`).hide();

        if (searchTerm.trim() == '') {
            $(".card").show();
        }
        countArtifacts();
    });

    countArtifacts();
});

function countArtifacts() {
    var n = $('a.ui.card:not([style*="display: none"])').length;
    $("#artifactsheader").text("Matching Artifacts (" + n + ")");
};


text:
'''
Test for tracking http://dev.zstack.io/browse/ZSTAC-5595
@author: SyZhao
'''

import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.node_operations as node_ops
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header
import zstackwoodpecker.operations.vm_operations as vm_ops
import test_stub
import threading

vm = None
vm2 = None

def async_exec_reboot_vr(uuid):
    vm_ops.reboot_vm(uuid)

def test():
    global vm, vm2

    test_stub.skip_if_scenario_is_multiple_networks(mul_nets_sce_list=["scenario-config-ceph-sep-man.xml", "scenario-config-ceph-sep-pub.xml"])
    test_stub.skip_if_vr_not_vyos("vr")
    test_lib.clean_up_all_vr()
    vm = test_stub.create_basic_vm()
    vm.check()
    vr_vm = test_lib.lib_find_vr_by_vm(vm.vm)[0]
    vm.destroy()

    t = threading.Thread(target=async_exec_reboot_vr, args=(vr_vm.uuid,))
    t.start()

    vm2 = test_stub.create_basic_vm(wait_vr_running=False)
    vm2.check()
    vm2.destroy()

    test_util.test_pass('Create VM when vyos is rebooting Test Success')

#Will be called what ever test result is
def env_recover():
    pass

#Will be called only if exception happens in test().
def error_cleanup():
    global vm,vm2
    if vm:
        try:
            vm2.destroy()
            vm.destroy()
        except:
            pass


text:
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@android:anim/fade_in"
    android:delay="0%" >
</layoutAnimation>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/video_container"
        android:layout_width="match_parent"
        android:layout_height="200dp">

        <SurfaceView
            android:id="@+id/SurfaceView"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>
    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="prepare"
            android:text="准备"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="play"
            android:text="播放"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="replay"
            android:text="重播"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="changeUrl"
            android:text="切换链接"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="pause"
            android:text="暂停"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="stop"
            android:text="停止"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="release"
            android:text="释放"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="testFullScreen"
            android:text="模拟全屏"/>

    </LinearLayout>

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="getFistImage"
            android:text="获取第一帧"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="getLastImage"
            android:text="获取第最后一帧"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="getCurrentPosition"
            android:text="获取当前播放时长"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="getDuration"
            android:text="获取视频时长"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="isStart"
            android:text="视频是否开始"/>

    </LinearLayout>

    <ImageView
        android:id="@+id/video_image"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>


text:
<?php
$conn = new mysqli("localhost", "root", "", "inout");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
session_start();
$id= $_REQUEST["id"];
?>

<!DOCTYPE HTML>

	<title>Doctor Form</title>
	<link rel="stylesheet" href="css/custom.css">

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="css/landing-page.css" rel="stylesheet">

<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link href="css/profile.css" rel="stylesheet">
<link href="css/profiletab.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Health India

Home

Profile

                        Logout

                      <?php
                         $sql="SELECT  *  from doctor WHERE doctorid='$id'";
                         $result=mysqli_query($conn,$sql);

                          if(mysqli_num_rows($result)>0){
                            $row = mysqli_fetch_assoc($result);

                            echo '

Profile

                          Email
                          '.$row["email"].'

                          Institute
                          '.$row["institute"].'

                          Specialization
                          '.$row["specialization"].'

                          Year Of Passing
                          '.$row["year of passing"].'

                          Hospital
                          '.$row["hospital"].'

                          City
                          '.$row["city"].'

                            ';

                          }
                      ?>


text:
Neutron Code Reviews
====================

Code reviews are a critical component of all OpenStack projects. Neutron accepts patches from many
diverse people with diverse backgrounds, employers, and experience levels. Code reviews provide a
way to enforce a level of consistency across the project, and also allow for the careful on boarding
of contributions from new contributors.

Neutron Code Review Practices
-----------------------------
Neutron follows the `code review guidelines <https://wiki.openstack.org/wiki/ReviewChecklist>`_ as
set forth for all OpenStack projects. It is expected that all reviewers are following the guidelines
set forth on that page.

Neutron Spec Review Practices
-----------------------------
In addition to code reviews, Neutron also maintains a BP specification git repository. Detailed
instructions for the use of this repository are provided `here <https://wiki.openstack.org/wiki/Blueprints>`_.
It is expected that Neutron core team members are actively reviewing specifications which are pushed out
for review to the specification repository. In addition, there is a neutron-drivers team, composed of a
handful of Neutron core reviewers, who can approve and merge Neutron specs.

Some guidelines around this process are provided below:

* Once a specification has been pushed, it is expected that it will not be approved for at least 3 days
  after a first Neutron core reviewer has reviewed it. This allows for additional cores to review the
  specification.
* For blueprints which the core team deems of High or Critical importance, core reviewers may be assigned
  based on their subject matter expertise.
* Specification priority will be set by the PTL with review by the core team once the specification is
  approved.

Tracking Review Statistics
--------------------------
Stackalytics provides some nice interfaces to track review statistics. The links are provided below. These
statistics are used to track not only Neutron core reviewer statistics, but also to track review statistics
for potential future core members.

* `30 day review stats <http://stackalytics.com/report/contribution/neutron-group/30>`_
* `60 day review stats <http://stackalytics.com/report/contribution/neutron-group/60>`_
* `90 day review stats <http://stackalytics.com/report/contribution/neutron-group/90>`_
* `180 day review stats <http://stackalytics.com/report/contribution/neutron-group/180>`_


text:
using System.IdentityModel.Services;
using System.Web.Mvc;

namespace Thinktecture.AuthorizationServer.WebHost.Controllers
{
    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult SignOut()
        {
            if (User.Identity.IsAuthenticated)
            {
                FederatedAuthentication.WSFederationAuthenticationModule.SignOut();
            }
            return View();
        }

    }
}


text:
import xyz

class Libusb(xyz.Package):
    pkg_name = 'libusb'
    uses_osx_frameworks = True
    configure = xyz.Package.host_lib_configure

rules = Libusb


text:
//
//  UFileHttpManager.m
//  ufilesdk
//
//  Created by wu shauk on 12/11/15.
//  Copyright © 2015 ucloud. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "UFileHttpManager.h"
#import "version.h"

/**
 steal from the AfNetwork
 */

#ifndef NSFoundationVersionNumber_iOS_8_0
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11
#else
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0
#endif

static dispatch_queue_t url_session_manager_creation_queue() {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue =
            dispatch_queue_create("com.ucloud.mobile.ufilesdk.session.manager.creation", DISPATCH_QUEUE_SERIAL);
    });

    return queue;
}

static void url_session_manager_create_task_safely(dispatch_block_t block) {
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
        // Fix of bug
        // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
        // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
        dispatch_sync(url_session_manager_creation_queue(), block);
    } else {
        block();
    }
}

static dispatch_queue_t url_session_manager_processing_queue() {
    static dispatch_queue_t queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("com.ucloud.mobile.ufilesdk.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
    });

    return queue;
}

static dispatch_group_t url_session_manager_completion_group() {
    static dispatch_group_t queueGroup;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queueGroup = dispatch_group_create();
    });

    return queueGroup;
}

typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);

typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);

@interface UFileSDKHttpTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@property (nonatomic, weak) UFileHttpManager *manager;
@property (nonatomic, strong) NSMutableData *mutableData;
@property (nonatomic, strong) NSProgress *uploadProgress;
@property (nonatomic, strong) NSProgress *downloadProgress;
@property (nonatomic, copy) NSURL *downloadFileURL;
@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
@end

@implementation UFileSDKHttpTaskDelegate

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.mutableData = [NSMutableData data];
    self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
    self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;

    self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
    self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;
    return self;
}

#pragma mark - NSProgress Tracking

- (void)setupProgressForTask:(NSURLSessionTask *)task {
    __weak __typeof__(task) weakTask = task;

    self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
    self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
    [self.uploadProgress setCancellable:YES];
    [self.uploadProgress setCancellationHandler:^{
        __typeof__(weakTask) strongTask = weakTask;
        [strongTask cancel];
    }];
    [self.uploadProgress setPausable:YES];
    [self.uploadProgress setPausingHandler:^{
        __typeof__(weakTask) strongTask = weakTask;
        [strongTask suspend];
    }];
    if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) {
        [self.uploadProgress setResumingHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask resume];
        }];
    }

    [self.downloadProgress setCancellable:YES];
    [self.downloadProgress setCancellationHandler:^{
        __typeof__(weakTask) strongTask = weakTask;
        [strongTask cancel];
    }];
    [self.downloadProgress setPausable:YES];
    [self.downloadProgress setPausingHandler:^{
        __typeof__(weakTask) strongTask = weakTask;
        [strongTask suspend];
    }];

    if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) {
        [self.downloadProgress setResumingHandler:^{
            __typeof__(weakTask) strongTask = weakTask;
            [strongTask resume];
        }];
    }

    [task addObserver:self
           forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))
              options:NSKeyValueObservingOptionNew
              context:NULL];
    [task addObserver:self
           forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))
              options:NSKeyValueObservingOptionNew
              context:NULL];

    [task addObserver:self
           forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))
              options:NSKeyValueObservingOptionNew
              context:NULL];
    [task addObserver:self
           forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))
              options:NSKeyValueObservingOptionNew
              context:NULL];

    [self.downloadProgress addObserver:self
                            forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
                               options:NSKeyValueObservingOptionNew
                               context:NULL];
    [self.uploadProgress addObserver:self
                          forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
                             options:NSKeyValueObservingOptionNew
                             context:NULL];
}

- (void)cleanUpProgressForTask:(NSURLSessionTask *)task {
    [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
    [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))];
    [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
    [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))];
    [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
    [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([object isKindOfClass:[NSURLSessionTask class]]) {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
            self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue];
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) {
            self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue];
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
            self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue];
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) {
            self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue];
        }
    }
    else if ([object isEqual:self.downloadProgress]) {
        if (self.downloadProgressBlock) {
            self.downloadProgressBlock(object);
        }
    }
    else if ([object isEqual:self.uploadProgress]) {
        if (self.uploadProgressBlock) {
            self.uploadProgressBlock(object);
        }
    }
}

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(__unused NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
    __strong UFileHttpManager *manager = self.manager;

    __block id responseObject = nil;

    //Performance Improvement from #2672
    if (self.mutableData) {
        responseObject = [self.mutableData copy];
        //We no longer need the reference, so nil it out to gain back some memory.
        self.mutableData = nil;
    }

    if (error) {

        dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
            if (self.completionHandler) {
                self.completionHandler(task.response, responseObject, error);
            }
        });
    } else {
        dispatch_async(url_session_manager_processing_queue(), ^{

            if (self.downloadFileURL) {
                responseObject = self.downloadFileURL;
            }

            dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
                if (self.completionHandler) {
                    self.completionHandler(task.response, responseObject, nil);
                }
            });
        });
    }
#pragma clang diagnostic pop
}

#pragma mark - NSURLSessionDataTaskDelegate

- (void)URLSession:(__unused NSURLSession *)session
          dataTask:(__unused NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    [self.mutableData appendData:data];
}

#pragma mark - NSURLSessionDownloadTaskDelegate

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSError *fileManagerError = nil;
    self.downloadFileURL = nil;

    if (self.downloadTaskDidFinishDownloading) {
        self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
        if (self.downloadFileURL) {
            [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
        }
    }
}

@end

@interface UFileHttpManager ()

@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks;
@property (readwrite, nonatomic, strong) NSLock *lock;

@property (readonly, nonatomic, strong) NSURLSession * defaultSession;
@property (readonly, nonatomic, strong) NSURLSession * downloadSession;
@end

@implementation UFileHttpManager

-(instancetype)init
{
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    _defaultSession = [NSURLSession sessionWithConfiguration:config
                                                    delegate:self
                                               delegateQueue:self.operationQueue];

    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
    return self;
}

- (NSString *)taskDescriptionForSessionTasks {
    return [NSString stringWithFormat:@"%p", self];
}

- (NSURLSessionDataTask *)Post:(NSURL *)URL
                  headerParams:(NSArray*)headerParams
                          body:(NSData*)body
                      progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                       success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                       failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSMutableURLRequest *request =
        [[NSMutableURLRequest alloc]
         initWithURL:URL];
    request.HTTPMethod = @"POST";

    for (NSArray* item in headerParams) {
        [request addValue:item[1] forHTTPHeaderField:item[0]];
    }
    [request addValue:[NSString stringWithFormat:@"UFile iOS/%@", @(UFILE_IOS_SDK_VERSION)] forHTTPHeaderField:@"UserAgent"];
    [request setHTTPBody:body];
    __block NSURLSessionDataTask *dataTask =
    [self dataTaskWithRequest:request
               uploadProgress:uploadProgress
             downloadProgress:nil
            completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                if (error) {
                    if (failure) {
                        failure(dataTask, error);
                    }
                } else {
                    if (success) {
                        success(dataTask, responseObject);
                    }
                }
            }];

    [dataTask resume];

    return dataTask;
}

- (NSURLSessionDataTask *) Put:(NSURL *)URL
                  headerParams:(NSArray*)headerParams
                          body:(NSData*)body
                      progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                       success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                       failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc]
     initWithURL:URL];
    request.HTTPMethod = @"PUT";

    for (NSArray* item in headerParams) {
        [request addValue:item[1] forHTTPHeaderField:item[0]];
    }
    [request addValue:[NSString stringWithFormat:@"UFile iOS/%@", @(UFILE_IOS_SDK_VERSION)] forHTTPHeaderField:@"UserAgent"];
    [request setHTTPBody:body];
    __block NSURLSessionDataTask *dataTask =
    [self dataTaskWithRequest:request
               uploadProgress:uploadProgress
             downloadProgress:nil
            completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                if (error) {
                    if (failure) {
                        failure(dataTask, error);
                    }
                } else {
                    if (success) {
                        success(dataTask, responseObject);
                    }
                }
            }];

    [dataTask resume];

    return dataTask;
}

-(NSURLSessionDataTask*) Get:(NSURL *)URL
                headerParams:(NSArray *)headerParams
                     queries:(NSArray *)queries
                    progress:(void (^)(NSProgress * _Nonnull))downloadProgress
                     success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                     failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc]
     initWithURL:URL];
    request.HTTPMethod = @"GET";

    for (NSArray* item in headerParams) {
        [request addValue:item[1] forHTTPHeaderField:item[0]];
    }
    [request addValue:[NSString stringWithFormat:@"UFile iOS/%@", @(UFILE_IOS_SDK_VERSION)] forHTTPHeaderField:@"UserAgent"];
    if (queries) {
        NSString * qs = nil;
        NSMutableString *queryString = [NSMutableString stringWithString:@"?"];
        for (NSArray* item in queries) {
            [queryString appendFormat:@"%@=%@&", item[0],UFilePercentEscapedStringFromString(item[1])];
        }
        qs = [queryString substringToIndex:([queryString length]-1)];
        URL = [NSURL URLWithString:[[URL path] stringByAppendingString:qs]];
    }

    __block NSURLSessionDataTask *dataTask =
    [self dataTaskWithRequest:request
               uploadProgress:nil
             downloadProgress:downloadProgress
            completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                if (error) {
                    if (failure) {
                        failure(dataTask, error);
                    }
                } else {
                    if (success) {
                        success(dataTask, responseObject);
                    }
                }
            }];

    [dataTask resume];

    return dataTask;
}

-(NSURLSessionDataTask*) Head:(NSURL *)URL
                headerParams:(NSArray *)headerParams
                     success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                     failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc]
     initWithURL:URL];
    request.HTTPMethod = @"HEAD";

    for (NSArray* item in headerParams) {
        [request addValue:item[1] forHTTPHeaderField:item[0]];
    }
    [request addValue:[NSString stringWithFormat:@"UFile iOS/%@", @(UFILE_IOS_SDK_VERSION)] forHTTPHeaderField:@"UserAgent"];
    __block NSURLSessionDataTask *dataTask =
    [self dataTaskWithRequest:request
               uploadProgress:nil
             downloadProgress:nil
            completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                if (error) {
                    if (failure) {
                        failure(dataTask, error);
                    }
                } else {
                    if (success) {
                        success(dataTask, responseObject);
                    }
                }
            }];

    [dataTask resume];

    return dataTask;
}

-(NSURLSessionDataTask*) Delete:(NSURL *)URL
                 headerParams:(NSArray *)headerParams
                      success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                      failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc]
     initWithURL:URL];
    request.HTTPMethod = @"DELETE";

    for (NSArray* item in headerParams) {
        [request addValue:item[1] forHTTPHeaderField:item[0]];
    }
    [request addValue:[NSString stringWithFormat:@"UFile iOS/%@", @(UFILE_IOS_SDK_VERSION)] forHTTPHeaderField:@"UserAgent"];
    __block NSURLSessionDataTask *dataTask =
    [self dataTaskWithRequest:request
               uploadProgress:nil
             downloadProgress:nil
            completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                if (error) {
                    if (failure) {
                        failure(dataTask, error);
                    }
                } else {
                    if (success) {
                        success(dataTask, responseObject);
                    }
                }
            }];

    [dataTask resume];

    return dataTask;
}

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromFile:(NSURL *)fileURL
                                         progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    __block NSURLSessionUploadTask *uploadTask = nil;
    url_session_manager_create_task_safely(^{
        uploadTask = [self.defaultSession uploadTaskWithRequest:request fromFile:fileURL];
    });

    if (!uploadTask) {
        return nil;
    }
    [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];

    return uploadTask;
}

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
                                             progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    __block NSURLSessionDownloadTask *downloadTask = nil;
    url_session_manager_create_task_safely(^{
        downloadTask = [self.defaultSession downloadTaskWithRequest:request];
    });

    [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];

    return downloadTask;
}

- (void)setDelegate:(UFileSDKHttpTaskDelegate *)delegate
            forTask:(NSURLSessionTask *)task
{
    NSParameterAssert(task);
    NSParameterAssert(delegate);
    [self.lock lock];
    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
    [delegate setupProgressForTask:task];
    [self.lock unlock];
}

- (UFileSDKHttpTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);

    UFileSDKHttpTaskDelegate *delegate = nil;
    [self.lock lock];
    delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
    [self.lock unlock];

    return delegate;
}

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler {

    __block NSURLSessionDataTask *dataTask = nil;
    url_session_manager_create_task_safely(^{
        dataTask = [self.defaultSession dataTaskWithRequest:request];
        NSLog(@"%@", dataTask);
    });

    [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];

    return dataTask;
}

- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
                uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
              downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
             completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    UFileSDKHttpTaskDelegate *delegate = [[UFileSDKHttpTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    dataTask.taskDescription = self.taskDescriptionForSessionTasks;
    [self setDelegate:delegate forTask:dataTask];

    delegate.uploadProgressBlock = uploadProgressBlock;
    delegate.downloadProgressBlock = downloadProgressBlock;
}

- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
                        progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
               completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    UFileSDKHttpTaskDelegate *delegate = [[UFileSDKHttpTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    uploadTask.taskDescription = self.taskDescriptionForSessionTasks;

    [self setDelegate:delegate forTask:uploadTask];

    delegate.uploadProgressBlock = uploadProgressBlock;
}

- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
                          progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                       destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                 completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    UFileSDKHttpTaskDelegate *delegate = [[UFileSDKHttpTaskDelegate alloc] init];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;

    if (destination) {
        delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
            return destination(location, task.response);
        };
    }

    downloadTask.taskDescription = self.taskDescriptionForSessionTasks;

    [self setDelegate:delegate forTask:downloadTask];

    delegate.downloadProgressBlock = downloadProgressBlock;
}

- (void)removeDelegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);

    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:task];
    [self.lock lock];
    [delegate cleanUpProgressForTask:task];
    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
    [self.lock unlock];
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
    NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;

    if (completionHandler) {
        completionHandler(disposition);
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{
    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:dataTask];
    if (delegate) {
        [self removeDelegateForTask:dataTask];
        [self setDelegate:delegate forTask:downloadTask];
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{

    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:dataTask];
    [delegate URLSession:session dataTask:dataTask didReceiveData:data];
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
 willCacheResponse:(NSCachedURLResponse *)proposedResponse
 completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
{
    if (completionHandler) {
        completionHandler(nil);
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:task];

    // delegate may be nil when completing a task in the background
    if (delegate) {
        [delegate URLSession:session task:task didCompleteWithError:error];

        [self removeDelegateForTask:task];
    }

}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
}

#pragma mark - NSURLSessionDownloadDelegate

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:downloadTask];
    if (delegate) {
        [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
    }
}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{

}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    UFileSDKHttpTaskDelegate *delegate = [self delegateForTask:downloadTask];
    [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
}

#pragma mark - NSURLSessionDelegate

@end

NSString * UFilePercentEscapedStringFromString(NSString *string) {
    static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@?/"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
    static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";

    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];

    return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
}


text:
$(document).ready(function() {
	navResponse();
})

$(window).resize(function() {
	navResponse();
})

function navResponse() {
	if ($(window).width() < 980) {
		// Display sidebar along the top.
		$('ul.nav-collapse-primary').css('height','auto');
		$('ul.nav-collapse-primary li').css('display', 'inline-block');
		$('ul.nav-collapse-primary li > span.glow').css('display', 'none');
		$('ul.nav-collapse-primary li.active a').css('color', '#ccc');
	} else {
		// Put it back the way it was.
		$('ul.nav-collapse-primary').css('height','inherit');
		$('ul.nav-collapse-primary li > span.glow').css('display', 'block');
		$('ul.nav-collapse-primary li').css('display', 'inherit');
		$('ul.nav-collapse-primary li.active a').css('color', '#939ea4');
	}
}


text:
#ifndef BOOST_POLY_COLLECTION_DETAIL_IS_EQUALITY_COMPARABLE_HPP
#define BOOST_POLY_COLLECTION_DETAIL_IS_EQUALITY_COMPARABLE_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/type_traits/has_equal_to.hpp>
#include <type_traits>

namespace boost{

namespace poly_collection{

namespace detail{

template<typename T>
using is_equality_comparable=std::integral_constant<
  bool,
  has_equal_to<T,T,bool>::value
>;

} /* namespace poly_collection::detail */

} /* namespace poly_collection */

} /* namespace boost */

#endif


text:
package com.caramel.restaurant.model.view.foodscroller;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class AddButtonBean implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -117768526281429448L;

	private FoodDAO foodDao = new FoodDAOImpl();

	private String name;
	private String desc;
	private String cat;

	public void addMessage(String summary) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary,  null);
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void saveMenu(){
		foodDao.save(new Food(name, desc, cat));
		addMessage("success");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public String getCat() {
		return cat;
	}

	public void setCat(String cat) {
		this.cat = cat;
	}
}