text:
<?php

declare(strict_types=1);

namespace Phpml\Tests\DimensionReduction;

use Phpml\DimensionReduction\PCA;
use Phpml\Exception\InvalidArgumentException;
use Phpml\Exception\InvalidOperationException;
use PHPUnit\Framework\TestCase;

class PCATest extends TestCase
{
    public function testPCA(): void
    {
        // Acceptable error
        $epsilon = 0.001;

        // First a simple example whose result is known and given in
        // http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf
        $data = [
            [2.5, 2.4],
            [0.5, 0.7],
            [2.2, 2.9],
            [1.9, 2.2],
            [3.1, 3.0],
            [2.3, 2.7],
            [2.0, 1.6],
            [1.0, 1.1],
            [1.5, 1.6],
            [1.1, 0.9],
        ];
        $transformed = [
            [-0.827970186], [1.77758033], [-0.992197494],
            [-0.274210416], [-1.67580142], [-0.912949103], [0.0991094375],
            [1.14457216], [0.438046137], [1.22382056], ];

        $pca = new PCA(0.90);
        $reducedData = $pca->fit($data);

        // Due to the fact that the sign of values can be flipped
        // during the calculation of eigenValues, we have to compare
        // absolute value of the values
        array_map(function ($val1, $val2) use ($epsilon): void {
            self::assertEqualsWithDelta(abs($val1[0]), abs($val2[0]), $epsilon);
        }, $transformed, $reducedData);

        // Test fitted PCA object to transform an arbitrary sample of the
        // same dimensionality with the original dataset
        foreach ($data as $i => $row) {
            $newRow = [[$transformed[$i]]];
            $newRow2 = $pca->transform($row);

            array_map(function ($val1, $val2) use ($epsilon): void {
                self::assertEqualsWithDelta(abs($val1[0][0]), abs($val2[0]), $epsilon);
            }, $newRow, $newRow2);
        }
    }

    public function testPCAThrowWhenTotalVarianceOutOfRange(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Total variance can be a value between 0.1 and 0.99');
        new PCA(0., null);
    }

    public function testPCAThrowWhenNumFeaturesOutOfRange(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Number of features to be preserved should be greater than 0');
        new PCA(null, 0);
    }

    public function testPCAThrowWhenParameterNotSpecified(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Either totalVariance or numFeatures should be specified in order to run the algorithm');
        new PCA();
    }

    public function testPCAThrowWhenBothParameterSpecified(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Either totalVariance or numFeatures should be specified in order to run the algorithm');
        new PCA(0.9, 1);
    }

    public function testTransformThrowWhenNotFitted(): void
    {
        $samples = [
            [1, 0],
            [1, 1],
        ];

        $pca = new PCA(0.9);

        $this->expectException(InvalidOperationException::class);
        $this->expectExceptionMessage('PCA has not been fitted with respect to original dataset, please run PCA::fit() first');
        $pca->transform($samples);
    }
}


text:
package com.amazonaws.services.snowball.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAddressesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The number of ADDRESS objects to return.
     *

     */
    private Integer maxResults;
    /**
     *

     * HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS objects,
     * you have the option of specifying a value for NextToken as the starting point for your list of
     * returned addresses.
     *

     */
    private String nextToken;

    /**
     *

     * The number of ADDRESS objects to return.
     *

     *
     * @param maxResults
     *        The number of ADDRESS objects to return.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The number of ADDRESS objects to return.
     *

     *
     * @return The number of ADDRESS objects to return.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The number of ADDRESS objects to return.
     *

     *
     * @param maxResults
     *        The number of ADDRESS objects to return.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAddressesRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS objects,
     * you have the option of specifying a value for NextToken as the starting point for your list of
     * returned addresses.
     *

     *
     * @param nextToken
     *        HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS
     *        objects, you have the option of specifying a value for NextToken as the starting point for
     *        your list of returned addresses.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS objects,
     * you have the option of specifying a value for NextToken as the starting point for your list of
     * returned addresses.
     *

     *
     * @return HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS
     *         objects, you have the option of specifying a value for NextToken as the starting point for
     *         your list of returned addresses.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS objects,
     * you have the option of specifying a value for NextToken as the starting point for your list of
     * returned addresses.
     *

     *
     * @param nextToken
     *        HTTP requests are stateless. To identify what object comes "next" in the list of ADDRESS
     *        objects, you have the option of specifying a value for NextToken as the starting point for
     *        your list of returned addresses.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeAddressesRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeAddressesRequest == false)
            return false;
        DescribeAddressesRequest other = (DescribeAddressesRequest) obj;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeAddressesRequest clone() {
        return (DescribeAddressesRequest) super.clone();
    }

}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

import logging
import inspect
from functools import wraps

import six
from fluent import event
from raven import Client

from scrapi import settings

logger = logging.getLogger(__name__)
sentry = Client(dsn=settings.SENTRY_DSN)

if not settings.USE_FLUENTD:
    logger.warning('USE_FLUENTD is set to False; logs will not be stored')

# Events
PROCESSING = 'processing'
HARVESTER_RUN = 'runHarvester'
CHECK_ARCHIVE = 'checkArchive'
NORMALIZATION = 'normalization'

# statuses
FAILED = 'failed'
SKIPPED = 'skipped'
CREATED = 'created'
STARTED = 'started'
COMPLETED = 'completed'

def log_to_sentry(message, **kwargs):
    if not settings.SENTRY_DSN:
        return logger.warn('send_to_raven called with no SENTRY_DSN')
    return sentry.captureMessage(message, extra=kwargs)

class Skip(Exception):
    pass

def serialize_fluent_data(data):
    if isinstance(data, dict):
        return {
            key: serialize_fluent_data(val)
            for key, val in data.items()
        }
    elif isinstance(data, list):
        return [
            serialize_fluent_data(item)
            for item in data
        ]
    elif isinstance(data, six.string_types):
        return data
    else:
        return repr(data)

# Ues _index here as to not clutter the namespace for kwargs
def dispatch(_event, status, _index=None, **kwargs):
    if not settings.USE_FLUENTD:
        return

    evnt = {
        'event': _event,
        'status': status
    }

    evnt.update(serialize_fluent_data(kwargs))

    if _index:
        _event = '{}.{}'.format(_event, _index)

    logger.debug('[{}][{}]{!r}'.format(_event, status, kwargs))
    event.Event(_event, evnt)

def logged(event, index=None):
    def _logged(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            context = extract_context(func, *args, **kwargs)
            dispatch(event, STARTED, _index=index, **context)
            try:
                res = func(*args, **kwargs)
            except Skip as e:
                # args[0] instead of message for Py3
                dispatch(event, SKIPPED, _index=index, reason=e.args[0], **context)
                return None
            except Exception as e:
                if settings.SENTRY_DSN:
                    sentry.captureException()
                dispatch(event, FAILED, _index=index, exception=e, **context)
                raise
            else:
                dispatch(event, COMPLETED, _index=index, **context)
            return res
        return wrapped
    return _logged

def extract_context(func, *args, **kwargs):
    arginfo = inspect.getargspec(func)
    arg_names = arginfo.args
    defaults = {
        arg_names.pop(-1): kwarg
        for kwarg in (arginfo.defaults or [])
    }

    computed_args = list(zip(arg_names, args))
    if arginfo.varargs:
        computed_args.append(('args', list(args[len(arg_names):])))

    if kwargs:
        defaults['kwargs'] = kwargs

    return dict(computed_args, **defaults)

def creates_task(event):
    def _creates_task(func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            res = func(*args, **kwargs)
            dispatch(event, CREATED, **extract_context(func, *args, **kwargs))
            return res
        return wrapped
    return _creates_task


text:
package io.rdbc.tck

import io.rdbc.sapi._
import io.rdbc.sapi.exceptions.ConversionException

trait ForValueSpec
  extends RdbcSpec
    with TableSpec
    with TxSpec {

  protected def intDataTypeName: String

  //TODO if any test fails next tests fail too - fix this
  "Value returning feature should" - {
    "return None on empty tables" - {
      withAndWithoutTx(s"col $intDataTypeName") { (c, t) =>
        val stmt = c.statement(sql"select col from #$t")
        stmt.executeForValue(_.int("col")).get shouldBe None
      }
    }

    "return value from first row on non-empty tables" - {
      withAndWithoutTx(s"col $intDataTypeName") { (c, t) =>
        val range = 1 to 10
        for {i <- range} yield {
          c.statement(sql"insert into #$t(col) values ($i)").execute().get
        }
        val stmt = c.statement(sql"select col from #$t where col >= 5 order by col")
        stmt.executeForValue(_.int("col")).get should contain(5)
      }
    }

    "throw an exception when non null-safe getter is used" - {
      withAndWithoutTx(s"col $intDataTypeName") { (c, t) =>
        c.statement(sql"insert into #$t(col) values (null)").execute().get
        val stmt = c.statement(sql"select col from #$t")
        val e = intercept[ConversionException] {
          stmt.executeForValue(_.int("col")).get
        }
        e.value shouldBe None
        e.targetType shouldBe classOf[Int]
      }
    }
  }

  //TODO tests for "connection should be in idle state when any method's future completes"

}


text:
    <img src="<?php echo DIR."/".$avatar->GETsAvatar($session); ?>" alt="">
    @<?php echo $universal->getUsernameFromSession(); ?>

      Username
      <input type="text" name="edit_un_text" value="<?php echo $universal->GETsDetails($session, "username"); ?>" class="edit_un_text" placeholder="Username" spellcheck="false" autofocus>

	  Steemit Username
	  <input type="text" name="edit_steem_un_text" value="<?php echo $universal->GETsDetails($session, "steemitusername"); ?>" class="edit_steem_un_text" placeholder="@username" spellcheck="false" autofocus>

      Firstname
      <input type="text" name="edit_fn_text" value="<?php echo $universal->GETsDetails($session, "firstname"); ?>" class="edit_fn_text" placeholder="Firstname" spellcheck="false">

      Surname
      <input type="text" name="edit_sn_text" value="<?php echo $universal->GETsDetails($session, "surname"); ?>" class="edit_sn_text" placeholder="Surname" spellcheck="false">

      Bio
      <textarea name="edit_ta" class="edit_ta" placeholder="Bio" spellcheck="false"><?php echo $universal->GETsDetails($session, "bio"); ?></textarea>

      sentiment_very_satisfied
      Update profile
      <?php
        if(!$universal->e_verified($_SESSION['id'])){
          echo "Resend verification link";
        }
      ?>

      Connections
      <input type="text" name="edit_em_instagram" value="<?php echo $universal->GETsDetails($session, "instagram"); ?>" class="edit_em_instagram sm" placeholder="Instagram" spellcheck="false">
      <input type="text" name="edit_em_youtube" value="<?php echo $universal->GETsDetails($session, "youtube"); ?>" class="edit_em_youtube sm" placeholder="Youtube" spellcheck="false">
      <input type="text" name="edit_em_facebook" value="<?php echo $universal->GETsDetails($session, "facebook"); ?>" class="edit_em_facebook sm" placeholder="Facebook" spellcheck="false">
      <input type="text" name="edit_em_twitter" value="<?php echo $universal->GETsDetails($session, "twitter"); ?>" class="edit_em_twitter sm" placeholder="Twitter" spellcheck="false">
      <input type="text" name="edit_em_website" value="<?php echo $universal->GETsDetails($session, "website"); ?>" class="edit_em_website sm" placeholder="Website" spellcheck="false">
      <input type="text" name="edit_em_mobile" value="<?php echo $universal->GETsDetails($session, "mobile"); ?>" class="edit_em_mobile" placeholder="Phone Number" spellcheck="false">

      Edit tags (click tags to remove)
      <input type="hidden" class="tags_hidden" name="tags_hidden" value="">

      <input type="text" name="add_tag_text" value="" class="add_tag_text" placeholder="Add a tag" spellcheck="false">
      Add

      <?php $tags->getTagsEdit($session); ?>


text:
package de.mpicbg.knime.hcs.base.nodes.norm;

import org.knime.core.node.NodeDialogPane;
import org.knime.core.node.NodeFactory;
import org.knime.core.node.NodeView;
import org.knime.core.node.defaultnodesettings.DialogComponentBoolean;
import org.knime.core.node.defaultnodesettings.DialogComponentStringSelection;

import java.util.Arrays;

import static de.mpicbg.knime.hcs.base.nodes.norm.AbstractScreenTrafoModel.*;

/**
 * Document me!
 *
 * @author Holger Brandl
 */
public class NPINormalizerFactory extends NodeFactory<NPINormalizer> {

    @Override
    public NPINormalizer createNodeModel() {
        return new NPINormalizer();
    }

    @Override
    public int getNrNodeViews() {
        return 0;
    }

    @Override
    public NodeView<NPINormalizer> createNodeView(final int viewIndex, final NPINormalizer nodeModel) {
        return null;
    }

    @Override
    public boolean hasDialog() {
        return true;
    }

    @Override
    public NodeDialogPane createNodeDialogPane() {
        return new AbstractScreenTrafoDialog() {

            private DialogComponentStringSelection posCtrlProperty;
            private DialogComponentStringSelection negCtrlProperty;

            @Override
            protected void createControls() {
                super.createControls();

                posCtrlProperty = new DialogComponentStringSelection(createTreatmentSelector(TREATMENT_POS_CONTROL),
                        "Positive Control", Arrays.asList(SELECT_TREATMENT_ADVICE), true);

                negCtrlProperty = new DialogComponentStringSelection(createTreatmentSelector(TREATMENT_NEG_CONTROL),
                        "Negative Control", Arrays.asList(SELECT_TREATMENT_ADVICE), true);

                // setup the treatment-attribute selector
                setupControlAttributeSelector(this, Arrays.asList(posCtrlProperty, negCtrlProperty));

                addDialogComponent(posCtrlProperty);
                addDialogComponent(negCtrlProperty);
                addDialogComponent(new DialogComponentBoolean(createPropRobustStats(), ROBUST_STATS_PROPERTY_DESCS));
            }
        };
    }
}


text:
Repo to hold all "This Week In Erlang" posts:

<https://gootik.github.io/this-week-in-erlang/>


text:
..
      Copyright 2015 Mirantis Inc. All Rights Reserved.

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          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.

.. _tutorial_step_3_benchmarking_with_existing_users:

Step 3. Benchmarking OpenStack with existing users
==================================================

.. contents::
   :local:

Motivation
----------

There are two very important reasons from the production world of why it is preferable to use some already existing users to benchmark your OpenStack cloud:

1. *Read-only Keystone Backends:* creating temporary users for benchmark scenarios in Rally is just impossible in case of r/o Keystone backends like *LDAP* and *AD*.

2. *Safety:* Rally can be run from an isolated group of users, and if something goes wrong, this won't affect the rest of the cloud users.

Registering existing users in Rally
-----------------------------------

The information about existing users in your OpenStack cloud should be passed to Rally at the :ref:`deployment initialization step <tutorial_step_1_setting_up_env_and_running_benchmark_from_samples>`. You have to use the **ExistingCloud** deployment plugin that just provides Rally with credentials of an already existing cloud. The difference from the deployment configuration we've seen previously is that you should set up the *"users"* section with the credentials of already existing users. Let's call this deployment configuration file *existing_users.json*:

.. code-block:: none

    {
        "type": "ExistingCloud",
        "auth_url": "http://example.net:5000/v2.0/",
        "region_name": "RegionOne",
        "endpoint_type": "public",
        "admin": {
            "username": "admin",
            "password": "pa55word",
            "tenant_name": "demo"
        },
        "users": [
            {
                "username": "b1",
                "password": "1234",
                "tenant_name": "testing"
            },
            {
                "username": "b2",
                "password": "1234",
                "tenant_name": "testing"
            }
        ]
    }

This deployment configuration requires some basic information about the OpenStack cloud like the region name, auth url. admin user credentials, and any amount of users already existing in the system. Rally will use their credentials to generate load in against this deployment as soon as we register it as usual:

.. code-block:: none

    $ rally deployment create --file existings_users --name our_cloud
    +--------------------------------------+----------------------------+-----------+------------------+--------+
    | uuid                                 | created_at                 | name      | status           | active |
    +--------------------------------------+----------------------------+-----------+------------------+--------+
    | 1849a9bf-4b18-4fd5-89f0-ddcc56eae4c9 | 2015-03-28 02:43:27.759702 | our_cloud | deploy->finished |        |
    +--------------------------------------+----------------------------+-----------+------------------+--------+
    Using deployment: 1849a9bf-4b18-4fd5-89f0-ddcc56eae4c9
    ~/.rally/openrc was updated

After that, the **rally show** command lists the resources for each user separately:

.. code-block:: none

    $ rally show images

    Images for user `admin` in tenant `admin`:
    +--------------------------------------+---------------------------------+-----------+
    | UUID                                 | Name                            | Size (B)  |
    +--------------------------------------+---------------------------------+-----------+
    | 041cfd70-0e90-4ed6-8c0c-ad9c12a94191 | cirros-0.3.4-x86_64-uec         | 25165824  |
    | 87710f09-3625-4496-9d18-e20e34906b72 | Fedora-x86_64-20-20140618-sda   | 209649664 |
    | b0f269be-4859-48e0-a0ca-03fb80d14602 | cirros-0.3.4-x86_64-uec-ramdisk | 3740163   |
    | d82eaf7a-ff63-4826-9aa7-5fa105610e01 | cirros-0.3.4-x86_64-uec-kernel  | 4979632   |
    +--------------------------------------+---------------------------------+-----------+

    Images for user `b1` in tenant `testing`:
    +--------------------------------------+---------------------------------+-----------+
    | UUID                                 | Name                            | Size (B)  |
    +--------------------------------------+---------------------------------+-----------+
    | 041cfd70-0e90-4ed6-8c0c-ad9c12a94191 | cirros-0.3.4-x86_64-uec         | 25165824  |
    | 87710f09-3625-4496-9d18-e20e34906b72 | Fedora-x86_64-20-20140618-sda   | 209649664 |
    | b0f269be-4859-48e0-a0ca-03fb80d14602 | cirros-0.3.4-x86_64-uec-ramdisk | 3740163   |
    | d82eaf7a-ff63-4826-9aa7-5fa105610e01 | cirros-0.3.4-x86_64-uec-kernel  | 4979632   |
    +--------------------------------------+---------------------------------+-----------+

    Images for user `b2` in tenant `testing`:
    +--------------------------------------+---------------------------------+-----------+
    | UUID                                 | Name                            | Size (B)  |
    +--------------------------------------+---------------------------------+-----------+
    | 041cfd70-0e90-4ed6-8c0c-ad9c12a94191 | cirros-0.3.4-x86_64-uec         | 25165824  |
    | 87710f09-3625-4496-9d18-e20e34906b72 | Fedora-x86_64-20-20140618-sda   | 209649664 |
    | b0f269be-4859-48e0-a0ca-03fb80d14602 | cirros-0.3.4-x86_64-uec-ramdisk | 3740163   |
    | d82eaf7a-ff63-4826-9aa7-5fa105610e01 | cirros-0.3.4-x86_64-uec-kernel  | 4979632   |
    +--------------------------------------+---------------------------------+-----------+

With this new deployment being active, Rally will use the already existing users *"b1"* and *"b2"* instead of creating the temporary ones when launching benchmark task that do not specify the *"users"* context.

Running benchmark scenarios with existing users
-----------------------------------------------

After you have registered a deployment with existing users, don't forget to remove the *"users"* context from your benchmark task configuration if you want to use existing users, like in the following configuration file (*boot-and-delete.json*):

.. code-block:: none

    {
        "NovaServers.boot_and_delete_server": [
            {
                "args": {
                    "flavor": {
                        "name": "m1.nano"
                    },
                    "image": {
                        "name": "^cirros.*uec$"
                    },
                    "force_delete": false
                },
                "runner": {
                    "type": "constant",
                    "times": 10,
                    "concurrency": 2
                },
                "context": {}
            }
        ]
    }

When you start this task, it will use the existing users *"b1"* and *"b2"* instead of creating the temporary ones:

.. code-block:: none

    $ rally task start samples/tasks/scenarios/nova/boot-and-delete.json
    ...

It goes without saying that support of benchmarking with predefined users simplifies the usage of Rally for generating loads against production clouds.

(based on: http://boris-42.me/rally-can-generate-load-with-passed-users-now/)


text:
function basisobj = create_easy_basis(rangeval, nresol, periodic, nderiv)
%CREATE_EASY_BASIS sets up a simple basis.
%  If argument PERIODIC is nonzero, the basis is of type 'fourier',
%  else it is of type 'bspline'.
%  Argument RANGEVAL determines the range of argument values.  If
%  the basis type is 'fourier', this also determines the period.
%  The number of basis functions is jointly determined by arguments
%  NRESOL and NDERIV.
%  This function is identical to MAKE_BASIS.
%
%  Arguments are as follows:
%
%  RANGEVAL ... A vector of length 2 giving the lower and upper limits
%               on argument values, respectively.
%  NRESOL   ... The resolution required in the functions.  This means
%               the maximum number of features or events that could in
%               principle be represented in each observation.  Features
%               are things like peaks, valleys, zero crossing, or plateaus.
%               The width of a single feature may naturally not be less than
%               the minimum difference between two successive argument values.
%               Roughly speaking, NRESOL is the width of the interval in
%               RANGEVAL divided by the width of the narrowest feature that
%               requires representation.  NRESOL cannot logically exceed
%               the number N of argument values, and for noisy data it should
%               be considerably less.
%  PERIODIC ... Is 0 if the functions are not periodic, and nonzero otherwise.
%               It is set to 0 by default.
%  NDERIV   ... The highest order of derivative that is needed for the
%               functional data object.  This is set to 2 by default.
%
%  Another option for a simple basis may be the polygonal basis of type 'polyg'
%    made by function CREATE_POLYGONAL_BASIS.  Only use this option if no
%    derivatives will be required.
%
%  last modified 30 January 2003

%  check RANGEVAL

if length(rangeval) == 1
    if rangeval <= 0
        error('RANGEVAL a single value that is not postive.');
    end
    rangeval = [0,rangeval];
end

if rangechk(rangeval) ~= 1
    error('RANGEVAL is not a legitimate range.');
end

%  set default values

if nargin < 4,  nderiv = 2;    end
if nargin < 3,  periodic = 0;  end

%  check NRESOL

if nargin < 2,
    error('Argument NRESOL must be supplied.');
end
nresol = floor(nresol);
if nresol < 0
   error('Argument NRESOL must be nonnegative.');
end

width = rangeval(2) - rangeval(1);
if  width <= 0
   error('Values in argument RANGEVAL must be strictly increasing.');
end

if periodic
   %  periodic basis
   nbasis   = nresol;
   basisobj = create_fourier_basis(rangeval, nbasis, width);
else
   %  B-spline basis
   nbasis   = nresol + nderiv + 4;
   basisobj = create_bspline_basis(rangeval, nbasis);
end


text:
import socket
import time

def write_html(andyshere):
	f = open('andy.html', 'w')
	f.write("<!DOCTYPE html><title>Andy Probe</title>")
	f.write("Andy is in Glennan!" if andyshere else  "Andy is not in Glennan (or avoiding my detection)")
	f.write("")
	f.close()

while True:
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

	sock.settimeout(1.0)

	print "Probing Andy..."
	write_html(sock.connect_ex(("129.22.158.148", 80)) == 0)

	sock.close()

	time.sleep(30)


text:
{% extends 'base.html' %}

{% block title %}Stock Out list{% endblock %}

{% block content %}

            Product Name
            Product Buying Price
            Product Selling Price
            Product Available unit
            Product Out Unit
            Stock Out Date

        {% for items in lists %}

            {{ items.product_info.product_name }}
            {{ items.product_info.product_price }}
            {{ items.product_sell_price }}
            {{ items.product_info.product_unit }}
            {{ items.product_sell_unit }}
            {{ items.stockout_date }}

        {% endfor %}

{% endblock %}


text:
@interface RCShortVideoMessage : RCMessageContent
@property (nonatomic, strong) NSString *cover;
@property (nonatomic, strong) NSString *url;
@end


text:
FIND_PROGRAM(MAN_EXE
             NAMES man
             PATHS /bin
                   /usr/bin
                   /usr/local/bin)
IF(MAN_EXE)
 SET(MAN_FOUND YES)
ELSE(MAN_EXE)
# MESSAGE(WARNING "Unable to find 'man' program.MAN pages not installed")
 SET(MAN_FOUND NO)
ENDIF(MAN_EXE)


text:
require 'librarian/dependency'

module Librarian
  class Resolver
    class Implementation

      class MultiSource
        attr_accessor :sources
        def initialize(sources)
          self.sources = sources
        end
        def manifests(name)
          sources.reverse.map{|source| source.manifests(name)}.flatten(1)
        end
      end

      attr_reader :resolver, :spec, :dependency_source_map

      def initialize(resolver, spec)
        @resolver = resolver
        @spec = spec
        @dependency_source_map = Hash[spec.dependencies.map{|d| [d.name, d.source]}]
        @level = 0
      end

      def resolve(dependencies, manifests = {})
        dependencies += manifests.values.map { |m|
          m.dependencies.map { |d| sourced_dependency_for(d) }
        }.flatten(1)
        resolution = recursive_resolve([], manifests, dependencies)
        resolution ? resolution[1] : nil
      end

      def default_source
        MultiSource.new(spec.sources)
      end

      def sourced_dependency_for(dependency)
        return dependency if dependency.source

        source = dependency_source_map[dependency.name] || default_source
        Dependency.new(dependency.name, dependency.requirement, source)
      end

      def recursive_resolve(dependencies, manifests, queue)
        if dependencies.empty?
          queue.each do |dependency|
            debug { "Scheduling #{dependency}" }
          end
        end
        failure = false
        until failure || queue.empty?
          dependency = queue.shift
          dependencies << dependency
          debug { "Resolving #{dependency}" }
          scope do
            if manifests.key?(dependency.name)
              unless dependency.satisfied_by?(manifests[dependency.name])
                debug { "Conflicts with #{manifests[dependency.name]}" }
                failure = true
              else
                debug { "Accords with all prior constraints" }
                # nothing left to do
              end
            else
              debug { "No known prior constraints" }
              resolution = nil
              related_dependencies = dependencies.select{|d| d.name == dependency.name}
              unless dependency.manifests && dependency.manifests.first
                debug { "No known manifests" }
              else
                debug { "Checking manifests" }
                scope do
                  dependency.manifests.each do |manifest|
                    break if resolution

                    debug { "Checking #{manifest}" }
                    scope do
                      if related_dependencies.all?{|d| d.satisfied_by?(manifest)}
                        m = manifests.merge(dependency.name => manifest)
                        a = manifest.dependencies.map { |d| sourced_dependency_for(d) }
                        a.each do |d|
                          debug { "Scheduling #{d}" }
                        end
                        q = queue + a
                        resolution = recursive_resolve(dependencies.dup, m, q)
                      end
                      if resolution
                        debug { "Resolved #{dependency} at #{manifest}" }
                      else
                        debug { "Backtracking from #{manifest}" }
                      end
                    end
                  end
                end
                if resolution
                  debug { "Resolved #{dependency}" }
                else
                  debug { "Failed to resolve #{dependency}" }
                end
              end
              unless resolution
                failure = true
              else
                dependencies, manifests, queue = *resolution
              end
            end
          end
        end
        failure ? nil : [dependencies, manifests, queue]
      end

    private

      def scope
        @level += 1
        yield
      ensure
        @level -= 1
      end

      def debug
        environment.logger.debug { '  ' * @level + yield }
      end

      def environment
        resolver.environment
      end

    end
  end
end


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

		<item value="-522" key="DIALOG_X_ORIGIN"/>
		<item value="470" key="DIALOG_Y_ORIGIN"/>

		<item value="900" key="dialogHeight"/>
		<item value="1600" key="dialogWidth"/>
		<list key="textEntries">
		</list>
		<list key="orderedElements">
		</list>
		<list key="orderedProviders">
		</list>
		<list key="textArray">
		</list>

		<item value="/Users/Yogurt/Downloads/Eclipse preferences.epf" key=""/>
		<list key="WizardPreferencesExportPage1.STORE_DESTINATION_NAMES_ID">
			<item value="/Users/Yogurt/Downloads/Eclipse preferences.epf"/>
			<item value="/Users/Yogurt/Downloads/Retta-2.jar"/>
			<item value="/Users/Yogurt/Downloads/theme-1004.epf"/>
			<item value="/Users/Yogurt/Downloads/theme-1004.xml"/>
		</list>

		<item value="org.eclipse.wb.swing.JFrame" key="NewWizardSelectionPage.STORE_SELECTED_ID"/>
		<list key="NewWizardSelectionPage.STORE_EXPANDED_CATEGORIES_ID">
			<item value="org.eclipse.wb"/>
		</list>

		<item value="702" key="DIALOG_WIDTH"/>
		<item value="1|.SF NS Text|11.0|0|COCOA|1|.SFNSText-Regular" key="DIALOG_FONT_NAME"/>
		<item value="652" key="DIALOG_HEIGHT"/>
		<item value="84" key="DIALOG_X_ORIGIN"/>
		<item value="-107" key="DIALOG_Y_ORIGIN"/>

		<item value="org.eclipse.ui.wizards.export.Preferences" key="ImportExportPage.STORE_SELECTED_EXPORT_WIZARD_ID"/>
		<item value="org.eclipse.ui.wizards.import.Preferences" key="ImportExportPage.STORE_SELECTED_IMPORT_WIZARD_ID"/>
		<list key="ImportExportPage.STORE_EXPANDED_IMPORT_CATEGORIES">
			<item value="org.eclipse.ui.Basic"/>
			<item value="org.eclipse.buildship.ui.importwizards"/>
			<item value="org.eclipse.equinox.p2.category"/>
			<item value="org.eclipse.m2e"/>
			<item value="org.eclipse.debug.ui"/>
			<item value="org.eclipse.mylyn.tasks.ui.wizards.import.category"/>
			<item value="org.eclipse.team.ui.importWizards"/>
			<item value="org.eclipse.wst.XMLCategory"/>
		</list>
		<list key="ImportExportPage.STORE_EXPANDED_EXPORT_CATEGORIES">
			<item value="org.eclipse.ui.Basic"/>
		</list>

		<item value="/Volumes/Documents/Eclipse Preferences.epf" key=""/>
		<item value="false" key="WizardPreferencesExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID"/>
		<item value="true" key="WizardPreferencesExportPage1.EXPORT_ALL_PREFERENCES_ID"/>
		<list key="WizardPreferencesExportPage1.STORE_DESTINATION_NAMES_ID">
			<item value="/Volumes/Documents/Eclipse Preferences.epf"/>
		</list>


text:
module MatrixProject
  VERSION = "0.0.1"
end


text:
#include "Core/Memory.h"

FLinearMemDevice::FLinearMemDevice()
{
	//Stack size equals the page size
	SYSTEM_INFO SysInfo = { 0 };
	GetSystemInfo( &SysInfo );
	StackSize = SysInfo.dwPageSize;

	Top = VirtualAlloc( NULL, StackSize, MEM_COMMIT, PAGE_READWRITE );
	Marker = 0;

	//Touch the memory
	FillMemory( Top, StackSize, -1 );
}

FLinearMemDevice::~FLinearMemDevice()
{
#if defined (_WIN32)
	VirtualFree( Top, 0, MEM_RELEASE );
#elif defined (__linux__)
	brk( FreeMarks );
#endif
}

void* FLinearMemDevice::Malloc( size_t Size )
{
	if (Size > StackSize) return nullptr;
	if ((Marker + Size) > StackSize)
	{
		Marker = 0;
		FillMemory( Top, Size, -1 );
	}
	void* R = (char*)Top + Marker;
	Marker += Size;

	return R;
}

void* FLinearMemDevice::Realloc( void* Ptr, size_t Size )
{
	return Ptr; //This function is unneeded with this allocator
}

void FLinearMemDevice::Free( void* Ptr )
{
	//Cannot free memory with this type of allocator
}


text:
package org.wildfly.extras.patch;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;

/**
 * A server instance.
 *
 * @author thomas.diesler@jboss.com
 * @since 10-Jun-2015
 */
public interface Server {

    PatchId SERVER_ID = PatchId.fromString("server");

	/**
	 * Get the server home path
	 * @return The path to the server home
	 */
	Path getServerHome();

	/**
	 * Get the default repository URL
	 * @return The URL for the default repository
	 */
    URL getDefaultRepositoryURL();

    /**
     * Get the audit log
	 * @return A list containing the audit log content
     */
    List<String> getAuditLog();

	/**
	 * Query the list of applied packages
	 * @return A list of applied patches
	 */
	List<PatchId> queryAppliedPatches();

	/**
	 * Query managed server paths
	 * @param pathsPattern The path pattern to query for
	 * @return A list of managed server paths
	 */
    List<ManagedPath> queryManagedPaths(String pathsPattern);

    /**
     * Get the applied package for a given prefix
	 * @param prefix The patch prefix
     * @return package or null
     */
	Patch getPatch(String prefix);

    /**
     * Get the applied package for the given id
	 * @param patchId The patch id
	 * @return The patch
     */
    Patch getPatch(PatchId patchId);

	/**
	 * Apply a smart patch and return the result
	 * @param smartPatch The patch to apply
	 * @param force Whether to force application of the patch
	 * @return The patched that was applied
	 * @throws java.io.IOException If an IO exception occurred
	 */
	Patch applySmartPatch(SmartPatch smartPatch, boolean force) throws IOException;

	/**
	 * Apply cleanup tasks to a server
	 */
	void cleanUp();
}


text:
import React from 'react'
import { render } from '@testing-library/react'
import TypingDots from './TypingDots'

describe('Dots', () => {
  test('Should render dots', () => {
    const { container } = render(<TypingDots />)
    const dots = container.querySelectorAll('.Dot')

    expect(dots.length).toBe(3)
    expect(window.getComputedStyle(dots[0]).animationDelay).toBe('0s')
    expect(window.getComputedStyle(dots[1]).animationDelay).toBe('-1.1s')
    expect(window.getComputedStyle(dots[2]).animationDelay).toBe('-0.9s')
    expect(window.getComputedStyle(dots[0]).opacity).toBe('1')
    expect(window.getComputedStyle(dots[1]).opacity).toBe('0.6')
    expect(window.getComputedStyle(dots[2]).opacity).toBe('0.2')
  })
})


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.

package com.google.api.ads.adwords.jaxws.v201809.cm;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             The result of a call to FeedService#get.
 *
 *
 *
Java class for FeedPage complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="FeedPage">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/cm/v201809}NullStatsPage">
 *       <sequence>
 *         <element name="entries" type="{https://adwords.google.com/api/adwords/cm/v201809}Feed" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FeedPage", propOrder = {
    "entries"
})
public class FeedPage
    extends NullStatsPage
{

    protected List<Feed> entries;

    /**
     * Gets the value of the entries property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the entries property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getEntries().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Feed }
     *
     *
     */
    public List<Feed> getEntries() {
        if (entries == null) {
            entries = new ArrayList<Feed>();
        }
        return this.entries;
    }

}


text:
package org.approvaltests.core;

public interface ApprovalFailureReporter
{
  public void report(String received, String approved);
}


text:
namespace System.Reflection.Metadata.Ecma335
{
    internal enum HeapSizeFlag : byte
    {
        StringHeapLarge = 0x01, // 4 byte uint indexes used for string heap offsets
        GuidHeapLarge = 0x02,   // 4 byte uint indexes used for GUID heap offsets
        BlobHeapLarge = 0x04,   // 4 byte uint indexes used for Blob heap offsets
        EncDeltas = 0x20,       // Indicates only EnC Deltas are present
        DeletedMarks = 0x80,    // Indicates metadata might contain items marked deleted
    }
}


text:
var App = require('app');

App.ReassignMasterController = App.WizardController.extend({

  name: 'reassignMasterController',

  totalSteps: 6,

  /**
   * @type {string}
   */
  displayName: Em.I18n.t('services.reassign.header'),

  /**
   * Used for hiding back button in wizard
   */
  hideBackButton: true,

  /**
   * All wizards data will be stored in this variable
   *
   * cluster - cluster name
   * installOptions - ssh key, repo info, etc.
   * services - services list
   * hosts - list of selected hosts
   * slaveComponentHosts, - info about slave hosts
   * masterComponentHosts - info about master hosts
   * config??? - to be described later
   */
  content: Em.Object.create({
    cluster: null,
    hosts: null,
    installOptions: null,
    services: null,
    slaveComponentHosts: null,
    masterComponentHosts: null,
    serviceConfigProperties: null,
    advancedServiceConfig: null,
    controllerName: 'reassignMasterController',
    serviceName: 'MISC',
    hdfsUser: "hdfs",
    group: "hadoop",
    reassign: null,
    componentsWithManualCommands: ['NAMENODE', 'SECONDARY_NAMENODE', 'OOZIE_SERVER', 'MYSQL_SERVER', 'APP_TIMELINE_SERVER'],
    hasManualSteps: false,
    hasCheckDBStep: false,
    componentsWithCheckDBStep: ['HIVE_METASTORE', 'HIVE_SERVER', 'OOZIE_SERVER'],
    componentsWithoutSecurityConfigs: ['MYSQL_SERVER'],
    componentsToStopAllServices: ['NAMENODE', 'SECONDARY_NAMENODE'],
    reassignComponentsInMM: [],
    configs: null,
    configsAttributes: null
  }),

  /**
   * Wizard properties in local storage, which should be cleaned right after wizard has been finished
   */
  dbPropertiesToClean: [
    'cluster',
    'hosts',
    'installOptions',
    'masterComponentHosts',
    'serviceComponents',
    'masterComponent',
    'currentStep',
    'reassignHosts',
    'tasksStatuses',
    'tasksRequestIds',
    'requestIds'
  ],

  /**
   * Load data for all steps until current step
   */
  loadMap: {
    '1': [
      {
        type: 'sync',
        callback: function () {
          this.loadComponentToReassign();
          this.loadDatabaseType();
          this.loadServiceProperties();
          this.load('cluster');
        }
      }
    ],
    '2': [
      {
        type: 'async',
        callback: function () {
          var self = this,
            dfd = $.Deferred();
          this.loadServicesFromServer();
          this.loadMasterComponentHosts().done(function () {
            self.loadConfirmedHosts();
            dfd.resolve();
          });
          return dfd.promise();
        }
      }
    ],
    '3': [
      {
        type: 'sync',
        callback: function () {
          this.loadReassignHosts();
        }
      }
    ],
    '4': [
      {
        type: 'sync',
        callback: function () {
          this.loadTasksStatuses();
          this.loadTasksRequestIds();
          this.loadRequestIds();
          this.loadReassignComponentsInMM();
          this.loadConfigs();
          this.loadSecureConfigs();
        }
      }
    ],
    '5': [
      {
        type: 'sync',
        callback: function () {
          this.loadComponentDir();
        }
      }
    ]
  },

  serviceToConfigSiteMap: {
    'NAMENODE': ['hdfs-site', 'core-site'],
    'SECONDARY_NAMENODE': ['hdfs-site', 'core-site'],
    'JOBTRACKER': ['mapred-site'],
    'RESOURCEMANAGER': ['yarn-site'],
    'WEBHCAT_SERVER': ['hive-env', 'webhcat-site', 'core-site'],
    'APP_TIMELINE_SERVER': ['yarn-site', 'yarn-env'],
    'OOZIE_SERVER': ['oozie-site', 'core-site', 'oozie-env'],
    'HIVE_SERVER': ['hive-site', 'webhcat-site', 'hive-env', 'core-site'],
    'HIVE_METASTORE': ['hive-site', 'webhcat-site', 'hive-env', 'core-site'],
    'MYSQL_SERVER': ['hive-site'],
    'HISTORYSERVER': ['mapred-site']
  },

  /**
   * Map with lists of related services.
   * Used to define list of services to stop/start.
   */
  relatedServicesMap: {
    'RESOURCEMANAGER': ['YARN', 'MAPREDUCE2', 'TEZ', 'HIVE', 'PIG', 'OOZIE', 'SLIDER', 'SPARK'],
    'APP_TIMELINE_SERVER': ['YARN', 'MAPREDUCE2', 'TEZ', 'HIVE', 'OOZIE', 'SLIDER', 'SPARK'],
    'HISTORYSERVER': ['MAPREDUCE2', 'HIVE', 'PIG', 'OOZIE'],
    'HIVE_SERVER': ['HIVE', 'FALCON', 'ATLAS', 'OOZIE'],
    'HIVE_METASTORE': ['HIVE', 'PIG', 'FALCON', 'ATLAS', 'OOZIE'],
    'WEBHCAT_SERVER': ['HIVE'],
    'OOZIE_SERVER': ['OOZIE', 'FALCON', 'KNOX'],
    'MYSQL_SERVER': ['HIVE', 'OOZIE', 'RANGER', 'RANGER_KMS'],
    'METRICS_COLLECTOR': ['AMBARI_METRICS']
  },

  isComponentWithReconfiguration: function () {
    return this.get('serviceToConfigSiteMap').hasOwnProperty(this.get('content.reassign.component_name'));
  }.property('content.reassign.component_name'),

  addManualSteps: function () {
    var hasManualSteps = this.get('content.componentsWithManualCommands').contains(this.get('content.reassign.component_name'));
    this.set('content.hasManualSteps', hasManualSteps);
    this.set('totalSteps', hasManualSteps ? 6 : 4);
  }.observes('content.reassign.component_name'),

  addCheckDBStep: function () {
    this.set('content.hasCheckDBStep', this.get('content.componentsWithCheckDBStep').contains(this.get('content.reassign.component_name')));
  }.observes('content.reassign.component_name'),

  /**
   * Load tasks statuses for step5 of Reassign Master Wizard to restore installation
   */
  loadTasksStatuses: function () {
    var statuses = App.db.getReassignTasksStatuses();
    this.set('content.tasksStatuses', statuses);
  },

  /**
   * save status of the cluster.
   * @param clusterStatus object with status,requestId fields.
   */
  saveClusterStatus: function (clusterStatus) {
    var oldStatus = this.toObject(this.get('content.cluster'));
    clusterStatus = jQuery.extend(oldStatus, clusterStatus);
    if (clusterStatus.requestId) {
      clusterStatus.requestId.forEach(function (requestId) {
        if (clusterStatus.oldRequestsId.indexOf(requestId) === -1) {
          clusterStatus.oldRequestsId.push(requestId)
        }
      }, this);
    }
    this.set('content.cluster', clusterStatus);
    this.save('cluster');
  },

  /**
   * Save Master Component Hosts data to Main Controller
   * @param stepController App.WizardStep5Controller
   */
  saveMasterComponentHosts: function (stepController) {
    var obj = stepController.get('selectedServicesMasters');

    var masterComponentHosts = [];
    obj.forEach(function (_component) {
      masterComponentHosts.push({
        display_name: _component.get('display_name'),
        component: _component.get('component_name'),
        hostName: _component.get('selectedHost'),
        serviceId: _component.get('serviceId'),
        isInstalled: true
      });
    });
    App.db.setMasterComponentHosts(masterComponentHosts);
    this.set('content.masterComponentHosts', masterComponentHosts);
    this.setDBProperty('masterComponentHosts', masterComponentHosts);
  },

  loadComponentToReassign: function () {
    var masterComponent = App.db.getMasterToReassign();
    if (masterComponent) {
      this.set('content.reassign', masterComponent);
    }
  },

  saveComponentToReassign: function (masterComponent) {
    var component = {
      component_name: masterComponent.get('componentName'),
      display_name: masterComponent.get('displayName'),
      service_id: masterComponent.get('service.serviceName'),
      host_id: masterComponent.get('hostName')
    };
    App.db.setMasterToReassign(component);
  },

  saveTasksStatuses: function (statuses) {
    App.db.setReassignTasksStatuses(statuses);
    this.set('content.tasksStatuses', statuses);
  },

  loadTasksRequestIds: function () {
    var requestIds = App.db.getReassignTasksRequestIds();
    this.set('content.tasksRequestIds', requestIds);
  },

  saveTasksRequestIds: function (requestIds) {
    App.db.setReassignTasksRequestIds(requestIds);
    this.set('content.tasksRequestIds', requestIds);
  },

  loadRequestIds: function () {
    var requestIds = App.db.getReassignMasterWizardRequestIds();
    this.set('content.requestIds', requestIds);
  },

  saveRequestIds: function (requestIds) {
    App.db.setReassignMasterWizardRequestIds(requestIds);
    this.set('content.requestIds', requestIds);
  },

  saveComponentDir: function (componentDir) {
    App.db.setReassignMasterWizardComponentDir(componentDir);
    this.set('content.componentDir', componentDir);
  },

  loadComponentDir: function () {
    var componentDir = App.db.getReassignMasterWizardComponentDir();
    this.set('content.componentDir', componentDir);
  },

  saveReassignHosts: function (reassignHosts) {
    App.db.setReassignMasterWizardReassignHosts(reassignHosts);
    this.set('content.reassignHosts', reassignHosts);
  },

  loadReassignHosts: function () {
    var reassignHosts = App.db.getReassignMasterWizardReassignHosts();
    this.set('content.reassignHosts', reassignHosts);
  },

  saveSecureConfigs: function (secureConfigs) {
    this.setDBProperty('secureConfigs', secureConfigs);
    this.set('content.secureConfigs', secureConfigs);
  },

  loadSecureConfigs: function () {
    var secureConfigs = this.getDBProperty('secureConfigs');
    this.set('content.secureConfigs', secureConfigs);
  },

  saveServiceProperties: function (properties) {
    this.setDBProperty('serviceProperties', properties);
    this.set('content.serviceProperties', properties);
  },

  loadServiceProperties: function () {
    var serviceProperties = this.getDBProperty('serviceProperties');
    this.set('content.serviceProperties', serviceProperties);
  },

  saveConfigs: function (configs, attributes) {
    var configsObject = {
      configs: configs,
      configsAttributes: attributes
    };
    this.setDBProperties(configsObject);
    this.get('content').setProperties(configsObject);
  },

  loadConfigs: function () {
    var configsObject = this.getDBProperties(['configs', 'configsAttributes']);
    this.get('content').setProperties(configsObject);
  },

  saveDatabaseType: function (type) {
    this.setDBProperty('databaseType', type);
    this.set('content.databaseType', type);
  },

  loadDatabaseType: function () {
    var databaseType = this.getDBProperty('databaseType');
    this.set('content.databaseType', databaseType);
    var component = this.get('content.reassign.component_name');

    if (component === 'OOZIE_SERVER') {
      if (this.get('content.hasCheckDBStep') && databaseType && databaseType !== 'derby') {
        // components with manual commands
        var manual = App.router.reassignMasterController.get('content.componentsWithManualCommands').without('OOZIE_SERVER');
        App.router.reassignMasterController.set('content.hasManualSteps', false);
        App.router.reassignMasterController.set('content.componentsWithManualCommands', manual);
        this.set('totalSteps', 4);
      }
    }
  },

  loadReassignComponentsInMM: function () {
    var reassignComponentsInMM = this.getDBProperty('reassignComponentsInMM');
    this.set('content.reassignComponentsInMM', reassignComponentsInMM);
  },

  saveReassignComponentsInMM: function (reassignComponentsInMM) {
    this.setDBProperty('reassignComponentsInMM', reassignComponentsInMM);
    this.set('content.reassignComponentsInMM', reassignComponentsInMM);
  },

  /**
   * Remove all loaded data.
   * Created as copy for App.router.clearAllSteps
   */
  clearAllSteps: function () {
    this.clearInstallOptions();
    // clear temporary information stored during the install
    this.set('content.cluster', this.getCluster());
  },

  setCurrentStep: function (currentStep, completed) {
    this._super(currentStep, completed);
    App.clusterStatus.setClusterStatus({
      clusterName: this.get('content.cluster.name'),
      wizardControllerName: 'reassignMasterController',
      localdb: App.db.data
    });
  },

  getReassignComponentsInMM: function () {
    var hostComponentsInMM = [];
    var sourceHostComponents = App.HostComponent.find().filterProperty('hostName', this.get('content.reassignHosts.source'));
    var reassignComponents = this.get('content.reassign.component_name') === 'NAMENODE' && App.get('isHaEnabled') ? ['NAMENODE', 'ZKFC'] : [this.get('content.reassign.component_name')];
    reassignComponents.forEach(function(hostComponent){
      var componentToReassign = sourceHostComponents.findProperty('componentName', hostComponent);
      if (componentToReassign && !componentToReassign.get('isActive') && componentToReassign.get('workStatus') === 'STARTED') {
        hostComponentsInMM.push(hostComponent);
      }
    });
    return hostComponentsInMM;
  },

  /**
   * Clear all temporary data
   */
  finish: function () {
    this.clearAllSteps();
    this.clearStorageData();
    this.resetDbNamespace();
    App.router.get('updateController').updateAll();
  }

});


text:
@extends(config('laravel-product-module.views.product.layout'))

@section('title')
    {!! lmcTrans('laravel-product-module/admin.product.show') !!}
@endsection

@section('page-title')

        {!! lmcTrans('laravel-product-module/admin.product.show') !!}

            {!! lmcTrans('laravel-product-module/admin.product.show_description', [
                'product' => $product->name_uc_first
            ]) !!}

@endsection

@section('css')
    @parent
    {{-- Profile CSS --}}
    {!! Html::style('vendor/laravel-modules-core/assets/pages/css/profile-2.css') !!}
    {{-- /Profile CSS --}}

    {{-- Select2 --}}
    {!! Html::style('vendor/laravel-modules-core/assets/global/plugins/select2/dist/css/select2.min.css') !!}
    {!! Html::style('vendor/laravel-modules-core/assets/global/plugins/select2/dist/css/select2-bootstrap.min.css') !!}
    {{-- /Select2 --}}

    {{-- jCrop Image Crop Extension --}}
    {!! Html::style('vendor/laravel-modules-core/assets/global/plugins/jcrop/css/jquery.Jcrop.min.css') !!}
    {!! Html::style('vendor/laravel-modules-core/assets/pages/css/image-crop.css') !!}
    {!! Html::style('vendor/laravel-modules-core/assets/global/plugins/bootstrap-fileinput/css/fileinput.min.css') !!}
    {{-- /jCrop Image Crop Extension --}}
@endsection

@section('script')
    @parent

@endsection

@section('content')
    {{-- Portlet --}}

is_publish ? 'success' : 'danger' }} uppercase">

            {{ $product->is_publish ? trans('laravel-modules-core::admin.ops.published') : trans('laravel-modules-core::admin.ops.not_published') }}

        {{-- Portlet Title --}}

            {{-- Caption --}}

                    {!! lmcTrans('laravel-product-module/admin.product.show') !!}

            {{-- /Caption --}}

            {{-- Actions --}}

                {!! getOps($product, 'show', true) !!}

            {{-- /Actions --}}

        {{-- /Portlet Title --}}

        {{-- Portlet Body --}}

            {{-- Error Messages --}}
            @include('laravel-modules-core::partials.error_message')
            {{-- /Error Messages --}}

                {{-- Profile Navigation --}}

                        @if( ! is_null($product->mainPhoto))

                            {!! $product->mainPhoto->getPhoto([
                                'class' => 'img-responsive pic-bordered',
                                'alt'   => $product->name_uc_first,
                            ], last(array_keys(config('laravel-product-module.product.uploads.photo.thumbnails'))),false,'product','product_id') !!}

                        @endif

                                {!! trans('laravel-modules-core::admin.fields.overview') !!}

                                {!! trans('laravel-modules-core::admin.fields.detail') !!}

                                {!! trans('laravel-modules-core::admin.fields.descriptions') !!}

                                {!! trans('laravel-modules-core::admin.fields.seo') !!}

                        @if (hasPermission('admin.'. (isset($product_category) ? 'product_category.product' : 'product') .'.update'))

                                {!! trans('laravel-modules-core::admin.fields.edit_info') !!}

                                {!! trans('laravel-modules-core::admin.fields.change_descriptions') !!}

                                {!! trans('laravel-modules-core::admin.fields.change_seo') !!}

                        @endif

                {{-- /Profile Navigation --}}

                {{-- Profile Content --}}

                        {{-- Overview --}}

                                @include('laravel-modules-core::product.partials.overview')

                        {{-- /Overview --}}

                        {{-- Detail --}}

                                @include('laravel-modules-core::product.partials.detail')

                        {{-- /Detail --}}

                        {{-- Descriptions --}}

                            @include('laravel-modules-core::product.partials.descriptions')

                        {{-- /Descriptions --}}

                        {{-- Seo --}}

                                @include('laravel-modules-core::product.partials.seo')

                        {{-- /Seo --}}

                        {{-- Edit Info --}}
                        @if (hasPermission('admin.'. (isset($product_category) ? 'product_category.product' : 'product') .'.update'))

                        {{-- Edit Info --}}

                            {!! Form::open([
                                'method'    => 'PATCH',
                                'url'       => lmbRoute('admin.product.update', [ 'id' => $product->id, 'form' => 'general' ]),
                                'class'     => 'product-form',
                                'files'     => true
                            ]) !!}
                                @include('laravel-modules-core::partials.form.actions', ['type' => 'top'])

                                    @include('laravel-modules-core::product.partials.form')
                                    @include('laravel-modules-core::product.partials.detail_form')

                                @include('laravel-modules-core::partials.form.actions', ['type' => 'fluid'])
                            {!! Form::close() !!}

                        {{-- /Edit Info --}}

                        {{-- Change Descriptions --}}

                            {!! Form::open([
                                'method'    => 'PATCH',
                                'url'       => lmbRoute('admin.product.update', [ 'id' => $product->id, 'form' => 'descriptions' ])
                            ]) !!}
                                @include('laravel-modules-core::partials.form.actions', ['type' => 'top'])

                                    @include('laravel-modules-core::product.partials.descriptions_form')

                                @include('laravel-modules-core::partials.form.actions', ['type' => 'fluid'])
                            {!! Form::close() !!}

                        {{-- /Change Descriptions --}}

                        {{-- Change Seo --}}

                            {!! Form::open([
                                'method'    => 'PATCH',
                                'url'       => lmbRoute('admin.product.update', [ 'id' => $product->id, 'form' => 'seo' ])
                            ]) !!}
                                @include('laravel-modules-core::partials.form.actions', ['type' => 'top'])

                                    @include('laravel-modules-core::product.partials.seo_form')

                                @include('laravel-modules-core::partials.form.actions', ['type' => 'fluid'])
                            {!! Form::close() !!}

                        {{-- /Change Seo --}}

                        @endif
                        {{-- /Edit Info --}}

                {{-- /Profile Content --}}

        {{-- /Portlet Body --}}

    {{-- /Portlet --}}
@endsection


text:
package cacustomroot

import (
	"fmt"
	"os"
	"path"
	"testing"

	"istio.io/istio/pkg/test/echo/common/scheme"
	"istio.io/istio/pkg/test/env"
	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/echo"
	"istio.io/istio/pkg/test/framework/components/echo/check"
	"istio.io/istio/pkg/test/framework/components/echo/match"
)

const (
	httpPlaintext = "http-plaintext"
	httpMTLS      = "http-mtls"
	tcpPlaintext  = "tcp-plaintext"
	tcpMTLS       = "tcp-mtls"
	tcpWL         = "tcp-wl"
	passThrough   = "tcp-mtls-pass-through"

	// policy to enable mTLS in client and server:
	// ports with plaintext: 8090 (http) and 8092 (tcp)
	// ports with mTLS: 8091 (http), 8093 (tcp) and 9000 (tcp passthrough).
	policy = `
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: "mtls"
spec:
  selector:
    matchLabels:
      app: server
  mtls:
    mode: STRICT
  portLevelMtls:
    8090:
      mode: DISABLE
    8092:
      mode: DISABLE
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: server
spec:
  host: server.%s.svc.cluster.local
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
    portLevelSettings:
    - port:
        number: 8090
      tls:
        mode: DISABLE
    - port:
        number: 8092
      tls:
        mode: DISABLE
`
)

// TestTrustDomainValidation tests the trust domain validation when mTLS is enabled.
// The trust domain validation should reject a request if it's not from the trust domains configured in the mesh config.
// The test uses naked client (no sidecar) with custom certificates of different trust domains and covers the following:
// - plaintext requests are not affected
// - same trust domain (cluster.local) and aliases (trust-domain-foo and trust-domain-bar)
// - works for both HTTP and TCP protocol
// - works for pass through filter chains
func TestTrustDomainValidation(t *testing.T) {
	framework.NewTest(t).Features("security.peer.trust-domain-validation").Run(
		func(ctx framework.TestContext) {
			testNS := apps.EchoNamespace.Namespace

			ctx.ConfigIstio().YAML(testNS.Name(), fmt.Sprintf(policy, testNS.Name())).ApplyOrFail(ctx)

			trustDomains := map[string]struct {
				cert string
				key  string
			}{
				"foo": {
					cert: readFile(ctx, "workload-foo-cert.pem"),
					key:  readFile(ctx, "workload-foo-key.pem"),
				},
				"bar": {
					cert: readFile(ctx, "workload-bar-cert.pem"),
					key:  readFile(ctx, "workload-bar-key.pem"),
				},
			}

			for _, cluster := range ctx.Clusters() {
				ctx.NewSubTest(fmt.Sprintf("From %s", cluster.StableName())).Run(func(t framework.TestContext) {
					// naked: only test app without sidecar, send requests from trust domain aliases
					// client: app with sidecar, send request from cluster.local
					// server: app with sidecar, verify requests from cluster.local or trust domain aliases
					client := match.Cluster(cluster).FirstOrFail(t, client)
					naked := match.Cluster(cluster).FirstOrFail(t, apps.Naked)
					server := match.Cluster(cluster).FirstOrFail(t, server)
					verify := func(ctx framework.TestContext, from echo.Instance, td, port string, s scheme.Instance, allow bool) {
						ctx.Helper()
						want := "allow"
						if !allow {
							want = "deny"
						}
						name := fmt.Sprintf("%s[%s]->server:%s[%s]", from.Config().Service, td, port, want)
						ctx.NewSubTest(name).Run(func(t framework.TestContext) {
							t.Helper()
							opt := echo.CallOptions{
								To:    server,
								Count: 1,
								Port: echo.Port{
									Name: port,
								},
								Address: "server",
								Scheme:  s,
								TLS: echo.TLS{
									Cert: trustDomains[td].cert,
									Key:  trustDomains[td].key,
								},
							}
							if port == passThrough {
								// Manually make the request for pass through port.
								opt = echo.CallOptions{
									ToWorkload: server,
									Port:       echo.Port{Name: tcpWL},
									TLS: echo.TLS{
										Cert: trustDomains[td].cert,
										Key:  trustDomains[td].key,
									},
									Check: check.OK(),
								}
							}
							if !allow {
								opt.Check = check.ErrorContains("tls: unknown certificate")
							}
							from.CallOrFail(t, opt)
						})
					}

					// Request using plaintext should always allowed.
					verify(t, client, "plaintext", httpPlaintext, scheme.HTTP, true)
					verify(t, client, "plaintext", tcpPlaintext, scheme.TCP, true)
					verify(t, naked, "plaintext", httpPlaintext, scheme.HTTP, true)
					verify(t, naked, "plaintext", tcpPlaintext, scheme.TCP, true)

					// Request from local trust domain should always allowed.
					verify(t, client, "cluster.local", httpMTLS, scheme.HTTP, true)
					verify(t, client, "cluster.local", tcpMTLS, scheme.TCP, true)

					// Trust domain foo is added as trust domain alias.
					// Request from trust domain bar should be denied.
					// Request from trust domain foo should be allowed.
					verify(t, naked, "bar", httpMTLS, scheme.HTTPS, false)
					verify(t, naked, "bar", tcpMTLS, scheme.TCP, false)
					verify(t, naked, "bar", passThrough, scheme.TCP, false)
					verify(t, naked, "foo", httpMTLS, scheme.HTTPS, true)
					verify(t, naked, "foo", tcpMTLS, scheme.TCP, true)
					verify(t, naked, "foo", passThrough, scheme.TCP, true)
				})
			}
		})
}

func readFile(ctx framework.TestContext, name string) string {
	data, err := os.ReadFile(path.Join(env.IstioSrc, "samples/certs", name))
	if err != nil {
		ctx.Fatal(err)
	}
	return string(data)
}


text:
. ./include.sh

REDIRECT=/dev/null
$PYTHON $examples_src/samples.py 2> $REDIRECT > $REDIRECT
rm -f out.samples.grib || true


text:
layout: page
title: Long Family Reunion
date: 2016-05-24
author: Christian Mckinney
tags: weekly links, java
status: published
summary: Cras eu accumsan nisl, et venenatis arcu. Phasellus eget pulvinar.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 03/31/2017
  endDate: 04/04/2017
  ctyhocn: CLECCHX
  groupCode: LFR
published: true
---
Aenean tempor dictum auctor. Aenean sit amet porta nisl. Pellentesque eros velit, aliquet at lacus gravida, sodales accumsan dui. Ut non turpis ultricies, finibus turpis maximus, viverra dui. Proin et quam interdum, ultrices nibh non, tincidunt orci. Vivamus et ante eu ex laoreet ullamcorper. Cras dapibus tortor eget leo commodo, eget finibus lacus fermentum.
Fusce laoreet nunc tortor, vitae pretium nunc ultrices eu. Nulla volutpat lectus sed diam mollis, ac accumsan lacus rhoncus. Vivamus metus libero, mollis ac nulla ac, vehicula dignissim ante. Suspendisse potenti. Etiam consequat quis lorem dictum sollicitudin. Ut congue dui at auctor faucibus. In rutrum, ipsum sit amet ultrices feugiat, lacus ante scelerisque sem, sodales porta sapien purus a nisi. Sed eget quam sed tortor sollicitudin interdum in in orci.

* Morbi non sem posuere, eleifend magna a, aliquam eros
* Nullam feugiat elit quis molestie maximus
* Praesent a tortor vitae nulla porta venenatis
* Donec gravida ante sit amet dapibus tincidunt.

In maximus ante nec diam iaculis rutrum. Morbi nec tincidunt nisl, cursus suscipit lectus. Nam eu ipsum nec lorem lobortis egestas. Mauris in nisi ultricies, posuere lectus a, fringilla orci. Donec posuere a sapien id lacinia. Cras malesuada felis cursus, maximus augue sed, dictum justo. Ut vehicula tellus eros, sit amet auctor quam euismod at. Etiam luctus ligula vitae lorem tempor, vel consectetur metus hendrerit. Mauris in lacus ut est tristique sodales. In hac habitasse platea dictumst. Maecenas dignissim dui euismod quam egestas, ut suscipit sapien porttitor. Nam fermentum nisi a ligula malesuada, nec vestibulum eros vehicula.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:\Users\Chrilieb\.cargo\registry\src\github.com-1ecc6299db9ec823\num-traits-0.1.40\src\ops\wrapping.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>wrapping.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="https://rust-num.github.io/num/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

use std::ops::{Add, Sub, Mul};
use std::num::Wrapping;

macro_rules! wrapping_impl {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self, v: &Self) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    };
    ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => {
        impl $trait_name<$rhs> for $t {
            #[inline]
            fn $method(&self, v: &$rhs) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    }
}

/// Performs addition that wraps around on overflow.
pub trait WrappingAdd: Sized + Add<Self, Output=Self> {
    /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of
    /// the type.
    fn wrapping_add(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingAdd, wrapping_add, u8);
wrapping_impl!(WrappingAdd, wrapping_add, u16);
wrapping_impl!(WrappingAdd, wrapping_add, u32);
wrapping_impl!(WrappingAdd, wrapping_add, u64);
wrapping_impl!(WrappingAdd, wrapping_add, usize);

wrapping_impl!(WrappingAdd, wrapping_add, i8);
wrapping_impl!(WrappingAdd, wrapping_add, i16);
wrapping_impl!(WrappingAdd, wrapping_add, i32);
wrapping_impl!(WrappingAdd, wrapping_add, i64);
wrapping_impl!(WrappingAdd, wrapping_add, isize);

/// Performs subtraction that wraps around on overflow.
pub trait WrappingSub: Sized + Sub<Self, Output=Self> {
    /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_sub(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingSub, wrapping_sub, u8);
wrapping_impl!(WrappingSub, wrapping_sub, u16);
wrapping_impl!(WrappingSub, wrapping_sub, u32);
wrapping_impl!(WrappingSub, wrapping_sub, u64);
wrapping_impl!(WrappingSub, wrapping_sub, usize);

wrapping_impl!(WrappingSub, wrapping_sub, i8);
wrapping_impl!(WrappingSub, wrapping_sub, i16);
wrapping_impl!(WrappingSub, wrapping_sub, i32);
wrapping_impl!(WrappingSub, wrapping_sub, i64);
wrapping_impl!(WrappingSub, wrapping_sub, isize);

/// Performs multiplication that wraps around on overflow.
pub trait WrappingMul: Sized + Mul<Self, Output=Self> {
    /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_mul(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingMul, wrapping_mul, u8);
wrapping_impl!(WrappingMul, wrapping_mul, u16);
wrapping_impl!(WrappingMul, wrapping_mul, u32);
wrapping_impl!(WrappingMul, wrapping_mul, u64);
wrapping_impl!(WrappingMul, wrapping_mul, usize);

wrapping_impl!(WrappingMul, wrapping_mul, i8);
wrapping_impl!(WrappingMul, wrapping_mul, i16);
wrapping_impl!(WrappingMul, wrapping_mul, i32);
wrapping_impl!(WrappingMul, wrapping_mul, i64);
wrapping_impl!(WrappingMul, wrapping_mul, isize);

// Well this is a bit funny, but all the more appropriate.
impl<T: WrappingAdd> WrappingAdd for Wrapping<T> where Wrapping<T>: Add<Output = Wrapping<T>> {
    fn wrapping_add(&self, v: &Self) -> Self {
        Wrapping(self.0.wrapping_add(&v.0))
    }
}
impl<T: WrappingSub> WrappingSub for Wrapping<T> where Wrapping<T>: Sub<Output = Wrapping<T>> {
    fn wrapping_sub(&self, v: &Self) -> Self {
        Wrapping(self.0.wrapping_sub(&v.0))
    }
}
impl<T: WrappingMul> WrappingMul for Wrapping<T> where Wrapping<T>: Mul<Output = Wrapping<T>> {
    fn wrapping_mul(&self, v: &Self) -> Self {
        Wrapping(self.0.wrapping_mul(&v.0))
    }
}

#[test]
fn test_wrapping_traits() {
    fn wrapping_add<T: WrappingAdd>(a: T, b: T) -> T { a.wrapping_add(&b) }
    fn wrapping_sub<T: WrappingSub>(a: T, b: T) -> T { a.wrapping_sub(&b) }
    fn wrapping_mul<T: WrappingMul>(a: T, b: T) -> T { a.wrapping_mul(&b) }
    assert_eq!(wrapping_add(255, 1), 0u8);
    assert_eq!(wrapping_sub(0, 1), 255u8);
    assert_eq!(wrapping_mul(255, 2), 254u8);
    assert_eq!(wrapping_add(255, 1), (Wrapping(255u8) + Wrapping(1u8)).0);
    assert_eq!(wrapping_sub(0, 1), (Wrapping(0u8) - Wrapping(1u8)).0);
    assert_eq!(wrapping_mul(255, 2), (Wrapping(255u8) * Wrapping(2u8)).0);
}

#[test]
fn wrapping_is_wrappingadd() {
    fn require_wrappingadd<T: WrappingAdd>(_: &T) {}
    require_wrappingadd(&Wrapping(42));
}

#[test]
fn wrapping_is_wrappingsub() {
    fn require_wrappingsub<T: WrappingSub>(_: &T) {}
    require_wrappingsub(&Wrapping(42));
}

#[test]
fn wrapping_is_wrappingmul() {
    fn require_wrappingmul<T: WrappingMul>(_: &T) {}
    require_wrappingmul(&Wrapping(42));
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
package feign;

import feign.Request.HttpMethod;
import java.util.Date;

/**
 * This exception is raised when the {@link Response} is deemed to be retryable, typically via an
 * {@link feign.codec.ErrorDecoder} when the {@link Response#status() status} is 503.
 */
public class RetryableException extends FeignException {

  private static final long serialVersionUID = 1L;

  private final Long retryAfter;
  private final HttpMethod httpMethod;

  /**
   * @param retryAfter usually corresponds to the {@link feign.Util#RETRY_AFTER} header.
   */
  public RetryableException(int status, String message, HttpMethod httpMethod, Throwable cause,
      Date retryAfter, Request request) {
    super(status, message, request, cause);
    this.httpMethod = httpMethod;
    this.retryAfter = retryAfter != null ? retryAfter.getTime() : null;
  }

  /**
   * @param retryAfter usually corresponds to the {@link feign.Util#RETRY_AFTER} header.
   */
  public RetryableException(int status, String message, HttpMethod httpMethod, Date retryAfter,
      Request request) {
    super(status, message, request);
    this.httpMethod = httpMethod;
    this.retryAfter = retryAfter != null ? retryAfter.getTime() : null;
  }

  /**
   * Sometimes corresponds to the {@link feign.Util#RETRY_AFTER} header present in {@code 503}
   * status. Other times parsed from an application-specific response. Null if unknown.
   */
  public Date retryAfter() {
    return retryAfter != null ? new Date(retryAfter) : null;
  }

  public HttpMethod method() {
    return this.httpMethod;
  }
}


text:
package org.jbpm.workbench.common.client.util;

import java.util.Date;

import org.jboss.errai.databinding.client.api.Converter;
import org.jbpm.workbench.common.client.resources.i18n.Constants;

public class DateTimeNAConverter implements Converter<Date, String> {

    private Constants constants = Constants.INSTANCE;

    @Override
    public Date toModelValue(final String value) {
        if (value == null || value.equals("")) {
            return null;
        }

        return DateUtils.createDate(value,
                                    DateUtils.getDateTimeFormatMask());
    }

    @Override
    public String toWidgetValue(final Date date) {
        final String dateTimeStr = DateUtils.getDateTimeStr(date);
        return dateTimeStr.trim().isEmpty() ? constants.NA() : dateTimeStr;
    }

    @Override
    public Class<Date> getModelType() {
        return Date.class;
    }

    @Override
    public Class<String> getComponentType() {
        return String.class;
    }
}


text:
namespace rclcpp
{

void
init(
  int argc,
  char const * const * argv,
  const InitOptions & init_options,
  SignalHandlerOptions signal_handler_options)
{
  using rclcpp::contexts::get_global_default_context;
  get_global_default_context()->init(argc, argv, init_options);
  // Install the signal handlers.
  install_signal_handlers(signal_handler_options);
}

bool
install_signal_handlers(SignalHandlerOptions signal_handler_options)
{
  return SignalHandler::get_global_signal_handler().install(signal_handler_options);
}

bool
signal_handlers_installed()
{
  return SignalHandler::get_global_signal_handler().is_installed();
}

SignalHandlerOptions
get_current_signal_handler_options()
{
  return SignalHandler::get_global_signal_handler().get_current_signal_handler_options();
}

bool
uninstall_signal_handlers()
{
  return SignalHandler::get_global_signal_handler().uninstall();
}

static
std::vector<std::string>
_remove_ros_arguments(
  char const * const * argv,
  const rcl_arguments_t * args,
  rcl_allocator_t alloc)
{
  rcl_ret_t ret;
  int nonros_argc = 0;
  const char ** nonros_argv = NULL;

  ret = rcl_remove_ros_arguments(
    argv,
    args,
    alloc,
    &nonros_argc,
    &nonros_argv);

  if (RCL_RET_OK != ret || nonros_argc < 0) {
    // Not using throw_from_rcl_error, because we may need to append deallocation failures.
    exceptions::RCLError exc(ret, rcl_get_error_state(), "");
    rcl_reset_error();
    if (NULL != nonros_argv) {
      alloc.deallocate(nonros_argv, alloc.state);
    }
    throw exc;
  }

  std::vector<std::string> return_arguments(static_cast<size_t>(nonros_argc));

  for (size_t ii = 0; ii < static_cast<size_t>(nonros_argc); ++ii) {
    return_arguments[ii] = std::string(nonros_argv[ii]);
  }

  if (NULL != nonros_argv) {
    alloc.deallocate(nonros_argv, alloc.state);
  }

  return return_arguments;
}

std::vector<std::string>
init_and_remove_ros_arguments(
  int argc,
  char const * const * argv,
  const InitOptions & init_options)
{
  init(argc, argv, init_options);

  using rclcpp::contexts::get_global_default_context;
  auto rcl_context = get_global_default_context()->get_rcl_context();
  return _remove_ros_arguments(argv, &(rcl_context->global_arguments), rcl_get_default_allocator());
}

std::vector<std::string>
remove_ros_arguments(int argc, char const * const * argv)
{
  rcl_allocator_t alloc = rcl_get_default_allocator();
  rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments();

  rcl_ret_t ret;

  ret = rcl_parse_arguments(argc, argv, alloc, &parsed_args);
  if (RCL_RET_OK != ret) {
    exceptions::throw_from_rcl_error(ret, "failed to parse arguments");
  }

  std::vector<std::string> return_arguments;
  try {
    return_arguments = _remove_ros_arguments(argv, &parsed_args, alloc);
  } catch (exceptions::RCLError & exc) {
    if (RCL_RET_OK != rcl_arguments_fini(&parsed_args)) {
      exc.formatted_message += std::string(
        ", failed also to cleanup parsed arguments, leaking memory: ") +
        rcl_get_error_string().str;
      rcl_reset_error();
    }
    throw exc;
  }

  ret = rcl_arguments_fini(&parsed_args);
  if (RCL_RET_OK != ret) {
    exceptions::throw_from_rcl_error(
      ret, "failed to cleanup parsed arguments, leaking memory");
  }

  return return_arguments;
}

bool
ok(Context::SharedPtr context)
{
  using rclcpp::contexts::get_global_default_context;
  if (nullptr == context) {
    context = get_global_default_context();
  }
  return context->is_valid();
}

bool
shutdown(Context::SharedPtr context, const std::string & reason)
{
  using rclcpp::contexts::get_global_default_context;
  auto default_context = get_global_default_context();
  if (nullptr == context) {
    context = default_context;
  }
  bool ret = context->shutdown(reason);
  if (context == default_context) {
    uninstall_signal_handlers();
  }
  return ret;
}

void
on_shutdown(std::function<void()> callback, Context::SharedPtr context)
{
  using rclcpp::contexts::get_global_default_context;
  if (nullptr == context) {
    context = get_global_default_context();
  }
  context->on_shutdown(callback);
}

bool
sleep_for(const std::chrono::nanoseconds & nanoseconds, Context::SharedPtr context)
{
  using rclcpp::contexts::get_global_default_context;
  if (nullptr == context) {
    context = get_global_default_context();
  }
  return context->sleep_for(nanoseconds);
}

const char *
get_c_string(const char * string_in)
{
  return string_in;
}

const char *
get_c_string(const std::string & string_in)
{
  return string_in.c_str();
}

std::vector<const char *>
get_c_vector_string(const std::vector<std::string> & strings_in)
{
  std::vector<const char *> cstrings;
  cstrings.reserve(strings_in.size());

  for (size_t i = 0; i < strings_in.size(); ++i) {
    cstrings.push_back(strings_in[i].c_str());
  }

  return cstrings;
}

}  // namespace rclcpp


text:
#ifndef TSQLTRANSACTION_H
#define TSQLTRANSACTION_H

#include <QSqlDatabase>
#include <TGlobal>

/*!
  \class Transaction
  \brief The Transaction class provides a transaction of database.
*/

class T_CORE_EXPORT TSqlTransaction {
public:
    TSqlTransaction();
    TSqlTransaction(const TSqlTransaction &other) = default;
    ~TSqlTransaction();

    TSqlTransaction &operator=(const TSqlTransaction &) = default;
    QSqlDatabase &database() { return _database; }
    bool begin();
    bool commit();
    bool rollback();
    bool isActive() const { return _active; }
    void setEnabled(bool enable);
    void setDisabled(bool disable);

private:
    QSqlDatabase _database;
    bool _enabled {true};
    bool _active {false};
    QString _connectionName;
};

inline void TSqlTransaction::setEnabled(bool enable)
{
    _enabled = enable;
}

inline void TSqlTransaction::setDisabled(bool disable)
{
    _enabled = !disable;
}

#endif  // TSQLTRANSACTION_H


text:
import Radio from './radio.jsx';
import Text from './text.jsx';

export {
  Radio,
  Text
};


text:
package jetbrick.template.parser.code;

import jetbrick.template.parser.support.TypedKlass;
import org.antlr.v4.runtime.ParserRuleContext;

/**
 * 专门用于存储 for_expression
 */
public class ForExpressionCode extends SegmentCode {
    private final String name; // 变量名

    public ForExpressionCode(TypedKlass typedKlass, String name, String source, ParserRuleContext node) {
        super(typedKlass, source, node);
        this.name = name;
    }

    public String getName() {
        return name;
    }
}


text:
package org.eigenbase.sql;

import java.util.*;

import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.validate.*;

/**
 * SqlProcedureCallOperator represents the CALL statement. It takes a single
 * operand which is the real SqlCall.
 *
 * @author John V. Sichi
 * @version $Id$
 */
public class SqlProcedureCallOperator
    extends SqlPrefixOperator
{
    //~ Constructors -----------------------------------------------------------

    public SqlProcedureCallOperator()
    {
        super("CALL", SqlKind.PROCEDURE_CALL, 0, null, null, null);
    }

    //~ Methods ----------------------------------------------------------------

    // override SqlOperator
    public SqlNode rewriteCall(SqlValidator validator, SqlCall call)
    {
        // for now, rewrite "CALL f(x)" to "SELECT f(x) FROM VALUES(0)"
        // TODO jvs 18-Jan-2005:  rewrite to SELECT * FROM TABLE f(x)
        // once we support function calls as tables
        SqlStdOperatorTable opTab = SqlStdOperatorTable.instance();
        return SqlStdOperatorTable.selectOperator.createCall(
            null,
            new SqlNodeList(
                Collections.singletonList(
                    call.getOperands()[0]),
                SqlParserPos.ZERO),
            SqlStdOperatorTable.valuesOperator.createCall(
                SqlParserPos.ZERO,
                SqlStdOperatorTable.rowConstructor.createCall(
                    SqlParserPos.ZERO,
                    SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO))),
            null,
            null,
            null,
            null,
            null,
            SqlParserPos.ZERO);
    }
}

// End SqlProcedureCallOperator.java


text:
require "spec_helper"

describe TableCloth::ColumnJury do
  let(:dummy_table) { double(:table, admin?: true, moderator?: false) }

  subject { TableCloth::ColumnJury.new(column, dummy_table) }

  context 'conditions' do
    context 'if' do
      let(:column) { FactoryGirl.build(:if_column) }

      specify 'the column is available when condition returns true' do
        expect(subject).to be_available
      end

      it 'the column is not available when condition returns false' do
        dummy_table.stub admin?: false
        expect(subject).not_to be_available
      end
    end

    context 'unless' do
      let(:column) { FactoryGirl.build(:unless_column) }

      specify 'the column is available when condition returns false' do
        expect(subject).to be_available
      end

      specify 'the column is not available when condition returns true' do
        dummy_table.stub moderator?: true
        expect(subject).not_to be_available
      end
    end
  end
end


text:
<?php

namespace AppBundle\Listener;

use AppBundle\Entity\Adventure;
use AppBundle\Entity\RelatedEntityInterface;
use AppBundle\Service\AdventureSerializer;
use AppBundle\Service\ElasticSearch;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Elasticsearch\Client;
use Elasticsearch\Common\Exceptions\Missing404Exception;

class SearchIndexUpdater implements EventSubscriber
{
    const INDEX = 'adventure';
    const TYPE = 'all';

    /**
     * @var Client
     */
    private $client;

    /**
     * @var AdventureSerializer
     */
    private $serializer;

    /**
     * @var string
     */
    private $indexName;

    /**
     * @var string
     */
    private $typeName;

    /**
     * @var int[]
     */
    private $adventureIdsToRemove;

    /**
     * If true, force immediate ElasticSearch refresh.
     * This is useful for tests, so they don't continue when the index isn't yet refreshed.
     * @var bool
     */
    private $isTestEnvironment;

    public function __construct(ElasticSearch $elasticSearch, $environment)
    {
        $this->serializer = new AdventureSerializer();
        $this->client = $elasticSearch->getClient();
        $this->indexName = $elasticSearch->getIndexName();
        $this->typeName = $elasticSearch->getTypeName();
        $this->adventureIdsToRemove = [];
        $this->isTestEnvironment = $environment === 'test';
    }

    /**
     * Returns an array of events this subscriber wants to listen to.
     *
     * @return array
     */
    public function getSubscribedEvents()
    {
        return [
            'onFlush',
            'preRemove',
            'postPersist',
            'postUpdate',
            'postRemove',
            'postFlush',
        ];
    }

    /**
     * Called right before the changes are flushed.
     *
     * Make sure to fetch the adventures for all associated entities which are going to be deleted.
     * We can't fetch them inside the postRemove handler, because the associated entities will have been removed
     * from the database at that point. Fetching them now by calling ->getValues() makes sure the
     * database is actually queried for the adventures and the collection isn't just proxying them.
     *
     * @param OnFlushEventArgs $eventArgs
     */
    public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $em = $eventArgs->getEntityManager();
        $uow = $em->getUnitOfWork();
        foreach ($uow->getScheduledEntityDeletions() as $entity) {
            if ($entity instanceof RelatedEntityInterface) {
                $entity->getAdventures()->getValues();
            }
        }
    }

    /**
     * Keep track of all ids of adventures being removed. We need to save them for later, because the id of
     * a removed adventure is not available inside postRemove.
     *
     * @param LifecycleEventArgs $args
     */
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Adventure) {
            $this->adventureIdsToRemove[] = $entity->getId();
        }
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $this->handleInsertOrUpdate($args);
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
        $this->handleInsertOrUpdate($args);
    }

    public function postRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Adventure) {
            // Do nothing - if this is an adventure being deleted, Doctrine sets its id to null.
            // We will delete the adventure in the postFlush listener - we saved the id in the preRemove listener.
        } else {
            // Don't delete the search index if the entity is not an adventure.
            // Simply reindex the adventure instead.
            $this->handleInsertOrUpdate($args);
        }
    }

    public function postFlush(PostFlushEventArgs $args)
    {
        foreach ($this->adventureIdsToRemove as $adventureId) {
            $this->deleteSearchIndexForAdventureId($adventureId);
        }
        // Make sure to reset the ids to remove in case another flush operation is following.
        $this->adventureIdsToRemove = [];
    }

    private function handleInsertOrUpdate(LifecycleEventArgs $args)
    {
        $adventures = $this->getAffectedAdventures($args);
        foreach ($adventures as $adventure) {
            if ($adventure->getId() === null) {
                // If the id is null, then this is a new related entity which references the main adventure which
                // doesn't yet have an id. We can simply skip it.
                continue;
            }
            $this->updateSearchIndexForAdventure($adventure);
        }
    }

    /**
     * Given the lifecycle event, find all adventures effected by it.
     *
     * @param LifecycleEventArgs $args
     * @return Adventure[]
     */
    private function getAffectedAdventures(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Adventure) {
            return [$entity];
        }
        if ($entity instanceof RelatedEntityInterface) {
            return $entity->getAdventures();
        }

        return [];
    }

    /**
     * Updates the search index for the given adventure.
     *
     * @param Adventure $adventure
     */
    public function updateSearchIndexForAdventure(Adventure $adventure)
    {
        $id = $adventure->getId();
        if (!is_numeric($id)) {
            throw new \RuntimeException('Trying to index an adventure without an id set! This should not have happened.');
        }
        $this->client->index([
            'index' => $this->indexName,
            'type' => $this->typeName,
            'id' => $id,
            'body' => $this->serializer->toElasticDocument($adventure),
            'refresh' => $this->isTestEnvironment,
        ]);
    }

    /**
     * Deletes the search index for the given adventure.
     * Fails silently if the index is already deleted.
     *
     * @param int $adventureId
     */
    private function deleteSearchIndexForAdventureId(int $adventureId)
    {
        try {
            $this->client->delete([
                'index' => $this->indexName,
                'type' => $this->typeName,
                'id' => $adventureId,
                'refresh' => $this->isTestEnvironment,
            ]);
        } catch (Missing404Exception $e) {
            // Apparently already deleted.
        }
    }
}


text:
regex-chain
===========

Chain regexes together in nodejs

Installation
------------

`npm install regex-chain`

Usage
-----

    var RegexChain = require('regex-chain');
    var containsNumbers = new RegexChain(/[0-9]/);
    var containsLetters = new RegexChain(/[a-zA-Z]/);
    console.log("asdf09 contains letters and numbers: " + containsLetters.and(containsNumbers).test("asdf09"));
    console.log("asdf contains letters and numbers: " + containsLetters.and(containsNumbers).test("asdf"));

Todo
----
 - Generate some documentation. For now, just skim the unit tests or code
 - Allow more than just `.test` method. `exec` would be the best one


text:
package org.apache.synapse.config.xml;

import org.apache.axiom.om.OMElement;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.builtin.LogMediator;

/**
 * <pre>
 * <log [level="simple|headers|full|custom"] [separator="string"] [category="INFO|TRACE|DEBUG|WARN|ERROR|FATAL"]>
 *      <property> *
 * </log>
 * </pre>
 */
public class LogMediatorSerializer extends AbstractMediatorSerializer {

    public OMElement serializeSpecificMediator(Mediator m) {

        if (!(m instanceof LogMediator)) {
            handleException("Unsupported mediator passed in for serialization : " + m.getType());
        }

        LogMediator mediator = (LogMediator) m;
        OMElement log = fac.createOMElement("log", synNS);
        saveTracingState(log,mediator);

        if (mediator.getLogLevel() != LogMediator.SIMPLE) {
            log.addAttribute(fac.createOMAttribute(
                "level", nullNS,
                    mediator.getLogLevel() == LogMediator.HEADERS ? "headers" :
                    mediator.getLogLevel() == LogMediator.FULL ? "full" :
                    mediator.getLogLevel() == LogMediator.CUSTOM ? "custom" : "simple"
                ));
        }

        if (mediator.getCategory() != LogMediator.CATEGORY_INFO) {
            log.addAttribute(fac.createOMAttribute(
                "category", nullNS,
                    mediator.getCategory() == LogMediator.CATEGORY_TRACE ?
                            LogMediatorFactory.CAT_TRACE :
                    mediator.getCategory() == LogMediator.CATEGORY_DEBUG ?
                            LogMediatorFactory.CAT_DEBUG :
                    mediator.getCategory() == LogMediator.CATEGORY_WARN ?
                            LogMediatorFactory.CAT_WARN :
                    mediator.getCategory() == LogMediator.CATEGORY_ERROR ?
                            LogMediatorFactory.CAT_ERROR :
                    mediator.getCategory() == LogMediator.CATEGORY_FATAL ?
                            LogMediatorFactory.CAT_FATAL :
                            LogMediatorFactory.CAT_INFO
                ));
        }

        if (!LogMediator.DEFAULT_SEP.equals(mediator.getSeparator())) {
            log.addAttribute(fac.createOMAttribute(
                    "separator", nullNS, mediator.getSeparator()));
        }

        super.serializeProperties(log, mediator.getProperties());

        return log;
    }

    public String getMediatorClassName() {
        return LogMediator.class.getName();
    }
}