text:
package org.kurento.room.test.browser;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.kurento.room.test.RoomFunctionalBrowserTest;
import org.kurento.test.browser.WebPage;

/**
 * Room demo integration test (basic version).
 *
 * @author Micael Gallego (micael.gallego@gmail.com)
 * @author Radu Tom Vlad (rvlad@naevatec.com)
 * @since 5.0.0
 */
public class NUsersEqualLifetime extends RoomFunctionalBrowserTest<WebPage> {

  public static final int NUM_USERS = 4;

  @Test
  public void test() throws Exception {
    ITERATIONS = 1;

    final boolean[] activeUsers = new boolean[NUM_USERS];

    final CountDownLatch[] joinCdl = createCdl(ITERATIONS, NUM_USERS);
    final CountDownLatch[] publishCdl = createCdl(ITERATIONS, NUM_USERS * NUM_USERS);
    final CountDownLatch[] leaveCdl = createCdl(ITERATIONS, NUM_USERS);

    iterParallelUsers(NUM_USERS, ITERATIONS, new UserLifecycle() {

      @Override
      public void run(final int numUser, final int iteration) throws Exception {
        final String userName = getBrowserKey(numUser);
        log.info("User '{}' is joining room '{}'", userName, roomName);
        synchronized (browsersLock) {
          joinToRoom(numUser, userName, roomName);
          activeUsers[numUser] = true;
          verify(activeUsers);
          joinCdl[iteration].countDown();
        }
        log.info("User '{}' joined room '{}'", userName, roomName);

        joinCdl[iteration].await(PLAY_TIME * 5000L, TimeUnit.MILLISECONDS);

        final long start = System.currentTimeMillis();

        parallelTasks(NUM_USERS, USER_BROWSER_PREFIX, "parallelWaitForStream", new Task() {
          @Override
          public void exec(int numTask) throws Exception {
            String videoUserName = getBrowserKey(numTask);
            synchronized (browsersLock) {
              waitForStream(numUser, userName, numTask);
            }
            long duration = System.currentTimeMillis() - start;
            log.info("Video received in browser of user '{}' for user '{}' in {} millis", userName,
                videoUserName, duration);
            publishCdl[iteration].countDown();
          }
        });
        publishCdl[iteration].await(PLAY_TIME * 5000L, TimeUnit.MILLISECONDS);

        sleep(PLAY_TIME);

        log.info("User '{}' is exiting from room '{}'", userName, roomName);
        synchronized (browsersLock) {
          exitFromRoom(numUser, userName);
          activeUsers[numUser] = false;
          verify(activeUsers);
          leaveCdl[iteration].countDown();
        }
        log.info("User '{}' exited from room '{}'", userName, roomName);
        leaveCdl[iteration].await(PLAY_TIME * 5000L, TimeUnit.MILLISECONDS);
      }
    });

  }

}


text:
namespace mf
{
    class QuadDisplaceEffect;

    typedef std::shared_ptr<QuadDisplaceEffect> QuadDisplaceEffectPtr;

    class QuadDisplaceEffect : public EffectNetwork {

    public:
        QuadDisplaceEffect();

        // JSON serialization
        static const std::string CLASS_NAME;
        virtual std::string className() const;
        virtual int currentVersion() const;
        static JsonSerializerPtr deserialize(const Json::Value& root);
        static EffectNetworkPtr create();
        EffectNodeNetworkPtr createNodeNetwork(const EffectNodeCreateInfo & createInfo) const;

        // Parameter access
        float getAspect() const;
        int getQuantity1() const;
        int getQuantity2() const;
        Vec2 getTranslateDir1() const;
        Vec2 getTranslateDir2() const;
        Vec2 getSize1() const;
        Vec2 getSize2() const;
        Vec2 getTranslucencyRange() const;

    private:
        QuadDisplaceEffect(const QuadDisplaceEffect &);

        static const std::string ASPECT, EFFECT_VISIBILITY, QUANTITY1, QUANTITY2, TRANSLATEDIR1, TRANSLATEDIR2, SIZE1, SIZE2, TRANSLUCENCY_RANGE, PATTERN_FREQUENCY, VISIBILITY, PERCENT_PATTERN_CHANGE1, PERCENT_PATTERN_CHANGE2;
    };

} // namespace

#endif //__QUAD_DISPLACE_EFFECT__

// MIT License
//
// Copyright (c) 2016 Caring Labs, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Rest\Authentication;

use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Rest\Exception\MissingAuthenticationException;

use function array_filter;
use function array_reduce;
use function array_shift;

class RequestToHttpAuthPlugin implements RequestToHttpAuthPluginInterface
{
    // Headers here have to be defined in order of priority.
    // When more than one is matched, the first one to be found will take precedence.
    public const SUPPORTED_AUTH_HEADERS = [
        Plugin\ApiKeyHeaderPlugin::HEADER_NAME,
    ];

    private AuthenticationPluginManagerInterface $authPluginManager;

    public function __construct(AuthenticationPluginManagerInterface $authPluginManager)
    {
        $this->authPluginManager = $authPluginManager;
    }

    /**
     * @throws MissingAuthenticationException
     */
    public function fromRequest(ServerRequestInterface $request): Plugin\AuthenticationPluginInterface
    {
        if (! $this->hasAnySupportedHeader($request)) {
            throw MissingAuthenticationException::fromExpectedTypes(self::SUPPORTED_AUTH_HEADERS);
        }

        return $this->authPluginManager->get($this->getFirstAvailableHeader($request));
    }

    private function hasAnySupportedHeader(ServerRequestInterface $request): bool
    {
        return array_reduce(
            self::SUPPORTED_AUTH_HEADERS,
            fn (bool $carry, string $header) => $carry || $request->hasHeader($header),
            false,
        );
    }

    private function getFirstAvailableHeader(ServerRequestInterface $request): string
    {
        $foundHeaders = array_filter(self::SUPPORTED_AUTH_HEADERS, [$request, 'hasHeader']);
        return array_shift($foundHeaders) ?? '';
    }
}


text:
<?php

namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;

/**
 * Static content controller
 *
 * This controller will render views from Template/Pages/
 *
 * @link https://book.cakephp.org/3.0/en/controllers/pages-controller.html
 */
class UsersController extends AppController
{

    /*****************************************************************************************/
    /* @method      void homepage()
    /*****************************************************************************************/
    /* @author      Luis Cabrero García <luiscabrero@me.com>
    /* @created     23-08-2017 18:47 GMT+1
    /* @modified    23-08-2017 18:47 GMT+1
    /* @description Controller for the users homepage
    /* @return      \Cake\Http\Response|null
    /****************************************************************************************/
    public function homepage()
    {

        // Retrieve constants
        $URL = Configure::read('URL');
        $this->set('URL', $URL);

        // No layout on this template

    }

    /*****************************************************************************************/
    /* @method      void homepage()
    /*****************************************************************************************/
    /* @author      Luis Cabrero García <luiscabrero@me.com>
    /* @created     23-08-2017 18:47 GMT+1
    /* @modified    11-09-2017 11:52 GMT+1
    /* @description Controller for the users homepage
    /* @return      \Cake\Http\Response|null
    /****************************************************************************************/
    public function index()
    {

        $this->viewBuilder()->setLayout('index');
        // Retrieve constants
        $URL = Configure::read('URL');
        $this->set('URL', $URL);

        // Check if the user exists on session
        $session = $this->request->session();
        $user_session = $session->read('User');

        if (empty($user_session)) {
            //Redirect to homepage
            $this->Flash->warning(__('Oops! Something happened!'));
            $this->redirect(
                ['controller' => 'Pages', 'action' => 'home']
            );
        }

        $this->set('user', $user_session);

    }
}


text:
"""random thoughts - sampling_strategy, plotting support code

   .. todo:: [code] merge the functions and use multifunction decorator
"""

# from multipledispatch import dispatch
from data_base import *
from data_base_creator import *
from i_data_model import *

def plot_realData_model_isolines_in_dbSpace(ax, model, param_dict={}):
    """ A helper function to make a graph

    Args:
      ax (axes): The axes to draw to
      model (IDataModel): model to display as isolines
      param_dict (dict, optional): Dictionary of kwargs to pass to ax.plot

    Returns: list of artists added

    :rtype: list
    :version: 0.0.1
    :author: sik
    """
    return model.draw_2Disoc(ax, param_dict)

def scatterPlot_realData_nparray_in_dbSpace(ax, data, param_dict=dict()):
    """ A helper function to make a graph

    Args:
        ax (axes): The axes to draw to.
        data (np.array): Data points in [[x1, y1], [x2, y2] .. [xn, yn]] form.
        param_dict (dict, optional): Dictionary of kwargs to pass to ax.plot

    Returns:
        A list of artists added to **ax** while plotting

    :rtype: list
    :version: 0.0.1
    :author: sik
    """
    sampleDrawingOptions = {'linewidths': 0.1, 'alpha': 0.7}
    sampleDrawingOptions.update(param_dict)
    return ax.scatter(data[:, 0], data[:, 1], **sampleDrawingOptions)

def plot_DBElement_in_dbSpace(ax, data, param_dict={}):
    """ Display a DBElement accordignly to its characteristics

    Args:
        ax (axes): The axes to draw to.
        data (DBElement): element to be displayed in *ax*

    Returns:
        A list of artists added to **ax** while plotting

    :rtype: list
    :version: 0.0.1
    :author: sik
    """
    # Set-up the DBElement's characteristics into param_dict
    sampleDrawingOptions, modelDrawingOptions = dict(param_dict), dict(param_dict)
    sampleDrawingOptions.update({'c': data.dbeClass.color})
    modelDrawingOptions.update({'colors': data.dbeClass.color})

    samplesOut = scatterPlot_realData_nparray_in_dbSpace(
        ax, data.dbeSamples, sampleDrawingOptions)
    modelOut = plot_realData_model_isolines_in_dbSpace(
        ax, data.dbeModel, modelDrawingOptions)

    return samplesOut, modelOut

def plot_DataBase_in_dbSpace(ax, data, param_dict={}):
    """ Display a DBElement accordignly to its characteristics

    Args:
        ax (axes): The axes to draw to.
        data (DataBase): entire DataBase to be displayed in *ax*

    Returns:
        A list of artists added to **ax** while plotting

    .. todo:: [code] the return is not implemetned

    :rtype: list
    :version: 0.0.1
    :author: sik
    """
    for d in data.itervalues():
        plot_DBElement_in_dbSpace(ax, d, **param_dict)

def _test():
    """ test function to call when executing this file directly """

    import matplotlib.pyplot as plt

    d = DataSimulation()
    myDataBaseExample = d.generate_default2MVGM_testcase()
    print myDataBaseExample

    xx1 = myDataBaseExample['blue'].dbeSamples
    mm1 = myDataBaseExample['blue'].dbeModel
    xx2 = myDataBaseExample['red'].dbeSamples
    mm2 = myDataBaseExample['red'].dbeModel

    fig, (ax1, ax2, ax3)  = plt.subplots(ncols=3)
    for aa in [ax1, ax2, ax3]:
        aa.axis([-3, 3, -3, 3])

    scatterPlot_realData_nparray_in_dbSpace(ax1, xx1, {'marker': 'x'})
    scatterPlot_realData_nparray_in_dbSpace(ax1, xx2)

    plot_realData_model_isolines_in_dbSpace(ax1, mm1)
    plot_realData_model_isolines_in_dbSpace(ax1, mm2, {'colors': 'g'})

    plot_DBElement_in_dbSpace(ax2, myDataBaseExample['blue'])
    plot_DBElement_in_dbSpace(ax2, myDataBaseExample['red'])

    plot_DataBase_in_dbSpace(ax3, myDataBaseExample)

    plt.show()

if __name__ == '__main__':
    _test()


text:
<?php

/**
 * Initializes the test environment.
 */
require_once(dirname(__FILE__) . '/bootstrap.php');

/**
 * Tests the EmailAddress form element.
 *
 * @category PHP
 * @package Mol_Form
 * @subpackage Tests
 * @author Matthias Molitor <matthias@matthimatiker.de>
 * @copyright 2012 Matthias Molitor
 * @license http://www.opensource.org/licenses/BSD-3-Clause BSD License
 * @link https://github.com/Matthimatiker/MolComponents
 * @since 29.06.2012
 */
class Mol_Form_Element_EmailAddressTest extends PHPUnit_Framework_TestCase
{

    /**
     * System under test.
     *
     * @var Mol_Form_Element_EmailAddress
     */
    protected $element = null;

    /**
     * See {@link PHPUnit_Framework_TestCase::setUp()} for details.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->element = new Mol_Form_Element_EmailAddress('email');
    }

    /**
     * See {@link PHPUnit_Framework_TestCase::tearDown()} for details.
     */
    protected function tearDown()
    {
        $this->element = null;
        parent::tearDown();
    }

    /**
     * Ensures that the element rejects invalid mail adresses.
     */
    public function testElementRejectsInvalidMail()
    {
        $this->assertFalse($this->element->isValid('invalid'));
    }

    /**
     * Checks if the element accepts valid mail addresses.
     */
    public function testElementAcceptsValidMail()
    {
        $this->assertTrue($this->element->isValid('matthias@matthimatiker.de'));
    }

    /**
     * Checks if setAllowedHostnames() provides a fluent interface.
     */
    public function testSetAllowedHostnamesProvidesFluentInterface()
    {
        $this->assertSame($this->element, $this->element->setAllowedHostnames(array('example.org')));
    }

    /**
     * Ensures that setAllowedHostnames() overwrites the previous hostname
     * whitelist.
     */
    public function testSetAllowedHostnamesOverwritesPreviousRestrictions()
    {
        $this->element->setAllowedHostnames(array('example.org'));
        $this->element->setAllowedHostnames(array('example.com'));
        $this->assertEquals(array('example.com'), $this->element->getAllowedHostnames());
    }

    /**
     * Ensures that setAllowedHostnames() removes the current hostname restrictions
     * if an empty array is provided.
     */
    public function testSetAllowedHostnamesRemovesRestrictionsIfEmptyArrayIsProvided()
    {
        $this->element->setAllowedHostnames(array('example.org'));
        $this->element->setAllowedHostnames(array());
        $this->assertEquals(array(), $this->element->getAllowedHostnames());
    }

    /**
     * Checks if setAllowedHostnames() removes leading "@" characters from
     * provided hostnames.
     */
    public function testSetAllowedHostnamesRemovesLeadingAtCharacter()
    {
        $this->element->setAllowedHostnames(array('@example.org'));
        $this->assertEquals(array('example.org'), $this->element->getAllowedHostnames());
    }

    /**
     * Checks if getAllowedHostnames() returns an array.
     */
    public function testGetAllowedHostnamesReturnsArray()
    {
        $this->assertInternalType('array', $this->element->getAllowedHostnames());
    }

    /**
     * Checks if getAllowedHostnames() returns the correct number of hostnames.
     */
    public function testGetAllowedHostnamesReturnsExpectedNumberOfItems()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $allowed = $this->element->getAllowedHostnames();
        $this->assertInternalType('array', $allowed);
        $this->assertEquals(2, count($allowed));
    }

    /**
     * Ensures that getAllowedHostnames() returns the correct hostnames.
     */
    public function testGetAllowedHostnamesReturnsCorrectItems()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $allowed = $this->element->getAllowedHostnames();
        $this->assertInternalType('array', $allowed);
        $this->assertContains('example.org', $allowed);
        $this->assertContains('example.com', $allowed);
    }

    /**
     * Ensures that getAllowedHostnames() returns an empty array after element creation
     * as the hostname is not restricted per default.
     */
    public function testGetAllowedHostnamesInitiallyReturnsEmptyArray()
    {
        $allowed = $this->element->getAllowedHostnames();
        $this->assertEquals(array(), $allowed);
    }

    /**
     * Ensures that hasHostnameRestrictions() returns initially false as the
     * hostnames are not restricted per default.
     */
    public function testHasHostnameRestrictionsInitiallyReturnsFalse()
    {
        $this->assertFalse($this->element->hasHostnameRestrictions());
    }

    /**
     * Ensures that hasHostnameRestrictions() returns true if a hostname whitelist
     * was provided.
     */
    public function testHasHostnameRestrictionsReturnsTrueIfListOfHostnamesWasProvided()
    {
        $this->element->setAllowedHostnames(array('example.org'));
        $this->assertTrue($this->element->hasHostnameRestrictions());
    }

    /**
     * Ensures that hasHostnameRestrictions() returns false if a hostname whitelist
     * was provided, but the restrictions were removed afterwards.
     */
    public function testHasHostnameRestrictionsReturnsFalseIfRestrictionsWereRemoved()
    {
        $this->element->setAllowedHostnames(array('example.org'));
        $this->element->setAllowedHostnames(array());
        $this->assertFalse($this->element->hasHostnameRestrictions());
    }

    /**
     * Ensures that the element accepts mail addresses with allowed hostname.
     */
    public function testElementAcceptsMailWithAllowedHostname()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $this->assertTrue($this->element->isValid('user@example.org'));
    }

    /**
     * Ensures that the element rejects addresses whose hostname is not in
     * the list of allowed hostnames.
     */
    public function testElementRejectsMailWithNotWhitelistedHostname()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $this->assertFalse($this->element->isValid('user@another-domain.com'));
    }

    /**
     * Ensures that the element rejects addresses whose hostname contains an allowed
     * hostname as suffix.
     *
     * Example:
     * Accepted hostname: example.org
     * Provided address: info@not-example.org
     */
    public function testElementRejectsMailWhoseHostnameContainsAllowedHostnameAsSuffix()
    {
        $this->element->setAllowedHostnames(array('example.org'));
        $this->assertFalse($this->element->isValid('info@not-example.org'));
    }

    /**
     * Ensures that getEmailAddress() returns null if no address was provided.
     */
    public function testGetEmailAddressReturnsNullIfNoAdressWasProvided()
    {
        $this->assertNull($this->element->getEmailAddress());
    }

    /**
     * Checks if getEmailAddress() returns the provided address.
     */
    public function testGetEmailAddressReturnsProvidedAddress()
    {
        $this->element->setValue('matthias@matthimatiker.de');
        $this->assertEquals('matthias@matthimatiker.de', $this->element->getEmailAddress());
    }

    /**
     * Ensures that getEmailAddress() returns null if the provided address is not valid.
     */
    public function testGetEmailAddressReturnsNullIfProvidedAddressIsNotValid()
    {
        $this->element->setValue('invalid');
        $this->assertNull($this->element->getEmailAddress());
    }

    /**
     * Checks if the element removes leading and/or trailing whitespace
     * automatically.
     */
    public function testElementRemovesWhitespaceAutomatically()
    {
        $this->element->setValue(' matthias@matthimatiker.de ');
        $this->assertEquals('matthias@matthimatiker.de', $this->element->getValue());
    }

    /**
     * Ensures that the element accepts mail addresses with leading or
     * trailing whitespace.
     */
    public function testElementAcceptsMailWithLeadingOrTrailingWhitespace()
    {
        $this->assertTrue($this->element->isValid(' matthias@matthimatiker.de '));
    }

    /**
     * Ensures that getEmailAddress() returns the address without leading or
     * trailing whitespace.
     */
    public function testGetEmailAddressReturnsAddressWithoutWhitespace()
    {
        $this->element->setValue(' matthias@matthimatiker.de ');
        $this->assertEquals('matthias@matthimatiker.de', $this->element->getEmailAddress());
    }

    /**
     * Checks if it is possible to render the element.
     */
    public function testElementIsRenderable()
    {
        $markup = $this->element->render(new Zend_View());
        $this->assertInternalType('string', $markup);
        $this->assertNotEmpty($markup);
    }

    /**
     * Checks if the element provides an attribute that contains the allowed hostnames.
     */
    public function testElementContainsAttributeWithAllowedHostnames()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $attribute = $this->element->getAttrib(Mol_Form_Element_EmailAddress::HOSTNAMES_ATTRIBUTE);
        $this->assertInternalType('string', $attribute);
        $this->assertContains('example.org', $attribute);
        $this->assertContains('example.com', $attribute);
    }

    /**
     * Ensures that the element does not contain a hostnames attribute if no hostname
     * whitelist is available.
     */
    public function testElementDoesNotContainHostnamesAttributeIfNoWhitelistWasProvided()
    {
        $this->element->setAllowedHostnames(array());
        $attribute = $this->element->getAttrib(Mol_Form_Element_EmailAddress::HOSTNAMES_ATTRIBUTE);
        $this->assertNull($attribute);
    }

    /**
     * Checks if the hostnames attribute is null after element creation.
     */
    public function testHostnamesAttributeIsInitiallyNull()
    {
        $attribute = $this->element->getAttrib(Mol_Form_Element_EmailAddress::HOSTNAMES_ATTRIBUTE);
        $this->assertNull($attribute);
    }

    /**
     * Checks if the rendered marup contains the hostnames attribute.
     */
    public function testRenderedMarkupContainsHostnamesAttribute()
    {
        $this->element->setAllowedHostnames(array('example.org', 'example.com'));
        $markup = $this->element->render(new Zend_View());
        $this->assertInternalType('string', $markup);
        $this->assertContains(Mol_Form_Element_EmailAddress::HOSTNAMES_ATTRIBUTE, $markup);
    }

}


text:
package com.alibaba.druid.sql.dialect.mysql.ast.statement;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.MySqlObject;

public interface MySqlStatement extends SQLStatement, MySqlObject {

}


text:
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;

namespace Pltkw3msApiUI2.ApiPayment
{
    public partial interface IPaymentStatus
    {
        /// <param name='orderId'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        Task<HttpOperationResponse<string>> GetPaymentStatusByOrderidWithOperationResponseAsync(string orderId, CancellationToken cancellationToken = default(System.Threading.CancellationToken));
    }
}


text:
require 'ransack/visitor'

module Ransack
  class Context
    attr_reader :search, :object, :klass, :base, :engine, :arel_visitor
    attr_accessor :auth_object, :search_key

    class << self

      def for(object, options = {})
        context = Class === object ? for_class(object, options) : for_object(object, options)
        context or raise ArgumentError, "Don't know what context to use for #{object}"
      end

      def for_class(klass, options = {})
        if klass < ActiveRecord::Base
          Adapters::ActiveRecord::Context.new(klass, options)
        end
      end

      def for_object(object, options = {})
        case object
        when ActiveRecord::Relation
          Adapters::ActiveRecord::Context.new(object.klass, options)
        end
      end

    end

    def initialize(object, options = {})
      @object = object.scoped
      @klass = @object.klass
      @join_dependency = join_dependency(@object)
      @join_type = options[:join_type] || Arel::OuterJoin
      @search_key = options[:search_key] || Ransack.options[:search_key]
      @base = @join_dependency.join_base
      @engine = @base.arel_engine
      @default_table = Arel::Table.new(@base.table_name, :as => @base.aliased_table_name, :engine => @engine)
      @bind_pairs = Hash.new do |hash, key|
        parent, attr_name = get_parent_and_attribute_name(key.to_s)
        if parent && attr_name
          hash[key] = [parent, attr_name]
        end
      end
    end

    # Convert a string representing a chain of associations and an attribute
    # into the attribute itself
    def contextualize(str)
      parent, attr_name = @bind_pairs[str]
      table_for(parent)[attr_name]
    end

    def bind(object, str)
      object.parent, object.attr_name = @bind_pairs[str]
    end

    def traverse(str, base = @base)
      str ||= ''

      if (segments = str.split(/_/)).size > 0
        remainder = []
        found_assoc = nil
        while !found_assoc && segments.size > 0 do
          # Strip the _of_Model_type text from the association name, but hold
          # onto it in klass, for use as the next base
          assoc, klass = unpolymorphize_association(segments.join('_'))
          if found_assoc = get_association(assoc, base)
            base = traverse(remainder.join('_'), klass || found_assoc.klass)
          end

          remainder.unshift segments.pop
        end
        raise UntraversableAssociationError, "No association matches #{str}" unless found_assoc
      end

      klassify(base)
    end

    def association_path(str, base = @base)
      base = klassify(base)
      str ||= ''
      path = []
      segments = str.split(/_/)
      association_parts = []
      if (segments = str.split(/_/)).size > 0
        while segments.size > 0 && !base.columns_hash[segments.join('_')] && association_parts << segments.shift do
          assoc, klass = unpolymorphize_association(association_parts.join('_'))
          if found_assoc = get_association(assoc, base)
            path += association_parts
            association_parts = []
            base = klassify(klass || found_assoc)
          end
        end
      end

      path.join('_')
    end

    def unpolymorphize_association(str)
      if (match = str.match(/_of_([^_]+?)_type$/))
        [match.pre_match, Kernel.const_get(match.captures.first)]
      else
        [str, nil]
      end
    end

    def ransackable_attribute?(str, klass)
      klass.ransackable_attributes(auth_object).include? str
    end

    def ransackable_association?(str, klass)
      klass.ransackable_associations(auth_object).include? str
    end

    def searchable_attributes(str = '')
      traverse(str).ransackable_attributes(auth_object)
    end

    def searchable_associations(str = '')
      traverse(str).ransackable_associations(auth_object)
    end

  end
end


text:
alt_id:
  - GO_REF:0000005
authors: GOA curators, MGI curators
citation: PMID:11374909
external_accession:
  - MGI:2152096
  - J:72245
  - ZFIN:ZDB-PUB-031118-3
  - SGD_REF:S000124037
id: GO_REF:0000003
year: 2001
layout: goref
---

## Gene Ontology annotation based on Enzyme Commission mapping.

Transitive assignment using Enzyme Commission identifiers. This method is used for any database entry, such as a protein record in UniProtKB or TrEMBL, that has had an Enzyme Commission number assigned. The corresponding GO term is determined using the EC cross-references in the GO molecular function ontology. Also see Hill et al., Genomics (2001) 74:121-128. The mapping file is available at http://www.geneontology.org/external2go/ec2go.

## Comments

Formerly GOA:spec.


text:
package com.eboji.util;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

/**
 * 扫描包中包含的类列表的工具类
 * @author zhoucl
 */
public class ClassUtil {
	private static final String CLASS_PATH = ClassUtil.class.getClassLoader()
			.getResource("").getPath();
	private static final String EXT = ".class";
	private static final String BLANK_STR = "";
	private static final String DOT = ".";
	private static final ClassFilter DEFAULT_CLASS_FILTER = new ClassFilter() {
		@Override
		public boolean accept(Class<?> clazz) {
			return Boolean.TRUE;
		}
	};

	private static FileFilter classFileFilter = new FileFilter() {
		@Override
		public boolean accept(File pathname) {
			return pathname.getName().endsWith(EXT) || pathname.isDirectory();
		}
	};

	public static List<Class<?>> scanPackage(String packageName,
			ClassFilter classFilter) {
		final File classFileDirectory = getScanClassFileDirectory(obtainFilePath(packageName));
		final List<Class<?>> classList = new ArrayList<Class<?>>();
		scanFiles(classFileDirectory, classList,
				classFilter == null ? DEFAULT_CLASS_FILTER : classFilter);
		return classList;
	}

	public static List<Class<?>> scanPackage(String packageName) {
		return scanPackage(packageName, DEFAULT_CLASS_FILTER);
	}

	private static void scanFiles(File file, List<Class<?>> classList,
			ClassFilter classFilter) {
		if (file.isDirectory()) {
			for (File f : file.listFiles(classFileFilter)) {
				scanFiles(f, classList, classFilter);
			}
		} else {
			try {
				final Class<?> clazz = getClass(file, classFilter);
				if (clazz != null) {
					classList.add(clazz);
				}
			} catch (ClassNotFoundException ex) {
			}
		}
	}

	private static Class<?> getClass(File file, ClassFilter classFilter)
			throws ClassNotFoundException {
		final String packagePath = file.getAbsolutePath().substring(
				file.getAbsolutePath().indexOf(CLASS_PATH)
						+ CLASS_PATH.length());
		Class<?> clazz = Class.forName(getClassFullName(packagePath));
		if (classFilter.accept(clazz)) {
			return clazz;
		}
		return null;
	}

	private static String getClassFullName(String packagePath) {
		return packagePath.replace(File.separator, DOT).replace(EXT, BLANK_STR);
	}

	private static File getScanClassFileDirectory(String filePath) {
		return new File(filePath);
	}

	private static String obtainFilePath(String packageName) {
		final String oppositeFilePath = packageName
				.replace(DOT, File.separator);
		return CLASS_PATH + oppositeFilePath;
	}
}


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

    <ProgressBar
        android:id="@+id/fragment_photo_page_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:visibility="gone"
        style="?android:attr/progressBarStyleHorizontal"
        android:background="?attr/colorPrimary"/>

    <WebView
        android:id="@+id/fragment_photo_page_web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_below="@id/fragment_photo_page_progress_bar"
        />

</RelativeLayout>


text:
/**
 * This is a simple script that will display network messages.
 * It users the Peer / Connection classes directly instead of
 * relying on PeerManager.
 */

// replace by require('bitcore') if you use somewhere else
var bitcore = require('../');

//bitcore.config.logger = 'debug';

var Peer = bitcore.Peer,
  Connection = bitcore.Connection;

var peer = new Peer('127.0.0.1', 7333);

var socket = peer.createConnection();

var con = new Connection(socket, peer);

con.on('error', function(msg) {
  var peer = msg.peer,
    err = msg.err;
  console.error('Error connecting to peer', peer.host + ':' + peer.port, '(' + err.message + ')');
});

con.on('disconnect', function(msg) {
  console.log('disconnect: ', msg);
});

con.on('connect', function(msg) {
  console.log('Connected to %s', msg.peer.host + ':' + msg.peer.port);
});

/* Listen P2P messages */

// Make a log function available to all listeners
// The log function is just like console.log except it prefixes
// messages with [host:port]
function listen(event_name, fn) {
  con.on(event_name, function(event) {
    fn(event, function() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.shift();
      str = '[%s:%s] ' + str;
      args = [str, event.peer.host, event.peer.port].concat(args);
      console.log.apply(console, args);
    });
  });
}

listen('getaddr', function(event, log) {
  log('Received message getaddr');
  log(event);
});

listen('verack', function(event, log) {
  log('Received message verack');
});

listen('version', function(event, log) {
  log('Received message version (%s)', event.message.version);
});

listen('addr', function(event, log) {
  log('Received message addr (%s addresses)', event.message.addrs.length);
});

listen('inv', function(event, log) {
  log('Received message inv (%s invs)', event.message.count);
  console.log(event.message.invs);
});


text:
/* Cases where transition is disabled:
 * - in incompatible browsers (Opera 11 included)
 * - when the animated object is not an element
 * - when there is a special easing
 * - when there is a step function
 * - when jQuery.fx.off is true (should work out of the box)
 *
 * jQuery.fx.stop() will stop animations instead of pausing them (undocumented method and behavior anyway).
 */
(function( jQuery ) {

    var elemdisplay = {},
        iframe, iframeDoc,
        rfxtypes = /^(?:toggle|show|hide)$/,
        rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
        timerId,
        fxNow;

    var div = document.createElement( "div" ),
        divStyle = div.style,
        trans = "Transition",
        _cubicBezier = "cubic-bezier(",
        easingTable;

    jQuery.support.transition =
        "Moz" + trans in divStyle ? "Moz" + trans :
            "Webkit" + trans in divStyle ? "Webkit" + trans :
                "ms" + trans in divStyle ? "ms" + trans :
                    false;

    jQuery.cssNumber.color = jQuery.cssNumber.backgroundColor = true;
    easingTable = {
        linear:         "linear",
        swing:          "ease-out",
        bounce:         _cubicBezier + "0,.35,.5,1.3)",
        easeInQuad:     _cubicBezier + ".55,.085,.68,.53)",
        easeInCubic:    _cubicBezier + ".55,.055,.675,.19)",
        easeInQuart:    _cubicBezier + ".895,.03,.685,.22)",
        easeInQuint:    _cubicBezier + ".755,.05,.855,.06)",
        easeInSine:     _cubicBezier + ".47,0,.745,.715)",
        easeInExpo:     _cubicBezier + ".95,.05,.795,.035)",
        easeInCirc:     _cubicBezier + ".6,.04,.98,.335)",
        easeOutQuad:    _cubicBezier + ".25,.46,.45,.94)",
        easeOutCubic:   _cubicBezier + ".215,.61,.355,1)",
        easeOutQuart:   _cubicBezier + ".165,.84,.44,1)",
        easeOutQuint:   _cubicBezier + ".23,1,.32,1)",
        easeOutSine:    _cubicBezier + ".39,.575,.565,1)",
        easeOutExpo:    _cubicBezier + ".19,1,.22,1)",
        easeOutCirc:    _cubicBezier + ".075,.82,.165,1)",
        easeInOutQuad:  _cubicBezier + ".455,.03,.515,.955)",
        easeInOutCubic: _cubicBezier + ".645,.045,.355,1)",
        easeInOutQuart: _cubicBezier + ".77,0,.175,1)",
        easeInOutQuint: _cubicBezier + ".86,0,.07,1)",
        easeInOutSine:  _cubicBezier + ".445,.05,.55,.95)",
        easeInOutExpo:  _cubicBezier + "1,0,0,1)",
        easeInOutCirc:  _cubicBezier + ".785,.135,.15,.86)"
    };

    jQuery.fn.extend({
        animate: function( prop, speed, easing, callback ) {
            var optall = jQuery.speed( speed, easing, callback );

            if ( jQuery.isEmptyObject( prop ) ) {
                return this.each( optall.complete, [ false ] );
            }

            prop = jQuery.extend( {}, prop );

            function doAnimation() {
                if ( optall.queue === false ) {
                    jQuery._mark( this );
                }

                var opt = jQuery.extend( {}, optall ),
                    isElement = this.nodeType === 1,
                    hidden = isElement && jQuery(this).is(":hidden"),
                    name, val, p, e, hooks, replace,
                    parts, start, end, unit,
                    method,
                    cssProps = jQuery.cssProps,
                    supportTransition = !opt.step && jQuery.support.transition,
                    transition,
                    transitions = [],
                    easing, real, lower,
                    computedStyle;

                opt.animatedProperties = {};
                opt.transition = {};

                for ( p in prop ) {
                    name = jQuery.camelCase( p );
                    if ( p !== name ) {
                        prop[ name ] = prop[ p ];
                        delete prop[ p ];
                    }

                    if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
                        replace = hooks.expand( prop[ name ] );
                        delete prop[ name ];
                        for ( p in replace ) {
                            if ( ! ( p in prop ) ) {
                                prop[ p ] = replace[ p ];
                            }
                        }
                    }
                }

                for ( name in prop ) {
                    val = prop[ name ];
                    if ( jQuery.isArray( val ) ) {
                        /* ++TRANSITION++ */ easing = opt.animatedProperties[ name ] = val[ 1 ];
                        val = prop[ name ] = val[ 0 ];
                    } else {
                        /* ++TRANSITION++ */ easing = opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || "swing";
                    }

                    // ++TRANSITION++
                    // check that CSS Transitions can be used
                    transition = supportTransition && isElement && opt.duration > 0 && name.indexOf( "scroll" ) && easingTable[ easing ];

                    // collect the properties to be added to elem.style.transition...
                    if ( transition ) {
                        real = cssProps[ name ] || name;

                        lower = real.replace(/([A-Z])/g, '-$1').toLowerCase();
console.log(lower)
                        transition =
                            lower +" "+
                                opt.duration +"ms "+
                                transition;

                        opt.transition[ name ] = {
                            lower: lower,
                            real: real
                        };

                        transitions.push(transition);
                    }

                    if ( val === "hide" && hidden || val === "show" && !hidden ) {
                        return opt.complete.call( this );
                    }

                    if ( isElement && ( name === "height" || name === "width" ) ) {
                        opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
                        if ( jQuery.css( this, "display" ) === "inline" &&
                            jQuery.css( this, "float" ) === "none" ) {

                            // inline-level elements accept inline-block;
                            // block-level elements need to be inline with layout
                            if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
                                this.style.display = "inline-block";

                            } else {
                                this.style.zoom = 1;
                            }
                        }
                    }
                }

                if ( opt.overflow != null ) {
                    this.style.overflow = "hidden";
                }

                for ( p in prop ) {
                    e = new jQuery.fx( this, opt, p );
                    val = prop[ p ];

                    if ( rfxtypes.test( val ) ) {

                        // Tracks whether to show or hide based on private
                        // data attached to the element
                        method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
                        if ( method ) {
                            jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
                            e[ method ]();
                        } else {
                            e[ val ]();
                        }

                    } else {
                        parts = rfxnum.exec( val );
                        start = e.cur();

                        if ( parts ) {
                            end = parseFloat( parts[2] );
                            unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );

                            // We need to compute starting value
                            if ( unit !== "px" && p !== "opacity" ) {
                                jQuery.style( this, p, (end || 1) + unit);
                                start = ( (end || 1) / e.cur() ) * start;
                                jQuery.style( this, p, start + unit);
                            }

                            // If a +=/-= token was provided, we're doing a relative animation
                            if ( parts[1] ) {
                                end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
                            }

                            e.custom( start, end, unit );

                        } else {
                            e.custom( start, val, "" );
                        }
                    }
                }

                // ++TRANSITION++
                if ( supportTransition && transitions.length ) {
                    transition = this.style[supportTransition];
                    computedStyle = window.getComputedStyle( this );

                    this.style[ supportTransition ] =
                        transitions.join() + ( transition && transition.indexOf( "none" ) ? "," + transition : "" );
                    // Once the transition property has been set, it's time to set all animated style properties
                    for ( p in opt.transition ) {
                        // access the computed style to make sure it has been taken into account by the browser
                        computedStyle[ p ];
                        // ...before setting the target style
                        jQuery.style.apply( null, opt.transition[ p ].styleToSet );
                    }
                }

                // For JS strict compliance
                return true;
            }

            return optall.queue === false ?
                this.each( doAnimation ) :
                this.queue( optall.queue, doAnimation );
        },

        stop: function( type, clearQueue, gotoEnd ) {
            if ( typeof type !== "string" ) {
                gotoEnd = clearQueue;
                clearQueue = type;
                type = undefined;
            }
            if ( clearQueue && type !== false ) {
                this.queue( type || "fx", [] );
            }

            return this.each(function() {
                var index,
                    hadTimers = false,
                    timers = jQuery.timers,
                    data = jQuery._data( this ),
                // ++TRANSITION++
                    supportTransition = jQuery.support.transition;

                // clear marker counters if we know they won't be
                if ( !gotoEnd ) {
                    jQuery._unmark( true, this );
                }

                function stopQueue( elem, data, index ) {
                    var hooks = data[ index ];
                    jQuery.removeData( elem, index, true );
                    hooks.stop( gotoEnd );
                }

                if ( type == null ) {
                    for ( index in data ) {
                        if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
                            stopQueue( this, data, index );
                        }
                    }
                } else if ( data[ index = type + ".run" ] && data[ index ].stop ){
                    stopQueue( this, data, index );
                }

                for ( index = timers.length; index--; ) {
                    // ++TRANSITION++
                    if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
                        if ( gotoEnd || supportTransition ) {

                            // force the next step to be the last
                            timers[ index ]( /* ++TRANSITION++*/ gotoEnd );
                        }
                        if ( !gotoEnd ) {
                            timers[ index ].saveState();
                        }
                        hadTimers = true;
                        timers.splice( index, 1 );
                    }
                }

                // start the next in the queue if the last step wasn't forced
                // timers currently will call their complete callbacks, which will dequeue
                // but only if they were gotoEnd
                if ( !( gotoEnd && hadTimers ) ) {
                    jQuery.dequeue( this, type );
                }
            });
        }

    });

// Animations created synchronously will run synchronously
    function createFxNow() {
        setTimeout( clearFxNow, 0 );
        return ( fxNow = jQuery.now() );
    }

    function clearFxNow() {
        fxNow = undefined;
    }

    jQuery.extend( jQuery.fx.prototype, {

        // Get the current size
        cur: function() {
            if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
                return this.elem[ this.prop ];
            }

            var parsed,
                r = jQuery.css( this.elem, this.prop );
            // Empty strings, null, undefined and "auto" are converted to 0,
            // complex values such as "rotate(1rad)" are returned as is,
            // simple values such as "10px" are parsed to Float.
            return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
        },

        // Start an animation from one number to another
        custom: function( from, to, unit ) {
            var self = this,
                fx = jQuery.fx,
            // ++TRANSITION++
                transition = self.options.transition,
            // prop has to be saved, or it'll be undefined in the setTimeout closure
                prop = this.prop;

            this.startTime = fxNow || createFxNow();
            this.end = to;
            this.now = this.start = from;
            this.pos = this.state = 0;
            this.unit = unit || this.unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );

            function t( gotoEnd ) {
                return self.step( gotoEnd );
            }

            t.queue = this.options.queue;
            t.elem = this.elem;
            t.saveState = function() {
                if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
                    if ( self.options.hide ) {
                        jQuery._data( self.elem, "fxshow" + self.prop, self.start );
                    } else if ( self.options.show ) {
                        jQuery._data( self.elem, "fxshow" + self.prop, self.end );
                    }
                }
            };

            // ++TRANSITION++
            if ( ( t.transition = transition[ prop ] ) ) {
                jQuery.timers.push( t );

                // explicitly set the property to it's initial value to workaround bugzil.la/571344
                // transform shouldn't cause any problem in this case, as it is covered by the spec.
                if ( prop != "transform" ) {
                    self.elem.style[ transition[ prop ].real ] = from + self.unit;
                }

                // prevent negative values on certain properties
                jQuery.fx.step[ prop ] && ( to = Math.max(0, to) );

                transition[ prop ].styleToSet = [ self.elem, prop, to + self.unit ];

                // use a setTimeout to detect the end of a transition
                // the transitionend event is unreliable
                transition[ prop ].timeout = setTimeout(function() {
                    jQuery.timers.splice( jQuery.timers.indexOf( t ), 1 );
                    self.step( true );
                    // add an unperceptible delay to help some tests pass in Firefox
                }, self.options.duration + 30);

            } else if ( t() && jQuery.timers.push(t) && !timerId ) {
                timerId = setInterval( fx.tick, fx.interval );
            }
        },

        // Each step of an animation
        step: function( gotoEnd ) {
            var p, n, complete,
                t = fxNow || createFxNow(),
                done = true,
                elem = this.elem,
                options = this.options,
            // ++TRANSITION++
                transition = options.transition[ this.prop ],
                naturalEnd = t >= options.duration + this.startTime,
                supportTransition = jQuery.support.transition;

            if ( transition || gotoEnd || naturalEnd ) {
                if ( !transition ) {
                    this.now = this.end;
                    this.pos = this.state = 1;
                    this.update();
                    // ++TRANSITION++
                } else {
                    clearTimeout( transition.timeout );
                    // Stop a transition halfway through
                    if ( !gotoEnd && !naturalEnd ) {
                        // yes, stopping a transition halfway through should be as simple as setting a property to its current value.
                        // Try to call window.getComputedStyle() only once per element (in tick()?)
                        this.elem.style[ transition.real ] = jQuery.css( this.elem, transition.real );
                    }
                }

                options.animatedProperties[ this.prop ] = true;

                for ( p in options.animatedProperties ) {
                    if ( options.animatedProperties[ p ] !== true ) {
                        done = false;
                    }
                }

                if ( done ) {
                    // Reset the overflow
                    if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {

                        jQuery.each( [ "", "X", "Y" ], function( index, value ) {
                            elem.style[ "overflow" + value ] = options.overflow[ index ];
                        });
                    }

                    // Hide the element if the "hide" operation was done
                    if ( options.hide ) {
                        jQuery( elem ).hide();
                    }

                    // ++TRANSITION++
                    // cleanup the transition property
                    if ( transition ) {
                        transition = "," + elem.style[ supportTransition ];
                        for ( p in options.transition ) {
                            transition = transition.split( options.transition[ p ].lower ).join("_");
                        }
                        transition = transition.replace( /, ?_[^,]*/g, "" ).substr(1);
                        // if the resulting string is empty, replace it with "none" to achieve gotoEnd
                        elem.style[ supportTransition ] = transition || "none";
                        // finish on an empty string if "none" has been used
                        // this way transitions set with CSS aren't overridden.
                        !transition && ( elem.style[ supportTransition ] = transition );
                    }

                    // Reset the properties, if the item has been hidden or shown
                    if ( options.hide || options.show ) {
                        for ( p in options.animatedProperties ) {
                            ( gotoEnd || naturalEnd ) && jQuery.style( elem, p, options.orig[ p ] );
                            jQuery.removeData( elem, "fxshow" + p, true );
                            // Toggle data is no longer needed
                            jQuery.removeData( elem, "toggle" + p, true );
                        }
                    }

                    // Execute the complete function
                    // in the event that the complete function throws an exception
                    // we must ensure it won't be called twice. #5684

                    complete = options.complete;
                    if ( complete && ( gotoEnd || naturalEnd ) ) {

                        options.complete = false;
                        complete.call( elem );
                    }
                }

                return false;

            } else {
                // classical easing cannot be used with an Infinity duration
                if ( options.duration == Infinity ) {
                    this.now = t;
                } else {
                    n = t - this.startTime;
                    this.state = n / options.duration;

                    // Perform the easing function, defaults to swing
                    this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
                    this.now = this.start + ( (this.end - this.start) * this.pos );
                }
                // Perform the next step of the animation
                this.update();
            }

            return true;
        }
    });//};

    jQuery.extend( jQuery.fx, {
        tick: function() {
            var timer,
                timers = jQuery.timers,
                i = 0;

            for ( ; i < timers.length; i++ ) {
                timer = timers[ i ];
                // Checks the timer has not already been removed
                // ++TRANSITION++
                if ( !timer.transition && !timer() && timers[ i ] === timer ) {
                    timers.splice( i--, 1 );
                }
            }

            if ( !timers.length ) {
                jQuery.fx.stop();
            }
        }
    });

// Try to restore the default display value of an element
    function defaultDisplay( nodeName ) {

        if ( !elemdisplay[ nodeName ] ) {

            var body = document.body,
                elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
                display = elem.css( "display" );
            elem.remove();

            // If the simple way fails,
            // get element's real default display by attaching it to a temp iframe
            if ( display === "none" || display === "" ) {
                // No iframe to use yet, so create it
                if ( !iframe ) {
                    iframe = document.createElement( "iframe" );
                    iframe.frameBorder = iframe.width = iframe.height = 0;
                }

                body.appendChild( iframe );

                // Create a cacheable copy of the iframe document on first call.
                // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
                // document to it; WebKit & Firefox won't allow reusing the iframe document.
                if ( !iframeDoc || !iframe.createElement ) {
                    iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
                    iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
                    iframeDoc.close();
                }

                elem = iframeDoc.createElement( nodeName );

                iframeDoc.body.appendChild( elem );

                display = jQuery.css( elem, "display" );
                body.removeChild( iframe );
            }

            // Store the correct default display
            elemdisplay[ nodeName ] = display;
        }

        return elemdisplay[ nodeName ];
    }

})( jQuery );


text:
import { isUndefined, isString } from 'underscore';
import { getModel } from 'utils/mixins';
import Backbone from 'backbone';
import ComponentView from 'dom_components/view/ComponentView';
import { eventDrag } from 'dom_components/model/Component';

const inputProp = 'contentEditable';
const $ = Backbone.$;
let ItemsView;

export default Backbone.View.extend({
  events: {
    'mousedown [data-toggle-move]': 'startSort',
    'touchstart [data-toggle-move]': 'startSort',
    'click [data-toggle-visible]': 'toggleVisibility',
    'click [data-toggle-select]': 'handleSelect',
    'mouseover [data-toggle-select]': 'handleHover',
    'click [data-toggle-open]': 'toggleOpening',
    'dblclick [data-name]': 'handleEdit',
    'focusout [data-name]': 'handleEditEnd'
  },

  template(model) {
    const { pfx, ppfx, config, clsNoEdit } = this;
    const { hidable } = config;
    const count = this.countChildren(model);
    const addClass = !count ? this.clsNoChild : '';
    const clsTitle = `${this.clsTitle} ${addClass}`;
    const clsTitleC = `${this.clsTitleC} ${ppfx}one-bg`;
    const clsCaret = `${this.clsCaret} fa fa-chevron-right`;
    const clsInput = `${this.inputNameCls} ${clsNoEdit} ${ppfx}no-app`;
    const level = this.level + 1;
    const gut = `${30 + level * 10}px`;
    const name = model.getName();
    const icon = model.getIcon();
    const clsBase = `${pfx}layer`;

    return `
      ${
        hidable
          ? ``
          : ''
      }

            ${icon ? `<span class="${clsBase}__icon">${icon}</span>` : ''}
            ${name}

${count || ''}

`;
  },

  initialize(o = {}) {
    this.opt = o;
    this.level = o.level;
    this.config = o.config;
    this.em = o.config.em;
    this.ppfx = this.em.get('Config').stylePrefix;
    this.sorter = o.sorter || '';
    this.pfx = this.config.stylePrefix;
    this.parentView = o.parentView;
    const pfx = this.pfx;
    const ppfx = this.ppfx;
    const model = this.model;
    const components = model.get('components');
    const type = model.get('type') || 'default';
    model.set('open', false);
    this.listenTo(components, 'remove add reset', this.checkChildren);
    this.listenTo(model, 'change:status', this.updateStatus);
    this.listenTo(model, 'change:open', this.updateOpening);
    this.listenTo(model, 'change:layerable', this.updateLayerable);
    this.listenTo(model, 'change:style:display', this.updateVisibility);
    this.className = `${pfx}layer ${pfx}layer__t-${type} no-select ${ppfx}two-color`;
    this.inputNameCls = `${ppfx}layer-name`;
    this.clsTitleC = `${pfx}layer-title-c`;
    this.clsTitle = `${pfx}layer-title`;
    this.clsCaret = `${pfx}layer-caret`;
    this.clsCount = `${pfx}layer-count`;
    this.clsMove = `${pfx}layer-move`;
    this.clsChildren = `${pfx}layer-children`;
    this.clsNoChild = `${pfx}layer-no-chld`;
    this.clsEdit = `${this.inputNameCls}--edit`;
    this.clsNoEdit = `${this.inputNameCls}--no-edit`;
    this.$el.data('model', model);
    this.$el.data('collection', components);
    model.viewLayer = this;
  },

  getVisibilityEl() {
    if (!this.eyeEl) {
      this.eyeEl = this.$el.children(`.${this.pfx}layer-vis`);
    }

    return this.eyeEl;
  },

  updateVisibility() {
    const pfx = this.pfx;
    const model = this.model;
    const hClass = `${pfx}layer-hidden`;
    const hideIcon = 'fa-eye-slash';
    const hidden = model.getStyle().display === 'none';
    const method = hidden ? 'addClass' : 'removeClass';
    this.$el[method](hClass);
    this.getVisibilityEl()[method](hideIcon);
  },

  /**
   * Toggle visibility
   * @param	Event
   *
   * @return 	void
   * */
  toggleVisibility(e) {
    e && e.stopPropagation();
    const { model } = this;
    const prevDspKey = '__prev-display';
    const prevDisplay = model.get(prevDspKey);
    const style = model.getStyle();
    const { display } = style;
    const hidden = display == 'none';

    if (hidden) {
      delete style.display;

      if (prevDisplay) {
        style.display = prevDisplay;
        model.unset(prevDspKey);
      }
    } else {
      display && model.set(prevDspKey, display);
      style.display = 'none';
    }

    model.setStyle(style);
  },

  /**
   * Handle the edit of the component name
   */
  handleEdit(e) {
    e && e.stopPropagation();
    const { em, $el, clsNoEdit, clsEdit } = this;
    const inputEl = this.getInputName();
    inputEl[inputProp] = true;
    inputEl.focus();
    em && em.setEditing(1);
    $el
      .find(`.${this.inputNameCls}`)
      .removeClass(clsNoEdit)
      .addClass(clsEdit);
  },

  /**
   * Handle with the end of editing of the component name
   */
  handleEditEnd(e) {
    e && e.stopPropagation();
    const { em, $el, clsNoEdit, clsEdit } = this;
    const inputEl = this.getInputName();
    const name = inputEl.textContent;
    inputEl.scrollLeft = 0;
    inputEl[inputProp] = false;
    this.model.set({ 'custom-name': name });
    em && em.setEditing(0);
    $el
      .find(`.${this.inputNameCls}`)
      .addClass(clsNoEdit)
      .removeClass(clsEdit);
  },

  /**
   * Get the input containing the name of the component
   * @return {HTMLElement}
   */
  getInputName() {
    if (!this.inputName) {
      this.inputName = this.el.querySelector(`.${this.inputNameCls}`);
    }
    return this.inputName;
  },

  /**
   * Update item opening
   *
   * @return void
   * */
  updateOpening() {
    var opened = this.opt.opened || {};
    var model = this.model;
    const chvDown = 'fa-chevron-down';

    if (model.get('open')) {
      this.$el.addClass('open');
      this.getCaret().addClass(chvDown);
      opened[model.cid] = model;
    } else {
      this.$el.removeClass('open');
      this.getCaret().removeClass(chvDown);
      delete opened[model.cid];
    }
  },

  /**
   * Toggle item opening
   * @param {Object}	e
   *
   * @return void
   * */
  toggleOpening(e) {
    e.stopPropagation();

    if (!this.model.get('components').length) return;

    this.model.set('open', !this.model.get('open'));
  },

  /**
   * Handle component selection
   */
  handleSelect(e) {
    e.stopPropagation();
    const { em, config } = this;

    if (em) {
      const model = this.model;
      em.setSelected(model, { fromLayers: 1 });
      const scroll = config.scrollCanvas;
      scroll && model.views.forEach(view => view.scrollIntoView(scroll));
    }
  },

  /**
   * Handle component selection
   */
  handleHover(e) {
    e.stopPropagation();
    const { em, config, model } = this;
    em && config.showHover && em.setHovered(model, { fromLayers: 1 });
  },

  /**
   * Delegate to sorter
   * @param	Event
   * */
  startSort(e) {
    e.stopPropagation();
    const { em, sorter } = this;
    // Right or middel click
    if (e.button && e.button !== 0) return;

    if (sorter) {
      sorter.onStart = data => em.trigger(`${eventDrag}:start`, data);
      sorter.onMoveClb = data => em.trigger(eventDrag, data);
      sorter.startSort(e.target);
    }
  },

  /**
   * Freeze item
   * @return	void
   * */
  freeze() {
    this.$el.addClass(this.pfx + 'opac50');
    this.model.set('open', 0);
  },

  /**
   * Unfreeze item
   * @return	void
   * */
  unfreeze() {
    this.$el.removeClass(this.pfx + 'opac50');
  },

  /**
   * Update item on status change
   * @param	Event
   * */
  updateStatus(e) {
    ComponentView.prototype.updateStatus.apply(this, [
      {
        avoidHover: !this.config.highlightHover
      }
    ]);
  },

  /**
   * Check if component is visible
   *
   * @return boolean
   * */
  isVisible() {
    const { display } = this.model.getStyle();

    return !(display && display === 'none');
  },

  /**
   * Update item aspect after children changes
   *
   * @return void
   * */
  checkChildren() {
    const { model, clsNoChild } = this;
    const count = this.countChildren(model);
    const title = this.$el
      .children(`.${this.clsTitleC}`)
      .children(`.${this.clsTitle}`);
    let { cnt } = this;

    if (!cnt) {
      cnt = this.$el.children('[data-count]').get(0);
      this.cnt = cnt;
    }

    title[count ? 'removeClass' : 'addClass'](clsNoChild);
    if (cnt) cnt.innerHTML = count || '';
    !count && model.set('open', 0);
  },

  /**
   * Count children inside model
   * @param  {Object} model
   * @return {number}
   * @private
   */
  countChildren(model) {
    var count = 0;
    model.get('components').each(function(m) {
      var isCountable = this.opt.isCountable;
      var hide = this.config.hideTextnode;
      if (isCountable && !isCountable(m, hide)) return;
      count++;
    }, this);
    return count;
  },

  getCaret() {
    if (!this.caret || !this.caret.length) {
      const pfx = this.pfx;
      this.caret = this.$el
        .children(`.${this.clsTitleC}`)
        .find(`.${this.clsCaret}`);
    }

    return this.caret;
  },

  setRoot(el) {
    el = isString(el) ? this.em.getWrapper().find(el)[0] : el;
    const model = getModel(el, $);
    if (!model) return;
    this.stopListening();
    this.model = model;
    this.initialize(this.opt);
    this.render();
  },

  updateLayerable() {
    const { parentView } = this;
    const toRerender = parentView || this;
    toRerender.render();
  },

  render() {
    const { model, config, pfx, ppfx, opt } = this;
    const { isCountable } = opt;
    const hidden = isCountable && !isCountable(model, config.hideTextnode);
    const vis = this.isVisible();
    const el = this.$el.empty();
    const level = this.level + 1;

    if (isUndefined(ItemsView)) {
      ItemsView = require('./ItemsView').default;
    }

    const children = new ItemsView({
      collection: model.get('components'),
      config: this.config,
      sorter: this.sorter,
      opened: this.opt.opened,
      parentView: this,
      parent: model,
      level
    }).render().$el;

    if (!this.config.showWrapper && level === 1) {
      el.append(children);
    } else {
      el.html(this.template(model));
      el.find(`.${this.clsChildren}`).append(children);
    }

    if (!model.get('draggable') || !this.config.sortable) {
      el.children(`.${this.clsMove}`).remove();
    }

    !vis && (this.className += ` ${pfx}hide`);
    hidden && (this.className += ` ${ppfx}hidden`);
    el.attr('class', this.className);
    this.updateOpening();
    this.updateStatus();
    this.updateVisibility();
    return this;
  }
});


text:
package com.xmldatamodifier.core;

import com.google.common.base.Strings;

import static java.util.Objects.requireNonNull;

public class ContentReplaceRule extends ContentRule {

    private final String regex;
    private final String replacement;

    public ContentReplaceRule(String regex, String replacement) {
        requireNonNull(regex, "Regex string cannot be null");
        requireNonNull(replacement, "Replacement string cannot be null");
        this.regex = regex;
        this.replacement = replacement;
    }

    private static final String STAR_REGEX = "*";

    @Override
    public String elaborate(String content) {
        if (STAR_REGEX.equals(regex)) {
            return replacement;
        }

        return Strings.nullToEmpty(content).replaceAll(regex, replacement);
    }

    @Override
    public String toString() {
        return "ContentReplaceRule{" + "regex='" + regex + '\'' + ", replacement='" + replacement + '\'' + '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ContentReplaceRule that = (ContentReplaceRule) o;

        if (regex != null ? !regex.equals(that.regex) : that.regex != null) return false;
        return !(replacement != null ? !replacement.equals(that.replacement) : that.replacement != null);

    }

    @Override
    public int hashCode() {
        int result = regex != null ? regex.hashCode() : 0;
        result = 31 * result + (replacement != null ? replacement.hashCode() : 0);
        return result;
    }
}


text:
package net.imagej.ops.threshold.shanbhag;

import net.imagej.ops.Ops;
import net.imagej.ops.threshold.AbstractComputeThresholdHistogram;
import net.imglib2.histogram.Histogram1d;
import net.imglib2.type.numeric.RealType;

import org.scijava.plugin.Plugin;

// NB - this plugin adapted from Gabriel Landini's code of his AutoThreshold
// plugin found in Fiji (version 1.14).

/**
 * Implements Shanbhag's threshold method.
 *
 * @author Barry DeZonia
 * @author Gabriel Landini
 */
@Plugin(type = Ops.Threshold.Shanbhag.class, name = Ops.Threshold.Shanbhag.NAME)
public class ComputeShanbhagThreshold<T extends RealType<T>> extends
		AbstractComputeThresholdHistogram<T> {

	@Override
	public long computeBin(final Histogram1d<T> hist) {
		long[] histogram = hist.toLongArray();
		// Shanhbag A.G. (1994) "Utilization of Information Measure as a Means
		// of
		// Image Thresholding" Graphical Models and Image Processing, 56(5):
		// 414-419
		// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8
		// routines
		int threshold;
		int ih, it;
		int first_bin;
		int last_bin;
		double term;
		double tot_ent; /* total entropy */
		double min_ent; /* max entropy */
		double ent_back; /* entropy of the background pixels at a given threshold */
		double ent_obj; /* entropy of the object pixels at a given threshold */
		double[] norm_histo = new double[histogram.length]; /*
															 * normalized
															 * histogram
															 */
		double[] P1 = new double[histogram.length]; /*
													 * cumulative normalized
													 * histogram
													 */
		double[] P2 = new double[histogram.length];

		int total = 0;
		for (ih = 0; ih < histogram.length; ih++)
			total += histogram[ih];

		for (ih = 0; ih < histogram.length; ih++)
			norm_histo[ih] = (double) histogram[ih] / total;

		P1[0] = norm_histo[0];
		P2[0] = 1.0 - P1[0];
		for (ih = 1; ih < histogram.length; ih++) {
			P1[ih] = P1[ih - 1] + norm_histo[ih];
			P2[ih] = 1.0 - P1[ih];
		}

		/* Determine the first non-zero bin */
		first_bin = 0;
		for (ih = 0; ih < histogram.length; ih++) {
			if (!(Math.abs(P1[ih]) < 2.220446049250313E-16)) {
				first_bin = ih;
				break;
			}
		}

		/* Determine the last non-zero bin */
		last_bin = histogram.length - 1;
		for (ih = histogram.length - 1; ih >= first_bin; ih--) {
			if (!(Math.abs(P2[ih]) < 2.220446049250313E-16)) {
				last_bin = ih;
				break;
			}
		}

		// Calculate the total entropy each gray-level
		// and find the threshold that maximizes it
		threshold = -1;
		min_ent = Double.MAX_VALUE;

		for (it = first_bin; it <= last_bin; it++) {
			/* Entropy of the background pixels */
			ent_back = 0.0;
			term = 0.5 / P1[it];
			for (ih = 1; ih <= it; ih++) { // 0+1?
				ent_back -= norm_histo[ih] * Math.log(1.0 - term * P1[ih - 1]);
			}
			ent_back *= term;

			/* Entropy of the object pixels */
			ent_obj = 0.0;
			term = 0.5 / P2[it];
			for (ih = it + 1; ih < histogram.length; ih++) {
				ent_obj -= norm_histo[ih] * Math.log(1.0 - term * P2[ih]);
			}
			ent_obj *= term;

			/* Total entropy */
			tot_ent = Math.abs(ent_back - ent_obj);

			if (tot_ent < min_ent) {
				min_ent = tot_ent;
				threshold = it;
			}
		}
		return threshold;
	}

}


text:
namespace Google.Cloud.Dataform.V1Beta1.Snippets
{
    // [START dataform_v1beta1_generated_Dataform_CreateRepository_sync_flattened]
    using Google.Cloud.Dataform.V1Beta1;

    public sealed partial class GeneratedDataformClientSnippets
    {
        /// <summary>Snippet for CreateRepository</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void CreateRepository()
        {
            // Create client
            DataformClient dataformClient = DataformClient.Create();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/locations/[LOCATION]";
            Repository repository = new Repository();
            string repositoryId = "";
            // Make the request
            Repository response = dataformClient.CreateRepository(parent, repository, repositoryId);
        }
    }
    // [END dataform_v1beta1_generated_Dataform_CreateRepository_sync_flattened]
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: API > Types > InputAxis > descriptor</title>
  <meta name="revised" content="04-Sep-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  API > Types > InputAxis > descriptor" />

  <link rel="stylesheet" href="../../../css/style.css" type="text/css" />

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

object.descriptor

Overview

Example

Ξ  ▸  API  ▸  Types  ▸  InputAxis  ▸  descriptor

object.descriptor

Type
String

Object
InputAxis

Revision
Current Public Release (2013.2076)

Keywords
device, input, axis, descriptor

Overview

Provides a human readable string assigned by Corona used to uniquely identify one axis input belonging to one device. This descriptor string is intended to be used by applications that set up key and axis bindings with a particular device, such as the first joystick connected to the system.

This descriptor string key is generated based on the device's descriptor and the axis number. For example, the first 2 axes belong to one joystick will be named "Joystick 1: Axis 1" and "Joystick 1: Axis 2".

Example

-- Fetch all input devices currently connected to the system.
local inputDevices = system.getInputDevices()

-- Traverse all input devices.
for deviceIndex = 1, #inputDevices do
    -- Fetch the input device's axes.
    local inputAxes = inputDevices[deviceIndex]:getAxes()

    -- Print all axis descriptors to the log.
    for axisIndex = 1, #inputAxes do
        print(inputAxes[axisIndex].descriptor)
    end
end

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 04-Sep-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
ActiveRecord::Schema.define do
  create_table "pirates", :force => true do |t|
    t.column "name",  :text
    t.column "drunk_for_the_first_time_at", :datetime
    t.column "drunk_last_at", :datetime
  end

  create_table "ships", :force => true do |t|
    t.column "name", :text
  end
end


text:
/**
 */
package com.specmate.model.batch;

import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.common.util.EList;

/**
 *
 * A representation of the model object 'Operation'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link com.specmate.model.batch.BatchOperation#getOperations Operations}

 *

 *
 * @see com.specmate.model.batch.BatchPackage#getBatchOperation()
 * @model
 * @extends CDOObject
 * @generated
 */
public interface BatchOperation extends CDOObject {

	/**
	 * Returns the value of the 'Operations' containment reference list.
	 * The list contents are of type {@link com.specmate.model.batch.Operation}.
	 *
	 *

	 * If the meaning of the 'Operations' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Operations' containment reference list.
	 * @see com.specmate.model.batch.BatchPackage#getBatchOperation_Operations()
	 * @model containment="true"
	 * @generated
	 */
	EList<Operation> getOperations();
} // BatchOperation


text:
from setuptools import find_packages, setup

VERSION = "7.0.0"
LONG_DESCRIPTION = """
.. image:: http://pinaxproject.com/pinax-design/patches/pinax-invitations.svg
    :target: https://pypi.python.org/pypi/pinax-invitations/

=================
Pinax Invitations
=================

.. image:: https://img.shields.io/pypi/v/pinax-invitations.svg
    :target: https://pypi.python.org/pypi/pinax-invitations/

\

.. image:: https://img.shields.io/circleci/project/github/pinax/pinax-invitations.svg
    :target: https://circleci.com/gh/pinax/pinax-invitations
.. image:: https://img.shields.io/codecov/c/github/pinax/pinax-invitations.svg
    :target: https://codecov.io/gh/pinax/pinax-invitations
.. image:: https://img.shields.io/github/contributors/pinax/pinax-invitations.svg
    :target: https://github.com/pinax/pinax-invitations/graphs/contributors
.. image:: https://img.shields.io/github/issues-pr/pinax/pinax-invitations.svg
    :target: https://github.com/pinax/pinax-invitations/pulls
.. image:: https://img.shields.io/github/issues-pr-closed/pinax/pinax-invitations.svg
    :target: https://github.com/pinax/pinax-invitations/pulls?q=is%3Apr+is%3Aclosed

\

.. image:: http://slack.pinaxproject.com/badge.svg
    :target: http://slack.pinaxproject.com/
.. image:: https://img.shields.io/badge/license-MIT-blue.svg
    :target: https://opensource.org/licenses/MIT/

\

``pinax-invitations`` is a user to user join invitations app.

Supported Django and Python Versions
------------------------------------

+-----------------+-----+-----+-----+
| Django / Python | 3.6 | 3.7 | 3.8 |
+=================+=====+=====+=====+
|  2.2            |  *  |  *  |  *  |
+-----------------+-----+-----+-----+
|  3.0            |  *  |  *  |  *  |
+-----------------+-----+-----+-----+
"""

setup(
    author="Pinax Team",
    author_email="team@pinaxproject.com",
    description="a user to user join invitations app",
    name="pinax-invitations",
    long_description=LONG_DESCRIPTION,
    version=VERSION,
    url="http://github.com/pinax/pinax-invitations/",
    license="MIT",
    packages=find_packages(),
    package_data={
        "invitations": []
    },
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Environment :: Web Environment",
        "Framework :: Django",
        'Framework :: Django :: 2.2',
        'Framework :: Django :: 3.0',
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
    install_requires=[
        "django>=2.2",
        "django-appconf>=1.0.1",
        "django-user-accounts>=2.0.3",
    ],
    test_suite="runtests.runtests",
    tests_require=[
        "django-test-plus",
        "pinax-templates>=1.0.2",
    ],
    zip_safe=False,
)


text:
{% comment %} _config_map(include.key, include.value, include.deep, include.key_prefix) {% endcomment %}
{% capture _config_map %}
  {% if include.key != '' and include.key != nil and include.deep <= 3 %}
    {% assign value_type = include.value | jsonify | slice: 0 %}
    {% if value_type == '{' %}
      {% for key_value in include.value %}
        {% assign key = key_value[0] %}
        {% assign value = key_value[1] %}
        {% assign deep = include.deep | plus: 1 %}
        {% capture key_prefix  %}{{ include.key_prefix }}{{ include.key }}.{% endcapture %}
        {% include _helper/_config_map.html key=key value=value deep=deep key_prefix=key_prefix %}
        {{ _config_map }}
      {% endfor %}
    {% elsif value_type != '[' %}
      {% assign value = include.value | jsonify %}
      {% if value != '{}' and value != '[]' %}
        '{{ include.key_prefix }}{{ include.key }}': {{ value }},
      {% endif %}
    {% endif %}
  {% endif %}
{% endcapture %}

{% assign _config_map = _config_map | normalize_whitespace %}


text:
package org.jclouds.openstack.nova.v2_0.compute.loaders;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertFalse;

import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
import org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;
import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;
import org.testng.annotations.Test;

import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;

@Test(groups = "unit", singleThreaded = true, testName = "LoadFloatingIpsForInstanceTest")
public class LoadFloatingIpsForInstanceTest {

   @Test
   public void testReturnsPublicIpOnMatch() throws Exception {
      NovaApi api = createMock(NovaApi.class);
      FloatingIPApi ipApi = createMock(FloatingIPApi.class);
      FloatingIP testIp = FloatingIP.builder().id("1").ip("1.1.1.1").fixedIp("10.1.1.1").instanceId("i-blah").build();

      expect(api.getFloatingIPApi("RegionOne")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();
      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(testIp)))
               .atLeastOnce();

      replay(api);
      replay(ipApi);

      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);

      assertEquals(ImmutableSet.copyOf(parser.load(RegionAndId.fromRegionAndId("RegionOne", "i-blah"))), ImmutableSet.of(testIp));

      verify(api);
      verify(ipApi);
   }

   @Test
   public void testReturnsNullWhenNotFound() throws Exception {
      NovaApi api = createMock(NovaApi.class);
      FloatingIPApi ipApi = createMock(FloatingIPApi.class);

      expect(api.getFloatingIPApi("region")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();

      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of()))
      .atLeastOnce();

      replay(api);
      replay(ipApi);

      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);

      assertFalse(parser.load(RegionAndId.fromRegionAndId("region", "i-blah")).iterator().hasNext());

      verify(api);
      verify(ipApi);

   }

   @Test
   public void testReturnsNullWhenNotAssigned() throws Exception {
      NovaApi api = createMock(NovaApi.class);
      FloatingIPApi ipApi = createMock(FloatingIPApi.class);

      expect(api.getFloatingIPApi("region")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();

      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(FloatingIP.builder().id("1").ip("1.1.1.1").build())))
      .atLeastOnce();

      replay(api);
      replay(ipApi);

      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);

      assertFalse(parser.load(RegionAndId.fromRegionAndId("region", "i-blah")).iterator().hasNext());

      verify(api);
      verify(ipApi);

   }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Fuzzycomplete.js example usage</title>
  <link rel="stylesheet" href="../dist/css/fuzzycomplete.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700">

Basic Usage

      Fuzzycomplete can be called with no options, simply with the data to be searched via jQuery.

      In this case it will search all fields supplied within the JSON data, displaying and outputting the first key.

Demo

      Companies: <input type="text" id="companyPicker" name="company">
      Output:

Code

var companies = [
        {"companyName":"Aperture Science"},
        {"companyName":"MomCorp"},
        {"companyName":"Wayne Enterprises"},
        {"companyName":"Umbrella Corp"},
        {"companyName":"Gringotts"},
        {"companyName":"Globex"}
      ];

$(document).ready(function(){
  $("#companyPicker").fuzzyComplete(companies);
});

Advanced usage

Searching multiple sets of data

      You might have a set of data which has two (or more) ways of referring to a particular item.

      An example might be airports:

City Name

Airport Code

      To help users, you can allow them to search by either type.

Demo

      Airports: <input type="text" id="airportPicker" name="airport">
      Output:

Code

var airports = [
                {"airportCode":"MEL","cityName":"Melbourne, Australia"},
                {"airportCode":"LAX","cityName":"Los Angeles, USA"},
                {"airportCode":"LHR","cityName":"Heathrow, London"},
                {"airportCode":"HKG","cityName":"Hong Kong"},
                {"airportCode":"NRT","cityName":"Narita, Tokyo, Japan"},
                {"airportCode":"FRA","cityName":"Frankfurt, Germany"}
              ];
var fuseOptions = { keys: ["airportCode", "cityName"] };
var options = { display: "cityName", key: "airportCode", fuseOptions: fuseOptions };

$(document).ready(function(){
  $("#airportPicker").fuzzyComplete(airports, options);
});

Non-searchable output

      You might use an internal value to track items (a database key, for example), but you don't wish for this value to be searchable. Only fields in the "keys" section of fuseOptions will be searched, so simply omit fields you don't wish to be searched.

Demo

      Shop: <input type="text" id="itemPicker" name="item">
      Output:

Code

var items = [
              {"itemCode":"item3442","itemName":"Bag of doorknobs"},
              {"itemCode":"item3446","itemName":"Blinker fluid"},
              {"itemCode":"item3479","itemName":"Widgets"},
              {"itemCode":"item3495","itemName":"Firefly class transport ship"},
              {"itemCode":"item3400","itemName":"Perpetual motion machine"},
              {"itemCode":"item3454","itemName":"Penrose triangle"}
            ];
var fuseOptions = { keys: ["itemName"] };
var options = { display: "itemName", key: "itemCode", fuseOptions: fuseOptions };

$(document).ready(function(){
  $("#itemPicker").fuzzyComplete(items, options);
});

Custom ResultsBox & Input Box Selection

      You might want to format results in a special format or combine fields from the search results. You can pass a function as the display option to define custom html in the resultbox. You can use displayValue to select what value to display in the input text box.

Demo

      Shop: <input type="text" id="customResultsBoxPicker" name="item">
      Output:

Code

var items = [
              {"itemCode":"item3442","itemName":"Bag of doorknobs"},
              {"itemCode":"item3446","itemName":"Blinker fluid"},
              {"itemCode":"item3479","itemName":"Widgets"},
              {"itemCode":"item3495","itemName":"Firefly class transport ship"},
              {"itemCode":"item3400","itemName":"Perpetual motion machine"},
              {"itemCode":"item3454","itemName":"Penrose triangle"}
            ];
var fuseOptions = { keys: ["itemName"] };
var displayFunction = function(result,id) {
  return id + ". <b>" + result['itemName'] "</b> - " + result['itemCode'];
};
var options = {
  display: displayFunction,
  displayValue: "itemName",
  key: "itemCode",
  fuseOptions: fuseOptions
};

$(document).ready(function(){
  $("#customResultsBoxPicker").fuzzyComplete(items, options);
});


text:
typedef accum value_t;
typedef value_t current_t;
typedef value_t voltage_t;

#endif


text:
/* Interface for classes using ConnectionIn, ConnectionOut, and ConnectionTracker
 */
public interface Receiver {
    public void receive(int flag, Object input);
}