text:
import asyncio
import collections
import logging

from elasticsearch.connection_pool import RoundRobinSelector

logger = logging.getLogger('elasticsearch')

class ConnectionPool:
    def __init__(self, connections, *, dead_timeout=60, timeout_cutoff=5,
                 selector_factory=RoundRobinSelector,
                 loop):
        self._dead_timeout = dead_timeout
        self._timeout_cutoff = timeout_cutoff
        self._selector = selector_factory(None)
        self._dead = asyncio.PriorityQueue(len(connections), loop=loop)
        self._dead_count = collections.Counter()
        self._connections = connections
        self._loop = loop

    def close(self):
        for connection in self._connections:
            connection.close()

        while not self._dead.empty():
            _, connection = self._dead.get_nowait()
            connection.close()

        ret = asyncio.Future(loop=self._loop)
        ret.set_result(None)
        return ret

    @property
    def connections(self):
        return list(self._connections)

    async def mark_dead(self, connection):
        """
        Mark the connection as dead (failed). Remove it from the live pool and
        put it on a timeout.

        :arg connection: the failed instance
        """
        now = self._loop.time()
        try:
            self._connections.remove(connection)
        except ValueError:
            # connection not alive or another thread marked it already, ignore
            return
        else:
            self._dead_count[connection] += 1
            dead_count = self._dead_count[connection]
            timeout = self._dead_timeout * 2 ** min(dead_count - 1,
                                                    self._timeout_cutoff)
            await self._dead.put((now + timeout, connection))
            logger.warning(
                "Connection %r has failed for %i times in a row, "
                "putting on %i second timeout.",
                connection, dead_count, timeout
            )

    async def mark_live(self, connection):
        """
        Mark connection as healthy after a resurrection. Resets the fail
        counter for the connection.

        :arg connection: the connection to redeem
        """
        del self._dead_count[connection]

    async def resurrect(self, force=False):
        """
        Attempt to resurrect a connection from the dead pool. It will try to
        locate one (not all) eligible (it's timeout is over) connection to
        return to th live pool.

        :arg force: resurrect a connection even if there is none eligible (used
            when we have no live connections)
        """
        if self._dead.empty():
            return

        timeout, connection = self._dead.get_nowait()

        if not force and timeout > self._loop.time():
            # return it back if not eligible and not forced
            await self._dead.put((timeout, connection))
            return

        # either we were forced or the connection is elligible to be retried
        self._connections.append(connection)
        logger.info('Resurrecting connection %r (force=%s).',
                    connection, force)

    async def get_connection(self):
        """
        Return a connection from the pool using the `ConnectionSelector`
        instance.

        It tries to resurrect eligible connections, forces a resurrection when
        no connections are availible and passes the list of live connections to
        the selector instance to choose from.

        Returns a connection instance
        """
        await self.resurrect()

        # no live nodes, resurrect one by force
        if not self._connections:
            await self.resurrect(True)

        connection = self._selector.select(self._connections)

        return connection


text:
![release level](https://img.shields.io/badge/release%20level-%20alpha-red.svg)

A generator and runtime for protocol buffer described APIs for and in C++.

This repository contains two subprojects:
- An API client library generator, implemented as a protoc plugin
- A runtime library supporting the generated code (known as gax)

The generator takes APIs specified by protocol buffers, such as those inside Google,
and generates a client library.

**Note:** this project has been shelved. See [`STATUS.md`](STATUS.md) for the current status of various features and designs.

## Versioning

This library follows [Semantic Versioning](http://semver.org/). Please note it
is currently under active development. Any release versioned 0.x.y is subject to
backwards-incompatible changes at any time.

**GA**: Libraries defined at a GA quality level are expected to be stable and
all updates in the libraries are guaranteed to be backwards-compatible. Any
backwards-incompatible changes will lead to the major version increment
(1.x.y -> 2.0.0).

**Beta**: Libraries defined at a Beta quality level are expected to be mostly
stable and we're working towards their release candidate. We will address issues
and requests with a higher priority.

**Alpha**: Libraries defined at an Alpha quality level are still a
work-in-progress and are more likely to get backwards-incompatible updates.
Additionally, it's possible for Alpha libraries to get deprecated and deleted
before ever being promoted to Beta or GA.

## Contributing changes

See [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to contribute to
this project, including how to build and test your changes as well as how to
properly format your code.

## Licensing

Apache 2.0; see [`LICENSE`](LICENSE) for details.

redpajama_set_name: RedPajamaGithub


text:
package org.la4j.factory;

import org.la4j.linear.LinearSystem;
import org.la4j.matrix.Matrix;
import org.la4j.vector.Vector;

public abstract class AbstractFactory implements Factory {

    private static final long serialVersionUID = 4071505L;

    @Override
    public LinearSystem createLinearSystem(Matrix a, Vector b) {
        return new LinearSystem(a, b, this);
    }
}


text:
<?php
include 'AutoCheck.php';
$post_id=$_GET['post_id'];
$uid=$_GET['uid'];
$link = mysql_connect('localhost', 'root','systemachinist' ,'work');
mysql_select_db('work',$link);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
//mysql_query("delete from upvote where post_id='".$post_id."' and uid='".$uid."'",$link);
mysql_query("insert into upvote values('".$post_id."','".$uid."')",$link);
//echo "Upvote!";
header("Location:Notifications.php");
?>


text:
{% extends "base.html" %}
{% from "challenges/helpers.html" import created_by with context %}

{% block page_title %}{{ _('Winning submissions') }} | {% endblock %}

{% block page_id %}winning_submissions{% endblock %}

{% block section_class %}entries{% endblock %}

{% block content %}
{% if winners %}

Winning ideas

    {% if phase.name == 'Ideation' %}

        {% for entry in winners %}
            {% include "challenges/includes/winning_entry.html"%}
        {% endfor %}

    {% else %}

Winning applications

        {% for group in development_winners|groupby('phase_round') %}
            {% if group.grouper %}
{{ group.grouper.name }}
{% endif %}

            {% for entry in group.list %}
                {% include "challenges/includes/winning_entry.html"%}
            {% endfor%}

        {% endfor %}
    {% endif %}
{% endif %}
{% endblock %}


text:
package net.fortytwo.smsn.brain.io.edges;

import net.fortytwo.smsn.brain.io.Format;

public class EdgeTSVFormat extends Format {
    private static final EdgeTSVFormat instance = new EdgeTSVFormat();

    private EdgeTSVFormat() {
        super("Edges", Type.FileBased, "tsv");
    }

    public static EdgeTSVFormat getInstance() {
        return instance;
    }
}


text:
{% fetch /api/product/sort_info > sort_info %}

		{% assign base_url = "" | url_remove_param: "page" %}
		{% assign request_order = base_url | url_get_param: "order" %}
		{% for sort_order in sort_info.sort_orders %}
		{% assign title = sort_order.name | trans %}
		{% if request_order == sort_order.value %}
		{{ title }}
		{% else %}
		{{ title }}
		{% endif %}
		{% endfor %}
		<input class="form-control price-lower-bound" value="0" />
		 ~
		<input class="form-control price-upper-bound" value="0" />
		{{ "FilterByPrice" | trans }}
		{{ "Cancel" | trans }}


text:
/**
 * Created by jayeshkawli on 1/11/15.
 */
$('#clock-one-title, #clock-two-title, #clock-three-title, #clock-four-title, #clock-five-title, #clock-six-title').jrumble({
    speed: 50
});

$('#clock-one-title, #clock-two-title, #clock-three-title, #clock-four-title, #clock-five-title, #clock-six-title').hover(function(){
    $(this).trigger('startRumble');
}, function(){
    $(this).trigger('stopRumble');
});


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34209
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Demo.Domain.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Demo.Domain.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The guarantor's first name is missing..
        /// </summary>
        public static string GuarantorFirstNameRequired {
            get {
                return ResourceManager.GetString("GuarantorFirstNameRequired", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The guarantor's last name is missing..
        /// </summary>
        public static string GuarantorLastNameRequired {
            get {
                return ResourceManager.GetString("GuarantorLastNameRequired", resourceCulture);
            }
        }
    }
}


text:
package org.wso2.developerstudio.bpmn.extensions.soapTask;

import org.activiti.designer.integration.annotation.Help;
import org.activiti.designer.integration.annotation.Property;
import org.activiti.designer.integration.annotation.PropertyItems;
import org.activiti.designer.integration.annotation.Runtime;
import org.activiti.designer.integration.servicetask.AbstractCustomServiceTask;
import org.activiti.designer.integration.servicetask.PropertyType;

/**
 * SOAP Task Activity Designer implementation.
 *
 * @See org.wso2.carbon.bpmn.extensions.soap.SOAPTask
 */
@Runtime(javaDelegateClass = SOAPConstants.SOAP_TASK_CLASS)
@Help(displayHelpShort = SOAPConstants.SOAP_TASK_HELP, displayHelpLong = SOAPConstants.SOAP_TASK_HELP_LONG)
public class SOAPTask extends AbstractCustomServiceTask {

    @Override
    public String getName() {
        return SOAPConstants.SOAP_TASK_NAME;
    }

    @Override
    public String contributeToPaletteDrawer() {
        return SOAPConstants.PALETTE_WSO2;
    }

    @Override
    public String getSmallIconPath() {
        return SOAPConstants.ICONS_SOAP_TASK;
    }

    /**
     * @See SOAPConstants.SERVICE_URL_HELP_LONG
     */
    @Property(type = PropertyType.TEXT, displayName = SOAPConstants.SERVICE_URL_LABEL, required = true)
    @Help(displayHelpShort = SOAPConstants.SERVICE_URL_HELP, displayHelpLong = SOAPConstants.SERVICE_URL_HELP_LONG)
    private String serviceURL;

    /**
     * @See SOAPConstants.INPUT_HELP_LONG
     */
    @Property(type = PropertyType.MULTILINE_TEXT, displayName = SOAPConstants.INPUT_LABEL, required = true)

    @Help(displayHelpShort = SOAPConstants.INPUT_HELP, displayHelpLong = SOAPConstants.INPUT_HELP_LONG)
    private String payload;

    /**
     * @See SOAPConstants.HEADER_BLOCK_HELP_LONG
     */
    @Property(type = PropertyType.MULTILINE_TEXT, displayName = SOAPConstants.HEADER_BLOCK_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.HEADER_BLOCK_HELP, displayHelpLong = SOAPConstants.HEADER_BLOCK_HELP_LONG)
    private String headers;

    /**
     * @See SOAPConstants.SOAP_VERSION_HELP_LONG
     */
    @Property(type = PropertyType.COMBOBOX_CHOICE, displayName = SOAPConstants.SOAP_VERSION_LABEL, required = false)
    @PropertyItems({SOAPConstants.SOAP11_LABEL, SOAPConstants.SOAP11_VALUE, SOAPConstants.SOAP12_LABEL, SOAPConstants
            .SOAP12_VALUE})
    @Help(displayHelpShort = SOAPConstants.SOAP_VERSION_HELP, displayHelpLong = SOAPConstants.SOAP_VERSION_HELP_LONG)
    private String soapVersion;

    /**
     * @See SOAPConstants.HTTP_CONNECTION_HELP_LONG
     */
    @Property(type = PropertyType.TEXT, displayName = SOAPConstants.HTTP_CONNECTION_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.HTTP_CONNECTION_HELP, displayHelpLong = SOAPConstants
            .HTTP_CONNECTION_HELP_LONG)
    private String httpConnection;

    /**
     * @See SOAPConstants.HTTP_TRANSFER_ENCODING_HELP_LONG
     */
    @Property(type = PropertyType.TEXT, displayName = SOAPConstants.HTTP_TRANSFER_ENCODING_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.HTTP_TRANSFER_ENCODING_HELP, displayHelpLong = SOAPConstants
            .HTTP_TRANSFER_ENCODING_HELP_LONG)
    private String httpTransferEncoding;

    /**
     * @See SOAPConstants.OUTPUT_VARIABLE_HELP_LONG
     */
    @Property(type = PropertyType.TEXT, displayName = SOAPConstants.OUTPUT_VARIABLE_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.OUTPUT_VARIABLE_HELP, displayHelpLong = SOAPConstants
            .OUTPUT_VARIABLE_HELP_LONG)
    private String outputVariable;

    /**
     * @See SOAPConstants.SOAP_ACTION_HELP_LONG
     */
    @Property(type = PropertyType.TEXT, displayName = SOAPConstants.SOAP_ACTION_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.SOAP_ACTION_HELP, displayHelpLong = SOAPConstants.SOAP_ACTION_HELP_LONG)
    private String soapAction;

    /**
     * @See SOAPConstants.TRANSPORT_HEADERS_HELP_LONG
     */
    @Property(type = PropertyType.MULTILINE_TEXT, displayName = SOAPConstants.TRANSPORT_HEADERS_LABEL, required = false)
    @Help(displayHelpShort = SOAPConstants.TRANSPORT_HEADERS_HELP, displayHelpLong = SOAPConstants
            .TRANSPORT_HEADERS_HELP_LONG)
    private String transportHeaders;

}


text:
package com.drillster.api2.drill;

import java.util.Comparator;
import java.util.Date;

public class DrillableAddedComparator implements Comparator<Drillable> {

	@Override
	public int compare(Drillable one, Drillable two) {
		Date date1 = one.getPractice() == null ? null : one.getPractice().getAdded();
		Date date2 = two.getPractice() == null ? null : two.getPractice().getAdded();

		if (date1 == null && date2 == null) {
			return 0;
		}
		if (date1 == null) {
			return -1;
		}
		if (date2 == null) {
			return 1;
		}
		return date1.compareTo(date2);
	}

}


text:
<?

class AjaxActionGetGainTypes implements IAjaxAction {
	/** @var JsonPrinter */
	private $JsonPrinter;

	/** @var GainTypesFacade */
	private $GainTypes;

	public function __construct(JsonPrinter $JsonPrinter, GainTypesFacade $Repository) {
		$this->JsonPrinter = $JsonPrinter;
		$this->GainTypes = $Repository;
	}

	public function assignData($data) {
		return $this;
	}

	public function run() {
		$types = $this->GainTypes->getSerializedGainTypes();
		$this->JsonPrinter->printAsJsonAndDie($types);
	}
}


text:
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar;

import com.google.common.base.Supplier;
import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction;
import hudson.model.*;
import hudson.plugins.claim.ClaimBuildAction;
import hudson.scm.ChangeLogSet;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.bfa.AnalysedTest.failureCauseBuildAction;
import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.plugins.claim.ClaimedTest.claimBuildAction;
import static org.mockito.Mockito.*;

/**
 * @author Jan Molak
 */
public class BuildStateRecipe implements Supplier<AbstractBuild<?, ?>> {

    private AbstractBuild<?, ?> build;

    public BuildStateRecipe() {
        build = mock(AbstractBuild.class);

        AbstractProject parent = mock(AbstractProject.class);
        when(build.getParent()).thenReturn(parent);
    }

    public BuildStateRecipe hasNumber(int number) {
        when(build.getNumber()).thenReturn(number);

        // see hudson.model.Run::getDisplayName
        return hasName("#" + number);
    }

    public BuildStateRecipe hasName(String name) {
        when(build.getDisplayName()).thenReturn(name);

        return this;
    }

    public BuildStateRecipe whichNumberIs(int number) {
        return hasNumber(number);
    }

    public BuildStateRecipe finishedWith(Result result) {
        when(build.getResult()).thenReturn(result);

        return this;
    }

    public BuildStateRecipe withChangesFrom(String... authors) {
        ChangeLogSet changeSet = changeSetBasedOn(entriesBy(authors));
        when(build.getChangeSet()).thenReturn(changeSet);

        // any methods that use getChangeSet as their source of data should be called normally
        // (build is a partial mock in this case)
        when(build.getCulprits()).thenCallRealMethod();

        return this;
    }

    public BuildStateRecipe succeededThanksTo(String... authors) {
        finishedWith(Result.SUCCESS);
        withChangesFrom(authors);

        return this;
    }

    public BuildStateRecipe wasBrokenBy(String... culprits) {
        finishedWith(Result.FAILURE);
        withChangesFrom(culprits);

        return this;
    }

    public BuildStateRecipe hasntStartedYet() {
        when(build.hasntStartedYet()).thenReturn(true);

        return this;
    }

    public BuildStateRecipe isStillBuilding() {
        when(build.isBuilding()).thenReturn(true);

        return this;
    }

    public BuildStateRecipe isStillUpdatingTheLog() {
        when(build.isLogUpdated()).thenReturn(true);

        return this;
    }

    public BuildStateRecipe startedAt(String time) throws Exception {
        long startedAt = new SimpleDateFormat("H:m:s").parse(time).getTime();

        Calendar timestamp = mock(Calendar.class);
        when(build.getTimestamp()).thenReturn(timestamp);

        when(timestamp.getTimeInMillis()).thenReturn(startedAt);

        return this;
    }

    public BuildStateRecipe took(int minutes) throws Exception{
        long duration = (long) minutes * 60 * 1000;

        when(build.getDuration()).thenReturn(duration);

        return this;
    }

    public BuildStateRecipe usuallyTakes(int minutes) throws Exception{
        long duration = (long) minutes * 60 * 1000;

        when(build.getEstimatedDuration()).thenReturn(duration);

        return this;
    }

    public BuildStateRecipe wasClaimedBy(String aPotentialHero, String reason) {
        final ClaimBuildAction action = claimBuildAction(aPotentialHero, reason);
        when(build.getAction(ClaimBuildAction.class)).thenReturn(action);

        return this;
    }

    public BuildStateRecipe knownFailures(String... failures) {
        final FailureCauseBuildAction action = failureCauseBuildAction(failures);
        when(build.getAction(FailureCauseBuildAction.class)).thenReturn(action);

        return this;
    }

    public BuildStateRecipe and() {
        return this;
    }

    @Override
    public AbstractBuild get() {
        return build;
    }

    private List<ChangeLogSet.Entry> entriesBy(String... authors) {
        List<ChangeLogSet.Entry> entries = new ArrayList<ChangeLogSet.Entry>();

        for (String name : authors) {
            User author = mock(User.class);
            ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);

            when(author.getFullName()).thenReturn(name);
            when(entry.getAuthor()).thenReturn(author);

            entries.add(entry);
        }
        return entries;
    }

    private ChangeLogSet changeSetBasedOn(final List<ChangeLogSet.Entry> entries) {
        return new ChangeLogSet<ChangeLogSet.Entry>(null) {
            @Override
            public boolean isEmptySet() {
                return false;
            }

            public Iterator<Entry> iterator() {
                return entries.iterator();
            }
        };
    }
}


text:
[![Build Status](https://travis-ci.org/kikito/bump.lua.svg?branch=master)](https://travis-ci.org/kikito/bump.lua)

Lua collision-detection library for axis-aligned rectangles. Its main features are:

* bump.lua only does axis-aligned bounding-box (AABB) collisions. If you need anything more complicated than that (circles, polygons, etc.) give [HardonCollider](https://github.com/vrld/HardonCollider) a look.
* Handles tunnelling - all items are treated as "bullets". The fact that we only use AABBs allows doing this fast.
* Strives to be fast while being economic in memory
* It's centered on *detection*, but it also offers some (minimal & basic) *collision response*
* Can also return the items that touch a point, a segment or a rectangular zone.
* bump.lua is _gameistic_ instead of realistic.

The demos are LÖVE based, but this library can be used in any Lua-compatible environment.

`bump` is ideal for:

* Tile-based games, and games where most entities can be represented as axis-aligned rectangles.
* Games which require some physics, but not a full realistic simulation - like a platformer.
* Examples of genres: top-down games (Zelda), Shoot-them-ups, fighting games (Street Fighter), platformers (Super Mario).

`bump` is not a good match for:

* Games that require polygons for the collision detection
* Games that require highly realistic simulations of physics - things "stacking up", "rolling over slides", etc.
* Games that require very fast objects colliding reallistically against each other (in bump, being _gameistic_, objects are moved and collided _one at a time_)
* Simulations where the order in which the collisions are resolved isn't known.

## Example

```lua

local bump = require 'bump'

-- The grid cell size can be specified via the initialize method
-- By default, the cell size is 32
local world = bump.newWorld(50)

-- create two rectangles
local A = {name="A"}
local B = {name="B"}

-- insert both rectangles into bump
world:add(A,   0, 0,    64, 256) -- x,y, width, height
world:add(B,   0, -100, 32, 32)

-- Try to move B to 0,64. If it collides with A, "slide over it"
local actualX, actualY, cols, len = world:move(B, 0,64)

-- prints "Attempted to move to 0,64, but ended up in 0,-32 due to 1 collisions"
if len > 0 then
  print(("Attempted to move to 0,64, but ended up in %d,%d due to %d collisions"):format(actualX, actualY, len))
else
  print("Moved B to 100,100 without collisions")
end

-- prints the new coordinates of B: 0, -32, 32, 32
print(world:getRect(B))

-- prints "Collision with A"
for i=1,len do -- If more than one simultaneous collision, they are sorted out by proximity
  local col = cols[i]
  print(("Collision with %s."):format(col.other.name))
end

-- remove A and B from the world
world:remove(A)
world:remove(B)
```

## Demos

There is a demo showing movement, collision detection and basic slide-based resolution in this branch:

http://github.com/kikito/bump.lua/tree/simpledemo

![simpledemo](https://kikito.github.io/bump.lua/img/bump-simpledemo.gif)

There's a more complex demo showing more advanced movement mechanics (i.e. acceleration, bouncing) in this other
repo:

http://github.com/kikito/bump.lua/tree/demo

![demo](https://kikito.github.io/bump.lua/img/bump-demo.gif)

You will need [LÖVE](http://love2d.org) in order to try any of them.

## Basic API - Adding, removing and moving items

### Requiring the library

``` lua
local bump = require 'bump'
```

The following methods (`bump.newWorld`, `world:add`, `world:remove`, `world:update`, `world:move` & `world:check`) are *basic* for
working with bump, as well as the 4 collision responses. If you want to use bump.lua effectively, you will need to understand at least
these.

### Creating a world

``` lua
local world = bump.newWorld(cellSize)
```

The first thing to do with bump is creating a world. That is done with `bump.newWorld`.

* `cellSize`. Is an optional number. It defaults to 64. It represents the size of the sides
  of the (squared) cells that will be used internally to provide the data. In tile based games, it's usually a multiple of
  the tile side size. So in a game where tiles are 32x32, `cellSize` will be 32, 64 or 128. In more sparse games, it can be
  higher.

Don't worry too much about `cellSize` at the beginning, you can tweak it later on to see if bigger/smaller numbers
give you better results (you can't change the value of cellSize in runtime, but you can create as many worlds as you want,
each one with a different cellsize, if the need arises.)

The rest of the methods we have are for the worlds that we create.

### Adding items to the world

``` lua
world:add(item, x,y,w,h)
```

`world:add` is what you need to insert a new item in a world. "Items" are "anything that matters to your collision". It can be the player character,
a tile, a missile etc. In fact, you can insert items that don't participate in the collision at all - like puffs of smoke or background tiles. This
can be handy if you want to use the bump world as a spatial database in addition to a collision detector (see the "queries section" below for mode details).

Each `item` will have an associated "rectangle" in the `world`.

* `item` is the new item being inserted (usually a table representing a game object, like `player` or `ground_tile`).
* `x,y,w,h`: the rectangle associated to `item` in the world. They are all mandatory. `w` & `h` are the "width" and "height"
  of the box. `x` and `y` depend on the host system's coordinate system. For example, in [LÖVE](http://love2d.org) &
  [Corona SDK](http://coronalabs.com/products/corona-sdk/) they represent "left" & "top", while in [Cocos2d-x](http://cocos2d-x.org/wiki/Lua)
  they represent "left" & "bottom".

`world:add` returns no values. It generates no collisions - you can call `world:check(item)` if you want to get the collisions it creates right after it's added.

If you try to add an item to a world that already contains it, you will get an error.

### Removing items from the world

``` lua
world:remove(item)
```

bump.lua stores *hard references* to any items that you add (with `world:add`). If you decide that a item is no longer necessary, in addition to removing it
from your "entity list", you must also remove it from the world using `world:remove`. Otherwise it will still be there, and other objects might still collide
with it.

* `item` must be something previously inserted in the world with `world:add(item, l,t,w,h)`. If this is not the case, `world:remove` will raise an error.

Once removed from the world, the item will stop existing in that world. It won't trigger any collisions with other objects any more. Attempting to move it
with `world:move` or checking collisions with `world:check` will raise an error.

It is ok to remove an object from the world and later add it again. In fact, some bump methods do this internally.

This method returns nothing.

### Changing the position and dimensions of items in the world

``` lua
world:update(item, x,y,<w>,<h>)
```

Even if your "player" has attributes like `player.x` and `player.y`, changing those will not automatically change them inside `world`. `update` is one of
the ways to do so: it changes the rect representing `item` inside `world`.

* `item` must be something previously inserted in the world with `world:add(item, l,t,w,h)`. Otherwise, `world:update` will raise an error.
* `x,y,w,h` the new dimensions of `item`. `x` and `y` are mandatory. `w` and `h` will default to the values the world already had for `item`.

This method always changes the rect associated to `item`, ignoring all collisions (use `world:move` for that). It returns nothing.

You may use `world:update` if you want to "teleport" your items around. A lot of time, however, you want to move them taking collisions into account.
In order to do that, you have `world:move`.

### Moving an item in the world, with collision resolution

``` lua
local actualX, actualY, cols, len = world:move(item, goalX, goalY, <filter>)
```

This is probably the most useful method of bump. It moves the item inside the world towards a desired position, but taking collisions into account.

* `item` must be something previously inserted in the world with `world:add(item, l,t,w,h)`. Otherwise, `world:move` will raise an error.
* `goalX, goalY` are the *desired* `x` and `y` coordinates. The item will end up in those coordinates if it doesn't collide with anything.
  If, however, it collides with 1 or more other items, it can end up in a different set of coordinates.
* `filter` is an optional function. If provided, it must have this signature: `local type = filter(item, other)`. By default, `filter` always returns `"slide"`.
  * `item` is the item being moved (the same one passed to `world:move` on the first param)
  * `other` is an item (different from `item`) which can collide with `item`.
  * `type` is a value which defines how `item` collides with `other`.
    * If `type` is `false` or `nil`, `item` will ignore `other` completely (there will be no collision)
    * If `type` is `"touch"`, `"cross"`, `"slide"` or `"bounce"`, `item` will respond to the collisions in different ways (explained below)
    * Any other value (unless handled in an advanced way) will provoke an error

* `actualX, actualY` are the coordinates where the object ended up after colliding with other objects in the world while trying to get to
  `goalX, goalY`. They can be equal to `goalX, goalY` if, for example, no collisions happened.
* `len` is the amount of collisions produced. It is equivalent to `#cols`
* `cols` is an array of all the collisions that were detected. Each collision is a table. The most important item in that table is `cols[i].other`, which
  points to the item that collided with `item`. A full description of what's inside of each collision can be found on the "Advanced API" section.

The usual way you would use move is: calculate a "desirable" `goalX, goalY` point for an item (maybe using its velocity), pass it to move, and then use `actualX, actualY`
as the real "updates" - . For example, here's how a player would move:

``` lua
function movePlayer(player, dt)
  local goalX, goalY = player.vx * dt, player.vy * dt
  local actualX, actualY, cols, len = world:move(player, goalX, goalY)
  player.x, player.y = actualX, actualY
  -- deal with the collisions
  for i=1,len do
    print('collided with ' .. tostring(cols[i].other))
  end
end
```

Notice that if `filter` returns `nil` or `false`, it is guaranteed that `other` will not produce a collision. But the opposite is not true: it is possible that `filter` returns
`"slide"`, and yet no collision is produced. This is because `filter` is applied to *all the neighbors of `item`*, that is, all the items that "touch" the same cells as item. Some
of them might be on the same cells, but still not collide with item..

#### Collision Resolution

For each of the collisions returned by `world:move`, the most interesting attribute is `cols[i].other`. Often it's enough with it - for example if `item`
is one of those bullets that disappear when impacting the player you must make the bullet disappear (and decrease the player's health).

`world:move()` returns a list (instead of a single collision element) because in some cases you might want to "skip" some
collisions, or react to several of them in a single frame.

For example, imagine a player which collides on the same frame with a coin first, an enemy fireball, and the floor.

* since `cols[1].other` will be a coin, you will want to make the coin disappear (maybe with a sound) and increase the player's score.
* `cols[2].other` will be a fireball, so you will want to decrease the player's health and make the fireball disappear.
* `cols[3].other` will be a ground tile, so you will need to stop the player from "falling down", and maybe align it with the ground.

The first two can be handled just by using `col.other`, but "aligning the player with the ground" requires *collision resolution*.

bump.lua comes with 4 built-in ways to handle collisions: `touch`, `cross`, `slide` & `bounce`. You can select which one is used on each collision by returning
their name in the `filter` param of `world:move` or `world:check`. You can also choose to ignore a collision by returning `nil` or `false`.

![touch](img/touch.png)

This is the type of collision for things like arrows or bullets; things that "gets stuck" on their targets.

Collisions of this type have their `type` attribute set to `"touch"` and don't have any additional information appart from the the default one, shared by all collisions (see below).

![cross](img/cross.png)

This type of collision is for cases where you want to detect a collision but you don't want any response. It is useful for things like: detecting that the player has entered a new area,
or consumables (i.e. coins) which usually don't affect the player's trajectory, but it's still useful to know then they are collided with.

Collisions of this type have their `type` attribute set to `"cross"` and don't have any additional information appart from the the default one, shared by all collisions (see below).

![slide](img/slide.png)

This is the default collision type used in bump. It's what you want to use for solid objects which "slide over other objects", like Super Mario does over a platform or the ground.

Collisions of this type have their `type` attribute set to `"slide"`. They also have a special attribute called `col.slide`, which is a 2d vector with two components: `col.slide.x` &
`col.slide.y`. It represents the x and y coordinates to which the `item` "attempted to slide to". They are different from `actualX` & `actualY` since other collisions later on can
modify them.

![bounce](img/bounce.png)

A good example of this behavior is Arkanoid's ball; you can use this type of collision for things that "move away" after touching others.

Collisions of this type have their `type` attribute set to `"bounce"`. They also have a special attributes called `col.bounce`. It is a 2d vector which represents the x and y
coordinates to which the `item` "attempted to bounce".

The [Grenades](https://github.com/kikito/bump.lua/blob/demo/entities/grenade.lua) and the [Debris](https://github.com/kikito/bump.lua/blob/demo/entities/debris.lua) in the
demo use `"bounce"` to resolve their collisions.

Here's an example of a filter displaying all these behaviors:

```lua
local playerFilter = function(item, other)
  if     other.isCoin   then return 'cross'
  elseif other.isWall   then return 'slide'
  elseif other.isExit   then return 'touch'
  elseif other.isSpring then return 'bounce'
  end
  -- else return nil
end
```

The code above will make a character work more or less like super-mario, collision-wise. It'll go though coins, collide with walls, bounce over springs, etc, ignoring things it should
not collide with like clouds in the background.

You could then use the collisions returned like so:

``` lua
function movePlayer(player, dt)
  local goalX, goalY = player.vx * dt, player.vy * dt
  local actualX, actualY, cols, len = world:move(player, goalX, goalY, playerFilter)
  player.x, player.y = actualX, actualY
  for i=1,len do
    local other = cols[i].other
    if other.isCoin then
      takeCoin(other)
    elseif other.isExit then
      changeLevel()
    elseif other.isSpring then
      highJump()
    end
  end
end
```

### Checking for collisions without moving

``` lua
local actualX, actualY, cols, len = world:check(item, goalX, goalY, <filter>)
```

It returns the position where `item` would end up, and the collisions it would encounter, should it attempt to move to `goalX, goalY` with the specified `filter`.

Notice that `check` has the same parameters and return values as `move`. The difference is that the former does not update the position of `item` in the world - you
would have to call `world:update` in order to do that. In fact, `world:move` is implemented by calling `world:check` first, and then `world:update` immediately after.

The equivalent code to the previous example using `check` would be:

``` lua
function movePlayer(player, dt)
  local goalX, goalY = player.vx * dt, player.vy * dt
  local actualX, actualY, cols, len = world:check(player, goalX, goalY)
  world:update(player, actualX, actualY) -- update the player's rectangle in the world
  player.x, player.y = actualX, actualY
  ... <deal with the collisions as before>
end
```

`world:check` is useful for things like "planing in advance" or "studying alternatives", when moving is still not fully decided.

### Collision info

Here's the info contained on every collision item contained in the `cols` variables mentioned above:

```lua
cols[i] = {
  item  = the item being moved / checked
  other = an item colliding with the item being moved
  type  = the result of `filter(other)`. It's usually "touch", "cross", "slide" or "bounce"
  overlaps  = boolean. True if item "was overlapping" other when the collision started.
              False if it didn't but "tunneled" through other
  ti        = Number between 0 and 1. How far along the movement to the goal did the collision occur>
  move      = Vector({x=number,y=number}). The difference between the original coordinates and the actual ones.
  normal    = Vector({x=number,y=number}). The collision normal; usually -1,0 or 1 in `x` and `y`
  touch     = Vector({x=number,y=number}). The coordinates where item started touching other
  itemRect  = The rectangle item occupied when the touch happened({x = N, y = N, w = N, h = N})
  otherRect = The rectangle other occupied when the touch happened({x = N, y = N, w = N, h = N})
}
```

Note that collisions of type `slide` and `bounce` have some additional fields. They are described
on each response's section above.

Most of this info is useful only if you are doing semi-advanced stuff with collisions, but they could have some uses.

For example, `cols[i].normal` could be used to "detect if a player is on ground or not". `cols[i].touch` could be used to
"spawn a puff of dust when a player touches ground after a fall", and so on.

## Intermediate API - Querying the world

The following methods are required for basic usage of bump.lua, but are quite handy, and you would be missing out some
nice features of this lib if you were not using it.

Sometimes it is desirable to know "which items are in a certain area". This is called "querying the world".

Bump allows querying the world via a point, a rectangular zone, and a straight line segment.

This makes it useful not only as a collision detection library, but also as a lightweight spatial dictionary. In particular,
you can use bump to "only draw the things that are needed" on the screen. In order to do this, you would have to add all your
"visible" objects into bump, even if they don't collide with anything (this is usually ok, just ignore them with your filters when
you do the collisions).

### Querying with a point

``` lua
local items, len = world:queryPoint(x,y, filter)
```
Returns the items that touch a given point.

It is useful for things like clicking with the mouse and getting the items affected.

* `x,y` are the coordinates of the point that is being checked
* `items` is the list items from the ones inserted on the world (like `player`) that contain the point `x,y`.
  If no items touch the point, then `items` will be an empty table. If not empty, then the order of these items is random.
* `filter` is an optional function. It takes one parameter (an item). `queryPoint` will not return the items that return
  `false` or `nil` on `filter(item)`. By default, all items touched by the point are returned.
* `len` is the length of the items list. It is equivalent to `#items`, but it's slightly faster to use `len` instead.

### Querying with a rectangle

``` lua
local items, len = world:queryRect(l,t,w,h, filter)
```
Returns the items that touch a given rectangle.

Useful for things like selecting what to display on the screen, as mentioned above, or selecting a group of units with the mouse in a strategy game.

* `l,t,w,h` is a rectangle. The items that intersect with it will be returned.
* `filter` is an optional function. When provided, it is used to "filter out" which items are returned - if `filter(item)` returns
  `false` or `nil`, that item is ignored. By default, all items are included.
* `items` is a list of items, like in `world:queryPoint`. But instead of for a point `x,y` for a rectangle `l,t,w,h`.
* `len` is equivalent to `#items`

### Querying with a segment

``` lua
local items, len = world:querySegment(x1,y1,x2,y2,filter)
```
Returns the items that touch a segment.

It's useful for things like line-of-sight or modelling bullets or lasers.

* `x1,y1,x2,y2` are the start and end coordinates of the segment.
* `filter` is an optional function. When provided, it is used to "filter out" which items are returned - if `filter(item)` returns
  `false` or `nil`, that item is ignored. By default, all items are included.
* `items` is a list of items, similar to `world:queryPoint`, intersecting with the given segment. The difference is that
  in `world:querySegment` the items are sorted by proximity. The ones closest to `x1,y1` appear first, while the ones farther
  away appear later.
* `len` is equivalent to `#items`.

### Querying with a segment (with more detailed info)

``` lua
local itemInfo, len = world:querySegmentWithCoords(x1,y1,x2,y2)
```
An extended version of `world:querySegment` which returns the collision points of the segment with the items,
in addition to the items.

It is useful if you need to **actually show** the lasers/bullets or if you need to show some impact effects (i.e. spawning some particles
where a bullet hits a wall). If you don't need the actual points of contact between the segment and the bounding rectangles, use
`world:querySegment`, since it's faster.

* `x1,y1,x2,y2,filter` same as in `world:querySegment`
* `itemInfo` is a list of tables. Each element in the table has the following elements: `item`, `x1`, `y1`, `x2`, `y2`, `t0` and `t1`.
  * `info.item` is the item being intersected by the segment.
  * `info.x1,info.y1` are the coordinates of the first intersection between `item` and the segment
  * `info.x2,info.y2` are the coordinates of the second intersection between `item` and the segment
  * `info.ti1` & `info.ti2` are numbers between 0 and 1 which say "how far from the starting point of the segment did the impact happen"
* `len` is equivalent to `#itemInfo`.

Most people will only need `info.item`, `info.x1` and `info.y1`. `info.x2` and `info.y2` are useful if you also need to show "the exit point
of a shoot", for example. `info.ti1` and `info.ti2` give an idea about the distance to the origin, so they can be used for things like
calculating the intensity of a shooting that becomes weaker with distance.

## Advanced API

The following methods are advanced and/or used internally by the library; most people will not need them.

``` lua
local result = world:hasItem(item)
```
Returns wether the world contains the given item or not. This function does not throw an error if `item` is not included in `world`; it just returns `false`.

``` lua
local count = world:countItems()
```
Returns the number of items inserted in the world. Useful for debugging

``` lua
local items, len = world:getItems()
```
Builds and returns an array containing all the items in the world (as well as its length). This can be useful if you want to draw or update all the items in the world, without
doing any queries. Notice that in which the items will be returned is non-deterministic.

``` lua
local x,y,w,h = world:getRect(item)
```
Given an item, obtain the coordinates of its bounding rect. Useful for debugging/testing things.

``` lua
local cell_count = world:countCells()
```

Returns the number of cells being used. Useful for testing/debugging.

``` lua
local cx,cy = world:toCell(x,y)
```

Given a point, return the coordinates of the cell that containg it using the world's `cellSize`. Useful mostly for debugging bump, or drawing
debug info.

``` lua
local x,y = world:toWorld(x,y)
```

The inverse of `world:toCell`. Given the coordinates of a cell, return the coordinates of its main corner (top-left in LÖVE and Corona SDK, bottom-left in Cocos2d-x) in the game world.

``` lua
local cols, len = world:project(item, x,y,w,h, goalX, goalY, filter)
```

Moves a the given imaginary rectangle towards goalX and goalY, providing a list of collisions as they happen *in that straight path*.

This method is useful mostly when creating new collision responses, although it could be also used as a query method.

You could use this method to implement your own collision response algorithm (this was the only way to
to it in prevous versions of bump)

```lua
bump.responses.touch
bump.responses.cross
bump.responses.slide
bump.responses.bounce
```

These are the functions bump uses to resolve collisions by default. You can use these function's source as a base to build your own response function, if you feel adventurous.

```lua
world:addResponse(name, response)
```

This is how you register a new type of response in the world. All world come with the 4 pre-defined responses "already installed", but you can add your own; if you register the
response `'foo'`, then when your filter return `'foo'` in a collision your world will handle them with `response`. This, however, is advanced stuff, and you
will have to read the source code of the default responses in order to know how to do that.

```lua
bump.rect.getNearestCorner
bump.rect.getSegmentIntersectionIndices
bump.rect.getDiff
bump.rect.containsPoint
bump.rect.isIntersecting
bump.rect.getSquareDistance
bump.rect.detectCollision
```

bump.lua comes with some rectangle-related functions in the `bump.rect` namespace. These are **not** part of the official API and can change at any moment. However, feel free to
use them if you are implementing your own collision responses.

## Installation

Just copy the bump.lua file wherever you want it. Then require it where you need it:

``` lua
local bump = require 'bump'
```

If you copied bump.lua to a file not accesible from the root folder (for example a lib folder), change the code accordingly:

``` lua
local bump = require 'lib.bump'
```

Please make sure that you read the license, too (for your convenience it's now included at the beginning of the bump.lua file.

## License

bump.lua is licensed under the MIT license.

## Specs

Specs for this project can be run using [busted](http://olivinelabs.com/busted).

## Changelog

See CHANGELOG.md for details


text:
FOUNDATION_EXPORT NSString *const kZLWorkItemDatabaseLocation;
FOUNDATION_EXPORT NSString *const kZLWorkItemDatabaseTableName;

FOUNDATION_EXPORT NSString *const kZLWorkItemIDColumnKey;
FOUNDATION_EXPORT NSString *const kZLTaskTypeColumnKey;
FOUNDATION_EXPORT NSString *const kZLTaskIDColumnKey;

FOUNDATION_EXPORT NSString *const kZLStateColumnKey;
FOUNDATION_EXPORT NSString *const kZLDataColumnKey;
FOUNDATION_EXPORT NSString *const kZLMajorPriorityColumnKey;
FOUNDATION_EXPORT NSString *const kZLMinorPriorityColumnKey;
FOUNDATION_EXPORT NSString *const kZLRetryCountColumnKey;
FOUNDATION_EXPORT NSString *const kZLTimeCreatedColumnKey;
FOUNDATION_EXPORT NSString *const kZLRequiresIntenetColumnKey;
FOUNDATION_EXPORT NSString *const kZLMaxNumberOfRetriesKey;
FOUNDATION_EXPORT NSString *const kZLShouldHoldAfterMaxRetriesKey;

@interface ZLWorkItemDatabaseConstants : NSObject

@end


text:
all:
	dpkg-buildpackage -rfakeroot -uc -b
	dpkg-deb -c ../python-fwmacro_0.9.6_all.deb

clean:
	fakeroot debian/rules clean
	rm -f *-stamp


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';

/**
 * Facebook renderer
 *
 * It creates an <iframe> from a <div> with specific configuration.
 * @see https://developers.facebook.com/docs/plugins/embedded-video-player
 */

var FacebookRenderer = {
	name: 'facebook',

	options: {
		prefix: 'facebook',
		facebook: {
			appId: '{your-app-id}',
			xfbml: true,
			version: 'v2.6'
		}
	},

	/**
  * Determine if a specific element type can be played with this render
  *
  * @param {String} type
  * @return {Boolean}
  */
	canPlayType: function canPlayType(type) {
		return ['video/facebook', 'video/x-facebook'].includes(type);
	},

	/**
  * Create the player instance and add all native events/methods/properties as possible
  *
  * @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
  * @param {Object} options All the player configuration options passed through constructor
  * @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
  * @return {Object}
  */
	create: function create(mediaElement, options, mediaFiles) {

		var fbWrapper = {},
		    apiStack = [],
		    eventHandler = {},
		    readyState = 4;

		var i = void 0,
		    il = void 0,
		    src = '',
		    paused = true,
		    ended = false,
		    hasStartedPlaying = false,
		    fbApi = null,
		    fbDiv = null;

		options = Object.assign(options, mediaElement.options);
		fbWrapper.options = options;
		fbWrapper.id = mediaElement.id + '_' + options.prefix;
		fbWrapper.mediaElement = mediaElement;

		// wrappers for get/set
		var props = mejs.html5media.properties,
		    assignGettersSetters = function assignGettersSetters(propName) {

			var capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);

			fbWrapper['get' + capName] = function () {

				if (fbApi !== null) {
					var value = null;

					// figure out how to get youtube dta here
					switch (propName) {
						case 'currentTime':
							return fbApi.getCurrentPosition();

						case 'duration':
							return fbApi.getDuration();

						case 'volume':
							return fbApi.getVolume();

						case 'paused':
							return paused;

						case 'ended':
							return ended;

						case 'muted':
							return fbApi.isMuted();

						case 'buffered':
							return {
								start: function start() {
									return 0;
								},
								end: function end() {
									return 0;
								},
								length: 1
							};
						case 'src':
							return src;

						case 'readyState':
							return readyState;
					}

					return value;
				} else {
					return null;
				}
			};

			fbWrapper['set' + capName] = function (value) {

				if (fbApi !== null) {

					switch (propName) {

						case 'src':
							var url = typeof value === 'string' ? value : value[0].src;

							// Only way is to destroy instance and all the events fired,
							// and create new one
							fbDiv.parentNode.removeChild(fbDiv);
							createFacebookEmbed(url, options.facebook);

							// This method reloads video on-demand
							FB.XFBML.parse();

							break;

						case 'currentTime':
							fbApi.seek(value);
							break;

						case 'muted':
							if (value) {
								fbApi.mute();
							} else {
								fbApi.unmute();
							}
							setTimeout(function () {
								var event = mejs.Utils.createEvent('volumechange', fbWrapper);
								mediaElement.dispatchEvent(event);
							}, 50);
							break;

						case 'volume':
							fbApi.setVolume(value);
							setTimeout(function () {
								var event = mejs.Utils.createEvent('volumechange', fbWrapper);
								mediaElement.dispatchEvent(event);
							}, 50);
							break;

						case 'readyState':
							var event = mejs.Utils.createEvent('canplay', fbWrapper);
							mediaElement.dispatchEvent(event);
							break;

						default:

							break;
					}
				} else {
					// store for after "READY" event fires
					apiStack.push({ type: 'set', propName: propName, value: value });
				}
			};
		};

		for (i = 0, il = props.length; i < il; i++) {
			assignGettersSetters(props[i]);
		}

		// add wrappers for native methods
		var methods = mejs.html5media.methods,
		    assignMethods = function assignMethods(methodName) {

			// run the method on the native HTMLMediaElement
			fbWrapper[methodName] = function () {

				if (fbApi !== null) {

					// DO method
					switch (methodName) {
						case 'play':
							return fbApi.play();
						case 'pause':
							return fbApi.pause();
						case 'load':
							return null;

					}
				} else {
					apiStack.push({ type: 'call', methodName: methodName });
				}
			};
		};

		for (i = 0, il = methods.length; i < il; i++) {
			assignMethods(methods[i]);
		}

		/**
   * Dispatch a list of events
   *
   * @private
   * @param {Array} events
   */
		function sendEvents(events) {
			for (var _i = 0, _il = events.length; _i < _il; _i++) {
				var event = mejs.Utils.mejs.Utils.createEvent(events[_i], fbWrapper);
				mediaElement.dispatchEvent(event);
			}
		}

		/**
   * Create a new Facebook player and attach all its events
   *
   * This method creates a <div> element that, once the API is available, will generate an <iframe>.
   * Valid URL format(s):
   *  - https://www.facebook.com/johndyer/videos/10107816243681884/
   *
   * @param {String} url
   * @param {Object} config
   */
		function createFacebookEmbed(url, config) {
			src = url;
			fbDiv = document.createElement('div');
			fbDiv.id = fbWrapper.id;
			fbDiv.className = "fb-video";
			fbDiv.setAttribute("data-href", url);
			fbDiv.setAttribute("data-allowfullscreen", "true");
			fbDiv.setAttribute("data-controls", "false");

			mediaElement.originalNode.parentNode.insertBefore(fbDiv, mediaElement.originalNode);
			mediaElement.originalNode.style.display = 'none';

			/*
    * Register Facebook API event globally
    *
    */
			window.fbAsyncInit = function () {

				FB.init(config);

				FB.Event.subscribe('xfbml.ready', function (msg) {

					if (msg.type === 'video') {
						(function () {

							fbApi = msg.instance;

							// Set proper size since player dimensions are unknown before this event
							var fbIframe = fbDiv.getElementsByTagName('iframe')[0],
							    width = parseInt(window.getComputedStyle(fbIframe, null).width),
							    height = parseInt(fbIframe.style.height),
							    events = ['mouseover', 'mouseout'],
							    assignEvents = function assignEvents(e) {
								var event = mejs.Utils.createEvent(e.type, fbWrapper);
								mediaElement.dispatchEvent(event);
							};

							fbWrapper.setSize(width, height);

							for (i = 0, il = events.length; i < il; i++) {
								fbIframe.addEventListener(events[i], assignEvents, false);
							}

							// remove previous listeners
							var fbEvents = ['startedPlaying', 'paused', 'finishedPlaying', 'startedBuffering', 'finishedBuffering'];
							for (i = 0, il = fbEvents.length; i < il; i++) {
								var event = fbEvents[i],
								    handler = eventHandler[event];
								if (handler !== undefined && handler !== null && !mejs.Utils.isObjectEmpty(handler) && typeof handler.removeListener === 'function') {
									handler.removeListener(event);
								}
							}

							// do call stack
							if (apiStack.length) {
								for (i = 0, il = apiStack.length; i < il; i++) {

									var stackItem = apiStack[i];

									if (stackItem.type === 'set') {
										var propName = stackItem.propName,
										    capName = '' + propName.substring(0, 1).toUpperCase() + propName.substring(1);

										fbWrapper['set' + capName](stackItem.value);
									} else if (stackItem.type === 'call') {
										fbWrapper[stackItem.methodName]();
									}
								}
							}

							sendEvents(['rendererready', 'loadeddata', 'canplay', 'progress', 'loadedmetadata', 'timeupdate']);

							var timer = void 0;

							// Custom Facebook events
							eventHandler.startedPlaying = fbApi.subscribe('startedPlaying', function () {
								if (!hasStartedPlaying) {
									hasStartedPlaying = true;
								}
								paused = false;
								ended = false;
								sendEvents(['play', 'playing', 'timeupdate']);

								// Workaround to update progress bar
								timer = setInterval(function () {
									fbApi.getCurrentPosition();
									sendEvents(['timeupdate']);
								}, 250);
							});
							eventHandler.paused = fbApi.subscribe('paused', function () {
								paused = true;
								ended = false;
								sendEvents(['pause']);
							});
							eventHandler.finishedPlaying = fbApi.subscribe('finishedPlaying', function () {
								paused = true;
								ended = true;

								// Workaround to update progress bar one last time and trigger ended event
								timer = setInterval(function () {
									fbApi.getCurrentPosition();
									sendEvents(['timeupdate', 'ended']);
								}, 250);

								clearInterval(timer);
								timer = null;
							});
							eventHandler.startedBuffering = fbApi.subscribe('startedBuffering', function () {
								sendEvents(['progress', 'timeupdate']);
							});
							eventHandler.finishedBuffering = fbApi.subscribe('finishedBuffering', function () {
								sendEvents(['progress', 'timeupdate']);
							});
						})();
					}
				});
			};

			(function (d, s, id) {
				var fjs = d.getElementsByTagName(s)[0];
				if (d.getElementById(id)) {
					return;
				}
				var js = d.createElement(s);
				js.id = id;
				js.src = '//connect.facebook.net/en_US/sdk.js';
				fjs.parentNode.insertBefore(js, fjs);
			})(document, 'script', 'facebook-jssdk');
		}

		if (mediaFiles.length > 0) {
			createFacebookEmbed(mediaFiles[0].src, fbWrapper.options.facebook);
		}

		fbWrapper.hide = function () {
			fbWrapper.stopInterval();
			fbWrapper.pause();
			if (fbDiv) {
				fbDiv.style.display = 'none';
			}
		};
		fbWrapper.show = function () {
			if (fbDiv) {
				fbDiv.style.display = '';
			}
		};
		fbWrapper.setSize = function (width, height) {
			if (fbApi !== null && !isNaN(width) && !isNaN(height)) {
				fbDiv.setAttribute('width', width);
				fbDiv.setAttribute('height', height);
			}
		};
		fbWrapper.destroy = function () {};
		fbWrapper.interval = null;

		fbWrapper.startInterval = function () {
			// create timer
			fbWrapper.interval = setInterval(function () {
				var event = mejs.Utils.createEvent('timeupdate', fbWrapper);
				mediaElement.dispatchEvent(event);
			}, 250);
		};
		fbWrapper.stopInterval = function () {
			if (fbWrapper.interval) {
				clearInterval(fbWrapper.interval);
			}
		};

		return fbWrapper;
	}
};

/**
 * Register Facebook type based on URL structure
 *
 */
mejs.Utils.typeChecks.push(function (url) {
	url = url.toLowerCase();
	return url.includes('//www.facebook') ? 'video/x-facebook' : null;
});

mejs.Renderers.add(FacebookRenderer);

},{}]},{},[1]);


text:
    <!-- Footer -->
    <footer>
        <div class="container text-center">

                <?php echo get_page_content('adresses');?>

        </div>
    </footer>

    <!-- jQuery -->
    <script src="<?php echo get_template_directory_uri();?>/js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="<?php echo get_template_directory_uri();?>/js/bootstrap.min.js"></script>

    <!-- Plugin JavaScript -->
    <script src="<?php echo get_template_directory_uri();?>/js/jquery.easing.min.js"></script>

    <!-- Custom Theme JavaScript -->
    <script src="<?php echo get_template_directory_uri();?>/js/grayscale.js"></script>

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-68704417-1', 'auto');
  ga('send', 'pageview');

</script>
<?php wp_footer(); ?>

</body>

</html>


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   iron-a11y-keys.html
 */

/// <reference path="../polymer/types/polymer.d.ts" />
/// <reference path="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.d.ts" />

interface IronA11yKeysElement extends Polymer.Element, Polymer.IronA11yKeysBehavior {
  target: Node|null;

  /**
   * Space delimited list of keys where each key follows the format:
   * `[MODIFIER+]*KEY[:EVENT]`.
   * e.g. `keys="space ctrl+shift+tab enter:keyup"`.
   * More detail can be found in the "Grammar" section of the documentation
   */
  keys: string|null|undefined;
  attached(): void;
  _targetChanged(target: any): void;
  _keysChanged(): void;
  _fireKeysPressed(event: any): void;
}

interface HTMLElementTagNameMap {
  "iron-a11y-keys": IronA11yKeysElement;
}


text:
<?php
namespace backend\models;
use yii\db\ActiveRecord;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Module extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'module';
    }

    public static function getModules()
    {

    }
}


text:
/* ----------------------------------------------------------------------- *//**
 *
 * @file Assertions_impl.cpp
 *
 * @brief Boost assertion handler
 *
 * See the comments in BoostIntegration.hpp.
 *
 *//* ----------------------------------------------------------------------- */

#include <sstream>
#include <stdexcept>

#include <boost/assert.hpp>

namespace boost {

/**
 * @brief Boost failed assertion handler, with message
 *
 * @internal
 * If the macro \c BOOST_ENABLE_ASSERT_HANDLER is defined when
 * <tt><boost/assert.hpp></tt> is included, instead of sending a error
 * message to an output stream, the expression
 * <tt>::boost::assertion_failed_msg(#expr, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)</tt>
 * is evaluated.
 */
inline
void
assertion_failed_msg(char const *inExpr, char const *inMsg,
    char const *inFunction, char const *inFile, long inLine) {

    std::stringstream tmp;
    tmp << inMsg
        << "\nDetails (for developers): \n"
        "Failed BOOST_ASSERT: " << inExpr <<
        "\nFunction: " << inFunction <<
        "\nFile: " << inFile << ":" << inLine;

    throw std::runtime_error( tmp.str() );
}

/**
 * @brief Boost failed assertion handler, without message
 *
 * @internal
 * If the macro \c BOOST_ENABLE_ASSERT_HANDLER is defined when
 * <tt><boost/assert.hpp></tt> is included, <tt>BOOST_ASSERT(expr)</tt>
 * evaluates \c expr and, if the result is false, evaluates the expression
 * <tt>::boost::assertion_failed(#expr, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)</tt>
 */
inline
void
assertion_failed(char const *inExpr, char const *inFunction,
    char const *inFile, long inLine) {

    assertion_failed_msg("A run-time error occured.", inExpr, inFunction,
        inFile, inLine);
}

} // namespace boost


text:
The sample source codes on this page shows how to make searchable pdf discarding existing content with pdf extractor sdk in VBScript. ByteScout Data Extraction Suite is the set that includes 3 SDK products for data extraction from PDF, scans, images and from spreadsheets: PDF Extractor SDK, Data Extraction SDK, Barcode Reader SDK. It can be applied to make searchable pdf discarding existing content with pdf extractor sdk using VBScript.

The following code snippet for ByteScout Data Extraction Suite works best when you need to quickly make searchable pdf discarding existing content with pdf extractor sdk in your VBScript application. This VBScript sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Enjoy writing a code with ready-to-use sample codes in VBScript.

Trial version of ByteScout Data Extraction Suite is available for free. Source code samples are included to help you with your VBScript app.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Data%20Extraction%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****MakeSearchablePDFDiscardingExistingContent.vbs:**

```
' Create Bytescout.PDFExtractor.SearchablePDFMaker object
Set searchablePDFMaker = CreateObject("Bytescout.PDFExtractor.SearchablePDFMaker")
searchablePDFMaker.RegistrationName = "demo"
searchablePDFMaker.RegistrationKey = "demo"

' Load sample PDF document
searchablePDFMaker.LoadDocumentFromFile("..\..\sample_ocr_withText.pdf")

' Set the location of OCR language data files
searchablePDFMaker.OCRLanguageDataFolder = "c:\Program Files\Bytescout PDF Extractor SDK\ocrdata_best"

' Set OCR language
' "eng" for english, "deu" for German, "fra" for French, "spa" for Spanish etc - according to files in "ocrdata" folder.
searchablePDFMaker.OCRLanguage = "eng"
' Find more language files at https://github.com/bytescout/ocrdata

' Set PDF document rendering resolution
searchablePDFMaker.OCRResolution = 300

' Discard Existing Text in document
searchablePDFMaker.DiscardExistingDocumentText = true

' Process the document
searchablePDFMaker.MakePDFSearchable("result.pdf")

WScript.Echo "Searchable document saved as 'result.pdf'."
```

<!-- code block end -->


text:
from recipe_scrapers.food52 import Food52
from tests import ScraperTest

class TestFood52(ScraperTest):

    scraper_class = Food52

    def test_host(self):
        self.assertEqual("food52.com", self.harvester_class.host())

    def test_canonical_url(self):
        self.assertEqual(
            "https://food52.com/recipes/84961-pomegranate-chicken-wings-recipe",
            self.harvester_class.canonical_url(),
        )

    def test_title(self):
        self.assertEqual(
            self.harvester_class.title(),
            "Sticky Pomegranate & Black Pepper Chicken Wings",
        )

    def test_total_time(self):
        self.assertEqual(1520, self.harvester_class.total_time())

    def test_yields(self):
        self.assertEqual("4 servings", self.harvester_class.yields())

    def test_ingredients(self):
        self.assertCountEqual(
            [
                "2 to 2 1/4 pounds chicken wings",
                "1 tablespoon kosher salt",
                "1 tablespoon granulated sugar",
                "2 teaspoons baking powder",
                "1/2 teaspoon MSG (optional)",
                "2 tablespoons neutral oil, such as grapeseed or canola",
                "1/4 cup granulated sugar",
                "1/2 cup pomegranate molasses",
                "2 tablespoons freshly ground black pepper",
                "2 teaspoons kosher salt",
                "2 teaspoons ground cinnamon",
                "1 teaspoon freshly ground nutmeg",
                "1/2 teaspoon toasted walnut halves, roughly chopped",
                "Flaky salt (optional)",
            ],
            self.harvester_class.ingredients(),
        )

    def test_instructions(self):
        return self.assertEqual(
            "\n".join(
                [
                    "Line a sheet pan with foil (for easy cleanup) and set an ovenproof wire rack inside.",
                    "Brine the wings: Pat the wings dry with a paper towel and place in a large bowl. In a small bowl, stir together the kosher salt, sugar, baking powder, and MSG (if using). Sprinkle this mixture over the wings and toss until evenly coated. Arrange the wings on the wire rack and refrigerate uncovered at least 6 hours or preferably overnight, flipping the wings halfway through. (Wash the bowl and keep it handy—we'll be using it again.)",
                    "When you're ready to roast, heat the oven to 350°F.",
                    "The first roast: Transfer the wings to the big bowl, toss with the oil until evenly coated, then return them to the wire rack. Roast the wings, flipping them once halfway through, until the skin is lightly browned, the flesh of the drumettes is starting to pull away from the bones, and the fat from the skin has mostly rendered, about 1 hour.",
                    "Meanwhile, prepare the glaze: Wash the large bowl. Add the sugar and pour 2 tablespoons of boiling water on top, whisking until the sugar dissolves. Add the pomegranate molasses, black pepper, salt, cinnamon, and nutmeg, whisking until combined.",
                    "The second roast: Remove the wings from the oven and increase the temperature to 375°F. Transfer the wings to the bowl with the glaze and toss to coat. Use tongs to return the wings to the rack, reserving any remaining glaze in the bowl, and roast until lightly charred and glossy, about 20 minutes.",
                    "Once the wings are out of the oven, transfer them to the bowl and toss again in the remaining glaze. Transfer the wings to a platter and garnish with the walnuts. Sprinkle with flaky salt if desired.",
                ]
            ),
            self.harvester_class.instructions(),
        )

    def test_ratings(self):
        self.assertEqual(5.0, self.harvester_class.ratings())


text:
package org.ondetem;

import org.ondetem.data.DataLayer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

	@Autowired
	DataLayer layer;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
	public CommandLineRunner demo() {
		return new CommandLineRunner() {
			@Override
			public void run(String... args) throws Exception {
				System.out.println(layer);
				if(layer != null){
					System.out.println(layer.getMarkersDAO());
				}
			}
		};

    }
}


text:
using netlib::TcpClient;
using netlib::EventLoop;
using netlib::SocketAddress;
using netlib::Thread;
using std::bind;

void ThreadFunction(EventLoop *loop)
{
	SocketAddress server_address("127.0.0.1", 1000);
	TcpClient client(loop, server_address, "TcpClient");
	client.Connect();
	::sleep(10);
}

int main()
{
	SetLogLevel(DEBUG);
	EventLoop loop;
	loop.RunAfter(bind(&EventLoop::Quit, &loop), 3.0);
	Thread thread(bind(ThreadFunction, &loop));
	thread.Start();
	loop.Loop();
}


text:
{% extends 'layout.html' %}
{% load i18n %}
{% load sale_list %}
{% load volunteer %}

{% block content %}

        Sie haben folgende Lieferadresse für Ihre Etiketten gewählt. Die Etiketten werden am Tag nach der Ausgabe
        mit der Post an die angegebene Adresse gesendet. Stellen Sie daher bitte sicher, dass die Adresse gültig ist.

    <form action="." method="post">
        {% csrf_token %}

            <textarea name="shipping_address" class="form-control" rows="5">{{ sale_list.shipping_address }}</textarea>

        <button class="btn btn-primary" type="submit">
             Adresse speichern
        </button>

             Abbrechen

    </form>

{% endblock %}


text:
@protocol IDEDeferredInitialization
+ (BOOL)ide_deferredInitializeWithOptions:(int)arg1 error:(id *)arg2;
@end

__attribute__((visibility("hidden")))
@interface GPUOSXInferiorSession : GPUInferiorSession
{
    NSString *_remoteHost;
    NSString *_remoteUsername;
    NSString *_remotePort;
    NSString *_remoteTargetPath;
}

+ (id)GPUToolsDeviceFromDVTDevice:(id)arg1 error:(id *)arg2;
+ (BOOL)isRemoteDebuggingRequested:(id)arg1;
- (void).cxx_destruct;
- (void)primitiveInvalidate;
- (id)GPUToolsDeviceFromDVTDevice:(id)arg1 error:(id *)arg2;
- (id)_updateRemoteDebuggingVariables;
- (id)_correctedTargetPath:(id)arg1;
- (id)_validateRemoteDebuggingEnvironmentVariables:(id)arg1;
- (void)launchDebugServerWithError:(id *)arg1;
- (id)initWithAppName:(id)arg1 launchSession:(id)arg2 controller:(id)arg3 error:(id *)arg4;

@end

__attribute__((visibility("hidden")))
@interface GPUOSXInitializer : NSObject <IDEDeferredInitialization>
{
}

+ (BOOL)ide_deferredInitializeWithOptions:(int)arg1 error:(id *)arg2;

@end

__attribute__((visibility("hidden")))
@interface GPUOSXQuicklooksEditor : GPUQuicklooksEditor
{
}

- (id)toolsDeviceFromDVTDevice:(id)arg1 error:(id *)arg2;

@end

__attribute__((visibility("hidden")))
@interface GPUOSXReplayController : GPUTraceReplayController
{
}

- (id)replayerGuestApp;
- (id)prepareCaptureArchive:(id)arg1 withDestinationName:(id)arg2;
- (id)connectedDevices;

@end

__attribute__((visibility("hidden")))
@interface _GPUDebuggerOSXSupportBundlePrivateClassForFindingBundle : NSObject
{
}

@end


text:
<?php

namespace Blog\Model;

use InvalidArgumentException;
use RuntimeException;
use Zend\Hydrator\HydratorInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Db\Sql\Sql;

class ZendDbSqlRepository implements PostRepositoryInterface
{
    /**
    * @var AdapterInterface
    */
    private $db;

    /**
    * @var HydratorInterface
    */
    private $hydrator;

    /**
    * @var Post
    */
    private $postPrototype;

    public function __construct(AdapterInterface $db,HydratorInterface $hydrator,Post $postPrototype)
    {
          $this->db             = $db;
          $this->hydrator       = $hydrator;
          $this->postPrototype  = $postPrototype;
    }

    /**
     * {@inheritDoc}
     */
    public function findAllPosts()
    {
        $sql       = new Sql($this->db);
        $select    = $sql->select('posts');
        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if (! $result instanceof ResultInterface || ! $result->isQueryResult()) {
          return [];
        }

        $resultSet = new HydratingResultSet($this->hydrator, $this->postPrototype);
        $resultSet->initialize($result);
        return $resultSet;
    }

    /**
     * {@inheritDoc}
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public function findPost($id)
    {
      $sql       = new Sql($this->db);
      $select    = $sql->select('posts');
      $select->where(['id = ?' => $id]);

      $statement = $sql->prepareStatementForSqlObject($select);
      $result    = $statement->execute();

      if (!$result instanceof ResultInterface || !$result->isQueryResult())
      {
        throw new RuntimeException(sprintf('Failed retrieving blog post with identifier "%s"; unknown database error.',$id));
      }

      $resultSet = new HydratingResultSet($this->hydrator, $this->postPrototype);
      $resultSet->initialize($result);
      $post = $resultSet->current();

      if (!$post)
      {
        throw new InvalidArgumentException(sprintf('Blog post with identifier "%s" not found.',$id));
      }

      return $post;
    }
}


text:
package net.foreworld.yx.util;

import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import net.foreworld.yx.model.ChannelInfo;

/**
 *
 * @author huangxin <3203317@qq.com>
 *
 */
public final class SenderUtil {

	private static final Logger logger = LoggerFactory.getLogger(SenderUtil.class);

	/**
	 *
	 * @param chan
	 * @return
	 */
	public static boolean canClose(Channel chan) {
		return (null != chan && chan.isOpen());
	}

	/**
	 *
	 * @param chan
	 * @return
	 */
	public static boolean canSend(Channel chan) {
		return (null != chan && chan.isActive());
	}

	/**
	 *
	 * @param ctx
	 * @param data
	 */
	public static void send(ChannelHandlerContext ctx, Object data) {
		Channel chan = ctx.channel();

		if (!canSend(chan))
			return;

		if (chan.isWritable()) {

			ctx.writeAndFlush(data.toString()).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture f) throws Exception {
					if (!f.isSuccess())
						logger.error("send data:", f.cause());
				}
			});

			return;
		}

		if (canClose(chan))
			ctx.close().addListener(f -> {
				SocketAddress addr = chan.remoteAddress();

				if (f.isSuccess()) {
					logger.info("sync ctx close: {}", addr);
					return;
				}

				logger.error("sync ctx close: {}", addr);
			});
	}

	/**
	 *
	 * @param chan
	 * @param data
	 */
	public static void send(Channel chan, Object data) {
		if (!canSend(chan))
			return;

		if (chan.isWritable()) {

			chan.writeAndFlush(data.toString()).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture f) throws Exception {
					if (!f.isSuccess())
						logger.error("send data:", f.cause());
				}
			});

			return;
		}

		if (canClose(chan))
			chan.close().addListener(f -> {
				SocketAddress addr = chan.remoteAddress();

				if (f.isSuccess()) {
					logger.info("sync chan close: {}", addr);
					return;
				}

				logger.error("sync chan close: {}", addr);
			});
	}

	/**
	 *
	 * @param receiver
	 * @param data
	 */
	public static void backSend(String receiver, String data) {
		if (Constants.ALL.equals(receiver)) {
			ChannelUtil.getDefault().broadcast(data).addListener(f -> {
				if (!f.isSuccess())
					logger.error("data: {}", data);
			});
			return;
		}

		String[] recs = receiver.split(",");

		for (int i = 0; i < recs.length; i++) {
			ChannelInfo ci = ChannelUtil.getDefault().getChannel(recs[i]);

			if (null != ci)
				send(ci.getChannel(), data);
		}
	}

}


text:
import bpy
from bpy import *
from urllib.parse import urlencode
from urllib.request import *
from html.parser import *
from smtplib import *
from email.mime.text import MIMEText
import time, platform, os
import codecs
import bpy.path
from bpy.path import abspath
import base64
import mathutils
from mathutils import *
from math import *
import pickle
import shutil
import subprocess
import sys

bl_info = {
    "name" : "BioBlender 2.0",
    "author" : "SciVis, IFC-CNR",
    "version" : (2,0),
    "blender" : (2,6,8,0),
    "location" : "Properties Window > Scene",
    "description" : "BioBlender 2.0",
    "warning" : "",
    "wiki_url" : "",
    "tracker_url" : "http://bioblender.eu/?page_id=665",
    "category" : "Add Mesh"
}

# ==================================================================================================================
# ==================================================================================================================
# ==================================================================================================================

from .BioBlender2 import *

# ==================================================================================================================
# ==================================================================================================================
# ==================================================================================================================

# ===== REGISTER = START ================================================
def register():
    bpy.utils.register_module(__name__)  # @UndefinedVariable

def unregister():
    bpy.utils.unregister_module(__name__)  # @UndefinedVariable

if __name__ == "__main__":
    register()
# ===== REGISTER = END ================================================


text:
namespace Google.Cloud.Notebooks.V1.Snippets
{
    // [START notebooks_v1_generated_NotebookService_GetInstanceHealth_sync]
    using Google.Cloud.Notebooks.V1;

    public sealed partial class GeneratedNotebookServiceClientSnippets
    {
        /// <summary>Snippet for GetInstanceHealth</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void GetInstanceHealthRequestObject()
        {
            // Create client
            NotebookServiceClient notebookServiceClient = NotebookServiceClient.Create();
            // Initialize request argument(s)
            GetInstanceHealthRequest request = new GetInstanceHealthRequest
            {
                InstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
            };
            // Make the request
            GetInstanceHealthResponse response = notebookServiceClient.GetInstanceHealth(request);
        }
    }
    // [END notebooks_v1_generated_NotebookService_GetInstanceHealth_sync]
}


text:
#include "config.h"
#include "InputType.h"

#include "BeforeTextInsertedEvent.h"
#include "ButtonInputType.h"
#include "CheckboxInputType.h"
#include "ColorInputType.h"
#include "DateComponents.h"
#include "DateInputType.h"
#include "DateTimeInputType.h"
#include "DateTimeLocalInputType.h"
#include "EmailInputType.h"
#include "ExceptionCode.h"
#include "FileInputType.h"
#include "FormDataList.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "HiddenInputType.h"
#include "ImageInputType.h"
#include "IsIndexInputType.h"
#include "KeyboardEvent.h"
#include "LocalizedStrings.h"
#include "MonthInputType.h"
#include "NumberInputType.h"
#include "PasswordInputType.h"
#include "RadioInputType.h"
#include "RangeInputType.h"
#include "RegularExpression.h"
#include "RenderObject.h"
#include "ResetInputType.h"
#include "SearchInputType.h"
#include "ShadowRoot.h"
#include "SubmitInputType.h"
#include "TelephoneInputType.h"
#include "TextInputType.h"
#include "TimeInputType.h"
#include "URLInputType.h"
#include "WeekInputType.h"
#include <limits>
#include <wtf/Assertions.h>
#include <wtf/HashMap.h>
#include <wtf/text/StringHash.h>

namespace WebCore {

using namespace std;

typedef PassOwnPtr<InputType> (*InputTypeFactoryFunction)(HTMLInputElement*);
typedef HashMap<String, InputTypeFactoryFunction, CaseFoldingHash> InputTypeFactoryMap;

static PassOwnPtr<InputTypeFactoryMap> createInputTypeFactoryMap()
{
    OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap);
    map->add(InputTypeNames::button(), ButtonInputType::create);
    map->add(InputTypeNames::checkbox(), CheckboxInputType::create);
    map->add(InputTypeNames::color(), ColorInputType::create);
    map->add(InputTypeNames::date(), DateInputType::create);
    map->add(InputTypeNames::datetime(), DateTimeInputType::create);
    map->add(InputTypeNames::datetimelocal(), DateTimeLocalInputType::create);
    map->add(InputTypeNames::email(), EmailInputType::create);
    map->add(InputTypeNames::file(), FileInputType::create);
    map->add(InputTypeNames::hidden(), HiddenInputType::create);
    map->add(InputTypeNames::image(), ImageInputType::create);
    map->add(InputTypeNames::isindex(), IsIndexInputType::create);
    map->add(InputTypeNames::month(), MonthInputType::create);
    map->add(InputTypeNames::number(), NumberInputType::create);
    map->add(InputTypeNames::password(), PasswordInputType::create);
    map->add(InputTypeNames::radio(), RadioInputType::create);
    map->add(InputTypeNames::range(), RangeInputType::create);
    map->add(InputTypeNames::reset(), ResetInputType::create);
    map->add(InputTypeNames::search(), SearchInputType::create);
    map->add(InputTypeNames::submit(), SubmitInputType::create);
    map->add(InputTypeNames::telephone(), TelephoneInputType::create);
    map->add(InputTypeNames::time(), TimeInputType::create);
    map->add(InputTypeNames::url(), URLInputType::create);
    map->add(InputTypeNames::week(), WeekInputType::create);
    // No need to register "text" because it is the default type.
    return map.release();
}

PassOwnPtr<InputType> InputType::create(HTMLInputElement* element, const String& typeName)
{
    static const InputTypeFactoryMap* factoryMap = createInputTypeFactoryMap().leakPtr();
    PassOwnPtr<InputType> (*factory)(HTMLInputElement*) = typeName.isEmpty() ? 0 : factoryMap->get(typeName);
    if (!factory)
        factory = TextInputType::create;
    return factory(element);
}

PassOwnPtr<InputType> InputType::createText(HTMLInputElement* element)
{
    return TextInputType::create(element);
}

InputType::~InputType()
{
}

bool InputType::isTextField() const
{
    return false;
}

bool InputType::isTextType() const
{
    return false;
}

bool InputType::isRangeControl() const
{
    return false;
}

bool InputType::saveFormControlState(String& result) const
{
    String currentValue = element()->value();
    if (currentValue == element()->defaultValue())
        return false;
    result = currentValue;
    return true;
}

void InputType::restoreFormControlState(const String& state) const
{
    element()->setValue(state);
}

bool InputType::isFormDataAppendable() const
{
    // There is no form data unless there's a name for non-image types.
    return !element()->name().isEmpty();
}

bool InputType::appendFormData(FormDataList& encoding, bool) const
{
    // Always successful.
    encoding.appendData(element()->name(), element()->value());
    return true;
}

double InputType::valueAsDate() const
{
    return DateComponents::invalidMilliseconds();
}

void InputType::setValueAsDate(double, ExceptionCode& ec) const
{
    ec = INVALID_STATE_ERR;
}

double InputType::valueAsNumber() const
{
    return numeric_limits<double>::quiet_NaN();
}

void InputType::setValueAsNumber(double, ExceptionCode& ec) const
{
    ec = INVALID_STATE_ERR;
}

bool InputType::supportsValidation() const
{
    return true;
}

bool InputType::typeMismatchFor(const String&) const
{
    return false;
}

bool InputType::typeMismatch() const
{
    return false;
}

bool InputType::supportsRequired() const
{
    // Almost all validatable types support @required.
    return supportsValidation();
}

bool InputType::valueMissing(const String&) const
{
    return false;
}

bool InputType::patternMismatch(const String&) const
{
    return false;
}

bool InputType::rangeUnderflow(const String&) const
{
    return false;
}

bool InputType::rangeOverflow(const String&) const
{
    return false;
}

bool InputType::supportsRangeLimitation() const
{
    return false;
}

double InputType::defaultValueForStepUp() const
{
    return 0;
}

double InputType::minimum() const
{
    ASSERT_NOT_REACHED();
    return 0;
}

double InputType::maximum() const
{
    ASSERT_NOT_REACHED();
    return 0;
}

bool InputType::stepMismatch(const String&, double) const
{
    // Non-supported types should be rejected by HTMLInputElement::getAllowedValueStep().
    ASSERT_NOT_REACHED();
    return false;
}

double InputType::stepBase() const
{
    ASSERT_NOT_REACHED();
    return 0;
}

double InputType::stepBaseWithDecimalPlaces(unsigned* decimalPlaces) const
{
    if (decimalPlaces)
        *decimalPlaces = 0;
    return stepBase();
}

double InputType::defaultStep() const
{
    return numeric_limits<double>::quiet_NaN();
}

double InputType::stepScaleFactor() const
{
    return numeric_limits<double>::quiet_NaN();
}

bool InputType::parsedStepValueShouldBeInteger() const
{
    return false;
}

bool InputType::scaledStepValueShouldBeInteger() const
{
    return false;
}

double InputType::acceptableError(double) const
{
    return 0;
}

String InputType::typeMismatchText() const
{
    return validationMessageTypeMismatchText();
}

String InputType::valueMissingText() const
{
    return validationMessageValueMissingText();
}

void InputType::handleClickEvent(MouseEvent*)
{
}

void InputType::handleMouseDownEvent(MouseEvent*)
{
}

#if PLATFORM(ANDROID) && ENABLE(TOUCH_EVENTS)
void InputType::handleTouchStartEvent(TouchEvent*)
{
}
#endif

void InputType::handleDOMActivateEvent(Event*)
{
}

void InputType::handleKeydownEvent(KeyboardEvent*)
{
}

void InputType::handleKeypressEvent(KeyboardEvent*)
{
}

void InputType::handleKeyupEvent(KeyboardEvent*)
{
}

void InputType::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent* event)
{
    element()->handleBeforeTextInsertedEvent(event);
}

void InputType::handleWheelEvent(WheelEvent*)
{
}

void InputType::forwardEvent(Event*)
{
}

bool InputType::shouldSubmitImplicitly(Event* event)
{
    return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && static_cast<KeyboardEvent*>(event)->charCode() == '\r';
}

PassRefPtr<HTMLFormElement> InputType::formForSubmission() const
{
    return element()->form();
}

RenderObject* InputType::createRenderer(RenderArena*, RenderStyle* style) const
{
    return RenderObject::createObject(element(), style);
}

void InputType::createShadowSubtree()
{
}

void InputType::destroyShadowSubtree()
{
    element()->removeShadowRoot();
}

double InputType::parseToDouble(const String&, double defaultValue) const
{
    return defaultValue;
}

double InputType::parseToDoubleWithDecimalPlaces(const String& src, double defaultValue, unsigned *decimalPlaces) const
{
    if (decimalPlaces)
        *decimalPlaces = 0;
    return parseToDouble(src, defaultValue);
}

bool InputType::parseToDateComponents(const String&, DateComponents*) const
{
    ASSERT_NOT_REACHED();
    return false;
}

String InputType::serialize(double) const
{
    ASSERT_NOT_REACHED();
    return String();
}

void InputType::dispatchSimulatedClickIfActive(KeyboardEvent* event) const
{
    if (element()->active())
        element()->dispatchSimulatedClick(event);
    event->setDefaultHandled();
}

bool InputType::canSetStringValue() const
{
    return true;
}

bool InputType::isKeyboardFocusable() const
{
    return true;
}

bool InputType::shouldUseInputMethod() const
{
    return false;
}

void InputType::handleBlurEvent()
{
}

void InputType::accessKeyAction(bool)
{
    element()->focus(false);
}

void InputType::attach()
{
}

void InputType::altAttributeChanged()
{
}

void InputType::srcAttributeChanged()
{
}

void InputType::valueChanged()
{
}

void InputType::willMoveToNewOwnerDocument()
{
}

bool InputType::shouldRespectAlignAttribute()
{
    return false;
}

bool InputType::canChangeFromAnotherType() const
{
    return true;
}

void InputType::minOrMaxAttributeChanged()
{
}

bool InputType::canBeSuccessfulSubmitButton()
{
    return false;
}

bool InputType::rendererIsNeeded()
{
    return true;
}

FileList* InputType::files()
{
    return 0;
}

bool InputType::getTypeSpecificValue(String&)
{
    return false;
}

String InputType::fallbackValue()
{
    return String();
}

String InputType::defaultValue()
{
    return String();
}

bool InputType::canSetSuggestedValue()
{
    return false;
}

bool InputType::shouldSendChangeEventAfterCheckedChanged()
{
    return true;
}

bool InputType::storesValueSeparateFromAttribute()
{
    return true;
}

bool InputType::canSetValue(const String&)
{
    return true;
}

PassOwnPtr<ClickHandlingState> InputType::willDispatchClick()
{
    return PassOwnPtr<ClickHandlingState>();
}

void InputType::didDispatchClick(Event*, const ClickHandlingState&)
{
}

String InputType::visibleValue() const
{
    return element()->value();
}

String InputType::convertFromVisibleValue(const String& visibleValue) const
{
    return visibleValue;
}

bool InputType::isAcceptableValue(const String&)
{
    return true;
}

String InputType::sanitizeValue(const String& proposedValue)
{
    return proposedValue;
}

bool InputType::hasUnacceptableValue()
{
    return false;
}

void InputType::setFileList(const Vector<String>&)
{
    ASSERT_NOT_REACHED();
}

bool InputType::shouldResetOnDocumentActivation()
{
    return false;
}

bool InputType::shouldRespectListAttribute()
{
    return false;
}

bool InputType::shouldRespectSpeechAttribute()
{
    return false;
}

bool InputType::isTextButton() const
{
    return false;
}

bool InputType::isRadioButton() const
{
    return false;
}

bool InputType::isSearchField() const
{
    return false;
}

bool InputType::isHiddenType() const
{
    return false;
}

bool InputType::isPasswordField() const
{
    return false;
}

bool InputType::isCheckbox() const
{
    return false;
}

bool InputType::isEmailField() const
{
    return false;
}

bool InputType::isFileUpload() const
{
    return false;
}

bool InputType::isImageButton() const
{
    return false;
}

bool InputType::isNumberField() const
{
    return false;
}

bool InputType::isSubmitButton() const
{
    return false;
}

bool InputType::isTelephoneField() const
{
    return false;
}

bool InputType::isURLField() const
{
    return false;
}

bool InputType::isEnumeratable()
{
    return true;
}

bool InputType::isCheckable()
{
    return false;
}

bool InputType::hasSpinButton()
{
    return false;
}

bool InputType::shouldRespectHeightAndWidthAttributes()
{
    return false;
}

namespace InputTypeNames {

// The type names must be lowercased because they will be the return values of
// input.type and input.type must be lowercase according to DOM Level 2.

const AtomicString& button()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("button"));
    return name;
}

const AtomicString& checkbox()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("checkbox"));
    return name;
}

const AtomicString& color()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("color"));
    return name;
}

const AtomicString& date()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("date"));
    return name;
}

const AtomicString& datetime()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime"));
    return name;
}

const AtomicString& datetimelocal()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime-local"));
    return name;
}

const AtomicString& email()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("email"));
    return name;
}

const AtomicString& file()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("file"));
    return name;
}

const AtomicString& hidden()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("hidden"));
    return name;
}

const AtomicString& image()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("image"));
    return name;
}

const AtomicString& isindex()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("khtml_isindex"));
    return name;
}

const AtomicString& month()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("month"));
    return name;
}

const AtomicString& number()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("number"));
    return name;
}

const AtomicString& password()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("password"));
    return name;
}

const AtomicString& radio()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("radio"));
    return name;
}

const AtomicString& range()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("range"));
    return name;
}

const AtomicString& reset()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("reset"));
    return name;
}

const AtomicString& search()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("search"));
    return name;
}

const AtomicString& submit()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("submit"));
    return name;
}

const AtomicString& telephone()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("tel"));
    return name;
}

const AtomicString& text()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("text"));
    return name;
}

const AtomicString& time()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("time"));
    return name;
}

const AtomicString& url()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("url"));
    return name;
}

const AtomicString& week()
{
    DEFINE_STATIC_LOCAL(AtomicString, name, ("week"));
    return name;
}

} // namespace WebCore::InputTypeNames

} // namespace WebCore


text:
require_relative "../adapter"

class Skala::Adapter::GetUserInterLibraryLoans < Skala::Adapter::Operation
  require_relative "./get_user_inter_library_loans/result"
end