text:
<!DOCTYPE HTML>

<title>org.freedesktop.dbus (dbus-java-core 4.2.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-05">
<meta name="description" content="declaration: module: org.freedesktop.dbus">
<meta name="generator" content="javadoc/ModuleWriterImpl">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

Module:

Description |

Modules |

Packages |

Services

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Module org.freedesktop.dbus

module org.freedesktop.dbus

Packages

Exports

Package

Description

org.freedesktop.dbus

org.freedesktop.dbus.annotations

org.freedesktop.dbus.bin

org.freedesktop.dbus.connections

org.freedesktop.dbus.connections.config

org.freedesktop.dbus.connections.impl

org.freedesktop.dbus.connections.transports

org.freedesktop.dbus.errors

org.freedesktop.dbus.exceptions

org.freedesktop.dbus.handlers

org.freedesktop.dbus.interfaces

org.freedesktop.dbus.messages

org.freedesktop.dbus.spi.message

org.freedesktop.dbus.spi.transport

org.freedesktop.dbus.types

org.freedesktop.dbus.utils

Copyright © 2022. All rights reserved.


text:
<?php

namespace Magento\Reports\Test\Unit\Observer;

class CatalogProductCompareAddProductObserverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Reports\Observer\CatalogProductCompareAddProductObserver
     */
    protected $observer;

    /**
     * @var \Magento\Reports\Observer\EventSaver|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $eventSaverMock;

    /**
     * @var \Magento\Customer\Model\Session|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerSessionMock;

    /**
     * @var \Magento\Customer\Model\Visitor|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customerVisitorMock;

    /**
     * @var \Magento\Reports\Model\Event|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $reportEventMock;

    /**
     * @var \Magento\Store\Model\Store|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $storeMock;

    /**
     * @var \Magento\Reports\Model\Product\Index\ComparedFactory|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $productCompFactoryMock;

    /**
     * @var \Magento\Reports\Model\Product\Index\Compared|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $productCompModelMock;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->customerSessionMock = $this->getMockBuilder('Magento\Customer\Model\Session')
            ->disableOriginalConstructor()->getMock();
        $this->customerVisitorMock = $this->getMockBuilder('Magento\Customer\Model\Visitor')
            ->disableOriginalConstructor()->getMock();

        $reportEventFactory = $this->getMockBuilder('Magento\Reports\Model\EventFactory')
            ->setMethods(['create'])->disableOriginalConstructor()->getMock();
        $this->reportEventMock = $this->getMockBuilder('Magento\Reports\Model\Event')
            ->disableOriginalConstructor()->getMock();

        $reportEventFactory->expects($this->any())
            ->method('create')
            ->willReturn($this->reportEventMock);

        /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject $storeManager */
        $storeManager = $this->getMock('Magento\Store\Model\StoreManagerInterface');
        $this->storeMock = $this->getMockBuilder('\Magento\Store\Model\Store')
            ->disableOriginalConstructor()->getMock();

        $storeManager->expects($this->any())
            ->method('getStore')
            ->willReturn($this->storeMock);

        $this->productCompModelMock = $this->getMockBuilder('Magento\Reports\Model\Product\Index\Compared')
            ->disableOriginalConstructor()
            ->getMock();

        $this->productCompFactoryMock = $this->getMockBuilder('Magento\Reports\Model\Product\Index\ComparedFactory')
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->productCompFactoryMock->expects($this->any())
            ->method('create')
            ->willReturn($this->productCompModelMock);

        $this->eventSaverMock = $this->getMockBuilder('\Magento\Reports\Observer\EventSaver')
            ->disableOriginalConstructor()
            ->setMethods(['save'])
            ->getMock();

        $this->observer = $objectManager->getObject(
            'Magento\Reports\Observer\CatalogProductCompareAddProductObserver',
            [
                'productCompFactory' => $this->productCompFactoryMock,
                'customerSession' => $this->customerSessionMock,
                'customerVisitor' => $this->customerVisitorMock,
                'eventSaver' => $this->eventSaverMock
            ]
        );
    }

    /**
     * @param bool $isLoggedIn
     * @param string $userKey
     * @param int $userId
     * @dataProvider catalogProductCompareAddProductDataProvider
     * @return void
     */
    public function testCatalogProductCompareAddProduct($isLoggedIn, $userKey, $userId)
    {
        $productId = 111;
        $customerId = 222;
        $visitorId = 333;
        $viewData = [
            'product_id' => $productId,
            $userKey => $userId
        ];
        $observerMock = $this->getObserverMock($productId);

        $this->customerSessionMock->expects($this->any())->method('isLoggedIn')->willReturn($isLoggedIn);
        $this->customerSessionMock->expects($this->any())->method('getCustomerId')->willReturn($customerId);

        $this->customerVisitorMock->expects($this->any())->method('getId')->willReturn($visitorId);

        $this->productCompModelMock->expects($this->any())->method('setData')->with($viewData)->willReturnSelf();
        $this->productCompModelMock->expects($this->any())->method('save')->willReturnSelf();
        $this->productCompModelMock->expects($this->any())->method('calculate')->willReturnSelf();

        $this->eventSaverMock->expects($this->once())->method('save');

        $this->observer->execute($observerMock);
    }

    /**
     * @return array
     */
    public function catalogProductCompareAddProductDataProvider()
    {
        return [
            'logged in' => [
                'isLoggedIn' => true,
                'userKey' => 'customer_id',
                'userId' => 222
            ],
            'not logged in' => [
                'isLoggedIn' => false,
                'userKey' => 'visitor_id',
                'userId' => 333
            ]
        ];
    }

    /**
     * @param int $productId
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getObserverMock($productId)
    {
        $eventObserverMock = $this->getMockBuilder('Magento\Framework\Event\Observer')
            ->disableOriginalConstructor()
            ->getMock();
        $eventMock = $this->getMockBuilder('Magento\Framework\Event')
            ->disableOriginalConstructor()
            ->setMethods(['getProduct'])->getMock();
        $productMock = $this->getMockBuilder('Magento\Catalog\Model\Product')
            ->disableOriginalConstructor()
            ->getMock();

        $productMock->expects($this->any())->method('getId')->willReturn($productId);

        $eventMock->expects($this->any())->method('getProduct')->willReturn($productMock);

        $eventObserverMock->expects($this->any())->method('getEvent')->willReturn($eventMock);

        return $eventObserverMock;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace OO_Sample ;

interface iNormalStaffTask{
    public function generate_task_report();
    public function execute_task($source_task_name);
}

?>


text:
<?php

namespace ArtisanSDK\Server\Timers;

use ArtisanSDK\Server\Commands\GetJob;
use ArtisanSDK\Server\Contracts\ShouldAutoStart;
use ArtisanSDK\Server\Entities\Timer;

class QueueWorker extends Timer implements ShouldAutoStart
{
    /**
     * Setup the timed command.
     */
    public function __construct()
    {
        $this->command(GetJob::class)
            ->interval(100);
    }
}


text:
from __future__ import print_function

import logging
import os
import sys

import astropy.units as u
import click
import numpy as np

import fastimgproto.casa.io as casa_io
import fastimgproto.casa.reduction as casa_reduce
import fastimgproto.imager as imager
from fastimgproto.gridder.conv_funcs import GaussianSinc
from fastimgproto.pipeline.io import save_as_fits

@click.command()
@click.argument('casavis', type=click.Path(exists=True))
@click.argument('outdir', type=click.Path())
def cli(casavis, outdir):
    logging.basicConfig(level=logging.DEBUG)
    """
    Create a dirty image of a CASA measurementset, using CASA & fastimgproto
    """

    image_size = 1024 * u.pixel
    cell_size = 3 * u.arcsecond
    # dirty_fits_path, clean_fits_path = casa_reduce.make_image_map_fits(
    #     casavis, outdir, image_size, cell_size)

    vis = casa_io.get_stokes_i_vis(casavis)
    casa_reduce.make_image_map_fits(casavis, outdir,
                                    image_size, cell_size)

    uvw_lambda = casa_io.get_uvw_in_lambda(casavis)
    kernel_support = 3
    kernel_func = GaussianSinc(trunc=kernel_support)
    image, beam = imager.image_visibilities(vis, uvw_lambda,
                                            uvw_lambda=image_size,
                                            image_size=image_size,
                                            cell_size=cell_size,
                                            kernel_func=kernel_func,
                                            kernel_support=kernel_support,
                                            kernel_oversampling=None)

    fits_path = os.path.join(outdir, 'pyimage.fits')
    save_as_fits(np.real(image), fits_path=fits_path)
    sys.exit(0)

if __name__ == '__main__':
    cli()


text:
<?php namespace Codesleeve\Stapler;

class Config
{
	/**
	 * The name of the attachment.
	 *
	 * @var string
	 */
	public $name;

	/**
	 * An array of attachment configuration options.
	 *
	 * @var array
	 */
	protected $options;

	/**
	 * Constructor method.
	 *
	 * @param string $name
	 * @param array $options
	 */
	function __construct($name, $options)
	{
		$this->name = $name;
		$this->options = $options;
	}

	/**
	 * Handle the dynamic setting of attachment options.
	 *
	 * @param string $name
	 * @param mixed $value
	 */
	public function __set($name, $value)
    {
        $this->options[$name] = $value;
    }

    /**
     * Handle the dynamic retrieval of attachment options.
     * Style options will be converted into a php stcClass.
     *
     * @param  string $optionName
     * @return mixed
     */
    public function __get($optionName)
    {
		if (array_key_exists($optionName, $this->options))
		{
		    if ($optionName == 'styles') {
		    	return $this->convertToObject($this->options[$optionName]);
		    }

		    return $this->options[$optionName];
		}

		return null;
    }

	/**
	 * Utility method for converting an associative array into an array of php stdClass objects.
	 * Both array keys and array values will be conveted to object properties.
	 *
	 * @param  mixed $arrayElements
	 * @return mixed
	 */
	protected function convertToObject($arrayElements)
	{
		$objects = [];

		foreach ($arrayElements as $key => $value) {
			$object = new \stdClass();
			$object->name = $key;
			$object->value = $value;
			$objects[] = $object;
		}

		return $objects;
	}
}


text:
(global as any).pxt = pxt;

import * as nodeutil from './nodeutil';
import * as fs from 'fs';
import * as path from 'path';
import * as child_process from 'child_process';
import * as hid from './hid';

import U = pxt.Util;
import Map = pxt.Map;

// abstract over build engine
export interface BuildEngine {
    updateEngineAsync: () => Promise<void>;
    setPlatformAsync: () => Promise<void>;
    buildAsync: () => Promise<void>;
    patchHexInfo: (extInfo: pxtc.ExtensionInfo) => pxtc.HexInfo;
    prepBuildDirAsync: () => Promise<void>;
    buildPath: string;
    appPath: string;
    moduleConfig: string;
    deployAsync?: (r: pxtc.CompileResult) => Promise<void>;
}

// abstract over C++ runtime target (currently the DAL)
export interface TargetRuntime {
    includePath: string;
}

interface BuildCache {
    sha?: string;
    modSha?: string;
}

function noopAsync() { return Promise.resolve() }

export const buildEngines: Map<BuildEngine> = {
    yotta: {
        updateEngineAsync: () => runYottaAsync(["update"]),
        buildAsync: () => runYottaAsync(["build"]),
        setPlatformAsync: () =>
            runYottaAsync(["target", pxt.appTarget.compileService.yottaTarget]),
        patchHexInfo: patchYottaHexInfo,
        prepBuildDirAsync: noopAsync,
        buildPath: "built/yt",
        moduleConfig: "module.json",
        deployAsync: msdDeployCoreAsync,
        appPath: "source"
    },

    dockeryotta: {
        updateEngineAsync: () => runDockerAsync(["yotta", "update"]),
        buildAsync: () => runDockerAsync(["yotta", "build"]),
        setPlatformAsync: () =>
            runDockerAsync(["yotta", "target", pxt.appTarget.compileService.yottaTarget]),
        patchHexInfo: patchYottaHexInfo,
        prepBuildDirAsync: noopAsync,
        buildPath: "built/dockeryt",
        moduleConfig: "module.json",
        deployAsync: msdDeployCoreAsync,
        appPath: "source"
    },

    platformio: {
        updateEngineAsync: noopAsync,
        buildAsync: () => runPlatformioAsync(["run"]),
        setPlatformAsync: noopAsync,
        patchHexInfo: patchPioHexInfo,
        prepBuildDirAsync: noopAsync,
        buildPath: "built/pio",
        moduleConfig: "platformio.ini",
        deployAsync: platformioDeployAsync,
        appPath: "src"
    },

    codal: {
        updateEngineAsync: updateCodalBuildAsync,
        buildAsync: () => runBuildCmdAsync("python", "build.py"),
        setPlatformAsync: noopAsync,
        patchHexInfo: patchCodalHexInfo,
        prepBuildDirAsync: prepCodalBuildDirAsync,
        buildPath: "built/codal",
        moduleConfig: "codal.json",
        deployAsync: msdDeployCoreAsync,
        appPath: "pxtapp"
    },

    dockercodal: {
        updateEngineAsync: updateCodalBuildAsync,
        buildAsync: () => runDockerAsync(["python", "build.py"]),
        setPlatformAsync: noopAsync,
        patchHexInfo: patchCodalHexInfo,
        prepBuildDirAsync: prepCodalBuildDirAsync,
        buildPath: "built/dockercodal",
        moduleConfig: "codal.json",
        deployAsync: msdDeployCoreAsync,
        appPath: "pxtapp"
    },

    dockermake: {
        updateEngineAsync: () => runBuildCmdAsync(nodeutil.addCmd("npm"), "install"),
        buildAsync: () => runDockerAsync(["make"]),
        setPlatformAsync: noopAsync,
        patchHexInfo: patchDockermakeHexInfo,
        prepBuildDirAsync: noopAsync,
        buildPath: "built/dockermake",
        moduleConfig: "package.json",
        deployAsync: msdDeployCoreAsync,
        appPath: "pxtapp"
    },

    cs: {
        updateEngineAsync: noopAsync,
        buildAsync: () => runBuildCmdAsync(getCSharpCommand(), "-t:library", "-out:pxtapp.dll", "lib.cs"),
        setPlatformAsync: noopAsync,
        patchHexInfo: patchCSharpDll,
        prepBuildDirAsync: noopAsync,
        buildPath: "built/cs",
        moduleConfig: "module.json",
        deployAsync: buildFinalCsAsync,
        appPath: "pxtapp"
    },
}

// once we have a different build engine, set this appropriately
export let thisBuild = buildEngines['yotta']

export function setThisBuild(b: BuildEngine) {
    if (pxt.appTarget.compileService.dockerImage && !process.env["PXT_NODOCKER"]) {
        if (b === buildEngines["codal"])
            b = buildEngines["dockercodal"];
        if (b === buildEngines["yotta"])
            b = buildEngines["dockeryotta"];
    }
    thisBuild = b;
}

function patchYottaHexInfo(extInfo: pxtc.ExtensionInfo) {
    let buildEngine = thisBuild
    let hexPath = buildEngine.buildPath + "/build/" + pxt.appTarget.compileService.yottaTarget
        + "/source/" + pxt.appTarget.compileService.yottaBinary;

    return {
        hex: fs.readFileSync(hexPath, "utf8").split(/\r?\n/)
    }
}

function patchCodalHexInfo(extInfo: pxtc.ExtensionInfo) {
    let bin = pxt.appTarget.compileService.codalBinary
    let hexPath = thisBuild.buildPath + "/build/" + bin + ".hex"
    return {
        hex: fs.readFileSync(hexPath, "utf8").split(/\r?\n/)
    }
}

function patchDockermakeHexInfo(extInfo: pxtc.ExtensionInfo) {
    let hexPath = thisBuild.buildPath + "/bld/pxt-app.hex"
    return {
        hex: fs.readFileSync(hexPath, "utf8").split(/\r?\n/)
    }
}

function patchCSharpDll(extInfo: pxtc.ExtensionInfo) {
    let hexPath = thisBuild.buildPath + "/lib.cs"
    return {
        hex: [fs.readFileSync(hexPath, "utf8")]
    }
}

function pioFirmwareHex() {
    let buildEngine = buildEngines['platformio']
    return buildEngine.buildPath + "/.pioenvs/myenv/firmware.hex"
}

function patchPioHexInfo(extInfo: pxtc.ExtensionInfo) {
    return {
        hex: fs.readFileSync(pioFirmwareHex(), "utf8").split(/\r?\n/)
    }
}

function platformioDeployAsync(r: pxtc.CompileResult) {
    if (pxt.appTarget.compile.useUF2) return msdDeployCoreAsync(r);
    else return platformioUploadAsync(r);
}

function platformioUploadAsync(r: pxtc.CompileResult) {
    // TODO maybe platformio has some option to do this?
    let buildEngine = buildEngines['platformio']
    let prevHex = fs.readFileSync(pioFirmwareHex())
    fs.writeFileSync(pioFirmwareHex(), r.outfiles[pxtc.BINARY_HEX])
    return runPlatformioAsync(["run", "--target", "upload", "--target", "nobuild", "-v"])
        .finally(() => {
            pxt.log('Restoring ' + pioFirmwareHex())
            fs.writeFileSync(pioFirmwareHex(), prevHex)
        })
}

export function buildHexAsync(buildEngine: BuildEngine, mainPkg: pxt.MainPackage, extInfo: pxtc.ExtensionInfo) {
    let tasks = Promise.resolve()
    let buildCachePath = buildEngine.buildPath + "/buildcache.json"
    let buildCache: BuildCache = {}
    if (fs.existsSync(buildCachePath)) {
        buildCache = nodeutil.readJson(buildCachePath)
    }

    if (buildCache.sha == extInfo.sha) {
        pxt.debug("Skipping C++ build.")
        return tasks
    }

    pxt.debug("writing build files to " + buildEngine.buildPath)

    let allFiles = U.clone(extInfo.generatedFiles)
    U.jsonCopyFrom(allFiles, extInfo.extensionFiles)

    let writeFiles = () => {
        for (let f of nodeutil.allFiles(buildEngine.buildPath + "/" + buildEngine.appPath, 8, true)) {
            let bn = f.slice(buildEngine.buildPath.length)
            bn = bn.replace(/\\/g, "/").replace(/^\//, "/")
            if (U.startsWith(bn, "/" + buildEngine.appPath + "/") && !allFiles[bn]) {
                pxt.log("removing stale " + bn)
                fs.unlinkSync(f)
            }
        }

        U.iterMap(allFiles, (fn, v) => {
            fn = buildEngine.buildPath + fn
            nodeutil.mkdirP(path.dirname(fn))
            let existing: string = null
            if (fs.existsSync(fn))
                existing = fs.readFileSync(fn, "utf8")
            if (existing !== v)
                nodeutil.writeFileSync(fn, v)
        })
    }

    tasks = tasks
        .then(buildEngine.prepBuildDirAsync)
        .then(writeFiles)

    let saveCache = () => fs.writeFileSync(buildCachePath, JSON.stringify(buildCache, null, 4) + "\n")

    let modSha = U.sha256(extInfo.generatedFiles["/" + buildEngine.moduleConfig])
    let needDal = false
    if (buildCache.modSha !== modSha) {
        tasks = tasks
            .then(buildEngine.setPlatformAsync)
            .then(buildEngine.updateEngineAsync)
            .then(() => {
                buildCache.sha = ""
                buildCache.modSha = modSha
                saveCache();
                needDal = true
            })
    } else {
        pxt.debug("Skipping C++ build update.")
    }

    tasks = tasks
        .then(buildEngine.buildAsync)
        .then(() => {
            buildCache.sha = extInfo.sha
            saveCache()
            if (needDal)
                buildDalConst(buildEngine, mainPkg, true);
        })

    return tasks
}

function runYottaAsync(args: string[]) {
    let ypath: string = process.env["YOTTA_PATH"]
    let ytCommand = "yotta"
    let env = U.clone(process.env)
    if (/;[A-Z]:\\/.test(ypath)) {
        for (let pp of ypath.split(";")) {
            let q = path.join(pp, "yotta.exe")
            if (fs.existsSync(q)) {
                ytCommand = q
                env["PATH"] = env["PATH"] + ";" + ypath
                break
            }
        }
    }

    pxt.log("*** " + ytCommand + " " + args.join(" "))
    let child = child_process.spawn("yotta", args, {
        cwd: thisBuild.buildPath,
        stdio: "inherit",
        env: env
    })
    return new Promise<void>((resolve, reject) => {
        child.on("close", (code: number) => {
            if (code === 0) resolve()
            else reject(new Error("yotta " + args.join(" ") + ": exit code " + code))
        })
    })
}

function runPlatformioAsync(args: string[]) {
    pxt.log("*** platformio " + args.join(" "))
    let child = child_process.spawn("platformio", args, {
        cwd: thisBuild.buildPath,
        stdio: "inherit",
        env: process.env
    })
    return new Promise<void>((resolve, reject) => {
        child.on("close", (code: number) => {
            if (code === 0) resolve()
            else reject(new Error("platformio " + args.join(" ") + ": exit code " + code))
        })
    })
}

function runDockerAsync(args: string[]) {
    let fullpath = process.cwd() + "/" + thisBuild.buildPath + "/"
    let cs = pxt.appTarget.compileService
    return nodeutil.spawnAsync({
        cmd: "docker",
        args: ["run", "--rm", "-v", fullpath + ":/src", "-w", "/src", "-u", "build",
            cs.dockerImage].concat(args),
        cwd: thisBuild.buildPath
    })
}

let parseCppInt = pxt.cpp.parseCppInt;

export function codalGitAsync(...args: string[]) {
    return nodeutil.spawnAsync({
        cmd: "git",
        args: args,
        cwd: thisBuild.buildPath
    })
}

function prepCodalBuildDirAsync() {
    if (fs.existsSync(thisBuild.buildPath + "/.git/config"))
        return Promise.resolve()
    let cs = pxt.appTarget.compileService
    let pkg = "https://github.com/" + cs.githubCorePackage
    nodeutil.mkdirP("built")
    return nodeutil.runGitAsync("clone", pkg, thisBuild.buildPath)
        .then(() => codalGitAsync("checkout", cs.gittag))
}

function runBuildCmdAsync(cmd: string, ...args: string[]) {
    return nodeutil.spawnAsync({
        cmd,
        args,
        cwd: thisBuild.buildPath,
    })
}

function updateCodalBuildAsync() {
    let cs = pxt.appTarget.compileService
    return codalGitAsync("checkout", cs.gittag)
        .then(
            () => /^v\d+/.test(cs.gittag) ? Promise.resolve() : codalGitAsync("pull"),
            e =>
                codalGitAsync("checkout", "master")
                    .then(() => codalGitAsync("pull")))
        .then(() => codalGitAsync("checkout", cs.gittag))
}

// TODO: DAL specific code should be lifted out
export function buildDalConst(buildEngine: BuildEngine, mainPkg: pxt.MainPackage, rebuild = false,
    create = false) {
    let constName = "dal.d.ts"
    let vals: Map<string> = {}
    let done: Map<string> = {}
    let excludeSyms: string[] = []

    function expandInt(s: string): number {
        s = s.trim()
        let existing = U.lookup(vals, s)
        if (existing != null && existing != "?")
            s = existing

        let mm = /^\((.*)\)/.exec(s)
        if (mm) s = mm[1]

        let m = /^(\w+)\s*([\+\|])\s*(.*)$/.exec(s)
        if (m) {
            let k = expandInt(m[1])
            if (k != null)
                return m[2] == "+" ? k + expandInt(m[3]) : k | expandInt(m[3])
        }
        let pp = parseCppInt(s)
        if (pp != null) return pp
        return null
    }

    function isValidInt(v: string) {
        return /^-?(\d+|0[xX][0-9a-fA-F]+)$/.test(v)
    }

    function extractConstants(fileName: string, src: string, dogenerate = false): string {
        let lineNo = 0
        // let err = (s: string) => U.userError(`${fileName}(${lineNo}): ${s}\n`)
        let outp = ""
        let inEnum = false
        let enumVal = 0
        let defineVal = (n: string, v: string) => {
            if (excludeSyms.some(s => U.startsWith(n, s)))
                return
            let parsed = expandInt(v)
            if (parsed != null) {
                v = parsed.toString()
                let curr = U.lookup(vals, n)
                if (curr == null || curr == v) {
                    vals[n] = v
                    if (dogenerate && !done[n]) {
                        outp += `    ${n} = ${v},\n`
                        done[n] = v
                    }
                } else {
                    vals[n] = "?"
                    // TODO: DAL-specific code
                    if (dogenerate && !/^MICROBIT_DISPLAY_(ROW|COLUMN)_COUNT$/.test(n))
                        pxt.log(`${fileName}(${lineNo}): #define conflict, ${n}`)
                }
            }
        }
        src.split(/\r?\n/).forEach(ln => {
            ++lineNo
            ln = ln.replace(/\/\/.*/, "").replace(/\/\*.*/g, "")
            let m = /^\s*#define\s+(\w+)\s+(.*)$/.exec(ln)
            if (m) {
                defineVal(m[1], m[2])
            }

            if (inEnum && /}/.test(ln))
                inEnum = false

            if (/^\s*enum\s+(\w+)/.test(ln)) {
                inEnum = true;
                enumVal = -1;
            }

            const shouldExpand = inEnum && (m = /^\s*(\w+)\s*(=\s*(.*?))?,?\s*$/.exec(ln));
            if (shouldExpand) {
                let v = m[3]
                if (v) {
                    enumVal = expandInt(v)
                    if (enumVal == null) {
                        pxt.log(`${fileName}(${lineNo}): invalid enum initializer, ${ln}`)
                        inEnum = false
                        return
                    }
                } else {
                    enumVal++
                    v = enumVal + ""
                }
                defineVal(m[1], v)
            }
        })
        return outp
    }

    if (mainPkg && (create ||
        (mainPkg.getFiles().indexOf(constName) >= 0 && (rebuild || !fs.existsSync(constName))))) {
        pxt.log(`rebuilding ${constName}...`)
        let files: string[] = []
        let foundConfig = false

        for (let d of mainPkg.sortedDeps()) {
            if (d.config.dalDTS) {
                for (let dn of d.config.dalDTS.includeDirs) {
                    dn = buildEngine.buildPath + "/" + dn
                    if (U.endsWith(dn, ".h")) files.push(dn)
                    else {
                        let here = nodeutil.allFiles(dn, 20).filter(fn => U.endsWith(fn, ".h"))
                        U.pushRange(files, here)
                    }
                }
                excludeSyms = d.config.dalDTS.excludePrefix || excludeSyms
                foundConfig = true
            }
        }

        if (!foundConfig) {
            let incPath = buildEngine.buildPath + "/yotta_modules/microbit-dal/inc/"
            if (!fs.existsSync(incPath))
                incPath = buildEngine.buildPath + "/yotta_modules/codal/inc/";
            if (!fs.existsSync(incPath))
                incPath = buildEngine.buildPath
            if (!fs.existsSync(incPath))
                U.userError("cannot find " + incPath);
            files = nodeutil.allFiles(incPath, 20)
                .filter(fn => U.endsWith(fn, ".h"))
                .filter(fn => fn.indexOf("/mbed-classic/") < 0)
                .filter(fn => fn.indexOf("/mbed-os/") < 0)
        }

        files.sort(U.strcmp)
        let fc: Map<string> = {}
        for (let fn of files) {
            if (U.endsWith(fn, "Config.h")) continue
            fc[fn] = fs.readFileSync(fn, "utf8")
        }
        files = Object.keys(fc)

        // pre-pass - detect conflicts
        for (let fn of files) {
            extractConstants(fn, fc[fn])
        }
        // stabilize
        for (let fn of files) {
            extractConstants(fn, fc[fn])
        }

        let consts = "// Auto-generated. Do not edit.\ndeclare const enum DAL {\n"
        for (let fn of files) {
            let v = extractConstants(fn, fc[fn], true)
            if (v) {
                consts += "    // " + fn.replace(/\\/g, "/") + "\n"
                consts += v
            }
        }
        consts += "}\n"
        fs.writeFileSync(constName, consts)
    }
}

const writeFileAsync: any = Promise.promisify(fs.writeFile)
const execAsync: (cmd: string, options?: { cwd?: string }) => Promise<Buffer | string> = Promise.promisify(child_process.exec)
const readDirAsync = Promise.promisify(fs.readdir)

function buildFinalCsAsync(res: ts.pxtc.CompileResult) {
    return nodeutil.spawnAsync({
        cmd: getCSharpCommand(),
        args: ["-out:pxtapp.exe", "binary.cs"],
        cwd: "built",
    })
}

function getCSharpCommand() {
    return process.platform == "win32" ? "mcs.bat" : "mcs";
}

function msdDeployCoreAsync(res: ts.pxtc.CompileResult) {
    const firmware = pxt.outputName()
    const encoding = pxt.isOutputText() ? "utf8" : "base64";

    if (pxt.appTarget.serial && pxt.appTarget.serial.useHF2 && !pxt.appTarget.serial.noDeploy
        && hid.isInstalled(true)) {
        let f = res.outfiles[pxtc.BINARY_UF2]
        let blocks = pxtc.UF2.parseFile(U.stringToUint8Array(atob(f)))
        return hid.initAsync()
            .then(dev => dev.flashAsync(blocks))
    }

    return getBoardDrivesAsync()
        .then(drives => filterDrives(drives))
        .then(drives => {
            if (drives.length == 0) {
                pxt.log("cannot find any drives to deploy to");
                return Promise.resolve(0);
            }
            pxt.log(`copying ${firmware} to ` + drives.join(", "));
            const writeHexFile = (filename: string) => {
                return writeFileAsync(path.join(filename, firmware), res.outfiles[firmware], encoding)
                    .then(() => pxt.log("   wrote hex file to " + filename));
            };
            return Promise.map(drives, d => writeHexFile(d))
                .then(() => drives.length);
        }).then(() => { });
}

function getBoardDrivesAsync(): Promise<string[]> {
    if (process.platform == "win32") {
        const rx = new RegExp("^([A-Z]:)\\s+(\\d+).* " + pxt.appTarget.compile.deployDrives)
        return execAsync("wmic PATH Win32_LogicalDisk get DeviceID, VolumeName, FileSystem, DriveType")
            .then((buf: Buffer) => {
                let res: string[] = []
                buf.toString("utf8").split(/\n/).forEach(ln => {
                    let m = rx.exec(ln)
                    if (m && m[2] == "2") {
                        res.push(m[1] + "/")
                    }
                })
                return res
            })
    }
    else if (process.platform == "darwin") {
        const rx = new RegExp(pxt.appTarget.compile.deployDrives)
        return readDirAsync("/Volumes")
            .then(lst => lst.filter(s => rx.test(s)).map(s => "/Volumes/" + s + "/"))
    } else if (process.platform == "linux") {
        const rx = new RegExp(pxt.appTarget.compile.deployDrives)
        const user = process.env["USER"]
        return readDirAsync(`/media/${user}`)
            .then(lst => lst.filter(s => rx.test(s)).map(s => `/media/${user}/${s}/`))
    } else {
        return Promise.resolve([])
    }
}

function filterDrives(drives: string[]): string[] {
    const marker = pxt.appTarget.compile.deployFileMarker;
    if (!marker) return drives;
    return drives.filter(d => {
        try {
            return fs.existsSync(path.join(d, marker));
        } catch (e) {
            return false;
        }
    });
}


text:
"""
    using to send systemg notification
"""

import smtplib
from email.mime.text import MIMEText
from logger import log
import config

def send_mail(mailto_list, message):
    if config.mail_open == "True":
        mail_host = config.mail_host
        mail_user = config.mail_user
        mail_pass = config.mail_pass
        mail_postfix = config.mail_postfix

        msg = MIMEText(message, 'plain')
        msg['From'] = mail_user + '@' + mail_postfix
        msg['Subject'] = 'XXX OMS Notification'
        msg['To'] = ",".join(mailto_list)

        try:
            server = smtplib.SMTP()
            server.connect(mail_host)
            server.login(mail_user, mail_pass)
            server.sendmail(msg['From'], mailto_list, msg.as_string())
            server.close()
        except Exception:
            log.exception('exception')
        else:
            log.info("sending mail successful.")
    else:
        pass


text:
print "Enter a temperature (e.g., 32F, 100C):\n";
$input = <STDIN>; # This reads one line from the user.
chomp($input);    # This removes the ending newline from $input.

if ($input =~ m/^([-+]?[0-9]+(?:\.[0-9]*)?)\s*([CF])$/i)
{
    # If we get in here, we had a match. $1 is the number, $2 is "C" or "F".
    $InputNum = $1;  # Save to named variables to make the ...
    $type     = $2;  # ... rest of the program easier to read.

    if ($type =~ m/c/i) { # 'eq' tests if two strings are equal
        # The input was Celsius, so calculate Fahrenheit
        $celsius = $InputNum;
        $fahrenheit = ($celsius * 9 / 5) + 32;
    } else {
        # If not "C", it must be an "F", so calculate Celsius
        $fahrenheit = $InputNum;
        $celsius = ($fahrenheit - 32) * 5 / 9;
    }
    # At this point we have both temperatures, so display the results:
    printf "%.2f C is %.2f F\n", $celsius, $fahrenheit;
} else {
    # The initial regex did not match, so issue a warning.
    print "Expecting a number followed by \"C\" or \"F\",\n";
    print "so I don't understand \"$input\".\n";
}


text:
<?php namespace ItLogic\HashInt\Facades;

use Illuminate\Support\Facades\Facade;

class HashInt extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'hashint'; }

}


text:
package com.webcohesion.enunciate.examples.jaxrsjackson.genealogy.data;

import lombok.Data;

/**
 * A gender assertion.
 *
 * @author Ryan Heaton
 */
@Data
public class Gender extends Assertion {

  private GenderType type;

  /**
   * The type of gender.
   *
   * @return The type of gender.
   */
  public GenderType getType() {
    return type;
  }

  /**
   * The type of gender.
   *
   * @param type The type of gender.
   */
  public void setType(GenderType type) {
    this.type = type;
  }
}


text:
<!DOCTYPE html>

<html>

	<head>
		<title> MODULE CHAT -  STAGE Unit Tests</title>
		<link rel="stylesheet" type="text/css" href="/src/library/console/themes/basic/css/console.css" />

		<script src="/test/unit.js"></script>
		<script src="/src/library/stage/stage.js"></script>
		<script src="/src/library/selectors/sizzle/sizzle.js"></script>
		<script src="/src/library/structs/structs.js"></script>
		<script src="/src/library/structs/hash/hash.js"></script>
		<script src="/src/library/function/function.js"></script>
		<script src="/src/library/events/events.js"></script>
		<script src="/src/library/string/string.js"></script>
		<script src="/src/library/json/json.js"></script>
		<script src="/src/library/array/array.js"></script>
		<script src="/src/library/dom/dom.js"></script>
		<script src="/src/library/storage/storage.js"></script>
		<script src="/src/library/css/css.js"></script>
		<script src="/src/library/position/position.js"></script>
		<script src="/src/library/structs/structs.js"></script>
		<script src="/src/library/structs/hash/hash.js"></script>
		<script src="/src/library/structs/queue/queue.js"></script>
		<script src="/src/library/xml/xml.js"></script>
		<script src="/src/library/io/ioManager.js"></script>
		<script src="/src/library/io/transport/outSocket/ajax/ajax.js"></script>
		<script src="/src/library/io/transport/outSocket/iframe/iframe.js"></script>
		<script src="/src/library/io/transport/outSocket/script/script.js"></script>
		<script src="/src/library/io/transport/outSocket/jsonp/jsonp.js"></script>
		<script src="/src/library/io/transport/inSocket/streaming/streaming.js"></script>
		<script src="/src/library/io/transport/inSocket/poll/poll.js"></script>
		<script src="/src/library/io/transport/inSocket/longPoll/longPoll.js"></script>
		<script src="/src/library/io/transport/transport.js"></script>
		<script src="/src/library/io/transport/ioSocket/socket/socket.js"></script>
		<script src="/src/library/io/transport/ioSocket/webSocket/webSocket.js"></script>

		<script src="/src/library/io/protocols/protocol.js"></script>
		<script src="/src/library/io/protocols/BOSH/BOSH.js"></script>
		<script src="/src/library/io/protocols/XMPP/XMPP.js"></script>

		<script src="/src/library/io/mechanisms/digestMD5/digestMD5.js"></script>
		<script src="/src/library/io/authentication/sasl/sasl.js"></script>

		<script src="/src/library/dom/dom.js"></script>
		<script src="/src/library/css/css.js"></script>
		<script src="/src/library/xml/xml.js"></script>
		<script src="/src/library/xslt/xslt.js"></script>

		<script src="/src/library/console/console.js"></script>
		<script src="/src/library/console/consoles/protocols/protocolsConsole.js"></script>
		<script src="/src/library/console/consoles/protocols/monitors/XMPPMonitor.js"></script>
		<script src="/src/library/console/consoles/protocols/monitors/BOSHMonitor.js"></script>

		<script src="/src/library/crypto/crypto.js"></script>
		<script src="/src/library/crypto/md5/md5.js"></script>
		<script src="/src/library/crypto/base64/base64.js"></script>

		<!-- STAGE-UI -->
		<script src="/src/stage-ui/stage-ui.js"></script>
		<script src="/src/stage-ui/i18n/i18n.js"></script>
		<script src="/src/stage-ui/date/date.js"></script>
		<script src="/src/stage-ui/color/color.js"></script>
		<!-- STAGE-MVC -->
		<script src="/src/stage-ui/data/data.js"></script>
		<script src="/src/stage-ui/data/model.js"></script>

		<script src="/src/stage-ui/effect/sampler.js"></script>
		<script src="/src/stage-ui/effect/effect.js"></script>
		<script src="/src/stage-ui/effect/transitions/transitions.js"></script>
		<script src="/src/stage-ui/effect/transitions/penner.js"></script>
		<script src="/src/stage-ui/effect/transitions/bezier.js"></script>
		<script src="/src/stage-ui/effect/effects/css.js"></script>
		<script src="/src/stage-ui/gestures/gestural.js"></script>
		<script src="/src/stage-ui/dragdrop/dragdrop.js"></script>
		<script src="/src/stage-ui/resize/resize.js"></script>

		<script src="/src/stage-ui/container/coreContainer.js"></script>
		<script src="/src/stage-ui/plugins/container/container.js"></script>
		<script src="/src/stage-ui/layout/coreLayout.js"></script>
		<script src="/src/stage-ui/layout/layouts/accordion/accordion.js"></script>
		<script src="/src/stage-ui/plugins/container/viewport.js"></script>
		<script src="/src/stage-ui/plugins/panel/panel.js"></script>
		<script src="/src/stage-ui/plugins/window/window.js"></script>

		<link rel="stylesheet" type="text/css" href="/src/stage-ui/themes/stage.ui.all.css" />
		<style type="text/css">
			body {
				font-family: Arial, Helvetica, Verdana, sans-serif;
    			font-size: 10px;
			}
		</style>

		<!-- STAGE-MODULE -->
		<script src="/src/stage-modules/stage-module.js"></script>
		<script src="/src/stage-modules/chat/src/chat.js"></script>
		<link rel="stylesheet" type="text/css" href="/src/stage-modules/chat/themes/default/chat.css" />

</head>

<body>
	<div id="chat"> </div>

	<script>

		var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
		asyncTestCase.stepTimeout = 30 * 1000;

		var testCallback = function(){

			var NSTestCallback = {
				state:{response:[],i:null},
				roster:{response:[],i:null},
				IM:		{response:[],i:null},
				presenceChanged: {response:[],i:null},
				subscribeState:	{response:[],i:null},
				error:	{response:[],error:null,i:null}
			};
			NSTestCallback.i = 0;

			NSTestCallback.protocolSettings = {

				/*
				onIM:function(response){

					var d = new Date();
					var time = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

					NSTestCallback.IM.response.push(response);
					NSTestCallback.IM.i = NSTestCallback.i++;

					//console.log(time+"# "+response.from+":  "+response.message);

					var message = [{
						tagName : "div",
						position : "bottom",
						attributes:{
							inner: time+"# "+response.from+":  "+response.message
						}
					}];
					$$stage("#contentChat").build(message);
				},

				onPresenceChanged:function(jid, presence, showStatus, status){

					NSTestCallback.presenceChanged.response.push({jid:jid, presence:presence, showStatus:showStatus, status:status });
					NSTestCallback.presenceChanged.i = NSTestCallback.i++;

					console.log("Presence received from " + jid +
						 ". Presence => "+presence+
						 ". Show => "+showStatus+
						 ". Status => "+status);
				},

				onRoster: function(roster){

					console.log("Roster received : ");
					console.log(roster);

					NSTestCallback.roster.response.push(roster);
					NSTestCallback.roster.i = NSTestCallback.i++;
				},

				onSubscribeState : function(jid, subscribeState){

					NSTestCallback.subscribeState.response.push( {jid:jid, subscribeState:subscribeState} );
					NSTestCallback.subscribeState.i = NSTestCallback.i++;

					switch(subscribeState){
						case "subscribed" :
							console.log("Confirmation de subscription de "+ jid);
						break;
						case "subscribe" :
							console.log("Demande de subscription de " + jid);
						break;
						case "unsubscribe" :
							console.log("Demande de non subscription de " + jid);
						break;
						case "unsubscribed" :
							console.log("Confirmation de non subscription de " + jid);
						break;

						default:
					}
				},

				onError:function(protocol, error){

					console.error(error.toString());
					stage.console.error(error);

					NSTestCallback.error.response.push(protocol);
					NSTestCallback.error.error = error;
					NSTestCallback.error.i = NSTestCallback.i++;
				}
				*/
			};

			return NSTestCallback;

		};

		/*
		function testWindow(){

			$$stage("#chat").window( {
				width:200,
				height:200,
				container:document.body,
				resizable:true,
				draggable:true
			});
		}
		*/

		/*function test_01_protocol_connect(){

			var NSTestCallback = new testCallback();
			var protocolSettings = NSTestCallback.protocolSettings;

			//

			protocolSettings.urlServer = "http://stage-box.fr";
			protocolSettings.urnServer = "http-bind";
			protocolSettings.portServer = "5280";

			protocolSettings.domain = 'stage-box.fr';
			protocolSettings.userName = "test";
			protocolSettings.pwd = "design";

			protocolSettings.proxyUrl = "/src/library/io/protocols/XMPP/test/curlProxy3.php";

			chatte = new stage.modules.chat.chat(document.body, "XMPP", "chatStage", protocolSettings);

			asyncTestCase.waitForAsync();
			setTimeout(function(){

				chatte.models[0].xmpp.setPresence("online");

			},5000);

		};*/

		function testChat(){

			chat  = stage.loadModule("chat", document.body, {
				protocol:{
					urlServer : "http://stage-box.fr",
					urnServer : "http-bind",
					portServer : "5280",
					domain : 'stage-box.fr',
					userName : "rrd",
					pwd : "design",
					proxyUrl : "/src/library/io/protocols/XMPP/test/curlProxy3.php"
				},
				display:{
					//position:"center"
				}
			});
			//console.log(chat);

			setTimeout(function(){
				chat.xmpp.setPresence("online","sboob")
			},15000);

			setTimeout(function(){
				//chat.xmpp.stop();
			},120000);

		}

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


text:
package com.googlecode.dex2jar.ir.ts.an;

import com.googlecode.dex2jar.ir.IrMethod;
import com.googlecode.dex2jar.ir.expr.Local;
import com.googlecode.dex2jar.ir.expr.Value;
import com.googlecode.dex2jar.ir.stmt.Stmt;
import com.googlecode.dex2jar.ir.ts.UniqueQueue;

import java.util.*;

public class SimpleLiveAnalyze extends BaseAnalyze<SimpleLiveValue> {
    protected Set<SimpleLiveValue> markUsed() {
        Set<SimpleLiveValue> used = new HashSet<SimpleLiveValue>(aValues.size() / 2);
        Queue<SimpleLiveValue> q = new UniqueQueue<>();
        for (SimpleLiveValue sv : aValues) {
            if (sv.used) {
                q.add(sv);
                while (!q.isEmpty()) {
                    SimpleLiveValue v = q.poll();
                    if (v.used) {
                        if (used.contains(v)) {
                            continue;
                        }
                        used.add(v);
                        {
                            SimpleLiveValue p = v.parent;
                            if (p != null) {
                                if (!p.used) {
                                    p.used = true;
                                    q.add(p);
                                }
                            }
                        }
                        if (v.otherParents != null) {
                            for (SimpleLiveValue p : v.otherParents) {
                                if (!p.used) {
                                    p.used = true;
                                    q.add(p);
                                }
                            }
                            v.otherParents = null;
                        }
                    }
                }
            }
        }

        return used;
    }

    @Override
    protected void analyzeValue() {
        markUsed();
    }

    public int getLocalSize() {
        return localSize;
    }

    public SimpleLiveAnalyze(IrMethod method, boolean reindexLocal) {
        super(method, reindexLocal);
    }

    @Override
    protected SimpleLiveValue onAssignLocal(Local local, Value value) {
        SimpleLiveValue v = super.onAssignLocal(local, value);
        v.used = true;
        return v;
    }

    @Override
    protected void onUseLocal(SimpleLiveValue aValue, Local local) {
        aValue.used = true;
        super.onUseLocal(aValue, local);
    }

    @Override
    public SimpleLiveValue[] merge(SimpleLiveValue[] srcFrame, SimpleLiveValue[] distFrame, Stmt src, Stmt dist) {
        if (distFrame == null) {
            distFrame = new SimpleLiveValue[this.localSize];
            for (int i = 0; i < srcFrame.length; i++) {
                SimpleLiveValue sV = srcFrame[i];
                if (sV != null) {
                    SimpleLiveValue dV = new SimpleLiveValue();
                    aValues.add(dV);
                    dV.parent = sV;
                    distFrame[i] = dV;
                }
            }
        } else {
            for (int i = 0; i < srcFrame.length; i++) {
                SimpleLiveValue sV = srcFrame[i];
                SimpleLiveValue dV = distFrame[i];
                if (sV != null && dV != null) {
                    List<SimpleLiveValue> ps = dV.otherParents;
                    if (ps == null) {
                        dV.otherParents = ps = new ArrayList<>(3);
                    }
                    ps.add(sV);
                }
            }
        }
        return distFrame;
    }

    @Override
    protected SimpleLiveValue[] newFrame(int size) {
        return new SimpleLiveValue[size];
    }

    @Override
    protected SimpleLiveValue newValue() {
        return new SimpleLiveValue();
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Application\Tests;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;

final class PromotionTest extends ApiTestCase
{
    use SetUpTestsTrait;

    public function setUp(): void
    {
        $this->setFixturesFiles(['test/config/fixtures/promotions.yaml']);
        $this->setUpTest();
    }

    /**
     * @test
     */
    public function it_gets_resource_collection_as_a_guest_by_custom_path(): void
    {
        static::createClient()->request('GET', '/api/v2/custom/promotions');

        $this->assertResponseIsSuccessful();
        $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');

        $this->assertJsonContains([
            '@context' => '/api/v2/contexts/Promotion',
            '@id' => '/api/v2/custom/promotions',
            '@type' => 'hydra:Collection',
            'hydra:member' => [
                [
                  '@type' => 'Promotion',
                  'name' => 'Sunday promotion',
                ],
            ],
            'hydra:totalItems' => 1,
        ]);
    }

    /**
     * @test
     */
    public function it_gets_resource_collection_as_a_admin_by_custom_path(): void
    {
        static::createClient()->request(
            'GET',
            '/api/v2/custom/promotions',
            ['auth_bearer' => $this->JWTAdminUserToken],
        );

        $this->assertResponseIsSuccessful();
        $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');

        $this->assertJsonContains([
            '@context' => '/api/v2/contexts/Promotion',
            '@id' => '/api/v2/custom/promotions',
            '@type' => 'hydra:Collection',
            'hydra:member' => [
                [
                    '@type' => 'Promotion',
                    'name' => 'Sunday promotion',
                ],
            ],
            'hydra:totalItems' => 1,
        ]);
    }
}


text:
---
layout: post
title: Unique Characters
date: 2015-10-21 03:35:07.000000000 -04:00
tags:
- Leetcode
categories:
- String
author: Jason
---

Implement an algorithm to determine if a string has all unique characters.

``` java
public class Solution {
    /**
     * @param str: a string
     * @return: a boolean
     */
    public boolean isUnique(String str) {
        // write your code here
        if (str == null || str.length() == 0) return false;
        int[] existed = new int[256];

        for (int i = 0; i < str.length(); i++) {
            if (++existed[str.charAt(i)] > 1) return false;
        }
        return true;
    }
    //no extra space
    public boolean isUnique(String str) {
        // write your code here
        if (str == null || str.length() == 0) return false;

        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j)) {
                    return false;
                }
            }
        }
        return true;
    }
}
```


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

/**
   File Name:          switch-001.js
   Section:
   Description:

   http://scopus.mcom.com/bugsplat/show_bug.cgi?id=315767

   Verify that switches do not use strict equality in
   versions of JavaScript < 1.4.  It's now been decided that
   we won't put in version switches, so all switches will
   be ECMA.

   Author:             christine@netscape.com
   Date:               12 november 1997
*/
var SECTION = "switch-001";
var VERSION = "JS1_3";
var TITLE   = "switch-001";
var BUGNUMBER="315767";

startTest();
writeHeaderToLog( SECTION + " "+ TITLE);

result = "fail:  did not enter switch";

switch (true) {
case 1:
  result = "fail:  version 130 should force strict equality";
  break;
case true:
  result = "pass";
  break;
default:
  result = "fail: evaluated default statement";
}

new TestCase(
  SECTION,
  "switch / case should use strict equality in version of JS < 1.4",
  "pass",
  result );

test();


text:
import { async, ComponentFixture } from '@angular/core/testing';

import { TestUtils } from '../../../test';

import { AboutPage } from './about';
import { SessionLogPage } from './session-log/session-log';

describe('AboutPage', () => {
  let fixture: ComponentFixture<AboutPage>;
  let instance;

  beforeEach(async(() =>
    TestUtils.configurePageTestingModule([AboutPage]).then(testEnv => {
      fixture = testEnv.fixture;
      instance = testEnv.instance;
      fixture.detectChanges();
    })));
  afterEach(() => {
    fixture.destroy();
  });
  describe('Lifecycle Hooks', () => {
    describe('ionViewDidLoad', () => {
      it('should log info', () => {
        spyOn(instance.logger, 'info');
        instance.ionViewDidLoad();
        expect(instance.logger.info).toHaveBeenCalledWith('Loaded: AboutPage');
      });
      it('should set correct commit hash and version', () => {
        instance.appProvider.info.commitHash = 'testHash';
        instance.appProvider.info.version = '21.0.0';
        instance.ionViewDidLoad();
        expect(instance.commitHash).toEqual('testHash');
        expect(instance.version).toEqual('21.0.0');
      });
      it('should set correct title', () => {
        spyOn(instance.replaceParametersProvider, 'replace').and.returnValue(
          'testTitle'
        );
        spyOn(instance.translate, 'instant').and.returnValue('testVal');
        instance.appProvider.info.nameCase = 'testName';
        instance.ionViewDidLoad();

        expect(instance.translate.instant).toHaveBeenCalledWith(
          'About {{appName}}'
        );
        expect(
          instance.replaceParametersProvider.replace
        ).toHaveBeenCalledWith('testVal', { appName: 'testName' });
        expect(instance.title).toEqual('testTitle');
      });
    });
  });
  describe('Methods', () => {
    describe('#openExternalLink', () => {
      it('open github repo with correct params', () => {
        spyOn(instance.externalLinkProvider, 'open');

        instance.appProvider.info.gitHubRepoName = 'testRepo';
        instance.appProvider.info.commitHash = 'testHash';

        const params = {
          'Go Back': 'Go Back',
          'Open GitHub': 'Open GitHub',
          'Open GitHub Project': 'Open GitHub Project',
          'You can see the latest developments and contribute to this open source app by visiting our project on GitHub.':
            'You can see the latest developments and contribute to this open source app by visiting our project on GitHub.'
        };

        spyOn(instance.translate, 'instant').and.callFake(myParam => {
          return params[myParam];
        });

        instance.openExternalLink();

        expect(instance.externalLinkProvider.open).toHaveBeenCalledWith(
          'https://github.com/bitpay/testRepo/tree/testHash',
          true,
          'Open GitHub Project',
          'You can see the latest developments and contribute to this open source app by visiting our project on GitHub.',
          'Open GitHub',
          'Go Back'
        );
      });
    });
    describe('#openSessionLog', () => {
      it('should open session log', () => {
        instance.openSessionLog();
        expect(instance.navCtrl.push).toHaveBeenCalledWith(SessionLogPage);
      });
    });
  });
});


text:
var assert = require('chai').assert,
    sinon = require('sinon'),
    _ = require('lodash'),
    helpers = require('./helpers'),
    Store = require('../src/store'),
    Model = require('../src/model'),
    Collection = require('../src/collection'),
    rawValues = require('../test/mock_values');

describe('Store() constructor', function() {
  helpers.init();
  it('cannot create a store with an invalid definition', function() {
    rawValues.forEach(function(val) {
      if (_.isObject(val)) {
        return;
      }
      assert.throws(function() {
        new Store(val);
      });
    });
  });

  it('can create a store with a valid definition', function() {
    assert.doesNotThrow(function() {
      var app = new Store({
        user: {
          name: Model.Str,
          age: Model.Decimal
        }
      });
    }, 'can create a store');
  });
});

describe('Store() snapshot/commit', function() {
  helpers.init();
  var app, dude;
  beforeEach(function() {
    app = new Store({
      users: {
        name: Model.Str,
        age: Model.Decimal
      }
    });
    dude = {
      name: 'dude',
      age: 21
    };
  });

  it('can add items to the store via commit()', function() {
    var user = app.create('users', dude);
    app.commit(user);
    var snapshot = app.snapshot();
    assert.equal(snapshot.get('users').length(), 1);
    assert.equal(app.get('users').length(), 1);
    assert.equal(snapshot.get('users').first().name.val, 'dude');
    assert.equal(app.get('users').first().name.val, 'dude');
  });

  it('can remove items from the store via commit()', function() {
    var user = app.create('users', dude);
    app.commit(user);

    user = app.snapshot().get('users', user.id); // reload user
    user.destroy();
    app.commit(user);

    var snapshot = app.snapshot();
    assert.equal(snapshot.get('users').length(), 0);
  });

  it('can update existing items in the store via commit()', function() {
    var user = app.create('users', dude);
    app.commit(user);

    var snapshot = app.snapshot();
    user = snapshot.get('users').first();
    user.age.inc();
    app.commit(user);

    snapshot = app.snapshot();
    assert.equal(snapshot.get('users').length(), 1);
    assert.equal(snapshot.get('users').first().name.val, dude.name);
    assert.equal(snapshot.get('users').first().age.val, dude.age + 1);
  });

  it('can find added items', function() {
    var user = app.create('users', dude);
    app.commit(user);

    var users = app.snapshot().get('users');
    assert.equal(users.length(), 1);
    assert.equal(users.first().name.val, dude.name);
    assert.equal(users.first().age.val, dude.age);
  });
});


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends MY_Controller {

	public function __construct(){
        parent::__construct();
        $this->load->model('user_m');
        $this->load->library('pagination');

        // $this->user_m->logged_in() == FALSE || redirect('user/login?login=false','refresh');
    }

	public function index()
	{
		$this->user_m->logged_in() == TRUE || redirect('user/login?login=false','refresh');

		//fetch all users from database
        $config['base_url'] = base_url('user/index/');
        $config['total_rows'] = sizeof($this->user_m->get());
        $config['per_page'] = 10;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        // catch page number
        $pageNumber = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        $this->data['users'] = $this->user_m->pagination($config['per_page'], $pageNumber);
        $this->data['paginationLinks'] = $this->pagination->create_links();

		$this->data['subview'] = 'user/index';
        $this->load->view('_layout',$this->data);

	}

	public function view($id = NULL)
    {

	        if ($id)
	        {
	            $this->data['user']  =   $this->user_m->get($id);
	            count($this->data['user']) || $this->data['error'][] = 'user could not be found';

	        }
	        else
	        {
	            redirect('user/add/');
	        }
	        $this->data['subview'] = 'user/view';
	        $this->load->view('_layout',$this->data);
    }

	public function edit($id = NULL)
    {
        // Fetch a user or set a new one
        if($id)
        {
            $this->data['user'] = $this->user_m->get($id);
            count($this->data['user']) || $this->data['error'][] = 'User could not be found';
        }
        else
        {
            redirect('user/add');
        }

        // Set up the form and rules
        $rules = $this->user_m->rulesUpdate;
        $this->form_validation->set_rules($rules);
        // var_dump($this->input->post());
        // process the form
        if($this->form_validation->run() == TRUE)
        {
            $data = $this->user_m->array_from_post(array('f_name','l_name','username','status'));
            //$data['password'] = $this->user_m->hash($data['password']);
            //print_r($data);
            // exit();

            $this->user_m->save($data,$id);

            redirect('user?updated=true');

        }

        // Load the view
        $this->data['subview'] = 'user/edit';
        $this->load->view('_layout',$this->data);
    }

	public function add($id = NULL)
	{
	    $this->data['user'] = $this->user_m->get_new();

        // Set up the form and rules
        $rules = $this->user_m->rulesNewUser;
        // $id || $rules['password'] .= '|required'; //assiume $id is set, if not password is required. (new user or existing user)
        $this->form_validation->set_rules($rules);

        var_dump($this->input->post());
        // process the form
        if($this->form_validation->run() == TRUE)
        {
            $data = $this->user_m->array_from_post(array('f_name','l_name','username','status'));
            $data['password'] = $this->user_m->hash($data['password']);

            $newUserID = $this->user_m->save($data,$id);
            // redirecting to user data grid
            redirect('user?inserted=true');

            //redirect('user');
        }

        // Load the view
        $this->data['subview'] = 'user/add';
        $this->load->view('_layout',$this->data);
	}

	public function login()
	{
		$this->load->view('_login');
	}

	public function u_login()
	{
		// set form
		$rules = $this->user_m->loginRules;
        $this->form_validation->set_rules($rules);

        // process form
        if($this->form_validation->run() == TRUE){
            // can login and redirect it..
            // echo 'form validation done';
            if($this->user_m->login() == TRUE){
            	// echo 'login Passed';
                // redirect('user/login?login=true');
                redirect('site/index?login=true');
            }
            else{
                // echo 'login Failed ddd';
                $this->session->set_flashdata('error','That email/password combination does not exist');
                redirect('user/login?login=false','refresh');
            }
        }
        redirect('user/login?login=false','refresh');

	}

	public function delete($id)
	{
	        // this function only access by Admin, if not redirect
	        if($this->session->userdata('usertype')!='1'){
	            redirect('dashboard');
	        }
	        $this->staff_m->delete($id);
	        redirect('user/?delete=true');
	        //redirect('user'); // Redirecting to users list view
	}

	public function disable($id)
	{
	        $this->member_m->save(array(
	            'status'=>0
	        ),$id);
	        redirect('member?disable=true');
    	}

}


text:
namespace crashpad {
namespace internal {

ModuleSnapshotWin::ModuleSnapshotWin()
    : ModuleSnapshot(),
      name_(),
      pdb_name_(),
      uuid_(),
      pe_image_reader_(),
      process_reader_(nullptr),
      timestamp_(0),
      age_(0),
      initialized_(),
      vs_fixed_file_info_(),
      initialized_vs_fixed_file_info_() {
}

ModuleSnapshotWin::~ModuleSnapshotWin() {
}

bool ModuleSnapshotWin::Initialize(
    ProcessReaderWin* process_reader,
    const ProcessInfo::Module& process_reader_module) {
  INITIALIZATION_STATE_SET_INITIALIZING(initialized_);

  process_reader_ = process_reader;
  name_ = process_reader_module.name;
  timestamp_ = process_reader_module.timestamp;
  pe_image_reader_.reset(new PEImageReader());
  if (!pe_image_reader_->Initialize(process_reader_,
                                    process_reader_module.dll_base,
                                    process_reader_module.size,
                                    base::UTF16ToUTF8(name_))) {
    return false;
  }

  DWORD age_dword;
  if (pe_image_reader_->DebugDirectoryInformation(
          &uuid_, &age_dword, &pdb_name_)) {
    static_assert(sizeof(DWORD) == sizeof(uint32_t), "unexpected age size");
    age_ = age_dword;
  } else {
    // If we fully supported all old debugging formats, we would want to extract
    // and emit a different type of CodeView record here (as old Microsoft tools
    // would do). As we don't expect to ever encounter a module that wouldn't be
    // be using .PDB that we actually have symbols for, we simply set a
    // plausible name here, but this will never correspond to symbols that we
    // have.
    pdb_name_ = base::UTF16ToUTF8(name_);
  }

  INITIALIZATION_STATE_SET_VALID(initialized_);
  return true;
}

void ModuleSnapshotWin::GetCrashpadOptions(CrashpadInfoClientOptions* options) {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  if (process_reader_->Is64Bit())
    GetCrashpadOptionsInternal<process_types::internal::Traits64>(options);
  else
    GetCrashpadOptionsInternal<process_types::internal::Traits32>(options);
}

std::string ModuleSnapshotWin::Name() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return base::UTF16ToUTF8(name_);
}

uint64_t ModuleSnapshotWin::Address() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return pe_image_reader_->Address();
}

uint64_t ModuleSnapshotWin::Size() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return pe_image_reader_->Size();
}

time_t ModuleSnapshotWin::Timestamp() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return timestamp_;
}

void ModuleSnapshotWin::FileVersion(uint16_t* version_0,
                                    uint16_t* version_1,
                                    uint16_t* version_2,
                                    uint16_t* version_3) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
  if (ffi) {
    *version_0 = ffi->dwFileVersionMS >> 16;
    *version_1 = ffi->dwFileVersionMS & 0xffff;
    *version_2 = ffi->dwFileVersionLS >> 16;
    *version_3 = ffi->dwFileVersionLS & 0xffff;
  } else {
    *version_0 = 0;
    *version_1 = 0;
    *version_2 = 0;
    *version_3 = 0;
  }
}

void ModuleSnapshotWin::SourceVersion(uint16_t* version_0,
                                      uint16_t* version_1,
                                      uint16_t* version_2,
                                      uint16_t* version_3) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
  if (ffi) {
    *version_0 = ffi->dwProductVersionMS >> 16;
    *version_1 = ffi->dwProductVersionMS & 0xffff;
    *version_2 = ffi->dwProductVersionLS >> 16;
    *version_3 = ffi->dwProductVersionLS & 0xffff;
  } else {
    *version_0 = 0;
    *version_1 = 0;
    *version_2 = 0;
    *version_3 = 0;
  }
}

ModuleSnapshot::ModuleType ModuleSnapshotWin::GetModuleType() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  const VS_FIXEDFILEINFO* ffi = VSFixedFileInfo();
  if (ffi) {
    switch (ffi->dwFileType) {
      case VFT_APP:
        return ModuleSnapshot::kModuleTypeExecutable;
      case VFT_DLL:
        return ModuleSnapshot::kModuleTypeSharedLibrary;
      case VFT_DRV:
      case VFT_VXD:
        return ModuleSnapshot::kModuleTypeLoadableModule;
    }
  }
  return ModuleSnapshot::kModuleTypeUnknown;
}

void ModuleSnapshotWin::UUIDAndAge(crashpad::UUID* uuid, uint32_t* age) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  *uuid = uuid_;
  *age = age_;
}

std::string ModuleSnapshotWin::DebugFileName() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return pdb_name_;
}

std::vector<std::string> ModuleSnapshotWin::AnnotationsVector() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  // These correspond to system-logged things on Mac. We don't currently track
  // any of these on Windows, but could in the future.
  // See https://crashpad.chromium.org/bug/38.
  return std::vector<std::string>();
}

std::map<std::string, std::string> ModuleSnapshotWin::AnnotationsSimpleMap()
    const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  PEImageAnnotationsReader annotations_reader(
      process_reader_, pe_image_reader_.get(), name_);
  return annotations_reader.SimpleMap();
}

template <class Traits>
void ModuleSnapshotWin::GetCrashpadOptionsInternal(
    CrashpadInfoClientOptions* options) {
  process_types::CrashpadInfo<Traits> crashpad_info;
  if (!pe_image_reader_->GetCrashpadInfo(&crashpad_info)) {
    options->crashpad_handler_behavior = TriState::kUnset;
    options->system_crash_reporter_forwarding = TriState::kUnset;
    return;
  }

  options->crashpad_handler_behavior =
      CrashpadInfoClientOptions::TriStateFromCrashpadInfo(
          crashpad_info.crashpad_handler_behavior);

  options->system_crash_reporter_forwarding =
      CrashpadInfoClientOptions::TriStateFromCrashpadInfo(
          crashpad_info.system_crash_reporter_forwarding);
}

const VS_FIXEDFILEINFO* ModuleSnapshotWin::VSFixedFileInfo() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

  if (initialized_vs_fixed_file_info_.is_uninitialized()) {
    initialized_vs_fixed_file_info_.set_invalid();
    if (pe_image_reader_->VSFixedFileInfo(&vs_fixed_file_info_)) {
      initialized_vs_fixed_file_info_.set_valid();
    }
  }

  return initialized_vs_fixed_file_info_.is_valid() ? &vs_fixed_file_info_
                                                    : nullptr;
}

}  // namespace internal
}  // namespace crashpad


text:
class PanelClickRecorderOutput;

extern class HookObserver
{
public:
	HookObserver() {}
	void h_handlePanelMouseEvent(int id, int ev, int mx, int my);
	void setUpReciever(PanelClickRecorderOutput * _callbackClass);
private:
	PanelClickRecorderOutput * callbackClass;
} observer;

#endif


text:
package com.jlj.dao;

import java.util.List;

import com.jlj.model.Wscpscenter;

public interface IWscpscenterDao {

	//保存一条记录
	public abstract void save(Wscpscenter wscpscenter);

	//删除一条记录
	public abstract void delete(Wscpscenter wscpscenter);

	//根据ID删除一条记录
	public abstract void deleteById(int id);

	//修改一条记录
	public abstract void update(Wscpscenter wscpscenter);

	//根据hql语句、条件、条件值修改某些记录
	public abstract void updateByHql(final String hql,
			final String[] paramNames, final Object[] values);

	//获得所有记录
	public abstract List<Wscpscenter> getWscpscenters();

	//根据hql语句来查询所有记录
	public abstract List<Wscpscenter> queryList(String queryString);

	//根据hql、条件值查询某些记录
	public abstract List<Wscpscenter> getObjectsByCondition(String queryString,
			Object[] p);

	//根据hql语句、条件、条件值查询某些记录
	public abstract List<Wscpscenter> queryList(String queryString,
			String[] paramNames, Object[] values);

	//根据hql、id列表查询某些记录
	public abstract List<Wscpscenter> getObjectsByIdList(final String hql,
			final List<Integer> idList);

	//根据hql语句、条件值、分页查询某些记录
	public abstract List<Wscpscenter> pageList(final String queryString,
			final Object[] p, final Integer page, final Integer size);

	//根据hql、条件值获得一个唯一值
	public abstract int getUniqueResult(final String queryString,
			final Object[] p);

	//根据id查询一条记录
	public abstract Wscpscenter loadById(int id);

	//根据hql语句、条件、值来查询一条记录
	public abstract Wscpscenter queryByNamedParam(String queryString,
			String[] paramNames, Object[] values);

	//根据hql语句、条件值来查询是否存在该记录
	public abstract boolean checkClientExistsWithName(String queryString,
			Object[] p);

}


text:
A demo to understand how to rotate text or image correctly.
I draw a normal, translated, and rotated text with different colors to demonstrate

One thing needs to mention:
the positive/negative degrees for UIView is clockwise/counterclockwise

Quote:

*The direction that the context is rotated may appear to be altered by the state of the current transformation matrix prior to executing this function. For example, on iOS, a UIView applies a transformation to the graphics context that inverts the Y-axis (by multiplying it by -1). Rotating the user coordinate system on coordinate system that was previously flipped results in a rotation in the opposite direction (that is, positive values appear to rotate the coordinate system in the clockwise direction).*


text:
<?php
namespace Gram\SurveyBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class SurveyRESTControllerTest extends WebTestCase
{

    public function testgetByIdAction()
    {
        $client = static::createClient();

        $client->request('GET', '/spa/v1/surveys/' . 1);

        $response = $client->getResponse();

        if ($response->isSuccessful()) {
            $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
        } else {
            $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode());
        }
    }

    public function testgetByPromocodeAction()
    {
        $client = static::createClient();

        $client->request('GET', '/spa/v1/surveys/' . md5(uniqid()));

        $response = $client->getResponse();

        if ($response->isSuccessful()) {
            $this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
        } else {
            $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode());
        }
    }
}


text:
buzzer squeaks.

![buzzer]

This image made with [Fritzing].

#### pieces that used:
1. arduino (uno/nano/mini/mega..)
2. jumper wires
3. buzzer
4. 1 x 220 Ω resistor
5. breadboard

[buzzer]: https://github.com/arslanbilal/arduino-examples/raw/master/examples/02-buzzer/assets/buzzer.png "buzzer image"
[Fritzing]: http://fritzing.org/home/


text:
using System;
using SciChart.iOS.Charting;
using Xamarin.Examples.Demo.Utils;

namespace Xamarin.Examples.Demo.iOS
{
    [Example3DDefinition("Polar Mesh 3D Chart", description: "Create a simple Polar Mesh 3D Chart", icon: ExampleIcon.Surface3D)]
    class PolarMesh3DChartViewController : SingleChartViewController<SCIChartSurface3D>
    {
        protected override void InitExample()
        {
            const int uSize = 30, vSize = 10;
            var dataSeries3D = new PolarDataSeries3D<double, double>(uSize, vSize, 0d, Math.PI * 1.75) { A = 1, B = 5 };

            var random = new Random();
            for (int u = 0; u < uSize; u++)
            {
                var weightU = 1d - Math.Abs(2d * u / uSize - 1d);
                for (int v = 0; v < vSize; v++)
                {
                    var weightV = 1d - Math.Abs(2d * v / vSize - 1d);
                    var offset = random.NextDouble();

                    dataSeries3D.SetDisplacement(u, v, offset * weightU * weightV);
                }
            }

            var rSeries3D = new SCIFreeSurfaceRenderableSeries3D
            {
                DataSeries = dataSeries3D,
                DrawMeshAs = SCIDrawMeshAs.SolidWireframe,
                Stroke = 0x77228B22,
                ContourInterval = 0.1f,
                ContourStroke = 0x77228B22,
                StrokeThickness = 1f,
                MeshColorPalette = new SCIGradientColorPalette(
                    new[] { ColorUtil.Sapphire, ColorUtil.Blue, ColorUtil.Cyan, ColorUtil.GreenYellow, ColorUtil.Yellow, ColorUtil.Red, ColorUtil.DarkRed },
                    new[] { 0, .1f, .3f, .5f, .7f, .9f, 1}),
                PaletteMaximum = new SCIVector3(0, 0.5f, 0),
            };

            using (Surface.SuspendUpdates())
            {
                Surface.XAxis = new SCINumericAxis3D { VisibleRange = new SCIDoubleRange(-7, 7) };
                Surface.YAxis = new SCINumericAxis3D { VisibleRange = new SCIDoubleRange(0, 3) };
                Surface.ZAxis = new SCINumericAxis3D { VisibleRange = new SCIDoubleRange(-7, 7) };
                Surface.RenderableSeries.Add(rSeries3D);
                Surface.ChartModifiers.Add(CreateDefault3DModifiers());

                Surface.Camera = new SCICamera3D();
                Surface.Viewport.WorldDimensions.AssignX(200, 50, 200);
            }
        }
    }
}


text:
package chord.analyses.heapacc;

import joeq.Compiler.Quad.Operator;
import joeq.Compiler.Quad.Quad;
import joeq.Compiler.Quad.Operator.ALoad;
import joeq.Compiler.Quad.Operator.AStore;
import chord.project.Chord;
import chord.project.analyses.ProgramRel;

/**
 * Relation containing each statement that accesses (reads or writes)
 * an array element (as opposed to an instance or static field).
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
@Chord(
	name = "aryElemE",
	sign = "E0"
)
public class RelAryElemE extends ProgramRel {
	public void fill() {
		DomE domE = (DomE) doms[0];
		int numE = domE.size();
		for (int eIdx = 0; eIdx < numE; eIdx++) {
			Quad e = (Quad) domE.get(eIdx);
			Operator op = e.getOperator();
			if (op instanceof ALoad || op instanceof AStore) {
				add(eIdx);
			}
		}
	}
}


text:
require 'rspec/given'

describe "Then with nesting" do
  use_natural_assertions
  Given(:index) { 1 }
  Given(:value) { "X" }
  Given(:array) { ["a", "b", "c"] }
  Then { array[index].upcase == value  }
end


text:
package org.apache.hadoop.tools.posum.simulation.predictor.basic;

import org.apache.hadoop.mapreduce.v2.api.records.TaskType;
import org.apache.hadoop.tools.posum.common.records.call.IdsByQueryCall;
import org.apache.hadoop.tools.posum.simulation.predictor.TaskPredictionInput;
import org.apache.hadoop.tools.posum.simulation.predictor.TaskPredictionOutput;
import org.apache.hadoop.tools.posum.simulation.predictor.TestPredictor;
import org.junit.Test;

import java.util.List;
import java.util.Set;

import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.JOB_HISTORY;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

public class TestBasicPredictor extends TestPredictor<BasicPredictor> {

  public TestBasicPredictor() {
    super(BasicPredictor.class);
  }

  @Test
  public void testModelMakeup() throws Exception {
    Set<String> sourceJobs = predictor.getModel().getSourceJobs();
    List<String> historicalJobs = db.execute(IdsByQueryCall.newInstance(JOB_HISTORY, null)).getEntries();
    assertThat(sourceJobs, containsInAnyOrder(historicalJobs.toArray()));

    // check history stats for known user
    BasicPredictionStats someJobStats = predictor.getModel().getRelevantStats(someJob);
    assertThat(someJobStats.getAvgMapDuration(), is(2869.0));
    assertThat(someJobStats.getAvgReduceDuration(), is(82522.0));

    // check history stats for unknown user
    BasicPredictionStats anotherJobStats = predictor.getModel().getRelevantStats(anotherJob);
    assertThat(anotherJobStats, nullValue());
  }

  @Test
  public void testMapPrediction() throws Exception {
    TaskPredictionOutput prediction = predictor.predictTaskBehavior(new TaskPredictionInput(someJob.getId(), TaskType.MAP));
    assertThat(prediction.getDuration(), is(2869L));

    someJob.setAvgMapDuration(1000L);
    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(someJob.getId(), TaskType.MAP));
    assertThat(prediction.getDuration(), is(1000L));

    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(anotherJob.getId(), TaskType.MAP));
    assertThat(prediction.getDuration(), is(DEFAULT_TASK_DURATION));

    anotherJob.setAvgMapDuration(2000L);
    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(anotherJob.getId(), TaskType.MAP));
    assertThat(prediction.getDuration(), is(2000L));
  }

  @Test
  public void testReducePrediction() throws Exception {
    TaskPredictionOutput prediction = predictor.predictTaskBehavior(new TaskPredictionInput(someJob.getId(), TaskType.REDUCE));
    assertThat(prediction.getDuration(), is(82522L));

    someJob.setAvgReduceDuration(1001L);
    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(someJob.getId(), TaskType.REDUCE));
    assertThat(prediction.getDuration(), is(1001L));

    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(anotherJob.getId(), TaskType.REDUCE));
    assertThat(prediction.getDuration(), is(DEFAULT_TASK_DURATION));

    anotherJob.setAvgReduceDuration(2001L);
    prediction = predictor.predictTaskBehavior(new TaskPredictionInput(anotherJob.getId(), TaskType.REDUCE));
    assertThat(prediction.getDuration(), is(2001L));
  }
}


text:
package io.druid.server.initialization;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.Period;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Objects;

/**
 */
public class ServerConfig
{
  @JsonProperty
  @Min(1)
  private int numThreads = Math.max(10, (Runtime.getRuntime().availableProcessors() * 17) / 16 + 2) + 30;

  @JsonProperty
  @Min(1)
  private int queueSize = Integer.MAX_VALUE;

  @JsonProperty
  private boolean enableRequestLimit = false;

  @JsonProperty
  @NotNull
  private Period maxIdleTime = new Period("PT5m");

  @JsonProperty
  @Min(0)
  private long defaultQueryTimeout = 300_000; // 5 minutes

  @JsonProperty
  @Min(1)
  private long maxScatterGatherBytes = Long.MAX_VALUE;

  public int getNumThreads()
  {
    return numThreads;
  }

  public int getQueueSize()
  {
    return queueSize;
  }

  public boolean isEnableRequestLimit()
  {
    return enableRequestLimit;
  }

  public Period getMaxIdleTime()
  {
    return maxIdleTime;
  }

  public long getDefaultQueryTimeout()
  {
    return defaultQueryTimeout;
  }

  public long getMaxScatterGatherBytes()
  {
    return maxScatterGatherBytes;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ServerConfig that = (ServerConfig) o;
    return numThreads == that.numThreads &&
           queueSize == that.queueSize &&
           enableRequestLimit == that.enableRequestLimit &&
           defaultQueryTimeout == that.defaultQueryTimeout &&
           maxScatterGatherBytes == that.maxScatterGatherBytes &&
           Objects.equals(maxIdleTime, that.maxIdleTime);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(
        numThreads,
        queueSize,
        enableRequestLimit,
        maxIdleTime,
        defaultQueryTimeout,
        maxScatterGatherBytes
    );
  }
}


text:
.. _devguide_workflow:

====================
Development Workflow
====================

Anyone wishing to make contributions to OpenMC should be fully acquianted and
comfortable working with git_ and GitHub_. We assume here that you have git
installed on your system, have a GitHub account, and have setup SSH keys to be
able to create/push to repositories on GitHub.

Overview
--------

Development of OpenMC relies heavily on branching; specifically, we use a
branching model sometimes referred to as `git flow`_. If you plan to contribute
to OpenMC development, we highly recommend that you read the linked blog post to
get a sense of how the branching model works. There are two main branches that
always exist: *master* and *develop*. The *master* branch is a stable branch
that contains the latest release of the code. The *develop* branch is where any
ongoing development takes place prior to a release and is not guaranteed to be
stable. When the development team decides that a release should occur, the
*develop* branch is merged into *master*.

Trivial changes to the code may be committed directly to the *develop* branch by
a trusted developer. However, most new features should be developed on a branch
that branches off of *develop*. When the feature is completed, a `pull request`_
is initiated on GitHub that is then reviewed by a trusted developer. If the pull
request is satisfactory, it is then merged into *develop*. Note that a trusted
developer may not review their own pull request (i.e., an independent code
review is required).

Code Review Criteria
--------------------

In order to be considered suitable for inclusion in the *develop* branch, the
following criteria must be satisfied for all proposed changes:

- Changes have a clear purpose and are useful.
- Compiles under all conditions (MPI, OpenMP, HDF5, etc.).  This is checked as
  part of the test suite (see `test_compile.py`_).
- Passes the regression suite.
- If appropriate, test cases are added to regression suite.
- No memory leaks (checked with valgrind_).
- Conforms to the OpenMC `style guide`_.
- No degradation of performance or greatly increased memory usage. This is not a
  hard rule -- in certain circumstances, a performance loss might be acceptable
  if there are compelling reasons.
- New features/input are documented.
- No unnecessary external software dependencies are introduced.

Contributing
------------

Now that you understand the basic development workflow, let's discuss how an
individual to contribute to development. Note that this would apply to both new
features and bug fixes. The general steps for contributing are as follows:

1. Fork the main openmc repository from `mit-crpg/openmc`_. This will create a
   repository with the same name under your personal account. As such, you can
   commit to it as you please without disrupting other developers.

   .. image:: ../_images/fork.png

2. Clone your fork of OpenMC and create a branch that branches off of *develop*:

   .. code-block:: sh

       git clone git@github.com:yourusername/openmc.git
       cd openmc
       git checkout -b newbranch develop

3. Make your changes on the new branch that you intend to have included in
   *develop*. If you have made other changes that should not be merged back,
   ensure that those changes are made on a different branch.

4. Issue a pull request from GitHub and select the *develop* branch of
   mit-crpg/openmc as the target.

   .. image:: ../_images/pullrequest.png

   At a minimum, you should describe what the changes you've made are and why
   you are making them. If the changes are related to an oustanding issue, make
   sure it is cross-referenced. A wise developer would also check whether their
   changes do indeed pass the regression test suite.

5. A trusted developer will review your pull request based on the criteria
   above. Any issues with the pull request can be discussed directly on the pull
   request page itself.

6. After the pull request has been thoroughly vetted, it is merged back into the
   *develop* branch of mit-crpg/openmc.

Private Development
-------------------

While the process above depends on the fork of the OpenMC repository being
publicly available on GitHub, you may also wish to do development on a private
repository for research or commercial purposes. The proper way to do this is to
create a complete copy of the OpenMC repository (not a fork from GitHub). The
private repository can then either be stored just locally or in conjunction with
a private repository on Github (this requires a `paid plan`_). Alternatively,
`Bitbucket`_ offers private repositories for free. If you want to merge some
changes you've made in your private repository back to mit-crpg/openmc
repository, simply follow the steps above with an extra step of pulling a branch
from your private repository into a public fork.

.. _git: http://git-scm.com/
.. _GitHub: https://github.com/
.. _git flow: http://nvie.com/git-model
.. _test_compile.py: https://github.com/mit-crpg/openmc/blob/develop/tests/test_compile/test_compile.py
.. _valgrind: http://valgrind.org/
.. _style guide: http://mit-crpg.github.io/openmc/devguide/styleguide.html
.. _pull request: https://help.github.com/articles/using-pull-requests
.. _mit-crpg/openmc: https://github.com/mit-crpg/openmc
.. _paid plan: https://github.com/plans
.. _Bitbucket: https://bitbucket.org


text: require File.join(File.dirname(__FILE__), '../..', 'wrapper')


text:
'use strict';

import ComponentHelper from '../helpers/ComponentHelper.js';
import EventMappers from '../helpers/EventMappers.js';
import {Objects} from 'js-prelude';
import {Surface} from 'js-surface';
import {SurfaceX} from 'js-surface-x';

const dom = Surface.createElement;

export default SurfaceX.createFactory({
    typeName: 'FKTextField',

    properties: {
        className: {
            type: 'String',
            defaultValue: null
        },

        disabled: {
            type: 'boolean',
            defaultValue: false
        },

        defaultValue: {
            type: 'string',
            defaultValue: null
        },

        label: {
            type: 'string',
            defaultValue: null
        },

        maxLength: {
            type: 'number',
            defaultValue: null
        },

        placeholder: {
            type: 'string',
            defaultValue: null
        },

        readOnly: {
            type: 'boolean',
            defaultValue: false
        },

        value: {
            type: 'String',
            defaultValue: null
        },

        visible: {
            type: 'boolean',
            defaultValue: true
        },

        onChange: {
            type: 'function',
            defaultValue: null
        }
    },

    initialState: {
        value: ''
    },

    stateTransitions: {
        setValue(value) {
            return state => Objects.transform(state, {
                value: {$set: value}
            });
        }
    },

    render: ({props, state, ctrl}) => {
        const
            value = state.value,
            placeholder = props.get('placeholder'),
            maxLength = props.getInteger('maxLength', null),
            disabled = props.get('disabled') ? 'disabled' : null,
            visible = props.get('visible'),
            readOnly = props.get('readOnly') ? 'readonly' : null,
            label = props.get('label'),
            labelElem = label === null ? null : dom('label', {className: 'fk-label'}, label),

            className =
                ComponentHelper.buildCssClass(
                    'fk-text-field',
                    props.get('className')),

            doOnChange = event => {
                const value = event.target.value;

                ctrl.setValue(value);

                props.getMappedFunction(
                    'onChange',
                        event => ({
                        type: 'change',
                        value: event.target.value
                    }),
                    null)(event);
            },

            ret =
                !visible
                ? dom('span')
                : dom('div', {
                        className
                    },
                    labelElem,
                    dom('input', {
                        type: 'text',
                        value,
                        placeholder,
                        maxLength,
                        disabled,
                        readOnly,
                        onChange: doOnChange
                    }));

console.log('value', value)
       return ret;
    },

    onWillMount({props, ctrl}) {
        if (props.isSomething('defaultValue')) {
            ctrl.setValue(props.getString('defaultValue'));
            console.log("onWillMount - state:", ctrl.getState())
        }
    },

    onNextProps({props, state, ctrl}) {
        if (props.isSomething('value')) {
            const newValue = props.getString('value');
            console.log('dooo', props.__data)
            if (newValue !== state.value) {
                ctrl.setValue(newValue);
            }
        }
    }
});


text:
package io.crate.planner.operators;

public class LogicalPlanVisitor<C, R> {

    protected R visitPlan(LogicalPlan logicalPlan, C context) {
        return null;
    }

    public R visitMultiPhase(MultiPhase logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitCollect(Collect logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitCount(Count logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitGet(Get logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitEval(Eval logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitFilter(Filter logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitGroupHashAggregate(GroupHashAggregate logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitHashAggregate(HashAggregate logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitInsert(Insert logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitInsert(InsertFromValues logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitNestedLoopJoin(NestedLoopJoin logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitHashJoin(HashJoin logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitLimit(Limit logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitOrder(Order logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitRootRelationBoundary(RootRelationBoundary logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitUnion(Union logicalPlan, C context) {
        return visitPlan(logicalPlan, context);
    }

    public R visitProjectSet(ProjectSet projectSet, C context) {
        return visitPlan(projectSet, context);
    }

    public R visitWindowAgg(WindowAgg windowAgg, C context) {
        return visitPlan(windowAgg, context);
    }

    public R visitTopNDistinct(TopNDistinct topNDistinct, C context) {
        return visitPlan(topNDistinct, context);
    }

    public R visitTableFunction(TableFunction tableFunction, C context) {
        return visitPlan(tableFunction, context);
    }

    public R visitRename(Rename rename, C context) {
        return visitPlan(rename, context);
    }

    public R visitFetch(Fetch fetch, C context) {
        return visitPlan(fetch, context);
    }
}