text:
import math
import numpy as np
from scipy.stats import norm

from . import common_args
from ..util import read_param_file, ResultDict

def analyze(
    problem,
    Y,
    M=4,
    num_resamples=100,
    conf_level=0.95,
    print_to_console=False,
    seed=None,
):
    """Perform extended Fourier Amplitude Sensitivity Test on model outputs

    Returns a dictionary with keys 'S1' and 'ST', where each entry is a list of
    size D (the number of parameters) containing the indices in the same order
    as the parameter file.

    Notes
    -----
    Compatible with:
        `fast_sampler` : :func:`SALib.sample.fast_sampler.sample`

    Examples
    --------
        >>> X = fast_sampler.sample(problem, 1000)
        >>> Y = Ishigami.evaluate(X)
        >>> Si = fast.analyze(problem, Y, print_to_console=False)

    Parameters
    ----------
    problem : dict
        The problem definition
    Y : numpy.array
        A NumPy array containing the model outputs
    M : int
        The interference parameter, i.e., the number of harmonics to sum in
        the Fourier series decomposition (default 4)
    print_to_console : bool
        Print results directly to console (default False)
    seed : int
        Seed to generate a random number

    References
    ----------
    .. [1] Cukier, R. I., C. M. Fortuin, K. E. Shuler, A. G. Petschek,
           and J. H. Schaibly (1973).
           "Study of the sensitivity of coupled reaction
           systems to uncertainties in rate coefficients."  J. Chem. Phys.,
           59(8):3873-3878, doi:10.1063/1.1680571.

    .. [2] Saltelli, A., S. Tarantola, and K. P.-S. Chan (1999).  "A
           Quantitative Model-Independent Method for Global Sensitivity
           Analysis of Model Output."  Technometrics, 41(1):39-56,
           doi:10.1080/00401706.1999.10485594.

    .. [3] Pujol, G. (2006)
           fast99 - R `sensitivity` package
           https://github.com/cran/sensitivity/blob/master/R/fast99.R
    """
    if seed:
        np.random.seed(seed)

    D = problem["num_vars"]

    if Y.size % (D) == 0:
        N = int(Y.size / D)
    else:
        msg = """
        Error: Number of samples in model output file must be a multiple of D,
        where D is the number of parameters.
        """
        raise ValueError(msg)

    # Recreate the vector omega used in the sampling
    omega_0 = math.floor((N - 1) / (2 * M))

    # Calculate and Output the First and Total Order Values
    Si = ResultDict((k, [None] * D) for k in ["S1", "ST", "S1_conf", "ST_conf"])
    Si["names"] = problem["names"]
    for i in range(D):
        z = np.arange(i * N, (i + 1) * N)

        Y_l = Y[z]

        S1, ST = compute_orders(Y_l, N, M, omega_0)
        Si["S1"][i] = S1
        Si["ST"][i] = ST

        S1_d_conf, ST_d_conf = bootstrap(Y_l, M, num_resamples, conf_level)
        Si["S1_conf"][i] = S1_d_conf
        Si["ST_conf"][i] = ST_d_conf

    if print_to_console:
        print(Si.to_df())

    return Si

def compute_orders(outputs: np.ndarray, N: int, M: int, omega: int):
    f = np.fft.fft(outputs)
    Sp = np.power(np.absolute(f[np.arange(1, math.ceil(N / 2))]) / N, 2)

    V = 2.0 * np.sum(Sp)

    # Calculate first and total order
    D1 = 2.0 * np.sum(Sp[np.arange(1, M + 1) * omega - 1])
    Dt = 2.0 * np.sum(Sp[np.arange(math.floor(omega / 2.0))])

    return (D1 / V), (1.0 - Dt / V)

def bootstrap(Y: np.ndarray, M: int, resamples: int, conf_level: float):
    """Compute CIs.

    Infers ``N`` from results of sub-sample ``Y`` and re-estimates omega (ω)
    for the above ``N``.
    """
    # Use half of available data each time
    T_data = Y.shape[0]
    n_size = math.ceil(T_data * 0.5)

    res_S1 = np.zeros(resamples)
    res_ST = np.zeros(resamples)
    for i in range(resamples):
        sample_idx = np.random.choice(T_data, replace=True, size=n_size)
        Y_rs = Y[sample_idx]

        N = len(Y_rs)
        omega = math.floor((N - 1) / (2 * M))

        S1, ST = compute_orders(Y_rs, N, M, omega)
        res_S1[i] = S1
        res_ST[i] = ST

    bnd = norm.ppf(0.5 + conf_level / 2.0)
    S1_conf = bnd * res_S1.std(ddof=1)
    ST_conf = bnd * res_ST.std(ddof=1)
    return S1_conf, ST_conf

# No additional arguments required for FAST
def cli_parse(parser):
    """Add method specific options to CLI parser.

    Parameters
    ----------
    parser : argparse object

    Returns
    ----------
    Updated argparse object
    """
    parser.add_argument(
        "-M", "--M", type=int, required=False, default=4, help="Inference parameter"
    )
    parser.add_argument(
        "-r",
        "--resamples",
        type=int,
        required=False,
        default=100,
        help="Number of bootstrap resamples for Sobol " "confidence intervals",
    )

    return parser

def cli_action(args):
    problem = read_param_file(args.paramfile)
    Y = np.loadtxt(
        args.model_output_file, delimiter=args.delimiter, usecols=(args.column,)
    )

    analyze(
        problem,
        Y,
        M=args.M,
        num_resamples=args.resamples,
        print_to_console=True,
        seed=args.seed,
    )

if __name__ == "__main__":
    common_args.run_cli(cli_parse, cli_action)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ADPhotoPrep
{
	public partial class EditADPrefs : Form
	{
		static string defpwd = "**UNCHANGED**";

		public EditADPrefs()
		{
			InitializeComponent();
		}

		private void EditADProps_Shown(object sender, EventArgs e)
		{
            DomainTB.Text = string.IsNullOrEmpty(AD.DomainName) ? Environment.GetEnvironmentVariable("USERDOMAIN") : AD.DomainName;
            AutoCredentialsChk.Checked = AD.UseWindowsCreds;
            LoginDomainTB.Text = string.IsNullOrEmpty(AD.LoginDomain) ? Environment.GetEnvironmentVariable("USERDOMAIN") : AD.LoginDomain;
            UsernameTB.Text = string.IsNullOrEmpty(AD.Username) ? Environment.GetEnvironmentVariable("USERNAME") : AD.Username;
			PasswordTB.Text = defpwd;

            AutoCredentialsChk_CheckedChanged(this, EventArgs.Empty);
		}

        private void AutoCredentialsChk_CheckedChanged(object sender, EventArgs e)
        {
            LoginDomainTB.Enabled = UsernameTB.Enabled = PasswordTB.Enabled = !AutoCredentialsChk.Checked;
        }

        private void button1_Click(object sender, EventArgs e)
		{
            AD.DomainName = DomainTB.Text;
            AD.UseWindowsCreds = AutoCredentialsChk.Checked;
			AD.LoginDomain = LoginDomainTB.Text;
			AD.Username = UsernameTB.Text;
			if (PasswordTB.Text != defpwd)
				AD.Password = PasswordTB.Text;

		}

		public static DialogResult Execute()
		{
			using (EditADPrefs frm = new EditADPrefs())
			{
				return frm.ShowDialog();
			}
		}
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace swganh
{
namespace messages
{

struct ChatOnEnteredRoom : public BaseSwgMessage
{
    uint16_t Opcount() const
    {
        return 5;
    }
    uint32_t Opcode() const
    {
        return 0xE69BDC0A;
    }

    std::string game_name; // default: SWG
    std::string server_name; // galaxy name
    std::string character_name;
    uint32_t success_bitmask;
    uint32_t channel_id;
    uint32_t nothing;

    ChatOnEnteredRoom()
        : game_name("SWG")
        , nothing(0)
    {}

    void OnSerialize(swganh::ByteBuffer& buffer) const
    {
        buffer.write(game_name);
        buffer.write(server_name);
        buffer.write(character_name);
        buffer.write(success_bitmask);
        buffer.write(channel_id);
        buffer.write(nothing);
    }

    void OnDeserialize(swganh::ByteBuffer& buffer)
    {
        game_name = buffer.read<std::string>();
        server_name = buffer.read<std::string>();
        character_name = buffer.read<std::string>();
        success_bitmask = buffer.read<uint32_t>();
        channel_id = buffer.read<uint32_t>();
        nothing = buffer.read<uint32_t>();
    }
};

}
} // namespace swganh::messages


text:
class Distances {
    public static euclid(a: number[], b: number[]): number {
        let dist = 0.0;
        for (var i = 0; i < a.length; i++) {
            dist += (a[i] - b[i]) * (a[i] - b[i]);
        }
        if (isNaN(dist))
            throw "Distance is NaN";
        return dist;
    }
}

export class GenLloyd {
    protected samplePoints: number[][];
    protected clusterPoints: number[][];
    protected relClusterWeight: number[];
    protected absClusterWeight: number[];

    private pointApproxIndices: number[];
    private pointDimension = 0;

    protected epsilon = 0.05;
    protected avgDistortion = 0.0;

    private setSamplePoints(samplePoints: number[][]) {
        if (samplePoints.length > 0) {
            this.samplePoints = samplePoints;
            this.pointDimension = samplePoints[0].length;
        }
    }

    public quantize(samplePoints: number[][], k: number) {
        this.setSamplePoints(samplePoints);
        this.calcClusters(k);
        return this.clusterPoints;
    }

    private makePoint(): number[] {
        let point : number[] = [];
        for (let i = 0; i < this.pointDimension; i++)
            point[i] = 0;
        return point;
    }

    /**
     * Calculate <numClusters> cluster points. This methods needs to be called
     * BEFORE getClusterPoints() and getClusterWeight()
     * @param numClusters Number of calculated cluster points
     */
    private calcClusters(numClusters: number) {
        // initialize with first cluster
        this.clusterPoints = [this.makePoint()];
        this.relClusterWeight = [];
        this.absClusterWeight = [];
        this.relClusterWeight[0] = 1.0;
        this.absClusterWeight[0] = this.samplePoints.length;

        let newClusterPoint = this.initializeClusterPoint(this.samplePoints);
        this.clusterPoints[0] = newClusterPoint;

        if (numClusters > 1) {
            // calculate initial average distortion
            this.avgDistortion = 0.0;
            this.samplePoints.forEach(samplePoint => {
                this.avgDistortion += Distances.euclid(samplePoint, newClusterPoint);
            });

            this.avgDistortion /= this.samplePoints.length * this.pointDimension;

            // set up array of point approximization indices
            this.pointApproxIndices = [];

            // split the clusters
            let i = 1;
            do {
                i = this.splitClusters();
            } while (i < numClusters);
        }
    }

    protected splitClusters(): number {
        let newClusterPointSize = 2;
        if (this.clusterPoints.length != 1) {
            newClusterPointSize = this.clusterPoints.length * 2;
        }

        // split clusters
        let newClusterPoints = [];
        let newClusterPointIdx = 0;
        this.clusterPoints.forEach(clusterPoint =>{
            newClusterPoints[newClusterPointIdx] = this.createNewClusterPoint(clusterPoint, -1);
            newClusterPoints[newClusterPointIdx+1] = this.createNewClusterPoint(clusterPoint, +1);
            newClusterPointIdx += 2;
        });

        this.clusterPoints = newClusterPoints;

        // iterate to approximate cluster points
        //int iteration = 0;
        let curAvgDistortion = 0.0;
        do {
            curAvgDistortion = this.avgDistortion;

            // find the min values
            for (let pointIdx = 0; pointIdx < this.samplePoints.length; pointIdx++) {
                let minDist = Number.MAX_VALUE;
                for (let clusterPointIdx = 0; clusterPointIdx < this.clusterPoints.length; clusterPointIdx++) {
                    let newMinDist = Distances.euclid(this.samplePoints[pointIdx], this.clusterPoints[clusterPointIdx]);
                    if (newMinDist < minDist) {
                        minDist = newMinDist;
                        this.pointApproxIndices[pointIdx] = clusterPointIdx;
                    }
                }
            }

            // update codebook
            for (let clusterPointIdx = 0; clusterPointIdx < this.clusterPoints.length; clusterPointIdx++) {
                let newClusterPoint = this.makePoint();
                let num = 0;
                for (let pointIdx = 0; pointIdx < this.samplePoints.length; pointIdx++) {
                    if (this.pointApproxIndices[pointIdx] == clusterPointIdx) {
                        this.addPointValues(newClusterPoint, this.samplePoints[pointIdx]);
                        num++;
                    }
                }

                if (num > 0) {
                    this.multiplyPointValues(newClusterPoint, 1.0 / num);
                    this.clusterPoints[clusterPointIdx] = newClusterPoint;
                    this.relClusterWeight[clusterPointIdx] = num / this.samplePoints.length;
                    this.absClusterWeight[clusterPointIdx] = num;
                }
            }

            // increase iteration count
            //System.out.println("  > Iteration = " + iteration);
            //iteration++;

            // update average distortion
            this.avgDistortion = 0.0;
            for (let pointIdx = 0; pointIdx < this.samplePoints.length; pointIdx++) {
                this.avgDistortion += Distances.euclid(this.samplePoints[pointIdx], this.clusterPoints[this.pointApproxIndices[pointIdx]]);
            }

            this.avgDistortion /= this.samplePoints.length * this.pointDimension;

        } while (((curAvgDistortion - this.avgDistortion) / curAvgDistortion) > this.epsilon);

        return this.clusterPoints.length;
    }

    protected initializeClusterPoint(pointsInCluster: number[][]): number[] {
        // calculate point sum
        let clusterPoint = this.makePoint();
        for (let numPoint = 0; numPoint < pointsInCluster.length; numPoint++) {
            this.addPointValues(clusterPoint, pointsInCluster[numPoint]);
        }

        // calculate average
        this.multiplyPointValues(clusterPoint, 1.0 / pointsInCluster.length);

        return clusterPoint;
    }

    protected createNewClusterPoint(clusterPoint: number[], epsilonFactor: number): number[] {
        let newClusterPoint = this.makePoint();
        this.addPointValues(newClusterPoint, clusterPoint);
        this.multiplyPointValues(newClusterPoint, 1.0 + epsilonFactor * this.epsilon);

        return newClusterPoint;
    }

    protected addPointValues(v1: number[], v2: number[]) {
        for (let pointIdx = 0; pointIdx < v1.length; pointIdx++) {
            v1[pointIdx] += v2[pointIdx];
        }
    }

    protected multiplyPointValues (v1: number[], f: number) {
        for (let pointIdx = 0; pointIdx < v1.length; pointIdx++) {
            v1[pointIdx] *= f;
        }
    }
}


text:
package com.yelbota.plugins.adt;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.testing.stubs.ArtifactStub;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

public class DependencyAdtMojoTest {

    @Test

    /**
     * Tests that adt dependency selected correctly from plugin dependencies.
     * @throws Exception if any
     */
    public void getAirSdkArtifactTest1() throws Exception {

        List<Artifact> artifactList = new ArrayList<Artifact>();
        ArtifactStub stub = new ArtifactStub();
        stub.setGroupId("com.adobe.air");
        stub.setArtifactId("air-sdk");
        artifactList.add(stub);

        DependencyAdtMojo adtMojo = new DependencyAdtMojo();
        adtMojo.pluginArtifacts = artifactList;
        Assert.assertNotNull(adtMojo.getAirSdkArtifact());
    }

    @Test

    /**
     * Tests that mojo fails when no dependency and airVersion defined
     * @throws Exception if any
     */
    public void getAirSdkArtifactTest2() throws Exception {

        List<Artifact> artifactList = new ArrayList<Artifact>();
        ArtifactStub stub = new ArtifactStub();
        stub.setArtifactId("");
        stub.setGroupId("");
        artifactList.add(stub);

        DependencyAdtMojo adtMojo = new DependencyAdtMojo();
        adtMojo.pluginArtifacts = artifactList;

        try {
            adtMojo.getAirSdkArtifact();
            Assert.fail("no dependency or sdk-version defined");
        } catch (MojoFailureException e) {
            // Ok. This is correct behaviour
        }
    }

    @Test
    public void getSDKArtifactPackagingTest() throws Exception {

        DependencyAdtMojo adtMojo = new DependencyAdtMojo();

        String p = adtMojo.getSDKArtifactPackaging("3.1", DependencyAdtMojo.OS_CLASSIFIER_WINDOWS);
        Assert.assertEquals(p, DependencyAdtMojo.ZIP);

        p = adtMojo.getSDKArtifactPackaging("3.1", DependencyAdtMojo.OS_CLASSIFIER_MAC);
        Assert.assertEquals(p, DependencyAdtMojo.ZIP);

        p = adtMojo.getSDKArtifactPackaging("3.2-RC1", DependencyAdtMojo.OS_CLASSIFIER_MAC);
        Assert.assertEquals(p, DependencyAdtMojo.ZIP);

        p = adtMojo.getSDKArtifactPackaging("3.4", DependencyAdtMojo.OS_CLASSIFIER_WINDOWS);
        Assert.assertEquals(p, DependencyAdtMojo.ZIP);

        p = adtMojo.getSDKArtifactPackaging("3.4", DependencyAdtMojo.OS_CLASSIFIER_MAC);
        Assert.assertEquals(p, DependencyAdtMojo.TBZ2);

        p = adtMojo.getSDKArtifactPackaging("3.4-beta-1", DependencyAdtMojo.OS_CLASSIFIER_MAC);
        Assert.assertEquals(p, DependencyAdtMojo.TBZ2);
    }

    @Test
    public void getVersionNumberTest() throws Exception {
        DependencyAdtMojo adtMojo = new DependencyAdtMojo();
        Assert.assertEquals(adtMojo.getVersionNumber("3.4"), Float.valueOf("3.4"));
        Assert.assertEquals(adtMojo.getVersionNumber("4.0"), Float.valueOf("4.0"));
        Assert.assertEquals(adtMojo.getVersionNumber("14.0.0.76"), Float.valueOf("14.0"));
    }

}


text:
<Alloy>
	<Model src="dummy" />
  <Window id="projectdetail_window" title="project Detail" backgroundColor="white">
	  <TableView id="projectdetail_table"  backgroundColor="transparent">
	  	<TableViewSection headerTitle="ProjectDetails">
		  <TableViewRow id="projectdetail_row" Title="projectDetail">
		  	  <Label id="ProjectName" text="{dummy.projectname}" />
		  </TableViewRow>
		  <TableViewRow id="clientprojectdetail_row" Title="clientprojectDetail">
	   		  <Label id="fullname" text="{dummy.fullname}" />
	   	  </TableViewRow>
		  <TableViewRow id="phoneprojectdetail_row" Title="PhoneprojectDetail">
	   		  <Label id="phone" text="{dummy.phone}" />
	   	  </TableViewRow>
	   	  <TableViewRow id="addressprojectdetail_row" Title="addressprojectDetail">
	   		  <Label id="address" text="{dummy.address}" />
	   	  </TableViewRow>
	   	  <TableViewRow id="emailprojectdetail_row" Title="emailprojectDetail">
	   		  <Label id="email" text="{dummy.email}" />
	   	  </TableViewRow>
	   	  <TableViewRow id="companyprojectdetail_row" Title="companyprojectDetail">
	   		  <Label id="company" text="{dummy.company}" />
		  </TableViewRow>
	  </TableViewSection>
	  <TableViewSection headerTitle="Pending Invoice">
		  <TableViewRow id="invoiceprojectdetail_row" Title="invoiceprojectDetail">
	   		  <Label id="invoice" text="{dummy.invoice}" />
		  </TableViewRow>
	  </TableViewSection>
	  <TableViewSection headerTitle="Percent Complete & Date Due">
		  <TableViewRow id="percentcompletedetail_row" Title="percentcompleteDetail">
	   		  <Label id="percentcomplete" text="{dummy.percentcomplete}" />
		  </TableViewRow>
		  <TableViewRow id="dateduedetail_row" Title="datedueDetail">
	   		  <Label id="datedue" text="{dummy.datedue}" />
		  </TableViewRow>
	  </TableViewSection>
	  <TableViewSection headerTitle="Next Appointment">
		  <TableViewRow id="nextapptdetail_row" Title="nextapptDetail">
	   		  <Label id="nextappt" text="{dummy.nextappt}" />
		  </TableViewRow>
	  </TableViewSection>
	  <TableViewSection headerTitle="Notes">
		  <TableViewRow id="notesdetail_row" Title="notesDetail">
	   		  <Label id="notes" text="{dummy.notes}" />
		  </TableViewRow>
	  </TableViewSection>
	  </TableView>
  </Window>
</Alloy>


text:
const Promise = require('promise');
const redis = require('./../redis');

module.exports = function (token, email, type) {
    console.log('validateToken('+ token+', '+ email +', '+ type +')');

    return new Promise(function (resolve, reject) {
        const key = 'token.' + type +'.' + token;

        redis
            .get(key)
            .then(value => resolve(value === email))
            .catch(reject);
    });
};


text:
``` sh
    ./benchdnn --rnn [benchdnn-knobs] [rnn-knobs] [rnn-desc] ...
```

where *rnn-knobs* are:

 - `--prop={FWD_D [default], BWD_DW}` -- mkldnn_prop_kind_t. Refer to the common
            glossary in README.md for details.
 - `--cfg={f32 [default], u8u8u8u8, ...}` -- refer to ``Configurations`` below.
 - `--alg={VANILLA_RNN [default], VANILLA_LSTM, VANILLA_GRU, LBR_GRU}`
            -- RNN algorithm.
 - `--direction={left2right [default], right2left, concat, sum}` -- TBA.
 - `--activation={RELU [default], LOGISTIC, TANH}` -- TBA.
 - `--scaling="scale_str"` -- RNN scaling policy, default `""` (no scaling).
            Refer to knobs_attr.md for details.
 - `--mb=N` -- override minibatch size specified in the problem description.
             When set to `0`, use minibatch size as defined by the individual
             problem descriptor. The default is `0`.

and *rnn-desc* is a problem descriptor. The canonical form is:
```
 lXtXmbX_sicX_slcX_dicX_dlcX_nS
```
Here X is an integer number and S is a string (n stands for name).
The special symbol `_` is ignored, so it may be used as a delimiter.

Description of RNN descriptor symbols: TBA.

There are default values for some entities in case they were not specified:
 - l = 1;
 - t = 1;
 - mb = 2;
 - slc = dlc = dic = sic;

## Precision Configurations

`--cfg` option specifies what data type will be used for a problem. It also
defines the data filling strategy. It is implicit for the integer type
saturation. This option also defines the threshold for computation errors.

The table below shows supported name configurations for this driver:

| states | input | dst_iter  | dst_last_layer | cfg         | notes
|:---    |:---   |:---       |:---            |:---         |:---
| f32    | f32   | f32       | f32            | f32         | TBA
| u8     | u8    | u8        | u8             | u8u8u8u8    | TBA
| u8     | u8    | u8        | f32            | u8u8u8f32   | TBA
| f32    | u8    | f32       | u8             | f32u8f32u8  | TBA
| f32    | u8    | f32       | f32            | f32u8f32f32 | TBA
| f16    | f16   | f16       | f16            | f16         | Only for GPU

## Essence of Testing
TBA.

## Examples. TBA.

Run the set of rnn training from input file with default settings:
``` sh
    ./benchdnn --rnn --batch=inputs/rnn/rnn_training
```

More examples with different driver options can be found at
inputs/rnn/test_rnn_***. Examples with different driver descriptors can be found
at inputs/rnn/rnn_***. More examples with different benchdnn options can be
found at driver_conv.md.


text:
package com.ifeng.controller;

import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/myblog")
public class MyBlogController {
	private static Logger logger = Logger.getLogger(DocumentController.class);

	@RequestMapping("/index") /*index 首页*/
	public String Index(HttpServletRequest request,ModelMap map) throws Exception{
		request.setCharacterEncoding("UTF-8");//解决中文乱码问题

		return "index";
	}
}


text:
from .client import Client
from .settings import Settings
from .control_channel import ControlChannel, AuthFailed
from .data_channel import DataChannel
from .common import Channel, InvalidPacketError, AuthFailed, ProtocolLogicError


text:
require 'pricing_definition/behaviours/priceable'
require 'pricing_definition/behaviours/priceable_modifier'

module PricingDefinition
  module Behaviours

  end
end


text:
importScripts("https://preview.babylonjs.com/recast.js");

onmessage = function(messageEvent) {
    // get message datas
    const meshData = messageEvent.data;
    const positions = meshData[0];
    const offset = meshData[1];
    const indices = meshData[2];
    const indicesLength = meshData[3];
    const parameters = meshData[4];

    // initialize Recast
    Recast().then((recast) => {
        // build rc config from parameters
        const rc = new recast.rcConfig();
        rc.cs = parameters.cs;
        rc.ch = parameters.ch;
        rc.borderSize = parameters.borderSize ? parameters.borderSize : 0;
        rc.tileSize = parameters.tileSize ? parameters.tileSize : 0;
        rc.walkableSlopeAngle = parameters.walkableSlopeAngle;
        rc.walkableHeight = parameters.walkableHeight;
        rc.walkableClimb = parameters.walkableClimb;
        rc.walkableRadius = parameters.walkableRadius;
        rc.maxEdgeLen = parameters.maxEdgeLen;
        rc.maxSimplificationError = parameters.maxSimplificationError;
        rc.minRegionArea = parameters.minRegionArea;
        rc.mergeRegionArea = parameters.mergeRegionArea;
        rc.maxVertsPerPoly = parameters.maxVertsPerPoly;
        rc.detailSampleDist = parameters.detailSampleDist;
        rc.detailSampleMaxError = parameters.detailSampleMaxError;

        // create navmesh and build it from message datas
        const navMesh = new recast.NavMesh();
        navMesh.build(positions, offset, indices, indicesLength, rc);

        // get recast uint8array
        const navmeshData = navMesh.getNavmeshData();
        const arrView = new Uint8Array(recast.HEAPU8.buffer, navmeshData.dataPointer, navmeshData.size);
        const ret = new Uint8Array(navmeshData.size);
        ret.set(arrView);
        navMesh.freeNavmeshData(navmeshData);

        // job done, returns the result
        postMessage(ret);
    });
}


text:
API Index
=========

* PAGI
    * PAGI\Application
        * [PAGIApplication](PAGI-Application-PAGIApplication.md)
    * PAGI\CallerId
        * [ICallerId](PAGI-CallerId-ICallerId.md)
        * PAGI\CallerId\Impl
            * [CallerIdFacade](PAGI-CallerId-Impl-CallerIdFacade.md)
    * PAGI\CallSpool
        * [CallFile](PAGI-CallSpool-CallFile.md)
        * PAGI\CallSpool\Exception
            * [CallSpoolException](PAGI-CallSpool-Exception-CallSpoolException.md)
        * [ICallSpool](PAGI-CallSpool-ICallSpool.md)
        * PAGI\CallSpool\Impl
            * [CallSpoolImpl](PAGI-CallSpool-Impl-CallSpoolImpl.md)
    * PAGI\CDR
        * [ICDR](PAGI-CDR-ICDR.md)
        * PAGI\CDR\Impl
            * [CDRFacade](PAGI-CDR-Impl-CDRFacade.md)
    * PAGI\ChannelVariables
        * [IChannelVariables](PAGI-ChannelVariables-IChannelVariables.md)
        * PAGI\ChannelVariables\Impl
            * [ChannelVariablesFacade](PAGI-ChannelVariables-Impl-ChannelVariablesFacade.md)
    * PAGI\Client
        * [AbstractClient](PAGI-Client-AbstractClient.md)
        * [ChannelStatus](PAGI-Client-ChannelStatus.md)
        * [IClient](PAGI-Client-IClient.md)
        * PAGI\Client\Impl
            * [ClientImpl](PAGI-Client-Impl-ClientImpl.md)
            * [MockedClientImpl](PAGI-Client-Impl-MockedClientImpl.md)
        * PAGI\Client\Result
            * [AmdResult](PAGI-Client-Result-AmdResult.md)
            * [DataReadResult](PAGI-Client-Result-DataReadResult.md)
            * [DialResult](PAGI-Client-Result-DialResult.md)
            * [DigitReadResult](PAGI-Client-Result-DigitReadResult.md)
            * [ExecResult](PAGI-Client-Result-ExecResult.md)
            * [FaxResult](PAGI-Client-Result-FaxResult.md)
            * [IReadResult](PAGI-Client-Result-IReadResult.md)
            * [IResult](PAGI-Client-Result-IResult.md)
            * [PlayResult](PAGI-Client-Result-PlayResult.md)
            * [ReadResultDecorator](PAGI-Client-Result-ReadResultDecorator.md)
            * [RecordResult](PAGI-Client-Result-RecordResult.md)
            * [Result](PAGI-Client-Result-Result.md)
            * [ResultDecorator](PAGI-Client-Result-ResultDecorator.md)
    * PAGI\DialDescriptor
        * [DAHDIDialDescriptor](PAGI-DialDescriptor-DAHDIDialDescriptor.md)
        * [DialDescriptor](PAGI-DialDescriptor-DialDescriptor.md)
        * [LocalDialDescriptor](PAGI-DialDescriptor-LocalDialDescriptor.md)
        * [SIPDialDescriptor](PAGI-DialDescriptor-SIPDialDescriptor.md)
    * PAGI\Exception
        * [ChannelDownException](PAGI-Exception-ChannelDownException.md)
        * [DatabaseInvalidEntryException](PAGI-Exception-DatabaseInvalidEntryException.md)
        * [ExecuteCommandException](PAGI-Exception-ExecuteCommandException.md)
        * [InvalidCommandException](PAGI-Exception-InvalidCommandException.md)
        * [MockedException](PAGI-Exception-MockedException.md)
        * [PAGIException](PAGI-Exception-PAGIException.md)
        * [RecordException](PAGI-Exception-RecordException.md)
        * [SoundFileException](PAGI-Exception-SoundFileException.md)
    * PAGI\Logger
        * PAGI\Logger\Asterisk
            * [IAsteriskLogger](PAGI-Logger-Asterisk-IAsteriskLogger.md)
            * PAGI\Logger\Asterisk\Impl
                * [AsteriskLoggerImpl](PAGI-Logger-Asterisk-Impl-AsteriskLoggerImpl.md)
                * [MockedAsteriskLoggerImpl](PAGI-Logger-Asterisk-Impl-MockedAsteriskLoggerImpl.md)
    * PAGI\Node
        * PAGI\Node\Exception
            * [NodeException](PAGI-Node-Exception-NodeException.md)
        * [MockedNode](PAGI-Node-MockedNode.md)
        * [Node](PAGI-Node-Node.md)
        * [NodeActionCommand](PAGI-Node-NodeActionCommand.md)
        * [NodeController](PAGI-Node-NodeController.md)


text:
using System;
using System.Numerics;

namespace Fractions {
    public partial struct Fraction
    {
        /// <summary>
        /// Create a fraction with <paramref name="numerator"/>, <paramref name="denominator"/> and the fraction' <paramref name="state"/>.
        /// Warning: if you use unreduced values combined with a state of <see cref="FractionState.IsNormalized"/>
        /// you will get wrong results when working with the fraction value.
        /// </summary>
        /// <param name="numerator"></param>
        /// <param name="denominator"></param>
        /// <param name="state"></param>
        private Fraction(BigInteger numerator, BigInteger denominator, FractionState state) {
            _numerator = numerator;
            _denominator = denominator;
            _state = state;
        }

        /// <summary>
        /// Creates a normalized (reduced/simplified) fraction using <paramref name="numerator"/> and <paramref name="denominator"/>.
        /// </summary>
        /// <param name="numerator">Numerator</param>
        /// <param name="denominator">Denominator</param>
        public Fraction(BigInteger numerator, BigInteger denominator)
            : this(numerator, denominator, true) { }

        /// <summary>
        /// Creates a normalized (reduced/simplified) or unnormalized fraction using <paramref name="numerator"/> and <paramref name="denominator"/>.
        /// </summary>
        /// <param name="numerator">Numerator</param>
        /// <param name="denominator">Denominator</param>
        /// <param name="normalize">If <c>true</c> the fraction will be created as reduced/simplified fraction.
        /// This is recommended, especially if your applications requires that the results of the equality methods <see cref="object.Equals(object)"/>
        /// and <see cref="IComparable.CompareTo"/> are always the same. (1/2 != 2/4)</param>
        public Fraction(BigInteger numerator, BigInteger denominator, bool normalize) {
            if (normalize) {
                this = GetReducedFraction(numerator, denominator);
                return;
            }

            _state = numerator.IsZero && denominator.IsZero
                ? FractionState.IsNormalized
                : FractionState.Unknown;

            _numerator = numerator;
            _denominator = denominator;
        }

        /// <summary>
        /// Creates a normalized fraction using a signed 32bit integer.
        /// </summary>
        /// <param name="numerator">integer value that will be used for the numerator. The denominator will be 1.</param>
        public Fraction(int numerator) {
            _numerator = new BigInteger(numerator);
            _denominator = numerator != 0 ? BigInteger.One : BigInteger.Zero;
            _state = FractionState.IsNormalized;
        }

        /// <summary>
        /// Creates a normalized fraction using a signed 64bit integer.
        /// </summary>
        /// <param name="numerator">integer value that will be used for the numerator. The denominator will be 1.</param>
        public Fraction(long numerator) {
            _numerator = new BigInteger(numerator);
            _denominator = numerator != 0 ? BigInteger.One : BigInteger.Zero;
            _state = FractionState.IsNormalized;
        }

        /// <summary>
        /// Creates a normalized fraction using a unsigned 32bit integer.
        /// </summary>
        /// <param name="numerator">integer value that will be used for the numerator. The denominator will be 1.</param>
        public Fraction(uint numerator) {
            _numerator = new BigInteger(numerator);
            _denominator = numerator != 0 ? BigInteger.One : BigInteger.Zero;
            _state = FractionState.IsNormalized;
        }

        /// <summary>
        /// Creates a normalized fraction using a unsigned 64bit integer.
        /// </summary>
        /// <param name="numerator">integer value that will be used for the numerator. The denominator will be 1.</param>
        public Fraction(ulong numerator) {
            _numerator = new BigInteger(numerator);
            _denominator = numerator != 0 ? BigInteger.One : BigInteger.Zero;
            _state = FractionState.IsNormalized;
        }

        /// <summary>
        /// Creates a normalized fraction using a big integer.
        /// </summary>
        /// <param name="numerator">big integer value that will be used for the numerator. The denominator will be 1.</param>
        public Fraction(BigInteger numerator) {
            _numerator = numerator;
            _denominator = numerator.IsZero ? BigInteger.Zero : BigInteger.One;
            _state = FractionState.IsNormalized;
        }

        /// <summary>
        /// Creates a normalized fraction using a 64bit floating point value (double).
        /// The value will not be rounded therefore you will probably get huge numbers as numerator und denominator.
        /// <see cref="double"/> values are not able to store simple rational numbers like 0.2 or 0.3 - so please
        /// don't be worried if the fraction looks weird. For more information visit
        /// http://en.wikipedia.org/wiki/Floating_point
        /// </summary>
        /// <param name="value">Floating point value.</param>
        public Fraction(double value) {
            this = FromDouble(value);
        }

        /// <summary>
        /// Creates a normalized fraction using a 128bit decimal value (decimal).
        /// </summary>
        /// <param name="value">Floating point value.</param>
        public Fraction(decimal value) {
            this = FromDecimal(value);
        }
    }
}


text:
BEGIN;

ALTER TABLE paths ADD COLUMN created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE paths ADD COLUMN updated_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP;
CREATE TRIGGER set_updated_at BEFORE INSERT OR UPDATE ON paths
     FOR EACH ROW EXECUTE PROCEDURE trigger_modify_updated_at();

END;


text:
#ifndef __SENSOR_MCP9808_H__
#define __SENSOR_MCP9808_H__

#include <errno.h>

#include <stdint.h>
#include <device.h>
#include <sensor.h>
#include <misc/util.h>
#include <gpio.h>
#include <misc/nano_work.h>

#define MCP9808_REG_CONFIG		0x01
#define MCP9808_REG_UPPER_LIMIT		0x02
#define MCP9808_REG_LOWER_LIMIT		0x03
#define MCP9808_REG_CRITICAL		0x04
#define MCP9808_REG_TEMP_AMB		0x05

#define MCP9808_ALERT_INT		BIT(0)
#define MCP9808_ALERT_CNT		BIT(3)
#define MCP9808_INT_CLEAR		BIT(5)

#define MCP9808_SIGN_BIT		BIT(12)
#define MCP9808_TEMP_INT_MASK		0x0ff0
#define MCP9808_TEMP_INT_SHIFT		4
#define MCP9808_TEMP_FRAC_MASK		0x000f

#define MCP9808_TEMP_MAX		0xffc

struct mcp9808_data {
	struct device *i2c_master;
	uint16_t i2c_slave_addr;

	uint16_t reg_val;

	struct gpio_callback gpio_cb;

#ifdef CONFIG_MCP9808_TRIGGER_OWN_FIBER
	struct nano_sem sem;
#endif

#ifdef CONFIG_MCP9808_TRIGGER_GLOBAL_FIBER
	struct nano_work work;
	struct device *dev;
#endif

#ifdef CONFIG_MCP9808_TRIGGER
	struct sensor_trigger trig;
	sensor_trigger_handler_t trigger_handler;
#endif
};

int mcp9808_reg_read(struct mcp9808_data *data, uint8_t reg, uint16_t *val);

#ifdef CONFIG_MCP9808_TRIGGER
int mcp9808_attr_set(struct device *dev, enum sensor_channel chan,
		     enum sensor_attribute attr,
		     const struct sensor_value *val);
int mcp9808_trigger_set(struct device *dev,
			const struct sensor_trigger *trig,
			sensor_trigger_handler_t handler);
void mcp9808_setup_interrupt(struct device *dev);
#else
static inline int mcp9808_attr_set(struct device *dev,
				   enum sensor_channel chan,
				   enum sensor_attribute attr,
				   const struct sensor_value *val)
{
	return -ENOTSUP;
}

static inline int mcp9808_trigger_set(struct device *dev,
				      const struct sensor_trigger *trig,
				      sensor_trigger_handler_t handler)
{
	return -ENOTSUP;
}

static void mcp9808_setup_interrupt(struct device *dev)
{
}
#endif /* CONFIG_MCP9808_TRIGGER */

#define SYS_LOG_DOMAIN "MCP9808"
#define SYS_LOG_LEVEL CONFIG_MCP9808_SYS_LOG_LEVEL
#include <misc/sys_log.h>
#endif /* __SENSOR_MCP9808_H__ */


text:
app.QueueCollection = Backbone.Collection.extend({
    model: app.QueueModel,

    url: app.queuesDetailsUrl,

    comparator: function(item) {
        return item.get('queueInfo').queueId;
    }
});


text:
import React, { Component, ComponentClass } from 'react';
import * as propTypes from 'prop-types';
import { Dimensions, NativeModules, StatusBar } from 'react-native';
import { RouteComponentProps } from 'react-router-native';
import { Location } from 'history';
import { Body, Button, Container, Drawer, Header, Icon, Left, Right, Title } from 'native-base';
import { inject, observer } from 'mobx-react/native';
import { IGlobalUIStore } from 'native/stores/ui';

const { StatusBarManager } = NativeModules;
const deviceHeight = Dimensions.get('window').height;

export interface IBaseProps extends RouteComponentProps<any> {
	globalUIStore: IGlobalUIStore;
	noDrawer?: boolean;
}

export interface IPBaseProps {
	location: Location;
	globalUIStore?: IGlobalUIStore;
	noDrawer?: boolean;
}

class BaseContainer extends Component<IBaseProps, void> {
	public static displayName = 'BaseRaw';
	public static propTypes = {
		globalUIStore:  propTypes.object.isRequired,
		children:  propTypes.node.isRequired,
	};

	public render(): JSX.Element | null {
		const { children, noDrawer, globalUIStore } = this.props;
		return (
			<Drawer open={globalUIStore.drawerOpen} onClose={globalUIStore.closeDrawer}>
				<Container style={{ height: deviceHeight - StatusBarManager.HEIGHT, marginTop: StatusBarManager.HEIGHT }}>
					<StatusBar translucent backgroundColor="rgba(0, 0, 0, .2)" />
					<Header>
						{
							noDrawer ? null : (
								<Left>
									<Button transparent onPress={globalUIStore.openDrawer}>
										<Icon name="menu" />
									</Button>
								</Left>
							)
						}
						<Body>
							<Title>{globalUIStore.title}</Title>
						</Body>
						<Right />
					</Header>
					{children}
				</Container>
			</Drawer>
		);
	}
}

const base: ComponentClass<IPBaseProps> = inject('globalUIStore')(observer(BaseContainer));
base.displayName = 'Base';

export { BaseContainer as BaseRaw };
export default base;


text:
.class Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;
.super Ljava/io/InputStream;
.source "SerializedFrame.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/filterfw/core/SerializedFrame;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "DirectByteInputStream"
.end annotation

# instance fields
.field private mBuffer:[B

.field private mPos:I

.field private mSize:I

.field final synthetic this$0:Landroid/filterfw/core/SerializedFrame;

# direct methods
.method public constructor <init>(Landroid/filterfw/core/SerializedFrame;[BI)V
    .locals 1
    .parameter
    .parameter "buffer"
    .parameter "size"

    .prologue
    .line 128
    iput-object p1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->this$0:Landroid/filterfw/core/SerializedFrame;

    invoke-direct {p0}, Ljava/io/InputStream;-><init>()V

    .line 125
    const/4 v0, 0x0

    iput v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    .line 129
    iput-object p2, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mBuffer:[B

    .line 130
    iput p3, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    .line 131
    return-void
.end method

# virtual methods
.method public final available()I
    .locals 2

    .prologue
    .line 135
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    sub-int/2addr v0, v1

    return v0
.end method

.method public final read()I
    .locals 3

    .prologue
    .line 140
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    if-ge v0, v1, :cond_0

    iget-object v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mBuffer:[B

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    add-int/lit8 v2, v1, 0x1

    iput v2, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    aget-byte v0, v0, v1

    and-int/lit16 v0, v0, 0xff

    :goto_0
    return v0

    :cond_0
    const/4 v0, -0x1

    goto :goto_0
.end method

.method public final read([BII)I
    .locals 2
    .parameter "b"
    .parameter "off"
    .parameter "len"

    .prologue
    .line 145
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    if-lt v0, v1, :cond_0

    .line 146
    const/4 v0, -0x1

    .line 153
    :goto_0
    return v0

    .line 148
    :cond_0
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    add-int/2addr v0, p3

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    if-le v0, v1, :cond_1

    .line 149
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    sub-int p3, v0, v1

    .line 151
    :cond_1
    iget-object v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mBuffer:[B

    iget v1, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    invoke-static {v0, v1, p1, p2, p3}, Ljava/lang/System;->arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V

    .line 152
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    add-int/2addr v0, p3

    iput v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    move v0, p3

    .line 153
    goto :goto_0
.end method

.method public final skip(J)J
    .locals 6
    .parameter "n"

    .prologue
    const-wide/16 v0, 0x0

    .line 158
    iget v2, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    int-to-long v2, v2

    add-long/2addr v2, p1

    iget v4, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    int-to-long v4, v4

    cmp-long v2, v2, v4

    if-lez v2, :cond_0

    .line 159
    iget v2, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mSize:I

    iget v3, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    sub-int/2addr v2, v3

    int-to-long p1, v2

    .line 161
    :cond_0
    cmp-long v2, p1, v0

    if-gez v2, :cond_1

    move-wide p1, v0

    .line 165
    .end local p1
    :goto_0
    return-wide p1

    .line 164
    .restart local p1
    :cond_1
    iget v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    int-to-long v0, v0

    add-long/2addr v0, p1

    long-to-int v0, v0

    iput v0, p0, Landroid/filterfw/core/SerializedFrame$DirectByteInputStream;->mPos:I

    goto :goto_0
.end method


text:
Dropdown is a simple directive which will toggle a dropdown menu on click or programmatically.
You can either use `is-open` to toggle or add inside a `<a dropdown-toggle>` element to toggle it when is clicked.
There is also the `on-toggle(open)` optional expression fired when dropdown changes state.

Add `dropdown-append-to-body` to the `dropdown` element to append to the inner `dropdown-menu` to the body.
This is useful when the dropdown button is inside a div with `overflow: hidden`, and the menu would otherwise be hidden.

By default the dropdown will automatically close if any of its elements is clicked, you can change this behavior by setting the `auto-close` option as follows:

  * `always` - (Default) automatically closes the dropdown when any of its elements is clicked.
  * `outsideClick` - closes the dropdown automatically only when the user clicks any element outside the dropdown.
  * `disabled` - disables the auto close. You can then control the open/close status of the dropdown manually, by using `is-open`. Please notice that the dropdown will still close if the toggle is clicked, the `esc` key is pressed or another dropdown is open.


text:
package com.vmware.vim25.mo.samples.network;

import java.net.URL;

import com.vmware.vim25.HostFirewallDefaultPolicy;
import com.vmware.vim25.HostFirewallInfo;
import com.vmware.vim25.HostFirewallRule;
import com.vmware.vim25.HostFirewallRuleset;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.HostFirewallSystem;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ServiceInstance;

/**
 * http://vijava.sf.net
 * @author Steve Jin
 */

public class TurnOnFirewallPolicy
{
  public static void main(String[] args) throws Exception
  {
    if(args.length != 4)
    {
      System.out.println("Usage: java TurnOnFirewallPolicy " +
          "<url> <username> <password> <hostname>");
      return;
    }

    ServiceInstance si = new ServiceInstance(
        new URL(args[0]), args[1], args[2], true);

    String hostname = args[3];
    Folder rootFolder = si.getRootFolder();
    HostSystem host = null;
    host = (HostSystem) new InventoryNavigator(
        rootFolder).searchManagedEntity("HostSystem", hostname);

    if(host==null)
    {
      System.out.println("Cannot find the host:" + hostname);
      si.getServerConnection().logout();
      return;
    }

    HostFirewallSystem hss = host.getHostFirewallSystem();

    HostFirewallInfo hsi = hss.getFirewallInfo();

    System.out.println("Default Firewall Policy:");
    HostFirewallDefaultPolicy defPolicy = hsi.getDefaultPolicy();
    System.out.println("IncomingBlocked:"
        + defPolicy.getIncomingBlocked());
    System.out.println("OutgoingBlocked:"
        + defPolicy.getOutgoingBlocked());

    HostFirewallRuleset[] rs = hsi.getRuleset();
    for(int i=0; rs!=null && i<rs.length; i++)
    {
      printRuleSet(rs[i]);
      if(!rs[i].isEnabled())
      {
        hss.enableRuleset(rs[i].getKey());
      }
    }
  }

  static void printRuleSet(HostFirewallRuleset rule)
  {
    System.out.println("\nKey:" + rule.getKey());
    System.out.println("Label:" + rule.getLabel());
    System.out.println("Required:" + rule.isRequired());
    System.out.println("Service:" + rule.getService());

    System.out.print("Rules:");
    HostFirewallRule[] rules = rule.getRule();
    for(int j=0; rules!=null && j<rules.length; j++)
    {
      System.out.println("Protocol:" + rules[j].getProtocol());
      System.out.println("Port:" + rules[j].getPort());
      System.out.println("Direction:" + rules[j].getDirection());
      System.out.println("EndPort:" + rules[j].getEndPort());
    }
    System.out.println("Enabled:" + rule.isEnabled());
  }
}


text:
{{ partial "head" . }}

{{ partial "nav-home" . }}

Releasing without the guesswork

							Avoid the sleepless nights and pager duty panic with release management that gives you
							control over software delivery every step of the way

							Book a test drive

Shorten delivery cycles

Make software run smoother and business move faster by continuously validating releases.

Keep projects on track

IT projects are full of obstacles. Benefit from a managed process to save approval chaos in your release train.

Make IT a business driver

							Whether or not you believe that every company should be a software company, ensure your delivery process delivers business outcomes.

Test in production – the only way that works for cloud

						Vamp lets you re-gain control over your software delivery lifecycle. Depend on automated releasing of microservices simply, safely and at scale. We are the only provider that offers a step-by-step analytics-based approach to releasing software in the only way that works for cloud – live in production.

How Vamp supports you

Test in production

Benefit from precisely-targeted user segments and phased release plans to control which users see what features and when.

Smart Release Strategies

Release when you want, day or night. Let your teams deploy when they like. Your users only see a feature when it's business-ready.

Safety first

No buttons to push. Sleep soundly, secure in the knowledge there is an automated safety net in place to protect you and your users.

Managed Service

Straight-forward experience. You manage your services. We manage Vamp, either in our cloud or yours.

Multi-cloud

								Use your favourite Kubernetes, cloud-provider managed Kubernetes service or BYOC (bring your own cluster). We support Google Cloud, AWS, Azure and hybrid-cloud.

360 observability

Visualise, centrally-manage and control your entire release landscape across multiple teams and multiple clusters with dashboards and ChatOps support.

Satisfy product managers with 60% faster time-to-market

Keep development teams happy with 30% faster coding times

Keep all your teams happy with 99.99% lower pager panic

Proven panic prevention track record

						146,000

releases

						7,300

automated rollbacks

						438,000

minutes saved on incident response

...and counting...

Explore the cost benefits of analytics-based software releasing

						At Vamp we help customers put their DevOps strategy to work by adding an average of 30% business value to their current setup. Take this two minute survey to find out how increasing your DevOps maturity with release automation can increase your DevOps ROI.

	{{ partial "roi-calculator-bot-row" . }}

Expert advice

					Book a test drive

						Tell us where you are on your cloud and microservice journey and we'll tell you your next steps.

						You can ask us anything you like, but our strongest topics are
						cloud, microservices and of course - release management.

You'll be in direct contact with experts only

We get it, this stuff is complicated, wouldn't it be refreshing if you could talk to someone who speaks your language? Our experts are engineers, but they like to translate technology to people and business too.

Bring your own containers

After the initial conversation, if you like what you hear then you can book a longer test drive with some of your own microservices. This works best if you have two services with a dependency. It could be a front-end service and a backend service or two backend services.

We don't claim silver bullets, just sound advice

{{ partial "footer" .}}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Ploeh.AutoFixture.Dsl;
using Ploeh.AutoFixture.Kernel;

namespace Ploeh.AutoFixture
{
    ///
    /// Provides anonymous object creation services.
    ///
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The main purpose of Fixture isn't to be a collection of anything. That it implements IEnumerable is just a coincidental side effect of how graphs are implemented in AutoFixture. Besides, fixing this CA error would be a breaking change.")]
    public class Fixture : IFixture, IEnumerable<ISpecimenBuilder>
    {
        private SingletonSpecimenBuilderNodeStackAdapterCollection behaviors;
        private SpecimenBuilderNodeAdapterCollection customizer;
        private readonly ISpecimenBuilder engine;
        private SpecimenBuilderNodeAdapterCollection residueCollector;
        private readonly MultipleRelay multiple;

        private ISpecimenBuilderNode graph;

        ///
        /// Initializes a new instance of the <see cref="Fixture"/> class.
        ///
        public Fixture()
            : this(new DefaultEngineParts())
        {
        }

        ///
        /// Initializes a new instance of the <see cref="Fixture"/> class with the supplied engine
        /// parts.
        ///
        /// <param name="engineParts">The engine parts.</param>
        public Fixture(DefaultRelays engineParts)
            : this(new CompositeSpecimenBuilder(engineParts), new MultipleRelay())
        {
        }

        ///
        /// Initializes a new instance of the <see cref="Fixture"/> class with the supplied engine
        /// and a definition of what 'many' means.
        ///
        /// <param name="engine">The engine.</param>
        /// <param name="multiple">The definition and implementation of 'many'.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is the Façade that binds everything else together, so being coupled to many other types must follow.")]
        public Fixture(ISpecimenBuilder engine, MultipleRelay multiple)
        {
            if (engine == null)
            {
                throw new ArgumentNullException("engine");
            }
            if (multiple == null)
            {
                throw new ArgumentNullException("multiple");
            }

            this.engine = engine;
            this.multiple = multiple;

            this.graph =
                new BehaviorRoot(
                    new TerminatingWithPathSpecimenBuilder(new TracingBuilder(new CompositeSpecimenBuilder(
                        new CustomizationNode(
                            new CompositeSpecimenBuilder(
                                new FilteringSpecimenBuilder(
                                    new FixedBuilder(
                                        this),
                                    new OrRequestSpecification(
                                        new ExactTypeSpecification(
                                            typeof (Fixture)),
                                        new ExactTypeSpecification(
                                            typeof (IFixture)),
                                        new ExactTypeSpecification(
                                            typeof (ISpecimenBuilder)))),
                                new StableFiniteSequenceRelay(),
                                new FilteringSpecimenBuilder(
                                    new Postprocessor(
                                        new MethodInvoker(
                                            new ModestConstructorQuery()),
                                        new DictionaryFiller()),
                                    new DictionarySpecification()),
                                new FilteringSpecimenBuilder(
                                    new MethodInvoker(
                                        new EnumerableFavoringConstructorQuery()),
                                    new ObservableCollectionSpecification()),
                                new FilteringSpecimenBuilder(
                                    new MethodInvoker(
                                        new ListFavoringConstructorQuery()),
                                    new CollectionSpecification()),
                                new FilteringSpecimenBuilder(
                                    new MethodInvoker(
                                        new EnumerableFavoringConstructorQuery()),
                                    new HashSetSpecification()),
                                new FilteringSpecimenBuilder(
                                    new MethodInvoker(
                                        new EnumerableFavoringConstructorQuery()),
                                    new ListSpecification()),
                                new FilteringSpecimenBuilder(
                                    new MethodInvoker(
                                        new ModestConstructorQuery()),
                                    new NullableEnumRequestSpecification()),
                                new EnumGenerator())),
                        new Postprocessor(
                            new AutoPropertiesTarget(
                                new CompositeSpecimenBuilder(
                                    engine,
                                    multiple)),
                            new AutoPropertiesCommand(),
                            new AnyTypeSpecification()),
                        new ResidueCollectorNode(
                            new CompositeSpecimenBuilder(
                                new DictionaryRelay(),
                                new CollectionRelay(),
                                new ListRelay(),
                                new EnumerableRelay())),
                        new FilteringSpecimenBuilder(
                            new MutableValueTypeWarningThrower(),
                            new AndRequestSpecification(
                                new ValueTypeSpecification(),
                                new NoConstructorsSpecification()))))));

            this.UpdateCustomizer();
            this.UpdateResidueCollector();
            this.UpdateBehaviors(new ISpecimenBuilderTransformation[0]);

            this.behaviors.Add(new ThrowingRecursionBehavior());
        }

        ///
        /// Gets the behaviors that wrap around the rest of the graph.
        ///
        public IList<ISpecimenBuilderTransformation> Behaviors
        {
            get { return this.behaviors; }
        }

        ///
        /// Gets the customizations that intercept the <see cref="Engine"/>.
        ///
        /// <remarks>
        /// <para>
        /// Any <see cref="ISpecimenBuilder"/> in this list are invoked before
        /// <see cref="Engine"/>, giving them a chance to intercept a request and resolve it before
        /// the Engine.
        /// </para>
        /// <para>
        /// <see cref="Customize{T}"/> places resulting customizations in this list.
        /// </para>
        /// </remarks>
        /// <seealso cref="Engine"/>
        /// <seealso cref="ResidueCollectors"/>
        public IList<ISpecimenBuilder> Customizations
        {
            get { return this.customizer; }
        }

        ///
        /// Gets the core engine of the <see cref="Fixture"/> instance.
        ///
        /// <remarks>
        /// <para>
        /// This is the core engine that drives a <see cref="Fixture"/> instance. Even with no
        /// <see cref="Customizations"/> or <see cref="ResidueCollectors"/>, the
        /// <see cref="Engine"/> should be capably of resolving a wide range of different requests,
        /// based on conventions.
        /// </para>
        /// </remarks>
        /// <see cref="Customizations"/>
        /// <see cref="ResidueCollectors"/>
        public ISpecimenBuilder Engine
        {
            get { return this.engine; }
        }

        ///
        /// Gets or sets if writable properties should generally be assigned a value when
        /// generating an anonymous object.
        ///
        /// <remarks>
        /// <para>
        /// The default value is false.
        /// </para>
        /// </remarks>
        public bool OmitAutoProperties
        {
            get
            {
                return !this.graph.Parents(b => b is AutoPropertiesTarget).Any(n => n is Postprocessor);
            }
            set
            {
                if (value == this.OmitAutoProperties)
                    return;

                var g = this.graph;
                if (value)
                {
                    foreach (var p in this.graph.Parents(b => b is AutoPropertiesTarget))
                    {
                        foreach (var b in p)
                        {
                            var aptn = b as AutoPropertiesTarget;
                            if (aptn != null)
                                g = g.ReplaceNodes(with: aptn, when: p.Equals);
                        }
                    }
                }
                else
                {
                    foreach (var p in this.graph.Parents(b => b is AutoPropertiesTarget))
                    {
                        var pps = p
                            .Select(b => new Postprocessor(
                                b,
                                new AutoPropertiesCommand(),
                                new AnyTypeSpecification()))
                            .Cast<ISpecimenBuilder>();
                        g = g.ReplaceNodes(with: pps, when: p.Equals);
                    }
                }
                this.OnGraphChanged(this, new SpecimenBuilderNodeEventArgs(g));
            }
        }

        ///
        /// Gets or sets a number that controls how many objects are created when a
        /// <see cref="Fixture"/> creates more than one anonymous objects.
        ///
        /// <remarks>
        /// <para>
        /// The default value is 3.
        /// </para>
        /// </remarks>
        /// <seealso cref="CollectionFiller.AddManyTo{T}(IFixture, ICollection{T})" />
        /// <seealso cref="CollectionFiller.AddManyTo{T}(IFixture, ICollection{T}, Func{T})" />
        /// <seealso cref="Repeat"/>
        public int RepeatCount
        {
            get { return this.multiple.Count; }
            set { this.multiple.Count = value; }
        }

        ///
        /// Gets the residue collectors that can be used to handle requests that neither the
        /// <see cref="Customizations"/> nor <see cref="Engine"/> could handle.
        ///
        /// <remarks>
        /// <para>
        /// These <see cref="ISpecimenBuilder"/> instances will be invoked if no previous builder
        /// could resolve a request. This gives you the opportunity to define fallback strategies
        /// to deal with unresolved requests.
        /// </para>
        /// </remarks>
        public IList<ISpecimenBuilder> ResidueCollectors
        {
            get { return this.residueCollector; }
        }

        ///
        /// Customizes the creation algorithm for a single object, effectively turning off all
        /// Customizations on the <see cref="IFixture"/>.
        ///
        /// <typeparam name="T">
        /// The type of object for which the algorithm should be customized.
        /// </typeparam>
        /// <returns>
        /// A <see cref="ICustomizationComposer{T}"/> that can be used to customize the creation
        /// algorithm before creating the object.
        /// </returns>
        /// <remarks>
        /// <para>
        /// The Build method kicks off a Fluent API which is usually completed by invoking
        /// <see cref="SpecimenFactory.Create{T}(IPostprocessComposer{T})"/> on the method
        /// chain.
        /// </para>
        /// <para>
        /// Note that the Build method chain is best understood as a one-off Customization. It
        /// bypasses all Customizations on the <see cref="Fixture"/> instance. Instead, it allows
        /// fine-grained control when building a specific specimen. However, in most cases, adding
        /// a convention-based <see cref="ICustomization"/> is a better, more flexible option.
        /// </para>
        /// </remarks>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Although this CA warning should never be suppressed, this particular usage scenario has been discussed and accepted on the FxCop DL.")]
        public ICustomizationComposer<T> Build<T>()
        {
            var g = this.graph.ReplaceNodes(
                with: n => new CompositeSpecimenBuilder(
                    SpecimenBuilderNodeFactory.CreateComposer<T>().WithAutoProperties(this.EnableAutoProperties),
                    n),
                when: n => n is BehaviorRoot);

            return new CompositeNodeComposer<T>(g);
        }

        ///
        /// Applies a customization.
        ///
        /// <param name="customization">The customization to apply.</param>
        /// <returns>
        /// The current instance.
        /// </returns>
        public IFixture Customize(ICustomization customization)
        {
            if (customization == null)
            {
                throw new ArgumentNullException("customization");
            }

            customization.Customize(this);
            return this;
        }

        ///
        /// Customizes the creation algorithm for all objects of a given type.
        ///
        /// <typeparam name="T">The type of object to customize.</typeparam>
        /// <param name="composerTransformation">
        /// A function that customizes a given <see cref="ICustomizationComposer{T}"/> and returns
        /// the modified composer.
        /// </param>
        /// <remarks>
        /// <para>
        /// The resulting <see cref="ISpecimenBuilder"/> is added to <see cref="Customizations"/>.
        /// </para>
        /// </remarks>
        public void Customize<T>(Func<ICustomizationComposer<T>, ISpecimenBuilder> composerTransformation)
        {
            if (composerTransformation == null)
            {
                throw new ArgumentNullException("composerTransformation");
            }

            var c = composerTransformation(SpecimenBuilderNodeFactory.CreateComposer<T>().WithAutoProperties(this.EnableAutoProperties));
            this.customizer.Insert(0, c);
        }

        ///
        /// Repeats a function many times.
        ///
        /// <typeparam name="T">
        /// The type of object that <paramref name="function"/> creates.
        /// </typeparam>
        /// <param name="function">
        /// A function that creates an instance of <typeparamref name="T"/>.
        /// </param>
        /// <returns>A sequence of objects created by <paramref name="function"/>.</returns>
        /// <remarks>
        /// <para>
        /// The number of times <paramref name="function"/> is invoked is determined by
        /// <see cref="RepeatCount"/>.
        /// </para>
        /// </remarks>
        public IEnumerable<T> Repeat<T>(Func<T> function)
        {
            return from f in Enumerable.Repeat(function, this.RepeatCount)
                   select f();
        }

        /// Creates a new specimen based on a request.
        /// <param name="request">
        /// The request that describes what to create.
        /// </param>
        /// <param name="context">
        /// A context that can be used to create other specimens.
        /// </param>
        /// <returns>
        /// The requested specimen if possible; otherwise an exception is
        /// thrown.
        /// </returns>
        /// <remarks>
        /// <para>
        /// The <paramref name="request" /> can be any object, but will often
        /// be a <see cref="Type" /> or other
        /// <see cref="System.Reflection.MemberInfo" /> instances.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            return this.graph.Create(request, context);
        }

        ///
        /// Gets an enumerator over the internal specimen builders used to
        /// create objects.
        ///
        /// <returns>
        /// An enumerator over the internal specimen builders used to create
        /// objects.
        /// </returns>
        public IEnumerator<ISpecimenBuilder> GetEnumerator()
        {
            yield return this.graph;
        }

        /// Returns an enumerator that iterates through a collection.
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
        /// </returns>
        /// <seealso cref="GetEnumerator()" />
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        private bool EnableAutoProperties
        {
            get { return !this.OmitAutoProperties; }
        }

        private void OnGraphChanged(object sender, SpecimenBuilderNodeEventArgs e)
        {
            var transformations = this.Behaviors.ToArray();

            this.graph = e.Graph;

            this.UpdateCustomizer();
            this.UpdateResidueCollector();
            this.UpdateBehaviors(transformations);
        }

        private void UpdateCustomizer()
        {
            this.customizer =
                new SpecimenBuilderNodeAdapterCollection(
                    this.graph,
                    n => n is CustomizationNode);
            this.customizer.GraphChanged += this.OnGraphChanged;
        }

        private void UpdateResidueCollector()
        {
            this.residueCollector =
                new SpecimenBuilderNodeAdapterCollection(
                    this.graph,
                    n => n is ResidueCollectorNode);
            this.residueCollector.GraphChanged += this.OnGraphChanged;
        }

        private void UpdateBehaviors(ISpecimenBuilderTransformation[] transformations)
        {
            this.behaviors = new SingletonSpecimenBuilderNodeStackAdapterCollection(this.graph, n => n is BehaviorRoot, transformations);
            this.behaviors.GraphChanged += this.OnGraphChanged;
        }
    }
}


text:
import json

from django.test import TestCase
from django.test.client import Client

class SimpleTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_mona_lisa_1(self):
        # TODO(sghiaus): Change test images to png.
        mona_lisa_1 = open("detection_app/testdata/MonaLisa1.png", "rb")
        mona_lisa_1_response = self.client.post('/identify_painting/', {
            'image': mona_lisa_1,
            'x': '2000',
            'y': '1350',
        })
        self.assertEqual(200, mona_lisa_1_response.status_code)
        mona_lisa_1_response_json = json.loads(mona_lisa_1_response.content)
        self.assertEqual(u'Mona Lisa', mona_lisa_1_response_json['name'])

    def test_mona_lisa_2(self):
        mona_lisa_2 = open("detection_app/testdata/MonaLisa2.png", "rb")
        mona_lisa_2_response = self.client.post('/identify_painting/', {
            'image': mona_lisa_2,
            'x': '1200',
            'y': '1400',
        })
        self.assertEqual(200, mona_lisa_2_response.status_code)
        mona_lisa_2_response_json = json.loads(mona_lisa_2_response.content)
        self.assertEqual(u'MonaLisa', mona_lisa_2_response_json['name'])

    def test_paintin_starry_night(self):
        starry_night = open("detection_app/testdata/StarryNightPhoto.png", "rb")
        starry_night_response = self.client.post('/identify_painting/', {
            'image': starry_night,
            'x': '750',
            'y': '450',
        })
        self.assertEqual(200, starry_night_response.status_code)
        starry_night_response_json = json.loads(starry_night_response.content)
        self.assertEqual(u'The Starry Night', starry_night_response_json['name'])


text:
<!DOCTYPE html>

        <title>Wingman - Create Order</title>

        <link type="text/css" rel="stylesheet" media="only screen and (min-device-width: 768px) and (max-device-width: 1920px)" href="styling/style_tablet.css" />

Wingman

            <input type="button" value="Home" id="home_button" class="header_button" onClick="window.location.href='main_menu.php'">

            <input type="button" value="Back" id="back_button" class="header_button" onClick="window.location.href='order_menu.php'">

            <input type="button" value="Log Out" id="logout_button" class="header_button" onClick="window.location.href='index.php'">

            <input type="button" value="Create Order" id="button_1" class="highlighted_mainmenu_button">

                <form name="createorder_form" method="post" action="">

                            <input type="text" name="bladeID" class="input_field_middle_1" placeholder="Blade ID" required="required">

                            <select name="blade_location" size="1" class="input_field_middle_2" required="required">
                                <option selected="selected" value="">From: Blade Location</option>
                                <option value=""></option>
                            </select>

                            <select name="user_location" size="1" class="input_field_middle_3" required="required">
                                <option selected="selected" value="">To: User Location</option>
                                <option value=""></option>
                            </select>

                            <input type="time" name="time" id="time" class="input_field_middle_4" required="required">

                            <input type="button" value="Save" id="accept_button" class="input_button" onClick="window.location.href='create_order_add_finish.php'">

                </form>

HELP:

    Input the desired
    Blade ID.

    Select from where the
    Blade should be picked
    up from.

    Select where you want
    the Blade to be
    delivered.

    Select the Time you
    wish the Order to be
    executed.


text:
function(test)
  set(res "")
  # Empty string -> true
  string_isempty("")
  ans(res)
  assert(res)

  set(res "")
  # String "false" -> not empty
  string_isempty("false")
  ans(res)
  assert(NOT res)

  set(res "")
  # String "no" -> not empty
  string_isempty("no")
  ans(res)
  assert(NOT res)

  set(res "")
  # String "abc" -> not empty
  string_isempty("abc")
  ans(res)
  assert(NOT res)

  set(res "")
  # String " " -> not empty
  string_isempty(" ")
  ans(res)
  assert(NOT res)

  set(res "")
  # String "_" -> not empty
  string_isempty("_")
  ans(res)
  assert(NOT res)
endfunction()


text:
package com.theclothingstore.mystore.fragments.shopingcart;

import com.theclothingstore.mystore.model.CartItem;

import java.util.List;

/**
 * @author Anand Soni
 */

interface ShoppingCartView {
    void updateCartList(List<CartItem> cartItems);

    void onProductRemoveFromCart(boolean running, int cartId);

    void showMessage(boolean success);

    void updateTotalCartPrice(double totalPrice);
}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <X11/Xlibint.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xext.h>
#include <X11/extensions/extutil.h>
#include <X11/extensions/XResproto.h>
#include <X11/extensions/XRes.h>
#include <limits.h>

#ifndef HAVE__XEATDATAWORDS
static inline void _XEatDataWords(Display *dpy, unsigned long n)
{
# ifndef LONG64
    if (n >= (ULONG_MAX >> 2))
        _XIOError(dpy);
# endif
    _XEatData (dpy, n << 2);
}
#endif

static XExtensionInfo _xres_ext_info_data;
static XExtensionInfo *xres_ext_info = &_xres_ext_info_data;
static const char *xres_extension_name = XRES_NAME;

#define XResCheckExtension(dpy,i,val) \
  XextCheckExtension (dpy, i, xres_extension_name, val)

static XEXT_GENERATE_CLOSE_DISPLAY (close_display, xres_ext_info)

static XExtensionHooks xres_extension_hooks = {
    NULL,                               /* create_gc */
    NULL,                               /* copy_gc */
    NULL,                               /* flush_gc */
    NULL,                               /* free_gc */
    NULL,                               /* create_font */
    NULL,                               /* free_font */
    close_display,                      /* close_display */
    NULL,                               /* wire_to_event */
    NULL,                               /* event_to_wire */
    NULL,                               /* error */
    NULL,                               /* error_string */
};

static XEXT_GENERATE_FIND_DISPLAY (find_display, xres_ext_info,
                                   xres_extension_name,
                                   &xres_extension_hooks,
                                   0, NULL)

Bool XResQueryExtension (
    Display *dpy,
    int *event_base_return,
    int *error_base_return
)
{
    XExtDisplayInfo *info = find_display (dpy);

    if (XextHasExtension(info)) {
        *event_base_return = info->codes->first_event;
        *error_base_return = info->codes->first_error;
        return True;
    } else {
        return False;
    }
}

Status XResQueryVersion(
    Display *dpy,
    int *major_version_return,
    int *minor_version_return
)
{
    XExtDisplayInfo *info = find_display (dpy);
    xXResQueryVersionReply rep;
    xXResQueryVersionReq *req;

    XResCheckExtension (dpy, info, 0);

    LockDisplay (dpy);
    GetReq (XResQueryVersion, req);
    req->reqType = info->codes->major_opcode;
    req->XResReqType = X_XResQueryVersion;
    req->client_major = XRES_MAJOR_VERSION;
    req->client_minor = XRES_MINOR_VERSION;
    if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
        UnlockDisplay (dpy);
        SyncHandle ();
        return 0;
    }
    *major_version_return = rep.server_major;
    *minor_version_return = rep.server_minor;
    UnlockDisplay (dpy);
    SyncHandle ();
    return 1;
}

Status XResQueryClients (
    Display *dpy,
    int *num_clients,
    XResClient **clients
)
{
    XExtDisplayInfo *info = find_display (dpy);
    xXResQueryClientsReq *req;
    xXResQueryClientsReply rep;
    XResClient *clnts;
    int result = 0;

    *num_clients = 0;
    *clients = NULL;

    XResCheckExtension (dpy, info, 0);

    LockDisplay (dpy);
    GetReq (XResQueryClients, req);
    req->reqType = info->codes->major_opcode;
    req->XResReqType = X_XResQueryClients;
    if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
        UnlockDisplay (dpy);
        SyncHandle ();
        return 0;
    }

    if(rep.num_clients) {
        if (rep.num_clients < (INT_MAX / sizeof(XResClient)))
            clnts = Xmalloc(sizeof(XResClient) * rep.num_clients);
        else
            clnts = NULL;

        if (clnts != NULL) {
            xXResClient scratch;
            int i;

            for(i = 0; i < rep.num_clients; i++) {
                _XRead(dpy, (char*)&scratch, sz_xXResClient);
                clnts[i].resource_base = scratch.resource_base;
                clnts[i].resource_mask = scratch.resource_mask;
            }
            *clients = clnts;
            *num_clients = rep.num_clients;
            result = 1;
        } else {
            _XEatDataWords(dpy, rep.length);
        }
    }

    UnlockDisplay (dpy);
    SyncHandle ();
    return result;
}

Status XResQueryClientResources (
    Display *dpy,
    XID xid,
    int *num_types,
    XResType **types
)
{
    XExtDisplayInfo *info = find_display (dpy);
    xXResQueryClientResourcesReq *req;
    xXResQueryClientResourcesReply rep;
    XResType *typs;
    int result = 0;

    *num_types = 0;
    *types = NULL;

    XResCheckExtension (dpy, info, 0);

    LockDisplay (dpy);
    GetReq (XResQueryClientResources, req);
    req->reqType = info->codes->major_opcode;
    req->XResReqType = X_XResQueryClientResources;
    req->xid = xid;
    if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
        UnlockDisplay (dpy);
        SyncHandle ();
        return 0;
    }

    if(rep.num_types) {
        if (rep.num_types < (INT_MAX / sizeof(XResType)))
            typs = Xmalloc(sizeof(XResType) * rep.num_types);
        else
            typs = NULL;

        if (typs != NULL) {
            xXResType scratch;
            int i;

            for(i = 0; i < rep.num_types; i++) {
                _XRead(dpy, (char*)&scratch, sz_xXResType);
                typs[i].resource_type = scratch.resource_type;
                typs[i].count = scratch.count;
            }
            *types = typs;
            *num_types = rep.num_types;
            result = 1;
        } else {
            _XEatDataWords(dpy, rep.length);
        }
    }

    UnlockDisplay (dpy);
    SyncHandle ();
    return result;
}

Status XResQueryClientPixmapBytes (
    Display *dpy,
    XID xid,
    unsigned long *bytes
)
{
    XExtDisplayInfo *info = find_display (dpy);
    xXResQueryClientPixmapBytesReq *req;
    xXResQueryClientPixmapBytesReply rep;

    *bytes = 0;

    XResCheckExtension (dpy, info, 0);

    LockDisplay (dpy);
    GetReq (XResQueryClientPixmapBytes, req);
    req->reqType = info->codes->major_opcode;
    req->XResReqType = X_XResQueryClientPixmapBytes;
    req->xid = xid;
    if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) {
        UnlockDisplay (dpy);
        SyncHandle ();
        return 0;
    }

#ifdef LONG64
    *bytes = (rep.bytes_overflow * 4294967295) + rep.bytes;
#else
    *bytes = rep.bytes_overflow ? 0xffffffff : rep.bytes;
#endif

    UnlockDisplay (dpy);
    SyncHandle ();
    return 1;
}


text:
namespace StringLength
{
    using System;
    using System.Text;

    /*•	Write a program that reads from the console a string of maximum 20 characters. If the
             * length of the string is less than 20, the rest of the characters should be filled with *.
              •	Print the result string into the console.*/

    class StringLength
    {
        static void Main()
        {
            string input = Console.ReadLine();
            Console.WriteLine(input.Replace(@"\", string.Empty).PadRight(20, '*'));

            //StringBuilder text = new StringBuilder();
            //string stext = Console.ReadLine();
            //if (stext.Length > 20)
            //{
            //    Console.WriteLine();
            //}
            //else
            //{
            //    text.Append(stext);
            //    if (stext.Length < 20)
            //    {
            //        for (int i = stext.Length; i <= 19; i++)
            //        {
            //            text.Append('*');
            //        }
            //    }
            //    //text.ToString();
            //    Console.WriteLine(text.ToString());
            //}

        }
    }
}


text:
import os,sys
from setuptools import setup
from pkg_resources import require, DistributionNotFound, VersionConflict

try:
    require('pytest-allure-adaptor')
    print("""
    You have pytest-allure-adaptor installed.
    You need to remove pytest-allure-adaptor from your site-packages
    before installing allure-pytest, or conflicts may result.
    """)
    sys.exit()
except (DistributionNotFound, VersionConflict):
    pass

PACKAGE = "allure-pytest"
VERSION = "2.2.3b1"

classifiers = [
    'Development Status :: 4 - Beta',
    'Framework :: Pytest',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Topic :: Software Development :: Quality Assurance',
    'Topic :: Software Development :: Testing',
]

install_requires = [
    "pytest>=2.7.3",
    "six>=1.9.0",
    "allure-python-commons==2.2.3b1"
]

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

def main():
    setup(
        name=PACKAGE,
        version=VERSION,
        description="Allure pytest integration",
        url="https://github.com/allure-framework/allure-python",
        author="QAMetaSoftware, Stanislav Seliverstov",
        author_email="sseliverstov@qameta.io",
        license="Apache-2.0",
        classifiers=classifiers,
        keywords="allure reporting pytest",
        long_description=read('README.rst'),
        packages=["allure_pytest"],
        package_dir={"allure_pytest": "src"},
        entry_points={"pytest11": ["allure_pytest = allure_pytest.plugin"]},
        install_requires=install_requires
    )

if __name__ == '__main__':
    main()


text:
""" py.test markers.

    For details needed to understand these tests, refer to:
        https://pytest.org/
        http://pythontesting.net/start-here/
"""
# Copyright ©  2015 1&1 Group <git@1and1.com>
#
# 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.
from __future__ import absolute_import, unicode_literals, print_function

import pytest

# See also setup.cfg » [pytest] » markers
cli = pytest.mark.cli
integration = pytest.mark.integration
online = pytest.mark.online

# Export all markers
__all__ = [_k
           for _k, _v in globals().items()
           if _v.__class__ is cli.__class__]


text:
title: Templates Overview

area: docs
section: templates
---

> Assemble allows use of either Lo-Dash or Handlebars templates, depending on where the templates are used.

## Separation of Concerns

In general:

* Lo-Dash templates are used for configuration and metadata. Lo-Dash may be used in the Gruntfile, JSON/YAML files, YAML front matter, etc.
* Handlebars templates are used for content. These templates may be used in the content of pages or partials.

_Note that there is **[one exception][pages-collections]** to this separation of concerns_, and these two libs also make a great team when you use them together.

### [Lo-Dash templates](http://lodash.com/)

#### Syntax
A basic template looks like this:

```yaml
title: <%= pkg.name %>
```
#### Usage

Lo-Dash templates can be used in:

* Gruntfile
* YAML/JSON files
* YAML front matter of files (pages, partials, etc.)

However, Lo-Dash templates **cannot be used in the "content of pages"**.

Assemble only limits _where_ you can use Lo-Dash templates, beyond that you can do anything with Lo-Dash templates that you can do with JavaScript. Keep in mind, however, that the more logic you add to the YAML front matter of page for instance, the more complicated you make your pages and the more difficult your projects will be to maintain.

### [Handlebars templates](http://handlebarsjs.com/)

#### Syntax
A basic expression looks like this:

```html
<h1>\{{component.title}}</h1>
```

Usage: May be used only in the "content" of pages, e.g. _anywhere but the YAML front matter of a page._.

Although Handlebars is most often used for generating HTML, you can also _generate_ JSON, XML, YAML, CSS, LESS, SASS and so on.

This keeps Lo-Dash templates focused on configuration(ish) data, or data that is used directly by the build process, and Handlebars focused on rendering content with as little logic as possible.

{{#todo}}
* add links to resources for both libs. maybe cheatsheets
{{/todo}}

## Templating Basics

Most templating languages share a few common features:

## "Do"s and "Don't"s

### Don't

```json
// alert.json
{
  "message": "this is an alert from \{{site.name}}"
}
```

Or this:

```html
---
title: \{{pkg.name}} # Oops! Can't use handlebars here!!!
---

<h1>\{{title}}</h1>
```

Neither of those examples will because Handlebars templates can only be used **outside of the YAML front matter**.

This won't work either:

```html
---
title: My Site
---
<h1><%= title %></h1>
Whoa! Nope, this won't work either. No Lo-Dash in the "content" part of the page!
```

Lo-Dash templates can only be used in the YAML front Matter (or in YAML/JSON files, or the Gruntfile).

### Do

This works:

```json
// alert.json
{
  "message": "this is an alert from <%= site.name %>"
}
```

This works too:

```html
---
title: <% pkg.name %> # Nice!!! Assuming you are reading in the package.json in the Gruntfile, this works!
---

<h1>\{{title}}</h1>

And this title will pull data from the YAML front matter. It's kind of like cheating, accept not.
```

So does this:

```yaml
# alert.yml
modifier: alert-warning
strong: Be advised!
message: this is an alert from <%= site.name %> # pass in the site name
```

And then pass it to `alert.hbs`:

```html
<div class="alert \{{alert.modifier}}">
  <strong>\{{ alert.strong }}</strong>\{{ alert.message }}
</div>
```

{{#draft}}

## Higher-Level Template Conventions

## Layouts

* [layouts][layouts] are used for "wrapping" multiple pages with common code, like the `<head></head>`, footer and so on.
* [Pages][pages] When we refer to "pages" we're referring to:
    1. Any files that pass through the `src-dest` [file mapping](http://gruntjs.com/configuring-tasks#files) in the Assemble task
    2. Files that are built using the actual [pages array](http://assemble.io/Pages.md).
* [Partials][partials]

## [Handlebars](http://handlebarsjs.com/)

Handlebars is the default template engine that ships with Assemble.

TODO:

How Handlebars Paths work.

Handlebars supports simple paths, just like Mustache.

```handlebars
<p>\{{name}}</p>
```

Handlebars also supports nested paths, making it possible to look up properties nested below the current context.

### Example

Layout

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>\{{title}}</title>
  </head>
  <body>
    \{{> body }}
  </body>
</html>
```

### Adding data to sections

To add data to a section, you have to understand how context works. For example, if we have a JSON file named `section.json` :

```json
{
  "header" : {
    "title" : "Page Title",
    "description" : "This is the page description."
  }
}
```

And we want that data to end up in our templates, so our templates must start with the `section` variable:

```handlebars
\{{#section.header}}
<div class="page-header">
  <h1>\{{ title }}</h1>
  <p>\{{ description }}</p>
</div>
\{{/section.header}}
```

Output:

```html
<div class="page-header">
  <h1>Page Title</h1>
  <p>This is the page description.</p>
</div>
```

## Lo-Dash

```html
---
title: Home
list: <% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>
people:
- Jon Schlinkert
- Brian Woodward
---
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>\{{title}}</title>
  </head>
  <body>
    <section class="people">
      <ul>
        \{{{list}}}
      </ul>
    </section>
  </body>
</html>
```

## Arrays

The `\{{#each}}` helper is used for accessing data in arrays. Let's say we start with an array of items:

```json
{
  "items" : [
    {
      "title" : "First Item",
      "description" : "This is the first item description."
    },
    {
      "title" : "Second Item",
      "description" : "This is the second item description."
    },
    {
      "title" : "Third Item",
      "description" : "This is the third item description."
    }
  ]
}
```

Inside our templates, we use the `\{{#each}}` helper like this:

```handlebars
\{{#each items}}
<div>
  <h1>\{{ title }}</h1>
  <p>\{{ description }}</p>
</div>
\{{/each}}
```

And it compiles to:

```html
<div>
  <h1>First Item</h1>
  <p>This is the first item description.</p>
</div>
<div>
  <h1>Second item</h1>
  <p>This is the second item description.</p>
</div>
<div>
  <h1>Third Item</h1>
  <p>This is the third item description.</p>
</div>
```

### Lo-Dash Templates in YAML Front Matter

Although the Handlebars helpers from [handlebars-helpers][handlebars-helpers] can be extremely useful and powerful, they can only be used inside the content of a page. So there are certain situation where they fall short, such as when you want to make a string lowercase _and_ replace spaces in the string with dashes.

Also see the [Lo-Dash-Cheatsheet][cheatsheet-lo-dash].

For example:

From this

```
Page Title
```

To this

```
page-title
```

We could use the `\{{hyphenate}}` Handlebars helper from [handlebars-helpers][handlebars-helpers] in the content of the page:

```handlebars
---
title: Page Title
---
<div class="\{{hyphenate title}}">
  <h1>\{{ title }}</h1>
</div>
```

But this will only replace spaces with hyphens: `Page-Title`, and not lowercase. To get the results we need we can use Lo-Dash templates inside the YAML front matter:

```handlebars
---
title: Page Title
class: <%= title.toLowerCase().split(" ").join("-") %>
---
<div class="\{{class}}">
  <h1>\{{ title }}</h1>
</div>
```
Results in `page-title`.

#### Lo-Dash and Handlebars together

Or, depending on your tastes, you might find it preferrable to use combination of underscore templates in the YAML front matter with handlebars in the page itself.

```handlebars
---
title: Page Title
class: <%= title.toLowerCase() %>
---
<div class="\{{hyphenate class}}">
  <h1>\{{ title }}</h1>
</div>
```

### Where can Lo-Dash Templates be used with Assemble?

* Inside the Gruntfile
* In YAML front matter of pages **and partials**
* In JSON or YAML files that supply content or data to pages or partials
* In external JSON or YAML files that are used to supply configuration data to Assemble

For example, inside `alert.json` :

```json
{
  "class": "welcome-alert",
  "message": "Welcome to <%= title %>, the best place on the web."
}
```

Or the same in YAML:

```yaml
class: welcome-alert
message: Welcome to <%= title %>, the best place on the web
```

Here are the global defaults:

1. `YAML front matter` : YAML front matter must be the first thing in the file and takes the form of:YAML front-matter allows wins over all other methods, if
not defined the following option is used.
2. page.json:
3. config.json with a `page` or `pages` object

```yaml
---
scaffold:
  theme:
  title: Home
  layout: full-width
  published: false
  tags:
---
```

## Page

Same as global defaults:
 1. `YAML Front Matter` on each page is the _most_ specific, and will always "win" over other methods
 2. `page.json`
 3. `something.json` which references a `page` or `pages` objects or properties

One way to take advantage of specificity is to **use underscore templates inside your YAML Front Matter**. For example:

```yaml
---
project: <%= projects %>/<%= project.type %>/<%= project.name %>.json
---
```
or:

```yaml
---
project:
  name: Project Name
  theme: <%= themes %>/<%= theme.type %>/<%= theme.name %>.json
  scaffold: <%= scaffolds %>/<%= scaffold.type %>/<%= scaffold.name %>.json
    page: <%= pages %>/<%= page.type %>/<%= page.name %>.json
      title: Page Name
      layout: <%= layouts %>/<%= layout.type %>/<%= layout.name %>.json
        section:
          - <%= sections %>/<%= sections.type %>/<%= sections.name %>.json
          components:
            - <%= component.name %>.json
            - <%= component.name2 %>.json
---
```

## Templates

**Template Processors**

## Layout

### Sections

zones...

## Partials

components, widgets, modules...

### Snippets

reusable blocks of code which are not

## Data

  * "mock" data
  * content
  * microcopy

{{/draft}}

## Related Information

* [Pages][pages]
* [Partials][partials]
* [Layouts][layouts]
* [Helpers][helpers]


text:
package com.kza.common.mq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Created by kza on 2015/9/7.
 */
public class RabbitMQService {

    public static final String QUEUE_NAME = "queue_1";

    public void send() throws IOException {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            String message = "Hello World!";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        } finally {

            if (null != channel) {
                channel.close();
            }
            if (null != connection) {
                connection.close();
            }
        }
    }

    public void receive() throws IOException {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                        throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println(" [x] Received '" + message + "'");
                }
            };

//            Consumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(QUEUE_NAME, true, consumer);
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {

        }
    }
}