text:
package main

import (
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
)

type BaseMetadata struct {
	TypeName    string
	TypeURL     string
	TypeVersion string
	Name        string
	RepoUUID    string
	Compression string
	Checksum    string
	Persistence string
	Versioned   bool
}

type Metadata struct {
	Base     BaseMetadata
	Extended interface{}
}

func getLabelMetadata(dstURL string) *LabelMetadata {
	infoUrl := dstURL + "/info"
	resp, err := http.Get(infoUrl)
	if err != nil {
		fmt.Printf("Error on getting metadata (%s): %v\n", infoUrl, err.Error())
		os.Exit(1)
	}
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Bad status on getting metadata (%s): %d\n", infoUrl, resp.StatusCode)
		os.Exit(1)
	}
	metadata, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Could not read metadata from labels (%s): %v\n", infoUrl, err.Error())
		os.Exit(1)
	}
	m := new(LabelMetadata)
	if err := json.Unmarshal(metadata, m); err != nil {
		fmt.Printf("Error parsing metadata from labels: %s\n", err.Error())
		os.Exit(1)
	}
	return m
}

type LabelMetadata struct {
	Base     BaseMetadata
	Extended struct {
		BlockSize [3]int
		MinIndex  [3]int
		MaxIndex  [3]int
	}
}

func sendLabels(src *LabelMetadata, name, srcURL string) {
	minIndex := src.Extended.MinIndex
	maxIndex := src.Extended.MaxIndex
	blockSize := src.Extended.BlockSize
	if blockSize[0] != blockSize[1] {
		fmt.Printf("Can't handle non-cubic block sizes as in %q data instance: %v\n", name, blockSize)
		os.Exit(1)
	}
	fmt.Printf("MinIndex: %v\n", minIndex)
	fmt.Printf("MaxIndex: %v\n", maxIndex)

	// Compute the output file name
	var ext string
	switch *compression {
	case "none":
		ext = "dat"
	case "lz4":
		ext = "lz4"
	case "gzip":
		ext = "gz"
	default:
		fmt.Printf("unknown compression type %q", *compression)
		os.Exit(1)
	}

	// Iterate through each XY plane of one block deep data.
	// Send it to destination, synchronously.
	nx := maxIndex[0] - minIndex[0] + 1
	ny := maxIndex[1] - minIndex[1] + 1

	// # voxels in x, and xy
	vx := nx * blockSize[0]
	vy := ny * blockSize[1]
	vz := blockSize[2]

	strips := 1
	if vx*vy*vz*8 > 2000000000 {
		strips = (vx*vy*vz*8)/2000000000 + 1
	}
	byPerStrip := ny / strips
	fmt.Printf("Number of strips per layer: %d\n", strips)
	fmt.Printf("Total uncompressed bytes per file: %d MB\n", vx*vy*vz*8/(strips*1000000))

	var err error
	ox := minIndex[0] * blockSize[0]
	for z := minIndex[2]; z <= maxIndex[2]; z++ {
		oz := z * blockSize[2]
		if oz+blockSize[2] < *minz || oz > *maxz {
			continue
		}
		by0 := minIndex[1]
		for n := 0; n < strips; n++ {
			if by0 > maxIndex[1] {
				break
			}
			by1 := by0 + byPerStrip - 1
			if by1 > maxIndex[1] {
				by1 = maxIndex[1]
			}

			oy := by0 * blockSize[1]
			vy := (by1 - by0 + 1) * blockSize[1]
			getURL := fmt.Sprintf("%s/raw/0_1_2/%d_%d_%d/%d_%d_%d?compression=lz4", srcURL, vx, vy, vz, ox, oy, oz)
			if *roi != "" {
				getURL += fmt.Sprintf("&roi=%s", *roi)
			}
			var resp *http.Response
			if *dryrun {
				fmt.Printf("-- would GET %s\n", getURL)
			} else {
				resp, err = http.Get(getURL)
				if err != nil {
					fmt.Printf("Receive error: %s\n", err.Error())
					os.Exit(1)
				}
				if resp.StatusCode != http.StatusOK {
					fmt.Printf("Bad status on receiving data: %d\n", resp.StatusCode)
					os.Exit(1)
				}
			}
			if *url != "" {
				postURL := fmt.Sprintf("%s/raw/0_1_2/%d_%d_%d/%d_%d_%d?compression=lz4", *url, vx, vy, vz, ox, oy, oz)
				if *dryrun {
					fmt.Printf("-- would POST %s\n", postURL)
				} else {
					resp2, err := http.Post(postURL, "application/octet-stream", resp.Body)
					if err != nil {
						fmt.Printf("Transmit error: %s\n", err.Error())
						os.Exit(1)
					}
					if resp2.StatusCode != http.StatusOK {
						fmt.Printf("Bad status on sending data: %d\n", resp2.StatusCode)
						os.Exit(1)
					}
				}
			}
			if *outdir != "" {
				base := fmt.Sprintf("%s-%dx%dx%d+%d+%d+%d.%s", name, vx, vy, vz, ox, oy, oz, ext)
				filename := filepath.Join(*outdir, base)
				if err := writeFile(resp.Body, filename); err != nil {
					fmt.Printf("Error writing file: %s\n", filename)
					os.Exit(1)
				}
			}

			by0 += byPerStrip
		}
	}
}

func writeFile(data io.ReadCloser, filename string) error {
	if *dryrun {
		return nil
	}
	defer data.Close()

	// Setup file for write
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	var out io.WriteCloser
	switch *compression {
	case "none":
		out = f
	case "gzip":
		out = gzip.NewWriter(f)
		defer out.Close()
	default:
		return fmt.Errorf("Can't compress to type %q, only %q\n", *compression, "gzip")
	}

	written, err := io.Copy(out, data)
	if err != nil {
		fmt.Printf("Error on copy of data from DVID to file: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("Wrote %d MB to %s\n", written/1000000, filename)
	return nil
}

func transferData(host, uuid, name string) {
	// If we are transferring to another DVID host, verify the destination.
	var dstMetadata *LabelMetadata
	if *url != "" {
		dstMetadata = getLabelMetadata(*url)
		dsttype := dstMetadata.Base.TypeName

		switch dsttype {
		case "labelblk":
			fmt.Printf("-- verified that POST URL (%v) is labelblk.\n", *url)
		default:
			fmt.Printf("POST URL (%v) must be labelblk but is %s data type\n", *url, dsttype)
			os.Exit(1)
		}
	}

	// Get the source metadata
	srcURL := fmt.Sprintf("%s/api/node/%s/%s", host, uuid, name)
	srcMetadata := getLabelMetadata(srcURL)
	if srcMetadata.Base.TypeName != "labelblk" {
		fmt.Printf("Source data instance %q is not labelblk type.  Aborting.\n", name)
		os.Exit(1)
	}

	// If we are writing files to output directory, make sure it's created.
	// Make sure output directory exists if it's specified.
	if *outdir != "" {
		if fileinfo, err := os.Stat(*outdir); os.IsNotExist(err) {
			fmt.Printf("Creating output directory: %s\n", *outdir)
			err := os.MkdirAll(*outdir, 0744)
			if err != nil {
				fmt.Printf("Can't make output directory: %s\n", err.Error())
				os.Exit(1)
			}
		} else if !fileinfo.IsDir() {
			fmt.Printf("Supplied output path (%s) is not a directory.", *outdir)
			os.Exit(1)
		}
	}

	sendLabels(srcMetadata, name, srcURL)
}


text:
package org.apache.commons.statistics.distribution;

import org.apache.commons.numbers.gamma.LogBeta;
import org.apache.commons.numbers.gamma.RegularizedBeta;

/**
 * Implementation of the F-distribution.
 *
 * @see F-distribution (Wikipedia)
 * @see F-distribution (MathWorld)
 */
public class FDistribution extends AbstractContinuousDistribution {
    /** The numerator degrees of freedom. */
    private final double numeratorDegreesOfFreedom;
    /** The numerator degrees of freedom. */
    private final double denominatorDegreesOfFreedom;

    /**
     * Creates a distribution.
     *
     * @param numeratorDegreesOfFreedom Numerator degrees of freedom.
     * @param denominatorDegreesOfFreedom Denominator degrees of freedom.
     * @throws IllegalArgumentException if {@code numeratorDegreesOfFreedom <= 0} or
     * {@code denominatorDegreesOfFreedom <= 0}.
     */
    public FDistribution(double numeratorDegreesOfFreedom,
                         double denominatorDegreesOfFreedom) {
        if (numeratorDegreesOfFreedom <= 0) {
            throw new DistributionException(DistributionException.NEGATIVE,
                                            numeratorDegreesOfFreedom);
        }
        if (denominatorDegreesOfFreedom <= 0) {
            throw new DistributionException(DistributionException.NEGATIVE,
                                            denominatorDegreesOfFreedom);
        }
        this.numeratorDegreesOfFreedom = numeratorDegreesOfFreedom;
        this.denominatorDegreesOfFreedom = denominatorDegreesOfFreedom;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double density(double x) {
        return Math.exp(logDensity(x));
    }

    /** {@inheritDoc} **/
    @Override
    public double logDensity(double x) {
        final double nhalf = numeratorDegreesOfFreedom / 2;
        final double mhalf = denominatorDegreesOfFreedom / 2;
        final double logx = Math.log(x);
        final double logn = Math.log(numeratorDegreesOfFreedom);
        final double logm = Math.log(denominatorDegreesOfFreedom);
        final double lognxm = Math.log(numeratorDegreesOfFreedom * x +
                denominatorDegreesOfFreedom);
        return nhalf * logn + nhalf * logx - logx +
               mhalf * logm - nhalf * lognxm - mhalf * lognxm -
               LogBeta.value(nhalf, mhalf);
    }

    /**
     * {@inheritDoc}
     *
     * The implementation of this method is based on
     *

     *

     *
     *   F-Distribution, equation (4).
     *

     *

     */
    @Override
    public double cumulativeProbability(double x)  {
        double ret;
        if (x <= 0) {
            ret = 0;
        } else {
            double n = numeratorDegreesOfFreedom;
            double m = denominatorDegreesOfFreedom;

            ret = RegularizedBeta.value((n * x) / (m + n * x),
                0.5 * n,
                0.5 * m);
        }
        return ret;
    }

    /**
     * Access the numerator degrees of freedom.
     *
     * @return the numerator degrees of freedom.
     */
    public double getNumeratorDegreesOfFreedom() {
        return numeratorDegreesOfFreedom;
    }

    /**
     * Access the denominator degrees of freedom.
     *
     * @return the denominator degrees of freedom.
     */
    public double getDenominatorDegreesOfFreedom() {
        return denominatorDegreesOfFreedom;
    }

    /**
     * {@inheritDoc}
     *
     * For denominator degrees of freedom parameter {@code b}, the mean is
     *

     *
if {@code b > 2} then {@code b / (b - 2)},

     *
else undefined ({@code Double.NaN}).
     *

     */
    @Override
    public double getMean() {
        final double denominatorDF = getDenominatorDegreesOfFreedom();

        if (denominatorDF > 2) {
            return denominatorDF / (denominatorDF - 2);
        }

        return Double.NaN;
    }

    /**
     * {@inheritDoc}
     *
     * For numerator degrees of freedom parameter {@code a} and denominator
     * degrees of freedom parameter {@code b}, the variance is
     *

     *

     *    if {@code b > 4} then
     *    {@code [2 * b^2 * (a + b - 2)] / [a * (b - 2)^2 * (b - 4)]},
     *

     *
else undefined ({@code Double.NaN}).
     *

     */
    @Override
    public double getVariance() {
        final double denominatorDF = getDenominatorDegreesOfFreedom();

        if (denominatorDF > 4) {
            final double numeratorDF = getNumeratorDegreesOfFreedom();
            final double denomDFMinusTwo = denominatorDF - 2;

            return (2 * (denominatorDF * denominatorDF) * (numeratorDF + denominatorDF - 2)) /
                   ((numeratorDF * (denomDFMinusTwo * denomDFMinusTwo) * (denominatorDF - 4)));
        }

        return Double.NaN;
    }

    /**
     * {@inheritDoc}
     *
     * The lower bound of the support is always 0 no matter the parameters.
     *
     * @return lower bound of the support (always 0)
     */
    @Override
    public double getSupportLowerBound() {
        return 0;
    }

    /**
     * {@inheritDoc}
     *
     * The upper bound of the support is always positive infinity
     * no matter the parameters.
     *
     * @return upper bound of the support (always Double.POSITIVE_INFINITY)
     */
    @Override
    public double getSupportUpperBound() {
        return Double.POSITIVE_INFINITY;
    }

    /**
     * {@inheritDoc}
     *
     * The support of this distribution is connected.
     *
     * @return {@code true}
     */
    @Override
    public boolean isSupportConnected() {
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Push notification services abstraction (http://github.com/juliangut/tify)
 *
 * @link https://github.com/juliangut/tify for the canonical source repository
 *
 * @license https://github.com/juliangut/tify/blob/master/LICENSE
 */

namespace Jgut\Tify\Adapter;

use Doctrine\Common\Collections\ArrayCollection;
use Jgut\Tify\Exception\AdapterException;
use Jgut\Tify\ParameterTrait;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class AbstractService.
 */
abstract class AbstractAdapter
{
    use ParameterTrait;

    /**
     * Sandbox environment.
     *
     * @var bool
     */
    protected $sandbox;

    /**
     * Constructor.
     *
     * @param array $parameters
     * @param bool  $sandbox
     *
     * @throws \Jgut\Tify\Exception\AdapterException
     */
    public function __construct(array $parameters = [], $sandbox = false)
    {
        $parametersResolver = new OptionsResolver();

        $parametersResolver->setDefined($this->getDefinedParameters());
        $parametersResolver->setDefaults($this->getDefaultParameters());
        $parametersResolver->setRequired($this->getRequiredParameters());

        try {
            $this->parameters = new ArrayCollection($parametersResolver->resolve($parameters));
        } catch (MissingOptionsException $exception) {
            throw new AdapterException(sprintf('Missing parameters on "%s"', self::class));
        } catch (\Exception $exception) {
            throw new AdapterException('Invalid parameter provided');
        }

        $this->sandbox = (bool) $sandbox;
    }

    /**
     * Retrieve if sandbox.
     *
     * @return bool
     */
    public function isSandbox()
    {
        return (bool) $this->sandbox;
    }

    /**
     * Set Sandbox.
     *
     * @param bool $sandbox
     *
     * @return $this
     */
    public function setSandbox($sandbox)
    {
        $this->sandbox = (bool) $sandbox;

        return $this;
    }

    /**
     * Get the list of defined parameters.
     *
     * @return array
     */
    protected function getDefinedParameters()
    {
        return [];
    }

    /**
     * Get the list of default parameters.
     *
     * @return array
     */
    protected function getDefaultParameters()
    {
        return [];
    }

    /**
     * Get the list of required parameters.
     *
     * @return array
     */
    protected function getRequiredParameters()
    {
        return [];
    }
}


text:
'use babel'

import { combineReducers } from 'redux';
import {fromJS} from 'immutable';

function generators(state = [], action) {
  switch(action.type) {
    case "GENERATORS_REFRESHED":
      return action.generators;
      break;
    default:
      return state;
  }
}

export default combineReducers({
  generators
});


text:
package org.curcon.app.web.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(2)
public class ControllerTestSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
	}
}


text:
ActiveRecord::Schema.define(:version => 0) do
  create_table :posts do |t|
    t.text :text
    t.datetime
  end

  create_table :users do |u|
    u.string :name
  end

  create_table :walls do |w|
    w.string :name
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<spirit:component xmlns:xilinx="http://www.xilinx.com"
		xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<spirit:vendor>xilinx.com</spirit:vendor>
	<spirit:library>customized_ip</spirit:library>
	<spirit:name>RAT_xlslice_0_0</spirit:name>
	<spirit:version>1.0</spirit:version>
	<spirit:model>
		<spirit:views>
			<spirit:view>
				<spirit:name>xilinx_vhdlsynthesis</spirit:name>
				<spirit:displayName>VHDL Synthesis</spirit:displayName>
				<spirit:envIdentifier>vhdlSource:vivado.xilinx.com:synthesis</spirit:envIdentifier>
				<spirit:language>vhdl</spirit:language>
				<spirit:fileSetRef>
					<spirit:localName>xilinx_vhdlsynthesis_view_fileset</spirit:localName>
				</spirit:fileSetRef>
				<spirit:parameters>
					<spirit:parameter>
						<spirit:name>GENtimestamp</spirit:name>
						<spirit:value>Fri Oct 27 05:43:56 UTC 2017</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRC</spirit:name>
						<spirit:value>725085a0</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRCversion</spirit:name>
						<spirit:value>1</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRC</spirit:name>
						<spirit:value>93711e2b</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRCversion</spirit:name>
						<spirit:value>6</spirit:value>
					</spirit:parameter>
				</spirit:parameters>
			</spirit:view>
			<spirit:view>
				<spirit:name>xilinx_vhdlsynthesiswrapper</spirit:name>
				<spirit:displayName>VHDL Synthesis Wrapper</spirit:displayName>
				<spirit:envIdentifier>vhdlSource:vivado.xilinx.com:synthesis.wrapper</spirit:envIdentifier>
				<spirit:language>vhdl</spirit:language>
				<spirit:fileSetRef>
					<spirit:localName>xilinx_vhdlsynthesiswrapper_view_fileset</spirit:localName>
				</spirit:fileSetRef>
				<spirit:parameters>
					<spirit:parameter>
						<spirit:name>GENtimestamp</spirit:name>
						<spirit:value>Fri Oct 27 05:43:56 UTC 2017</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRC</spirit:name>
						<spirit:value>725085a0</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRCversion</spirit:name>
						<spirit:value>1</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRC</spirit:name>
						<spirit:value>93711e2b</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRCversion</spirit:name>
						<spirit:value>6</spirit:value>
					</spirit:parameter>
				</spirit:parameters>
			</spirit:view>
			<spirit:view>
				<spirit:name>xilinx_vhdlbehavioralsimulation</spirit:name>
				<spirit:displayName>VHDL Simulation</spirit:displayName>
				<spirit:envIdentifier>vhdlSource:vivado.xilinx.com:simulation</spirit:envIdentifier>
				<spirit:language>vhdl</spirit:language>
				<spirit:fileSetRef>
					<spirit:localName>xilinx_vhdlbehavioralsimulation_view_fileset</spirit:localName>
				</spirit:fileSetRef>
				<spirit:parameters>
					<spirit:parameter>
						<spirit:name>GENtimestamp</spirit:name>
						<spirit:value>Fri Oct 27 05:43:56 UTC 2017</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRC</spirit:name>
						<spirit:value>725085a0</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRCversion</spirit:name>
						<spirit:value>1</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRC</spirit:name>
						<spirit:value>14da1889</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRCversion</spirit:name>
						<spirit:value>6</spirit:value>
					</spirit:parameter>
				</spirit:parameters>
			</spirit:view>
			<spirit:view>
				<spirit:name>xilinx_vhdlsimulationwrapper</spirit:name>
				<spirit:displayName>VHDL Simulation Wrapper</spirit:displayName>
				<spirit:envIdentifier>vhdlSource:vivado.xilinx.com:simulation.wrapper</spirit:envIdentifier>
				<spirit:language>vhdl</spirit:language>
				<spirit:fileSetRef>
					<spirit:localName>xilinx_vhdlsimulationwrapper_view_fileset</spirit:localName>
				</spirit:fileSetRef>
				<spirit:parameters>
					<spirit:parameter>
						<spirit:name>GENtimestamp</spirit:name>
						<spirit:value>Fri Oct 27 05:43:56 UTC 2017</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRC</spirit:name>
						<spirit:value>725085a0</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRCversion</spirit:name>
						<spirit:value>1</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRC</spirit:name>
						<spirit:value>14da1889</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRCversion</spirit:name>
						<spirit:value>6</spirit:value>
					</spirit:parameter>
				</spirit:parameters>
			</spirit:view>
			<spirit:view>
				<spirit:name>xilinx_externalfiles</spirit:name>
				<spirit:displayName>External Files</spirit:displayName>
				<spirit:envIdentifier>:vivado.xilinx.com:external.files</spirit:envIdentifier>
				<spirit:fileSetRef>
					<spirit:localName>xilinx_externalfiles_view_fileset</spirit:localName>
				</spirit:fileSetRef>
				<spirit:parameters>
					<spirit:parameter>
						<spirit:name>GENtimestamp</spirit:name>
						<spirit:value>Fri Oct 27 05:43:57 UTC 2017</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRC</spirit:name>
						<spirit:value>725085a0</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>boundaryCRCversion</spirit:name>
						<spirit:value>1</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRC</spirit:name>
						<spirit:value>93711e2b</spirit:value>
					</spirit:parameter>
					<spirit:parameter>
						<spirit:name>customizationCRCversion</spirit:name>
						<spirit:value>6</spirit:value>
					</spirit:parameter>
				</spirit:parameters>
			</spirit:view>
		</spirit:views>
		<spirit:ports>
			<spirit:port>
				<spirit:name>Din</spirit:name>
				<spirit:wire>
					<spirit:direction>in</spirit:direction>
					<spirit:vector>
						<spirit:left spirit:format="long"
								spirit:resolve="dependent"
								spirit:dependency="(spirit:decode(id('MODELPARAM_VALUE.DIN_WIDTH')) - 1)">17</spirit:left>
						<spirit:right spirit:format="long">0</spirit:right>
					</spirit:vector>
					<spirit:wireTypeDefs>
						<spirit:wireTypeDef>
							<spirit:typeName>std_logic_vector</spirit:typeName>
							<spirit:viewNameRef>xilinx_vhdlsynthesis</spirit:viewNameRef>
							<spirit:viewNameRef>xilinx_vhdlbehavioralsimulation</spirit:viewNameRef>
						</spirit:wireTypeDef>
					</spirit:wireTypeDefs>
				</spirit:wire>
			</spirit:port>
			<spirit:port>
				<spirit:name>Dout</spirit:name>
				<spirit:wire>
					<spirit:direction>out</spirit:direction>
					<spirit:vector>
						<spirit:left spirit:format="long"
								spirit:resolve="dependent"
								spirit:dependency="(spirit:decode(id('MODELPARAM_VALUE.DIN_FROM')) - spirit:decode(id('MODELPARAM_VALUE.DIN_TO')))">9</spirit:left>
						<spirit:right spirit:format="long">0</spirit:right>
					</spirit:vector>
					<spirit:wireTypeDefs>
						<spirit:wireTypeDef>
							<spirit:typeName>std_logic_vector</spirit:typeName>
							<spirit:viewNameRef>xilinx_vhdlsynthesis</spirit:viewNameRef>
							<spirit:viewNameRef>xilinx_vhdlbehavioralsimulation</spirit:viewNameRef>
						</spirit:wireTypeDef>
					</spirit:wireTypeDefs>
				</spirit:wire>
			</spirit:port>
		</spirit:ports>
		<spirit:modelParameters>
			<spirit:modelParameter xsi:type="spirit:nameValueTypeType"
					spirit:dataType="integer">
				<spirit:name>DIN_WIDTH</spirit:name>
				<spirit:displayName>Din Width</spirit:displayName>
				<spirit:value spirit:format="long"
						spirit:resolve="generated"
						spirit:id="MODELPARAM_VALUE.DIN_WIDTH">18</spirit:value>
			</spirit:modelParameter>
			<spirit:modelParameter spirit:dataType="integer">
				<spirit:name>DIN_FROM</spirit:name>
				<spirit:displayName>Din From</spirit:displayName>
				<spirit:value spirit:format="long"
						spirit:resolve="generated"
						spirit:id="MODELPARAM_VALUE.DIN_FROM">12</spirit:value>
			</spirit:modelParameter>
			<spirit:modelParameter spirit:dataType="integer">
				<spirit:name>DIN_TO</spirit:name>
				<spirit:displayName>Din Down To</spirit:displayName>
				<spirit:value spirit:format="long"
						spirit:resolve="generated"
						spirit:id="MODELPARAM_VALUE.DIN_TO">3</spirit:value>
			</spirit:modelParameter>
		</spirit:modelParameters>
	</spirit:model>
	<spirit:fileSets>
		<spirit:fileSet>
			<spirit:name>xilinx_vhdlsynthesis_view_fileset</spirit:name>
			<spirit:file>
				<spirit:name>../../ipshared/c49f/xlslice.vhd</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:logicalName>work</spirit:logicalName>
			</spirit:file>
		</spirit:fileSet>
		<spirit:fileSet>
			<spirit:name>xilinx_vhdlsynthesiswrapper_view_fileset</spirit:name>
			<spirit:file>
				<spirit:name>synth/RAT_xlslice_0_0.vhd</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
		</spirit:fileSet>
		<spirit:fileSet>
			<spirit:name>xilinx_vhdlbehavioralsimulation_view_fileset</spirit:name>
			<spirit:file>
				<spirit:name>../../ipshared/c49f/xlslice.vhd</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:logicalName>work</spirit:logicalName>
			</spirit:file>
		</spirit:fileSet>
		<spirit:fileSet>
			<spirit:name>xilinx_vhdlsimulationwrapper_view_fileset</spirit:name>
			<spirit:file>
				<spirit:name>sim/RAT_xlslice_0_0.vhd</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
		</spirit:fileSet>
		<spirit:fileSet>
			<spirit:name>xilinx_externalfiles_view_fileset</spirit:name>
			<spirit:file>
				<spirit:name>RAT_xlslice_0_0.dcp</spirit:name>
				<spirit:userFileType>dcp</spirit:userFileType>
				<spirit:userFileType>USED_IN_implementation</spirit:userFileType>
				<spirit:userFileType>USED_IN_synthesis</spirit:userFileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
			<spirit:file>
				<spirit:name>RAT_xlslice_0_0_sim_netlist.v</spirit:name>
				<spirit:fileType>verilogSource</spirit:fileType>
				<spirit:userFileType>USED_IN_simulation</spirit:userFileType>
				<spirit:userFileType>USED_IN_single_language</spirit:userFileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
			<spirit:file>
				<spirit:name>RAT_xlslice_0_0_sim_netlist.vhdl</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:userFileType>USED_IN_simulation</spirit:userFileType>
				<spirit:userFileType>USED_IN_single_language</spirit:userFileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
			<spirit:file>
				<spirit:name>RAT_xlslice_0_0_stub.v</spirit:name>
				<spirit:fileType>verilogSource</spirit:fileType>
				<spirit:userFileType>USED_IN_synth_blackbox_stub</spirit:userFileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
			<spirit:file>
				<spirit:name>RAT_xlslice_0_0_stub.vhdl</spirit:name>
				<spirit:fileType>vhdlSource</spirit:fileType>
				<spirit:userFileType>USED_IN_synth_blackbox_stub</spirit:userFileType>
				<spirit:logicalName>xil_defaultlib</spirit:logicalName>
			</spirit:file>
		</spirit:fileSet>
	</spirit:fileSets>
	<spirit:description>Slices a number of bits off of Din input. dout = din[from_position : to_position]</spirit:description>
	<spirit:parameters>
		<spirit:parameter>
			<spirit:name>DOUT_WIDTH</spirit:name>
			<spirit:displayName>Dout Width</spirit:displayName>
			<spirit:value spirit:format="long"
					spirit:resolve="user"
					spirit:id="PARAM_VALUE.DOUT_WIDTH"
					spirit:order="1400">10</spirit:value>
		</spirit:parameter>
		<spirit:parameter>
			<spirit:name>DIN_TO</spirit:name>
			<spirit:displayName>Din Down To</spirit:displayName>
			<spirit:value spirit:format="long"
					spirit:resolve="user"
					spirit:id="PARAM_VALUE.DIN_TO"
					spirit:order="1200"
					spirit:minimum="0"
					spirit:maximum="17"
					spirit:rangeType="long">3</spirit:value>
		</spirit:parameter>
		<spirit:parameter>
			<spirit:name>DIN_FROM</spirit:name>
			<spirit:displayName>Din From</spirit:displayName>
			<spirit:value spirit:format="long"
					spirit:resolve="user"
					spirit:id="PARAM_VALUE.DIN_FROM"
					spirit:order="1300"
					spirit:minimum="3"
					spirit:maximum="17"
					spirit:rangeType="long">12</spirit:value>
		</spirit:parameter>
		<spirit:parameter>
			<spirit:name>DIN_WIDTH</spirit:name>
			<spirit:displayName>Din Width</spirit:displayName>
			<spirit:value spirit:format="long"
					spirit:resolve="user"
					spirit:id="PARAM_VALUE.DIN_WIDTH"
					spirit:order="1100"
					spirit:minimum="2"
					spirit:maximum="4096"
					spirit:rangeType="long">18</spirit:value>
		</spirit:parameter>
		<spirit:parameter>
			<spirit:name>Component_Name</spirit:name>
			<spirit:value spirit:resolve="user"
					spirit:id="PARAM_VALUE.Component_Name"
					spirit:order="1">RAT_xlslice_0_0</spirit:value>
		</spirit:parameter>
	</spirit:parameters>
	<spirit:vendorExtensions>
		<xilinx:coreExtensions>
			<xilinx:displayName>Slice</xilinx:displayName>
			<xilinx:coreRevision>0</xilinx:coreRevision>
			<xilinx:configElementInfos>
				<xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.DIN_FROM"
						xilinx:valueSource="user"/>
				<xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.DIN_TO"
						xilinx:valueSource="user"/>
				<xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.DIN_WIDTH"
						xilinx:valueSource="user"/>
				<xilinx:configElementInfo xilinx:referenceId="PARAM_VALUE.DOUT_WIDTH"
						xilinx:valueSource="user"/>
			</xilinx:configElementInfos>
		</xilinx:coreExtensions>
		<xilinx:packagingInfo>
			<xilinx:xilinxVersion>2015.1</xilinx:xilinxVersion>
			<xilinx:checksum xilinx:scope="fileGroups"
					xilinx:value="c1a8718f"/>
			<xilinx:checksum xilinx:scope="ports"
					xilinx:value="f85a9b84"/>
			<xilinx:checksum xilinx:scope="hdlParameters"
					xilinx:value="73fac5c4"/>
			<xilinx:checksum xilinx:scope="parameters"
					xilinx:value="24d28dc0"/>
		</xilinx:packagingInfo>
	</spirit:vendorExtensions>
</spirit:component>


text:
//
//  ZHTransfer.h
//  足球控(DIY)
//
//  Created by Aaron on 16/1/17.
//  Copyright © 2016年 叶无道. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ZHTransfer : NSObject
@property (nonatomic ,copy) NSString *type;
/*
 *转到的球队
 */
@property (nonatomic ,copy) NSString *to_team_name;

@property (nonatomic ,copy) NSString *from_team_name;

@property (nonatomic ,copy) NSString *value;
@end


text:
Template
========

My template for a new website


text:
class Cask::Source::Path
  def self.me?(query)
    File.file?(query)
  end

  attr_reader :path

  def initialize(path)
    @path = Pathname(path).expand_path
  end

  def load
    require path
    Cask.const_get(cask_class_name).new
  end

  def cask_class_name
    path.basename.to_s.sub(/\.rb/, '').split('-').map(&:capitalize).join
  end
end


text:
package org.elasticsearch.xpack.ml.filestructurefinder;

import org.elasticsearch.xpack.core.ml.filestructurefinder.FieldStats;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Calculate statistics for a set of scalar field values.
 * Count, cardinality (distinct count) and top hits (most common values) are always calculated.
 * Extra statistics are calculated if the field is numeric: min, max, mean and median.
 */
public class FieldStatsCalculator {

    private long count;
    private SortedMap<String, Integer> countsByStringValue = new TreeMap<>();
    private SortedMap<Double, Integer> countsByNumericValue = new TreeMap<>();

    /**
     * Add a collection of values to the calculator.
     * The values to be added can be combined by the caller and added in a
     * single call to this method or added in multiple calls to this method.
     * @param fieldValues Zero or more values to add.  May not be null.
     */
    public void accept(Collection<String> fieldValues) {

        count += fieldValues.size();

        for (String fieldValue : fieldValues) {

            countsByStringValue.compute(fieldValue, (k, v) -> (v == null) ? 1 : (1 + v));

            if (countsByNumericValue != null) {

                try {
                    countsByNumericValue.compute(Double.valueOf(fieldValue), (k, v) -> (v == null) ? 1 : (1 + v));
                } catch (NumberFormatException e) {
                    countsByNumericValue = null;
                }
            }
        }
    }

    /**
     * Calculate field statistics based on the previously accepted values.
     * @param numTopHits The maximum number of entries to include in the top hits.
     * @return The calculated field statistics.
     */
    public FieldStats calculate(int numTopHits) {

        if (countsByNumericValue != null && countsByNumericValue.isEmpty() == false) {
            return new FieldStats(count, countsByNumericValue.size(), countsByNumericValue.firstKey(), countsByNumericValue.lastKey(),
                calculateMean(), calculateMedian(), findNumericTopHits(numTopHits));
        } else {
            return new FieldStats(count, countsByStringValue.size(), findStringTopHits(numTopHits));
        }
    }

    Double calculateMean() {

        assert countsByNumericValue != null;

        if (countsByNumericValue.isEmpty()) {
            return null;
        }

        double runningCount = 0.0;
        double runningMean = Double.NaN;

        for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) {

            double entryCount = (double) entry.getValue();
            double newRunningCount = runningCount + entryCount;

            // Updating a running mean like this is more numerically stable than using (sum / count)
            if (runningCount > 0.0) {
                runningMean = runningMean * (runningCount / newRunningCount) + entry.getKey() * (entryCount / newRunningCount);
            } else if (entryCount > 0.0) {
                runningMean = entry.getKey();
            }

            runningCount = newRunningCount;
        }

        return runningMean;
    }

    Double calculateMedian() {

        assert countsByNumericValue != null;

        if (count % 2 == 1) {

            // Simple case - median is middle value
            long targetCount = count / 2 + 1;
            long currentUpperBound = 0;

            for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) {

                currentUpperBound += entry.getValue();

                if (currentUpperBound >= targetCount) {
                    return entry.getKey();
                }
            }

        } else {

            // More complicated case - median is average of two middle values
            long target1Count = count / 2;
            long target2Count = target1Count + 1;
            double target1Value = Double.NaN;
            long prevUpperBound = -1;
            long currentUpperBound = 0;

            for (Map.Entry<Double, Integer> entry : countsByNumericValue.entrySet()) {

                currentUpperBound += entry.getValue();

                if (currentUpperBound >= target2Count) {

                    if (prevUpperBound < target1Count) {
                        // Both target values are the same
                        return entry.getKey();
                    } else {
                        return (target1Value + entry.getKey()) / 2.0;
                    }
                }

                if (currentUpperBound >= target1Count) {
                    target1Value = entry.getKey();
                }

                prevUpperBound = currentUpperBound;
            }
        }

        return null;
    }

    List<Map<String, Object>> findNumericTopHits(int numTopHits) {
        assert countsByNumericValue != null;
        return findTopHits(numTopHits, countsByNumericValue, Comparator.comparing(Map.Entry<Double, Integer>::getKey),
            FieldStats::toIntegerIfInteger);
    }

    List<Map<String, Object>> findStringTopHits(int numTopHits) {
        return findTopHits(numTopHits, countsByStringValue, Comparator.comparing(Map.Entry<String, Integer>::getKey), s -> s);
    }

    /**
     * Order by descending count, with a secondary sort to ensure reproducibility of results.
     */
    private static <T> List<Map<String, Object>> findTopHits(int numTopHits, Map<T, Integer> countsByValue,
                                                             Comparator<Map.Entry<T, Integer>> secondarySort,
                                                             Function<T, Object> outputMapper) {

        List<Map.Entry<T, Integer>> sortedByCount = countsByValue.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry<T, Integer>::getValue, Comparator.reverseOrder()).thenComparing(secondarySort))
            .limit(numTopHits).collect(Collectors.toList());

        List<Map<String, Object>> topHits = new ArrayList<>(sortedByCount.size());

        for (Map.Entry<T, Integer> entry : sortedByCount) {

            Map<String, Object> topHit = new LinkedHashMap<>(3);
            topHit.put("value", outputMapper.apply(entry.getKey()));
            topHit.put("count", entry.getValue());
            topHits.add(topHit);
        }

        return topHits;
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe UserSessionsController do

  #Delete this example and add some real ones
  it "should use UserSessionsController" do
    controller.should be_an_instance_of(UserSessionsController)
  end

  describe "POST create" do
    before(:each) do
      @user = Factory.create(:user)
    end

    describe "with correct parameters" do
      it "should succeed" do
        post :create, :user_session => {:login => @user.login, :password => 'foobar'}
        assigns(:user_session).user.should == @user
      end

      it "should redirect home" do
        post :create, :user_session => {:login => @user.login, :password => 'foobar'}
        response.should redirect_to(home_url)
      end

      it "should add a long entry" do
        old = LogEntry.count
        post :create, :user_session => {:login => @user.login, :password => 'foobar'}
        response.should redirect_to(home_url)
        LogEntry.count.should eql(old + 1)
      end
    end

    it "should fail with correct parametets" do
      post :create, :user_session => {:login => @user.login, :password => 'wrong password'}
      assigns(:user_session).user.should be_nil
    end

  end

end


text:
// JavaScript Document
// New Order, Edit Order and Customer Feedback page common code written here

$(document).ready(function(){

	// Code for floating button while scrolling start.....
	// page take-order.html
	var s = $("#sticker");
	var pos = s.position();

	$(window).scroll(function() {
		browser_width = $( window ).width();
		survey_box_height = $(".survey-box").height();
		survey_box_width = $(".survey-box").width();
		var windowpos = $(window).scrollTop();

		gap_height = browser_width <= 1180 ? windowpos+450 : windowpos-survey_box_height;

		//s.html("Survey-Box: "+survey_box_height+ "
Distance from top:" + pos.top + "
Scroll position: " + windowpos + "
Browser Width: " + browser_width);

		if (gap_height >= pos.top) {

			s.addClass("stick");
			s.css('width',survey_box_width);
		} else {
			s.removeClass("stick");
		}
	});
	// Code for floating button while scrolling end.......

	// Edit Order Form auto populate order summary on load
	var order_items_selected = $("input[name='Items[]']:checked").map(function(){
		   return $(this).val();
		}).get();

	$.each(order_items_selected,function(index,item_id){
		//console.log(item_id);
		populate_order_summary_box(item_id);
	});

});

$(document).on('click', '#overwrite_cancel', function(){
	$('#TakOrderError').html(' ');
	$('#SubmitBtn').show();
	$('#start_feedback_button').show();
});

$( ".MenuCategory" ).click(function() {

	previous_visible_category_id = $('.MenuItem:visible').attr('catid');
	category_id = $(this).closest('tr').attr('catrowid');

	// Hide the previous visible element
	if(previous_visible_category_id != category_id)
	{
		$(".category_items_row_"+previous_visible_category_id).hide();
	}

	// Toggle current clicked element
	$( ".category_items_row_"+category_id ).toggle( "slow", function() {
	// Animation complete.
	});
});

// hide all MenuItem
$('.MenuItem').hide();

$(document).on('click', '.add-amount', function(){
	var ItemID = $(this).attr('data-id');
	var CurrentValue = $('#'+ItemID+'_selected input[name="selecteditemsQuantity[]"]').val();
	var NewValue = parseInt(CurrentValue) + parseInt(1);
	if($('#'+ItemID+'_selected').length)
	{
		$('#'+ItemID+'_selected input[name="selecteditemsQuantity[]"]').val(NewValue);
		$('#'+ItemID+'_quantity_box').html(NewValue);
		$('#'+ItemID+'_quantity_box_summary').html(NewValue);
	}
});

$(document).on('click', '.minus-amount', function(){
	var ItemID = $(this).attr('data-id');
	if($('#'+ItemID+'_selected').length)
	{
		var CurrentValue = $('#'+ItemID+'_selected input[name="selecteditemsQuantity[]"]').val();
		if(CurrentValue>1)
		{
			var NewValue = parseInt(CurrentValue) - parseInt(1);
			$('#'+ItemID+'_selected input[name="selecteditemsQuantity[]"]').val(NewValue);
			$('#'+ItemID+'_quantity_box').html(NewValue);
			$('#'+ItemID+'_quantity_box_summary').html(NewValue);
		}
	}
});

$(document).on('click', '.OrderItem', function(){
	var ItemID = $(this).val();

	if($(this).is(':checked'))
	{
		/*$('#Amount_'+ItemID+' li a').css('opacity', '1');
		var ItemImage = $('#'+ItemID+'_image').html();
		var Quantity = $('#'+ItemID+'_quantity_box').html();
		var ItemName = $('#'+ItemID+'_title').html();
		var ItemDesc = $('#'+ItemID+'_desc').html();
		var ItemPrice = $('#'+ItemID+'_price').html();
		var ItemRequestComment = $('#'+ItemID+'_request_comment').val();
		$('#SelectItemMsg').hide();
		var HTML = '
';
			HTML += '<input type="hidden" name="selecteditemsQuantity[]" value="'+Quantity+'" /><input type="hidden" name="selecteditems[]" value="'+ItemID+'" />';
			HTML += '
'+ItemImage+'
';
			HTML += '

'+ItemName+' x '+Quantity+'

'+ItemDesc+'

'+ItemRequestComment+'

'+ItemPrice+' x '+Quantity+'

';
			HTML += '
X
';
			HTML += '

';
			HTML += '';
		HTML += '
';
		$('#ShowSelectedItems').append(HTML);*/
		populate_order_summary_box(ItemID);
	}
	else
	{
		$('#Amount_Item_'+ItemID+' a').css('opacity', '0.4');
		$('#Item_'+ItemID+'_selected').remove();
	}
});

$(document).on('submit', '#TakeOrderForm', function(){
	var Table = $('#Table').val();
	var temporary = $('#temporary').val();

	var Form = $('#TakeOrderForm').serialize();
	$('#TakOrderError').html('Please wait...');
	$.post(WEB_URL+"order/take_order", Form, function(Data, textStatus){
			if(Data.Error==0)
			{
				if(temporary == 1)
				{
					window.location.href = WEB_URL+"order/make_feedback_for_single_table/?temporary="+temporary+"&Table="+Table;
				}
				$('.notification').html(Data.Msg);
				ShowNotification();
				$('#TakOrderError').html(' ');

				$('input[type="checkbox"]').removeAttr('checked');
				$('#ShowSelectedItems li').remove();
				$('#SelectItemMsg').css('display', '');
				$('.DisplayQuantities').html('1');
				$('.order-amounts li a').removeAttr('style');
				$('.special_comment_textbox').val('');
				$('#customerid').val('');
				$('#SubmitBtn').show();
				// hide all MenuItem
				$('.MenuItem').hide();
				$('#keyword').val('');
				$('#hidden_table').val($('#Table').val());
				$('#Table').val('');
				$('#customerid').focus();
				window.scrollTo(0, 0); // scroll top of the page.

				if(Data.temporary_pending_orders_count > 0 && Data.table_number > 0)
				{
					check_temporary_pending_orders(Data.table_number);
				}
			}
			else
			{
				if(Data.action=='hide confirm order button')
				{
					$('#SubmitBtn').hide();
					$('#start_feedback_button').hide();
				}
				$('#TakOrderError').html(Data.Msg);
			}

			//if(Data.Url!=''){ window.location.href=Data.Url; }

	}, 'json');
	return false;
});

$(document).on('click', '.removeSelected', function(){
	var ItemID = $(this).attr('id');
	$('input[id="'+ItemID+'"]').removeAttr('checked');
	$('#'+ItemID+'_selected').remove();
});

function update_req_comm(element,index_id)
{
	$('#Item_'+index_id+'_drequest_comment').val(element.value);
}

function update_req_comm_duplicate(element,index_id)
{
	$('#Item_'+index_id+'_request_comment').val(element.value);
}

function populate_order_summary_box(ItemID)
{
	item_id = ItemID;
	ItemID = 'Item_'+ItemID;
	$('#Amount_'+ItemID+' a').css('opacity', '1');
	var ItemImage = $('#'+ItemID+'_image').html();
	var Quantity = $('#'+ItemID+'_quantity_box').html();
	var ItemName = $('#'+ItemID+'_title').html();
	var ItemDesc = $('#'+ItemID+'_desc').html();
	var ItemPrice = $('#'+ItemID+'_price').html();
	var ItemRequestComment = $('#'+ItemID+'_request_comment').val();
	$('#SelectItemMsg').hide();
	var HTML = '
';
		HTML += '<input type="hidden" name="selecteditemsQuantity[]" value="'+Quantity+'" /><input type="hidden" name="selecteditems[]" value="'+ItemID+'" />';
		HTML += '
'+ItemImage+'
';
		HTML += '
'+ItemName+'
';
		HTML += '
'+ItemDesc+'
';
		HTML += '

';
		HTML += '	';
		HTML += ''+Quantity+'	';
		HTML += '	';
		HTML += '

';
		HTML += '

'+ItemPrice+'
   <input type="text" name="request_comment_summary_box[]" id="'+ItemID+'_drequest_comment" value="'+ItemRequestComment+'" placeholder="Special Reqeust" onKeyUp="update_req_comm_duplicate(this, \''+item_id+'\');"  >
';
		HTML += '
X
';
		HTML += '

';
		HTML += '';
	HTML += '
';
	$('#ShowSelectedItems').append(HTML);
}

function search_item()
{
	keyword = $( '#keyword' ).val();

	$.each(items_tags,function(index,value){

		//console.log(value);
		if(value == keyword)
		{
			chunks = index.split('-');
			category_id = chunks[0];
			item_id = chunks[1];

			display_search_result(category_id,item_id);
			return false;
		}

	});

}
function display_search_result(category_id,item_id)
{
	// hide all MenuItem
	$('.MenuItem').hide();

	previous_visible_category_id = $('.MenuItem:visible').attr('catid');

	// Hide the previous visible element
	$(".category_items_row_"+previous_visible_category_id).hide();

	// Toggle current clicked element
	$( ".category_items_row_"+category_id ).toggle( "slow", function() {
	// Animation complete.
	});

	$('#Record_'+item_id).focus();
	$('#Record_'+item_id).effect("pulsate", {}, 1000);

	var windowHeight = $(window).height();
	var elementHeight = $('#Record_'+item_id).height();

	var elementPosition = $('#Record_'+item_id).position();
	var elementTop = elementPosition.top;

	var toScroll = (windowHeight / 2) - (elementHeight / 2);

	window.scroll(0,(elementTop - toScroll));
}


text:
import urllib2

from webkitpy.common.net.network_transaction import NetworkTransaction

class Web(object):

    def get_binary(self, url, return_none_on_404=False):
        return NetworkTransaction(return_none_on_404=return_none_on_404).run(lambda: urllib2.urlopen(url).read())


text:
angular.module('backend-module.category', [])
    .config(['$stateProvider', function ($stateProvider) {
        $stateProvider.state('backend.category', {
            url: '/category?id_cat&list',
            templateUrl: 'backend/category/category-module.html',
            controller: 'CategoryController',
            resolve: {
                _categoryFieldsHome: [
                    'CategoryCategoriesFormatted', '$stateParams',
                    function (CategoryCategoriesFormatted, $stateParams) {
                        if ($stateParams.id_cat) {
                            return CategoryCategoriesFormatted.getList({"parent_id": $stateParams.id_cat});
                        }
                        else {
                            return CategoryCategoriesFormatted.getList();
                        }
                    }
                ],
                _newestCategories: [
                    'CategoryCategories', '$stateParams',
                    function (CategoryCategories) {
                        return CategoryCategories.getList({
                            'sort': '-updatedAt',
                            'per-page': 4
                        });
                    }
                ]
            }

        })
    }
    ])
    .controller('CategoryController',
        ['$scope', '$modal', '$timeout', '$state', '$stateParams', '_categoryFieldsHome', '_newestCategories',
            function ($scope, $modal, $timeout, $state, $stateParams, _categoryFieldsHome, _newestCategories) {
                $scope.newestCategories = _newestCategories.data;

                $scope.listCategoriesExpanded = [];
                if ($stateParams.list) {

                    $scope.listCategoriesExpanded = JSON.parse("[" + $stateParams.list + "]");

                }

                $scope.idCategory = $stateParams.list;

                $scope.state = $state;
                $scope.categoryFieldsHome = _categoryFieldsHome.data;
                $scope.goInCategory = function (idCategory) {
                    $scope.listCategoriesExpanded.push(idCategory);

                    goToTheCurrentState(idCategory, $scope.listCategoriesExpanded.toString());

                };
                $scope.deleteLastRecord = function () {
                    $scope.listCategoriesExpanded.pop();
                    var idCategory = $scope.listCategoriesExpanded[$scope.listCategoriesExpanded.length - 1];
                    goToTheCurrentState(idCategory, $scope.listCategoriesExpanded.toString());
                };

                function goToTheCurrentState(idCategory, listStringCategories) {
                    $state.go(".",
                        {
                            id_cat: idCategory,
                            list: listStringCategories
                        });
                }
            }]);


text:
package org.kie.workbench.common.stunner.bpmn.client.forms.fields.notificationsEditor.widget;

import com.google.gwt.user.client.ui.IsWidget;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.NotificationRow;

public interface NotificationEditorWidgetView extends IsWidget {

    interface Presenter {

        String getNameHeader();

        String getExpirationLabel(String type);

        void createOrEdit(NotificationWidgetView parent, NotificationRow row);
    }

    void init(final NotificationEditorWidgetView.Presenter presenter);

    void createOrEdit(NotificationWidgetView parent, NotificationRow row);

    void setReadOnly(boolean readOnly);
}


text:
<?php
/**
 * Job to update link tables for pages
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup JobQueue
 */

/**
 * Job to prune link tables for pages that were deleted
 *
 * Only DataUpdate classes should construct these jobs
 *
 * @ingroup JobQueue
 * @since 1.27
 */
class DeleteLinksJob extends Job {
	function __construct( Title $title, array $params ) {
		parent::__construct( 'deleteLinks', $title, $params );
		$this->removeDuplicates = true;
	}

	function run() {
		if ( is_null( $this->title ) ) {
			$this->setLastError( "deleteLinks: Invalid title" );
			return false;
		}

		$pageId = $this->params['pageId'];
		if ( WikiPage::newFromID( $pageId, WikiPage::READ_LATEST ) ) {
			// The page was restored somehow or something went wrong
			$this->setLastError( "deleteLinks: Page #$pageId exists" );
			return false;
		}

		$timestamp = isset( $this->params['timestamp'] ) ? $this->params['timestamp'] : null;

		$page = WikiPage::factory( $this->title ); // title when deleted
		$update = new LinksDeletionUpdate( $page, $pageId, $timestamp );
		DataUpdate::runUpdates( [ $update ] );

		return true;
	}
}


text:
package cz.zcu.fav.remotestimulatorcontrol.model.configuration.tvep;

import org.junit.Before;
import org.junit.Test;

import cz.zcu.fav.remotestimulatorcontrol.model.configuration.AConfiguration;
import cz.zcu.fav.remotestimulatorcontrol.model.configuration.tvep.ConfigurationTVEP.Pattern;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotSame;

/**
 * Testovací třída pro třídu {@link ConfigurationTVEP}
 */
public class ConfigurationTVEPTest {

    private static final String DEFAULT_NAME = "test";

    private ConfigurationTVEP configuration;

    @Before
    public void setUp() throws Exception {
        configuration = new ConfigurationTVEP(DEFAULT_NAME);
    }

    // region PATTERN_LENGTH parameter
    @Test
    public void testGetDefaultPatternLengthValue() throws Exception {
        assertEquals("Chyba: Výchozí hodnota parametru 'patternLength' má špatnou hodnotu.", ConfigurationTVEP.DEF_PATTERN_LENGTH, configuration.getPatternLength());
    }
    // endregion

    // region PULS_LENGTH parameter
    @Test
    public void testGetDefaultPulsLengthValue() throws Exception {
        assertEquals("Chyba: Výchozí hodnota parametru 'pulsLength' má špatnou hodnotu.", ConfigurationTVEP.DEF_PULS_LENGTH, configuration.getPulsLength());
    }
    // endregion

    // region TIME_BETWEEN parameter
    @Test
    public void testGetDefaultTimeBetweenValue() throws Exception {
        assertEquals("Chyba: Výchozí hodnota parametru 'timeBetween' má špatnou hodnotu.", ConfigurationTVEP.DEF_TIME_BETWEEN, configuration.getTimeBetween());
    }
    // endregion

    // region BRIGHTNESS parameter
    @Test
    public void testGetDefaultBrightnessValue() throws Exception {
        assertEquals("Chyba: Výchozí hodnota parametru 'brightness' má špatnou hodnotu.", AConfiguration.DEF_BRIGHTNESS, configuration.getBrightness());
    }
    // endregion

    // region ConfigurationDuplicate
    @Test
    public void testDuplicatePositive() throws Exception {
        String duplicatedName = "duplicated";
        ConfigurationTVEP duplicated = (ConfigurationTVEP) configuration.duplicate(duplicatedName);

        // Kontrola, jestli se duplikovaly informace z abstraktní třídy AConfiguration
        assertNotSame("Chyba: Duplikovaná konfigurace má stejný název jeko originální.", configuration.getName(), duplicated.getName());
        assertEquals("Chyba: Duplikovaná konfigurace není stejného typu jako originální.", configuration.getConfigurationType(), duplicated.getConfigurationType());
        assertEquals("Chyba: Duplikovaná konfigurace nemá styjný typ media jako originální.", configuration.getMediaType(), duplicated.getMediaType());
        assertEquals("Chyba: Duplikovaná konfigurace nemá stejný počet výstupů jako originální.", configuration.getOutputCount(), duplicated.getOutputCount());
        assertEquals("Chyba: Duplikovaná konfigurace nemá stejný parametr 'valid' jako originální", configuration.isValid(), duplicated.isValid());
        assertEquals("Chyba: Duplikovaná konfigurace nemá stejný parametr 'validityFlag' jako originální", configuration.getValidityFlag(), duplicated.getValidityFlag());

        // Kontrola, jestli se zduplikovaly informace z konkrétní třídy ConfigurationTVEP
        assertNotSame("Chyba: Kolekce výstupů v duplikované konfiguraci ukazuje na stejnou referenci jako originální.", configuration.patternList, duplicated.patternList);
        assertEquals("Chyba: Kolekce výstupů v duplikované konfigurace nemá stejný počet výstupů jako originální.", configuration.getOutputCount(), duplicated.patternList.size());
        assertEquals("Chyba: Velikost duplikované kolekce neodpovídá velikosti originální kolekce.", configuration.patternList.size(), duplicated.patternList.size());

        for (int i = 0; i < duplicated.getOutputCount(); i++) {
            Pattern duplicatedOutput = duplicated.patternList.get(i);
            Pattern originalOutput   = configuration.patternList.get(i);

            assertEquals("Chyba: Duplikovaný pattern nemá stejné ID jako originální.", originalOutput.getId(), duplicatedOutput.getId());
            assertEquals("Chyba: Duplicovaný pattern nemá stejnou hodnotu jako originální.", originalOutput.getValue(), duplicatedOutput.getValue());
        }
    }
    // endregion

    // region OutputCount
    @Test
    public void testGetDefaultOutputCount() throws Exception {
        assertEquals("Chyba: Výchozí počet výstupů má špatnou hdnotu.", AConfiguration.DEF_OUTPUT_COUNT, configuration.getOutputCount());
        assertEquals("Chyba: Výchozí velikost kolekce neodpovídá výchozímu počtu výstupů.", AConfiguration.DEF_OUTPUT_COUNT, configuration.patternList.size());
    }

    @Test
    public void testOutputCountPositive() throws Exception {
        int outputCount = AConfiguration.DEF_OUTPUT_COUNT - 1;
        configuration.setOutputCount(outputCount);

        assertEquals("Chyba: Vrácený počet výstupů se neshoduje s nastavenou hodnotou.", outputCount, configuration.getOutputCount());
        assertEquals("Chyba: Velikost kolekce s výstupy se neshoduje s parametrem 'outputCount'.", outputCount, configuration.patternList.size());
    }
    // endregion
}


text:
Creating regular, secure backups of data on your mobile devices is important, whether you want to protect against loss, theft, or catastrophic user error (eg. accidentally wiping your device while encrypting it). This session will cover the creation of encrypted backups for iOS and Android users, and make recommendations on a backup schedule. Even if you don't get on a regular schedule, you should always backup your phone before you make any major changes to it.

Getting everyone started backing up their phones is a great way to make sure everyone leaves a workshop with something solidly accomplished.

## About This Lesson Plan

**Review date:** Dec 5, 2017

**Lesson duration:** This should take under an hour.

**Level:** Introductory

**What materials will participants need?**

Any phones or tablets they want to back up.

**What materials will the instructor need?**

**Links in the news**

+ BuzzFeed's Nicole Nguyen has a nice [round up of backup apps](https://www.buzzfeed.com/nicolenguyen/what-to-do-if-your-phones-storage-is-full)

+ Hackers Stole My Life by [Mat Honan on Wired](https://www.wired.com/2012/08/apple-amazon-mat-honan-hacking/) is a great lesson in the perils of cloud backups.

## Lesson Plan

Read [EFF on Harm Reduction](https://sec.eff.org/articles/harm-reduction) -- it's an important perspective to keep in mind here. And remember that it is better to acknowledge it when you're [out of scope](https://sec.eff.org/articles/out-of-scope), than to bluff or share bad information.

Everyone should take stock of what is actually on their phone that isn't already backed up. Most folks are syncing calendars and contacts with [Nextcloud](https://nextcloud.com/) or Google or iCloud or iTunes already, but if anyone isn't, start there.

Have everyone go through the apps installed on their phones (this is also a fine time to think about deleting apps you don't use). Some things, like email, are easily restored from settings, but if you know you're going to do a hard reset on your phone, take a moment to make sure you have a record of those settings.

+ Social Media (eg. Tumblr, Twitter, What's App) is easy to restore if you know your login information.
+ Email often requires you to know a few settings.
+ Two Factor Authentication can really throw you -- if you're using 2FA open your authenticator app and make sure that you have backup codes for every service listed. If you aren't, make that sure that's one of your next sessions. :)
+ Photos might be backed up automatically but if you'll be devastated to lose them, consider copying them to a hard drive somewhere.
+ Podcast subscriptions probably aren't dire, but you can usually export an OPML that will make it easy to restore your subscriptions after a reset.

As other things come up, add to this list. Does the app contain data or settings that need backing up? What's a good strategy for making that backup happen?

Note: we'd love your help expanding this lesson. Consider filing an [issue](https://github.com/OpenNewsLabs/newsroom-security-curricula/issues) or pull request if there are valuable backup points that you think belong here.

### Automated Backups
By default, Android phones back up quite a bit of data to Google, iOS phones to iCloud. These baked in cloud backup services are far and away the easiest way to make sure that your contacts, photos and calendar are backed up someplace off of your phone. However, commercial cloud backup services are not a good fit for everyone. Commercial cloud providers may not be willing or able to fight a subpoena for contacts you've backed up to their server.

Where you back your work up depends a lot on your values and threat model. For some folks, the risk of losing all their data outweighs their discomfort with or handing over evermore personal data to Google or Apple.

Setting up and hosting your own service ([Nextcloud](https://nextcloud.com/) or [ownCloud](https://owncloud.com/) are good options if you want to go that route) is not a trivial undertaking. Keeping up with updates and ensuring that your server is configured securely are all you as the host. You can also [pay someone to maintain Nextcloud for you](https://nextcloud.com/providers/).

Users should make a conscious decision about their own needs and values: if you're fine backing up to Google or iCloud, then go for it. If you'd rather backup to them than lose all your data, then go ahead and make sure things are getting backed up while you work on setting up a more perfect solution. And if you'd rather risk losing your contacts than backing up to a Google or iCloud, at least take a moment to export your data and back it up manually from time to time.

Some folks like to start over with a clean slate from time to time -- they're fine not backing up at all.

Everyone's backup strategy is going to be different. Your goal is to find a strategy that you'll actually stick with, and that suits your values.

### Android Users
In addition to backing up to a cloud or web-based service, Android users can back up directly to a laptop or desktop via USB.  Just watch out for power-only USB cables that don't support data transfer. You should see a prompt inviting you to allow file transfer when you connect your phone to your laptop via USB -- it might be labeled "MTP" or "FTP". Once you accept that, your phone should mount as a drive on your laptop. If you're going to make a one-off backup like this, especially if you're going to be resetting your phone consider also ...

+ Export your contacts to a `.vcf` file (`Import/Export` is one of just four menu options) and back that up.
+ Most podcast apps will let you export an OPML file so you can restore your subscriptions.

### iOS Users

*You can help us make this lesson stronger by [contributing](contributing.html) insights on backup strategies for iOS users.*


text:
package dmtest.stack

import dmtest._

object Pool {
  case class S(pool: Pool, size: Sector) extends Stack {
    private val linear: Linear = pool.alloc(size)
    override def terminate: Unit = {
      pool.free(linear)
    }
    override def path = linear.path
  }
  case class Range(start: Sector, len: Sector) extends Ordered[Range] {
    override def compare(that: Range): Int = (this.start.unwrap - that.start.unwrap).toInt
    def take(size: Sector): (Range, Range) = {
      require(len >= size)
      (Range(start, size), Range(start + size, len - size))
    }
  }
  class FreeArea(initSize: Sector) {
    val m = scala.collection.mutable.SortedSet[Range](Range(Sector(0), initSize))
    def getFreeSpace(size: Sector): Range = {
      val target = m.find(_.len >= size).get
      m -= target
      val (res, rem) = target.take(size)
      if (rem.len > Sector(0)) m += rem
      res
    }
    def merge(): Boolean = {
      val a = m.toList
      val b = m.toList.drop(1)
      a.zip(b).find { case (x, y) =>
        x.start + x.len == y.start
      } match {
        case Some((x, y)) =>
          m -= x
          m -= y
          m += Range(x.start, x.len + y.len)
          true
        case None => false
      }
    }
    def release(range: Range) = {
      m += range
      while (merge) {}
    }
  }
}
case class Pool(pool: Stack) {
  import Pool._
  val freeArea = new FreeArea(pool.bdev.size)
  def alloc(size: Sector): Linear = {
    val space = freeArea.getFreeSpace(size)
    Linear.Table(pool, space.start, space.len).create
  }
  def free(linearS: Linear): Unit = {
    linearS.terminate()
    val space = Range(linearS.start, linearS.len)
    freeArea.release(space)
  }
}


text:
// Copyright (c) 2013-present, febit.org. All Rights Reserved.
package org.febit.wit.loggers;

/**
 * @author zqq90
 */
public interface Logger {

    boolean isDebugEnabled();

    void debug(String msg);

    void debug(String format, Object... args);

    void debug(String msg, Throwable t);

    boolean isInfoEnabled();

    void info(String msg);

    void info(String format, Object... args);

    void info(String msg, Throwable t);

    boolean isWarnEnabled();

    void warn(String msg);

    void warn(String format, Object... args);

    void warn(String msg, Throwable t);

    boolean isErrorEnabled();

    void error(String msg);

    void error(String format, Object... args);

    void error(String msg, Throwable t);
}


text:
@interface MWMSideMenuView : SolidTouchView <MWMSideMenuDownloadBadgeOwner>

@property (weak, nonatomic, readonly) IBOutlet UIView * dimBackground;
@property (weak, nonatomic) id<MWMSideMenuInformationDisplayProtocol> delegate;
@property (weak, nonatomic) MWMSideMenuDownloadBadge * downloadBadge;

- (instancetype)initWithFrame:(CGRect)frame __attribute__((unavailable("initWithFrame is not available")));
- (instancetype)init __attribute__((unavailable("init is not available")));

- (void)setup;

@end


text:
Jobs Available

        {{ item.name }}

Add new job

      <form ng-submit="addJob()" class="form-inline" role="form">

          <input type="text" ng-model="jobTitle" class="form-control" placeholder="Enter a course name">

        <button type="submit" class="btn btn-default btn-lg">Submit</button>
      </form>


text:
(function() {

    'use strict';
    var isIonic = !!window.ionic;

    function TrailappAgendaButtonController($scope, TrailappAgendaService) {
        var self = this;

        self.isIonic = isIonic;

        self.state = 'none';
        self.inAgenda = false;
        self.mouseover = false;

        $scope.$watch("occurrence", function(newValue, oldValue) {
            self.occurrence = newValue;
            update();
        });

        function update() {
            self.state = 'loading';
            if (!self.occurrence) {
                self.state = 'none';
                return;
            }
            TrailappAgendaService.get(function(agenda) {
                for (var iii = 0; iii < agenda.length; iii++) {
                    if (agenda[iii].OccurrenceId === self.occurrence.OccurrenceId)
                        self.inAgenda = true;
                }
                self.state = 'done';
            }, function(err) {
                self.state = 'error';
            });
        }

        self.onClick = function() {
            if (self.state !== 'done') return;
            self.state = 'loading';
            if (self.inAgenda) {
                TrailappAgendaService.postRemove(self.occurrence.OccurrenceId, function() {
                    self.state = 'done';
                    self.inAgenda = false;
                }, function(err) {
                    alert('There was a problem removing this from the agenda');
                    self.state = 'error';
                });
            } else {
                TrailappAgendaService.postAdd(self.occurrence, function() {
                    self.state = 'done';
                    self.inAgenda = true;
                }, function(err) {
                    alert('There was a problem adding this to the agenda');
                    self.state = 'error';
                });
            }
        };
    }

    TrailappAgendaButtonController.$inject = ['$scope', 'TrailappAgendaService'];

    function trailappAgendaButton() {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'shared/agenda/agenda.button.html',
            controller: 'TrailappAgendaButtonController',
            controllerAs: 'AgendaBtnCtrl',
            scope: {
                occurrence: '='
            }
        };
    }

    function trailappAgendaIonOptionButton() {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'shared/agenda/agenda.button.option.html',
            controller: 'TrailappAgendaButtonController',
            controllerAs: 'AgendaBtnCtrl',
            scope: {
                occurrence: '='
            }
        };
    }

    function TrailappAgendaService(trailappConfig, ApiService, TrailappAuthService) {
        var agenda;
        var service = {};
        var self = this;

        function getWithHighestAuth() {
            if (TrailappAuthService.getUser())
                return 'getWithToken';
            else
                return 'getWithSystemId';
        }

        function postJsonWithHighestAuth() {
            if (TrailappAuthService.getUser())
                return 'postJsonWithToken';
            else
                return 'postJsonWithSystemId';
        }

        var getInProgress = false;
        var getOnSuccess = [],
            getOnError = [];

        service.get = function(onSuccess, onError) {
            if (agenda)
                return onSuccess(agenda);
            else if (service.agendaId) {
                getOnSuccess.push(onSuccess);
                getOnError.push(onError);
                if (!getInProgress) {
                    getInProgress = true;
                    ApiService[getWithHighestAuth()]('/api/agendas/details/' + service.agendaId)
                        .$promise.then(function(data) {
                            agenda = data.EventOccurrences;
                            getInProgress = false;
                            for (var iii = 0; iii < getOnSuccess.length; iii++) {
                                getOnSuccess[iii](agenda);
                            }
                            getOnSuccess = [];
                            getOnError = [];
                        }, function(err) {
                            getInProgress = false;
                            if(err.status === 404) {
                                if (typeof(Storage) !== "undefined")
                                    localStorage[trailappConfig.systemId + "_agendaId"] = undefined;
                                service.agendaId = undefined;
                                for (var iii = 0; iii < getOnSuccess.length; iii++) {
                                    getOnSuccess[iii]([]);
                                    agenda = [];
                                }
                            }
                            else {
                                for (var iii = 0; iii < getOnError.length; iii++) {
                                    getOnError[iii](err);
                                }
                            }
                            getOnSuccess = [];
                            getOnError = [];
                        });
                }
            } else {
                return onSuccess([]);
            }
        };

        service.setNewAgendaId = function(newId, onSuccess, onError) {
            var oldId = service.agendaId;
            var oldAgenda = agenda;
            agenda = undefined;
            service.agendaId = newId;
            service.get(function(agenda) {
                if (typeof(Storage) !== "undefined")
                    localStorage[trailappConfig.systemId + "_agendaId"] = newId;
                onSuccess(agenda);
            }, function(err) {
                agenda = oldAgenda;
                agendaId = oldId;
                onError(err);
            });
        };

        service.postAdd = function(occurrence, onSuccess, onError) {
            ApiService[postJsonWithHighestAuth()]('/api/agendas/add', {
                OccurrenceId: occurrence.OccurrenceId,
                AgendaId: service.agendaId
            }).$promise.then(function(data) {
                if (!service.agendaId) {
                    service.agendaId = data.AgendaId;
                    if (typeof(Storage) !== "undefined") {
                        localStorage[trailappConfig.systemId + "_agendaId"] = service.agendaId;
                        service.get(function() {}, function() {});
                    }
                    agenda = [];
                }
                agenda.push(occurrence);
                _.sortByAll(agenda, 'IsCancelled', 'Start');
                return onSuccess();
            }, onError);
        };

        service.postRemove = function(occurrenceId, onSuccess, onError) {
            ApiService[postJsonWithHighestAuth()]('/api/agendas/remove', {
                OccurrenceId: occurrenceId,
                AgendaId: service.agendaId
            }).$promise.then(function(data) {
                _.remove(agenda, function(a) {
                    return a.OccurrenceId === occurrenceId;
                });
                return onSuccess();
            }, onError);
        };

        service.suggestedEvents = function(agendaId, onSuccess, onError) {
            ApiService[getWithHighestAuth()]('/api/agendas/suggested/' + service.agendaId)
                .$promise.then(onSuccess, onError);
        };

        // If localStorage supported then get stored token
        if (typeof(Storage) !== "undefined") {
            service.agendaId = localStorage[trailappConfig.systemId + "_agendaId"];
            service.get(function() {}, function() {});
        }

        return service;
    }

    TrailappAgendaService.$inject = ['trailappConfig', 'ApiService', 'TrailappAuthService'];

    angular
        .module('trailapp.agenda', [])
        .controller('TrailappAgendaButtonController', TrailappAgendaButtonController)
        .directive('trailappAgendaButton', trailappAgendaButton)
        .directive('trailappAgendaIonOptionButton', trailappAgendaIonOptionButton)
        .factory('TrailappAgendaService', TrailappAgendaService);

})();


text:
namespace ktt
{

VulkanPushConstant::VulkanPushConstant(const std::vector<KernelArgument*>& arguments)
{
    m_Range.size = 0;
    m_Range.offset = 0;
    m_Range.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;

    for (const auto* argument : arguments)
    {
        KttAssert(argument->GetMemoryType() == ArgumentMemoryType::Scalar || argument->GetMemoryType() == ArgumentMemoryType::Symbol,
            "Only scalar and symbol arguments can be used as push constants");
        const size_t dataSize = argument->GetDataSize();

        for (size_t i = 0; i < dataSize; ++i)
        {
            m_Data.push_back(argument->GetDataWithType<uint8_t>()[i]);
        }

        m_Range.size += static_cast<uint32_t>(dataSize);
    }

    uint32_t paddingSize = 0;

    if (m_Range.size % 4 != 0)
    {
        paddingSize = 4 - m_Range.size % 4;
    }

    for (uint32_t i = 0; i < paddingSize; ++i)
    {
        m_Data.push_back(0);
    }

    m_Range.size += paddingSize;
}

const VkPushConstantRange& VulkanPushConstant::GetRange() const
{
    return m_Range;
}

const std::vector<uint8_t>& VulkanPushConstant::GetData() const
{
    return m_Data;
}

bool VulkanPushConstant::IsValid() const
{
    return !m_Data.empty();
}

} // namespace ktt

#endif // KTT_API_VULKAN


text:
namespace Ui {
	class MainWindow;
}

class MainWindow : public QMainWindow {
	Q_OBJECT

	public:
		explicit MainWindow(QWidget *parent = 0);
		~MainWindow();

	private slots:
		void on_actionOpen_Database_triggered();
		void on_treeView_clicked(const QModelIndex &index);

		void on_MainWindow_destroyed();

	private:
		Ui::MainWindow *ui;
		QueryField *queryField;
		QTableView *tableView;
		QHeaderView *horizontalHeader;

		SQLHelper sql;
		QStringList tables_list;

};

#endif // MAINWINDOW_H


text:
SOAP Server 6: setclass with constructor
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
class Foo {
  private $str = "";

  function Foo($str) {
    $this->str = $str . " World";
  }

  function test() {
    return $this->str;
  }
}

$server = new soapserver(null,array('uri'=>"http://testuri.org"));
$server->setclass("Foo","Hello");

$HTTP_RAW_POST_DATA = <<<EOF
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:si="http://soapinterop.org/xsd">
  <SOAP-ENV:Body>
    <ns1:test xmlns:ns1="http://testuri.org" />
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOF;

$server->handle($HTTP_RAW_POST_DATA);
echo "ok\n";
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://testuri.org" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:testResponse><return xsi:type="xsd:string">Hello World</return></ns1:testResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
ok


text:
package plugin

import (
	"github.com/mitchellh/packer/packer"
	"log"
)

type cmdPostProcessor struct {
	p      packer.PostProcessor
	client *Client
}

func (c *cmdPostProcessor) Configure(config ...interface{}) error {
	defer func() {
		r := recover()
		c.checkExit(r, nil)
	}()

	return c.p.Configure(config...)
}

func (c *cmdPostProcessor) PostProcess(ui packer.Ui, a packer.Artifact) (packer.Artifact, bool, error) {
	defer func() {
		r := recover()
		c.checkExit(r, nil)
	}()

	return c.p.PostProcess(ui, a)
}

func (c *cmdPostProcessor) checkExit(p interface{}, cb func()) {
	if c.client.Exited() && cb != nil {
		cb()
	} else if p != nil && !Killed {
		log.Panic(p)
	}
}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_ORTHOMETHODS_H
#define EIGEN_ORTHOMETHODS_H

namespace Eigen {

/** \geometry_module
  *
  * \returns the cross product of \c *this and \a other
  *
  * Here is a very good explanation of cross-product: http://xkcd.com/199/
  *
  * With complex numbers, the cross product is implemented as
  * \f$ (\mathbf{a}+i\mathbf{b}) \times (\mathbf{c}+i\mathbf{d}) = (\mathbf{a} \times \mathbf{c} - \mathbf{b} \times \mathbf{d}) - i(\mathbf{a} \times \mathbf{d} - \mathbf{b} \times \mathbf{c})\f$
  *
  * \sa MatrixBase::cross3()
  */
template<typename Derived>
template<typename OtherDerived>
inline typename MatrixBase<Derived>::template cross_product_return_type<OtherDerived>::type
MatrixBase<Derived>::cross(const MatrixBase<OtherDerived>& other) const
{
  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,3)
  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3)

  // Note that there is no need for an expression here since the compiler
  // optimize such a small temporary very well (even within a complex expression)
  typename internal::nested_eval<Derived,2>::type lhs(derived());
  typename internal::nested_eval<OtherDerived,2>::type rhs(other.derived());
  return typename cross_product_return_type<OtherDerived>::type(
    numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)),
    numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)),
    numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0))
  );
}

namespace internal {

template< int Arch,typename VectorLhs,typename VectorRhs,
          typename Scalar = typename VectorLhs::Scalar,
          bool Vectorizable = bool((VectorLhs::Flags&VectorRhs::Flags)&PacketAccessBit)>
struct cross3_impl {
  static inline typename internal::plain_matrix_type<VectorLhs>::type
  run(const VectorLhs& lhs, const VectorRhs& rhs)
  {
    return typename internal::plain_matrix_type<VectorLhs>::type(
      numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)),
      numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)),
      numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0)),
      0
    );
  }
};

}

/** \geometry_module
  *
  * \returns the cross product of \c *this and \a other using only the x, y, and z coefficients
  *
  * The size of \c *this and \a other must be four. This function is especially useful
  * when using 4D vectors instead of 3D ones to get advantage of SSE/AltiVec vectorization.
  *
  * \sa MatrixBase::cross()
  */
template<typename Derived>
template<typename OtherDerived>
inline typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::cross3(const MatrixBase<OtherDerived>& other) const
{
  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,4)
  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,4)

  typedef typename internal::nested_eval<Derived,2>::type DerivedNested;
  typedef typename internal::nested_eval<OtherDerived,2>::type OtherDerivedNested;
  DerivedNested lhs(derived());
  OtherDerivedNested rhs(other.derived());

  return internal::cross3_impl<Architecture::Target,
                        typename internal::remove_all<DerivedNested>::type,
                        typename internal::remove_all<OtherDerivedNested>::type>::run(lhs,rhs);
}

/** \returns a matrix expression of the cross product of each column or row
  * of the referenced expression with the \a other vector.
  *
  * The referenced matrix must have one dimension equal to 3.
  * The result matrix has the same dimensions than the referenced one.
  *
  * \geometry_module
  *
  * \sa MatrixBase::cross() */
template<typename ExpressionType, int Direction>
template<typename OtherDerived>
const typename VectorwiseOp<ExpressionType,Direction>::CrossReturnType
VectorwiseOp<ExpressionType,Direction>::cross(const MatrixBase<OtherDerived>& other) const
{
  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3)
  EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename OtherDerived::Scalar>::value),
    YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)

  typename internal::nested_eval<ExpressionType,2>::type mat(_expression());
  typename internal::nested_eval<OtherDerived,2>::type vec(other.derived());

  CrossReturnType res(_expression().rows(),_expression().cols());
  if(Direction==Vertical)
  {
    eigen_assert(CrossReturnType::RowsAtCompileTime==3 && "the matrix must have exactly 3 rows");
    res.row(0) = (mat.row(1) * vec.coeff(2) - mat.row(2) * vec.coeff(1)).conjugate();
    res.row(1) = (mat.row(2) * vec.coeff(0) - mat.row(0) * vec.coeff(2)).conjugate();
    res.row(2) = (mat.row(0) * vec.coeff(1) - mat.row(1) * vec.coeff(0)).conjugate();
  }
  else
  {
    eigen_assert(CrossReturnType::ColsAtCompileTime==3 && "the matrix must have exactly 3 columns");
    res.col(0) = (mat.col(1) * vec.coeff(2) - mat.col(2) * vec.coeff(1)).conjugate();
    res.col(1) = (mat.col(2) * vec.coeff(0) - mat.col(0) * vec.coeff(2)).conjugate();
    res.col(2) = (mat.col(0) * vec.coeff(1) - mat.col(1) * vec.coeff(0)).conjugate();
  }
  return res;
}

namespace internal {

template<typename Derived, int Size = Derived::SizeAtCompileTime>
struct unitOrthogonal_selector
{
  typedef typename plain_matrix_type<Derived>::type VectorType;
  typedef typename traits<Derived>::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar,2,1> Vector2;
  EIGEN_DEVICE_FUNC
  static inline VectorType run(const Derived& src)
  {
    VectorType perp = VectorType::Zero(src.size());
    Index maxi = 0;
    Index sndi = 0;
    src.cwiseAbs().maxCoeff(&maxi);
    if (maxi==0)
      sndi = 1;
    RealScalar invnm = RealScalar(1)/(Vector2() << src.coeff(sndi),src.coeff(maxi)).finished().norm();
    perp.coeffRef(maxi) = -numext::conj(src.coeff(sndi)) * invnm;
    perp.coeffRef(sndi) =  numext::conj(src.coeff(maxi)) * invnm;

    return perp;
   }
};

template<typename Derived>
struct unitOrthogonal_selector<Derived,3>
{
  typedef typename plain_matrix_type<Derived>::type VectorType;
  typedef typename traits<Derived>::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  EIGEN_DEVICE_FUNC
  static inline VectorType run(const Derived& src)
  {
    VectorType perp;
    /* Let us compute the crossed product of *this with a vector
     * that is not too close to being colinear to *this.
     */

    /* unless the x and y coords are both close to zero, we can
     * simply take ( -y, x, 0 ) and normalize it.
     */
    if((!isMuchSmallerThan(src.x(), src.z()))
    || (!isMuchSmallerThan(src.y(), src.z())))
    {
      RealScalar invnm = RealScalar(1)/src.template head<2>().norm();
      perp.coeffRef(0) = -numext::conj(src.y())*invnm;
      perp.coeffRef(1) = numext::conj(src.x())*invnm;
      perp.coeffRef(2) = 0;
    }
    /* if both x and y are close to zero, then the vector is close
     * to the z-axis, so it's far from colinear to the x-axis for instance.
     * So we take the crossed product with (1,0,0) and normalize it.
     */
    else
    {
      RealScalar invnm = RealScalar(1)/src.template tail<2>().norm();
      perp.coeffRef(0) = 0;
      perp.coeffRef(1) = -numext::conj(src.z())*invnm;
      perp.coeffRef(2) = numext::conj(src.y())*invnm;
    }

    return perp;
   }
};

template<typename Derived>
struct unitOrthogonal_selector<Derived,2>
{
  typedef typename plain_matrix_type<Derived>::type VectorType;
  EIGEN_DEVICE_FUNC
  static inline VectorType run(const Derived& src)
  { return VectorType(-numext::conj(src.y()), numext::conj(src.x())).normalized(); }
};

} // end namespace internal

/** \returns a unit vector which is orthogonal to \c *this
  *
  * The size of \c *this must be at least 2. If the size is exactly 2,
  * then the returned vector is a counter clock wise rotation of \c *this, i.e., (-y,x).normalized().
  *
  * \sa cross()
  */
template<typename Derived>
typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::unitOrthogonal() const
{
  EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
  return internal::unitOrthogonal_selector<Derived>::run(derived());
}

} // end namespace Eigen

#endif // EIGEN_ORTHOMETHODS_H


text:
package soasimple.com.jackfruit;

public enum TestStatus {
	SUCESS,
	FAILURE,
	ERROR
}


text:
from nose.tools import raises
from nose.plugins.attrib import attr
from requests import HTTPError

from rightscale import RightScale

@raises(ValueError)
def test_empty_api_endpoint():
    rs = RightScale(refresh_token='not empty', api_endpoint='')
    rs.login()

@raises(ValueError)
def test_empty_refresh_token():
    rs = RightScale(refresh_token='', api_endpoint='not empty')
    rs.login()

@attr('real_conn')
@raises(HTTPError)
def test_bogus_refresh_token():
    rs = RightScale(refresh_token='bogus')
    rs.login()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ="vertical" ="fill_parent" ="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
<!--
id: 182580246
link: http://tumblr.atmos.org/post/182580246/four-phase-test-at-xunitpatterns-com
slug: four-phase-test-at-xunitpatterns-com
date: Mon Sep 07 2009 21:58:41 GMT-0700 (PDT)
publish: 2009-09-07
tags:
title: Four Phase Test at XUnitPatterns.com
-->

Four Phase Test at XUnitPatterns.com
=====================================

[http://xunitpatterns.com/Four Phase
Test.html](http://xunitpatterns.com/Four%20Phase%20Test.html)


text:
<?php
/**
 * Scripts
 */
add_action( 'wp_enqueue_scripts', 'nc_scripts' );
function nc_scripts() {
  wp_register_script( 'modernizr', get_theme_file_uri( 'assets/js/vendor/modernizr-3.11.2.min.js' ), false, '3.11.2', true );

  wp_deregister_script( 'jquery' );
  wp_register_script( 'jquery', get_theme_file_uri( 'assets/js/vendor/jquery-3.5.1.min.js' ), false, '3.5.1', true );

  if ( file_exists( get_theme_file_path( 'assets/js/scripts.js' ) ) ) {
    wp_enqueue_script( 'js-main', get_theme_file_uri( 'assets/js/scripts.js' ), array( 'modernizr', 'jquery' ), filemtime( get_theme_file_path( 'assets/js/scripts.js' ) ), true );
  }

  /**
   * Variables for JS (ncVar.ajax_url, ncVar.home_url, ncVar.theme_url, etc.)
   */
  wp_localize_script( 'js-main', 'ncVar', array(
    'ajax_url'  => admin_url( 'admin-ajax.php' ),
    'home_url'  => home_url(),
    'theme_url' => get_stylesheet_directory_uri(),
  ) );
}

/**
 * Clean up script tags
 */
add_filter( 'script_loader_tag', 'nc_clean_script_tag' );
function nc_clean_script_tag( $input ) {
  $input = str_replace( ' type="text/javascript"', '', $input );
  return $input;
}