text:
(function () {
  'use strict';

  angular.module('autoFocus', [])
    .directive('ngAutoFocus', function ($timeout) {
      return {
        link: function (scope, element, attrs) {
          scope.$watch(attrs.ngAutoFocus, function (value) {
            if (!value) {
              return;
            }

            $timeout(function () {
              element[0].focus();
            }, 100);
          });
        }
      };
    });
})();


text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.application;

import java.util.Map;

import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.client.api.TimelineClient;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;

public interface Application extends EventHandler<ApplicationEvent> {

  String getUser();

  Map<ContainerId, Container> getContainers();

  ApplicationId getAppId();

  ApplicationState getApplicationState();

  String getFlowName();

  String getFlowVersion();

  long getFlowRunId();

  TimelineClient getTimelineClient();

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace FnacApiClient\Service\Response;

use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;

use FnacApiClient\Entity\Carrier;

/**
 * BatchQueryResponse service base definition for batch query response
 *
 * @author     Fnac
 * @version    1.0.0
 */
class CarrierQueryResponse extends ResponseService
{
    private $carriers = array();

    /**
     * {@inheritdoc}
     */
    public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array())
    {
        parent::denormalize($denormalizer, $data, $format);

        $this->carriers = new \ArrayObject();
        foreach ($data['carrier'] as $carrier) {
            $carrObj = new Carrier();
            $carrObj->denormalize($denormalizer, $carrier, $format);
            $this->carriers[] = $carrObj;
        }
    }

    /**
     * Carrier list
     *
     * @see FnacApiClient\Entity\Carrier
     *
     * @return ArrayObject<Carrier>
     */
    public function getCarriers()
    {
        return $this->carriers;
    }
}


text:
<?php

namespace Dabble\Query;

use Dabble\Adapter;
use Dabble\Query;

class Insert extends Query
{
    protected $fields;

    /**
     * Insert a row into the database.
     *
     * @param Dabble\Adapter $adapter The adapter to use.
     * @param string $table The table to insert into.
     * @param array $fields Array of Field => value pairs to insert.
     * @return mixed The last inserted serial, or 0 or true if none found.
     * @throws Dabble\Query\InsertException if no rows were inserted.
     * @throws Dabble\Query\SqlException on error.
     */
    public function __construct(Adapter $adapter, $table, array $fields)
    {
        parent::__construct($adapter, $table);
        $use = [];
        foreach ($fields as $name => $field) {
            if (is_null($field)) {
                continue;
            }
            $use[$name] = $field;
        }
        if (!$use) {
            throw new InsertException(
                "No fields to bind; did you pass only NULL values?"
            );
        }
        $this->fields = $this->prepareBindings($use);
    }

    public function execute()
    {
        $stmt = parent::execute();
        if ($affectedRows = $stmt->rowCount() and $affectedRows) {
            return $affectedRows;
        }
        $info = $stmt->errorInfo();
        $msg = "{$info[0]} / {$info[1]}: {$info[2]} - $this";
        throw new InsertException($this->error($msg, $this->bound));
    }

    public function __toString()
    {
        return sprintf(
            "INSERT INTO %s (%s) VALUES (%s)",
            $this->table,
            str_replace("'", '', implode(', ', array_keys($this->fields))),
            implode(', ', $this->fields)
        );
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Jiying's Web</title>

    <base href="https://jiyingqi.github.io/">

    <link rel='shortcut icon' type='image/x-icon' href='img/Flavicon.png'/>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link href="css/clean-blog.min.css" rel="stylesheet">

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

              Home

              About

Aaron Gu

              Leader, Laughy, Turtle

Hey Aaron,

We really didn't talk to each other until what??!? Like Laffey shaft lmao

That was so rough, but the people in the class were pretty cool

I remember thinking that there was a thing between you and Emily and you were like "hell naw we ain't like that"

Well look at what happened smh you're so fake

You literally lied to me

But i'm glad that you are happy now and I wish you luck on your long distance relationship

Also you really do look like a turtle lmao i'm sorry but its so funny

Anyways, sorry for making fun of you when this is supposed to be a farewell message

I hope you have a great time in college and hey you are a cool dude

Copyright © Jiying 2017


text:
package org.apache.flink.runtime.taskexecutor;

import org.apache.flink.api.common.JobID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.execution.librarycache.LibraryCacheManager;
import org.apache.flink.runtime.io.network.netty.PartitionProducerStateChecker;
import org.apache.flink.runtime.io.network.partition.ResultPartitionConsumableNotifier;
import org.apache.flink.runtime.jobmaster.JobMasterGateway;
import org.apache.flink.runtime.jobmaster.JobMasterId;
import org.apache.flink.runtime.taskmanager.CheckpointResponder;
import org.apache.flink.runtime.taskmanager.TaskManagerActions;
import org.apache.flink.util.Preconditions;

/**
 * Container class for JobManager specific communication utils used by the {@link TaskExecutor}.
 */
public class JobManagerConnection {

	// Job id related with the job manager
	private final JobID jobID;

	// The unique id used for identifying the job manager
	private final ResourceID resourceID;

	// Gateway to the job master
	private final JobMasterGateway jobMasterGateway;

	// Task manager actions with respect to the connected job manager
	private final TaskManagerActions taskManagerActions;

	// Checkpoint responder for the specific job manager
	private final CheckpointResponder checkpointResponder;

	// GlobalAggregateManager interface to job manager
	private final GlobalAggregateManager aggregateManager;

	// Library cache manager connected to the specific job manager
	private final LibraryCacheManager libraryCacheManager;

	// Result partition consumable notifier for the specific job manager
	private final ResultPartitionConsumableNotifier resultPartitionConsumableNotifier;

	// Partition state checker for the specific job manager
	private final PartitionProducerStateChecker partitionStateChecker;

	public JobManagerConnection(
				JobID jobID,
				ResourceID resourceID,
				JobMasterGateway jobMasterGateway,
				TaskManagerActions taskManagerActions,
				CheckpointResponder checkpointResponder,
				GlobalAggregateManager aggregateManager,
				LibraryCacheManager libraryCacheManager,
				ResultPartitionConsumableNotifier resultPartitionConsumableNotifier,
				PartitionProducerStateChecker partitionStateChecker) {
		this.jobID = Preconditions.checkNotNull(jobID);
		this.resourceID = Preconditions.checkNotNull(resourceID);
		this.jobMasterGateway = Preconditions.checkNotNull(jobMasterGateway);
		this.taskManagerActions = Preconditions.checkNotNull(taskManagerActions);
		this.checkpointResponder = Preconditions.checkNotNull(checkpointResponder);
		this.aggregateManager = Preconditions.checkNotNull(aggregateManager);
		this.libraryCacheManager = Preconditions.checkNotNull(libraryCacheManager);
		this.resultPartitionConsumableNotifier = Preconditions.checkNotNull(resultPartitionConsumableNotifier);
		this.partitionStateChecker = Preconditions.checkNotNull(partitionStateChecker);
	}

	public JobID getJobID() {
		return jobID;
	}

	public ResourceID getResourceID() {
		return resourceID;
	}

	public JobMasterId getJobMasterId() {
		return jobMasterGateway.getFencingToken();
	}

	public JobMasterGateway getJobManagerGateway() {
		return jobMasterGateway;
	}

	public TaskManagerActions getTaskManagerActions() {
		return taskManagerActions;
	}

	public CheckpointResponder getCheckpointResponder() {
		return checkpointResponder;
	}

	public GlobalAggregateManager getGlobalAggregateManager() {
		return aggregateManager;
	}

	public LibraryCacheManager getLibraryCacheManager() {
		return libraryCacheManager;
	}

	public ResultPartitionConsumableNotifier getResultPartitionConsumableNotifier() {
		return resultPartitionConsumableNotifier;
	}

	public PartitionProducerStateChecker getPartitionStateChecker() {
		return partitionStateChecker;
	}
}


text:
<?php

namespace Phlexible\Bundle\GuiBundle\Tests\Asset;

use org\bovigo\vfs\vfsStream;
use Phlexible\Bundle\GuiBundle\Asset\TranslationsBuilder;
use Phlexible\Component\Bundler\Asset\Asset;
use Phlexible\Component\Bundler\Compressor\CompressorInterface;
use Phlexible\Component\Bundler\Translation\TranslationBuilderInterface;
use Phlexible\Component\Bundler\Translation\TranslationExtractorInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\TranslatorBagInterface;

/**
 * @covers \Phlexible\Bundle\GuiBundle\Asset\TranslationsBuilder
 */
class TranslationsBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testBuild()
    {
        $root = vfsStream::setup();

        $messageCatalog = new MessageCatalogue('de', array());

        $translator = $this->prophesize(TranslatorBagInterface::class);
        $translator->getCatalogue('de')->willReturn($messageCatalog);

        $extractor = $this->prophesize(TranslationExtractorInterface::class);
        $extractor->extract($messageCatalog, 'testDomain')->willReturn(array());

        $builder = $this->prophesize(TranslationBuilderInterface::class);

        $compressor = $this->prophesize(CompressorInterface::class);
        $compressor->compressFile(vfsStream::path('/root/translations-de.js'));

        $builder = new TranslationsBuilder($translator->reveal(), $extractor->reveal(), $builder->reveal(), $compressor->reveal(), $root->url(), 'de', false);

        $result = $builder->build('de', 'testDomain');

        $this->assertEquals(new Asset('vfs://root/translations-de.js'), $result);
    }
}


text:
package rottentomatoes

import (
	"fmt"
	"net/url"

	"github.com/zquestz/s/providers"
)

func init() {
	providers.AddProvider("rottentomatoes", &Provider{})
}

// Provider merely implements the Provider interface.
type Provider struct{}

// BuildURI generates a search URL for RottenTomatoes.
func (p *Provider) BuildURI(q string) string {
	return fmt.Sprintf("http://www.rottentomatoes.com/search/?search=%s", url.QueryEscape(q))
}

// Tags returns the tags relevant to this provider.
func (p *Provider) Tags() []string {
	return []string{"movies"}
}


text:
<?php
namespace LaravelRocket\Generator\Objects;

use function ICanBoogie\singularize;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use LaravelRocket\Generator\Helpers\StringHelper;

class Relation
{
    protected $uneditables = ['passwordResets', 'notifications'];
    protected $unlistables = ['passwordResets', 'notifications'];
    protected $unshowables = ['passwordResets', 'notifications'];

    protected $name = '';
    protected $type = '';

    /**
     * @var null|\TakaakiMizuno\MWBParser\Elements\Column
     */
    protected $column = null;
    /**
     * @var null|\TakaakiMizuno\MWBParser\Elements\Column
     */
    protected $referenceColumn = null;

    protected $tableName             = '';
    protected $referenceTableName    = '';
    protected $intermediateTableName = '';

    /**
     * @var string
     */
    protected $editFieldType = 'string';

    /**
     * @var array
     */
    protected $editFieldOptions = [];

    /**
     * @var \LaravelRocket\Generator\Objects\Definitions|null
     */
    protected $json = null;

    const TYPE_BELONGS_TO      = 'belongsTo';
    const TYPE_HAS_MANY        = 'hasMany';
    const TYPE_HAS_ONE         = 'hasOne';
    const TYPE_BELONGS_TO_MANY = 'belongsToMany';

    const EDIT_TYPE_CHECKBOX      = 'checkbox';
    const EDIT_TYPE_RADIO_BUTTON  = 'radio_button';
    const EDIT_TYPE_SELECT_SINGLE = 'select_single';
    const EDIT_TYPE_SELECT_MULTI  = 'select_multi';
    const EDIT_TYPE_IMAGE         = 'image';
    const EDIT_TYPE_FILE          = 'file';

    /**
     * Relation constructor.
     *
     * @param string                                   $type
     * @param string                                   $tableName
     * @param \TakaakiMizuno\MWBParser\Elements\Column $column
     * @param string                                   $referenceTableName
     * @param \TakaakiMizuno\MWBParser\Elements\Column $referenceColumn
     * @param string                                   $intermediateTableName
     */
    public function __construct($type, $tableName, $column, $referenceTableName, $referenceColumn, $json, $intermediateTableName = '')
    {
        $this->type                  = $type;
        $this->tableName             = $tableName;
        $this->column                = $column;
        $this->referenceTableName    = $referenceTableName;
        $this->referenceColumn       = $referenceColumn;
        $this->intermediateTableName = $intermediateTableName;
        $this->json                  = $json;

        $this->setName();
        $this->editFieldType = $this->detectEditType();
    }

    protected function setName()
    {
        switch ($this->type) {
            case self::TYPE_BELONGS_TO:
                $this->name = Str::camel(preg_replace('/_id$/', '', $this->column->getName()));

                return;
            case self::TYPE_HAS_MANY:
                $this->name = Str::camel($this->referenceTableName);

                return;
            case self::TYPE_HAS_ONE:
                $this->name = Str::camel(singularize($this->referenceTableName));

                return;
            case self::TYPE_BELONGS_TO_MANY:
                $this->name = Str::camel($this->referenceTableName);

                return;
        }

        $this->name = Str::camel($this->referenceTableName);
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getTableName(): string
    {
        return $this->tableName;
    }

    /**
     * @return string
     */
    public function getReferenceTableName(): string
    {
        return $this->referenceTableName;
    }

    /**
     * @return string
     */
    public function getDisplayName(): string
    {
        return Str::title(str_replace('_', ' ', Str::snake($this->getName())));
    }

    /**
     * @return null|\TakaakiMizuno\MWBParser\Elements\Column
     */
    public function getColumn()
    {
        return $this->column;
    }

    /**
     * @return null|\TakaakiMizuno\MWBParser\Elements\Column
     */
    public function getReferenceColumn()
    {
        return $this->referenceColumn;
    }

    /**
     * @return bool
     */
    public function isRoles(): bool
    {
        return $this->getType() === self::TYPE_HAS_MANY && StringHelper::hasPostFix($this->getName(), 'roles');
    }

    /**
     * @return bool
     */
    public function isTypes(): bool
    {
        return $this->getType() === self::TYPE_HAS_MANY && StringHelper::hasPostFix($this->getName(), 'types');
    }

    /**
     * @return bool
     */
    public function isStatues(): bool
    {
        return $this->getType() === self::TYPE_HAS_MANY && StringHelper::hasPostFix($this->getName(), 'statuses');
    }

    /**
     * @return bool
     */
    public function isEditable(): bool
    {
        if (StringHelper::hasPostFix($this->getName(), $this->uneditables)) {
            return false;
        }

        if ($this->getType() === self::TYPE_BELONGS_TO) {
            return false;
        }

        return $this->isRoles() || $this->isTypes();
    }

    /**
     * @return bool
     */
    public function isListable(): bool
    {
        return !StringHelper::hasPostFix($this->getName(), $this->unlistables)
            && ($this->getType() === self::TYPE_BELONGS_TO || $this->isRoles() || $this->isTypes());
    }

    /**
     * @return bool
     */
    public function isShowable(): bool
    {
        return !StringHelper::hasPostFix($this->getName(), $this->unshowables)
            && ($this->getType() === self::TYPE_BELONGS_TO || $this->isRoles() || $this->isTypes());
    }

    /**
     * @return bool
     */
    public function shouldIncludeInAPI(): bool
    {
        if (StringHelper::hasPostFix($this->getName(), $this->unshowables)) {
            return false;
        }

        return $this->isEditable() || $this->isShowable() || $this->isListable();
    }

    /**
     * @return bool
     */
    public function isImage(): bool
    {
        return StringHelper::hasPostFix($this->getName(), 'image');
    }

    /**
     * @return bool
     */
    public function isFile(): bool
    {
        return StringHelper::hasPostFix($this->getName(), ['file', 'image']);
    }

    /**
     * @return string
     */
    public function getViewName(): string
    {
        return Str::title(str_replace('_', ' ', Str::snake($this->name)));
    }

    /**
     * @return string
     */
    public function getReferenceModel(): string
    {
        return ucfirst(Str::camel(singularize($this->referenceTableName)));
    }

    /**
     * @return string
     */
    public function getIntermediateTableName(): string
    {
        return $this->intermediateTableName;
    }

    /**
     * @return string
     */
    public function getIntermediateTableModel(): string
    {
        return ucfirst(Str::camel(singularize($this->intermediateTableName)));
    }

    /**
     * @return bool
     */
    public function isMultipleSelection(): bool
    {
        return $this->type === self::TYPE_HAS_MANY || $this->type === self::TYPE_BELONGS_TO_MANY;
    }

    /**
     * @return string
     */
    public function getEditFieldType(): string
    {
        return $this->editFieldType;
    }

    /**
     * @return array
     */
    public function getEditFieldOptions(): array
    {
        return $this->editFieldOptions;
    }

    /**
     * @return string
     */
    public function detectEditType(): string
    {
        if ($this->isMultipleSelection()) {
            if (StringHelper::hasPostFix($this->name, 'type') || StringHelper::hasPostFix($this->name, 'role')
                || StringHelper::hasPostFix($this->name, 'types') || StringHelper::hasPostFix($this->name, 'roles')) {
                return self::EDIT_TYPE_CHECKBOX;
            }

            return self::EDIT_TYPE_SELECT_MULTI;
        }

        if (Str::endsWith($this->name, '_type') || Str::endsWith($this->name, 'role')) {
            return self::EDIT_TYPE_RADIO_BUTTON;
        }

        if ($this->isImage()) {
            return self::EDIT_TYPE_IMAGE;
        }

        if ($this->isFile()) {
            return self::EDIT_TYPE_FILE;
        }

        return self::EDIT_TYPE_SELECT_SINGLE;
    }

    /**
     * @return string
     */
    public function getAPIName(): string
    {
        return Str::camel($this->getName());
    }

    /**
     * @return string
     */
    public function getQueryName(): string
    {
        return Str::snake($this->getName());
    }

    /**
     * @return string
     */
    public function getPresentation(): string
    {
        if ($this->isTypes() || $this->isRoles() || $this->isStatues()) {
            return 'badge';
        }

        return 'normal';
    }

    /**
     * @return string
     */
    public function getInterestedColumnName(): string
    {
        if ($this->isRoles()) {
            return 'role';
        }

        if ($this->isTypes()) {
            return 'type';
        }

        return 'id';
    }

    /**
     * @return array
     */
    public function getInterestedColumnOptions(): array
    {
        if (empty($this->json)) {
            return [];
        }
        $definition = $this->json->getColumnDefinition($this->getReferenceTableName(), $this->getInterestedColumnName());

        $type    = Arr::get($definition, 'type');
        $options = Arr::get($definition, 'options', []);
        if ($type === 'type' && is_array($options) && count($options) > 0) {
            return $options;
        }

        return [];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tab.Slack.Common.Model;
using Tab.Slack.Common.Model.Requests;
using Tab.Slack.Common.Model.Responses;

namespace Tab.Slack.WebApi
{
    public class ApiApi : IApiApi
    {
        private readonly IRequestHandler request;

        public ApiApi(IRequestHandler requestHandler)
        {
            if (requestHandler == null)
                throw new ArgumentNullException(nameof(requestHandler));

            this.request = requestHandler;
        }

        public ApiTestResponse Test(string error = null, params string[] args)
        {
            var queryParams = new List<string>();

            if (error != null)
                queryParams.Add($"error={Uri.EscapeDataString(error)}");

            int argIndex = 1;

            foreach (var arg in args ?? Enumerable.Empty<string>())
            {
                queryParams.Add($"arg{argIndex++}={Uri.EscapeDataString(arg)}");
            }

            var request = "/api.test?" + string.Join("&", queryParams);

            var response = this.request.ExecuteAndDeserializeRequest<ApiTestResponse>(request);

            return response;
        }
    }
}


text:
/* Webfont: Overpass-ExtraLightItalic */@font-face {
    font-family: 'Overpass';
    src: url('Overpass-ExtraLightItalic.eot'); /* IE9 Compat Modes */
    src: url('Overpass-ExtraLightItalic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('Overpass-ExtraLightItalic.woff') format('woff'), /* Modern Browsers */
         url('Overpass-ExtraLightItalic.ttf') format('truetype'), /* Safari, Android, iOS */
         url('Overpass-ExtraLightItalic.svg#Overpass-ExtraLightItalic') format('svg'); /* Legacy iOS */
    font-style: italic;
    font-weight: normal;
    text-rendering: optimizeLegibility;
}


text:
using System;

namespace LinqExtender
{
    /// <summary>
    /// Custom extender expection class.
    /// </summary>
    public class ProviderException : Exception
    {
        /// <summary>
        /// Parametrized constructor for the expection.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public ProviderException(string message, Exception ex) : base(message, ex) { }
        /// <summary>
        /// Defautl constructor for the expection.
        /// </summary>
        /// <param name="message"></param>
        public ProviderException(string message) : base(message) { }
    }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */

$installer->startSetup();

$defaultValue = 'container2';

$installer->addAttribute('catalog_product', 'options_container', array(
    'group'             => 'Design',
    'type'              => 'varchar',
    'backend'           => '',
    'frontend'          => '',
    'label'             => 'Display Product Options In',
    'input'             => 'select',
    'class'             => '',
    'source'            => 'catalog/entity_product_attribute_design_options_container',
    'global'            => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'           => true,
    'required'          => false,
    'user_defined'      => false,
    'default'           => $defaultValue,
    'searchable'        => false,
    'filterable'        => false,
    'comparable'        => false,
    'visible_on_front'  => false,
    'visible_in_advanced_search' => false,
    'unique'            => false,
    )
);

$newAttributeId = $installer->getAttributeId('catalog_product', 'options_container');

$installer->run("
INSERT INTO {$this->getTable('catalog_product_entity_varchar')}
    (entity_id, entity_type_id, attribute_id, value)
    SELECT entity_id, entity_type_id, {$newAttributeId}, '{$defaultValue}'
    FROM {$this->getTable('catalog_product_entity')}
");

$installer->endSetup();


text:
> A super-small (505 B gzipped), non-dependent JavaScript framework that allows you to slice up your HTML in separate files.

## Install

**Bower**
```bash
$ bower install amputee
```

**npm**
```bash
$ npm install amputee
```

## Usage

```html
<html>
  <head>
    <title>amputee</title>
    <meta charset="UTF-8">
  <body>

    <amputee src="hello.html"></amputee>

    <script src="amputee.js"></script>
```

**hello.html**

```html
<h1>Hello World</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit…</p>
```

## Examples

You can't run the examples via the `file://` protocol so you have run it with a server. In this example we are using `serve`.

Go to [http://localhost:3000/examples](http://localhost:3000/examples).

```
npm install -g serve
serve .
```

## Contribute

See the [contributing guide](CONTRIBUTING.md)

### Licence

[MIT](licence) © Johnie Hjelm


text:
package io.getlime.security.powerauth.crypto.lib.model;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Class representing recovery code seed information.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
public class RecoverySeed {

    private byte[] nonce;
    private Map<Integer, Long> pukDerivationIndexes = new LinkedHashMap<>();

    /**
     * Default constructor.
     */
    public RecoverySeed() {
    }

    /**
     * Constructor with nonce bytes and PUK derivation indexes.
     * @param nonce Nonce.
     * @param pukDerivationIndexes PUK derivation indexes.
     */
    public RecoverySeed(byte[] nonce, Map<Integer, Long> pukDerivationIndexes) {
        this.nonce = nonce;
        this.pukDerivationIndexes = new LinkedHashMap<>(pukDerivationIndexes);
    }

    /**
     * Get nonce bytes.
     * @return Nonce bytes.
     */
    public byte[] getNonce() {
        return nonce;
    }

    /**
     * Set nonce bytes.
     * @param nonce Nonce bytes.
     */
    public void setNonce(byte[] nonce) {
        this.nonce = nonce;
    }

    /**
     * Get PUK derivation indexes.
     * @return PUK derivation indexes.
     */
    public Map<Integer, Long> getPukDerivationIndexes() {
        return new LinkedHashMap<>(pukDerivationIndexes);
    }

    /**
     * Set PUK derivation indexes.
     * @param pukDerivationIndexes PUK derivation indexes.
     */
    public void setPukDerivationIndexes(Map<Integer, Long> pukDerivationIndexes) {
        this.pukDerivationIndexes = new LinkedHashMap<>(pukDerivationIndexes);
    }
}


text:
// Karma configuration
// Generated on Thu Jan 29 2015 17:17:36 GMT+0100 (CET)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      '../app/libs/angular.min.js',
      'libs/angular-mocks.js',
      '../app/*.js',
      '../app/**/*.js',
      '**/*-test.js',
      'mocks/mocks.js'
    ],

    // list of files to exclude
    exclude: [
      '../app/libs/jquery.min.js',
      '../app/libs/bootstrap.min.js',
      '../app/libs/metisMenu.min.js',
      '../app/libs/sb-admin-2.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};


text:
hpc-coveralls-testing-sandbox
=============================

[![Build Status](https://travis-ci.org/guillaume-nargeot/hpc-coveralls-testing-sandbox.png?branch=master)](https://travis-ci.org/guillaume-nargeot/hpc-coveralls-testing-sandbox) [![Coverage Status](https://coveralls.io/repos/guillaume-nargeot/hpc-coveralls-sandbox/badge.png?branch=master)](https://coveralls.io/r/guillaume-nargeot/hpc-coveralls-testing-sandbox?branch=master)

Project used to test hpc-coveralls with Travis CI and Coveralls, with hpc-coveralls installed in a sandbox


text:
$(function() {
    $("#track-btn").click(function() {
        updateAlertMsg('Fetching results...');
        $("#output").children("tbody").remove(); // remove existing results
        var isOneWay = $("#ed").val().trim().length === 0;

        $.ajax({
            url: '/fetchPriceTable',
            method: 'post',
            data: $("form").serialize(),
            success: function(data) {
                var priceTable = data.table;
                for (var itrip in priceTable) {
                    var tr = $("<tr />");
                    var srcDest = $("<td />").text(priceTable[itrip].source + '-' + priceTable[itrip].destination);
                    var startDateTime = $("<td />").text(getFormattedDateTime(priceTable[itrip].sd));
                    var endDateTime = $("<td />").text(getFormattedDateTime(priceTable[itrip].ed));
                    var price = $("<td />").text(priceTable[itrip].price);
                    var toduration = $("<td />").text(priceTable[itrip].toduration);
                    var froduration = $("<td />").text(priceTable[itrip].froduration);
                    var airlines = $("<td />").text(priceTable[itrip].airlines);

                    var source = priceTable[itrip].source;
                    var destination = priceTable[itrip].destination;
                    var startDate = priceTable[itrip].sd.split('T')[0];
                    var endDate = priceTable[itrip].ed.split('T')[0];

                    var href = 'https://www.studentuniverse.com/flights/1/' + source + '/' + destination + '/' + startDate;
                    if (!isOneWay) {
                        href += '/' + destination + '/' + source + '/' + endDate;
                    }
                    var link = $("<td />").html(
                        $('<div />').addClass('truncate').html(
                            $("<a />").attr({
                                href: href,
                                target: '_blank'
                            }).text(href)));

                    $(tr).append(srcDest).append(startDateTime).append(endDateTime).append(price)
                        .append(toduration).append(froduration).append(airlines).append(link);
                    $("#output").append(tr);
                }
                updateAlertMsg('Completed!');
            },
            error: function(data) {
                updateAlertMsg('ERROR: ' + JSON.stringify(data));
            }
        })
    });

    var es = new EventSource("/progress");
    var listener = function(event) {
        var type = event.type;
        if (event.type == "message")
            updateAlertMsg((event.data * 100).toFixed(2) + "% done");
    };
    es.addEventListener("open", listener);
    es.addEventListener("message", listener);
    es.addEventListener("error", listener);

    function updateAlertMsg(message) {
        $("#alert-msg").html(message);
    }

    /**
     * Returns user friendly date time format for a given ISO date time
     * Returns the same value if invalid date is passed
     * @param  {string} dateTime datetime string in ISO format
     * @return {string}          user friendly date and time format
     */
    function getFormattedDateTime(dateTime) {
        if (isNaN(Date.parse(dateTime)))
            return dateTime;
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        var d = new Date(dateTime);
        return months[d.getMonth()] + '' + d.getDate() + ', ' + d.getFullYear() +
            ' at ' + d.getHours() + ':' + d.getMinutes() + ' hrs'
    }
});


text:
using System.Collections.Generic;

namespace ShogunLib.CommandLine.Commands.Parameters.ArgumentValidation
{
    /// <summary>
    /// Provides functionality for console command arguments validation.
    /// </summary>
    public interface IArgumentValidator
    {
        /// <summary>
        /// Gets the error validation message if validation is failed.
        /// </summary>
        string ErrorMessage { get; }

        /// <summary>
        /// Validate console command arguments.
        /// </summary>
        /// <param name="args">Input arguments.</param>
        /// <returns>true - validation succeeded; false - fail.</returns>
        bool Validate(IEnumerable<string> args);
    }
}


text:
"""
    This program executes AeroDyn and a regression test for a single test case.
    The test data is contained in a git submodule, r-test, which must be initialized
    prior to running. See the r-test README or OpenFAST documentation for more info.

    Get usage with: `executeAerodynRegressionCase.py -h`
"""

import os
import sys
basepath = os.path.sep.join(sys.argv[0].split(os.path.sep)[:-1]) if os.path.sep in sys.argv[0] else "."
sys.path.insert(0, os.path.sep.join([basepath, "lib"]))
import argparse
import shutil
import glob
import subprocess
import rtestlib as rtl
import openfastDrivers
import pass_fail
from errorPlotting import exportCaseSummary

##### Main program

### Store the python executable for future python calls
pythonCommand = sys.executable

### Verify input arguments
parser = argparse.ArgumentParser(description="Executes OpenFAST and a regression test for a single test case.")
parser.add_argument("caseName", metavar="Case-Name", type=str, nargs=1, help="The name of the test case.")
parser.add_argument("executable", metavar="AeroDyn-Driver", type=str, nargs=1, help="The path to the AeroDyn driver executable.")
parser.add_argument("sourceDirectory", metavar="path/to/openfast_repo", type=str, nargs=1, help="The path to the OpenFAST repository.")
parser.add_argument("buildDirectory", metavar="path/to/openfast_repo/build", type=str, nargs=1, help="The path to the OpenFAST repository build directory.")
parser.add_argument("tolerance", metavar="Test-Tolerance", type=float, nargs=1, help="Tolerance defining pass or failure in the regression test.")
parser.add_argument("systemName", metavar="System-Name", type=str, nargs=1, help="The current system\'s name: [Darwin,Linux,Windows]")
parser.add_argument("compilerId", metavar="Compiler-Id", type=str, nargs=1, help="The compiler\'s id: [Intel,GNU]")
parser.add_argument("-p", "-plot", dest="plot", action='store_true', help="bool to include plots in failed cases")
parser.add_argument("-n", "-no-exec", dest="noExec", action='store_true', help="bool to prevent execution of the test cases")
parser.add_argument("-v", "-verbose", dest="verbose", action='store_true', help="bool to include verbose system output")

args = parser.parse_args()

caseName = args.caseName[0]
executable = args.executable[0]
sourceDirectory = args.sourceDirectory[0]
buildDirectory = args.buildDirectory[0]
tolerance = args.tolerance[0]
plotError = args.plot if args.plot is False else True
noExec = args.noExec if args.noExec is False else True
verbose = args.verbose if args.verbose is False else True

# validate inputs
rtl.validateExeOrExit(executable)
rtl.validateDirOrExit(sourceDirectory)
if not os.path.isdir(buildDirectory):
    os.makedirs(buildDirectory)

### Build the filesystem navigation variables for running the test case
regtests = os.path.join(sourceDirectory, "reg_tests")
lib = os.path.join(regtests, "lib")
rtest = os.path.join(regtests, "r-test")
moduleDirectory = os.path.join(rtest, "modules", "aerodyn")
inputsDirectory = os.path.join(moduleDirectory, caseName)
targetOutputDirectory = os.path.join(inputsDirectory)
testBuildDirectory = os.path.join(buildDirectory, caseName)

# verify all the required directories exist
if not os.path.isdir(rtest):
    rtl.exitWithError("The test data directory, {}, does not exist. If you haven't already, run `git submodule update --init --recursive`".format(rtest))
if not os.path.isdir(targetOutputDirectory):
    rtl.exitWithError("The test data outputs directory, {}, does not exist. Try running `git submodule update`".format(targetOutputDirectory))
if not os.path.isdir(inputsDirectory):
    rtl.exitWithError("The test data inputs directory, {}, does not exist. Verify your local repository is up to date.".format(inputsDirectory))

# create the local output directory if it does not already exist
# and initialize it with input files for all test cases
if not os.path.isdir(testBuildDirectory):
    os.makedirs(testBuildDirectory)
    for file in glob.glob(os.path.join(inputsDirectory,"ad_*inp")):
        filename = file.split(os.path.sep)[-1]
        shutil.copy(os.path.join(inputsDirectory,filename), os.path.join(testBuildDirectory,filename))

### Run aerodyn on the test case
if not noExec:
    caseInputFile = os.path.join(testBuildDirectory, "ad_driver.inp")
    returnCode = openfastDrivers.runAerodynDriverCase(caseInputFile, executable)
    if returnCode != 0:
        rtl.exitWithError("")

### Build the filesystem navigation variables for running the regression test
localOutFile = os.path.join(testBuildDirectory, "ad_driver.out")
baselineOutFile = os.path.join(targetOutputDirectory, "ad_driver.out")
rtl.validateFileOrExit(localOutFile)
rtl.validateFileOrExit(baselineOutFile)

testData, testInfo, testPack = pass_fail.readFASTOut(localOutFile)
baselineData, baselineInfo, _ = pass_fail.readFASTOut(baselineOutFile)
performance = pass_fail.calculateNorms(testData, baselineData)
normalizedNorm = performance[:, 1]

# export all case summaries
results = list(zip(testInfo["attribute_names"], [*performance]))
results_max = performance.max(axis=0)
exportCaseSummary(testBuildDirectory, caseName, results, results_max, tolerance)

# failing case
if not pass_fail.passRegressionTest(normalizedNorm, tolerance):
    if plotError:
        from errorPlotting import finalizePlotDirectory, plotOpenfastError
        ixFailChannels = [i for i in range(len(testInfo["attribute_names"])) if normalizedNorm[i] > tolerance]
        failChannels = [channel for i, channel in enumerate(testInfo["attribute_names"]) if i in ixFailChannels]
        failResults = [res for i, res in enumerate(results) if i in ixFailChannels]
        for channel in failChannels:
            try:
                plotOpenfastError(localOutFile, baselineOutFile, channel)
            except:
                error = sys.exc_info()[1]
                print("Error generating plots: {}".format(error.msg))
        finalizePlotDirectory(localOutFile, failChannels, caseName)
    sys.exit(1)

# passing case
sys.exit(0)


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

class home extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // if ($this->session->userdata('SESS_GURU_IS_LOGIN') === TRUE) {
        //     $path = ($this->session->userdata('SESS_GURU_IS_LOGIN') === TRUE) ? 'guru/home' : 'staf_admin/home';
        //     redirect($path);
        // }

            $this->output->set_header('Last-Modified:'.gmdate('D,d M Y H:i:s').'GMT');
            $this->output->set_header('Cache-Control:no-store, no-cache, must-revalidate');
            $this->output->set_header('Cache-Control:post-check=0,pre-check=0',false);
            $this->output->set_header('Pragma: no-cache');

    }

    public function index()
    {
        $this->load->view('global_home/header_global_home');
        $this->load->view('v_home');
        $this->load->view('global_home/footer_global_home');

    }
}


text:
package com.realizationtime.btdogg.utils

import scala.concurrent.duration.FiniteDuration

object TimeUtils {

  implicit def asFiniteDuration(d: java.time.Duration): FiniteDuration =
    scala.concurrent.duration.Duration.fromNanos(d.toNanos)

}


text:
[![CI Status](http://img.shields.io/travis/timbodeit/SwiftPipes.svg?style=flat)](https://travis-ci.org/timbodeit/SwiftPipes)
[![Version](https://img.shields.io/cocoapods/v/SwiftPipes.svg?style=flat)](http://cocoapods.org/pods/SwiftPipes)
[![License](https://img.shields.io/cocoapods/l/SwiftPipes.svg?style=flat)](http://cocoapods.org/pods/SwiftPipes)
[![Platform](https://img.shields.io/cocoapods/p/SwiftPipes.svg?style=flat)](http://cocoapods.org/pods/SwiftPipes)

Essential components for the functional Swift programmer.
Pipes, currying, function composition.

## Requirements

This version of SwiftPipes is meant to be used with Swift 3.0

## Installation

SwiftPipes is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "SwiftPipes"
```

## Author

Tim Bodeit, tim@bodeit.com

SwiftPipes is inspired by:

- The [pipe-forward](https://gist.github.com/kristopherjohnson/ed97acf0bbe0013df8af) gist by
[kristopherjohnson](https://github.com/kristopherjohnson)
- [Pipe](https://github.com/danthorpe/Pipe) by [danthorpe](https://github.com/danthorpe)

## License

SwiftPipes is available under the MIT license. See the LICENSE file for more info.


text:
require 'forwardable'

module HumanizedSlackApi
  class Channels
    attr_reader :channel
    extend Forwardable
    include Enumerable
    def_delegators(:@channels, :each)

    def initialize(channels_list, root_parent)
      @channels = []
      @channels_names = {}
      @channels_ids = {}
      channels_list['channels'].each do |c|
        channel = Channel.build(c, root_parent)
        @channels << channel
        @channels_names[channel.name.to_s] = channel
        @channels_ids[channel.id.to_s] = channel
      end

    end

    def find(key)
      key = key.id if key.instance_of?(Channel)
      @channels_ids[key.to_s] || @channels_names[key.to_s] || raise(NoChannelFoundError.new("Not found #{key}"))
    end

    class NoChannelFoundError < StandardError; end
  end

  class Channel
    attr_reader :id, :name, :created, :creator, :is_archived, :is_general, :is_member, :num_members, :topic, :purpose, :last_read, :latest, :unread_count, :unread_count_display

    def self.build(json, root_parent)
      channel = Channel.new
      channel.instance_eval do
        @root_parent = root_parent
        @id = json['id']
        @name = json['name']
        @created = json['created']
        @creator = json['creator']
        @is_archived = json['is_archived']
        @is_general = json['is_general']
        @members = json['members']
        @is_member = json['is_member']
        @num_members = json['num_members']
        @topic = Topic.build(json['topic'])
        @purpose = Purpose.build(json['purpose'])
        @last_read = json['last_read']
        @latest = json['latest']
        @unread_count = json['unread_count']
        @unread_count_display = json['unread_count_display']
      end
      channel
    end

    def members
      @members.first.class == User ? @members : @members = @members.map {|m| @root_parent.users.find(m) }
    end

    class ChannelAttr
      attr_reader :value, :creator, :last_set

      def self.build(json)
        attrs = self.new
        attrs.instance_eval do
          @value = json['value']
          @creator = json['creator']
          @last_set = json['last_set']
        end
        attrs
      end
    end

    class Topic < ChannelAttr; end
    class Purpose < ChannelAttr; end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>GBD.Build.Blackjack: D:/SourceControl/GitRepos/GBD.Build.BlackJack/blackjack/cmake/cmd/include_directories.py Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

GBD.Build.Blackjack

A Module allowing for the automatic generation of CMakeLists.txt files from within python

Main Page

Related Pages

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

include_directories.py

Go to the documentation of this file.

    1 from blackjack.cmake.ScriptBase import ScriptBase

    2 from blackjack.cmake.cmdpart.IncludeDir import IncludeDir

    3

    4 ##

    5 #

    6 #     CMake Command - Include Directories

    7 #

    8 class include_directories(ScriptBase):

    9

   10

   11     def __init__(self, incdirs: [] = None):

   12         super().__init__()

   13         self.IncDirs = incdirs

   14         """Include Directories to add in"""

   15         return

   16

   17     def render_body(self):

   18         # First split the array into strings, and IncludeDir class's

   19         ret = []

   20         inc_strs = []

   21         inc_cls = []

   22         for item in self.IncDirs:

   23             if isinstance(item, str):

   24                 inc_strs.append(item)

   25             if isinstance(item, IncludeDir):

   26                 inc_cls.append(item)

   27

   28         # Include any string only include directories

   29         if len(inc_strs) > 0:

   30             ret.append("include_directories(")

   31             for item in inc_strs:

   32                 ret.append('    "' + item + '"')

   33             ret[-1] += ")"

   34

   35         # Include any directories specified via the IncludeDir class

   36         for item in inc_cls:

   37             ret.append("include_directories(")

   38             ret += item.render_global()

   39             ret[-1] += ")"

   40         return ret

blackjack.cmake.cmdpart.IncludeDir

Definition: IncludeDir.py:1

blackjack.cmake.cmd.include_directories.include_directories

CMake Command - Include Directories.

Definition: include_directories.py:8

blackjack.cmake.cmd.include_directories.include_directories.render_body

def render_body(self)

Definition: include_directories.py:17

blackjack.cmake.cmd.include_directories.include_directories.__init__

def __init__

Definition: include_directories.py:11

blackjack.cmake.ScriptBase

Definition: ScriptBase.py:1

blackjack.cmake.ScriptBase.ScriptBase

Represents a base class for all script sections That can be rendered or outputted to a CMakeLists...

Definition: ScriptBase.py:12

blackjack.cmake.cmd.include_directories.include_directories.IncDirs

IncDirs

Definition: include_directories.py:13

blackjack

cmake

cmd

include_directories.py

Generated by

     1.8.10


text:
/**
 * Sphyraena compiler options
 *
 * SPHY_DEBUG
 * Global debugging option, prints info during execution
 *
 * USE_INT64
 * Uses 64 bit integers instead of 32 bit integers for gpu executions
 *
 * USE_DOUBLES
 * Uses doubles instead of floats for gpu executions
 */

#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>

#include "sqlite3.h"
#include "sqliteInt.h"
#include "vdbe.h"
#include "vdbeInt.h"
#include "opcodes.h"

#include "cuda_runtime_api.h"
#include "driver_types.h"

#define SPHYRAENA_SUCCESS		0
#define SPHYRAENA_ERR_MEM		1
#define SPHYRAENA_ERR_STMT		2
#define SPHYRAENA_ERR_CUDAMEMCPY	3
#define SPHYRAENA_ERR_CUDAMALLOC	4
#define SPHYRAENA_ERR_DEVICE		5
#define SPHYRAENA_ERR_CUDAFREE	6
#define SPHYRAENA_ERR_CUDAFREEHOST	7
#define SPHYRAENA_ERR_KERNEL		8
#define SPHYRAENA_ERR_TYPE		9
#define SPHYRAENA_ERR_TEXTURE		10

#define SPHYRAENA_AGG_COUNT		0
#define SPHYRAENA_AGG_MIN		1
#define SPHYRAENA_AGG_MAX		2
#define SPHYRAENA_AGG_SUM		3
#define SPHYRAENA_AGG_AVG		4

#define SPHYRAENA_AGG_STR_COUNT	"count"
#define SPHYRAENA_AGG_STR_MIN		"min"
#define SPHYRAENA_AGG_STR_MAX		"max"
#define SPHYRAENA_AGG_STR_SUM		"sum"
#define SPHYRAENA_AGG_STR_AVG		"avg"

#define SPHYRAENA_MAX_OPS		64
#define SPHYRAENA_MAX_COLUMNS		16
#define SPHYRAENA_REGISTERS		32
#define SPHYRAENA_GLOBAL_REGISTERS	8
#define SPHYRAENA_THREADSPERBLOCK	192
#define SPHYRAENA_STREAMWIDTH		2

#define SPHYRAENA_INT			0
#define SPHYRAENA_INT64			1
#define SPHYRAENA_FLOAT			2
#define SPHYRAENA_DOUBLE		3
#define SPHYRAENA_ULLI			4
#define SPHYRAENA_NULL			5

#define SPHYRAENA_KB			1024
#define SPHYRAENA_MB			1048576
#define SPHYRAENA_GB			1073741824

// ############################################################################
// Struct definitions

struct sphyraena_op {
	u8 opcode;
	int p1;
	int p2;
	int p3;
	union {
		int i;
		i64 li;
		float f;
		double d;
	} p4;
	u8 p5;
} __attribute__((aligned (32))); // gcc and nvcc align this struct differently
typedef struct sphyraena_op sphyraena_op;

struct sphyraena_stmt {
	int start;	// TODO remove if not needed
	int nOp;
	sphyraena_op op[SPHYRAENA_MAX_OPS];
};
typedef struct sphyraena_stmt sphyraena_stmt;

#define SPHYRAENA_DATA_PADDING (128 - (((3 + 2 * SPHYRAENA_MAX_COLUMNS) * sizeof(int)) % 128))
struct sphyraena_data {
	int rows;
	int columns;
	int stride;
	int types[SPHYRAENA_MAX_COLUMNS];
	int offsets[SPHYRAENA_MAX_COLUMNS];
	//char pad[SPHYRAENA_DATA_PADDING];
	char d[];
};
typedef struct sphyraena_data sphyraena_data;

struct sphyraena_data_gpu {
	int rows;
	int columns;
	int stride;
	int types[SPHYRAENA_MAX_COLUMNS];
	int offsets[SPHYRAENA_MAX_COLUMNS];
};
typedef struct sphyraena_data_gpu sphyraena_data_gpu;

struct sphyraena_results {
	int rows;
	int columns;
	int stride;
	int types[SPHYRAENA_MAX_COLUMNS];
	int offsets[SPHYRAENA_MAX_COLUMNS];
	char r[];
};
typedef struct sphyraena_results sphyraena_results;

struct sphyraena_mem {
	union {
		int i;
		i64 li;
		unsigned long long int ulli;
		float f;
		double d;
		struct {
			int hi;
			int lo;
		} segment;
	} mem;
	int type;
};// __attribute__((aligned (16))); // gcc and nvcc align this struct differently
typedef struct sphyraena_mem sphyraena_mem;

struct sphyraena {
	sqlite3 *db;				// pointer to sqlite 3 database
	sphyraena_data *data_cpu;		// pointer to data block on cpu
	char *data_gpu;				// pointer to data block on gpu
	sphyraena_results *results_cpu;	// pointer to results block on cpu
	sphyraena_results *results_gpu;	// pointer to results block on gpu
	sphyraena_stmt *stmt_cpu;		// pointer to instruction block on cpu
	size_t data_size;				// size of data block
	size_t results_size;			// size of results block
	int threads_per_block;			// set to max
	int pinned_memory;
	int stream_width;
};
typedef struct sphyraena sphyraena;

// ############################################################################
// Function Declarations

int sphyraena_init(
	sphyraena *s,		// pointer to state struct we will initialize
	sqlite3 *db,		// pointer to sqlite 3 database
	size_t data_size, 	// size of data block allocated on both
					//   the cpu and gpu
	size_t results_size,	// size of results block allocated on both
					//   the cpu and gpu
	int pinned_memory);

int sphyraena_cleanup(sphyraena *s);

int sphyraena_prepare_data(sphyraena *s, const char* sql_stmt);

int sphyraena_transfer_data(sphyraena *s);

int sphyraena_transfer_results(sphyraena *s);

int sphyraena_select(sphyraena *s, const char* sql_stmt, int streaming);

int sphyraena_vm(sphyraena *s);

int sphyraena_vm_streaming(sphyraena *s);

int sphyraena_test_queries(sphyraena *s);

int sphyraena_test_sizes(sphyraena *s, int streaming, int include_transfer);

int sphyraena_test_case(
	sphyraena *s,
	const char *sql,
	double *time_native,
	double *time_gpu,
	double *time_transfer,
	int *rows,
	int streaming,
	int include_transfer);

// ############################################################################
// Debug helpers

struct timeval sphyraena_starttime;
struct timeval sphyraena_endtime;

void sphyraena_timer_start();
double sphyraena_timer_stop();
double sphyraena_timer_end(const char* label);
void sphyraena_print_results(sphyraena *s, int n);
cudaError_t sphyraena_print_error();

#ifdef SPHY_DEBUG

const char *sqlite3OpcodeName(int i);

#endif // ifdef DEBUG

// ############################################################################
// Macros

#define SPHYRAENA_ROUNDTOPWR2(x)	\
x--;						\
x |= x >> 1;				\
x |= x >> 2;				\
x |= x >> 4;				\
x |= x >> 8;				\
x |= x >> 16;				\
x++;

#define SPHYRAENA_MIN(a, b) a = ((a <= b) ? a : b);

#define SPHYRAENA_MAX(a, b) a = ((a >= b) ? a : b);


text:
import cherrypy

class HelloWorld(object):
  def index(self, name='World'):
    return 'Hello, <b>%s</b>!' % name
  index.exposed = True

if __name__ == '__main__':
  import logging
  import sys
  from syncless import wsgi
  if len(sys.argv) > 1:
    logging.root.setLevel(logging.DEBUG)
  else:
    logging.root.setLevel(logging.INFO)
  wsgi.RunHttpServer(HelloWorld)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="ajitsingh.com.androiduiplayground.DemoActivity">

    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>


text:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

#pragma warning disable IDE1006 // Naming Styles

namespace KerbDump
{
    public class LSASecret : IDisposable
    {
        private const string ADVAPI32 = "advapi32.dll";
        private const uint POLICY_GET_PRIVATE_INFORMATION = 0x00000004;

        [StructLayout(LayoutKind.Sequential)]
        private struct LSA_UNICODE_STRING
        {
            public UInt16 Length;
            public UInt16 MaximumLength;
            public IntPtr Buffer;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct LSA_OBJECT_ATTRIBUTES
        {
            public int Length;
            public IntPtr RootDirectory;
            public LSA_UNICODE_STRING ObjectName;
            public uint Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;
        }

        [DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
        private static extern uint LsaRetrievePrivateData(
            IntPtr PolicyHandle,
            ref LSA_UNICODE_STRING KeyName,
            out IntPtr PrivateData
        );

        [DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
        private static extern uint LsaOpenPolicy(
           ref LSA_UNICODE_STRING SystemName,
           ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
           uint DesiredAccess,
           out IntPtr PolicyHandle
        );

        [DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
        private static extern int LsaNtStatusToWinError(uint status);

        [DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
        private static extern uint LsaClose(IntPtr policyHandle);

        [DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
        private static extern uint LsaFreeMemory(IntPtr buffer);

        private LSA_UNICODE_STRING secretName;

        private readonly IntPtr lsaPolicyHandle;

        public LSASecret(string key)
        {
            this.secretName = new LSA_UNICODE_STRING()
            {
                Buffer = Marshal.StringToHGlobalUni(key),
                Length = (ushort)(key.Length * 2),
                MaximumLength = (ushort)((key.Length + 1) * 2)
            };

            var localsystem = default(LSA_UNICODE_STRING);
            var objectAttributes = default(LSA_OBJECT_ATTRIBUTES);

            var winErrorCode = LsaNtStatusToWinError(
                LsaOpenPolicy(
                    ref localsystem,
                    ref objectAttributes,
                    POLICY_GET_PRIVATE_INFORMATION,
                    out this.lsaPolicyHandle
                )
            );

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode);
            }
        }

        private static void FreeMemory(IntPtr Buffer)
        {
            var winErrorCode = LsaNtStatusToWinError(LsaFreeMemory(Buffer));

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode);
            }
        }

        public string GetSecret(out byte[] data)
        {
            var winErrorCode = LsaNtStatusToWinError(
                LsaRetrievePrivateData(this.lsaPolicyHandle, ref this.secretName, out IntPtr privateData)
            );

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode);
            }

            var lusSecretData = (LSA_UNICODE_STRING)Marshal.PtrToStructure(privateData, typeof(LSA_UNICODE_STRING));

            data = new byte[lusSecretData.Length];

            Marshal.Copy(lusSecretData.Buffer, data, 0, lusSecretData.Length);

            FreeMemory(privateData);

            return Encoding.Unicode.GetString(data);
        }

        public void Dispose()
        {
            var winErrorCode = LsaNtStatusToWinError(LsaClose(this.lsaPolicyHandle));

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode);
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.drip.sample.stretch</title>
<meta name="date" content="2014-01-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.drip.sample.stretch

Classes

CustomCurveBuilder

PenalizedCurvatureFit

PenalizedCurvatureLengthFit

RegressionSplineEstimator

StretchAdjuster

StretchEstimation

TensionStretchEstimation


text:
package org.codehaus.xfire.aegis.jdom;

import javax.xml.namespace.QName;

import org.codehaus.xfire.aegis.AbstractMessageWriter;
import org.codehaus.xfire.aegis.MessageWriter;
import org.jdom.Attribute;

public class AttributeWriter
    extends AbstractMessageWriter
{
    private Attribute att;

    public AttributeWriter(Attribute att)
    {
        this.att = att;
    }

    public void writeValue(Object value)
    {
        att.setValue(value.toString());
    }

    public MessageWriter getAttributeWriter(String name)
    {
        throw new IllegalStateException();
    }

    public MessageWriter getAttributeWriter(String name, String namespace)
    {
        throw new IllegalStateException();
    }

    public MessageWriter getAttributeWriter(QName qname)
    {
        throw new IllegalStateException();
    }

    public MessageWriter getElementWriter(String name)
    {
        throw new IllegalStateException();
    }

    public MessageWriter getElementWriter(String name, String namespace)
    {
        throw new IllegalStateException();
    }

    public MessageWriter getElementWriter(QName qname)
    {
        throw new IllegalStateException();
    }

    public String getPrefixForNamespace( String namespace )
    {
        throw new IllegalStateException();
    }

    public String getPrefixForNamespace(String namespace, String hint)
    {
        throw new IllegalStateException();
    }

    public void close()
    {
    }
}


text:
package com.github.tkocsis.vertx.graphql.utils;

import java.util.concurrent.CompletableFuture;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;

/**
 *
 * https://gist.github.com/purplefox/1a1d8dfddd04a2b2733c2062fb9fbbba
 *
 */
public class AsyncResCF<T> extends CompletableFuture<T> implements Handler<AsyncResult<T>> {

    @Override
    public void handle(AsyncResult<T> ar) {
        if (ar.succeeded()) {
            complete(ar.result());
        } else {
            completeExceptionally(ar.cause());
        }
    }

}


text:
layout: post
title: SwiftUI学习(7)-Combine入门Part I-Publisher
date: 2021-10-22 10:01:20 +0800
description: Combine使用基础之Publisher。
img: swiftui_logo.png # Add image post (optional)
fig-caption: # Add figcaption (optional)
tags: [SwiftUI]
---

>  **コニクマル**撰写
>
>  本文使用目前最新版本的xcode 13 + macOS Big sur + iOS15

# 简介

用[苹果自己话](https://developer.apple.com/documentation/combine/receiving-and-handling-events-with-combine)说:*`Combine`提供了APP处理事件的响应式声明框架。相较于之前的继承`Delegate`回调或者使用`完成闭包`参数,你可以创建一个从事件源头开的是处理链。该处理链每一个环节都是一个`Combine运算`,每个运算都会对上一个运算传递出来的内容进行特定处理。*

听起来很抽象, 举个不严谨的例子, 使用URLSession请求网络解析JSON数据

- 之前的做法:

  ```swift
  let task = URLSession.shared.dataTask(with: URL(string:"https://www.url.com")!) { data, resp, error in
      guard error == nil else{
          // 处理错误
          return
      }
      guard data != nil else{
          // 处理错误
          return
      }

      let decoder = JSONDecoder()
      if let json = try? decoder.decode(JsonTarget.self, from: data!){
      	self.response = json
      }else{
        self.response = Json(code: -1)
      }
  }
  task.resume()
  ```

- `Combine`的写法:

  ```swift
  let publisher =  URLSession.shared.dataTaskPublisher(for:URL(string:"https://www.url.com")!)
  let cancellable =
      .map({return $0.data})
      .decode(type: JsonTarget.self, decoder: JSONDecoder())
      .replaceError(with: JsonTarget(code: -1))
      .assign(to: \.resposne, on: self)
  ```

  - `URLSession.shared.dataTaskPublisher`返回的是发布者(Publisher)
  - `map` `decode`和`replaceError`是操作(Operator)
  - `assign`是订阅者(Subscriber)
  - `cancellable`是一个`Cancellable`可以用其`cancel()`方法来取消相关操作的。

  `Combine`的流程如下:

  ![image-20211022152214994](/assets/img/image-20211022152214994.png)

  - 首先订阅者请求订阅(Subscriber)
  - 然后发布者返回订阅内容(Subscription)
  - 再次订阅者请求数据
  - 发布者不断发布数据给订阅者
  - 发布者发送完成事件,结束整个流程

## 发布者(Publisher)

`Publisher`是`Combine`框架的一个很重要的的协议。`Publisher`是发布事件给一个或者多个订阅者。好比使用`NotificationCenter`编程时调用`NotificationCenter.default.post`来发布事件,这个发布事件的对象就相当于一个`Publisher`, 只不过不是使用`Combine`框架而已。

一个`Publisher`可以传递事件给一个或者多个订阅者(Subscriber)实例。 `Publisher`包含了`Output`类型和`Failure`错误类型。可以通过操作(Operator)来转换这个`Output`类型和`Failure`类型,订阅者(Subscriber)的`Intput`和`Failure`类型要符合`Publisher`的`Output`类型和`Failure`错误类型或者经过操作(Operator)转换后的`Output`类型和`Failure`错误类型才可以订阅。

### Publisher协议

先看看`Publisher`协议:

```swift
public protocol Publisher {
    associatedtype Output

    associatedtype Failure : Error

    func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
}

```

协议包含`Output`类型和错误`Failure`类型,以及一个接受订阅者的方法。简单实现一个自定义的`Publisher`,如下:

```swift
class TestPublisher: Publisher{
    func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Int == S.Input {
        subscriber.receive(1)
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2){
            subscriber.receive(2)
            subscriber.receive(completion: .finished)
        }
    }

    typealias Output = Int

    typealias Failure = Never
}

let  testPublisher = TestPublisher()
testPublisher.sink(receiveCompletion: { print("completed", $0)}, receiveValue: {print("received value", $0)})

```

输出如下:

```sh
received value 1
received value 2
completed finished
```

在`subscriber.receive(completion: .finished)`之后加一行`subscriber.receive(3)`,修改后:

```swift
...
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2){
    subscriber.receive(2)
    subscriber.receive(completion: .finished)
    subscriber.receive(3)
}
...
```

运行下:

```sh
received value 1
received value 2
completed finished
```

可以看到当`subscriber.receive(completion:)`调用完了后,流程已经结束了,之后在发送事件,订阅者无法收到的事件的。

### 便捷发布者(Convenience Publishers)

> Swift内置了一些便捷的Publisher, 方便快速使用。

#### Future

从名字看就是未来某个时刻会发出一个事件然后就结束。

举个栗子,在10秒后发出一个1:

```swift
let future = Future<Int, Never>{ promise in
    DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 10) {
        promise(.success(1))
    }
}
future.sink(receiveCompletion: { print("Received value", $0)}, receiveValue: { print("Receive value:", $0)}).store(in: &store)
```

运行10s后看到输出:

```sh
Receive value: 1
Received value finished
```

`Future<Int, Never>`: Int表示`Publisher`的Output类型, `Never`是`Failure`类型,`Never`表示不会发生错误。构造函数里的promise参数用来成功或者失败发送事件。

#### Just

这是一个马上发出事件的`Publisher`。

```swift
var store = Set<AnyCancellable>()
Just(1).sink(receiveCompletion: { print("Received value", $0)}, receiveValue: { print("Receive value:", $0)}).store(in: &store)
```

运行后马上看到输出:

```sh
Receive value: 1
Received value finished
```

#### Deferred

这个是延时创建`Publisher`,当被订阅的时候才会创建`Publisher`。

举个例子,  5s后发布一个:

```swift
let date = Date()
let publisher = Deferred { () -> Just<Int> in
    print("Create Pulisher", 0 - date.timeIntervalSinceNow)
    return Just(1)
}

DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 5){
    print("Subscribe", 0 - date.timeIntervalSinceNow)
    publisher.sink(receiveCompletion: { print("completed", $0, 0 - date.timeIntervalSinceNow)}, receiveValue: {print("received value", $0, 0 - date.timeIntervalSinceNow)})
}

print("Run", 0 - date.timeIntervalSinceNow)
```

输出如下:

```swift
Run 0.0022840499877929688
Subscribe 5.497779011726379
Create Pulisher 5.497919082641602
received value 1 5.4987300634384155
completed finished 5.49881899356842
```

可以看到当调用`sink`后才创建`Just Publisher`。

#### Empty

`Empty`不会发送任何内容,当订阅后立刻发送complete事件。

#### Fail

`Fail`不会发送任何内容,当订阅后立刻发送指定Error。

#### Record

`Record`可以先用`Record.Recording`来记录一系列事件,稍后在通过`Record`发送给订阅者。

举个例子

```swift
var recording = Record<Int, Never>.Recording()
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1) {
    let publisher = Record<Int, Never>(recording: recording)
    publisher.sink(receiveCompletion: { print("Received completed", $0)}, receiveValue: { print("Received Value", $0)})
}
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2) {
    let publisher2 = Record<Int, Never>(recording: recording)
    publisher2.sink(receiveCompletion: { print("Received 2 completed", $0)}, receiveValue: { print("Received 2 Value", $0)})
}
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 3) {
    let publisher3 = Record<Int, Never>(recording: recording)
    publisher3.sink(receiveCompletion: { print("Received 3 completed", $0)}, receiveValue: { print("Received 3 Value", $0)})
}

recording.receive(1)
recording.receive(2)
recording.receive(completion: .finished)
```

共用一个Recording记录了发送1,2和finish事件。创建3个Record来发布Recording的内容。


text:
extern int WINDOW_WIDTH;
extern int WINDOW_HEIGHT;

namespace gines
{
	InputManager::InputManager() : mouseCoordinates(0.0f)
	{
	}

	InputManager::~InputManager()
	{
	}

	void InputManager::update()
	{
		// Copying keyMap to previousKeyMap using for_each loop
		for (auto& it : keyMap)
		{
			previousKeyMap[it.first] = it.second;
		}

		static SDL_Event mEvent;
		while (SDL_PollEvent(&mEvent))
		{
			switch (mEvent.type)
			{
			default:
				break;
			case SDL_KEYDOWN:
				inputManager.keyPress(mEvent.key.keysym.sym);
				break;
			case SDL_KEYUP:
				inputManager.keyRelease(mEvent.key.keysym.sym);
				break;
			case SDL_MOUSEMOTION:
				inputManager.setMouseCoordinates(mEvent.motion.x, mEvent.motion.y);
				break;
			case SDL_MOUSEBUTTONDOWN:
				inputManager.keyPress(mEvent.button.button);
				break;
			case SDL_MOUSEBUTTONUP:
				inputManager.keyRelease(mEvent.button.button);
				break;
			case SDL_QUIT:
				SDL_Quit();
				break;
			}

		}
	}

	void InputManager::keyPress(unsigned int keyID)
	{
		keyMap[keyID] = true;
	}

	void InputManager::keyRelease(unsigned int keyID)
	{
		keyMap[keyID] = false;
	}

	void InputManager::setMouseCoordinates(float x, float y)
	{
		mouseCoordinates.x = x;
		mouseCoordinates.y = (y - WINDOW_HEIGHT) * -1;
	}

	bool InputManager::isKeyHeld(unsigned int keyID)
	{
		auto it = keyMap.find(keyID);
		if (it != keyMap.end())
		{ // Found key
			return it->second;
		}
		else
		{ // Didn't find key
			return false;
		}
	}

	bool InputManager::wasKeyHeld(unsigned int keyID)
	{
		auto it = previousKeyMap.find(keyID);
		if (it != previousKeyMap.end())
		{ // Found key
			return it->second;
		}
		else
		{ // Didn't find key
			return false;
		}
	}

	bool InputManager::isKeyPressed(unsigned int keyID)
	{	//Checks if the key was pressed this frame and WASN'T last frame.
		if (isKeyHeld(keyID) == true && wasKeyHeld(keyID) == false)
		{
			return true;
		}
		return false;
	}
}


text:
package hook

import (
	"os"
	"strings"

	"github.com/gleez/gandalf/config"
	"github.com/gleez/gandalf/fs"
)

func createHookFile(path string, content []byte) error {
	file, err := fs.Filesystem().OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.Write(content)
	if err != nil {
		return err
	}
	return nil
}

// Adds a hook script.
func Add(name string, repos []string, content []byte) error {
	configParam := "git:bare:template"
	if len(repos) > 0 {
		configParam = "git:bare:location"
	}
	path, err := config.GetString(configParam)
	if err != nil {
		return err
	}
	s := []string{path, "hooks", name}
	scriptPath := strings.Join(s, "/")
	if len(repos) > 0 {
		for _, repo := range repos {
			repo += ".git"
			s = []string{path, repo, "hooks", name}
			scriptPath = strings.Join(s, "/")
			err = fs.Filesystem().MkdirAll(scriptPath+"hooks", 0755)
			if err != nil {
				return err
			}
			err := createHookFile(scriptPath, content)
			if err != nil {
				return err
			}
		}
	} else {
		return createHookFile(scriptPath, content)
	}
	return nil
}


text:
package kg.apc.jmeter.functions;

import kg.apc.emulators.TestJMeterUtils;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterContextService;
import org.junit.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class EnvTest {

    private static String key, value;

    public EnvTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        TestJMeterUtils.createJmeterEnv();
        Map<String, String> env = System.getenv();
        if (!env.isEmpty()) {
            key = env.keySet().iterator().next();
            value = env.get(key);
        }
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of execute method, of class Env.
     */
    @Test
    public void testExecute() throws Exception {
        System.out.println("execute 1");
        SampleResult previousResult = null;
        Sampler currentSampler = null;
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
        Collection<CompoundVariable> parameters = new ArrayList<>();
        parameters.add(new CompoundVariable(key));
        Env instance = new Env();
        instance.setParameters(parameters);
        String result = instance.execute(null, null);
        Assert.assertEquals(value, result);
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
    }

    @Test
    public void testExecute_1() throws Exception {
        System.out.println("execute 1");
        SampleResult previousResult = null;
        Sampler currentSampler = null;

        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
        Collection<CompoundVariable> parameters = new ArrayList<>();
        parameters.add(new CompoundVariable(key));
        parameters.add(new CompoundVariable("toto"));
        Env instance = new Env();
        instance.setParameters(parameters);
        String result = instance.execute(null, null);
        Assert.assertEquals(value, result);
        Assert.assertNotNull(JMeterContextService.getContext().getVariables().remove("toto"));
    }

    @Test
    public void testExecute_2() throws Exception {
        System.out.println("execute 1");
        SampleResult previousResult = null;
        Sampler currentSampler = null;
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
        Collection<CompoundVariable> parameters = new ArrayList<>();
        String overrideKey = key + "testExecute_2";
        parameters.add(new CompoundVariable(overrideKey));
        Env instance = new Env();
        instance.setParameters(parameters);
        String result = instance.execute(null, null);
        Assert.assertEquals(overrideKey, result);
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
    }

    @Test
    public void testExecute_3() throws Exception {
        System.out.println("execute 1");
        SampleResult previousResult = null;
        Sampler currentSampler = null;
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
        Collection<CompoundVariable> parameters = new ArrayList<>();
        String overrideKey = key + "testExecute_3";
        String defaultValue = "defaultValue";
        parameters.add(new CompoundVariable(overrideKey));
        parameters.add(new CompoundVariable(""));
        parameters.add(new CompoundVariable(defaultValue));
        Env instance = new Env();
        instance.setParameters(parameters);
        String result = instance.execute(null, null);
        Assert.assertEquals(defaultValue, result);
        Assert.assertNull(JMeterContextService.getContext().getVariables().get("toto"));
    }

    /**
     * Test of setParameters method, of class Env.
     */
    @Test
    public void testSetParameters() throws Exception {
        System.out.println("setParameters");
        Collection<CompoundVariable> parameters = new ArrayList<>();
        parameters.add(new CompoundVariable(key));
        Env instance = new Env();
        instance.setParameters(parameters);

        // second parameter
        parameters.add(new CompoundVariable("save_variable"));
        instance.setParameters(parameters);

        // third parameter
        parameters.add(new CompoundVariable("default_value"));
        instance.setParameters(parameters);
    }

    @Test(expected = InvalidVariableException.class)
    public void testSetParametersException() throws Exception {
        System.out.println("setParameters");
        Collection<CompoundVariable> parameters = new ArrayList<>();
        Env instance = new Env();
        instance.setParameters(parameters);
    }

    @Test(expected = InvalidVariableException.class)
    public void testSetParametersException2() throws Exception {
        System.out.println("setParameters");
        Collection<CompoundVariable> parameters = new ArrayList<>();
        parameters.add(new CompoundVariable(key));
        parameters.add(new CompoundVariable("save_variable"));
        parameters.add(new CompoundVariable("default_value"));
        parameters.add(new CompoundVariable("Error"));
        Env instance = new Env();
        instance.setParameters(parameters);
    }

    /**
     * Test of getReferenceKey method, of class Env.
     */
    @Test
    public void testGetReferenceKey() {
        System.out.println("getReferenceKey");
        Env instance = new Env();
        String expResult = "__env";
        String result = instance.getReferenceKey();
        Assert.assertEquals(expResult, result);
    }

    /**
     * Test of getArgumentDesc method, of class Env.
     */
    @Test
    public void testGetArgumentDesc() {
        System.out.println("getArgumentDesc");
        Env instance = new Env();
        List<String> result = instance.getArgumentDesc();
        Assert.assertEquals(3, result.size());
    }
}


text:
cask 'github-desktop' do
  version '0.5.9-d08be790'
  sha256 '335c28e70f52fc53048a6dc6b12abf89ee7fd2b55a49bd90b982537ae3cdcb1e'

  # githubusercontent.com was verified as official when first introduced to the cask
  url "https://desktop.githubusercontent.com/releases/#{version}/GitHubDesktop.zip"
  appcast 'https://github.com/desktop/desktop/releases.atom',
          checkpoint: 'acf2ad7c22e097177a3a1f381ba26301d0817d124c1df73af9df70d053587cc4'
  name 'GitHub Desktop'
  homepage 'https://desktop.github.com/'

  auto_updates true

  app 'GitHub Desktop.app'

  zap delete: [
                '~/Library/Application Support/GitHub Desktop',
                '~/Library/Application Support/ShipIt_stderr.log',
                '~/Library/Application Support/ShipIt_stdout.log',
                '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.github.GitHubClient.sfl',
                '~/Library/Application Support/com.github.GitHubClient',
                '~/Library/Application Support/com.github.GitHubClient.ShipIt',
                '~/Library/Caches/com.github.GitHubClient',
                '~/Library/Caches/com.github.GitHubClient.ShipIt',
                '~/Library/Preferences/com.github.GitHubClient.helper.plist',
                '~/Library/Preferences/com.github.GitHubClient.plist',
              ],
      rmdir:  '~/.config/git'
end


text:
<?php namespace Sclr;

class SclrArray extends SclrValue {

	public function init()
	{
		if (!is_array($this->value)) {
			throw new \Exception('The value is not an array');
		}
	}

	public function append($value)
	{
		array_push($this->value, $value);
		return $this;
	}

	public function contains($value)
	{
		return in_array($value, $this->value);
	}

	public function filter($callback)
	{
		$this->value = array_filter($this->value, $callback);
		return $this;
	}

	public function find($search)
	{
		$key = array_search($search, $this->value);
		if ($key && isset($this->value[$key])) {
			return $this->value[$key];
		}

		return false;
	}

	public function map($callback)
	{
		$this->value = array_map($callback, $this->value);
		return $this;
	}

	public function prepend($value)
	{
		array_unshift($this->value, $value);
		return $this;
	}

	public function reduce($callback)
	{
		return array_reduce($this->value, $callback);
	}

	public function reject($callback)
	{
		$filtered = [];

		foreach ($this->value as $key => $value) {
			if (!$callback($value, $key)) {
				$filtered[$key] = $value;
			}
		}

		$this->value = array_values($filtered);
		return $this;
	}

	public function size()
	{
		return sizeof($this->value);
	}

	public function toObject()
	{
		return (object)$this->value;
	}

}


text:
```ruby
on hosts do |host|
  as 'www-data' do
    puts capture(:whoami)
  end
end
```

## Run with default environmental variables

```ruby
SSHKit.config.default_env = { path: '/usr/local/libexec/bin:$PATH' }
on hosts do |host|
  puts capture(:env)
end
```

## Run a command in a different directory

```ruby
on hosts do |host|
  within '/var/log' do
    puts capture(:head, '-n5', 'messages')
  end
end
```

## Run a command with specific environmental variables

```ruby
# Please see the documentation for caveats related to commands that do not use
# the command map [such as simple strings].
#
# https://github.com/capistrano/sshkit#the-command-map
on hosts do |host|
  with rack_env: :test do
    puts capture("env | grep RACK_ENV")
  end
end
```

## Print some arbitrary output with the logging methods

```ruby
on hosts do |host|
  f = '/some/file'
  if test("[ -f #{f} ]")
    info "#{f} already exists on #{host}!"
  else
    execute :touch, f
  end
end
```

The `debug()`, `info()`, `warn()`, `error()` and `fatal()` honor the current
log level of `SSHKit.config.output_verbosity`

## Run a command in a different directory as a different user

```ruby
on hosts do |host|
  as 'www-data' do
    within '/var/log' do
      puts capture(:whoami)
      puts capture(:pwd)
    end
  end
end
```

This will output:

    www-data
    /var/log

**Note:** This example is a bit misleading, as the `www-data` user doesn't
have a shell defined, one cannot switch to that user.

## Run a command which requires interaction between the client and the server

```ruby
on hosts do |host|
  execute(:passwd, interaction_handler: {
    '(current) UNIX password: ' => "old_pw\n",
    'Enter new UNIX password: ' => "new_pw\n",
    'Retype new UNIX password: ' => "new_pw\n",
    'passwd: password updated successfully' => nil # For stdout/stderr which can be ignored, map a nil input
  })
end
```

## Download a file from disk

```ruby
on roles(:all) do
  puts 'Downloading DB Backup File'
  date_path = Date.today.strftime("%Y/%m/%d")
  download! "/var/mysql-backup/#{date_path}/my-awesome-db.sql.gz", "my-awesome-db.sql.gz"
end
```

## Upload a file from disk

```ruby
on hosts do |host|
  upload! '/config/database.yml', '/opt/my_project/shared/database.yml'
end
```

Upload and download will respect the `within()` directories:

```ruby
on hosts do |host|
  within 'my/app/directory' do
    upload! 'database.yml', 'config/database.yml'
  end
end
```

**Note:** The `upload!()` method doesn't honor the values of `as()` etc, this
will be improved as the library matures, but we're not there yet.

## Upload a file from a stream

```ruby
on hosts do |host|
  file = File.open('/config/database.yml')
  io   = StringIO.new(....)
  upload! file, '/opt/my_project/shared/database.yml'
  upload! io,   '/opt/my_project/shared/io.io.io'
end
```

The IO streaming is useful for uploading something rather than "cat"ing it,
for example

```ruby
on hosts do |host|
  contents = StringIO.new('ALL ALL = (ALL) NOPASSWD: ALL')
  upload! contents, '/etc/sudoers.d/yolo'
end
```

This spares one from having to figure out the correct escaping sequences for
something like "echo(:cat, '...?...', '> /etc/sudoers.d/yolo')".

**Note:** The `upload!()` method doesn't honor the values of `within()`, `as()`
etc, this will be improved as the library matures, but we're not there yet.

## Upload a directory of files

```ruby
on hosts do |host|
  upload! '.', '/tmp/mypwd', recursive: true
end
```

In this case the `recursive: true` option mirrors the same options which are
available to [`Net::{SCP,SFTP}`](http://net-ssh.github.io/net-scp/).

## Setting global SSH options

Setting global SSH options, these will be overwritten by options set on the
individual hosts:

```ruby
SSHKit::Backend::Netssh.configure do |ssh|
  ssh.connection_timeout = 30
  ssh.ssh_options = {
    user: 'adifferentuser',
    keys: %w(/home/user/.ssh/id_rsa),
    forward_agent: false,
    auth_methods: %w(publickey password)
  }
end
```

## Run a command with a different effective group ID

```ruby
on hosts do |host|
  as user: 'www-data', group: 'project-group' do
    within '/var/log' do
      execute :touch, 'somefile'
      execute :ls, '-l'
    end
  end
end
```

One will see that the created file is owned by the user `www-data` and the
group `project-group`.

When combined with the `umask` configuration option, it is easy to share
scripts for deployment between team members without sharing logins.

## Stack directory nestings

```ruby
on hosts do
  within "/var" do
    puts capture(:pwd)
    within :log do
      puts capture(:pwd)
    end
  end
end
```

This will output:

    /var/
    /var/log

The directory paths are joined using `File.join()`, which should correctly
join parts without forcing the user of the code to care about trailing or
leading slashes. It may be misleading as the `File.join()` is performed on the
machine running the code, if that's a Windows box, the paths may be incorrectly
joined according to the expectations of the machine receiving the commands.

## Do not care about the host block

```ruby
on hosts do
  # The |host| argument is optional, it will
  # be nil in the block if not passed
end
```

## Change the output formatter

```ruby
# The default format is pretty, which outputs colored text
SSHKit.config.format = :pretty

# Text with no coloring
SSHKit.config.format = :simpletext

# Red / Green dots for each completed step
SSHKit.config.format = :dot

# No output
SSHKit.config.format = :blackhole
```

## Implement a dirt-simple formatter class

```ruby
module SSHKit
  module Formatter
    class MyFormatter < SSHKit::Formatter::Abstract
      def write(obj)
        case obj.is_a? SSHKit::Command
          # Do something here, see the SSHKit::Command documentation
        end
      end
    end
  end
end

# If your formatter is defined in the SSHKit::Formatter module configure with the format option:
SSHKit.config.format = :myformatter

# Or configure the output directly
SSHKit.config.output = MyFormatter.new($stdout)
SSHKit.config.output = MyFormatter.new(SSHKit.config.output)
SSHKit.config.output = MyFormatter.new(File.open('log/deploy.log', 'wb'))
```

## Set a password for a host.

```ruby
host = SSHKit::Host.new('user@example.com')
host.password = "hackme"

on host do |host|
  puts capture(:echo, "I don't care about security!")
end
```

## Execute and raise an error if something goes wrong

```ruby
on hosts do |host|
  execute(:echo, '"Example Message!" 1>&2; false')
end
```

This will raise `SSHKit::Command::Failed` with the `#message` "Example Message!"
which will cause the command to abort.

## Make a test, or run a command which may fail without raising an error:

```ruby
on hosts do |host|
  if test "[ -d /opt/sites ]"
    within "/opt/sites" do
      execute :git, :pull
    end
  else
    execute :git, :clone, 'some-repository', '/opt/sites'
  end
end
```

The `test()` command behaves exactly the same as execute however will return
false if the command exits with a non-zero exit (as `man 1 test` does). As it
returns boolean it can be used to direct the control flow within the block.

## Do something different on one host, or another depending on a host property

```ruby
host1 = SSHKit::Host.new 'user@example.com'
host2 = SSHKit::Host.new 'user@example.org'

on hosts do |host|
  target = "/var/www/sites/"
  if host.hostname =~ /org/
    target += "dotorg"
  else
    target += "dotcom"
  end
  execute! :git, :clone, "git@git.#{host.hostname}", target
end
```

## Connect to a host in the easiest possible way

```ruby
on 'example.com' do |host|
  execute :uptime
end
```

This will resolve the `example.com` hostname into a `SSHKit::Host` object, and
try to pull up the correct configuration for it.

## Connect to a host on a port different than 22

If your ssh server is running on a port different than 22, you can change this is
shown:

```ruby
on('example.com', {port: 1234}) do
end
```

## Run a command without it being command-mapped

If the command you attempt to call contains a space character it won't be
mapped:

```ruby
Command.new(:git, :push, :origin, :master).to_s
# => /usr/bin/env git push origin master
# (also: execute(:git, :push, :origin, :master)

Command.new("git push origin master").to_s
# => git push origin master
# (also: execute("git push origin master"))
```

This can be used to access shell builtins (such as `if` and `test`)

## Run a command with a heredoc

An extension of the behaviour above, if you write a command like this:

```ruby
c = Command.new <<-EOCOMMAND
  if test -d /var/log
  then echo "Directory Exists"
  fi
EOCOMMAND
c.to_s
# => if test -d /var/log; then echo "Directory Exists; fi
# (also: execute <<- EOCOMMAND........))
```

**Note:** The logic which reformats the script into a oneliner may be naïve, but in all
known test cases, it works. The key thing is that `if` is not mapped to
`/usr/bin/env if`, which would break with a syntax error.

## Using with Rake

Into the `Rakefile` simply put something like:

```ruby
require 'sshkit'

SSHKit.config.command_map[:rake] = "./bin/rake"

desc "Deploy the site, pulls from Git, migrate the db and precompile assets, then restart Passenger."
task :deploy do
  include SSHKit::DSL

  on "example.com" do |host|
    within "/opt/sites/example.com" do
      execute :git, :pull
      execute :bundle, :install, '--deployment'
      execute :rake, 'db:migrate'
      execute :rake, 'assets:precompile'
      execute :touch, 'tmp/restart.txt'
    end
  end
end
```

## Using without the DSL

The *Coordinator* will resolve all hosts into *Host* objects, you can mix and
match.

```ruby
Coordinator.new("one.example.com", SSHKit::Host.new('two.example.com')).each in: :sequence do
  puts capture :uptime
end
```

You might also look at `./lib/sshkit/dsl.rb` where you can see almost the
exact code as above, which implements the `on()` method.

## Use the Host properties attribute

Implemented since `v0.0.6`

```ruby
servers = %w{one.example.com two.example.com
             three.example.com four.example.com}.collect do |s|
  h = SSHKit::Host.new(s)
  if s.match /(one|two)/
    h.properties.roles = [:web]
  else
    h.properties.roles = [:app]
  end
end

on servers do |host|
  if host.properties.roles.include?(:web)
    # Do something pertinent to web servers
  elsif host.properties.roles.include?(:app)
    # Do something pertinent to application servers
  end
end
```

The `SSHKit::Host#properties` is an [`OpenStruct`](http://ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html)
which is not verified or validated in any way, it is up to you, or your
library to attach meanings or conventions to this mechanism.

## Running local commands

Replace `on` with `run_locally`

```ruby
run_locally do
  within '/tmp' do
    execute :whoami
  end
end
```

You can achieve the same thing with `on(:local)`

```ruby
on(:local) do
  within '/tmp' do
    execute :whoami
  end
end
```


text:
external help file: posh-tex-help.xml
online version: http://www.cgranade.com/posh-tex/cmdlets/Get-TeXDistribution/
schema: 2.0.0
---

# Get-TeXDistribution

## SYNOPSIS
Detects which TeX distribution is installed by running
"tex" and checking the reported version.

## SYNTAX

```
Get-TeXDistribution [<CommonParameters>]
```

## DESCRIPTION
{{Fill in the Description}}

## EXAMPLES

### Example 1
```
PS C:\> {{ Add example code here }}
```

{{ Add example description here }}

## PARAMETERS

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES

## RELATED LINKS