text:
/* global Fullnode */
/*
 * BIP44 Account
 * =============
 *
 * According to BIP44, an account is a xpub or xprv from which you can derive
 * the chain index and then address index. If you have the private key, you can
 * derive the other private keys. If you have the public key, you can only
 * derive public keys and addresses.
 */
'use strict'
let Address = Fullnode.Address
let BIP32 = Fullnode.BIP32
let Struct = Fullnode.Struct
let asink = require('asink')

function BIP44Account (bip32, extindex, intindex, pathmap, addrhexmap) {
  if (!(this instanceof BIP44Account)) {
    return new BIP44Account(bip32, extindex, intindex, pathmap, addrhexmap)
  }
  this.initialize()
  this.fromObject({bip32, extindex, intindex, pathmap, addrhexmap})
}

BIP44Account.prototype = Object.create(Struct.prototype)
BIP44Account.prototype.constructor = BIP44Account

BIP44Account.prototype.initialize = function () {
  this.pathmap = new Map()
  this.addrhexmap = new Map()
  this.extindex = -1
  this.intindex = -1
  return this
}

BIP44Account.prototype.asyncFromMasterXprvPrivate = function (bip32, accountindex) {
  return asink(function *() {
    if (!(accountindex >= 0 && accountindex < Math.pow(2, 31))) {
      throw new Error('accountindex must be a valid non-hardened integer greater than 0')
    }
    // TODO: Support testnet, which has a 1 for the coin type
    let path = "m/44'/0'/" + accountindex + "'"
    bip32 = yield bip32.asyncDerive(path)
    this.fromObject({bip32})
    return this
  }, this)
}

BIP44Account.prototype.asyncFromMasterXprvPublic = function (bip32, accountindex) {
  return asink(function *() {
    if (!(accountindex >= 0 && accountindex < Math.pow(2, 31))) {
      throw new Error('accountindex must be a valid non-hardened integer greater than 0')
    }
    // TODO: Support testnet, which has a 1 for the coin type
    let path = "m/44'/0'/" + accountindex + "'"
    bip32 = yield bip32.asyncDerive(path)
    bip32 = bip32.toPublic()
    this.fromObject({bip32})
    return this
  }, this)
}

BIP44Account.prototype.toJSON = function () {
  let json = {}
  json.extindex = this.extindex
  json.intindex = this.intindex

  // TODO: Replace with proper non-blocking method
  json.bip32 = this.bip32.toHex()

  json.pathmap = {}
  this.pathmap.forEach((keys, path) => {
    json.pathmap[path] = {}

    if (this.isPrivate()) {
      // TODO: Replace with proper non-blocking method
      json.pathmap[path].xprv = keys.xprv.toHex()
    }

    // TODO: Replace with proper non-blocking method
    json.pathmap[path].xpub = keys.xpub.toHex()

    json.pathmap[path].address = keys.address.toHex()
  })

  return json
}

BIP44Account.prototype.fromJSON = function (json) {
  this.extindex = json.extindex
  this.intindex = json.intindex

  // TODO: Replace with proper non-blocking method
  this.bip32 = BIP32().fromHex(json.bip32)

  this.pathmap = new Map()
  Object.keys(json.pathmap).forEach((path) => {
    let keys = json.pathmap[path]
    let xprv

    if (keys.xprv) {
      // TODO: Replace with proper non-blocking method
      xprv = BIP32().fromHex(keys.xprv)
    }

    // TODO: Replace with proper non-blocking method
    let xpub = BIP32().fromHex(keys.xpub)

    let address = Address().fromHex(keys.address)
    this.pathmap.set(path, {xprv, xpub, address})
  })

  // Note that addrhexmap is not directly stored in JSON - it is rederived from
  // the pathmap, which has all the information. We just have to rebuild the
  // map.
  this.addrhexmap = new Map()
  Object.keys(json.pathmap).forEach((path) => {
    let keys = json.pathmap[path]
    let xprv

    if (keys.xprv) {
      // TODO: Replace with proper non-blocking method
      xprv = BIP32().fromHex(keys.xprv)
    }

    // TODO: Replace with proper non-blocking method
    let xpub = BIP32().fromHex(keys.xpub)

    let address = Address().fromHex(keys.address)
    this.addrhexmap.set(keys.address, {xprv, xpub, address})
  })

  return this
}

BIP44Account.prototype.isPrivate = function () {
  return this.bip32.isPrivate()
}

/**
 * TODO: When deriving keys from a path, we should also create a map from
 * address to private key. This will let us easily sign transactions when we
 * know which of our addresses it is.
 */
BIP44Account.prototype.asyncDeriveKeysFromPath = function (path) {
  return asink(function *() {
    if (!path) {
      throw new Error('must specify path - see bip32 specification for format')
    }
    let keys
    keys = this.pathmap.get(path)
    if (keys) {
      return keys
    }
    if (this.bip32.isPrivate()) {
      let xprv = yield this.bip32.asyncDerive(path)
      let xpub = xprv.toPublic()
      let address = yield Address().asyncFromPubkey(xpub.pubkey)
      keys = {xprv, xpub, address}
    } else {
      let xpub = this.bip32.toPublic()
      let address = yield Address().asyncFromPubkey(xpub.pubkey)
      keys = {xpub, address}
    }
    this.pathmap.set(path, keys)
    this.addrhexmap.set(keys.address.toHex(), keys)
    return keys
  }, this)
}

/**
 * Returns all external (non-change) addresses up to extindex. This is
 * essentially all the addresses that have been gotten with
 * asyncGetAddressKeys.
 */
BIP44Account.prototype.asyncGetAllExtAddresses = function () {
  return asink(function *() {
    let addresses = []
    for (let index = 0; index <= this.extindex; index++) {
      let keys = yield this.asyncGetExtAddressKeys(index)
      addresses.push(keys.address)
    }
    return addresses
  }, this)
}

/**
 * Returns all internal (change) addresses up to intindex. This is all the change
 * addresses that have been gotten with asyncGetChangeKeys.
 */
BIP44Account.prototype.asyncGetAllIntAddresses = function () {
  return asink(function *() {
    let addresses = []
    for (let index = 0; index <= this.intindex; index++) {
      let keys = yield this.asyncGetIntAddressKeys(index)
      addresses.push(keys.address)
    }
    return addresses
  }, this)
}

/**
 * Get external (non-change) address keys.
 */
BIP44Account.prototype.asyncGetExtAddressKeys = function (extindex) {
  return asink(function *() {
    if (typeof extindex !== 'number' || extindex < 0 || Object.is(extindex, NaN)) {
      throw new Error('invalid extindex - must be number >= 0')
    }
    let path = 'm/0/' + extindex
    let keys = yield this.asyncDeriveKeysFromPath(path)
    return keys
  }, this)
}

BIP44Account.prototype.asyncGetNextExtAddressKeys = function () {
  return asink(function *() {
    let extindex = this.extindex + 1
    let keys = yield this.asyncGetExtAddressKeys(extindex)
    this.extindex = extindex
    return keys
  }, this)
}

/**
 * Get internal (change) address keys.
 */
BIP44Account.prototype.asyncGetIntAddressKeys = function (intindex) {
  return asink(function *() {
    let path = 'm/1/' + intindex
    let keys = yield this.asyncDeriveKeysFromPath(path)
    return keys
  }, this)
}

BIP44Account.prototype.asyncGetNextIntAddressKeys = function () {
  return asink(function *() {
    let intindex = this.intindex + 1
    let keys = yield this.asyncGetIntAddressKeys(intindex)
    this.intindex = intindex
    return keys
  }, this)
}

module.exports = BIP44Account


text:
<?php
//src/AirAtlantique/UserBundle/Entity/MembershipCard.php
namespace AirAtlantique\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="MembershipCard")
 * @ORM\Entity(repositoryClass="AirAtlantique\UserBundle\Entity\MembershipCardRepository")
 */

class MembershipCard
{
	/**
     * @ORM\Column(type="string")
     * @var string
     */
    private $cardNumber;

    /**
    * @ORM\Id
    * @ORM\ManyToOne(targetEntity="AirAtlantique\UserBundle\Entity\Subscription")
     */
    private $subscription;

    /**
    * @ORM\Id
    * @ORM\OneToOne(targetEntity="AirAtlantique\UserBundle\Entity\User")
     */
    private $user;

    /**
     * Set cardNumber
     *
     * @param integer $cardNumber
     * @return MembershipCard
     */
    public function setCardNumber($cardNumber)
    {
        $this->cardNumber = $cardNumber;

        return $this;
    }

    /**
     * Get cardNumber
     *
     * @return integer
     */
    public function getCardNumber()
    {
        return $this->cardNumber;
    }

    /**
     * Set subscription
     *
     * @param \AirAtlantique\UserBundle\Entity\Subscription $subscription
     * @return MembershipCard
     */
    public function setSubscription(\AirAtlantique\UserBundle\Entity\Subscription $subscription)
    {
        $this->subscription = $subscription;

        return $this;
    }

    /**
     * Get subscription
     *
     * @return \AirAtlantique\UserBundle\Entity\Subscription
     */
    public function getSubscription()
    {
        return $this->subscription;
    }

    /**
     * Set user
     *
     * @param \AirAtlantique\UserBundle\Entity\User $user
     * @return MembershipCard
     */
    public function setUser(\AirAtlantique\UserBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AirAtlantique\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}

redpajama_set_name: RedPajamaGithub


text:
FactoryGirl.define do
  factory :profile do
    username "simeonwillbanks"
    gravatar_id "a624cb08e20db3ac4adb6380928a7b11"

    after(:build) { |p| p.token = MyGists::Secure.encrypt("token") }
    after(:stub) { |p| p.token = MyGists::Secure.encrypt("token") }
  end
end


text:
/** @define MyComponent */

:root {
  --MyComponent-property: value;
}

.MyComponent {}

.MyComponent .other {}


text:
<?php

namespace hiqdev\php\collection\yii;

use yii\helpers\Yii;

/**
 * Manager Trait.
 * Like basic collection but instantiates items when getting.
 */
trait ManagerTrait
{
    use ObjectTrait;

    /**
     * @var string default class to create item objects
     */
    protected $_itemClass;

    public function setItemClass($class)
    {
        $this->_itemClass = $class;
    }

    public function getItemClass()
    {
        return $this->_itemClass ?: get_called_class();
    }

    public function getItemConfig($name = null, array $config = [])
    {
        if (!isset($config['__class'])) {
            $config['__class'] = $this->getItemClass($name, $config) ?: get_called_class();
        }

        return $config;
    }

    /**
     * Creates item instance from array configuration.
     * @param string $name   item name
     * @param array  $config item instance configuration
     * @return object instance
     */
    protected function createItem($name, array $config = [])
    {
        return Yii::createObject($this->getItemConfig($name, $config));
    }

    /**
     * Returns item by name. Instantiates it before.
     * @param string $name item name
     * @param mixed $default default value
     * @return object item instance
     */
    public function getItem($name, $default = null)
    {
        if (empty($this->_items[$name])) {
            $this->_items[$name] = $default;
        }
        $item = &$this->_items[$name];
        if (is_array($item) || is_null($item)) {
            $item = $this->createItem($name, $item ?: []);
        }

        return $item;
    }

    public function hasObject($name)
    {
        return is_object($this->_items[$name]);
    }

    /**
     * Get them all as array of items!
     * Instantiates all the items.
     * @return array list of items
     * @see get
     */
    public function getItems()
    {
        foreach ($this->_items as $name => $item) {
            $this->getItem($name);
        }

        return $this->_items;
    }

    /**
     * Get raw items - uninstantiated.
     * @return array
     */
    public function rawItems()
    {
        return $this->_items;
    }
}


text:
namespace SccmTools.Library.Module.Commands.CreateApplication
{
    public interface IPackageDefinitionFileProvider
    {
        File GetPackageDefinitionFile(string packageDefinitionFileName);
    }
}


text:
FactoryGirl.define do
  factory :provider, class: Provider::Desk do
    name 'desk'
    type 'Provider::Desk'

    factory :provider_zendesk, class: Provider::Zendesk do
      name 'zendesk'
      type 'Provider::Zendesk'
    end
  end
end


text:
import Item from "#SRC/js/structs/Item";

export default class Backend extends Item {
  getApplicationReachabilityPercent() {
    return Number(this.get("application_reachability_pct") || 0);
  }

  getFailLastMinute() {
    return Number(this.get("fail_last_minute") || 0);
  }

  getFailPercent() {
    const success = this.getSuccessLastMinute();
    const fail = this.getFailLastMinute();

    // No execution
    if (success + fail === 0) {
      return 0;
    }

    // Only failures
    if (success === 0) {
      return 100;
    }

    return Math.floor((fail / success) * 100);
  }

  getFrameworkID() {
    const frameworkID = this.get("framework_id");

    if (frameworkID && frameworkID.length) {
      return frameworkID;
    }

    return null;
  }

  getIP() {
    return this.get("ip");
  }

  getMachineReachabilityPercent() {
    return Number(this.get("machine_reachability_pct") || 0);
  }

  getP99Latency() {
    return Number(Number(this.get("p99_latency_ms")).toFixed(2));
  }

  getPort() {
    return Number(this.get("port"));
  }

  getSuccessLastMinute() {
    return Number(this.get("success_last_minute"));
  }

  getTaskID() {
    const taskID = this.get("task_id");

    if (taskID && taskID.length) {
      return taskID;
    }

    return null;
  }
}


text:
import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import { SemVer } from 'semver';
import * as TypeMoq from 'typemoq';
import { IFileSystem } from '../../../client/common/platform/types';
import {
    createCondaEnv,
    createPythonEnv,
    createWindowsStoreEnv,
} from '../../../client/common/process/pythonEnvironment';
import { IProcessService, StdErrError } from '../../../client/common/process/types';
import { Architecture } from '../../../client/common/utils/platform';
import { Conda } from '../../../client/pythonEnvironments/common/environmentManagers/conda';
import { OUTPUT_MARKER_SCRIPT } from '../../../client/common/process/internal/scripts';

use(chaiAsPromised);

suite('PythonEnvironment', () => {
    let processService: TypeMoq.IMock<IProcessService>;
    let fileSystem: TypeMoq.IMock<IFileSystem>;
    const pythonPath = 'path/to/python';

    setup(() => {
        processService = TypeMoq.Mock.ofType<IProcessService>(undefined, TypeMoq.MockBehavior.Strict);
        fileSystem = TypeMoq.Mock.ofType<IFileSystem>(undefined, TypeMoq.MockBehavior.Strict);
    });

    test('getInterpreterInformation should return an object if the python path is valid', async () => {
        const json = {
            versionInfo: [3, 7, 5, 'candidate', 1],
            sysPrefix: '/path/of/sysprefix/versions/3.7.5rc1',
            version: '3.7.5rc1 (default, Oct 18 2019, 14:48:48) \n[Clang 11.0.0 (clang-1100.0.33.8)]',
            is64Bit: true,
        };

        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
            .returns(() =>
                Promise.resolve({
                    stdout: JSON.stringify(json),
                }),
            );
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();
        const expectedResult = {
            architecture: Architecture.x64,
            path: pythonPath,
            version: new SemVer('3.7.5-candidate1'),
            sysPrefix: json.sysPrefix,
            sysVersion: undefined,
        };

        expect(result).to.deep.equal(expectedResult, 'Incorrect value returned by getInterpreterInformation().');
    });

    test('getInterpreterInformation should return an object if the version info contains less than 5 items', async () => {
        const json = {
            versionInfo: [3, 7, 5, 'alpha'],
            sysPrefix: '/path/of/sysprefix/versions/3.7.5a1',
            version: '3.7.5a1 (default, Oct 18 2019, 14:48:48) \n[Clang 11.0.0 (clang-1100.0.33.8)]',
            is64Bit: true,
        };

        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
            .returns(() =>
                Promise.resolve({
                    stdout: JSON.stringify(json),
                }),
            );
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();
        const expectedResult = {
            architecture: Architecture.x64,
            path: pythonPath,
            version: new SemVer('3.7.5-alpha'),
            sysPrefix: json.sysPrefix,
            sysVersion: undefined,
        };

        expect(result).to.deep.equal(
            expectedResult,
            'Incorrect value returned by getInterpreterInformation() with truncated versionInfo.',
        );
    });

    test('getInterpreterInformation should return an object if the version info contains less than 4 items', async () => {
        const json = {
            versionInfo: [3, 7, 5],
            sysPrefix: '/path/of/sysprefix/versions/3.7.5rc1',
            version: '3.7.5rc1 (default, Oct 18 2019, 14:48:48) \n[Clang 11.0.0 (clang-1100.0.33.8)]',
            is64Bit: true,
        };

        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
            .returns(() =>
                Promise.resolve({
                    stdout: JSON.stringify(json),
                }),
            );
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();
        const expectedResult = {
            architecture: Architecture.x64,
            path: pythonPath,
            version: new SemVer('3.7.5'),
            sysPrefix: json.sysPrefix,
            sysVersion: undefined,
        };

        expect(result).to.deep.equal(
            expectedResult,
            'Incorrect value returned by getInterpreterInformation() with truncated versionInfo.',
        );
    });

    test('getInterpreterInformation should return an object with the architecture value set to x86 if json.is64bit is not 64bit', async () => {
        const json = {
            versionInfo: [3, 7, 5, 'candidate'],
            sysPrefix: '/path/of/sysprefix/versions/3.7.5rc1',
            version: '3.7.5rc1 (default, Oct 18 2019, 14:48:48) \n[Clang 11.0.0 (clang-1100.0.33.8)]',
            is64Bit: false,
        };

        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
            .returns(() =>
                Promise.resolve({
                    stdout: JSON.stringify(json),
                }),
            );
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();
        const expectedResult = {
            architecture: Architecture.x86,
            path: pythonPath,
            version: new SemVer('3.7.5-candidate'),
            sysPrefix: json.sysPrefix,
            sysVersion: undefined,
        };

        expect(result).to.deep.equal(
            expectedResult,
            'Incorrect value returned by getInterpreterInformation() for x86b architecture.',
        );
    });

    test('getInterpreterInformation should error out if interpreterInfo.py times out', async () => {
        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))

            .returns(() => Promise.reject(new Error('timed out')));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();

        expect(result).to.equal(
            undefined,
            'getInterpreterInfo() should return undefined because interpreterInfo timed out.',
        );
    });

    test('getInterpreterInformation should return undefined if the json value returned by interpreterInfo.py is not valid', async () => {
        processService
            .setup((p) => p.shellExec(TypeMoq.It.isAny(), TypeMoq.It.isAny()))
            .returns(() => Promise.resolve({ stdout: 'bad json' }));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getInterpreterInformation();

        expect(result).to.equal(undefined, 'getInterpreterInfo() should return undefined because of bad json.');
    });

    test('getExecutablePath should return pythonPath if pythonPath is a file', async () => {
        fileSystem.setup((f) => f.pathExists(pythonPath)).returns(() => Promise.resolve(true));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getExecutablePath();

        expect(result).to.equal(pythonPath, "getExecutablePath() sbould return pythonPath if it's a file");
    });

    test('getExecutablePath should not return pythonPath if pythonPath is not a file', async () => {
        const executablePath = 'path/to/dummy/executable';
        fileSystem.setup((f) => f.pathExists(pythonPath)).returns(() => Promise.resolve(false));
        processService
            .setup((p) => p.shellExec(`${pythonPath} -c "import sys;print(sys.executable)"`, TypeMoq.It.isAny()))
            .returns(() => Promise.resolve({ stdout: executablePath }));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.getExecutablePath();

        expect(result).to.equal(executablePath, "getExecutablePath() sbould not return pythonPath if it's not a file");
    });

    test('getExecutablePath should throw if the result of exec() writes to stderr', async () => {
        const stderr = 'bar';
        fileSystem.setup((f) => f.pathExists(pythonPath)).returns(() => Promise.resolve(false));
        processService
            .setup((p) => p.shellExec(`${pythonPath} -c "import sys;print(sys.executable)"`, TypeMoq.It.isAny()))
            .returns(() => Promise.reject(new StdErrError(stderr)));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = env.getExecutablePath();

        await expect(result).to.eventually.be.rejectedWith(stderr);
    });

    test('isModuleInstalled should call processService.exec()', async () => {
        const moduleName = 'foo';
        const argv = ['-c', `import ${moduleName}`];
        processService
            .setup((p) => p.exec(pythonPath, argv, { throwOnStdErr: true }))
            .returns(() => Promise.resolve({ stdout: '' }))
            .verifiable(TypeMoq.Times.once());
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        await env.isModuleInstalled(moduleName);

        processService.verifyAll();
    });

    test('isModuleInstalled should return true when processService.exec() succeeds', async () => {
        const moduleName = 'foo';
        const argv = ['-c', `import ${moduleName}`];
        processService
            .setup((p) => p.exec(pythonPath, argv, { throwOnStdErr: true }))
            .returns(() => Promise.resolve({ stdout: '' }));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.isModuleInstalled(moduleName);

        expect(result).to.equal(true, 'isModuleInstalled() should return true if the module exists');
    });

    test('isModuleInstalled should return false when processService.exec() throws', async () => {
        const moduleName = 'foo';
        const argv = ['-c', `import ${moduleName}`];
        processService
            .setup((p) => p.exec(pythonPath, argv, { throwOnStdErr: true }))
            .returns(() => Promise.reject(new StdErrError('bar')));
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = await env.isModuleInstalled(moduleName);

        expect(result).to.equal(false, 'isModuleInstalled() should return false if the module does not exist');
    });

    test('getExecutionInfo should return pythonPath and the execution arguments as is', () => {
        const args = ['-a', 'b', '-c'];
        const env = createPythonEnv(pythonPath, processService.object, fileSystem.object);

        const result = env.getExecutionInfo(args);

        expect(result).to.deep.equal(
            { command: pythonPath, args, python: [pythonPath], pythonExecutable: pythonPath },
            'getExecutionInfo should return pythonPath and the command and execution arguments as is',
        );
    });
});

suite('CondaEnvironment', () => {
    let processService: TypeMoq.IMock<IProcessService>;
    let fileSystem: TypeMoq.IMock<IFileSystem>;
    const args = ['-a', 'b', '-c'];
    const pythonPath = 'path/to/python';
    const condaFile = 'path/to/conda';

    setup(() => {
        sinon.stub(Conda, 'getConda').resolves(new Conda(condaFile));
        sinon.stub(Conda.prototype, 'getInterpreterPathForEnvironment').resolves(pythonPath);
        processService = TypeMoq.Mock.ofType<IProcessService>(undefined, TypeMoq.MockBehavior.Strict);
        fileSystem = TypeMoq.Mock.ofType<IFileSystem>(undefined, TypeMoq.MockBehavior.Strict);
    });

    teardown(() => sinon.restore());

    test('getExecutionInfo with a named environment should return execution info using the environment name', async () => {
        const condaInfo = { name: 'foo', path: 'bar' };
        const env = await createCondaEnv(condaInfo, processService.object, fileSystem.object);

        const result = env?.getExecutionInfo(args, pythonPath);

        expect(result).to.deep.equal({
            command: condaFile,
            args: ['run', '-n', condaInfo.name, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT, ...args],
            python: [condaFile, 'run', '-n', condaInfo.name, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT],
            pythonExecutable: pythonPath,
        });
    });

    test('getExecutionInfo with a non-named environment should return execution info using the environment path', async () => {
        const condaInfo = { name: '', path: 'bar' };
        const env = await createCondaEnv(condaInfo, processService.object, fileSystem.object);

        const result = env?.getExecutionInfo(args, pythonPath);

        expect(result).to.deep.equal({
            command: condaFile,
            args: ['run', '-p', condaInfo.path, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT, ...args],
            python: [condaFile, 'run', '-p', condaInfo.path, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT],
            pythonExecutable: pythonPath,
        });
    });

    test('getExecutionObservableInfo with a named environment should return execution info using conda full path with the name', async () => {
        const condaInfo = { name: 'foo', path: 'bar' };
        const expected = {
            command: condaFile,
            args: ['run', '-n', condaInfo.name, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT, ...args],
            python: [condaFile, 'run', '-n', condaInfo.name, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT],
            pythonExecutable: pythonPath,
        };
        const env = await createCondaEnv(condaInfo, processService.object, fileSystem.object);

        const result = env?.getExecutionObservableInfo(args, pythonPath);

        expect(result).to.deep.equal(expected);
    });

    test('getExecutionObservableInfo with a non-named environment should return execution info using conda full path', async () => {
        const condaInfo = { name: '', path: 'bar' };
        const expected = {
            command: condaFile,
            args: ['run', '-p', condaInfo.path, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT, ...args],
            python: [condaFile, 'run', '-p', condaInfo.path, '--no-capture-output', 'python', OUTPUT_MARKER_SCRIPT],
            pythonExecutable: pythonPath,
        };
        const env = await createCondaEnv(condaInfo, processService.object, fileSystem.object);

        const result = env?.getExecutionObservableInfo(args, pythonPath);

        expect(result).to.deep.equal(expected);
    });
});

suite('WindowsStoreEnvironment', () => {
    let processService: TypeMoq.IMock<IProcessService>;
    const pythonPath = 'foo';

    setup(() => {
        processService = TypeMoq.Mock.ofType<IProcessService>(undefined, TypeMoq.MockBehavior.Strict);
    });

    test('Should return pythonPath if it is the path to the windows store interpreter', async () => {
        const env = createWindowsStoreEnv(pythonPath, processService.object);

        const executablePath = await env.getExecutablePath();

        expect(executablePath).to.equal(pythonPath);
        processService.verifyAll();
    });
});


text:
% latex table generated in R 3.3.1 by xtable 1.8-2 package
% Fri Jul  8 14:09:29 2016
\begin{tabular}{l}
  \hline
Analysis of Variance Table \\
  \hline
Model 1: Miles/Gal \textasciitilde No. Cylinders \\
  Model 2: Miles/Gal \textasciitilde No. Cylinders + Displacement \\
  Model 3: Miles/Gal \textasciitilde No. Cylinders + Displacement + Horsepower \\
  Model 4: Miles/Gal \textasciitilde No. Cylinders + Displacement + Horsepower + Rear Axle Ratio \\
  Model 5: Miles/Gal \textasciitilde No. Cylinders + Displacement + Horsepower + Rear Axle Ratio + Weight \\
   \hline
\end{tabular}


text:
import alt from '../core/alt';
import QuestionActions from '../actions/QuestionActions';

class QuestionStore {
    constructor() {
        this.bindActions(QuestionActions);
        this.loaded = false;
        this.modalIsOpen = false;
        this.questionAddedSnackbarOpen = false;
        this.questionDeletedSnackbarOpen = false;
        this.data = [];
        this.question = {
            id: '',
            text: '',
            tags: [],
            answers: [{
                text: '',
                preferred : true
            }],
            level: '',
            tech: '',
            createdAt: ''
        };
        this.error = null;
    }

    onGetQuestionsSuccess(data) {
        if (data === false) {
            this.onFailed();
        } else {
            this.data = data;
            this.loaded = true;
        }
    }

    onCreateQuestionSuccess(data) {
        if (data === false) {
            this.onFailed();
        } else {
            this.questionAddedSnackbarOpen = true;
        }
    }

    onDeleteQuestionSuccess(data) {
        if (data === false) {
            this.onFailed();
        } else {
            this.questionDeletedSnackbarOpen = true;
        }
    }

    onFailed(err) {
        this.loaded = true;
        this.error = "Data unavailable";
    }
}

export default alt.createStore(QuestionStore, 'QuestionStore');


text:
package be.error.wsproxy.configuration.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import be.error.wsproxy.configuration.profiles.Local;

/**
 * When the module forwards messages to the actual target endpoint, you have to option to specify if the transport needs
 * to be secure or not. This will most likely be used for external outbound, where messages are to be sent to the
 * external target service requesting secure transport.
 *
 * @author Koen Serneels
 */
@Configuration("endpointProtocolMappingConfiguration")
public class EndpointProtocolMapping {

	@Local
	public static class LocalConfiguration {
		@Value("${endpoint.protocol.mapping}")
		private String endpointProtocolMapping;

		// The configuration is returned as a single String to make externalization of the property easier as required
		// by other profiles (eg. JNDI for the production profile).
		@Bean
		public String serviceEndpointProtocolMapping() {
			return endpointProtocolMapping;
		}
	}
}


text:
<?php
// Filename: /module/FuelStation/src/FuelStation/Mapper/StationMapperInterface.php

namespace FuelStation\Mapper;

use FuelStation\Entity\StationInterface;

interface StationMapperInterface
{
    /**
     * @param int|string $id
     * @returns FuelStationInterface
     * @throws \InvalidArgumentException
     */
    public function find($id);

    /**
     * @return array|FuelStationInterface[]
     */
    public function findAll();

    /**
     * @param StationInterface $stationObject
     *
     * @param StationInterface $stationObject
     * @return StationInterface
     * @throws \Exception
     */
    public function save(StationInterface $stationObject);
}


text:
<?php namespace RatkoR\Crate;

use RatkoR\Crate\Schema\Builder;
use Crate\DBAL\Driver\PDOCrate\Driver as DoctrineDriver;
use RatkoR\Crate\Query\Grammars\Grammar as QueryGrammar;
use RatkoR\Crate\Schema\Grammars\Grammar as SchemaGrammar;
use Crate\PDO\PDO;

class Connection extends \Illuminate\Database\Connection
{
	/**
	 * Set the default fetch mode for the connection.
	 *
	 * NOTE! Crate cannot use PDO::FETCH_CLASS fetch mode, so
	 * 	we silently  change it to PDO::FETCH_ASSOC
	 *
	 * @param  int  $fetchMode
	 * @return int
	 */
	public function setFetchMode($fetchMode)
	{
		if ($fetchMode === \PDO::FETCH_CLASS)
			$fetchMode = \PDO::FETCH_ASSOC;

		parent::setFetchMode($fetchMode);
	}

	/**
	 * Get a schema builder instance for the connection.
	 *
	 * @return \Illuminate\Database\Schema\MySqlBuilder
	 */
	public function getSchemaBuilder()
	{
		if (is_null($this->schemaGrammar)) { $this->useDefaultSchemaGrammar(); }

		return new Builder($this);
	}

	/**
	 * Get the default query grammar instance.
	 *
	 * @return \Illuminate\Database\Query\Grammars\MySqlGrammar
	 */
	protected function getDefaultQueryGrammar()
	{
		return $this->withTablePrefix(new QueryGrammar);
	}

	/**
	 * Get the default schema grammar instance.
	 *
	 * @return \Illuminate\Database\Schema\Grammars\MySqlGrammar
	 */
	protected function getDefaultSchemaGrammar()
	{
		return $this->withTablePrefix(new SchemaGrammar);
	}

	/**
	 * Get the default post processor instance.
	 *
	 * @return \Illuminate\Database\Query\Processors\Processor
	 */
	protected function getDefaultPostProcessor()
	{
		return new Query\Processors\Processor;
	}

	/**
	 * Get the Doctrine DBAL driver.
	 *
	 * @return \Doctrine\DBAL\Driver\PDOMySql\Driver
	 */
	protected function getDoctrineDriver()
	{
		return new DoctrineDriver;
	}

	/**
	 * Execute an SQL statement and return the boolean result.
	 *
	 * We need to override statement to bind parameters one by one. The
	 * execute() function of crate-pdo can take bind parameters, but it
	 * wrongly sets all of them to strings. So if you bind array to an
	 * array field, you'd get error. A patch was sent to crate-pdo, but was
	 * NACK-ed (with "fix eloquent").
	 *
	 * So in order to make this work we override statement().
	 *
	 * @param  string  $query
	 * @param  array   $bindings
	 * @return bool
	 */
	public function statement($query, $bindings = array())
	{
		return $this->run($query, $bindings, function($me, $query, $bindings)
		{
			if ($me->pretending()) return true;

			$bindings = $me->prepareBindings($bindings);

			$stmt = $me->getPdo()->prepare($query);

			$this->bindParameters($stmt, $bindings);

			return $stmt->execute();
		});
	}

	protected function bindParameters(&$stmt, $values)
	{
		if (!$values || !is_array($values))
			return;

		$i = 0;

		foreach ($values AS $value) {
			$this->bindParameter($i++, $stmt, $value);
		}
	}

	protected function bindParameter($index, &$stmt, $value)
	{
		$dataType = $this->guessDataType($value);
		$stmt->bindParam($index+1, $value, $dataType);
	}

    /**
     * Returns PDO::PARAM_* type based on parameter value.
     */
    protected function guessDataType($value)
    {
        switch (gettype($value)) {
            case 'array':
                return PDO::PARAM_ARRAY;
            case 'object':
                return PDO::PARAM_OBJECT;
            case 'double':
                return PDO::PARAM_DOUBLE;
            case 'boolean':
                return PDO::PARAM_BOOL;
            case 'NULL':
                return PDO::PARAM_NULL;
            case 'integer':
                return PDO::PARAM_LONG;
            default:
                return PDO::PARAM_STR;
        }
    }
}


text:
/**
 * form - jQuery EasyUI
 *
 */
(function($){
	/**
	 * submit the form
	 */
	function ajaxSubmit(target, options){
		var opts = $.data(target, 'form').options;
		$.extend(opts, options||{});

		var param = $.extend({}, opts.queryParams);
		if (opts.onSubmit.call(target, param) == false){return;}

		var frameId = 'easyui_frame_' + (new Date().getTime());
		var frame = $('<iframe id='+frameId+' name='+frameId+'></iframe>').appendTo('body')
		frame.attr('src', window.ActiveXObject ? 'javascript:false' : 'about:blank');
		frame.css({
			position:'absolute',
			top:-1000,
			left:-1000
		});
		frame.bind('load', cb);

		submit(param);

		function submit(param){
			var form = $(target);
			if (opts.url){
				form.attr('action', opts.url);
			}
			var t = form.attr('target'), a = form.attr('action');
			form.attr('target', frameId);
			var paramFields = $();
			try {
				for(var n in param){
					var field = $('<input type="hidden" name="' + n + '">').val(param[n]).appendTo(form);
					paramFields = paramFields.add(field);
				}
				checkState();
				form[0].submit();
			} finally {
				form.attr('action', a);
				t ? form.attr('target', t) : form.removeAttr('target');
				paramFields.remove();
			}
		}

		function checkState(){
			var f = $('#'+frameId);
			if (!f.length){return}
			try{
				var s = f.contents()[0].readyState;
				if (s && s.toLowerCase() == 'uninitialized'){
					setTimeout(checkState, 100);
				}
			} catch(e){
				cb();
			}
		}

		var checkCount = 10;
		function cb(){
			var f = $('#'+frameId);
			if (!f.length){return}
			f.unbind();
			var data = '';
			try{
				var body = f.contents().find('body');
				data = body.html();
				if (data == ''){
					if (--checkCount){
						setTimeout(cb, 100);
						return;
					}
				}
				var ta = body.find('>textarea');
				if (ta.length){
					data = ta.val();
				} else {
					var pre = body.find('>pre');
					if (pre.length){
						data = pre.html();
					}
				}
			} catch(e){
			}
			opts.success(data);
			setTimeout(function(){
				f.unbind();
				f.remove();
			}, 100);
		}
	}

	/**
	 * load form data
	 * if data is a URL string type load from remote site,
	 * otherwise load from local data object.
	 */
	function load(target, data){
		var opts = $.data(target, 'form').options;

		if (typeof data == 'string'){
			var param = {};
			if (opts.onBeforeLoad.call(target, param) == false) return;

			$.ajax({
				url: data,
				data: param,
				dataType: 'json',
				success: function(data){
					_load(data);
				},
				error: function(){
					opts.onLoadError.apply(target, arguments);
				}
			});
		} else {
			_load(data);
		}

		function _load(data){
			var form = $(target);
			for(var name in data){
				var val = data[name];
				var rr = _checkField(name, val);
				if (!rr.length){
					var count = _loadOther(name, val);
					if (!count){
						$('input[name="'+name+'"]', form).val(val);
						$('textarea[name="'+name+'"]', form).val(val);
						$('select[name="'+name+'"]', form).val(val);
					}
				}
				_loadCombo(name, val);
			}
			opts.onLoadSuccess.call(target, data);
			validate(target);
		}

		/**
		 * check the checkbox and radio fields
		 */
		function _checkField(name, val){
			var rr = $(target).find('input[name="'+name+'"][type=radio], input[name="'+name+'"][type=checkbox]');
			rr._propAttr('checked', false);
			rr.each(function(){
				var f = $(this);
				if (f.val() == String(val) || $.inArray(f.val(), $.isArray(val)?val:[val]) >= 0){
					f._propAttr('checked', true);
				}
			});
			return rr;
		}

		function _loadOther(name, val){
			var count = 0;
			var pp = ['textbox','numberbox','slider'];
			for(var i=0; i<pp.length; i++){
				var p = pp[i];
				var f = $(target).find('input['+p+'Name="'+name+'"]');
				if (f.length){
					f[p]('setValue', val);
					count += f.length;
				}
			}
			return count;
		}

		function _loadCombo(name, val){
			var form = $(target);
			var cc = ['combobox','combotree','combogrid','datetimebox','datebox','combo'];
			var c = form.find('[comboName="' + name + '"]');
			if (c.length){
				for(var i=0; i<cc.length; i++){
					var type = cc[i];
					if (c.hasClass(type+'-f')){
						if (c[type]('options').multiple){
							c[type]('setValues', val);
						} else {
							c[type]('setValue', val);
						}
						return;
					}
				}
			}
		}
	}

	/**
	 * clear the form fields
	 */
	function clear(target){
		$('input,select,textarea', target).each(function(){
			var t = this.type, tag = this.tagName.toLowerCase();
			if (t == 'text' || t == 'hidden' || t == 'password' || tag == 'textarea'){
				this.value = '';
			} else if (t == 'file'){
				var file = $(this);
				var newfile = file.clone().val('');
				newfile.insertAfter(file);
				if (file.data('validatebox')){
					file.validatebox('destroy');
					newfile.validatebox();
				} else {
					file.remove();
				}
			} else if (t == 'checkbox' || t == 'radio'){
				this.checked = false;
			} else if (tag == 'select'){
				this.selectedIndex = -1;
			}

		});

		var t = $(target);
		var plugins = ['textbox','combo','combobox','combotree','combogrid','slider'];
		for(var i=0; i<plugins.length; i++){
			var plugin = plugins[i];
			var r = t.find('.'+plugin+'-f');
			if (r.length && r[plugin]){
				r[plugin]('clear');
			}
		}
		validate(target);
	}

	function reset(target){
		target.reset();
		var t = $(target);

		var plugins = ['textbox','combo','combobox','combotree','combogrid','datebox','datetimebox','spinner','timespinner','numberbox','numberspinner','slider'];
		for(var i=0; i<plugins.length; i++){
			var plugin = plugins[i];
			var r = t.find('.'+plugin+'-f');
			if (r.length && r[plugin]){
				r[plugin]('reset');
			}
		}
		validate(target);
	}

	/**
	 * set the form to make it can submit with ajax.
	 */
	function setForm(target){
		var options = $.data(target, 'form').options;
		$(target).unbind('.form');
		if (options.ajax){
			$(target).bind('submit.form', function(){
				setTimeout(function(){
					ajaxSubmit(target, options);
				}, 0);
				return false;
			});
		}
		setValidation(target, options.novalidate);
	}

	function initForm(target, options){
		options = options || {};
		var state = $.data(target, 'form');
		if (state){
			$.extend(state.options, options);
		} else {
			$.data(target, 'form', {
				options: $.extend({}, $.fn.form.defaults, $.fn.form.parseOptions(target), options)
			});
		}
	}

	function validate(target){
		if ($.fn.validatebox){
			var t = $(target);
			t.find('.validatebox-text:not(:disabled)').validatebox('validate');
			var invalidbox = t.find('.validatebox-invalid');
			invalidbox.filter(':not(:disabled):first').focus();
			return invalidbox.length == 0;
		}
		return true;
	}

	function setValidation(target, novalidate){
		var opts = $.data(target, 'form').options;
		opts.novalidate = novalidate;
		$(target).find('.validatebox-text:not(:disabled)').validatebox(novalidate ? 'disableValidation' : 'enableValidation');
	}

	$.fn.form = function(options, param){
		if (typeof options == 'string'){
			this.each(function(){
				initForm(this);
			});
			return $.fn.form.methods[options](this, param);
		}

		return this.each(function(){
			initForm(this, options);
			setForm(this);
		});
	};

	$.fn.form.methods = {
		options: function(jq){
			return $.data(jq[0], 'form').options;
		},
		submit: function(jq, options){
			return jq.each(function(){
				ajaxSubmit(this, options);
			});
		},
		load: function(jq, data){
			return jq.each(function(){
				load(this, data);
			});
		},
		clear: function(jq){
			return jq.each(function(){
				clear(this);
			});
		},
		reset: function(jq){
			return jq.each(function(){
				reset(this);
			});
		},
		validate: function(jq){
			return validate(jq[0]);
		},
		disableValidation: function(jq){
			return jq.each(function(){
				setValidation(this, true);
			});
		},
		enableValidation: function(jq){
			return jq.each(function(){
				setValidation(this, false);
			});
		}
	};

	$.fn.form.parseOptions = function(target){
		var t = $(target);
		return $.extend({}, $.parser.parseOptions(target, [{ajax:'boolean'}]), {
			url: (t.attr('action') ? t.attr('action') : undefined)
		});
	};

	$.fn.form.defaults = {
		novalidate: false,
		ajax: true,
		url: null,
		queryParams: {},
		onSubmit: function(param){return $(this).form('validate');},
		success: function(data){},
		onBeforeLoad: function(param){},
		onLoadSuccess: function(data){},
		onLoadError: function(){}
	};
})(jQuery);


text:
package executor

import (
	"fmt"
	"strings"

	"github.com/juju/errors"
	"github.com/pingcap/tidb/ast"
	"github.com/pingcap/tidb/context"
	"github.com/pingcap/tidb/evaluator"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/model"
	"github.com/pingcap/tidb/mysql"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessionctx/db"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/util"
	"github.com/pingcap/tidb/util/charset"
	"github.com/pingcap/tidb/util/sqlexec"
	"github.com/pingcap/tidb/util/types"
)

// SimpleExec represents simple statement executor.
// For statements do simple execution.
// includes `UseStmt`, 'SetStmt`, `SetCharsetStmt`.
// `DoStmt`, `BeginStmt`, `CommitStmt`, `RollbackStmt`.
// TODO: list all simple statements.
type SimpleExec struct {
	Statement ast.StmtNode
	ctx       context.Context
	done      bool
}

// Fields implements Executor Fields interface.
func (e *SimpleExec) Fields() []*ast.ResultField {
	return nil
}

// Next implements Execution Next interface.
func (e *SimpleExec) Next() (*Row, error) {
	if e.done {
		return nil, nil
	}
	var err error
	switch x := e.Statement.(type) {
	case *ast.UseStmt:
		err = e.executeUse(x)
	case *ast.SetStmt:
		err = e.executeSet(x)
	case *ast.SetCharsetStmt:
		err = e.executeSetCharset(x)
	case *ast.DoStmt:
		err = e.executeDo(x)
	case *ast.BeginStmt:
		err = e.executeBegin(x)
	case *ast.CommitStmt:
		err = e.executeCommit(x)
	case *ast.RollbackStmt:
		err = e.executeRollback(x)
	case *ast.CreateUserStmt:
		err = e.executeCreateUser(x)
	case *ast.SetPwdStmt:
		err = e.executeSetPwd(x)
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	e.done = true
	return nil, nil
}

// Close implements Executor Close interface.
func (e *SimpleExec) Close() error {
	return nil
}

func (e *SimpleExec) executeUse(s *ast.UseStmt) error {
	dbname := model.NewCIStr(s.DBName)
	dbinfo, exists := sessionctx.GetDomain(e.ctx).InfoSchema().SchemaByName(dbname)
	if !exists {
		return infoschema.DatabaseNotExists.Gen("database %s not exists", dbname)
	}
	db.BindCurrentSchema(e.ctx, dbname.O)
	// character_set_database is the character set used by the default database.
	// The server sets this variable whenever the default database changes.
	// See: http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_character_set_database
	sessionVars := variable.GetSessionVars(e.ctx)
	sessionVars.Systems[variable.CharsetDatabase] = dbinfo.Charset
	sessionVars.Systems[variable.CollationDatabase] = dbinfo.Collate
	return nil
}

func (e *SimpleExec) executeSet(s *ast.SetStmt) error {
	sessionVars := variable.GetSessionVars(e.ctx)
	globalVars := variable.GetGlobalVarAccessor(e.ctx)
	for _, v := range s.Variables {
		// Variable is case insensitive, we use lower case.
		name := strings.ToLower(v.Name)
		if !v.IsSystem {
			// User variable.
			value, err := evaluator.Eval(e.ctx, v.Value)
			if err != nil {
				return errors.Trace(err)
			}

			if value == nil {
				delete(sessionVars.Users, name)
			} else {
				sessionVars.Users[name] = fmt.Sprintf("%v", value)
			}
			return nil
		}
		sysVar := variable.GetSysVar(name)
		if sysVar == nil {
			return variable.UnknownSystemVar.Gen("Unknown system variable '%s'", name)
		}
		if sysVar.Scope == variable.ScopeNone {
			return errors.Errorf("Variable '%s' is a read only variable", name)
		}
		if v.IsGlobal {
			if sysVar.Scope&variable.ScopeGlobal > 0 {
				value, err := evaluator.Eval(e.ctx, v.Value)
				if err != nil {
					return errors.Trace(err)
				}
				if value == nil {
					value = ""
				}
				svalue, err := types.ToString(value)
				if err != nil {
					return errors.Trace(err)
				}
				err = globalVars.SetGlobalSysVar(e.ctx, name, svalue)
				return errors.Trace(err)
			}
			return errors.Errorf("Variable '%s' is a SESSION variable and can't be used with SET GLOBAL", name)
		}
		if sysVar.Scope&variable.ScopeSession > 0 {
			if value, err := evaluator.Eval(e.ctx, v.Value); err != nil {
				return errors.Trace(err)
			} else if value == nil {
				sessionVars.Systems[name] = ""
			} else {
				sessionVars.Systems[name] = fmt.Sprintf("%v", value)
			}
			return nil
		}
		return errors.Errorf("Variable '%s' is a GLOBAL variable and should be set with SET GLOBAL", name)
	}
	return nil
}

func (e *SimpleExec) executeSetCharset(s *ast.SetCharsetStmt) error {
	collation := s.Collate
	if len(collation) == 0 {
		var err error
		collation, err = charset.GetDefaultCollation(s.Charset)
		if err != nil {
			return errors.Trace(err)
		}
	}
	sessionVars := variable.GetSessionVars(e.ctx)
	for _, v := range variable.SetNamesVariables {
		sessionVars.Systems[v] = s.Charset
	}
	sessionVars.Systems[variable.CollationConnection] = collation
	return nil
}

func (e *SimpleExec) executeDo(s *ast.DoStmt) error {
	for _, expr := range s.Exprs {
		_, err := evaluator.Eval(e.ctx, expr)
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

func (e *SimpleExec) executeBegin(s *ast.BeginStmt) error {
	_, err := e.ctx.GetTxn(true)
	if err != nil {
		return errors.Trace(err)
	}
	// With START TRANSACTION, autocommit remains disabled until you end
	// the transaction with COMMIT or ROLLBACK. The autocommit mode then
	// reverts to its previous state.
	variable.GetSessionVars(e.ctx).SetStatusFlag(mysql.ServerStatusInTrans, true)
	return nil
}

func (e *SimpleExec) executeCommit(s *ast.CommitStmt) error {
	err := e.ctx.FinishTxn(false)
	variable.GetSessionVars(e.ctx).SetStatusFlag(mysql.ServerStatusInTrans, false)
	return errors.Trace(err)
}

func (e *SimpleExec) executeRollback(s *ast.RollbackStmt) error {
	err := e.ctx.FinishTxn(true)
	variable.GetSessionVars(e.ctx).SetStatusFlag(mysql.ServerStatusInTrans, false)
	return errors.Trace(err)
}

func (e *SimpleExec) executeCreateUser(s *ast.CreateUserStmt) error {
	users := make([]string, 0, len(s.Specs))
	for _, spec := range s.Specs {
		userName, host := parseUser(spec.User)
		exists, err1 := userExists(e.ctx, userName, host)
		if err1 != nil {
			return errors.Trace(err1)
		}
		if exists {
			if !s.IfNotExists {
				return errors.New("Duplicate user")
			}
			continue
		}
		pwd := ""
		if spec.AuthOpt.ByAuthString {
			pwd = util.EncodePassword(spec.AuthOpt.AuthString)
		} else {
			pwd = util.EncodePassword(spec.AuthOpt.HashString)
		}
		user := fmt.Sprintf(`("%s", "%s", "%s")`, host, userName, pwd)
		users = append(users, user)
	}
	if len(users) == 0 {
		return nil
	}
	sql := fmt.Sprintf(`INSERT INTO %s.%s (Host, User, Password) VALUES %s;`, mysql.SystemDB, mysql.UserTable, strings.Join(users, ", "))
	_, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}

// parse user string into username and host
// root@localhost -> roor, localhost
func parseUser(user string) (string, string) {
	strs := strings.Split(user, "@")
	return strs[0], strs[1]
}

func userExists(ctx context.Context, name string, host string) (bool, error) {
	sql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User="%s" AND Host="%s";`, mysql.SystemDB, mysql.UserTable, name, host)
	rs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)
	if err != nil {
		return false, errors.Trace(err)
	}
	defer rs.Close()
	row, err := rs.Next()
	if err != nil {
		return false, errors.Trace(err)
	}
	return row != nil, nil
}

func (e *SimpleExec) executeSetPwd(s *ast.SetPwdStmt) error {
	// TODO: If len(s.User) == 0, use CURRENT_USER()
	userName, host := parseUser(s.User)
	// Update mysql.user
	sql := fmt.Sprintf(`UPDATE %s.%s SET password="%s" WHERE User="%s" AND Host="%s";`, mysql.SystemDB, mysql.UserTable, util.EncodePassword(s.Password), userName, host)
	_, err := e.ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(e.ctx, sql)
	return errors.Trace(err)
}


text:
/**
 * @file
 *   This file includes definitions for Primary Backbone Router service management in the Thread Network.
 */

#ifndef BACKBONE_ROUTER_LEADER_HPP_
#define BACKBONE_ROUTER_LEADER_HPP_

#include "openthread-core-config.h"

#if (OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2)
#include <openthread/backbone_router.h>
#include <openthread/ip6.h>

#include "common/locator.hpp"
#include "net/ip6_address.hpp"

namespace ot {

namespace BackboneRouter {

typedef otBackboneRouterConfig BackboneRouterConfig;

/**
 * This class implements the basic Primary Backbone Router service operations.
 *
 */
class Leader : public InstanceLocator
{
public:
    // Primary Backbone Router Service state or state change.
    enum State
    {
        kStateNone = 0,       ///< Not exist (trigger Backbone Router register its service).
        kStateAdded,          ///< Newly added.
        kStateRemoved,        ///< Newly removed (trigger Backbone Router register its service).
        kStateToTriggerRereg, ///< Short address or sequence number changes (trigger re-registration).
                              ///< May also have ReregistrationDelay or MlrTimeout update.
        kStateRefreshed,      ///< Only ReregistrationDelay or MlrTimeout changes.
        kStateUnchanged,      ///< No change on Primary Backbone Router information (only for logging).
    };

    // Domain Prefix state or state change.
    enum DomainPrefixState
    {
        kDomainPrefixNone = 0,  ///< Not available.
        kDomainPrefixAdded,     ///< Added.
        kDomainPrefixRemoved,   ///< Removed.
        kDomainPrefixRefreshed, ///< Changed.
        kDomainPrefixUnchanged, ///< Nothing changed.
    };

    /**
     * This constructor initializes the `Leader`.
     *
     * @param[in] aInstance  A reference to the OpenThread instance.
     *
     */
    explicit Leader(Instance &aInstance);

    /**
     * This method resets the cached Primary Backbone Router.
     *
     */
    void Reset(void);

    /**
     * This method updates the cached Primary Backbone Router if any when new network data is available.
     *
     */
    void Update(void);

    /**
     * This method gets the Primary Backbone Router in the Thread Network.
     *
     * @param[out]  aConfig        The Primary Backbone Router information.
     *
     * @retval OT_ERROR_NONE       Successfully got the Primary Backbone Router information.
     * @retval OT_ERROR_NOT_FOUND  No Backbone Router in the Thread Network.
     *
     */
    otError GetConfig(BackboneRouterConfig &aConfig) const;

    /**
     * This method gets the Backbone Router Service ID.
     *
     * @param[out]  aServiceId     The reference whether to put the Backbone Router Service ID.
     *
     * @retval OT_ERROR_NONE       Successfully got the Backbone Router Service ID.
     * @retval OT_ERROR_NOT_FOUND  Backbone Router service doesn't exist.
     *
     */
    otError GetServiceId(uint8_t &aServiceId) const;

    /**
     * This method gets the short address of the Primary Backbone Router.
     *
     * @returns short address of Primary Backbone Router, or Mac::kShortAddrInvalid if no Primary Backbone Router.
     *
     */
    uint16_t GetServer16(void) const { return mConfig.mServer16; }

    /**
     * This method indicates whether or not there is Primary Backbone Router.
     *
     * @retval TRUE if there is Primary Backbone Router, FALSE otherwise.
     *
     */
    bool HasPrimary(void) const { return mConfig.mServer16 != Mac::kShortAddrInvalid; }

    /**
     * This method gets the Domain Prefix in the Thread Network.
     *
     * @retval A pointer to the Domain Prefix or nullptr if there is no Domain Prefix.
     *
     */
    const otIp6Prefix *GetDomainPrefix(void) const { return (mDomainPrefix.mLength == 0) ? nullptr : &mDomainPrefix; }

    /**
     * This method indicates whether or not the Domain Prefix is available in the Thread Network.
     *
     * @retval TRUE if there is Domain Prefix, FALSE otherwise.
     *
     */
    bool HasDomainPrefix(void) const { return (mDomainPrefix.mLength > 0); }

    /**
     * This method indicates whether or not the address is a Domain Unicast Address.
     *
     * @param[in]  aAddress A reference to the address.
     *
     * @retval true  @p aAddress is a domain unicast address.
     * @retval false @p aAddress is not a domain unicast address.
     *
     */
    bool IsDomainUnicast(const Ip6::Address &aAddress) const;

private:
    void UpdateBackboneRouterPrimary(void);
    void UpdateDomainPrefixConfig(void);
#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_BBR == 1)
    void               LogBackboneRouterPrimary(State aState, const BackboneRouterConfig &aConfig) const;
    void               LogDomainPrefix(DomainPrefixState aState, const otIp6Prefix &aPrefix) const;
    static const char *StateToString(State aState);
    static const char *DomainPrefixStateToString(DomainPrefixState aState);
#else
    void LogBackboneRouterPrimary(State, const BackboneRouterConfig &) const {}
    void LogDomainPrefix(DomainPrefixState, const otIp6Prefix &) const {}
#endif

    BackboneRouterConfig mConfig;       ///< Primary Backbone Router information.
    otIp6Prefix          mDomainPrefix; ///< Domain Prefix in the Thread network.
};

} // namespace BackboneRouter

/**
 * @}
 */

} // namespace ot

#endif // (OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2)

#endif // BACKBONE_ROUTER_LEADER_HPP_


text:
package main

import (
	"flag"
	"os"

	"github.com/disintegration/bebop/store"
)

// printAdmins prints all the administrator users.
func printAdmins() {
	cfg, err := getConfig()
	if err != nil {
		logger.Fatalf("failed to load configuration: %s", err)
	}

	s, err := getStore(cfg)
	if err != nil {
		logger.Fatalf("failed to get data store: %s", err)
	}

	admins, err := s.Users().GetAdmins()
	if err != nil {
		logger.Fatalf("failed to get the list of admins: %s", err)
	}

	for i, user := range admins {
		logger.Printf("%d: %s", i+1, user.Name)
	}
}

// addAdmin adds a user to the list of administrators.
func addAdmin() {
	setAdmin(true)
}

// removeAdmin removes a user to the list of administrators.
func removeAdmin() {
	setAdmin(false)
}

func setAdmin(isAdmin bool) {
	username := flag.Arg(1)
	if username == "" {
		help()
		os.Exit(2)
	}

	cfg, err := getConfig()
	if err != nil {
		logger.Fatalf("failed to load configuration: %s", err)
	}

	s, err := getStore(cfg)
	if err != nil {
		logger.Fatalf("failed to get data store: %s", err)
	}

	user, err := s.Users().GetByName(username)
	if err != nil {
		if err == store.ErrNotFound {
			logger.Fatalf("user not found: %s", username)
		} else {
			logger.Fatalf("user search by username failed: %s", err)
		}
	}

	if user.Admin == isAdmin {
		if isAdmin {
			logger.Fatalf("user %s is already an admin", username)
		} else {
			logger.Fatalf("user %s is not an admin", username)
		}
	}

	err = s.Users().SetAdmin(user.ID, isAdmin)
	if err != nil {
		logger.Fatalf("failed to change user admin rights: %s", err)
	}

	if isAdmin {
		logger.Printf("user %s is added to admin list", username)
	} else {
		logger.Printf("user %s is removed from admin list", username)
	}
}


text:
<?php

namespace instantjay\salesmatephp\Entity;

class User extends SalesmateEntity
{
    public function __construct($data)
    {
        $this->path = '/users';

        $this->availableProperties = [
            'id',
            'firstName',
            'lastName',
            'email',
            'allowedLoginFrom',
            'timezone',
            'photo',
            'dateFormat',
            'timeFormat',
            'emailSignature',
            'isActive',
            'invitationAccepted',
            'nickname',
            'Role',
            'Profile',
            'UserAccessTokens'
        ];

        parent::__construct($data);
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->data['id'];
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->data['firstName'];
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->data['lastName'];
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->data['email'];
    }

    /**
     * @return string
     */
    public function getAllowedLoginFrom()
    {
        return $this->data['allowedLoginFrom'];
    }

    /**
     * @return string
     */
    public function getTimezone()
    {
        return $this->data['timezone'];
    }

    /**
     * @return string
     */
    public function getPhoto()
    {
        return $this->data['photo'];
    }

    /**
     * @return string
     */
    public function getDateFormat()
    {
        return $this->data['dateFormat'];
    }

    /**
     * @return string
     */
    public function getTimeFormat()
    {
        return $this->data['timeFormat'];
    }

    /**
     * @return string
     */
    public function getEmailSignature()
    {
        return $this->data['emailSignature'];
    }

    /**
     * @return string
     */
    public function isActive()
    {
        return $this->data['isActive'];
    }

    /**
     * @return string
     */
    public function getInvitationAccepted()
    {
        return $this->data['invitationAccepted'];
    }

    /**
     * @return string
     */
    public function getNickname()
    {
        return $this->data['nickname'];
    }

    /**
     * @return string
     */
    public function getRole()
    {
        return $this->data['Role'];
    }

    /**
     * @return string
     */
    public function getProfile()
    {
        return $this->data['Profile'];
    }

    /**
     * @return string
     */
    public function getUserAccessTokens()
    {
        return $this->data['UserAccessTokens'];
    }
}


text:
class CreateLoyalPassportLockers < ActiveRecord::Migration
  def change
    create_table :loyal_passport_lockers do |t|
      t.references :target
      t.integer    :owner_id

      t.integer :position, default: 0, null: false

      # 发布状态 ###############################
      t.integer :publish_status_value, default: 0, :null => false

      # 级别 #################################
      t.integer :level, default: 0, null: false

      t.timestamps
    end
  end
end


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Department;

/**
 * DepartmentSearch represents the model behind the search form about `app\models\Department`.
 */
class DepartmentSearch extends Department
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['depart_id'], 'integer'],
            [['depart_name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Department::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'depart_id' => $this->depart_id,
        ]);

        $query->andFilterWhere(['like', 'depart_name', $this->depart_name]);

        return $dataProvider;
    }
}


text:
Inferno Redux is a [redux](https://github.com/reactjs/redux) library for [Inferno](https://github.com/infernojs/inferno).

Inferno Redux passes `context.store` value to each component.

## Install

```
npm install inferno-redux
```

## Contents

* Provider
* connect

## Usage

Usage of `inferno-redux` is similar to that of [react-redux](https://github.com/reactjs/react-redux).
Inspiration was taken from `react-redux` to provide Inferno with a similar API.

```js
import Inferno from 'inferno';
import { Router, Route, browserHistory } from 'inferno-router';
import { Provider } from 'inferno-redux';
import { createStore } from 'redux';

const store = createStore(function(state, action) {
  switch (action.type) {
    case 'CHANGE_NAME':
      return {
        name: action.name
      }
    default:
      return {
        name: 'TOM'
      };
  }
})

class App extends Component {
    render() {
        return <div>
            { this.props.children }
        </div>;
    }
}

class BasicComponent1 extends Component {
    render() {
        const store = this.context.store;
        const state = store.getState();

        const onClick = e => {
            e.preventDefault();
            store.dispatch({
                type: 'CHANGE_NAME',
                name: 'Jerry'
            });
        };

        return (
            <div className="basic">
                <a id="dispatch" onClick={ onClick }>
                    <span>Hello { state.name || 'Tom' }</span>
                </a>
            </div>
        );
    }
}

class BasicComponent2 extends Component {
    render() {
        const store = this.context.store;
        const state = store.getState();

        return (
            <div className="basic2">
                { state.name === 'Jerry' ? 'You\'re a mouse!' : 'You\'re a cat!' }
            </div>
        );
    }
}

InfernoDOM.render((
    <Provider store={ store }>
        <Router history={ browserHistory } component={ App }>
            <Route path='/next' component={ BasicComponent2 } />
            <Route path='/' component={ BasicComponent1 } />
        </Router>
    </Provider>
), container);
```


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.jps.incremental.storage;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.jps.incremental.relativizer.PathRelativizerService;

import java.io.File;
import java.io.IOException;

/**
 * @author Eugene Zhuravlev
 */
public final class ProjectStamps {
  public static final String PORTABLE_CACHES_PROPERTY = "org.jetbrains.jps.portable.caches";
  public static final boolean PORTABLE_CACHES = Boolean.getBoolean(PORTABLE_CACHES_PROPERTY);
  public static final boolean FORCE_DOWNLOAD_PORTABLE_CACHES = Boolean.getBoolean("org.jetbrains.jps.portable.caches.force.download");

  private static final Logger LOG = Logger.getInstance(ProjectStamps.class);

  private final StampsStorage<? extends StampsStorage.Stamp> myStampsStorage;

  public ProjectStamps(File dataStorageRoot,
                       BuildTargetsState targetsState,
                       PathRelativizerService relativizer) throws IOException {
    myStampsStorage = PORTABLE_CACHES
                      ? new FileStampStorage(dataStorageRoot, relativizer, targetsState)
                      : new FileTimestampStorage(dataStorageRoot, targetsState);
  }

  public StampsStorage<? extends StampsStorage.Stamp> getStampStorage() {
    return myStampsStorage;
  }

  public void clean() {
    myStampsStorage.wipe();
  }

  public void close() {
    try {
      myStampsStorage.close();
    }
    catch (IOException e) {
      LOG.error(e);
      FileUtil.delete(myStampsStorage.getStorageRoot());
    }
  }
}


text:
using System;
using NUnit.Framework;
using Symbooglix;
using Microsoft.Boogie;

namespace ExprBuilderTests.ConstantFoldingTests
{
    [TestFixture()]
    public class FoldLt : ConstantFoldingExprBuilderTests
    {
        [Test()]
        public void simpleConstantIntEqual()
        {
            var cfb = GetConstantFoldingBuilder();
            var constant0 = cfb.ConstantInt(0);
            var constant1 = cfb.ConstantInt(0);
            var result = cfb.Lt(constant0, constant1);
            CheckIsBoolType(result);
            Assert.IsTrue(ExprUtil.IsFalse(result));
        }

        [Test()]
        public void simpleConstantIntLt()
        {
            var cfb = GetConstantFoldingBuilder();
            var constant0 = cfb.ConstantInt(0);
            var constant1 = cfb.ConstantInt(1);
            var result = cfb.Lt(constant0, constant1);
            CheckIsBoolType(result);
            Assert.IsTrue(ExprUtil.IsTrue(result));
        }

        [Test()]
        public void simpleConstantRealEqual()
        {
            var cfb = GetConstantFoldingBuilder();
            var constant0 = cfb.ConstantReal("0.0");
            var constant1 = cfb.ConstantReal("0.0");
            var result = cfb.Lt(constant0, constant1);
            CheckIsBoolType(result);
            Assert.IsTrue(ExprUtil.IsFalse(result));
        }

        [Test()]
        public void simpleConstantRealLt()
        {
            var cfb = GetConstantFoldingBuilder();
            var constant0 = cfb.ConstantReal("0.0");
            var constant1 = cfb.ConstantReal("0.1");
            var result = cfb.Lt(constant0, constant1);
            CheckIsBoolType(result);
            Assert.IsTrue(ExprUtil.IsTrue(result));
        }

        [Test()]
        public void foldSameExpr()
        {
            var builderPair = GetSimpleAndConstantFoldingBuilder();
            var cfb = builderPair.Item2;
            var v0 = GetVarAndIdExpr("x", BasicType.Int);
            var side = cfb.Add(v0.Item2, v0.Item2);
            var foldedResult = cfb.Lt(side, side);
            CheckIsBoolType(foldedResult);
            Assert.IsTrue(ExprUtil.IsFalse(foldedResult));
        }

        [Test()]
        public void NoFold()
        {
            var builderPair = GetSimpleAndConstantFoldingBuilder();
            var sfb = builderPair.Item1;
            var cfb = builderPair.Item2;
            var v0 = GetVarAndIdExpr("x", BasicType.Int);
            var v1 = GetVarAndIdExpr("y", BasicType.Int);
            var foldedResult = cfb.Lt(v0.Item2, v1.Item2);
            var simpleResult = sfb.Lt(v0.Item2, v1.Item2);
            CheckIsBoolType(foldedResult);
            CheckIsBoolType(simpleResult);
            Assert.AreEqual(simpleResult, foldedResult);
        }
    }
}


text:
package internal

import (
	"encoding/json"
	"fmt"

	keychain "github.com/keybase/go-keychain"
	"github.com/ovh/cds/cli"
)

var keychainEnabled = true

//storeTokens store tokens into keychain
func storeTokens(contextName string, tokens ContextTokens) error {
	// delete existing value if present
	item := keychain.NewItem()
	item.SetSecClass(keychain.SecClassGenericPassword)
	item.SetService(contextName)
	item.SetAccount(contextName)
	keychain.DeleteItem(item) // nolint: errcheck

	// populate the rest of the object and save
	label := fmt.Sprintf("CDS-cdsctl/%s", contextName)
	item.SetLabel(label)

	b, err := json.Marshal(tokens)
	if err != nil {
		return cli.WrapError(err, "error while encoding tokens into keychain")
	}

	item.SetData(b)
	item.SetSynchronizable(keychain.SynchronizableNo)
	item.SetAccessible(keychain.AccessibleAccessibleAlwaysThisDeviceOnly)

	if err := keychain.AddItem(item); err != nil {
		return cli.WrapError(err, "error while add item '%s' into keychain", label)
	}
	return nil
}

//getTokens rerieves a CDS Context from keychain
func (c CDSContext) getTokens(contextName string) (*ContextTokens, error) {
	item := keychain.NewItem()
	item.SetSecClass(keychain.SecClassGenericPassword)
	item.SetService(contextName)
	item.SetAccount(contextName)
	item.SetMatchLimit(keychain.MatchLimitOne)
	item.SetReturnData(true)
	results, err := keychain.QueryItem(item)
	if err != nil {
		return nil, cli.WrapError(err, "error while retrieving context")
	}
	if len(results) != 1 {
		return nil, cli.NewError("context not found in keychain")
	}

	tokens := &ContextTokens{}
	if err := json.Unmarshal(results[0].Data, &tokens); err != nil {
		return nil, cli.WrapError(err, "error while unmarshal tokens from keychain")
	}
	return tokens, nil
}


text:
/*
 * File: filelib.cpp
 * -----------------
 * This file implements the filelib.h interface.  All platform dependencies
 * are managed through the platform interface.
 *
 * @version 2016/08/12
 * - added second overload of openFileDialog that accepts path parameter
 * @version 2015/07/05
 * - removed static global Platform variable, replaced by getPlatform as needed
 * - moved appendSpace function to simpio
 * @version 2015/04/12
 * - added promptUserForFile overload without stream parameter
 * @version 2014/10/19
 * - alphabetized function declarations
 * - converted many funcs to take const string& rather than string for efficiency
 * - added listDirectory overload that returns a Vector
 * @version 2014/10/08
 * - removed 'using namespace' statement
 */

#include "filelib.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "private/platform.h"
#include "simpio.h"
#include "strlib.h"
#include "vector.h"

/* Prototypes */

static void splitPath(const std::string& path, Vector<std::string> list);
static bool recursiveMatch(const std::string& str, int sx, const std::string& pattern, int px);

/* Implementations */

void createDirectory(const std::string& path) {
    return stanfordcpplib::getPlatform()->filelib_createDirectory(path);
}

void createDirectoryPath(const std::string& path) {
    size_t cp = 1;
    if (path == "") return;
    while ((cp = path.find('/', cp + 1)) != std::string::npos) {
        createDirectory(path.substr(0, cp - 1));
    }
    createDirectory(path);
}

std::string defaultExtension(const std::string& filename, const std::string& ext) {
    std::string extCopy = ext;
    bool force = (extCopy[0] == '*');
    if (force) extCopy = extCopy.substr(1);
    int dot = -1;
    int len = filename.length();
    for (int i = 0; i < len; i++) {
        char ch = filename[i];
        if (ch == '.') dot = i;
        if (ch == '/' || ch == '\\') dot = -1;
    }
    if (dot == -1) {
        force = true;
        dot = len;
    }
    if (force) {
        return filename.substr(0, dot) + extCopy;
    } else {
        return filename;
    }
}

void deleteFile(const std::string& filename) {
    remove(expandPathname(filename).c_str());
}

std::string expandPathname(const std::string& filename) {
    return stanfordcpplib::getPlatform()->filelib_expandPathname(filename);
}

bool fileExists(const std::string& filename) {
    return stanfordcpplib::getPlatform()->filelib_fileExists(filename);
}

std::string findOnPath(const std::string& path, const std::string& filename) {
    std::ifstream stream;
    std::string result = openOnPath(stream, path, filename);
    if (result != "") stream.close();
    return result;
}

std::string getCurrentDirectory() {
    return stanfordcpplib::getPlatform()->filelib_getCurrentDirectory();
}

std::string getDirectoryPathSeparator() {
    return stanfordcpplib::getPlatform()->filelib_getDirectoryPathSeparator();
}

std::string getExtension(const std::string& filename) {
    int dot = -1;
    int len = filename.length();
    for (int i = 0; i < len; i++) {
        char ch = filename[i];
        if (ch == '.') dot = i;
        if (ch == '/' || ch == '\\') dot = -1;
    }
    if (dot == -1) {
        return "";
    } else {
        return filename.substr(dot);
    }
}

std::string getHead(const std::string& filename) {
    size_t slash = std::string::npos;
    size_t len = filename.length();
    for (size_t i = 0; i < len; i++) {
        char ch = filename[i];
        if (ch == '/' || ch == '\\') slash = i;
    }
    if (slash == std::string::npos) {
        return "";
    } else if (slash == 0) {
        return "/";
    } else {
        return filename.substr(0, slash);
    }
}

std::string getRoot(const std::string& filename) {
    int dot = -1;
    int len = filename.length();
    for (int i = 0; i < len; i++) {
        char ch = filename[i];
        if (ch == '.') dot = i;
        if (ch == '/' || ch == '\\') dot = -1;
    }
    if (dot == -1) {
        return filename;
    } else {
        return filename.substr(0, dot);
    }
}

std::string getSearchPathSeparator() {
    return stanfordcpplib::getPlatform()->filelib_getSearchPathSeparator();
}

std::string getTail(const std::string& filename) {
    size_t slash = std::string::npos;
    size_t len = filename.length();
    for (size_t i = 0; i < len; i++) {
        char ch = filename[i];
        if (ch == '/' || ch == '\\') slash = i;
    }
    if (slash == std::string::npos) {
        return filename;
    } else {
        return filename.substr(slash + 1);
    }
}

std::string getTempDirectory() {
    return stanfordcpplib::getPlatform()->filelib_getTempDirectory();
}

bool isDirectory(const std::string& filename) {
    return stanfordcpplib::getPlatform()->filelib_isDirectory(filename);
}

bool isFile(const std::string& filename) {
    return stanfordcpplib::getPlatform()->filelib_isFile(filename);
}

bool isSymbolicLink(const std::string& filename) {
    return stanfordcpplib::getPlatform()->filelib_isSymbolicLink(filename);
}

void listDirectory(const std::string& path, Vector<std::string>& list) {
    std::vector<std::string> vec;
    listDirectory(path, vec);
    list.clear();
    for (std::string file : vec) {
        list.add(file);
    }
}

void listDirectory(const std::string& path, std::vector<std::string>& list) {
    return stanfordcpplib::getPlatform()->filelib_listDirectory(path, list);
}

Vector<std::string> listDirectory(const std::string& path) {
    std::vector<std::string> vec;
    listDirectory(path, vec);
    Vector<std::string> v(vec);
    return v;
}

bool matchFilenamePattern(const std::string& filename, const std::string& pattern) {
    return recursiveMatch(filename, 0, pattern, 0);
}

bool openFile(std::ifstream& stream, const std::string& filename) {
    stream.clear();
    stream.open(expandPathname(filename).c_str());
    return !stream.fail();
}

bool openFile(std::ofstream& stream, const std::string& filename) {
    stream.clear();
    stream.open(expandPathname(filename).c_str());
    return !stream.fail();
}

std::string openFileDialog(std::ifstream& stream) {
    return openFileDialog(stream, "Open File", "");
}

std::string openFileDialog(std::ifstream& stream,
                           const std::string& title) {
    return openFileDialog(stream, title, "");
}

std::string openFileDialog(std::ifstream& stream,
                           const std::string& title,
                           const std::string& path) {
    std::string filename = stanfordcpplib::getPlatform()->file_openFileDialog(title, "load", path);
    if (filename == "") return "";
    stream.open(filename.c_str());
    return (stream.fail()) ? "" : filename;
}

std::string openFileDialog(const std::string& title,
                           const std::string& path) {
    std::string filename = stanfordcpplib::getPlatform()->file_openFileDialog(title, "load", path);
    if (filename == "") return "";
    return (fileExists(filename)) ? filename : "";
}

std::string openFileDialog(std::ofstream& stream) {
    return openFileDialog(stream, "Open File", "");
}

std::string openFileDialog(std::ofstream& stream,
                           const std::string& title) {
    return openFileDialog(stream, title, "");
}

std::string openFileDialog(std::ofstream& stream,
                           const std::string& title,
                           const std::string& path) {
    std::string filename = stanfordcpplib::getPlatform()->file_openFileDialog(title, "save", path);
    if (filename == "") return "";
    stream.open(filename.c_str());
    return (stream.fail()) ? "" : filename;
}

std::string openOnPath(std::ifstream& stream,
                       const std::string& path,
                       const std::string& filename) {
    Vector<std::string> paths;
    splitPath(path, paths);
    for (std::string dir : paths) {
        std::string pathname = dir + "/" + filename;
        if (openFile(stream, pathname)) return pathname;
    }
    return "";
}

std::string openOnPath(std::ofstream& stream,
                       const std::string& path,
                       const std::string& filename) {
    Vector<std::string> paths;
    splitPath(path, paths);
    for (std::string dir : paths) {
        std::string pathname = dir + "/" + filename;
        if (openFile(stream, pathname)) return pathname;
    }
    return "";
}

std::string promptUserForFile(std::ifstream& stream,
                              const std::string& prompt,
                              const std::string& reprompt) {
    std::string promptCopy = prompt;
    std::string repromptCopy = reprompt;
    if (reprompt == "") {
        repromptCopy = "Unable to open that file.  Try again.";
    }
    appendSpace(promptCopy);
    while (true) {
        std::cout << promptCopy;
        std::string filename;
        getline(std::cin, filename);
        if (!filename.empty()) {
            openFile(stream, filename);
            if (!stream.fail()) return filename;
            stream.clear();
        }
        std::cout << repromptCopy << std::endl;
        if (promptCopy == "") promptCopy = "Input file: ";
    }
}

std::string promptUserForFile(std::ofstream& stream,
                              const std::string& prompt,
                              const std::string& reprompt) {
    std::string promptCopy = prompt;
    std::string repromptCopy = reprompt;
    if (reprompt == "") {
        repromptCopy = "Unable to open that file.  Try again.";
    }
    appendSpace(promptCopy);
    while (true) {
        std::cout << promptCopy;
        std::string filename;
        getline(std::cin, filename);
        if (!filename.empty()) {
            openFile(stream, filename);
            if (!stream.fail()) return filename;
            stream.clear();
        }
        std::cout << repromptCopy << std::endl;
        if (promptCopy == "") promptCopy = "Output file: ";
    }
}

std::string promptUserForFile(const std::string& prompt,
                              const std::string& reprompt) {
    std::string promptCopy = prompt;
    std::string repromptCopy = reprompt;
    if (reprompt == "") {
        repromptCopy = "Unable to open that file.  Try again.";
    }
    appendSpace(promptCopy);
    while (true) {
        std::cout << promptCopy;
        std::string filename;
        getline(std::cin, filename);
        if (!filename.empty()) {
            std::ifstream stream;
            openFile(stream, filename);
            if (!stream.fail()) {
                stream.close();
                return filename;
            }
        }
        std::cout << repromptCopy << std::endl;
        if (promptCopy == "") promptCopy = "Input file: ";
    }
}

void readEntireFile(std::istream& is, Vector<std::string>& lines) {
    lines.clear();
    while (true) {
        std::string line;
        getline(is, line);
        if (is.fail()) break;
        lines.add(line);
    }
}

void readEntireFile(std::istream& is, std::vector<std::string>& lines) {
    lines.clear();
    while (true) {
        std::string line;
        getline(is, line);
        if (is.fail()) break;
        lines.push_back(line);
    }
}

std::string readEntireFile(const std::string& filename) {
    std::string out;
    if (readEntireFile(filename, out)) {
        return out;
    } else {
        error(std::string("input file not found or cannot be opened: ") + filename);
        return "";
    }
}

bool readEntireFile(const std::string& filename, std::string& out) {
    std::ifstream input;
    input.open(filename.c_str());
    if (input.fail()) {
        return false;
    }
    std::ostringstream output;
    while (true) {
        int ch = input.get();
        if (input.fail()) break;
        output << (char) ch;
    }
    input.close();
    out = output.str();
    return true;
}

void renameFile(const std::string& oldname, const std::string& newname) {
    std::string oldExpand = expandPathname(oldname);
    std::string newExpand = expandPathname(newname);
    rename(oldExpand.c_str(), newExpand.c_str());
}

void rewindStream(std::istream& input) {
    input.clear();                  // removes any current eof/failure flags
    input.seekg(0, std::ios::beg);  // tells the stream to seek back to the beginning
}

void setCurrentDirectory(const std::string& path) {
    return stanfordcpplib::getPlatform()->filelib_setCurrentDirectory(path);
}

bool writeEntireFile(const std::string& filename,
                     const std::string& text,
                     bool append) {
    std::ofstream output;
    if (append) {
        output.open(filename.c_str(), std::ios_base::out | std::ios_base::app);
    } else {
        output.open(filename.c_str());
    }
    if (output.fail()) {
        return false;
    }
    output << text;
    output.close();
    return !output.fail();
}

/* Private functions */

static void splitPath(const std::string& path, Vector<std::string> list) {
    char sep = (path.find(';') == std::string::npos) ? ':' : ';';
    std::string pathCopy = path + sep;
    size_t start = 0;
    while (true) {
        size_t finish = pathCopy.find(sep, start);
        if (finish == std::string::npos) break;
        if (finish > start + 1) {
            list.add(pathCopy.substr(start, finish - start - 1));
        }
        start = finish + 1;
    }
}

static bool recursiveMatch(const std::string& str, int sx, const std::string& pattern, int px) {
    int slen = str.length();
    int plen = pattern.length();
    if (px == plen) return (sx == slen);
    char pch = pattern[px];
    if (pch == '*') {
        for (int i = sx; i <= slen; i++) {
            if (recursiveMatch(str, i, pattern, px + 1)) return true;
        }
        return false;
    }
    if (sx == slen) return false;
    char sch = str[sx];
    if (pch == '[') {
        bool match = false;
        bool invert = false;
        px++;
        if (px == plen) {
            error("matchFilenamePattern: missing ]");
        }
        if (pattern[px] == '^') {
            px++;
            invert = true;
        }
        while (px < plen && pattern[px] != ']') {
            if (px + 2 < plen && pattern[px + 1] == '-') {
                match |= (sch >= pattern[px] && sch <= pattern[px + 2]);
                px += 3;
            } else {
                match |= (sch == pattern[px]);
                px++;
            }
        }
        if (px == plen) {
            error("matchFilenamePattern: missing ]");
        }
        if (match == invert) return false;
    } else if (pch != '?') {
        if (pch != sch) return false;
    }
    return recursiveMatch(str, sx + 1, pattern, px + 1);
}


text:
//--------------------------------------
// utgb-core Project
//
// OSInfo.java
// Since: 2010/10/13
//
//--------------------------------------
package org.utgenome.util;

/**
 * Utilities for retrieving OS information
 *
 * @author leo
 *
 */
public class OSInfo {

	public static int availableProcessors() {
		return Runtime.getRuntime().availableProcessors();
	}

	public static long availaableFreeMemory() {
		return Runtime.getRuntime().freeMemory();
	}

}


text:
require_relative "shared_examples"

describe UnpackStrategy::Zip do
  let(:path) { TEST_FIXTURE_DIR/"cask/MyFancyApp.zip" }

  include_examples "UnpackStrategy::detect"

  context "when unzip is available", :needs_unzip do
    include_examples "#extract", children: ["MyFancyApp"]
  end

  context "when ZIP archive is corrupted" do
    let(:path) {
      (mktmpdir/"test.zip").tap do |path|
        FileUtils.touch path
      end
    }

    include_examples "UnpackStrategy::detect"
  end
end