text:
<?php

namespace CascadeFramework\Diagnostics;

/**
 * Description of KDiagnostics
 *
 * @author Shirasho
 */
final class KDiagnostics {

    const WARNING_SESSION_HTTP_ONLY = 1;

    const EXCEPTION_CONFIG_SAVE = 1 << 5;

    private static $Warnings = self::WARNING_SESSION_HTTP_ONLY;

    private static $ErrorHandler = null;
    private static $Loggers = [];

    private function __construct() {}

    /**
     *
     * @param type $Handlers
     */
    public static function Init(\Whoops\Handler\Handler ...$Handlers) {
        if (self::$ErrorHandler === null) {
            self::$ErrorHandler = new \Whoops\Run;
            foreach ($Handlers as $Handler) {
                self::$ErrorHandler->pushHandler($Handler);
            }
            self::$ErrorHandler->register();
        }
    }

    /**
     * Adds a logger to the logger list. All calls to Log will be sent to every
     * registered logger.
     *
     * @param \CascadeFramework\Diagnostics\ALogger ...$Loggers The loggers to register.
     */
    public static function RegisterLogger(ALogger ...$Loggers) {
        foreach ($Loggers as $Logger) {
            array_push(self::$Loggers, $Logger);
        }
    }

    /**
     * Removes a logger from the logger list.
     *
     * @param \CascadeFramework\Diagnostics\ALogger ...$Loggers The loggers to unregister.
     */
    public static function UnregisterLogger(ALogger ...$Loggers) {
        foreach ($Loggers as $Logger) {
            $Index = array_search($Logger, self::$Loggers);
            if ($Index !== false) {
                unset(self::$Loggers[$Index]);
            }
        }
    }

    /**
     * Log a message to all registered loggers.
     *
     * @param mixed $Message The message to write to the log. The message must be a string,
     * null, a scalar, or an object that implements '__toString()'.
     * @param int $Verbosity The verbosity of this message, defined by the EVerbosity enumeration.
     * @param bool $bAppend [optional] True to append the content, false to clear existing content.
     */
    public static function Log($Message, int $Verbosity = EVerbosity::Log, bool $bAppend = true) {
        foreach (self::$Loggers as $Log) {
            // Unneccesary check, but better safe than sorry.
            if ($Log !== null) {
                $Log->Log($Message, $Verbosity, $bAppend);
            }
        }
    }
    /**
     * Log a warning message to all registered loggers.
     *
     * @param mixed $Message The message to write to the log. The message must be a string,
     * null, a scalar, or an object that implements '__toString()'.
     * @param bool $bAppend [optional] True to append the content, false to clear existing content.
     */
    public static function LogWarning($Message, bool $bAppend = true) {
        foreach (self::$Loggers as $Log) {
            // Unneccesary check, but better safe than sorry.
            if ($Log !== null) {
                $Log->LogWarning($Message, $bAppend);
            }
        }
    }
    /**
     * Log an error message to all registered loggers.
     *
     * @param mixed $Message The message to write to the log. The message must be a string,
     * null, a scalar, or an object that implements '__toString()'.
     * @param bool $bAppend [optional] True to append the content, false to clear existing content.
     */
    public static function LogError($Message, bool $bAppend = true) {
        foreach (self::$Loggers as $Log) {
            // Unneccesary check, but better safe than sorry.
            if ($Log !== null) {
                $Log->LogError($Message, $bAppend);
            }
        }
    }
    /**
     * Log a fatal message to all registered loggers.
     *
     * @param mixed $Message The message to write to the log. The message must be a string,
     * null, a scalar, or an object that implements '__toString()'.
     * @param bool $bAppend [optional] True to append the content, false to clear existing content.
     */
    public static function LogFatal($Message, bool $bAppend = true) {
        foreach (self::$Loggers as $Log) {
            // Unneccesary check, but better safe than sorry.
            if ($Log !== null) {
                $Log->LogFatal($Message, $bAppend);
            }
        }
    }

    /**
     * Logs the current exception stack to all registered logs. This method is
     * called within the framework and should not be called manually.
     */
    public function LogException(\Whoops\Exception\FrameCollection $Frames, string $ExceptionMessage = '') {
        //$Frames->getArray()[0]->getFile();

        $this->LogError('An error has occurred.');
        $this->LogError('Message: ' . $ExceptionMessage);
        $this->LogError('Stack: ' . $ExceptionMessage);

        $FrameSet = $Frames->getArray();
        $StackValue = 0;
        foreach ($FrameSet as $Frame) {
            $this->LogError('    [' . $StackValue++ . '] ' . $Frame->getFile() . ':' . $Frame->getLine());
            $this->LogError('          at ' . $Frame->getClass() . '::' . $Frame->getFunction() . '()');
        }
    }

    /**
     * Enables the warnings in the provided flag mask.
     *
     * @param int $FlagMask An int mask containing the flags to enable.
     */
    public static function EnableWarnings(int $FlagMask) {
        self::$Warnings |= $FlagMask;
    }

    /**
     * Disables the warnings in the provided flag mask.
     *
     * @param int $FlagMask An int mask containing the flags to disable.
     */
    public static function DisableWarnings(int $FlagMask) {
        self::$Warnings &= ~$FlagMask;
    }

    /**
     * Returns whether the specified warning is enabled.
     *
     * @param int $Warning The warning flag.
     * @return bool True if the warning is enabled, false otherwise.
     */
    public static function IsWarningEnabled(int $Warning) : bool {
        return (self::$Warnings & $Warning) > 0;
    }

    /**
     * Dumps the value of an expression in a human-readable form.
     *
     * @param mixed $Expression The expression.
     * @param bool $bReturn [optional] True to return the value, false to print it.
     */
    public static function Print_r($Expression, bool $bReturn = false) {
        if ($bReturn) {
            return print_r($Expression, true);
        }
        echo '<pre>' , \CascadeFramework\Core\KString::create(print_r($Expression, true)) , '</pre>';
    }
}


text:
var Asteroids = require('./src/Asteroids');

Asteroids.start();

redpajama_set_name: RedPajamaGithub


text:
module CSVPort

  QueueData = Struct.new(:id, :processor)

  class QueueBlockParser

    def initialize(block)
      @block = block
    end

    def parse
      remove_queue
      remove_whitespace
      extract_id
      extract_processor
      export
    end

    def remove_queue
      @block.slice!(/^queue/)
    end

    def remove_whitespace
      @block.strip!
    end

    def extract_id
      @id = @block.slice!(/^\S+/).to_sym
    end

    def export
      QueueData.new(@id, @processor)
    end

    def extract_processor
      processor_pattern = /([A-Z]\S+)\s*(\{.+?\})?/
      proc_class, opts = nil, nil
      @block.scan(processor_pattern) do |match_data|
        proc_class, opts = match_data[0..1] if match_data
      end
      proc_class = "Queue" if not proc_class
      @processor = ProcessorData.new(proc_class, opts)
    end

  end
end


text:
<!doctype html>

      <meta charset="utf-8">
      <title>Le scarabée-robot</title>
    <link class="module" rel="stylesheet" href="../../../_common/modules/pemFioi/taskStyles-0.1.css" id="http://www.france-ioi.org/modules/pemFioi/taskStyles-0.1.css">

    <link class="stdAnswerTypes module" rel="stylesheet" type="text/css" href="../../../_common/modules/integrationAPI.01/installationAPI.01/pemFioi/answerTypes.css" id="http://www.france-ioi.org/modules/integrationAPI.01/installationAPI.01/pemFioi/stdAnsTypes.css" />

Le scarabée-robot

Un scarabée-robot peut se déplacer sur ce damier de la façon suivante :

	A	B	C	D	E

1

2

3

4

Le scarabée-robot commence sur une case quelconque dans l'une des colonnes A à D.
Le scarabée-robot compte alors le nombre de flèches qui se trouvent dans cette case.
Ensuite il se déplace dans le sens des flèches indiqué d'autant de cases qu'il y avait de flèches, et s'immobilise.

Si, par exemple, il se trouve sur B4, il va se déplacer de trois
cases vers le haut et se trouver ensuite sur B1.

Le scarabée-robot continue, jusqu'à ce qu'il sorte du damier
ou qu'il se trouve sur une case de la colonne E.

À partir de quelles cases de la colonne A le scarabée peut-il démarrer pour se retrouver sur une
case de la colonne E ?

La solution

   La réponse B est correcte.

Commencer en A2 mène à : A4, B4, B1, D1, D3, C3, C4 puis E4. A4 est sur ce chemin, donc A4 mène aussi à E4.

Commencer en A1 mène à : C1, C2 puis fait sortir de la grille, en bas de la colonne C.

Commencer en A3 mène à : B3, B2, C2 puis en dehors de la grille, en bas de la colonne C.

C'est de l'informatique

L'informatique pose de nombreuses questions sur les différentes propriétés des programmes. Le plateau décrit ici
est un exemple de programme. Le robot commence dans une situation initiale (colonne A) et suit les commandes
du programme jusqu'à-ce qu'une situation finale ait été atteinte. Certains états finaux sont désirables (Colonne E)
et d'autres indésirables (sortie du plateau). Existe-t-il une situation telle que le robot n'atteint jamais de situation
finale ? Probablement pas dans ce programme. Est-ce que cela peut arriver avec un autre programme ? Dans
d'autres langages de programmation ? Sous quelles contraintes ? Cette propriété d'un programme, avec d'autres, a
beaucoup d'importance en pratique, et est un thème essentiel de l'informatique.


text:
import tornado.web
from .base import Base
__author__ = 'zheng'

class MainHandler(Base):

    @tornado.web.authenticated
    def get(self):
        self.render('application.html')


text:
PullToDismissPager
==================
PullToDismissPager is an Adroid Open Source Libray for showing ViewPager in similar way Facebook app does in its Friend Request Section. This library is based on awesome [AndroidSlidingUpPanel](https://github.com/umano/AndroidSlidingUpPanel) library by [Umano](https://github.com/umano).

![Screenshot](/screenshot.jpg)

Download the source to use it as a library project or use it directly from Maven Central in your dependencies.  For example:

	dependencies {
		compile 'com.github.baneizalfe.pulltodismisspager:library:1.0.1'
	}

### Usage
* Include `com.mrbug.pulltodismisspager.PullToDismissPager` as the root element in your activity layout.
* No need for gravity attribite anymore. Default is BOTTOM
* Make sure that it has only one child, your main layout.
* The main layout should have the width and the height set to `match_parent`.
For more information, checkout sample code.
```xml
<com.mrbug.pulltodismisspager.PullToDismissPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pull_to_dismiss_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    </FrameLayout>
</com.mrbug.pulltodismisspager.PullToDismissPager>
```
* In your activity set your custom `PagerAdapter` to `PullToDismissPager`
```
pull_to_dismiss_pager = (PullToDismissPager) findViewById(R.id.pull_to_dismiss_pager);
pagerAdapter = new SlidingPagerAdapter(this);
pull_to_dismiss_pager.setPagerAdapter(pagerAdapter);
```
###ToDo
Add some easing to animations
### Licence

> Licensed under the Apache License, Version 2.0 (the "License");
> you may not use this work except in compliance with the License.
> You may obtain a copy of the License in the LICENSE file, or at:
>
>  [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
>
> Unless required by applicable law or agreed to in writing, software
> distributed under the License is distributed on an "AS IS" BASIS,
> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> See the License for the specific language governing permissions and
> limitations under the License.


text:
{$first_login}
<form class="" action="login.php" method="POST">

		username
		<input class="w220" type="text" name="username" />

		password
		<input class="w220" type="password" name="password" />

		<input class=" mb20" type="submit" value="login" />

</form>


text:
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union

import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1
from google.api_core import retry as retries
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.longrunning import operations_pb2  # type: ignore
from google.oauth2 import service_account  # type: ignore
from google.protobuf import empty_pb2  # type: ignore
import pkg_resources

from google.cloud.assuredworkloads_v1.types import assuredworkloads

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-cloud-assured-workloads",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

class AssuredWorkloadsServiceTransport(abc.ABC):
    """Abstract transport class for AssuredWorkloadsService."""

    AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)

    DEFAULT_HOST: str = "assuredworkloads.googleapis.com"

    def __init__(
        self,
        *,
        host: str = DEFAULT_HOST,
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
        **kwargs,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A list of scopes.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
        """

        scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}

        # Save the scopes.
        self._scopes = scopes

        # If no credentials are provided, then determine the appropriate
        # defaults.
        if credentials and credentials_file:
            raise core_exceptions.DuplicateCredentialArgs(
                "'credentials_file' and 'credentials' are mutually exclusive"
            )

        if credentials_file is not None:
            credentials, _ = google.auth.load_credentials_from_file(
                credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
            )
        elif credentials is None:
            credentials, _ = google.auth.default(
                **scopes_kwargs, quota_project_id=quota_project_id
            )
            # Don't apply audience if the credentials file passed from user.
            if hasattr(credentials, "with_gdch_audience"):
                credentials = credentials.with_gdch_audience(
                    api_audience if api_audience else host
                )

        # If the credentials are service account credentials, then always try to use self signed JWT.
        if (
            always_use_jwt_access
            and isinstance(credentials, service_account.Credentials)
            and hasattr(service_account.Credentials, "with_always_use_jwt_access")
        ):
            credentials = credentials.with_always_use_jwt_access(True)

        # Save the credentials.
        self._credentials = credentials

        # Save the hostname. Default to port 443 (HTTPS) if none is specified.
        if ":" not in host:
            host += ":443"
        self._host = host

    def _prep_wrapped_messages(self, client_info):
        # Precompute the wrapped methods.
        self._wrapped_methods = {
            self.create_workload: gapic_v1.method.wrap_method(
                self.create_workload,
                default_timeout=None,
                client_info=client_info,
            ),
            self.update_workload: gapic_v1.method.wrap_method(
                self.update_workload,
                default_timeout=None,
                client_info=client_info,
            ),
            self.restrict_allowed_resources: gapic_v1.method.wrap_method(
                self.restrict_allowed_resources,
                default_timeout=None,
                client_info=client_info,
            ),
            self.delete_workload: gapic_v1.method.wrap_method(
                self.delete_workload,
                default_timeout=None,
                client_info=client_info,
            ),
            self.get_workload: gapic_v1.method.wrap_method(
                self.get_workload,
                default_timeout=None,
                client_info=client_info,
            ),
            self.list_workloads: gapic_v1.method.wrap_method(
                self.list_workloads,
                default_timeout=None,
                client_info=client_info,
            ),
            self.list_violations: gapic_v1.method.wrap_method(
                self.list_violations,
                default_timeout=None,
                client_info=client_info,
            ),
            self.get_violation: gapic_v1.method.wrap_method(
                self.get_violation,
                default_timeout=None,
                client_info=client_info,
            ),
            self.acknowledge_violation: gapic_v1.method.wrap_method(
                self.acknowledge_violation,
                default_timeout=None,
                client_info=client_info,
            ),
        }

    def close(self):
        """Closes resources associated with the transport.

        .. warning::
             Only call this method if the transport is NOT shared
             with other clients - this may cause errors in other clients!
        """
        raise NotImplementedError()

    @property
    def operations_client(self):
        """Return the client designed to process long-running operations."""
        raise NotImplementedError()

    @property
    def create_workload(
        self,
    ) -> Callable[
        [assuredworkloads.CreateWorkloadRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def update_workload(
        self,
    ) -> Callable[
        [assuredworkloads.UpdateWorkloadRequest],
        Union[assuredworkloads.Workload, Awaitable[assuredworkloads.Workload]],
    ]:
        raise NotImplementedError()

    @property
    def restrict_allowed_resources(
        self,
    ) -> Callable[
        [assuredworkloads.RestrictAllowedResourcesRequest],
        Union[
            assuredworkloads.RestrictAllowedResourcesResponse,
            Awaitable[assuredworkloads.RestrictAllowedResourcesResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def delete_workload(
        self,
    ) -> Callable[
        [assuredworkloads.DeleteWorkloadRequest],
        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
    ]:
        raise NotImplementedError()

    @property
    def get_workload(
        self,
    ) -> Callable[
        [assuredworkloads.GetWorkloadRequest],
        Union[assuredworkloads.Workload, Awaitable[assuredworkloads.Workload]],
    ]:
        raise NotImplementedError()

    @property
    def list_workloads(
        self,
    ) -> Callable[
        [assuredworkloads.ListWorkloadsRequest],
        Union[
            assuredworkloads.ListWorkloadsResponse,
            Awaitable[assuredworkloads.ListWorkloadsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def list_violations(
        self,
    ) -> Callable[
        [assuredworkloads.ListViolationsRequest],
        Union[
            assuredworkloads.ListViolationsResponse,
            Awaitable[assuredworkloads.ListViolationsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_violation(
        self,
    ) -> Callable[
        [assuredworkloads.GetViolationRequest],
        Union[assuredworkloads.Violation, Awaitable[assuredworkloads.Violation]],
    ]:
        raise NotImplementedError()

    @property
    def acknowledge_violation(
        self,
    ) -> Callable[
        [assuredworkloads.AcknowledgeViolationRequest],
        Union[
            assuredworkloads.AcknowledgeViolationResponse,
            Awaitable[assuredworkloads.AcknowledgeViolationResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def list_operations(
        self,
    ) -> Callable[
        [operations_pb2.ListOperationsRequest],
        Union[
            operations_pb2.ListOperationsResponse,
            Awaitable[operations_pb2.ListOperationsResponse],
        ],
    ]:
        raise NotImplementedError()

    @property
    def get_operation(
        self,
    ) -> Callable[
        [operations_pb2.GetOperationRequest],
        Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
    ]:
        raise NotImplementedError()

    @property
    def kind(self) -> str:
        raise NotImplementedError()

__all__ = ("AssuredWorkloadsServiceTransport",)


text:
using NUnit.Framework;

namespace Ghpr.NUnitTests
{
    [TestFixture, Ignore("Ignored test fixture")]
    public class TestClass3
    {
        [Test]
        [Category("Cat3")]
        public void TestMethod1()
        {
            Assert.AreEqual(1, 2);
        }

        [Test, Category("SuccessCategory")]
        [Category("Cat3")]
        public void TestMethod2()
        {
            Assert.AreEqual(1, 1);
        }
    }
}


text:
hblacklist
==========

Watch snort fast log and blacklist source ip adresses whose gid is 115.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CircularMotion.cs" company="Slash Games">
//   Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Slash.Math.Utils
{
    public enum CircularMotion
    {
        Invalid,

        Clockwise,

        CounterClockwise,
    }
}


text:
package com.emerchantpay.gateway.api.requests.financial.apm;

import java.math.BigDecimal;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.emerchantpay.gateway.api.Request;
import com.emerchantpay.gateway.api.RequestBuilder;
import com.emerchantpay.gateway.api.constants.TransactionTypes;
import com.emerchantpay.gateway.util.Configuration;
import com.emerchantpay.gateway.util.Currency;
import com.emerchantpay.gateway.util.Http;
import com.emerchantpay.gateway.util.NodeWrapper;

public class InPayRequest extends Request {

	protected Configuration configuration;
	private Http http;

	private NodeWrapper response;

	private String transactionId;
	private String transactionType = TransactionTypes.INPAY;
	private String usage;
	private String remoteIp;
	private URL successUrl;
	private URL failureUrl;
	private BigDecimal amount;
	private BigDecimal convertedAmount;
	private String currency;
	private Boolean isPayout;
	private Integer customerBankId;
	private String orderDescription;
	private String orderId;
	private String bankCountry;
	private String bankName;
	private String swift;
	private String accNumber;
	private String bankAddress;
	private String ownerName;
	private String ownerAddress;
	private String customerEmail;
	private String customerPhone;

	private InPayAddressRequest billingAddress;
	private InPayAddressRequest shippingAddress;

	public InPayRequest() {
		super();
	}

	public InPayRequest(Configuration configuration) {

		super();
		this.configuration = configuration;
	}

	public InPayRequest setTransactionId(String transactionId) {
		this.transactionId = transactionId;
		return this;
	}

	public InPayRequest setUsage(String usage) {
		this.usage = usage;
		return this;
	}

	public InPayRequest setRemoteIp(String remoteIp) {
		this.remoteIp = remoteIp;
		return this;
	}

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

	public InPayRequest setCurrency(String currency) {
		this.currency = currency;
		return this;
	}

	public InPayRequest setIsPayout(Boolean isPayout) {
		this.isPayout = isPayout;
		return this;
	}

	public InPayRequest setCustomerBankId(Integer customerBankId) {
		this.customerBankId = customerBankId;
		return this;
	}

	public InPayRequest setOrderDescription(String orderDescription) {
		this.orderDescription = orderDescription;
		return this;
	}

	public InPayRequest setOrderId(String orderId) {
		this.orderId = orderId;
		return this;
	}

	public InPayRequest setBankCountry(String bankCountry) {
		this.bankCountry = bankCountry;
		return this;
	}

	public InPayRequest setBankName(String bankName) {
		this.bankName = bankName;
		return this;
	}

	public InPayRequest setSwift(String swift) {
		this.swift = swift;
		return this;
	}

	public InPayRequest setAccNumber(String accNumber) {
		this.accNumber = accNumber;
		return this;
	}

	public InPayRequest setBankAddress(String bankAddress) {
		this.bankAddress = bankAddress;
		return this;
	}

	public InPayRequest setOwnerName(String ownerName) {
		this.ownerName = ownerName;
		return this;
	}

	public InPayRequest setOwnerAddress(String ownerAddress) {
		this.ownerAddress = ownerAddress;
		return this;
	}

	public InPayRequest setCustomerEmail(String customerEmail) {
		this.customerEmail = customerEmail;
		return this;
	}

	public InPayRequest setCustomerPhone(String customerPhone) {
		this.customerPhone = customerPhone;
		return this;
	}

	public InPayRequest setReturnSuccessUrl(URL successUrl) {
		this.successUrl = successUrl;
		return this;
	}

	public InPayRequest setReturnFailureUrl(URL failureUrl) {
		this.failureUrl = failureUrl;
		return this;
	}

	public InPayAddressRequest billingAddress() {
		billingAddress = new InPayAddressRequest(this, "billing_address");
		return billingAddress;
	}

	public InPayAddressRequest shippingAddress() {
		shippingAddress = new InPayAddressRequest(this, "shipping_address");
		return shippingAddress;
	}

	@Override
	public String toXML() {
		return buildRequest("payment_transaction").toXML();
	}

	@Override
	public String toQueryString(String root) {
		return buildRequest(root).toQueryString();
	}

	protected RequestBuilder buildRequest(String root) {

		if (amount != null && currency != null) {

			Currency curr = new Currency();

			curr.setAmountToExponent(amount, currency);
			convertedAmount = curr.getAmount();
		}

		return new RequestBuilder(root).addElement("transaction_type", transactionType)
				.addElement("transaction_id", transactionId).addElement("usage", usage)
				.addElement("remote_ip", remoteIp).addElement("customer_email", customerEmail)
				.addElement("customer_phone", customerPhone).addElement("return_success_url", successUrl)
				.addElement("return_failure_url", failureUrl).addElement("amount", convertedAmount)
				.addElement("currency", currency).addElement("is_payout", isPayout)
				.addElement("customer_bank_id", customerBankId).addElement("order_description", orderDescription)
				.addElement("payout_order_id", orderId).addElement("payout_bank_country", bankCountry)
				.addElement("payout_bank_name", bankName).addElement("payout_swift", swift)
				.addElement("payout_acc_number", accNumber).addElement("payout_bank_address", bankAddress)
				.addElement("payout_owner_name", ownerName).addElement("payout_owner_address", ownerAddress)
				.addElement("billing_address", billingAddress).addElement("shippingAddress", shippingAddress);
	}

	public Request execute(Configuration configuration) {

		configuration.setAction("process");
		http = new Http(configuration);
		response = http.post(configuration.getBaseUrl(), this);

		return this;
	}

	public NodeWrapper getResponse() {
		return response;
	}

	public List<Map.Entry<String, Object>> getElements() {
		return buildRequest("payment_transaction").getElements();
	}

	public InPayAddressRequest getBillingAddress() {
		return billingAddress;
	}
}


text:
require 'hypercharge/api_calls/sandbox'

module Hypercharge
  # This module provides API calls available on the Sansbox only.
  # It provides the ability to simulate chargebacks, chargeback reversals,
  # pre arbitrations, retrieval request on credit card related transactions
  # and also simulates chargebacked, rejected and charged debit sale transactions.
  # Additionaly you can create deposits on purchase on account and pay in advance transactions.
  # By using this interface, you can simulate a complete transaction lifecycle
  # and test your back systems to handle those events accordingly.
  module Sandbox
    extend ApiCalls::Sandbox

    # This module contains credit card numbers which yield a given result when used in the Sandbox
    module CreditCardNumbers
      VISA_APPROVED                         = 4200000000000000.freeze
      VISA_DECLINED                         = 4111111111111111.freeze
      MASTER_CARD_APPROVED                  = 5555555555554444.freeze
      MASTER_CARD_DECLINED                  = 5105105105105100.freeze

      # 3D-Secure enrolled
      THREE_D_SECURE_ENROLLED               = 4711100000000000.freeze

      # 3D-Secure enrolled failing authentication
      THREE_D_SECURE_FAILING_AUTHENTICATION = 4012001037461114.freeze

      # 3D-Secure unavailable - Card Not Participating
      THREE_D_SECURE_UNAVAILABLE            = 4200000000000000.freeze

      # Error in 3DSecure Network in first step of 3D-Secure authentication process
      THREE_D_SECURE_ERROR_IN_STEP_1        = 4012001037484447.freeze

      # Error in 3DSecure Network in second (asynchronous) step of 3D-Secure authentication process
      THREE_D_SECURE_ERROR_IN_STEP_2        = 4012001036273338.freeze
    end

    # This module contains bank account numbers which yield a given result when used in the Sandbox
    module BankAccountNumbers
      APPROVED = 1234567890.freeze
      DECLINED = 2345678901.freeze
      ERROR    = 3456789012.freeze
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

  <copyright>
    <year>2020</year><year>2021</year>
    <holder>wxWidgets team.</holder></copyright>
  <legalnotice>Licensed under the wxWindows Free Documentation Licence, Version 3
  </legalnotice>
  <title>wxSingleChoiceDialog</title>

<module>wxSingleChoiceDialog</module>
<modulesummary>Functions for wxSingleChoiceDialog class</modulesummary>
<description>
This class represents a dialog that shows a list of strings, and allows the user to select one. Double-clicking on a list item is equivalent to single-clicking and then pressing OK.

Styles

This class supports the following styles:

See: <url href="https://docs.wxwidgets.org/3.1/overview_cmndlg.html#overview_cmndlg_singlechoice">Overview cmndlg</url>, <seeerl marker="wxMultiChoiceDialog"><c>wxMultiChoiceDialog</c></seeerl>

This class is derived (and can use functions) from:
    <seeerl marker="wxDialog"><c>wxDialog</c></seeerl> <seeerl marker="wxTopLevelWindow"><c>wxTopLevelWindow</c></seeerl> <seeerl marker="wxWindow"><c>wxWindow</c></seeerl> <seeerl marker="wxEvtHandler"><c>wxEvtHandler</c></seeerl>

wxWidgets docs: <url href="https://docs.wxwidgets.org/3.1/classwx_single_choice_dialog.html">wxSingleChoiceDialog</url>

  </description>
<datatypes><datatype><name name="wxSingleChoiceDialog"/></datatype></datatypes>

<funcs>
  <func>
    <name name="new" arity="4" clause_i="1" since=""/>
    <fsummary>See: <c>new/5</c></fsummary>
  </func>

  <func>
    <name name="new" arity="5" clause_i="1" since=""/>
    <fsummary>Constructor, taking an array of <c>wxString</c> (not implemented in wx) choices and optional client data. </fsummary>
    <desc>
Constructor, taking an array of <c>wxString</c> (not implemented in wx) choices and optional client data.

Remark: Use <seemfa marker="wxDialog#showModal/1"><c>wxDialog:showModal/1</c></seemfa> to show the dialog.

</desc>
  </func>

  <func>
    <name name="getSelection" arity="1" clause_i="1" since=""/>
    <fsummary>Returns the index of selected item. </fsummary>
    <desc>
Returns the index of selected item.

</desc>
  </func>

  <func>
    <name name="getStringSelection" arity="1" clause_i="1" since=""/>
    <fsummary>Returns the selected string. </fsummary>
    <desc>
Returns the selected string.

</desc>
  </func>

  <func>
    <name name="setSelection" arity="2" clause_i="1" since=""/>
    <fsummary>Sets the index of the initially selected item. </fsummary>
    <desc>
Sets the index of the initially selected item.

</desc>
  </func>

  <func>
    <name name="destroy" arity="1" clause_i="1" since=""/>
    <fsummary>Destructor</fsummary>
    <desc>
Destroys the object.
</desc>
  </func>
  </funcs>
</erlref>


text:
using NUnit.Framework;
using ruibarbo.nunit;
using ruibarbo.sampletest.AutomationLayer;

namespace ruibarbo.sampletest.Features
{
    [TestFixture]
    public class CheckBoxTest : TestBase
    {
        [Test]
        public void CheckBoxIsChecked()
        {
            var tab1 = MainWindow.MainTabControl.Tab1;
            tab1.Click();
            var checkBox = tab1.ShowStuffCheckBox;
            checkBox.AssertThat(x => x.IsChecked, Is.True);
        }

        [Test]
        public void CheckBoxChangeIsChecked()
        {
            var tab1 = MainWindow.MainTabControl.Tab1;
            tab1.Click();
            var checkBox = tab1.ShowStuffCheckBox;
            checkBox.Click();
            checkBox.AssertThat(x => x.IsChecked, Is.False);
        }
    }
}


text:
<!DOCTYPE html>

Madoko Maintenance

Apologies, the madoko server is currently under maintenance...

See madoko.codeplex.com for the latest status


text:
The HelloPush sample contains a Cordova project that you can use to learn.

### Before you begin

Before you start, make sure you have the following:

- A [IBM Cloud](http://bluemix.net) account.
- Learn about [Getting Started with Push](https://www.ng.bluemix.net/docs/services/mobilepush/index.html).
- APNs enabled push certificate (.p12 file) and the certificate password for your sandbox environment. For information about how to obtain a p.12 certificate, see the [configuring credentials for Apple push notifications(APNs)](https://console.bluemix.net/docs/services/mobilepush/push_step_1.html#push_step_1_ios) section in the Push documentation. For FCM find teh details here - [FCM Configurations](https://console.bluemix.net/docs/services/mobilepush/push_step_1.html#push_step_1_android).

### Create IBM Cloud Push Notifications Service

Create and Configure Push Notification service:

1. In the IBM Cloud Push Notifications Dashboard, go to the **Configuration** tab to configure your Push Notification Service.
2. In the Apple Push Certificate section, select the Sandbox environment
3. Upload a valid APNs enabled push certificate (.p12 file), then enter the password associated with the certificate.
4. For FCM add the SenderID and APIKey

### Download the sample

Clone the samples with the following command:

```Bash
git clone https://github.com/ibm-bluemix-mobile-services/bms-samples-cordova-hellopush
```

### Add the native platforms to your app

```Bash
cordova platform add ios
cordova platform add android
```

## Add the plugin

```Bash
cordova plugin add bms-push
```

> Adding the bms-push plugin also adds the bms-core plugin

### Configure Cordova

Follow the README instructions for [Configuration](https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-push/#configuration) to configure your development environment.

***Note: Project will not build until you follow instructions from this step.***

### Configure the front end in the sample

1. Navigate to the directory where the project was cloned.
2. Open <b>index.js</b> located at [your-directory]/www/js/index.js

JavaScript:

```Javascript
// deviceready Event Handler
//
// Replace the appGuid and clientSecret with your own values
// These can be retrieved from your Push Notifications service instance
// Set the region: BMSClient.REGION_US_SOUTH, BMSClient.REGION_UK, or BMSClient.REGION_SYDNEY
onDeviceReady: function() {
		var appGuid = "MY APP GUID";
		var clientSecret = "MY CLIENT SECRET";

		BMSClient.initialize(BMSClient.REGION_US_SOUTH);

 		// iOS Actionable notification options. Eg : {"category_Name":[{"identifier_name_1":"action_Name_1"},{"identifier_name_2":"action_Name_2"}]}
		// Pass empty for Android
		var category = {};
		BMSPush.initialize(appGuid, clientSecret, category);
},
```

***Note: Don't forget commas at the end of each line!***

### Build/Run the Cordova App

Now you can run your application in your mobile emulator or on your device.

1. Build the Cordova app. From your terminal enter the following command:

	```Bash
	cordova build ios
	cordova build android
	```

2. Run the sample app. From your terminal enter the following command:

	```Bash
	cordova run ios
	cordova run android
	```

***Note: If testing iOS you need to use a real device connected to your network and build/run from Xcode to register for and receive notifications.***

You will see a single view application with a "REGISTER" button. When you click this button the application will attempt to register the device and application to the Push Notification Service. The application will then display if the registration was successful or unsuccessful. In the unsuccessful state an error will be displayed in the Xcode/Android log, as well as in the application.

Once your device is registered for Push Notifications, it is ready to receive remote notifications. In the IBM Cloud Push Dashboard, navigate to Notifications. Under **Choose The Audience** select **All Devices**. This will send a notification to all devices that have registered for push notifications. Once the notification is received by your app an alert should appear with notification contents.

***Note: For iOS, this application runs on the latest version of XCode (7.0). You may need to update the application settings by setting Enable Bitcode to No. For more info please see the following blog entry:***

## Adding Auto signing in iOS

To set signing credentials iOS create file `build.json` in your app root. Follow the below patter,

Xcode 8 and iOS 10:

```
{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "development",
            "buildFlag": [
                "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
                "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
                "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
            ]
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "app-store",
            "buildFlag": [
                "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
                "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
                "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
            ]
        }
    }
}
```

Earlier versions:

```
{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Development",
            "provisioningProfile": "926c2bd6-8de9-4c2f-8407-1016d2d12954",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Distribution",
            "provisioningProfile": "70f699ad-faf1-4adE-8fea-9d84738fb306",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "app-store"
        }
    }
}
```

Change teh bundle identifier in `config.xml` file.
After that to build ios use the `--buildConfig` flag in `cordova build` command

```
  cordova build ios --buildConfig
```

### Samples & videos

* Please visit for samples - [Github Sample](https://github.com/ibm-bluemix-mobile-services/bms-samples-android-hellopush)

* Video Tutorials Available here - [IBM Cloud Push Notifications](https://www.youtube.com/channel/UCRr2Wou-z91fD6QOYtZiHGA)

### License

This package contains sample code provided in source code form. The samples are licensed under the under the Apache License, Version 2.0 (the "License"). You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 and may also view the license in the license.txt file within this package. Also see the notices.txt file within this package for additional notices.


text:
#import "FBGraphObjectTableCell.h"

static const CGFloat titleFontHeight = 16;
static const CGFloat subtitleFontHeight = 12;
static const CGFloat pictureEdge = 40;
static const CGFloat pictureMargin = 1;
static const CGFloat horizontalMargin = 4;
static const CGFloat titleTopNoSubtitle = 11;
static const CGFloat titleTopWithSubtitle = 3;
static const CGFloat subtitleTop = 23;
static const CGFloat titleHeight = titleFontHeight * 1.25;
static const CGFloat subtitleHeight = subtitleFontHeight * 1.25;

@interface FBGraphObjectTableCell()

@property (nonatomic, retain) UIImageView *pictureView;\
@property (nonatomic, retain) UILabel* titleSuffixLabel;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;

- (void)updateFonts;

@end

@implementation FBGraphObjectTableCell

@synthesize pictureView = _pictureView;
@synthesize titleSuffixLabel = _titleSuffixLabel;
@synthesize activityIndicator = _activityIndicator;
@synthesize boldTitle = _boldTitle;
@synthesize boldTitleSuffix = _boldTitleSuffix;

#pragma mark - Lifecycle

- (id)initWithStyle:(UITableViewCellStyle)style
    reuseIdentifier:(NSString*)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Picture
        UIImageView *pictureView = [[UIImageView alloc] init];
        pictureView.clipsToBounds = YES;
        pictureView.contentMode = UIViewContentModeScaleAspectFill;

        self.pictureView = pictureView;
        [self.contentView addSubview:pictureView];
        [pictureView release];

        // Subtitle
        self.detailTextLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.detailTextLabel.textColor = [UIColor colorWithRed:0.4 green:0.6 blue:0.8 alpha:1.0];
        self.detailTextLabel.font = [UIFont systemFontOfSize:subtitleFontHeight];

        // Title
        self.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.textLabel.font = [UIFont systemFontOfSize:titleFontHeight];

        // Content View
        self.contentView.clipsToBounds = YES;
    }

    return self;
}

- (void)dealloc
{
    [_titleSuffixLabel release];
    [_pictureView release];

    [super dealloc];
}

#pragma mark -

#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- (void)layoutSubviews
{
    [super layoutSubviews];

    [self updateFonts];

    BOOL hasPicture = (self.picture != nil);
    BOOL hasSubtitle = (self.subtitle != nil);
    BOOL hasTitleSuffix = (self.titleSuffix != nil);

    CGFloat pictureWidth = hasPicture ? pictureEdge : 0;
    CGSize cellSize = self.contentView.bounds.size;
    CGFloat textLeft = (hasPicture ? ((2 * pictureMargin) + pictureWidth) : 0) + horizontalMargin;
    CGFloat textWidth = cellSize.width - (textLeft + horizontalMargin);
    CGFloat titleTop = hasSubtitle ? titleTopWithSubtitle : titleTopNoSubtitle;

    self.pictureView.frame = CGRectMake(pictureMargin, pictureMargin, pictureEdge, pictureWidth);
    self.detailTextLabel.frame = CGRectMake(textLeft, subtitleTop, textWidth, subtitleHeight);
    if (!hasTitleSuffix) {
        self.textLabel.frame = CGRectMake(textLeft, titleTop, textWidth, titleHeight);
    } else {
        CGSize titleSize = [self.textLabel.text sizeWithFont:self.textLabel.font];
        CGSize spaceSize = [@" " sizeWithFont:self.textLabel.font];
        CGFloat titleWidth = titleSize.width + spaceSize.width;
        self.textLabel.frame = CGRectMake(textLeft, titleTop, titleWidth, titleHeight);

        CGFloat titleSuffixLeft = textLeft + titleWidth;
        CGFloat titleSuffixWidth = textWidth - titleWidth;
        self.titleSuffixLabel.frame = CGRectMake(titleSuffixLeft, titleTop, titleSuffixWidth, titleHeight);
    }

    [self.pictureView setHidden:!(hasPicture)];
    [self.detailTextLabel setHidden:!(hasSubtitle)];
    [self.titleSuffixLabel setHidden:!(hasTitleSuffix)];
}
#pragma GCC diagnostic warning "-Wdeprecated-declarations"

+ (CGFloat)rowHeight
{
    return pictureEdge + (2 * pictureMargin) + 1;
}

- (void)startAnimatingActivityIndicator {
    CGRect cellBounds = self.bounds;
    if (!self.activityIndicator) {
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityIndicator.hidesWhenStopped = YES;
        activityIndicator.autoresizingMask =
        (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);

        self.activityIndicator = activityIndicator;
        [self addSubview:activityIndicator];
        [activityIndicator release];
    }

    self.activityIndicator.center = CGPointMake(CGRectGetMidX(cellBounds), CGRectGetMidY(cellBounds));

    [self.activityIndicator startAnimating];
}

- (void)stopAnimatingActivityIndicator {
    if (self.activityIndicator) {
        [self.activityIndicator stopAnimating];
    }
}

- (void)updateFonts {
    if (self.boldTitle) {
        self.textLabel.font = [UIFont boldSystemFontOfSize:titleFontHeight];
    } else {
        self.textLabel.font = [UIFont systemFontOfSize:titleFontHeight];
    }

    if (self.boldTitleSuffix) {
        self.titleSuffixLabel.font = [UIFont boldSystemFontOfSize:titleFontHeight];
    } else {
        self.titleSuffixLabel.font = [UIFont systemFontOfSize:titleFontHeight];
    }
}

- (void)createTitleSuffixLabel {
    if (!self.titleSuffixLabel) {
        UILabel *titleSuffixLabel = [[UILabel alloc] init];
        titleSuffixLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self.contentView addSubview:titleSuffixLabel];

        self.titleSuffixLabel = titleSuffixLabel;
        [titleSuffixLabel release];
    }
}
#pragma mark - Properties

- (UIImage *)picture
{
    return self.pictureView.image;
}

- (void)setPicture:(UIImage *)picture
{
    self.pictureView.image = picture;
    [self setNeedsLayout];
}

- (NSString*)subtitle
{
    return self.detailTextLabel.text;
}

- (void)setSubtitle:(NSString *)subtitle
{
    self.detailTextLabel.text = subtitle;
    [self setNeedsLayout];
}

- (NSString*)title
{
    return self.textLabel.text;
}

- (void)setTitle:(NSString *)title
{
    self.textLabel.text = title;
    [self setNeedsLayout];
}

- (NSString*)titleSuffix
{
    return self.titleSuffixLabel.text;
}

- (void)setTitleSuffix:(NSString *)titleSuffix
{
    if (titleSuffix) {
        [self createTitleSuffixLabel];
    }
    if (self.titleSuffixLabel) {
        self.titleSuffixLabel.text = titleSuffix;
    }
    [self setNeedsLayout];
}

@end


text:
<?xml version="1.0" encoding="utf-8" ?>
<mapserver>

  <globals outputurl="http://localhost/output"
           outputpath="c:\output"
           tilecachepath="C:\output\tiles"
           removeinterval="20"
           onlineresource="http://localhost:{port}"
           />

  <servers>
    <server port="8001">
      <instances>
        <instance port="8011" />
        <instance port="8012" />
      </instances>
    </server>
  </servers>

</mapserver>


text:
bash-CVE-2014-6271 CHANGELOG
============================

This file is used to list changes made in each version of the bash-CVE-2014-6271 cookbook.

0.1.0
-----
- [jblaine] - Initial release of bash-CVE-2014-6271


text:
"""High level entry point for processing a sample.

Samples may include multiple lanes, or barcoded subsections of lanes,
processed together.
"""
import copy
import os

import toolz as tz

from bcbio import utils, bam, broad
from bcbio.log import logger
from bcbio.pipeline.merge import merge_bam_files
from bcbio.bam import fastq, callable
from bcbio.bam.trim import trim_adapters
from bcbio.ngsalign import postalign
from bcbio.pipeline.fastq import get_fastq_files
from bcbio.pipeline.alignment import align_to_sort_bam
from bcbio.pipeline import cleanbam
from bcbio.variation import bedutils, recalibrate
from bcbio.variation import multi as vmulti
import bcbio.pipeline.datadict as dd

def prepare_sample(data):
    """Prepare a sample to be run, potentially converting from BAM to
    FASTQ and/or downsampling the number of reads for a test run
    """
    NUM_DOWNSAMPLE = 10000
    logger.debug("Preparing %s" % data["rgnames"]["sample"])
    file1, file2 = get_fastq_files(data)
    if data.get("test_run", False):
        if bam.is_bam(file1):
            file1 = bam.downsample(file1, data, NUM_DOWNSAMPLE)
            file2 = None
        else:
            file1, file2 = fastq.downsample(file1, file2, data,
                                            NUM_DOWNSAMPLE, quick=True)
    data["files"] = [file1, file2]
    return [[data]]

def trim_sample(data):
    """Trim from a sample with the provided trimming method.
    Support methods: read_through.
    """
    to_trim = [x for x in data["files"] if x is not None]
    dirs = data["dirs"]
    config = data["config"]
    # this block is to maintain legacy configuration files
    trim_reads = config["algorithm"].get("trim_reads", False)
    if not trim_reads:
        logger.info("Skipping trimming of %s." % (", ".join(to_trim)))
        return [[data]]

    out_dir = os.path.join(dd.get_work_dir(data), "trimmed")
    utils.safe_makedir(out_dir)

    if trim_reads == "read_through":
        logger.info("Trimming low quality ends and read through adapter "
                    "sequence from %s." % (", ".join(to_trim)))
        out_files = trim_adapters(to_trim, out_dir, config)
        data["files"] = out_files
    return [[data]]

# ## Alignment

def link_bam_file(orig_file, new_dir):
    """Provide symlinks of BAM file and existing indexes.
    """
    new_dir = utils.safe_makedir(new_dir)
    sym_file = os.path.join(new_dir, os.path.basename(orig_file))
    utils.symlink_plus(orig_file, sym_file)
    return sym_file

def _add_supplemental_bams(data):
    """Add supplemental files produced by alignment, useful for structural
    variant calling.
    """
    file_key = "work_bam"
    if data.get(file_key):
        for supext in ["disc", "sr"]:
            base, ext = os.path.splitext(data[file_key])
            test_file = "%s-%s%s" % (base, supext, ext)
            if os.path.exists(test_file):
                sup_key = file_key + "-plus"
                if not sup_key in data:
                    data[sup_key] = {}
                data[sup_key][supext] = test_file
    return data

def process_alignment(data):
    """Do an alignment of fastq files, preparing a sorted BAM output file.
    """
    if "files" not in data:
        fastq1, fastq2 = None, None
    elif len(data["files"]) == 2:
        fastq1, fastq2 = data["files"]
    else:
        assert len(data["files"]) == 1, data["files"]
        fastq1, fastq2 = data["files"][0], None
    config = data["config"]
    aligner = config["algorithm"].get("aligner", None)
    if fastq1 and utils.file_exists_or_remote(fastq1) and aligner:
        logger.info("Aligning lane %s with %s aligner" % (data["rgnames"]["lane"], aligner))
        data = align_to_sort_bam(fastq1, fastq2, aligner, data)
        data = _add_supplemental_bams(data)
    elif fastq1 and os.path.exists(fastq1) and fastq1.endswith(".bam"):
        sort_method = config["algorithm"].get("bam_sort")
        bamclean = config["algorithm"].get("bam_clean")
        if bamclean is True or bamclean == "picard":
            if sort_method and sort_method != "coordinate":
                raise ValueError("Cannot specify `bam_clean: picard` with `bam_sort` other than coordinate: %s"
                                 % sort_method)
            out_bam = cleanbam.picard_prep(fastq1, data["rgnames"], data["sam_ref"], data["dirs"],
                                           data)
        elif sort_method:
            runner = broad.runner_from_config(config)
            out_file = os.path.join(data["dirs"]["work"], "{}-sort.bam".format(
                os.path.splitext(os.path.basename(fastq1))[0]))
            out_bam = runner.run_fn("picard_sort", fastq1, sort_method, out_file)
        else:
            out_bam = link_bam_file(fastq1, os.path.join(data["dirs"]["work"], "prealign",
                                                         data["rgnames"]["sample"]))
        bam.check_header(out_bam, data["rgnames"], data["sam_ref"], data["config"])
        dedup_bam = postalign.dedup_bam(out_bam, data)
        data["work_bam"] = dedup_bam
    elif fastq1 and utils.file_exists_or_remote(fastq1) and fastq1.endswith(".cram"):
        data["work_bam"] = fastq1
    elif fastq1 is None and "vrn_file" in data:
        data["config"]["algorithm"]["variantcaller"] = False
        data["work_bam"] = None
    else:
        raise ValueError("Could not process input file: %s" % fastq1)
    return [[data]]

def prep_samples(*items):
    """Handle any global preparatory steps for samples with potentially shared data.

    Avoids race conditions in postprocess alignment when performing prep tasks
    on shared files between multiple similar samples.

    Cleans input BED files to avoid issues with overlapping input segments.
    """
    out = []
    for data in (x[0] for x in items):
        data = bedutils.clean_inputs(data)
        out.append([data])
    return out

def postprocess_alignment(data):
    """Perform post-processing steps required on full BAM files.
    Prepares list of callable genome regions allowing subsequent parallelization.
    """
    if vmulti.bam_needs_processing(data) and data["work_bam"].endswith(".bam"):
        callable_region_bed, nblock_bed, callable_bed = \
            callable.block_regions(data["work_bam"], data["sam_ref"], data["config"])
        data["regions"] = {"nblock": nblock_bed, "callable": callable_bed}
        if (os.path.exists(callable_region_bed) and
                not data["config"]["algorithm"].get("variant_regions")):
            data["config"]["algorithm"]["variant_regions"] = callable_region_bed
            data = bedutils.clean_inputs(data)
        data = _recal_no_markduplicates(data)
    return [[data]]

def _recal_no_markduplicates(data):
    orig_config = copy.deepcopy(data["config"])
    data["config"]["algorithm"]["mark_duplicates"] = False
    data = recalibrate.prep_recal(data)[0][0]
    data["config"] = orig_config
    return data

def _merge_out_from_infiles(in_files):
    """Generate output merged file name from set of input files.

    Handles non-shared filesystems where we don't know output path when setting
    up split parts.
    """
    fname = os.path.commonprefix([os.path.basename(f) for f in in_files])
    while fname.endswith(("-", "_", ".")):
        fname = fname[:-1]
    ext = os.path.splitext(in_files[0])[-1]
    dirname = os.path.dirname(in_files[0])
    while dirname.endswith(("split", "merge")):
        dirname = os.path.dirname(dirname)
    return os.path.join(dirname, "%s%s" % (fname, ext))

def delayed_bam_merge(data):
    """Perform a merge on previously prepped files, delayed in processing.

    Handles merging of associated split read and discordant files if present.
    """
    if data.get("combine"):
        assert len(data["combine"].keys()) == 1
        file_key = data["combine"].keys()[0]
        extras = []
        for x in data["combine"][file_key].get("extras", []):
            if isinstance(x, (list, tuple)):
                extras.extend(x)
            else:
                extras.append(x)
        if file_key in data:
            extras.append(data[file_key])
        in_files = sorted(list(set(extras)))
        out_file = tz.get_in(["combine", file_key, "out"], data, _merge_out_from_infiles(in_files))
        sup_exts = data.get(file_key + "-plus", {}).keys()
        for ext in sup_exts + [""]:
            merged_file = None
            if os.path.exists(utils.append_stem(out_file, "-" + ext)):
                cur_out_file, cur_in_files = out_file, []
            if ext:
                cur_in_files = list(filter(os.path.exists, (utils.append_stem(f, "-" + ext) for f in in_files)))
                cur_out_file = utils.append_stem(out_file, "-" + ext) if len(cur_in_files) > 0 else None
            else:
                cur_in_files, cur_out_file = in_files, out_file
            if cur_out_file:
                config = copy.deepcopy(data["config"])
                config["algorithm"]["save_diskspace"] = False
                if len(cur_in_files) > 0:
                    merged_file = merge_bam_files(cur_in_files, os.path.dirname(cur_out_file), config,
                                                  out_file=cur_out_file)
                else:
                    assert os.path.exists(cur_out_file)
                    merged_file = cur_out_file
            if merged_file:
                if ext:
                    data[file_key + "-plus"][ext] = merged_file
                else:
                    data[file_key] = merged_file
        data.pop("region", None)
        data.pop("combine", None)
    return [[data]]


text:
from office365.runtime.client_value import ClientValue

class ServicePlanInfo(ClientValue):
    """Contains information about a service plan associated with a subscribed SKU. The servicePlans property of
    the subscribedSku entity is a collection of servicePlanInfo."""

    def __init__(self, _id=None, name=None, provisioning_status=None, applies_to=None):
        """

        :param str applies_to: The object the service plan can be assigned to. Possible values:
               "User" - service plan can be assigned to individual users.
               "Company" - service plan can be assigned to the entire tenant.
        :param str provisioning_status: The provisioning status of the service plan. Possible values:
               "Success" - Service is fully provisioned.
               "Disabled" - Service has been disabled.
               "PendingInput" - Service is not yet provisioned; awaiting service confirmation.
               "PendingActivation" - Service is provisioned but requires explicit activation by administrator
               (for example, Intune_O365 service plan)
               "PendingProvisioning" - Microsoft has added a new service to the product SKU and it has not been
               activated in the tenant, yet.
        :param str name: The name of the service plan.
        :param str _id: The unique identifier of the service plan.
        """
        super(ServicePlanInfo, self).__init__()
        self.servicePlanId = _id
        self.servicePlanName = name
        self.provisioningStatus = provisioning_status
        self.appliesTo = applies_to


text:
package oghamspringbootv2autoconfigure.it;

import static fr.sii.ogham.testing.assertion.OghamMatchers.isIdenticalHtml;
import static fr.sii.ogham.testing.assertion.hamcrest.ExceptionMatchers.hasAnyCause;
import static fr.sii.ogham.testing.assertion.hamcrest.ExceptionMatchers.hasMessage;
import static fr.sii.ogham.testing.util.ResourceUtils.resourceAsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThrows;
import static org.springframework.boot.autoconfigure.AutoConfigurations.of;

import java.io.IOException;

import org.jsmpp.bean.SubmitSm;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

import com.icegreen.greenmail.junit4.GreenMailRule;

import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.message.content.TemplateContent;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.email.message.Email;
import fr.sii.ogham.sms.message.Sms;
import fr.sii.ogham.spring.v2.autoconfigure.OghamSpringBoot2AutoConfiguration;
import fr.sii.ogham.testing.assertion.OghamAssertions;
import fr.sii.ogham.testing.extension.junit.LoggingTestRule;
import fr.sii.ogham.testing.extension.junit.email.RandomPortGreenMailRule;
import fr.sii.ogham.testing.extension.junit.sms.JsmppServerRule;
import fr.sii.ogham.testing.extension.junit.sms.SmppServerRule;
import freemarker.core.InvalidReferenceException;
import mock.context.SimpleBean;

public class StaticMethodAccessTest {
	@Rule public final LoggingTestRule loggingRule = new LoggingTestRule();
	@Rule public final GreenMailRule greenMail = new RandomPortGreenMailRule();
	@Rule public final SmppServerRule<SubmitSm> smppServer = new JsmppServerRule();

	private ApplicationContextRunner contextRunner;

	@Before
	public void setUp() {
		contextRunner = new ApplicationContextRunner()
				.withPropertyValues(
						"mail.smtp.host="+greenMail.getSmtp().getBindTo(),
						"mail.smtp.port="+greenMail.getSmtp().getPort(),
						"ogham.sms.smpp.host=127.0.0.1",
						"ogham.sms.smpp.port="+smppServer.getPort(),
						"spring.freemarker.suffix=")
				.withConfiguration(of(FreeMarkerAutoConfiguration.class, OghamSpringBoot2AutoConfiguration.class));
	}

	@Test
	public void emailUsingFreemarkerTemplateShouldBeAbleToCallStaticMethods() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=true");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			messagingService.send(new Email()
					.from("foo@yopmail.com")
					.to("bar@yopmail.com")
					.content(new TemplateContent("/freemarker/source/static-methods.html.ftl", new SimpleBean("world", 0))));
			OghamAssertions.assertThat(greenMail)
				.receivedMessages()
					.count(is(1))
					.message(0)
						.body()
							.contentAsString(isIdenticalHtml(resourceAsString("/freemarker/expected/static-methods.html")));
		});
	}

	@Test
	public void smsUsingFreemarkerTemplateShouldBeAbleToCallStaticMethods() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=true");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			messagingService.send(new Sms()
					.from("+33102030405")
					.to("+33123456789")
					.content(new TemplateContent("/freemarker/source/static-methods.txt.ftl", new SimpleBean("world", 0))));
			OghamAssertions.assertThat(smppServer)
			.receivedMessages()
				.count(is(1))
				.message(0)
					.content(is(resourceAsString("/freemarker/expected/static-methods.txt")));
		});
	}

	@Test
	public void emailUsingFreemarkerTemplateAndStaticMethodAccessDisabledShouldFail() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=false");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			// @formatter:off
			MessagingException e = assertThrows("should throw", MessagingException.class, () -> {
				messagingService.send(new Email()
						.from("foo@yopmail.com")
						.to("bar@yopmail.com")
						.content(new TemplateContent("/freemarker/source/static-methods.html.ftl", new SimpleBean("world", 0))));
			});
			assertThat("should report missing statics", e, allOf(
					instanceOf(MessagingException.class),
					hasAnyCause(InvalidReferenceException.class, hasMessage(containsString("The following has evaluated to null or missing:\n==> statics")))));
			// @formatter:on
		});
	}

	@Test
	public void smsUsingFreemarkerTemplateAndStaticMethodAccessDisabledShouldFail() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=false");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			// @formatter:off
			MessagingException e = assertThrows("should throw", MessagingException.class, () -> {
				messagingService.send(new Sms()
						.from("+33102030405")
						.to("+33123456789")
						.content(new TemplateContent("/freemarker/source/static-methods.txt.ftl", new SimpleBean("world", 0))));
			});
			// @formatter:on
			assertThat("should report missing statics", e, allOf(
					instanceOf(MessagingException.class),
					hasAnyCause(InvalidReferenceException.class, hasMessage(containsString("The following has evaluated to null or missing:\n==> statics")))));
		});
	}

	@Test
	public void emailUsingFreemarkerTemplateShouldBeAbleToCallStaticMethodsWithCustomVariableName() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=true",
				"ogham.freemarker.static-method-access.variable-name=global");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			messagingService.send(new Email()
					.from("foo@yopmail.com")
					.to("bar@yopmail.com")
					.content(new TemplateContent("/freemarker/source/static-methods-different-name.html.ftl", new SimpleBean("world", 0))));
			OghamAssertions.assertThat(greenMail)
				.receivedMessages()
					.count(is(1))
					.message(0)
						.body()
							.contentAsString(isIdenticalHtml(resourceAsString("/freemarker/expected/static-methods.html")));
		});
	}

	@Test
	public void smsUsingFreemarkerTemplateShouldBeAbleToCallStaticMethodsWithCustomVariableName() throws MessagingException, IOException {
		contextRunner = contextRunner.withPropertyValues(
				"ogham.freemarker.static-method-access.enable=true",
				"ogham.freemarker.static-method-access.variable-name=global");
		contextRunner.run((context) -> {
			MessagingService messagingService = context.getBean(MessagingService.class);
			messagingService.send(new Sms()
					.from("+33102030405")
					.to("+33123456789")
					.content(new TemplateContent("/freemarker/source/static-methods-different-name.txt.ftl", new SimpleBean("world", 0))));
			OghamAssertions.assertThat(smppServer)
			.receivedMessages()
				.count(is(1))
				.message(0)
					.content(is(resourceAsString("/freemarker/expected/static-methods.txt")));
		});
	}

}


text:
/**
 * generated by Xtext 2.9.2
 */
package xmodelica.modelica;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Component Declaration'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link xmodelica.modelica.ComponentDeclaration#getDecl Decl}

 *
{@link xmodelica.modelica.ComponentDeclaration#getCond Cond}

 *
{@link xmodelica.modelica.ComponentDeclaration#getComment Comment}

 *

 *
 * @see xmodelica.modelica.ModelicaPackage#getComponentDeclaration()
 * @model
 * @generated
 */
public interface ComponentDeclaration extends EObject
{
  /**
   * Returns the value of the 'Decl' containment reference.
   *
   *

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

   *
   * @return the value of the 'Decl' containment reference.
   * @see #setDecl(Declaration)
   * @see xmodelica.modelica.ModelicaPackage#getComponentDeclaration_Decl()
   * @model containment="true"
   * @generated
   */
  Declaration getDecl();

  /**
   * Sets the value of the '{@link xmodelica.modelica.ComponentDeclaration#getDecl Decl}' containment reference.
   *
   *
   * @param value the new value of the 'Decl' containment reference.
   * @see #getDecl()
   * @generated
   */
  void setDecl(Declaration value);

  /**
   * Returns the value of the 'Cond' containment reference.
   *
   *

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

   *
   * @return the value of the 'Cond' containment reference.
   * @see #setCond(ConditionAttribute)
   * @see xmodelica.modelica.ModelicaPackage#getComponentDeclaration_Cond()
   * @model containment="true"
   * @generated
   */
  ConditionAttribute getCond();

  /**
   * Sets the value of the '{@link xmodelica.modelica.ComponentDeclaration#getCond Cond}' containment reference.
   *
   *
   * @param value the new value of the 'Cond' containment reference.
   * @see #getCond()
   * @generated
   */
  void setCond(ConditionAttribute value);

  /**
   * Returns the value of the 'Comment' containment reference.
   *
   *

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

   *
   * @return the value of the 'Comment' containment reference.
   * @see #setComment(Comment)
   * @see xmodelica.modelica.ModelicaPackage#getComponentDeclaration_Comment()
   * @model containment="true"
   * @generated
   */
  Comment getComment();

  /**
   * Sets the value of the '{@link xmodelica.modelica.ComponentDeclaration#getComment Comment}' containment reference.
   *
   *
   * @param value the new value of the 'Comment' containment reference.
   * @see #getComment()
   * @generated
   */
  void setComment(Comment value);

} // ComponentDeclaration


text:
using StyletIoC.Internal.Creators;
using StyletIoC.Internal.Registrations;
using System;

namespace StyletIoC.Internal.Builders
{
    internal class BuilderAbstractFactoryBinding : BuilderBindingBase
    {
        public BuilderAbstractFactoryBinding(Type serviceType)
            : base(serviceType)
        {
            if (serviceType.IsGenericTypeDefinition)
                throw new StyletIoCRegistrationException(String.Format("Unbound generic type {0} can't be used as an abstract factory", serviceType.GetDescription()));
        }

        public override void Build(Container container)
        {
            var factoryType = container.GetFactoryForType(this.ServiceType);
            var creator = new AbstractFactoryCreator(factoryType);
            var registration = new TransientRegistration(creator);

            container.AddRegistration(new TypeKey(this.ServiceType.TypeHandle, this.Key), registration);
        }
    }
}


text:
import xbmc
import xbmcgui
import urllib
import os
import time
import urlparse
from xbmctorrent import plugin, torrent2http
from xbmctorrent.ga import track_event
from xbmctorrent.utils import url_get_json
from contextlib import contextmanager, closing, nested

TORRENT2HTTP_TIMEOUT = 20
TORRENT2HTTP_POLL = 200

WINDOW_FULLSCREEN_VIDEO = 12005

XBFONT_LEFT = 0x00000000
XBFONT_RIGHT = 0x00000001
XBFONT_CENTER_X = 0x00000002
XBFONT_CENTER_Y = 0x00000004
XBFONT_TRUNCATED = 0x00000008
XBFONT_JUSTIFY = 0x00000010

STATE_STRS = [
    'Queued',
    'Checking',
    'Downloading metadata',
    'Downloading',
    'Finished',
    'Seeding',
    'Allocating',
    'Allocating file & Checking resume'
]

VIEWPORT_WIDTH = 1920.0
VIEWPORT_HEIGHT = 1088.0
OVERLAY_WIDTH = int(VIEWPORT_WIDTH * 0.7) # 70% size
OVERLAY_HEIGHT = 150

ENCRYPTION_SETTINGS = {
    "Forced": 0,
    "Enabled": 1,
    "Disabled": 2,
}

# Somehow if we close the dialog too fast, it makes XBMC go bonkers
class SafeDialogProgress(xbmcgui.DialogProgress):
    def close(self):
        xbmc.sleep(1000)
        super(SafeDialogProgress, self).close()

class OverlayText(object):
    def __init__(self, w, h, *args, **kwargs):
        self.window = xbmcgui.Window(WINDOW_FULLSCREEN_VIDEO)
        viewport_w, viewport_h = self._get_skin_resolution()
        # Adjust size based on viewport, we are using 1080p coordinates
        w = int(w * viewport_w / VIEWPORT_WIDTH)
        h = int(h * viewport_h / VIEWPORT_HEIGHT)
        x = (viewport_w - w) / 2
        y = (viewport_h - h) / 2
        self._shown = False
        self._text = ""
        self._label = xbmcgui.ControlLabel(x, y, w, h, self._text, *args, **kwargs)
        self._background = xbmcgui.ControlImage(x, y, w, h, os.path.join(plugin.addon.getAddonInfo("path"), "resources", "images", "black.png"))
        self._background.setColorDiffuse("0xD0000000")

    def show(self):
        if not self._shown:
            self.window.addControls([self._background, self._label])
            self._shown = True

    def hide(self):
        if self._shown:
            self._shown = False
            self.window.removeControls([self._background, self._label])

    def close(self):
        self.hide()

    @property
    def text(self):
        return self._text

    @text.setter
    def text(self, text):
        self._text = text
        if self._shown:
            self._label.setLabel(self._text)

    # This is so hackish it hurts.
    def _get_skin_resolution(self):
        import xml.etree.ElementTree as ET
        skin_path = xbmc.translatePath("special://skin/")
        tree = ET.parse(os.path.join(skin_path, "addon.xml"))
        res = tree.findall("./extension/res")[0]
        return int(res.attrib["width"]), int(res.attrib["height"])

class TorrentPlayer(xbmc.Player):
    def init(self, magnet_uri):
        track_event("torrent_player", "start")
        self.magnet_uri = magnet_uri
        self.magnet_args = urlparse.parse_qs(self.magnet_uri.replace("magnet:?", "")) # I know about urlparse.urlsplit but this is faster
        self.magnet_display_name = ""
        if self.magnet_args["dn"]:
            self.magnet_display_name = self.magnet_args["dn"][0]
        self.torrent2http_options = {
            "magnet": magnet_uri,
            "dlpath": plugin.get_setting("dlpath") or ".",
            "dlrate": plugin.get_setting("max_download_rate") or "0",
            "ulrate": plugin.get_setting("max_upload_rate") or "0",
            "ulrate": plugin.get_setting("max_upload_rate") or "0",
            "encryption": plugin.get_setting("encryption"),
        }
        if plugin.get_setting("keep"):
            self.torrent2http_options["keep"] = None
        track_event("download", "start", magnet_uri)
        self.on_playback_started = []
        self.on_playback_resumed = []
        self.on_playback_paused = []
        self.on_playback_stopped = []
        return self

    def onPlayBackStarted(self):
        for f in self.on_playback_started:
            f()
        track_event("video", "play", self.magnet_display_name)

    def onPlayBackResumed(self):
        for f in self.on_playback_resumed:
            f()
        self.onPlayBackStarted()

    def onPlayBackPaused(self):
        for f in self.on_playback_paused:
            f()
        track_event("video", "pause", self.magnet_display_name)

    def onPlayBackStopped(self):
        for f in self.on_playback_stopped:
            f()
        track_event("video", "stop", self.magnet_display_name)

    def _get_status_lines(self, status):
        return [
            self.magnet_display_name,
            "%.2f%% %s" % (status["progress"] * 100, STATE_STRS[status["state"]]),
            "D:%(download_rate).2fkb/s U:%(upload_rate).2fkb/s S:%(num_seeds)d P:%(num_peers)d" % status
        ]

    @contextmanager
    def attach(self, callback, *events):
        for event in events:
            event.append(callback)
        yield
        for event in events:
            event.remove(callback)

    def _wait_t2h_startup(self, t2h):
        start = time.time()
        while (time.time() - start) < TORRENT2HTTP_TIMEOUT:
            try:
                t2h("status")
                return True
            except:
                pass
            xbmc.sleep(TORRENT2HTTP_POLL)
        return False

    def loop(self):
        has_resolved = False

        plugin.log.info("Starting torrent2http...")
        with closing(torrent2http.start(**self.torrent2http_options)) as t2h_instance:
            t2h = lambda cmd: url_get_json("http://%s/%s" % (t2h_instance.bind_address, cmd))

            if not self._wait_t2h_startup(t2h):
                return

            plugin.log.info("Opening download dialog...")
            with closing(SafeDialogProgress()) as dialog:
                dialog.create(plugin.name)

                plugin.log.info("Waiting for file resolution...")
                while not has_resolved:
                    if xbmc.abortRequested or dialog.iscanceled():
                        return

                    status = t2h("status")

                    if status["state"] >= 0:
                        dialog.update(int(status["progress"] * 100), *self._get_status_lines(status))

                    if status["state"] >= 3 and not has_resolved: # Downloading?
                        files = t2h("ls")["files"]
                        biggest_file = sorted(files, key=lambda x: x["size"])[-1]
                        percent_complete = float(biggest_file["complete_pieces"]) / float(biggest_file["total_pieces"]) * 100.0

                        if percent_complete >= 0.5:
                            plugin.log.info("Resolving to http://%s/files/%s" % (t2h_instance.bind_address, biggest_file["name"]))
                            has_resolved = True
                            url_name = "/".join(map(urllib.quote, biggest_file["name"].split("/")))
                            plugin.set_resolved_url({
                                "label": self.magnet_display_name,
                                "path": "http://%s/files/%s" % (t2h_instance.bind_address, url_name),
                                "is_playable": True,
                            })
                            break

                    xbmc.sleep(TORRENT2HTTP_POLL)

            # We are now playing
            plugin.log.info("Now playing torrent...")
            with closing(OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay:
                with nested(self.attach(overlay.show, self.on_playback_paused),
                            self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)):
                    while not xbmc.abortRequested and self.isPlaying():
                        overlay.text = "\n".join(self._get_status_lines(t2h("status")))
                        xbmc.sleep(TORRENT2HTTP_POLL)

        plugin.log.info("Closing Torrent player.")


text:
[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)

Will load a series of images while adhering to rate limits.

## Example
```javascript
// the following will create a loader
// which will load 2 images every 1000 milliseconds
var loader = require('rate-limited-image-loader')(2, 1000);

var images = [
    'imageURL.jpg', 'imageURL.png', 'imageURL1.jpg', 'imageURL1.png'
];

// Load in images.
// The api is based around https://github.com/Jam3/async-image-loader
loader(images, function(images) {
    images.forEach( function(image) {
        document.body.appendChild(image);
    });
})
.on('progress', function(info) {
    console.log('percentage loaded:', info.count / info.total);
});
```

## Install

```sh
npm install rate-limited-image-loader --save
```

## Usage

[![NPM](https://nodei.co/npm/rate-limited-image-loader.png)](https://www.npmjs.com/package/rate-limited-image-loader)

#### `loader = require('rate-limited-image-loader')(imagesToLoad, milliseconds)`

Returns a function which can be used to load images. This loader function is based on the module [`async-image-loader`](https://github.com/Jam3/async-image-loader). The difference being the image load will be rate limited. `imagesToLoad` is the count of images that can be loaded in `milliseconds`.

For instance with the Google Maps Image API you can load 50 images per minute your loader would be constructed like this:
```javascript
// loader to load 50 images per minute
var loader = require('rate-limited-image-loader')(50, 60 * 1000);
```

#### `emitter = loader(urls, [opt], [cb])`

Starts loading the specified `urls`. Elements in the `urls` array can either be strings, or objects containing `{ url }`.

The `opt` settings can be:

- `crossOrigin` the CORS setting for image loading (default undefined)
- `defaultImage` the fallback Image to use when a load 404s (default null)

On complete, `cb` is called with an array of HTMLImageObjects as the first paramter (same order as input). Any images not found will be replaced with `defaultImage`, or null.

#### `emitter.on('progress', fn)`

Each resource will trigger a `progress` event when it completes loading, or when it fails. The function is passed an `event` parameter:

```js
{
  total: Number        // total # of images,  N
  count: Number        // # of loaded images, [ 1 .. N ]
  image: Image         // loaded image element, or defaultImage
  data:  String|Object // the value provided in the input array
}
```

Since the loading is done in parallel, the order is not the same as the input. This event will be triggered regardless of whether the `image` resource loaded successfully, so `image` may be null.

Here, `ev.data` is the same element that was given in the input array, either a string URL or the object containing `{ url }`.

#### `emitter.on('not-found', fn)`

Emitted for each resource that cannot be loaded (i.e. 404). The passed value is the `data` that was unable to load; either a String or `{ url }` object depending on what was passed to input.

This is emitted before the `progress` event.

## License

MIT, see [LICENSE.md](http://github.com/Jam3/rate-limited-image-loader/blob/master/LICENSE.md) for details.


text:
import java.util.Optional;

public class LinearSearch {

    public Optional<Integer> search(Integer[] array, Integer key) {
        for (int index = 0; index < array.length; index++) {
            if (key.equals(array[index])) {
                return Optional.of(index);
            }
        }
        return Optional.empty();
    }

}


text:
'use strict';

import 'vs/css!./media/notabstitle';
import errors = require('vs/base/common/errors');
import { IEditorGroup, toResource } from 'vs/workbench/common/editor';
import DOM = require('vs/base/browser/dom');
import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl';
import { EditorLabel } from 'vs/workbench/browser/labels';
import { Verbosity } from 'vs/platform/editor/common/editor';
import { TAB_ACTIVE_FOREGROUND } from 'vs/workbench/common/theme';

export class NoTabsTitleControl extends TitleControl {
	private titleContainer: HTMLElement;
	private editorLabel: EditorLabel;

	public setContext(group: IEditorGroup): void {
		super.setContext(group);

		this.editorActionsToolbar.context = { group };
	}

	public create(parent: HTMLElement): void {
		super.create(parent);

		this.titleContainer = parent;

		// Pin on double click
		this.toUnbind.push(DOM.addDisposableListener(this.titleContainer, DOM.EventType.DBLCLICK, (e: MouseEvent) => this.onTitleDoubleClick(e)));

		// Detect mouse click
		this.toUnbind.push(DOM.addDisposableListener(this.titleContainer, DOM.EventType.CLICK, (e: MouseEvent) => this.onTitleClick(e)));

		// Editor Label
		this.editorLabel = this.instantiationService.createInstance(EditorLabel, this.titleContainer, void 0);
		this.toUnbind.push(this.editorLabel);
		this.toUnbind.push(DOM.addDisposableListener(this.editorLabel.labelElement, DOM.EventType.CLICK, (e: MouseEvent) => this.onTitleLabelClick(e)));
		this.toUnbind.push(DOM.addDisposableListener(this.editorLabel.descriptionElement, DOM.EventType.CLICK, (e: MouseEvent) => this.onTitleLabelClick(e)));

		// Right Actions Container
		const actionsContainer = document.createElement('div');
		DOM.addClass(actionsContainer, 'title-actions');
		this.titleContainer.appendChild(actionsContainer);

		// Editor actions toolbar
		this.createEditorActionsToolBar(actionsContainer);

		// Context Menu
		this.toUnbind.push(DOM.addDisposableListener(this.titleContainer, DOM.EventType.CONTEXT_MENU, (e: Event) => this.onContextMenu({ group: this.context, editor: this.context.activeEditor }, e, this.titleContainer)));
	}

	private onTitleLabelClick(e: MouseEvent): void {
		DOM.EventHelper.stop(e, false);
		if (!this.dragged) {
			setTimeout(() => this.quickOpenService.show()); // delayed to let the onTitleClick() come first which can cause a focus change which can close quick open
		}
	}

	private onTitleDoubleClick(e: MouseEvent): void {
		DOM.EventHelper.stop(e);
		if (!this.context) {
			return;
		}

		const group = this.context;

		this.editorGroupService.pinEditor(group, group.activeEditor);
	}

	private onTitleClick(e: MouseEvent): void {
		if (!this.context) {
			return;
		}

		const group = this.context;

		// Close editor on middle mouse click
		if (e.button === 1 /* Middle Button */) {
			this.closeEditorAction.run({ group, editor: group.activeEditor }).done(null, errors.onUnexpectedError);
		}

		// Focus editor group unless click on toolbar
		else if (this.stacks.groups.length === 1 && !DOM.isAncestor((e.target || e.srcElement) as HTMLElement, this.editorActionsToolbar.getContainer().getHTMLElement())) {
			this.editorGroupService.focusGroup(group);
		}
	}

	protected doRefresh(): void {
		const group = this.context;
		const editor = group && group.activeEditor;
		if (!editor) {
			this.editorLabel.clear();
			this.clearEditorActionsToolbar();

			return; // return early if we are being closed
		}

		const isPinned = group.isPinned(group.activeEditor);
		const isActive = this.stacks.isActive(group);

		// Activity state
		if (isActive) {
			DOM.addClass(this.titleContainer, 'active');
		} else {
			DOM.removeClass(this.titleContainer, 'active');
		}

		// Dirty state
		if (editor.isDirty()) {
			DOM.addClass(this.titleContainer, 'dirty');
		} else {
			DOM.removeClass(this.titleContainer, 'dirty');
		}

		// Editor Label
		const resource = toResource(editor, { supportSideBySide: true });
		const name = editor.getName() || '';
		const description = isActive ? (editor.getDescription() || '') : '';
		let title = editor.getTitle(Verbosity.LONG);
		if (description === title) {
			title = ''; // dont repeat what is already shown
		}

		this.editorLabel.setLabel({ name, description, resource }, { title, italic: !isPinned, extraClasses: ['title-label'] });
		this.editorLabel.element.style.color = this.getColor(TAB_ACTIVE_FOREGROUND, (color, theme) => {
			if (!isActive) {
				if (theme.type === 'dark') {
					return color.transparent(0.5);
				}

				if (theme.type === 'light') {
					return color.transparent(0.7);
				}
			}

			return color;
		});

		// Update Editor Actions Toolbar
		this.updateEditorActionsToolbar();
	}
}


text:
<!DOCTYPE html>
<html lang="en">
		<head>
		<title>plane test</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
body {
	font-family: Monospace;
	background-color: #f0f0f0;
	margin: 0px;
	overflow: hidden;
}
</style>
		</head>
		<body>
<script src="build/three.js"></script>
<script src="js/controls/TrackballControls.js"></script>
<script src="js/libs/tween.min.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
var container, stats;
var camera, scene, raycaster, renderer, controls,lookAtVector;

var mouse = new THREE.Vector2(),
    INTERSECTED;
var radius = 100,
    theta = 0;
	var texturearray =[];
	var objarray=[];

init();
animate();

function init() {
	loadtextures();

    container = document.createElement('div');
    document.body.appendChild(container);

    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);

    scene = new THREE.Scene();
    controls = new THREE.TrackballControls(camera);
    controls.dynamicDampingFactor = 0.3;
	lookAtVector = new THREE.Vector3(0,0,0);

    //var light = new THREE.DirectionalLight(0xffffff, 1);
    //light.position.set(1, 1, 1).normalize();
    //scene.add(light);
	var light = new THREE.AmbientLight( 0xf1f1f1 ); // soft white light
scene.add( light );
	var pointLight = new THREE.PointLight( 0xffffff );
pointLight.position.set(1,1,2);
camera.add(pointLight);

    var geometry = new THREE.PlaneBufferGeometry(20, 20, 32);
	var count=0;
    for (var i = 0; i < 600; i++) {
		//var texture = new THREE.TextureLoader().load( 'images/image'+i+'.jpg' );

		//var material = new THREE.MeshBasicMaterial({map: texture});

        var object = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
            color: 0xffffff, transparent: true
        }));
		console.log(object, i);

        object.position.x = Math.random() * 600 - 400;
        object.position.y = Math.random() * 600 - 400;
        object.position.z = Math.random() * 600 - 400;

        object.rotation.x = Math.random() * Math.PI / 2;
        object.rotation.y = Math.random() * Math.PI / 2;
        //object.rotation.z = Math.random() * 2 * Math.PI;

        //object.scale.x = Math.random() + 0.5;
        //object.scale.y = Math.random() + 0.5;
        //object.scale.z = Math.random() + 0.5;

 		 //material = new THREE.MeshBasicMaterial({map: texture});
		object.material.side = THREE.DoubleSide
		object.material.map = texturearray[count];
		if(count == 114){
			count=0;
		}else{
			count++;
		}

		objarray.push(object);

        scene.add(object);

    }

    raycaster = new THREE.Raycaster();

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xf0f0f0);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.sortObjects = false;
    container.appendChild(renderer.domElement);

    stats = new Stats();
    container.appendChild(stats.dom);

    document.addEventListener('mousemove', onDocumentMouseMove, false);
    document.addEventListener('mousedown', onDocumentMouseDown, false);

    //

    window.addEventListener('resize', onWindowResize, false);
	camera.lookAt(scene);

}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);

}

function onDocumentMouseMove(event) {

    event.preventDefault();

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

}

function onDocumentMouseDown(event) {

    event.preventDefault();

    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children);

    if (intersects.length > 0) {
        INTERSECTED = intersects[0].object;
        //INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
        //INTERSECTED.material.emissive.setHex(0xff0000);

        //var camtween = new TWEEN.Tween( camera.position ).to( {x:INTERSECTED.position.x, y: INTERSECTED.position.y, z:INTERSECTED.position.z}, 2000 ).easing( TWEEN.Easing.Elastic.Out).start();
        //camera.lookAt( INTERSECTED.position );
        toObj(INTERSECTED);

    }

}

function toObj(obj) {
var normalMatrix = new THREE.Matrix3().getNormalMatrix( obj.matrixWorld );
var worldNormal = new THREE.Vector3(0,0,1).applyMatrix3( normalMatrix ).normalize();
var camPosition = new THREE.Vector3().copy(obj.position).add(worldNormal.multiplyScalar(20));

var rotateTween = new TWEEN.Tween(lookAtVector)
    .to({
        x: obj.position.x,
        y: obj.position.y,
        z: obj.position.z
    }, 2000)
    .easing(TWEEN.Easing.Quadratic.InOut)
    .onUpdate(function(){
        camera.lookAt(lookAtVector);
    })
    .onComplete(function(){
        lookAtVector.copy(obj.position);
    })
    .start();

    var goTween = new TWEEN.Tween(camera.position)
    .to(camPosition, 2000)
    .easing(TWEEN.Easing.Quadratic.InOut)
    .start();

}

//

function animate() {

    requestAnimationFrame(animate);

    render();
    stats.update();

}

function render() {
    TWEEN.update();

    camera.updateMatrixWorld();

    // find intersections

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children);

    if (intersects.length > 0) {

        if (INTERSECTED != intersects[0].object) {

            if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);

            INTERSECTED = intersects[0].object;
            INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
            //INTERSECTED.material.emissive.setHex(0xeeeeee);

        }

    } else {

        if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);

        INTERSECTED = null;

    }

    renderer.render(scene, camera);

}

function getRandomMaterial() {
    var lng = materialArray.length;
    var rnd = Math.floor(Math.random() * lng);
    return materialArray[rnd];
}

function loadtextures(){
				for (i = 0; i < 114; i++) {
					console.log('images/image'+i+'.jpg');
				var texture = new THREE.TextureLoader().load( 'images/image'+i+'.jpg' );
				texture.wrapS = THREE.RepeatWrapping;
				texture.wrapT = THREE.RepeatWrapping;

		// how many times to repeat in each direction; the default is (1,1),
		//   which is probably why your example wasn't working
		texture.repeat.set( 1, 1 );
				texturearray.push(texture);
				}

			}

		</script>
</body>
</html>


text:
import logging
import os, sys, time, socket
import docker

def setupLogging():
  log = logging.getLogger('maestro')
  if not len(log.handlers):
    log.setLevel(logging.DEBUG)

    formatter = logging.Formatter("%(asctime)s %(levelname)-10s %(message)s")
    filehandler = logging.FileHandler('maestro.log')
    filehandler.setLevel(logging.DEBUG)
    filehandler.setFormatter(formatter)
    log.addHandler(filehandler)
  return log

quiet=False
def setQuiet(state=True):
  global quiet
  quiet = state

# Display the status
def status(string):
  global quiet
  log = logging.getLogger('maestro')
  log.info(string)

  if not quiet:
    print string

def order(raw_list):
  def _process(wait_list):
    new_wait = []
    for item in wait_list:
      match = False
      for dependency in raw_list[item]['require']:
        if dependency in ordered_list:
          match = True
        else:
          match = False
          break

      if match:
        ordered_list.append(item)
      else:
        new_wait.append(item)

    if len(new_wait) > 0:
      # Guard against circular dependencies
      if len(new_wait) == len(wait_list):
        raise Exception("Unable to satisfy the require for: " + item)

      # Do it again for any remaining items
      _process(new_wait)

  ordered_list = []
  wait_list = []
  # Start by building up the list of items that do not have any dependencies
  for item in raw_list:
    if 'require' not in raw_list[item]:
      ordered_list.append(item)
    else:
      wait_list.append(item)

  # Then recursively order the items that do define dependencies
  _process(wait_list)

  return ordered_list

def waitForService(ip, port, retries=60):
  while retries >= 0:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((ip, port))
        s.close()
        break
    except:
      time.sleep(0.5)
      retries = retries - 1
      continue

  return retries

def findImage(name, tag="latest"):
  result =  docker.Client().images(name=name)

  for image in result:
    if image['Tag'] == tag:
      return image['Id']
  return None


text:
<?php

namespace PragmaRX\Sdk\Services\Tags\Events;

class UserWasInvited {

	public $user;

	function __construct($user)
	{
		$this->user = $user;
	}

}


text:
/*
 * The IPv4 and IPv6 map types are basically identical, except for the
 * names of the functions, and the size of the values that are being
 * stored.  Rather than having two mostly duplicate definitions of each
 * function, we define "template functions" where anything that depends
 * on the size of the IP address is defined using the following macros.
 */

/* The name of the cork_ipvX type. */
#define CORK_IP  struct cork_ipv4

/* The number of bits in an IPvX address. */
#define IP_BIT_SIZE  32

/* The value of the discriminator variable for an IPvX address. */
#define IP_DISCRIMINATOR_VALUE  true

/* Creates a identifier of the form "ipset_ipv4_<basename>". */
#define IPSET_NAME(basename) ipset_ipv4_##basename

/* Creates a identifier of the form "ipmap_ipv4_<basename>". */
#define IPMAP_NAME(basename) ipmap_ipv4_##basename

/* Now include all of the templates. */
#include "inspection-template.c.in"