text:
/* global describe, it */
var assert = require('assert')
var changeCase = require('./')

describe('change case', function () {
  it('should convert to lower case', function () {
    assert.equal(changeCase.lower('test'), 'test')
    assert.equal(changeCase.lowerCase('TEST'), 'test')
  })

  it('should convert to upper case', function () {
    assert.equal(changeCase.upper('TEST'), 'TEST')
    assert.equal(changeCase.upperCase('test'), 'TEST')
  })

  it('should upper case the first character', function () {
    assert.equal(changeCase.ucFirst('TEST'), 'TEST')
    assert.equal(changeCase.upperCaseFirst('test'), 'Test')
  })

  it('should lower case the first character', function () {
    assert.equal(changeCase.lcFirst('TEST'), 'tEST')
    assert.equal(changeCase.lowerCaseFirst('Test'), 'test')
  })

  it('should determine whether a string is all upper case or not', function () {
    assert.equal(changeCase.isUpper('ALLUPPERCASE'), true)
    assert.equal(changeCase.isUpperCase('NotAllUpperCase'), false)
    assert.equal(changeCase.isUpperCase('alllowercase'), false)
  })

  it('should determine whether a string is all upper case or not', function () {
    assert.equal(changeCase.isLower('ALLUPPERCASE'), false)
    assert.equal(changeCase.isLowerCase('NotAllLowerCase'), false)
    assert.equal(changeCase.isLowerCase('alllowercase'), true)
  })

  it('should convert to title case', function () {
    assert.equal(changeCase.title('a test sentence'), 'A Test Sentence')
    assert.equal(changeCase.titleCase('i found a bug'), 'I Found A Bug')
    assert.equal(changeCase.titleCase("some things'"), 'Some Things')
    assert.equal(changeCase.titleCase('"quotes"'), 'Quotes')
    assert.equal(changeCase.titleCase('hyphen-ness'), 'Hyphen Ness')
  })

  it('should convert to sentence case', function () {
    assert.equal(changeCase.sentence('a-simple-test'), 'a simple test')
    assert.equal(changeCase.sentenceCase('this is a test'), 'this is a test')
    assert.equal(changeCase.sentenceCase('this_is_a_test'), 'this is a test')
    assert.equal(changeCase.sentenceCase('this-is-a-test'), 'this is a test')
  })

  it('should convert to camel case', function () {
    assert.equal(changeCase.camel('TestString'), 'testString')
    assert.equal(changeCase.camelCase('Test String'), 'testString')
    assert.equal(changeCase.camelCase('Test_String'), 'testString')
    assert.equal(changeCase.camelCase('Test-String'), 'testString')
    assert.equal(changeCase.camelCase('Facebook API'), 'facebookApi')
    assert.equal(changeCase.camelCase('-webkit-transform'), 'webkitTransform')
    assert.equal(changeCase.camelCase('fooBarBaz'), 'fooBarBaz')
    assert.equal(changeCase.camelCase('some (things)'), 'someThings')
  })

  it('should convert to pascal case', function () {
    assert.equal(changeCase.pascal('testString'), 'TestString')
    assert.equal(changeCase.pascalCase('Test String'), 'TestString')
    assert.equal(changeCase.pascalCase('Test_String'), 'TestString')
    assert.equal(changeCase.pascalCase('Test-String'), 'TestString')
    assert.equal(changeCase.pascalCase('Facebook API'), 'FacebookApi')
    assert.equal(changeCase.pascalCase('a-test-again'), 'ATestAgain')
    assert.equal(changeCase.pascalCase('a---better__test'), 'ABetterTest')
  })

  it('should convert to snake case', function () {
    assert.equal(changeCase.snake('testString'), 'test_string')
    assert.equal(changeCase.snakeCase('Test String'), 'test_string')
    assert.equal(changeCase.snakeCase('Test_String'), 'test_string')
    assert.equal(changeCase.snakeCase('Test-String'), 'test_string')
    assert.equal(changeCase.snakeCase('a---better__test'), 'a_better_test')
  })

  it('should convert to param case', function () {
    assert.equal(changeCase.param('testString'), 'test-string')
    assert.equal(changeCase.paramCase('Test String'), 'test-string')
    assert.equal(changeCase.paramCase('Test_String'), 'test-string')
    assert.equal(changeCase.paramCase('Test-String'), 'test-string')
    assert.equal(changeCase.paramCase('a---better__test'), 'a-better-test')
  })

  it('should convert to constant case', function () {
    assert.equal(changeCase.constant('testString'), 'TEST_STRING')
    assert.equal(changeCase.constantCase('Test String'), 'TEST_STRING')
    assert.equal(changeCase.constantCase('Test_String'), 'TEST_STRING')
    assert.equal(changeCase.constantCase('Test-String'), 'TEST_STRING')
    assert.equal(changeCase.constantCase('a---better__test'), 'A_BETTER_TEST')
  })

  it('should convert to dot case', function () {
    assert.equal(changeCase.dot('testString'), 'test.string')
    assert.equal(changeCase.dotCase('Test String'), 'test.string')
    assert.equal(changeCase.dotCase('Test_String'), 'test.string')
    assert.equal(changeCase.dotCase('Test-String'), 'test.string')
    assert.equal(changeCase.dotCase('a---better__test'), 'a.better.test')
  })

  it('should convert to path case', function () {
    assert.equal(changeCase.path('testString'), 'test/string')
    assert.equal(changeCase.pathCase('Test String'), 'test/string')
    assert.equal(changeCase.pathCase('Test_String'), 'test/string')
    assert.equal(changeCase.pathCase('Test-String'), 'test/string')
    assert.equal(changeCase.pathCase('a---better__test'), 'a/better/test')
  })

  it('should swap the cases', function () {
    assert.equal(changeCase.swap('RaNdOMcasE'), 'rAnDomCASe')
    assert.equal(changeCase.swapCase('mIX It.Down?'), 'Mix iT.dOWN?')
  })
})


text:
/*
 * class Perlin::Generator
 */

#ifndef GENERATOR_H
#define GENERATOR_H

#include <ruby.h>

#include <stdbool.h>

#include "classic.h"
#include "simplex.h"

extern long seed;

void Init_Perlin_Generator();

// Getters.
VALUE Perlin_Generator_get_seed(const VALUE self);
VALUE Perlin_Generator_get_persistence(const VALUE self);
VALUE Perlin_Generator_get_octave(const VALUE self);
VALUE Perlin_Generator_get_classic(const VALUE self);

// Setters.
VALUE Perlin_Generator_set_seed(const VALUE self, const VALUE seed);
VALUE Perlin_Generator_set_persistence(const VALUE self, const VALUE persistence);
VALUE Perlin_Generator_set_octave(const VALUE self, const VALUE octave);
VALUE Perlin_Generator_set_classic(const VALUE self, const VALUE classic);

// Actually getting noise.
VALUE Perlin_Generator_run(const int argc, const VALUE *argv, const VALUE self);
VALUE Perlin_Generator_run2d(const VALUE self, const VALUE x, const VALUE y);
VALUE Perlin_Generator_run3d(const VALUE self, const VALUE x, const VALUE y, const VALUE z);

VALUE Perlin_Generator_chunk(const int argc, const VALUE *argv, const VALUE self);
VALUE Perlin_Generator_chunk2d(const VALUE self, const VALUE x, const VALUE y, const VALUE steps_x, const VALUE steps_y, VALUE interval);
VALUE Perlin_Generator_chunk3d(const VALUE self, const VALUE x, const VALUE y, const VALUE z, const VALUE steps_x, const VALUE steps_y, const VALUE steps_z, const VALUE interval);

VALUE Perlin_Generator_init(const int argc, const VALUE *argv, const VALUE self);

// Data management stuff.

typedef struct _PerlinGenerator
{
    bool is_classic; // True if Classic, false if Simplex.
    long seed; // >= 1
    long octave; // >= 1
    double persistence;
} PerlinGenerator;

#define GENERATOR() \
    PerlinGenerator* generator; \
    Data_Get_Struct(self, PerlinGenerator, generator);

VALUE Perlin_Generator_allocate(VALUE klass);
void Perlin_Generator_free(PerlinGenerator* generator);

#endif // GENERATOR_H

redpajama_set_name: RedPajamaGithub


text:
package org.incode.module.commchannel.integtests.postaladdress;

import java.util.SortedSet;

import javax.inject.Inject;

import com.google.common.eventbus.Subscribe;

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

import org.apache.isis.applib.AbstractSubscriber;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;

import org.incode.module.commchannel.dom.impl.channel.CommunicationChannel;
import org.incode.module.commchannel.dom.impl.postaladdress.PostalAddress;
import org.incode.module.commchannel.dom.impl.postaladdress.PostalAddress_clearGeocode;
import org.incode.module.commchannel.fixture.dom.CommChannelDemoObject;
import org.incode.module.commchannel.fixture.dom.CommChannelDemoObjectMenu;
import org.incode.module.commchannel.fixture.scripts.teardown.CommChannelDemoObjectsTearDownFixture;
import org.incode.module.commchannel.integtests.CommChannelModuleIntegTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;

public class PostalAddress_clearGeocode_IntegTest extends CommChannelModuleIntegTest {

    @Inject
    CommChannelDemoObjectMenu commChannelDemoObjectMenu;

    CommChannelDemoObject fredDemoOwner;
    PostalAddress postalAddress;

    PostalAddress_clearGeocode mixinResetGeocode(final PostalAddress postalAddress) {
        return mixin(PostalAddress_clearGeocode.class, postalAddress);
    }

    @Before
    public void setUpData() throws Exception {
        fixtureScripts.runFixtureScript(new CommChannelDemoObjectsTearDownFixture(), null);

        fredDemoOwner = wrap(commChannelDemoObjectMenu).create("Fred");

        wrap(mixinNewPostalAddress(fredDemoOwner)).$$(
                "45", "High Street", "Oxford", null, "OX1", "UK", "Work", "Fred Smith's work", true);

        final SortedSet<CommunicationChannel> communicationChannels = wrap(mixinCommunicationChannels(fredDemoOwner)).$$();
        postalAddress = (PostalAddress) communicationChannels.first();

    }

    public static class ActionImplementationIntegrationTest extends PostalAddress_clearGeocode_IntegTest {

        @Test
        public void clear() throws Exception {

            assumeThat(isInternetReachable(), is(true));

            // given
            assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNotNull();
            assertThat(postalAddress.getName()).isEqualTo("45 High St, Oxford OX1, UK");

            // when
            wrap(mixinResetGeocode(postalAddress)).$$();

            // then
            assertThat(postalAddress.getName()).isEqualTo("45, High Stree...ford, OX1, UK");
            assertThat(postalAddress.getFormattedAddress()).isNull();
            assertThat(postalAddress.getGeocodeApiResponseAsJson()).isNull();
            assertThat(postalAddress.getLatLng()).isNull();
            assertThat(postalAddress.getPlaceId()).isNull();
            assertThat(postalAddress.getAddressComponents()).isNull();
        }
    }

    public static class RaisesEventIntegrationTest extends PostalAddress_clearGeocode_IntegTest {

        @DomainService(nature = NatureOfService.DOMAIN)
        public static class TestSubscriber extends AbstractSubscriber {
            PostalAddress_clearGeocode.DomainEvent ev;

            @Subscribe
            public void on(PostalAddress_clearGeocode.DomainEvent ev) {
                this.ev = ev;
            }
        }

        @Inject
        TestSubscriber testSubscriber;

        @Test
        public void happy_case() throws Exception {

            wrap(mixinResetGeocode(postalAddress)).$$();

            assertThat(testSubscriber.ev).isNotNull();
        }
    }

}


text:
function pushCharacter(character) {
    var input = document.querySelector("#display");
    input.value = input.value + character;
    console.log(character);
};
function calculate() {
    var input = document.querySelector("#display");
    input.value = eval(input.value).toString();
};
function clear() {
    var input = document.querySelector("#display");
    input.value = "";
};

window.onload = function() {
    var buttons = document.querySelectorAll(".button");
    [].forEach.call(buttons, function(button) {
        button.addEventListener("click", function() { pushCharacter(button.innerHTML); });
    });

    var equalbutton = document.querySelector(".button-equals");
    equalbutton.onclick = calculate;

    var clearbutton = document.querySelector(".clearbutton");
    clearbutton.onclick = clear;
}

$('#display').on('keypress', function(e){

    var code = (e.keyCode ? e.keyCode : e.which);
             if(code == 13) {
                 calculate()
             }
    });


text:
uid: mailboxes
title: Mailboxes
---

# Mailboxes

## What Mailboxes Do?

In Akka.NET, Mailboxes hold messages that are destined for an actor. When you send a message to an actor, the message doesn't go directly to the actor, but goes to the actor's mailbox until the actor has time to process it.

A mailbox can be described as a queue of messages. Messages are usually then delivered from the mailbox to the actor one at a time in the order they were received, but there are implementations like the [Priority Mailbox](#unboundedprioritymailbox) that can change the order of delivery.

Normally every actor has its own mailbox, but this is not a requirement. There are implementations of [routers](xref:routers) where all routees share a single mailbox.

## Using a Mailbox

To make an actor use a specific mailbox, you can set it up one of the following locations:

1. In the actor's props

  ```cs
  Props.Create<ActorType>().WithMailbox("my-custom-mailbox");
  ```

2. In the actor's deployment configuration

  ```hocon
  akka.actor.deployment {
      /my-actor-path {
          mailbox = my-custom-mailbox
      }
  }
  ```

The `my-custom-mailbox` is a key that was setup using the [mailbox configuration](#configuring-custom-mailboxes).

## Configuring Custom Mailboxes

In order to use a custom mailbox, it must be first configured with a key that the actor system can lookup. You can do this using a custom HOCON setting.

The example below will setup a mailbox key called `my-custom-mailbox` pointing to a custom mailbox implementation. Note that the configuration of the mailbox is outside the akka section.

```hocon
akka { ... }
my-custom-mailbox {
    mailbox-type : "MyProject.CustomMailbox, MyProjectAssembly"
}
```

## Built-in Mailboxes

### UnboundedMailbox

**This is the default mailbox** used by Akka.NET. It's a non-blocking unbounded mailbox, and should be good enough for most cases.

### UnboundedPriorityMailbox

The unbounded mailbox priority mailbox is blocking mailbox that allows message prioritization, so that you can choose the order the actor should process messages that are already in the mailbox.

In order to use this mailbox, you need to extend the `UnboundedPriorityMailbox` class and provide an ordering logic. The value returned by the `PriorityGenerator` method will be used to order the message in the mailbox. Lower values will be delivered first. Delivery order for messages of equal priority is undefined.

```cs
public class IssueTrackerMailbox : UnboundedPriorityMailbox
{
  protected override int PriorityGenerator(object message)
  {
	  var issue = message as Issue;

	  if (issue != null)
	  {
		  if (issue.IsSecurityFlaw)
			  return 0;

		  if (issue.IsBug)
			  return 1;
	  }

	  return 2;
  }
}
```

Once the class is implemented, you should set it up using the [instructions above](#using-a-mailbox).

> [!WARNING]
> While we have updated the `UnboundedPriorityMailbox` to support Stashing. We don't recommend using it.
Once you stash messages, they are no longer part of the prioritization process that your PriorityMailbox uses. Once you unstash all messages, they are fed to the Actor, in the order of stashing.


text:
/**
 * Created by Nicholas on 2017/2/10.
 */
'use strict';

const Etcd = require('etcd-cli');
const path = require('path');
const _ = require('lodash');
const arguejs = require('arguejs');
const Promise = require('bluebird');
const events = require('events');
const util = require('util');
const Cache = require('./lib/cache');
const bunyan = require('bunyan');

function NgConf(etcd, project, options) {
    events.EventEmitter.apply(this);
    this._etcd = new Etcd.V2HTTPClient(etcd);
    this._project = project;
    let _defaults = {
        localOnly: false,
        profile: function () {
            return process.env.NODE_ENV || 'development';
        },
        cachePath: './cache',
        localPath: './config',
        namespace: 'ngconf'
    };
    this._options = _.defaultsDeep(options, _defaults);
    this._namespace = this._options.namespace;
    if (typeof this._options.profile === 'function') {
        this._profile = this._options.profile();
    } else {
        this._profile = this._options.profile;
    }
    if (this._options.logger) {
        this._logger = this._options.logger;
    } else {
        this._logger = bunyan.createLogger({
            name: 'NgConf'
        });
    }
    this._watchers = {};
    this._cache = new Cache({
        localPath: this._options.localPath,
        cachePath: this._options.cachePath,
        logger: this._logger
    });
    this._version = null;
    this._inited = false;
    this._remoteOnly = false;
    this._connected = false;
    this._cache.init().then(() => {
        // Initialize remote configs
        return this.initRemote();
    }).then(() => {
        // Create version watcher
        //TODO: Watch from exact index
        return this._etcd.watcher(path.join('/', this._namespace, this._project, this._profile, 'version')).then((watcher) => {
            this._watcher = watcher;
            watcher.on('change', (data) => {
                this._logger.info('Profile version changed to %s, loading new profile.', data.node.value);
                this.loadVersion(data.node.value).then(() => {
                    this._logger.info('New profile version %d loaded.', this._version);
                    this.emit('change');
                })
            })
        })
    }).then(() => {
        this._inited = true;
        this.emit('init');
    })
}

util.inherits(NgConf, events.EventEmitter);

NgConf.prototype.loadVersion = function (version) {
    return this._etcd.get(path.join('/', this._namespace, this._project, this._profile, 'versions', String(version)), {
        recursive: true
    }).then((data) => {
        this._logger.debug('Got config version %d data %s', version, data);
        return this._cache.sync(this.buildCacheItems(data.node));
    })
};

NgConf.prototype.initRemote = function () {
    return this._etcd.get(path.join('/', this._namespace, this._project, this._profile, 'version')).then((data) => {
        // Load current version
        this._version = Number(data.node.value);
        this._logger.info('Got current version %d, loading', this._version);
        return this.loadVersion(this._version).then(() => {
            this._logger.info('Version %d loaded.', this._version);
        });
    }).catch((err) => {
        if (err.errorCode === 100) {
            // Profile does not exist, initialize it.
            this._logger.info('Remote profile %s does not exist in project %s, initializing.', this._profile, this._namespace);
            let promises = [];
            let localConfigs = this._cache.getAll();
            if (!this._cache.getProfile(this._profile)) {
                throw new Error('Local profile does not exist.');
            }
            for (let profile in localConfigs) {
                let configs = localConfigs[profile];
                for (let name in configs) {
                    promises.push(this._etcd.set(path.join('/', this._namespace, this._project, profile, 'versions', '0', name), configs[name], {
                        prevExist: false
                    }).then((data) => {
                        this._logger.debug('Key %s set.', data.node.key);
                    }).catch((err) => {
                        if (err.errorCode !== 105) {
                            throw err;
                        }
                        this._logger.debug('Key %s has been set by other process, ignore.', err.cause);
                    }))
                }
                promises.push(this._etcd.set(path.join('/', this._namespace, this._project, profile, 'version'), '0', {
                    prevExist: false
                }).catch((err) => {
                    if (err.errorCode !== 105) {
                        throw err;
                    }
                    this._logger.debug('Version key %s has been initialized by other process, ignore.', err.cause);
                }).then((data) => {
                    this._version = 0;
                    this._logger.debug('Version key %s set.', data.node.key);
                }))
            }
            return Promise.all(promises).then(() => {
                this._logger.info('All remote profiles has been initialized.');
            })
        } else {
            throw err;
        }
    }).then(() => {
        this._logger.info('Remote profile initialized.');
        this._connected = true;
        this.emit('connected');
    }).catch((err) => {
        this._logger.warn('Failed to initialize remote profile, retry after 5s.');
        this._connected = false;
        this._cache.isProfileCached(this._profile).then((cached) => {
            if (cached) {
                this._logger.warn('This profile has been cached, use cached profile.');
                this._remoteOnly = false;
            } else {
                this._logger.warn('This profile has not been cached, reject all requests.');
                this._remoteOnly = true;
            }
            this._retryTimer = setTimeout(() => {
                this.initRemote();
            }, 5000);
        });
    })
};

NgConf.prototype.buildCacheItems = function (rootNode) {
    let cacheItems = {};
    cacheItems[this._profile] = {};
    let extract = (node) => {
        let result = [];
        if (node.nodes) {
            node.nodes.forEach((node) => {
                extract(node).forEach((r) => {
                    result.push(r);
                })
            });
        } else {
            result.push({
                name: node.key.substr(rootNode.key.length),
                value: node.value
            })
        }
        return result;
    };
    rootNode.nodes.forEach((node) => {
        extract(node).forEach((config) => {
            cacheItems[this._profile][config.name] = config.value;
        })
    });
    return cacheItems;
};

NgConf.prototype.raw = function (name) {
    if (!this._inited) {
        throw new Error('NgConf not initialized.');
    }
    if (!this._connected && this._remoteOnly) {
        throw new Error('Not initialized before and cannot connect to etcd');
    }
    let args = arguejs({
        name: String
    }, arguments);
    if (args.name.indexOf('/') !== 0) {
        args.name = '/' + args.name;
    }
    return this._cache.get(this._profile, args.name);
};

NgConf.prototype.json = function (name) {
    let args = arguejs({
        name: String
    }, arguments);
    return JSON.parse(this.raw(args.name));
};

module.exports = NgConf;


text:
package filodb.kafka

import java.lang.{Long => JLong}

import scala.collection.JavaConverters._
import scala.concurrent.Future

import com.typesafe.config.Config
import com.typesafe.scalalogging.StrictLogging
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.clients.producer.internals.DefaultPartitioner
import org.apache.kafka.common.serialization.{ByteArraySerializer, LongSerializer}

import filodb.core.{Response, Success}
import filodb.core.downsample.DownsamplePublisher

class KafkaDownsamplePublisher(downsampleConfig: Config) extends DownsamplePublisher with StrictLogging {

  private val kafkaConfig = propsFromConfig(downsampleConfig.getConfig("publisher-config.kafka"))

  private val topics: Map[Int, String] = downsampleConfig.getConfig("publisher-config.topics")
    .entrySet().asScala.map { e => e.getKey.toInt -> e.getValue.unwrapped().toString }.toMap

  private var producer: KafkaProducer[JLong, Array[Byte]] = _

  override def publish(shardNum: Int, resolution: Int, records: Seq[Array[Byte]]): Future[Response] = {
    topics.get(resolution) match {
      case Some(topic) =>
        records.foreach { bytes =>
          val rec = new ProducerRecord[JLong, Array[Byte]](topic, shardNum, shardNum.toLong: JLong,
            bytes)
          producer.send(rec)
        }
        Future.successful(Success)
      case None =>
        Future.failed(new IllegalArgumentException(s"Unregistered resolution $resolution"))
    }
  }

  def propsFromConfig(config: Config): Map[String, Object] = {

    val map = config.entrySet().asScala.map({ entry =>
      entry.getKey -> entry.getValue.unwrapped()
    }).toMap

    // immutable properties to be overwritten
    map ++ Map( "value.serializer" -> classOf[ByteArraySerializer],
                "key.serializer" -> classOf[LongSerializer],
                "partitioner.class" -> classOf[DefaultPartitioner])
  }

  override def start(): Unit = {
    logger.info(s"Starting Kafka Downsampling Publisher. Will be publishing to $topics with config: $kafkaConfig")
    producer = new KafkaProducer(kafkaConfig.asJava)
  }

  override def stop(): Unit = {
    logger.info("Stopping Kafka Downsampling Publisher")
    producer.close()
  }
}


text:
import { component, inject } from 'tsdi';
import * as vscode from 'vscode';
import { Git } from './git';
import { getConfiguration } from './helper';
import { Client, createClient } from './provider/client';
import { GitHubError } from './provider/github/api';
import { Issue, IssueComment } from './provider/issue';
import {
  Comment,
  MergeBody,
  MergeMethod,
  PullRequest,
} from './provider/pull-request';
import {
  CreatePullRequestBody,
  ListPullRequestsParameters,
  Repository,
} from './provider/repository';
import { User } from './provider/user';
import { getTokens } from './tokens';

@component
export class WorkflowManager {
  @inject({ name: 'vscode.ExtensionContext' })
  private readonly context!: vscode.ExtensionContext;

  @inject('vscode.OutputChannel')
  private readonly channel!: vscode.OutputChannel;

  @inject private readonly git!: Git;

  private providers: { [cwd: string]: Client } = {};

  private async connect(uri: vscode.Uri): Promise<Client> {
    const logger = (message: string) => this.log(message);
    const provider = await createClient(
      this.git,
      getTokens(this.context.globalState),
      uri,
      logger
    );
    try {
      await provider.test();
    } catch (e) {
      throw new Error(
        `Connection with ${provider.name} failed. Please make sure your git executable` +
          `is setup correct, and your token has enought access rights.`
      );
    }
    this.log(`Connected with provider ${provider.name}`);
    return provider;
  }

  private async getProvider(uri: vscode.Uri): Promise<Client> {
    if (!this.providers[uri.fsPath]) {
      this.providers[uri.fsPath] = await this.connect(uri);
    }
    return this.providers[uri.fsPath];
  }

  public resetProviders(): void {
    this.providers = {};
  }

  private log(message: string, obj?: any): void {
    const formatted =
      `${message} ` + (obj ? JSON.stringify(obj, undefined, ' ') : '');
    this.channel.appendLine(formatted);
    console.log(formatted);
  }

  public async canConnect(uri: vscode.Uri): Promise<true | Error> {
    try {
      await this.getProvider(uri);
      return true;
    } catch (e) {
      this.log(`Failed to connect to provider`, (e as Error).message);
      return e as Error;
    }
  }

  public async getRepository(uri: vscode.Uri): Promise<Repository> {
    const [owner, repository] = await this.git.getGitProviderOwnerAndRepository(
      uri
    );
    const provider = await this.getProvider(uri);
    return (await provider.getRepository(uri, `${owner}/${repository}`)).body;
  }

  public async getDefaultBranch(uri: vscode.Uri): Promise<string> {
    return (await this.getRepository(uri)).defaultBranch;
  }

  public async getEnabledMergeMethods(
    uri: vscode.Uri
  ): Promise<Set<MergeMethod>> {
    const repo = await this.getRepository(uri);
    const set = new Set<MergeMethod>();
    if (repo.allowMergeCommits) {
      set.add('merge');
    }
    if (repo.allowSquashCommits) {
      set.add('squash');
    }
    if (repo.allowRebaseCommits) {
      set.add('rebase');
    }
    return set;
  }

  public async getPullRequestForCurrentBranch(
    uri: vscode.Uri
  ): Promise<PullRequest | undefined> {
    const branch = await this.git.getCurrentBranch(uri);
    const list = (await this.listPullRequests(uri)).filter(
      (pr) => pr.sourceBranch === branch
    );
    if (list.length !== 1) {
      return undefined;
    }
    const repository = await this.getRepository(uri);
    return (await repository.getPullRequest(list[0].number)).body;
  }

  public async hasPullRequestForCurrentBranch(
    uri: vscode.Uri
  ): Promise<boolean> {
    return Boolean(await this.getPullRequestForCurrentBranch(uri));
  }

  public async createPullRequest(
    uri: vscode.Uri,
    upstream?: { owner: string; repository: string; branch: string }
  ): Promise<PullRequest | undefined> {
    if (await this.hasPullRequestForCurrentBranch(uri)) {
      return undefined;
    }
    const branch = await this.git.getCurrentBranch(uri);
    if (!branch) {
      throw new Error('No current branch');
    }
    const defaultBranch = await this.getDefaultBranch(uri);
    this.log(`Create pull request on branch '${branch}'`);
    const firstCommit = await this.git.getFirstCommitOnBranch(
      branch,
      defaultBranch,
      uri
    );
    this.log(`First commit on branch '${firstCommit}'`);
    const requestBody = await this.git.getPullRequestBody(firstCommit, uri);
    if (requestBody === undefined) {
      vscode.window.showWarningMessage(
        `For some unknown reason no pull request body could be build; Aborting operation`
      );
      return undefined;
    }

    const requestTitle = await this.getTitle(firstCommit, uri);
    if (requestTitle === undefined) {
      this.channel.appendLine(
        `No pull request title created; Aborting operation`
      );
      return undefined;
    }

    return this.createPullRequestFromData(
      {
        upstream,
        sourceBranch: branch,
        targetBranch: upstream ? upstream.branch : defaultBranch,
        title: requestTitle,
        body: requestBody,
      },
      uri
    );
  }

  private async getTitle(
    firstCommit: string,
    uri: vscode.Uri
  ): Promise<string | undefined> {
    const customTitle = getConfiguration('github', uri).customPullRequestTitle;
    if (customTitle) {
      const title = await vscode.window.showInputBox({
        prompt: 'Pull request title',
      });
      if (!title) {
        return undefined;
      }
      return title;
    }
    return this.git.getCommitMessage(firstCommit, uri);
  }

  public async createPullRequestFromData(
    {
      upstream,
      sourceBranch,
      targetBranch,
      title,
      body,
    }: {
      upstream?: { owner: string; repository: string };
      sourceBranch: string;
      targetBranch: string;
      title: string;
      body?: string;
    },
    uri: vscode.Uri
  ): Promise<PullRequest | undefined> {
    if (await this.hasPullRequestForCurrentBranch(uri)) {
      return undefined;
    }
    this.log(`Create pull request on branch '${sourceBranch}'`);
    const pullRequestBody: CreatePullRequestBody = {
      sourceBranch,
      targetBranch,
      title,
      body,
    };
    this.log('pull request body:', pullRequestBody);

    const getRepository = async () => {
      if (upstream) {
        const provider = await this.getProvider(uri);
        return (
          await provider.getRepository(
            uri,
            `${upstream.owner}/${upstream.repository}`
          )
        ).body;
      } else {
        return this.getRepository(uri);
      }
    };
    return this.doCreatePullRequest(await getRepository(), pullRequestBody);
  }

  private async doCreatePullRequest(
    repository: Repository,
    body: CreatePullRequestBody
  ): Promise<PullRequest> {
    try {
      return (await repository.createPullRequest(body)).body;
    } catch (e) {
      if (e instanceof GitHubError) {
        this.log('Create pull request error:', e.response);
      }
      throw e;
    }
  }

  public async updatePullRequest(
    pullRequest: PullRequest,
    uri: vscode.Uri
  ): Promise<void> {
    if (await this.hasPullRequestForCurrentBranch(uri)) {
      return undefined;
    }
    const branch = await this.git.getCurrentBranch(uri);
    if (!branch) {
      throw new Error('No current branch');
    }
    this.log(`Update pull request on branch '${branch}'`);
    const firstCommit = await this.git.getFirstCommitOnBranch(
      branch,
      pullRequest.targetBranch,
      uri
    );
    this.log(`First commit on branch '${firstCommit}'`);
    const requestBody = await this.git.getPullRequestBody(firstCommit, uri);
    if (requestBody === undefined) {
      vscode.window.showWarningMessage(
        `For some unknown reason no pull request body could be build; Aborting operation`
      );
      return undefined;
    }
    if (requestBody !== pullRequest.body) {
      await pullRequest.update({
        title: await this.git.getCommitMessage(firstCommit, uri),
        body: requestBody,
      });
    }
  }

  public async listPullRequests(uri: vscode.Uri): Promise<PullRequest[]> {
    const repository = await this.getRepository(uri);
    const parameters: ListPullRequestsParameters = {
      state: 'open',
    };
    return (await repository.getPullRequests(parameters)).body;
  }

  public async mergePullRequest(
    pullRequest: PullRequest,
    method: MergeMethod
  ): Promise<boolean | undefined> {
    try {
      if (pullRequest.mergeable) {
        const body: MergeBody = {
          mergeMethod: method,
        };
        const result = await pullRequest.merge(body);
        return result.body.merged;
      }
      return undefined;
    } catch (e) {
      if (!(e instanceof GitHubError)) {
        throw e;
      }
      this.log('Error while merging:', await e.response.json());
      // status 405 (method not allowed)
      // tslint:disable-next-line:comment-format
      // TODO...
      return false;
    }
  }

  public async getRepositoryUrl(uri: vscode.Uri): Promise<string> {
    const repository = await this.getRepository(uri);
    return repository.url;
  }

  public async getIssueUrl(
    uri: vscode.Uri,
    id: string
  ): Promise<string | undefined> {
    const hostname = await this.git.getGitHostname(uri);
    const [owner, repo] = await this.git.getGitProviderOwnerAndRepository(uri);
    return `https://${hostname}/${owner}/${repo}/issues/${id}`;
  }

  public async getGithubFileUrl(
    uri: vscode.Uri,
    file: string,
    line = 0,
    endLine = 0
  ): Promise<string> {
    const hostname = await this.git.getGitHostname(uri);
    const [owner, repo] = await this.git.getGitProviderOwnerAndRepository(uri);
    const branch = await this.git.getCurrentBranch(uri);
    const linuxStylePaths = file.replaceAll('\\', '/');
    const currentFile = linuxStylePaths.replace(/^\//, '');
    return `https://${hostname}/${owner}/${repo}/blob/${branch}/${currentFile}#L${
      line + 1
    }:L${endLine + 1}`;
  }

  public async getAssignees(uri: vscode.Uri): Promise<User[]> {
    const repository = await this.getRepository(uri);
    try {
      return (await repository.getUsers()).body;
    } catch (e) {
      this.log((e as Error).message);
      return [];
    }
  }

  public async addAssignee(
    pullRequest: PullRequest,
    name: string,
    uri: vscode.Uri
  ): Promise<void> {
    this.log('Add assignee', { pullRequest, name });
    const provider = await this.getProvider(uri);
    const user = await provider.getUserByUsername(name);
    await pullRequest.assign([user.body]);
  }

  public async removeAssignee(pullRequest: PullRequest): Promise<void> {
    this.log('Remove assignee', { pullRequest });
    await pullRequest.unassign();
  }

  public async requestReview(
    issue: number,
    name: string,
    uri: vscode.Uri
  ): Promise<void> {
    const repository = await this.getRepository(uri);
    const pullRequest = await repository.getPullRequest(issue);
    await pullRequest.body.requestReview({
      reviewers: [name],
    });
  }

  public async deleteReviewRequest(
    issue: number,
    name: string,
    uri: vscode.Uri
  ): Promise<void> {
    const repository = await this.getRepository(uri);
    const pullRequest = await repository.getPullRequest(issue);
    await pullRequest.body.cancelReview({
      reviewers: [name],
    });
  }

  public async issues(
    uri: vscode.Uri,
    state: 'closed' | 'all' | 'open' = 'all'
  ): Promise<Issue[]> {
    const repository = await this.getRepository(uri);
    const result = await repository.getIssues({
      sort: 'updated',
      direction: 'desc',
      state,
    });
    return result.body;
  }

  public async getPullRequestReviewComments(
    pullRequest: PullRequest
  ): Promise<Comment[]> {
    return (await pullRequest.getComments()).body;
  }

  public async getIssueComments(issue: Issue): Promise<IssueComment[]> {
    return (await issue.comments()).body;
  }
}


text:
package com.dassmeta.weixin.web.home.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.JDOMException;

import com.dassmeta.weixin.web.home.vo.recv.WxRecvEventMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvGeoMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvLinkMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvPicMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvTextMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvVideoMsg;
import com.dassmeta.weixin.web.home.vo.recv.WxRecvVoiceMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendMusicMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendNewsMsg;
import com.dassmeta.weixin.web.home.vo.send.WxSendTextMsg;

/**
 * 非线程安全 (应该每个请求创建一个) Created by 0x0001 on 14-9-28.
 */
public abstract class WeixinAbstractHandler {
	private final HttpServletRequest req;
	private final HttpServletResponse res;
	private final String TOKEN;
	private WxRecvMsg recvMsg;

	public WeixinAbstractHandler(HttpServletRequest req, HttpServletResponse res, String token) {
		this.req = req;
		this.res = res;
		this.TOKEN = token;
	}

	public void handler() {
		if (!isFromWeiXin()) {
			onNotFromWeixin();
			return;
		}

		if (isWeixinVerifyURL()) {
			renderText(getPara("echostr"));
			return;
		}

		try {
			WxRecvMsg msg = WeiXin.recv(req.getInputStream());
			handler(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ------------------------------------------------------------------- protected Methods

	protected void sendText(String content) {
		WxSendMsg send = WeiXin.builderSendByRecv(this.recvMsg);
		send(new WxSendTextMsg(send, content));
	}

	protected void sendNewsMsg(WxSendNewsMsg wxSendNewsMsg) {
		send(wxSendNewsMsg);
	}

	protected void sendMusicMsg(String title, String desc, String music, String hqMusic) {
		WxSendMsg send = WeiXin.builderSendByRecv(this.recvMsg);
		send(new WxSendMusicMsg(send, title, desc, music, hqMusic));
	}

	protected WxSendNewsMsg buildNewsMsg() {
		return new WxSendNewsMsg(WeiXin.builderSendByRecv(this.recvMsg));
	}

	protected void send(WxSendMsg send) {
		try {
			WeiXin.send(send, res.getOutputStream());
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected boolean isFromWeiXin() {
		if (verifySignature()) {
			return isWeixinVerifyURL() || isPost();
		}
		return false;
	}

	// ------------------------------------------------------------------- Abstract Methods

	/**
	 * 收到图片消息
	 *
	 * @param msg
	 */
	protected abstract void onPic(WxRecvPicMsg msg);

	/**
	 * 收到链接消息
	 *
	 * @param msg
	 */
	protected abstract void onLink(WxRecvLinkMsg msg);

	/**
	 * 收到地址消息
	 *
	 * @param msg
	 */
	protected abstract void onGeo(WxRecvGeoMsg msg);

	/**
	 * 收到文本消息
	 *
	 * @param msg
	 */
	protected abstract void onText(WxRecvTextMsg msg);

	/**
	 * 收到事件消息
	 *
	 * @param msg
	 */
	protected abstract void onEvent(WxRecvEventMsg msg);

	/**
	 * 语音消息
	 *
	 * @param msg
	 */
	protected abstract void onVoice(WxRecvVoiceMsg msg);

	/**
	 * 视频消息
	 *
	 * @param msg
	 */
	protected abstract void onVideo(WxRecvVideoMsg msg);

	/**
	 * 请求可能不是来自微信
	 */
	protected abstract void onNotFromWeixin();

	// -------------------------------------------------------- Get Set

	public HttpServletRequest getRequest() {
		return req;
	}

	public HttpServletResponse getResponse() {
		return res;
	}

	// -------------------------------------------------------- Private Methods

	private boolean isPost() {
		return "POST".equalsIgnoreCase(req.getMethod());
	}

	private boolean isWeixinVerifyURL() {
		return getPara("echostr") != null;
	}

	private boolean verifySignature() {
		String signature = getPara("signature");
		String timestamp = getPara("timestamp");
		String nonce = getPara("nonce");
		if (null != timestamp && null != nonce && null != signature) {
			return WeiXin.access(TOKEN, signature, timestamp, nonce);
		}
		return false;
	}

	private void handler(WxRecvMsg msg) {
		this.recvMsg = msg;
		if (msg instanceof WxRecvTextMsg) {
			onText((WxRecvTextMsg) msg);
		} else if (msg instanceof WxRecvEventMsg) {
			onEvent((WxRecvEventMsg) msg);
		} else if (msg instanceof WxRecvGeoMsg) {
			onGeo((WxRecvGeoMsg) msg);
		} else if (msg instanceof WxRecvLinkMsg) {
			onLink((WxRecvLinkMsg) msg);
		} else if (msg instanceof WxRecvPicMsg) {
			onPic((WxRecvPicMsg) msg);
		} else if (msg instanceof WxRecvVoiceMsg) {
			onVoice((WxRecvVoiceMsg) msg);
		} else if (msg instanceof WxRecvVideoMsg) {
			onVideo((WxRecvVideoMsg) msg);
		}
	}

	private String getPara(String key) {
		return req.getParameter(key);
	}

	private void renderText(String text) {
		try {
			PrintWriter pw = res.getWriter();
			pw.write(text);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


text:
<?php

namespace Okanjo\Marketplace\Tests;

use Okanjo\Common\Response;
use Okanjo\UnitTestConfig;

class ProductParcelTest extends \PHPUnit_Framework_TestCase {

    public function testPostProductWithParcel() {

        $api = ClientTest::getInstance(UnitTestConfig::$marketplace_user1, $session);

        $media = MediaTest::getMediaUpload($api);
        $data = ProductsTest::newProductData($media, $session->user->stores[0]->id);

        // LWH+weight
        $data['title'] .= ' with Dynamic Shipping';
        $data['parcel_length'] = 10.2;
        $data['parcel_width'] = 7.8;
        $data['parcel_height'] = 4.3;
        $data['parcel_weight'] = 21.2;
        $data['use_dynamic_shipping'] = 1;

        $r = $api->postProduct()->data($data)->execute();
        $this->assertEquals($data['parcel_length'], $r->data['parcel']['length']);
        $this->assertEquals($data['parcel_width'], $r->data['parcel']['width']);
        $this->assertEquals($data['parcel_height'], $r->data['parcel']['height']);
        $this->assertEquals($data['parcel_weight'], $r->data['parcel']['weight']);

//        print_r($r);

        $this->assertEquals(Response::HTTP_OK, $r->status);

    }

    public function testPostProductWithPredefinedParcel() {

        $api = ClientTest::getInstance(UnitTestConfig::$marketplace_user1, $session);

        $media = MediaTest::getMediaUpload($api);
        $data = ProductsTest::newProductData($media, $session->user->stores[0]->id);

        // LWH+weight
        $data['title'] .= ' with Dynamic Shipping';
        $data['parcel_predefined_package'] = "FlatRateEnvelope";
        $data['parcel_weight'] = 4.5;
        $data['use_dynamic_shipping'] = 1;

        $r = $api->postProduct()->data($data)->execute();

//        print_r($r);

        $this->assertEquals(Response::HTTP_OK, $r->status);
        $this->assertEquals($data['parcel_predefined_package'], $r->data['parcel']['predefined_package']);
        $this->assertEquals($data['parcel_weight'], $r->data['parcel']['weight']);

    }

    public function testPostProductWithVariantParcels() {

        $api = ClientTest::getInstance(UnitTestConfig::$marketplace_user1, $session);

        $media = MediaTest::getMediaUpload($api);
        $data = ProductsTest::newProductData($media, $session->user->stores[0]->id);

        // LWH+weight
        $data['title'] .= ' with Dynamic Shipping';
        $data['parcel_length'] = 5;
        $data['parcel_width'] = 5;
        $data['parcel_height'] = 5;
        $data['parcel_weight'] = 5;
        $data['use_dynamic_shipping'] = 1;

        $data['dimensions'] = ProductVariantTest::generateProductDimensions();
        $data['variants'] = array(
            'Color=Red&Size=S' => array(
                'stock' => 1,
                'parcel' => array(
                    'length' => 10.2,
                    'width' => 7.8,
                    'height' => 4.3,
                    'weight' => 21.2
                )
            ),
            'Color=Green&Size=S' => array(
                'stock' => 1,
                'parcel' => array(
                    'length' => 10,
                    'width' => 20,
                    'height' => 8,
                    'weight' => 41.2
                )
            ),
            'Color=Red&Size=M' => array(
                'stock' => 2,
                'parcel' => array(
                    'predefined_package' => 'Tube',
                    'weight' => 6.5
                )
            ),
            'Color=Green&Size=M' => array(
                'stock' => 0,
                'parcel' => array(
                    'predefined_package' => 'Parcel',
                    'weight' => 12
                )
            )
        );

        $r = $api->postProduct()->data($data)->execute();

        //print_r($r);

        $this->assertEquals(Response::HTTP_OK, $r->status);
        $this->assertEquals($data['variants']['Color=Red&Size=S'], $r->data['variants']['Color=Red&Size=S']);
        $this->assertEquals($data['variants']['Color=Green&Size=S'], $r->data['variants']['Color=Green&Size=S']);
        $this->assertEquals($data['variants']['Color=Red&Size=M'], $r->data['variants']['Color=Red&Size=M']);
        $this->assertEquals($data['variants']['Color=Green&Size=M'], $r->data['variants']['Color=Green&Size=M']);

    }

    public function testPostProductWithParcelThenRemoveParcel() {

        $api = ClientTest::getInstance(UnitTestConfig::$marketplace_user1, $session);

        $media = MediaTest::getMediaUpload($api);
        $data = ProductsTest::newProductData($media, $session->user->stores[0]->id);

        // LWH+weight
        $data['title'] .= ' with Dynamic Shipping';
        $data['parcel_length'] = 10.2;
        $data['parcel_width'] = 7.8;
        $data['parcel_height'] = 4.3;
        $data['parcel_weight'] = 21.2;
        $data['use_dynamic_shipping'] = 1;

        $r = $api->postProduct()->data($data)->execute();

//        print_r($r);

        $this->assertEquals(Response::HTTP_OK, $r->status);
        $id = $r->data['id'];

        // Turn off dynamic shipping
        $r = $api->putProductById($r->data['id'])->data(array(
            'use_dynamic_shipping' => 0
        ))->execute();

//        print_r($r);

        $this->assertEquals(Response::HTTP_OK, $r->status);

        $r = $api->getProductById($id)->execute();
        $this->assertEquals(Response::HTTP_OK, $r->status);
        $this->assertNull($r->data['parcel']);

    }

}


text:
#include "fbsetbg.h"

/*
 * Check the filename for the evil chars ` and $ and find the absolute path to
 * the file.
 */
int
cleanpath(char *filename)
{
        char            *temppath;

        if ((temppath = strdup(filename)) == NULL)
                errx(1, "can't allocate memory.");

        if (strlen(temppath) > MAXPATHLEN)
                errx(1, "try something shorter");

        if ((strchr(temppath, '`')) != NULL || (strchr(temppath, '$')) != NULL)
                errx(1, "Evil chars detected in %s", temppath);

        if (realpath(temppath, filename) == NULL)
                errx(1, "can't find the realpath of %s", filename);

        free(temppath);
        return (TRUE);
}


text:
'use strict';

const fs = require('fs').promises;
const {
  EVENT_TEST_PASS,
  EVENT_TEST_FAIL,
  EVENT_RUN_END,
  EVENT_TEST_PENDING,
  EVENT_SUITE_BEGIN,
  EVENT_SUITE_END,
} = require('mocha').Runner.constants;
const {Base} = require('mocha').reporters;
const {inherits} = require('mocha').utils;

/**
 *
 * @param {string} output
 * @param {string} filename
 * @return {Promise<void>}
 */
async function writeOutput(output, filename) {
  try {
    await fs.mkdir('result-reports');
    await fs.writeFile(filename, JSON.stringify(output, null, 4));
  } catch (error) {
    process.stdout.write(
      Base.color(
        'fail',
        `Could not write test result report to file '${filename}'`
      )
    );
  }
}

/**
 * Custom Mocha reporter for CI builds.
 * Mimics the structured karma reporter, but for Mocha.
 * @param {*} runner
 */
function JsonReporter(runner) {
  Base.call(this, runner);
  const testEvents = [];
  let suiteList = [];

  runner.on(EVENT_SUITE_BEGIN, function (suite) {
    suiteList.push(suite.title);
  });

  runner.on(EVENT_SUITE_END, function () {
    // We need a fresh copy every time we make a new suite,
    // so we can't use pop here (or the suiteList info of previous
    // tests would be changed)
    suiteList = suiteList.slice(0, -1);
  });

  [EVENT_TEST_PASS, EVENT_TEST_FAIL, EVENT_TEST_PENDING].forEach((event) => {
    runner.on(event, (test) => {
      testEvents.push({test, suiteList, event});
    });
  });

  runner.on(EVENT_RUN_END, async function () {
    const results = testEvents.map(({test, suiteList, event}) => ({
      description: test.title,
      suite: suiteList,
      success: event === EVENT_TEST_PASS,
      skipped: event === EVENT_TEST_PENDING,
      time: test.duration, // in milliseconds
    }));

    // Apparently we'll need to add a --no-exit flag when calling this
    // to allow for the asynchronous reporter.
    // See https://github.com/mochajs/mocha/issues/812
    await writeOutput({browsers: [{results}]}, `result-reports/e2e.json`);
  });
}

inherits(JsonReporter, Base);
module.exports = JsonReporter;


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Eisk.BusinessEntities;

namespace Eisk.Tests.UnitTests.PositiveTests
{
    [TestClass]
    public class Employee_Property_GetSet_Tests
    {
        [TestMethod]
        public void FirstName_ValidValueAssigned_ShouldGetSameValue()
        {
            //Arrange
            Employee employee = new Employee();
            const string EXPECTED_FIRST_NAME = "Ashraf";

            //Act
            employee.FirstName = EXPECTED_FIRST_NAME;

            //Assert
            string ACTUAL_FIRST_NAME = employee.FirstName;
            Assert.AreEqual(EXPECTED_FIRST_NAME, ACTUAL_FIRST_NAME, "First name has not been properly set.");
        }
    }
}


text:
using GuiLabs.Editor.Blocks;

namespace GuiLabs.Editor.Xml
{
	public class AttributeList : HContainerBlock
	{
		public AttributeList()
		{
			MyControl.Box.Margins.Left = 10;
			MyControl.Box.SetMouseSensitivityToMargins();
			this.Add(new TextBoxBlock());
		}
	}
}


text:
package generate

import (
	"context"
	"fmt"
	"os"
	"strings"

	"github.com/containers/common/pkg/config"
	"github.com/containers/podman/v3/libpod"
	"github.com/containers/podman/v3/libpod/define"
	"github.com/containers/podman/v3/libpod/image"
	"github.com/containers/podman/v3/pkg/rootless"
	"github.com/containers/podman/v3/pkg/specgen"
	"github.com/containers/podman/v3/pkg/util"
	spec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/generate"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// Get the default namespace mode for any given namespace type.
func GetDefaultNamespaceMode(nsType string, cfg *config.Config, pod *libpod.Pod) (specgen.Namespace, error) {
	// The default for most is private
	toReturn := specgen.Namespace{}
	toReturn.NSMode = specgen.Private

	// Ensure case insensitivity
	nsType = strings.ToLower(nsType)

	// If the pod is not nil - check shared namespaces
	if pod != nil && pod.HasInfraContainer() {
		podMode := false
		switch {
		case nsType == "pid" && pod.SharesPID():
			podMode = true
		case nsType == "ipc" && pod.SharesIPC():
			podMode = true
		case nsType == "uts" && pod.SharesUTS():
			podMode = true
		case nsType == "user" && pod.SharesUser():
			podMode = true
		case nsType == "net" && pod.SharesNet():
			podMode = true
		case nsType == "cgroup" && pod.SharesCgroup():
			podMode = true
		}
		if podMode {
			toReturn.NSMode = specgen.FromPod
			return toReturn, nil
		}
	}

	if cfg == nil {
		cfg = &config.Config{}
	}
	switch nsType {
	case "pid":
		return specgen.ParseNamespace(cfg.Containers.PidNS)
	case "ipc":
		return specgen.ParseNamespace(cfg.Containers.IPCNS)
	case "uts":
		return specgen.ParseNamespace(cfg.Containers.UTSNS)
	case "user":
		return specgen.ParseUserNamespace(cfg.Containers.UserNS)
	case "cgroup":
		return specgen.ParseCgroupNamespace(cfg.Containers.CgroupNS)
	case "net":
		ns, _, err := specgen.ParseNetworkNamespace(cfg.Containers.NetNS)
		return ns, err
	}

	return toReturn, errors.Wrapf(define.ErrInvalidArg, "invalid namespace type %q passed", nsType)
}

// namespaceOptions generates container creation options for all
// namespaces in a SpecGenerator.
// Pod is the pod the container will join. May be nil is the container is not
// joining a pod.
// TODO: Consider grouping options that are not directly attached to a namespace
// elsewhere.
func namespaceOptions(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.Pod, img *image.Image) ([]libpod.CtrCreateOption, error) {
	toReturn := []libpod.CtrCreateOption{}

	// If pod is not nil, get infra container.
	var infraCtr *libpod.Container
	if pod != nil {
		infraID, err := pod.InfraContainerID()
		if err != nil {
			// This is likely to be of the fatal kind (pod was
			// removed) so hard fail
			return nil, errors.Wrapf(err, "error looking up pod %s infra container", pod.ID())
		}
		if infraID != "" {
			ctr, err := rt.GetContainer(infraID)
			if err != nil {
				return nil, errors.Wrapf(err, "error retrieving pod %s infra container %s", pod.ID(), infraID)
			}
			infraCtr = ctr
		}
	}

	errNoInfra := errors.Wrapf(define.ErrInvalidArg, "cannot use pod namespace as container is not joining a pod or pod has no infra container")

	// PID
	switch s.PidNS.NSMode {
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithPIDNSFrom(infraCtr))
	case specgen.FromContainer:
		pidCtr, err := rt.LookupContainer(s.PidNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share pid namespace with")
		}
		toReturn = append(toReturn, libpod.WithPIDNSFrom(pidCtr))
	}

	// IPC
	switch s.IpcNS.NSMode {
	case specgen.Host:
		// Force use of host /dev/shm for host namespace
		toReturn = append(toReturn, libpod.WithShmDir("/dev/shm"))
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithIPCNSFrom(infraCtr))
		toReturn = append(toReturn, libpod.WithShmDir(infraCtr.ShmDir()))
	case specgen.FromContainer:
		ipcCtr, err := rt.LookupContainer(s.IpcNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share ipc namespace with")
		}
		toReturn = append(toReturn, libpod.WithIPCNSFrom(ipcCtr))
		toReturn = append(toReturn, libpod.WithShmDir(ipcCtr.ShmDir()))
	}

	// UTS
	switch s.UtsNS.NSMode {
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithUTSNSFrom(infraCtr))
	case specgen.FromContainer:
		utsCtr, err := rt.LookupContainer(s.UtsNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share uts namespace with")
		}
		toReturn = append(toReturn, libpod.WithUTSNSFrom(utsCtr))
	}

	// User
	switch s.UserNS.NSMode {
	case specgen.KeepID:
		if rootless.IsRootless() {
			toReturn = append(toReturn, libpod.WithAddCurrentUserPasswdEntry())

			// If user is not overridden, set user in the container
			// to user running Podman.
			if s.User == "" {
				_, uid, gid, err := util.GetKeepIDMapping()
				if err != nil {
					return nil, err
				}
				toReturn = append(toReturn, libpod.WithUser(fmt.Sprintf("%d:%d", uid, gid)))
			}
		} else {
			// keep-id as root doesn't need a user namespace
			s.UserNS.NSMode = specgen.Host
		}
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithUserNSFrom(infraCtr))
	case specgen.FromContainer:
		userCtr, err := rt.LookupContainer(s.UserNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share user namespace with")
		}
		toReturn = append(toReturn, libpod.WithUserNSFrom(userCtr))
	}

	if s.IDMappings != nil {
		toReturn = append(toReturn, libpod.WithIDMappings(*s.IDMappings))
	}
	if s.User != "" {
		toReturn = append(toReturn, libpod.WithUser(s.User))
	}
	if len(s.Groups) > 0 {
		toReturn = append(toReturn, libpod.WithGroups(s.Groups))
	}

	// Cgroup
	switch s.CgroupNS.NSMode {
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithCgroupNSFrom(infraCtr))
	case specgen.FromContainer:
		cgroupCtr, err := rt.LookupContainer(s.CgroupNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share cgroup namespace with")
		}
		toReturn = append(toReturn, libpod.WithCgroupNSFrom(cgroupCtr))
	}

	if s.CgroupParent != "" {
		toReturn = append(toReturn, libpod.WithCgroupParent(s.CgroupParent))
	}

	if s.CgroupsMode != "" {
		toReturn = append(toReturn, libpod.WithCgroupsMode(s.CgroupsMode))
	}

	// Net
	// TODO validate CNINetworks, StaticIP, StaticIPv6 are only set if we
	// are in bridge mode.
	postConfigureNetNS := !s.UserNS.IsHost()
	switch s.NetNS.NSMode {
	case specgen.FromPod:
		if pod == nil || infraCtr == nil {
			return nil, errNoInfra
		}
		toReturn = append(toReturn, libpod.WithNetNSFrom(infraCtr))
	case specgen.FromContainer:
		netCtr, err := rt.LookupContainer(s.NetNS.Value)
		if err != nil {
			return nil, errors.Wrapf(err, "error looking up container to share net namespace with")
		}
		toReturn = append(toReturn, libpod.WithNetNSFrom(netCtr))
	case specgen.Slirp:
		portMappings, err := createPortMappings(ctx, s, img)
		if err != nil {
			return nil, err
		}
		val := "slirp4netns"
		if s.NetNS.Value != "" {
			val = fmt.Sprintf("slirp4netns:%s", s.NetNS.Value)
		}
		toReturn = append(toReturn, libpod.WithNetNS(portMappings, postConfigureNetNS, val, nil))
	case specgen.Private:
		fallthrough
	case specgen.Bridge:
		if postConfigureNetNS && rootless.IsRootless() {
			return nil, errors.New("CNI networks not supported with user namespaces")
		}
		portMappings, err := createPortMappings(ctx, s, img)
		if err != nil {
			return nil, err
		}
		toReturn = append(toReturn, libpod.WithNetNS(portMappings, postConfigureNetNS, "bridge", s.CNINetworks))
	}

	if s.UseImageHosts {
		toReturn = append(toReturn, libpod.WithUseImageHosts())
	} else if len(s.HostAdd) > 0 {
		toReturn = append(toReturn, libpod.WithHosts(s.HostAdd))
	}
	if len(s.DNSSearch) > 0 {
		toReturn = append(toReturn, libpod.WithDNSSearch(s.DNSSearch))
	}
	if s.UseImageResolvConf {
		toReturn = append(toReturn, libpod.WithUseImageResolvConf())
	} else if len(s.DNSServers) > 0 {
		var dnsServers []string
		for _, d := range s.DNSServers {
			dnsServers = append(dnsServers, d.String())
		}
		toReturn = append(toReturn, libpod.WithDNS(dnsServers))
	}
	if len(s.DNSOptions) > 0 {
		toReturn = append(toReturn, libpod.WithDNSOption(s.DNSOptions))
	}
	if s.StaticIP != nil {
		toReturn = append(toReturn, libpod.WithStaticIP(*s.StaticIP))
	}
	if s.StaticMAC != nil {
		toReturn = append(toReturn, libpod.WithStaticMAC(*s.StaticMAC))
	}
	if s.NetworkOptions != nil {
		toReturn = append(toReturn, libpod.WithNetworkOptions(s.NetworkOptions))
	}

	return toReturn, nil
}

func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt *libpod.Runtime, pod *libpod.Pod) error {
	// PID
	switch s.PidNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.PidNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified PID namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.PIDNamespace), s.PidNS.Value); err != nil {
			return err
		}
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.PIDNamespace)); err != nil {
			return err
		}
	case specgen.Private:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.PIDNamespace), ""); err != nil {
			return err
		}
	}

	// IPC
	switch s.IpcNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.IpcNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified IPC namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.IPCNamespace), s.IpcNS.Value); err != nil {
			return err
		}
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.IPCNamespace)); err != nil {
			return err
		}
	case specgen.Private:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.IPCNamespace), ""); err != nil {
			return err
		}
	}

	// UTS
	switch s.UtsNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.UtsNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified UTS namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.UTSNamespace), s.UtsNS.Value); err != nil {
			return err
		}
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.UTSNamespace)); err != nil {
			return err
		}
	case specgen.Private:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.UTSNamespace), ""); err != nil {
			return err
		}
	}

	hostname := s.Hostname
	if hostname == "" {
		switch {
		case s.UtsNS.NSMode == specgen.FromPod:
			hostname = pod.Hostname()
		case s.UtsNS.NSMode == specgen.FromContainer:
			utsCtr, err := rt.LookupContainer(s.UtsNS.Value)
			if err != nil {
				return errors.Wrapf(err, "error looking up container to share uts namespace with")
			}
			hostname = utsCtr.Hostname()
		case (s.NetNS.NSMode == specgen.Host && hostname == "") || s.UtsNS.NSMode == specgen.Host:
			tmpHostname, err := os.Hostname()
			if err != nil {
				return errors.Wrap(err, "unable to retrieve hostname of the host")
			}
			hostname = tmpHostname
		default:
			logrus.Debug("No hostname set; container's hostname will default to runtime default")
		}
	}

	g.RemoveHostname()
	if s.Hostname != "" || s.UtsNS.NSMode != specgen.Host {
		// Set the hostname in the OCI configuration only if specified by
		// the user or if we are creating a new UTS namespace.
		// TODO: Should we be doing this for pod or container shared
		// namespaces?
		g.SetHostname(hostname)
	}
	if _, ok := s.Env["HOSTNAME"]; !ok && s.Hostname != "" {
		g.AddProcessEnv("HOSTNAME", hostname)
	}

	// User
	switch s.UserNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.UserNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified user namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.UserNamespace), s.UserNS.Value); err != nil {
			return err
		}
		// runc complains if no mapping is specified, even if we join another ns.  So provide a dummy mapping
		g.AddLinuxUIDMapping(uint32(0), uint32(0), uint32(1))
		g.AddLinuxGIDMapping(uint32(0), uint32(0), uint32(1))
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.UserNamespace)); err != nil {
			return err
		}
	case specgen.KeepID:
		var (
			err      error
			uid, gid int
		)
		s.IDMappings, uid, gid, err = util.GetKeepIDMapping()
		if err != nil {
			return err
		}
		g.SetProcessUID(uint32(uid))
		g.SetProcessGID(uint32(gid))
		fallthrough
	case specgen.Private:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.UserNamespace), ""); err != nil {
			return err
		}
		if s.IDMappings == nil || (len(s.IDMappings.UIDMap) == 0 && len(s.IDMappings.GIDMap) == 0) {
			return errors.Errorf("must provide at least one UID or GID mapping to configure a user namespace")
		}
		for _, uidmap := range s.IDMappings.UIDMap {
			g.AddLinuxUIDMapping(uint32(uidmap.HostID), uint32(uidmap.ContainerID), uint32(uidmap.Size))
		}
		for _, gidmap := range s.IDMappings.GIDMap {
			g.AddLinuxGIDMapping(uint32(gidmap.HostID), uint32(gidmap.ContainerID), uint32(gidmap.Size))
		}
	}

	// Cgroup
	switch s.CgroupNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.CgroupNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified cgroup namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.CgroupNamespace), s.CgroupNS.Value); err != nil {
			return err
		}
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.CgroupNamespace)); err != nil {
			return err
		}
	case specgen.Private:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.CgroupNamespace), ""); err != nil {
			return err
		}
	}

	// Net
	switch s.NetNS.NSMode {
	case specgen.Path:
		if _, err := os.Stat(s.NetNS.Value); err != nil {
			return errors.Wrap(err, "cannot find specified network namespace path")
		}
		if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), s.NetNS.Value); err != nil {
			return err
		}
	case specgen.Host:
		if err := g.RemoveLinuxNamespace(string(spec.NetworkNamespace)); err != nil {
			return err
		}
	case specgen.Private, specgen.NoNetwork:
		if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), ""); err != nil {
			return err
		}
	}

	if g.Config.Annotations == nil {
		g.Config.Annotations = make(map[string]string)
	}
	if s.PublishExposedPorts {
		g.Config.Annotations[define.InspectAnnotationPublishAll] = define.InspectResponseTrue
	} else {
		g.Config.Annotations[define.InspectAnnotationPublishAll] = define.InspectResponseFalse
	}

	return nil
}

// GetNamespaceOptions transforms a slice of kernel namespaces
// into a slice of pod create options. Currently, not all
// kernel namespaces are supported, and they will be returned in an error
func GetNamespaceOptions(ns []string) ([]libpod.PodCreateOption, error) {
	var options []libpod.PodCreateOption
	var erroredOptions []libpod.PodCreateOption
	if ns == nil {
		//set the default namespaces
		ns = strings.Split(specgen.DefaultKernelNamespaces, ",")
	}
	for _, toShare := range ns {
		switch toShare {
		case "cgroup":
			options = append(options, libpod.WithPodCgroups())
		case "net":
			options = append(options, libpod.WithPodNet())
		case "mnt":
			return erroredOptions, errors.Errorf("Mount sharing functionality not supported on pod level")
		case "pid":
			options = append(options, libpod.WithPodPID())
		case "user":
			continue
		case "ipc":
			options = append(options, libpod.WithPodIPC())
		case "uts":
			options = append(options, libpod.WithPodUTS())
		case "":
		case "none":
			return erroredOptions, nil
		default:
			return erroredOptions, errors.Errorf("Invalid kernel namespace to share: %s. Options are: net, pid, ipc, uts or none", toShare)
		}
	}
	return options, nil
}


text:
module Einvoice
  module Tradevan
    module Model
      class IssueData < Base
        VALID_OPTIONS_KEYS = [
          :companyUn,
          :orgId,
          :orgUn,
          :type,
          :saleIdentifier,
          :allowanceIdentifier,
          :transactionNumber,
          :transactionDate,
          :transactionTime,
          :total,
          :transactionSource,
          :transactionTarget,
          :invoiceNumber,
          :allowanceNumber,
          :allowanceDate,
          :allowanceExclusiveAmount,
          :allowanceTax,
          :allowancePaperReturned,
          :allowanceInclusiveAmount,
          :paperPrintMode,
          :invoiceAlarmMode,
          :invoicePaperReturned,
          :donate,
          :donationUnit,
          :carrierType,
          :carrierId,
          :carrierIdHidden,
          :buyerUn,
          :buyerTitle,
          :receiverName,
          :receiverAddrZip,
          :receiverAddrRoad,
          :receiverEmail,
          :receiverMobile,
          :allowaDeclaration,
          :idViewId,
          :memberId,
          :checkNumber,
          :invoiceDate,
          :invoiceTime,
          :texclusiveAmount,
          :oeclusiveAmount,
          :zexclusiveAmount,
          :tax,
          :mainRemark,
          :invoiceType,
          :itemList
        ].freeze

        attr_accessor *VALID_OPTIONS_KEYS

        validates :companyUn, presence: true, length: { is: 8 }
        validates :orgId, presence: true, length: { is: 5 }
        validates :orgUn, length: { is: 8 }, allow_blank: true
        validates :type, presence: true, length: { is: 1 }, inclusion: { in: %w(I R G H A) }
        validates :transactionNumber, presence: true, length: { maximum: 50 }
        validates :transactionDate, presence: true, length: { is: 8 }, format: { with: /\A\d{8}\Z/ }
        validates :transactionSource, length: { maximum: 50 } # Public Affair Firm presence: true
        validates :transactionTarget, length: { maximum: 50 } # Public Affair Firm presence: true
        validates :paperPrintMode, presence: true, length: { is: 1 }, inclusion: { in: %w(0 1 2 3 4) }
        validates :invoiceAlarmMode, presence: true, length: { is: 1 }, inclusion: { in: %w(0 1 2 3 4 5 6) }
        validates :invoicePaperReturned, presence: true, length: { maximum: 1 }, inclusion: { in: %w(Y N) }, invoicePaperReturned: true, if: proc { self.type == 'A' || (self.buyerUn.blank? && self.paperPrintMode.to_i != 0) }
        validates :carrierType, presence: true, length: { is: 6 }, if: proc { self.paperPrintMode.to_i == 0 && self.donate == 'N' && self.type != 'A' }
        validates :buyerUn, length: { is: 8 }, allow_blank: true, unless: proc { %w(A H).include?(self.type) }
        validates :buyerTitle, length: { maximum: 60 }, allow_blank: true, unless: proc { %w(A H).include?(self.type) }
        validates :idViewId, allow_blank: true, length: { maximum: 10 }
        validates :memberId, allow_blank: true, length: { maximum: 50 }
        validates :itemList, presence: true, itemList: true

        # Type I R G H
        validates :saleIdentifier, presence: true, length: { maximum: 100 }, saleIdentifier: true, if: proc { %w(I R G H).include?(self.type) }

        # Type A H
        validates :allowanceIdentifier, presence: true, length: { maximum: 100 }, allowanceIdentifier: true, if: proc { %w(A H).include?(self.type) }
        validates :allowanceExclusiveAmount, presence: true, length: { maximum: 20 }, if: proc { %w(A H).include?(self.type) }
        validates :allowanceTax, presence: true, length: { maximum: 8 }, if: proc { %w(A H).include?(self.type) }
        validates :allowancePaperReturned, presence: true, length: { is: 1 }, inclusion: { in: %w(Y N) }, if: proc { %w(A H).include?(self.type) }
        validates :allowanceInclusiveAmount, presence: true, length: { maximum: 20 }, if: proc { %w(A H).include?(self.type) }

        # Type R G H
        validates :invoiceNumber, presence: true, length: { is: 10 }, if: proc { %w(R G H).include?(self.type) }

        # Type H
        validates :allowanceNumber, presence: true, length: { is: 16 }, allowanceNumber: true, if: proc { self.type == 'H' }
        validates :allowanceDate, presence: true, length: { is: 8 }, format: { with: /\A\d{8}\Z/ }, if: proc { self.type == 'H' }

        # Type A
        validates :allowaDeclaration, allow_blank: true, length: { is: 6 }, format: { with: /\A\d{6}\Z/ }, if: proc { self.type == 'A' }

        # Type I R G
        validates :transactionTime, presence: true, length: { is: 8 }, format: { with: /\A\d{2}\:\d{2}\:\d{2}\Z/ }, if: proc { %w(I R G).include?(self.type) }
        validates :total, presence: true, length: { maximum: 20 }, total: true, if: proc { %w(I R G).include?(self.type) }
        validates :donate, presence: true, length: { is: 1 }, if: proc { %w(I R G).include?(self.type) && self.buyerUn.blank? && self.paperPrintMode.to_i == 0 }
        validates :donationUnit, presence: true, length: { maximum: 10 }, donationUnit: true, if: proc { %w(I R G).include?(self.type) && self.donate == 'Y' }
        validates :carrierId, presence: true, length: { maximum: 64 }, if: proc { %w(I R G).include?(self.type) && self.paperPrintMode.to_i == 0 && self.donate == 'N' }
        validates :carrierIdHidden, presence: true, length: { maximum: 64 }, if: proc { %w(I R G).include?(self.type) && self.paperPrintMode.to_i == 0 && self.donate == 'N' }

        # Type I R G A
        validates :receiverName, allow_blank: true, length: { maximum: 30 }, if: proc { %w(I R G A).include?(self.type) }
        validates :receiverAddrZip, allow_blank: true, length: { maximum: 5 }, if: proc { %w(I R G A).include?(self.type) }
        validates :receiverAddrRoad, allow_blank: true, length: { maximum: 100 }, if: proc { %w(I R G A).include?(self.type) }
        validates :receiverEmail, allow_blank: true, length: { maximum: 80 }, if: proc { %w(I R G A).include?(self.type) }
        validates :receiverMobile, allow_blank: true, length: { maximum: 15 }, if: proc { %w(I R G A).include?(self.type) }

        # Type I G
        validates :tax, allow_blank: true, length: { maximum: 20 }, if: proc { %w(I G).include?(self.type) }

        # Type G
        validates :checkNumber, allow_blank: true, length: { is: 4 }, if: proc { self.type == 'G' }
        validates :invoiceDate, allow_blank: true, length: { is: 8 }, if: proc { self.type == 'G' }
        validates :invoiceTime, allow_blank: true, length: { is: 8 }, if: proc { self.type == 'G' }
        validates :texclusiveAmount, allow_blank: true, length: { maximum: 20 }, if: proc { self.type == 'G' }
        validates :oeclusiveAmount, allow_blank: true, length: { maximum: 20 }, if: proc { self.type == 'G' }
        validates :zexclusiveAmount, allow_blank: true, length: { maximum: 20 }, if: proc { self.type == 'G' }
        validates :mainRemark, allow_blank: true, length: { maximum: 300 }, if: proc { self.type == 'G' }
        validates :invoiceType, allow_blank: true, length: { is: 2 }, inclusion: { in: %w(07 08) }, if: proc { self.type == 'G' }

        def payload
          serializable_hash(except: [:errors, :validation_context], include: [:itemList])
        end
      end
    end
  end
end


text:
.. _getting_started:

Getting Started
===============

Once you have installed **smif** (see :ref:`Installation and Configuration`), the quickest way
to get started is to use the sample project.

This section walks through setting up the sample project and extending it to configure models
and data.

If you prefer to start with an overview of the concepts that **smif** uses, these are
documented in :ref:`Concepts`.

Setup
-----

First, check smif has installed correctly by typing on the command line::

    $ smif
    usage: smif [-h] [-V] {setup,list,app,run} ...

    Command line tools for smif

    positional arguments:
    {setup,list,app,run}  available commands
        setup               Setup the project folder
        list                List available model runs
        app                 Open smif app
        run                 Run a model

    optional arguments:
    -h, --help            show this help message and exit
    -V, --version         show the current version of smif

You can also check which version is installed::

    $ smif --version
    smif 1.0

.. topic:: Command-line examples

    Commands that can be run in a terminal or command line are written prefixed with a $. This
    means you can copy the rest of the line to run - don't copy or type the $ itself.

Sample Project
--------------

Make a new directory and copy the sample project files there by running:

.. code:: console

    $ mkdir sample_project
    $ cd sample_project
    $ smif setup
    $ ls
    config/ data/ models/ planning/ results/ smif.log

On the command line, from within the project directory, type the following
command to list the available model runs::

    $ smif list
    energy_central
    energy_water_cp_cr

Note that the ``-d`` directory flag can be used to point to the project folder,
so you can run smif commands from any directory::

    $ smif list -d ~/projects/smif_sample_project/
    ...

smif also comes with a web-based user interface, which helps to manage project configurations.
The app can be started within a project configuration directory::

    $ smif app
    Opening smif app

    Copy/paste this URL into your web browser to connect:
        http://localhost:5000

    Close your browser then type Control-C here to quit.

Copy/paste or type the URL ``http://localhost:5000`` into a web browser to open the app.

.. <<This figure can be regenerated using the script in docs/gui/screenshot.sh>>
.. figure:: gui/welcome.png
    :target: _images/welcome.png
    :align: center
    :alt: alternate text
    :figclass: align-center

    The Smif app welcome screen

.. topic:: Hints

    [A] Model Runs - model configurations to run (or which have been run in the past)

    [B] System-of-Systems models -  integrated models which can be configured and run

    [C] Model Wrappers - individual models which can be composed into System-of-Systems models

    [D] Scenarios - exogenous data to provide inputs for models

    [E] Narratives - combinations of parameters to configure models

Run a model
-----------

To run a model run, type the following command::

    $ smif run energy_central
    Model run complete

Groups of model runs can run as a batches by using the ``-b`` flag and a path to a batch file::

    $ smif run -b batchfile

A batch file is a text file with a list of model run names, each on a new line, like::

    energy_central
    energy_water_cp_cr

Or, in the app, go to the "Job Runner" screen.

.. <<This figure can be regenerated using the script in docs/gui/screenshot.sh>>
.. figure:: gui/jobs-runner.png
    :target: _images/jobs-runner.png
    :align: center
    :alt: alternate text
    :figclass: align-center

    The Job Runner

.. csv-table::
   :header:  "#", "Section", "Notes"
   :widths: 3, 10, 45

   1, Stepper, "Displays the status of the Modelrun job"
   2, Modelrun Configuation, "Provides an overview of the Modelrun configuration"
   3, Controls, "Provides run settings and a start/stop button for the Modelrun job"
   4, Console Output, "Real-time output from the Job runner process"

.. topic:: Hints

    [A] Change the verbosity or output format of the Job Runner

    [B] Start / Restart or Stop a Modelrun Job

    [C] Save the console output to disk

    [D] Click on the down-arrow button to follow the console output as the job runs

View results
------------

Results are saved to the filesystem (depending on the storage interface used) in the
``results`` directory in the sample project.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
	<TITLE></TITLE>
	<META NAME="GENERATOR" CONTENT="OpenOffice.org 1.1.5  (Linux)">
	<META NAME="CREATED" CONTENT="20080430;10144900">
	<META NAME="CHANGED" CONTENT="20080518;10080400">
	<META NAME="ProgId" CONTENT="Word.Document">
	<META NAME="Originator" CONTENT="Microsoft Word 11">

============================================================================

Description
of ALICE Silicon Pixel Detector (SPD) Code (Rev. 1.00 — May 8, 2008
— D. Elia)

============================================================================

Content

1.      SPD
module geometrical description

2.      Raw
data format

3.      Simulation

4.      Local
reconstruction

5.      Calibration
and DAs

SPD
module geometrical description

The SPD module geometrical
description is managed by the AliITSsegmentationSPD class.

This offline module
corresponds to half of a single SPD basic unit (the half-stave which
is made of 2 ladders), so it corresponds to a single SPD ladder. In
total the SPD consists of 240 modules, 80 on the inner layer and 160
on the outer layer. The module is divided into 5 chips with the
corresponding sensor cells connected to 5 independent read-out
matrices.

The single pixel cell size
is 425 microns (local Z) x 50 microns (local X). Pixels at the
boundary between adjacent chips in the module are 625 microns wide in
Z.

The single chip has 32
columns (local Z) x 256 rows (local X).

The single module size is
6.96 cm (local Z) x 1.28 cm (local X). The sensor is 200 microns
thick. The read-out chip is 150 microns thick.

The module numbering
and the correspondence between online and offline conventions are
illustrated here.
In the AliITSRawStreamSPD
class the raw data is decoded and so-called digits
are extracted. Inside this class a module map matrix
(fgkDDLModuleMap[][]) is used:

This map specifies how the modules
are numbered (the rows of the matrix represent different equipment
ids, the columns have the 2 ladders of hs0, the 2 ladders of hs1, and
so on...).
Then one also needs to take the columns and rows
numbering into account.

To make the conversion between
online and offline coordinates there are the following static member
functions in AliITSRawStreamSPD:

=================================================================================================================

Raw
data format

The SPD raw data are decoded by the
AliITSRawStreamSPD class.

The SPD has equipment IDs
from 0 to 19, each corresponding to the readout of one half sector.
The geometrical map of the DDLs is illustrated here.

Each equipment starts
with the Equipment Header (15 32-bit words) of which the last
8 words are known as the Common Data Header, CDH (8 32-bit
words). After these headers, sometimes a Calibration Header
appears (for dedicated calibration runs). This extra header has
variable length, depending on the type of calibration scan. Finally,
there is the actual data words, i.e. which pixels are hit in the
event. This part has a variable length depending on the number of
hits. Further details on the various headers and the data word
formats can be found here.

=================================================================================================================

Simulation

The SPD digitization is
implemented in the AliITSsimulationSPD class and managed via
the AliITSDetTypeSim class.

It is based on the
following working scheme:

1) Hits --> SDigits
(AliSimulation::RunSDigitization)

-> AliITS::Hits2SDigits

->
AliITS::Hits2Predigits

->
AliITSsimulationSPD::SDigitiseModule

->
AliITSsimulationSPD::HitToSDigitFast

- read hits, gets
parameters for diffusion (temperature, thickness over bias voltage,
asymmetry of gaussian diffusion, etc.) and for electronic coupling
from OCDB

- apply electron cloud
diffusion (gaussian smearing) along z and r*phi

- eventually apply the
Lorentz drift to the electron cloud (by default null Lorentz drift)

- apply coupling between
adiacent pixels

->
AliITSsimulationSPD::RemoveDeadPixel

-  remove dead pixels
as stored in the calibration object

->
AliITSsimulationSPD::WriteSDigits

- write SDigits to file,
basically call AliITS::AddSumDigit (which calls
AliITSDetTypeSim::AddSumDigit) to write SDigits (AliITSpListItem) to
file

2) SDigits -->
Digits (AliSimulation::RunDigitization)

->
AliITSDigitizer::Exec

- load SDigits

->
AliITSsimulationSPD::FinishSDigitiseModule

- call
AliITSsimulationSPD::FrompListToDigits

- eventually add
electronic baseline and noise, perform the zero suppression and add
the digits to the list  (by calling AliITS::AddSimDigit)

A detailed
description of the SPD response model (in
AliITSsimulationSPD::HitToSDigitFast) can be found here
(ALICE-INT-2008-003 and references therein). The model parameters are
stored in two OCDB files under $ALICE_ROOT/ITS/Calib:

1) RespSPD: contains 1
AliITSresponseSPD object with parameters common to all the modules
(coupling type and diffusion asymmetry)

2) SPDDead: contains 1
TOjArray with 240 AliITSCalibrationSPD objects, i.e. 1
AliITSCalibrationSPD object for each module with the list of dead
pixels (see calibration section below) and the other parameters
needed to the response model (threshold, noise, coupling strength,
bias-over-voltage)

========================================================================================================================

Local
Reconstruction

The SPD local
reconstruction is implemented in AliITSClusterFinderV2SPD class
and managed via the AliITSDetTypeRec class.

It is based on the
following working scheme:

Cluster Finding
(AliReconstruction::RunLocalEventReconstruction)

->
AliITSReconstructor::Reconstruct

->
AliITSDetTypeRec::DigitsToRecPoints

- Based on the input data
(simulation digits or simulation/real raw data), there are two
possibilities:

   A)
RECONSTRUCTION FROM DIGITS

   ->
AliITSClusterFinderV2SPD::FindRawClusters

   - call
AliITSClusterFinderV2SPD::FindClustersSPD

   - build
AliBin array from digit tree

   - call
AliITSClusterFinderV2SPD::ClustersSPD

   B)
RECONSTRUCTION FROM RAW DATA

   ->
AliITSClusterFinderV2SPD::RawdataToClusters

   -
instantiate AliITSRawStreamSPD object

   - call
AliITSClusterFinderV2SPD::FindClustersSPD

   - build
AliBin array from raw data

   - call
AliITSClusterFinderV2SPD::ClustersSPD

-> AliITS
ClusterFinderV2SPD::ClustersSPD

- loop on dead pixels as
stored in the calibration objects and reset them (corresponding
AliBin elements)

- loop on AliBin elements
and:

1) find cluster
(FindCluster)

2) unfold cluster if
allowed (this is set via AliITSRecoParam, the default is unfolding
off)

3) calculate cluster
coordinates and sigmas

4) add cluster to cluster
array

===============================================================================================================================

Calibration
and DAs

For the SPD there are two types of processes, called
Detector Algoritms (DAs), running on the DAQ network to
produce output transported via the File Exchange Server (FXS)
to the Offline and Detector Control System (DCS)
networks. The following picture illustrates how the Online
Calibration scheme works:

In case a the calibration is performed
as a standalone scan. The raw data collected on the Local
Data Concentrators (LDCs) are analyzed. In case b the
calibration is performed on a regular physics run and the data
is analyzed online through the DATE monitoring functionality.
Further details on the types of runs and scans and a global overview
of the SPD calibration can be found here.

The so-called Shuttle brings
the output files from the FXS to DCS and Offline
networks. Here the data go through a second level of processing,
generally called preprocessing. Finally, the Offline Calibration
Database (OCDB) and the DCS Configuration Database are
updated.

The procedures also produce
so-called Reference Data, basically raw data summaries, which
can later be used offline to reconstruct the calibration output. This
may be useful for instance for debugging purposes. A Reference
Data Displayer (GUI) program has been developed to simplify the
analysis of the Reference Data.

The two top level classes
corresponding to Standalone Calibration Runs and Physics Runs are
ITSSPDSCANda and ITSSPDPHYSda respectively. The Offline
Preprocessing is implemented in the AliITSPreprocessorSPD
class. It takes care of saving the reference data and put information
relevant for the offline reconstruction (lists of dead and noisy
pixels) in the OCDB.

The calibration files in
the OCDB are stored in two directories under $ALICE_ROOT/ITS/Calib:

1)
SPDDead: contains 1 TOjArray with 240 AliITSCalibrationSPD objects,
i.e. 1 AliITSCalibrationSPD object for each module with the list of
dead pixels and some parameters needed to the response model

2) SPDNoisy:
conatins 1 TOjArray with 240
AliITSCalibrationSPD objects, i.e. 1 AliITSCalibrationSPD object for
each module with the list of noisy pixels

The noisy pixel
search is always based on one run only. There is a minimum number of
events required to do the search which is basically performed at the
level of one read-out chip (8192 pixels). The dead pixel search may
span several runs, in order to collect more statistics (which is
mandatory for the p-p runs). Also here there is a minimum number of
events required to even try to perform the search. The search
requires that a noisy pixel search has been done first. The noisy
pixels are then removed from the hit-maps before the dead pixel
search. Also the dead pixel search is basically performed on the
level of one read-out chip. For further details on the dead and noisy
pixel search see here.


text:
package org.apache.hedwig.client.loadtest;

import org.apache.commons.math3.distribution.IntegerDistribution;
import org.apache.commons.math3.distribution.UniformIntegerDistribution;

public class UniformDistMessageProvider extends MessageProvider {

    private IntegerDistribution distribution;
    public UniformDistMessageProvider(TopicProvider topicProvider, int messageSize,
                           LoadTestUtils ltUtil) {
        super(topicProvider, messageSize, ltUtil);
        if (topicProvider.numTopics() > 1) {
            this.distribution = new UniformIntegerDistribution(0, topicProvider.numTopics() - 1);
        } else {
            // This is a hack because UniformIntegerDistribution doesn't support (0,0)
            this.distribution = new UniformIntegerDistribution(0, 2) {
                @Override
                public int sample() {
                    return 0;
                }
            };
        }
    }

    @Override
    protected IntegerDistribution getDistribution() {
        return distribution;
    }
}


text:
package org.springframework.boot.autoconfigure.data.couchbase;

import org.junit.After;
import org.junit.Test;

import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration;
import org.springframework.boot.autoconfigure.couchbase.CouchbaseTestConfigurer;
import org.springframework.boot.autoconfigure.data.alt.couchbase.CityCouchbaseRepository;
import org.springframework.boot.autoconfigure.data.alt.couchbase.ReactiveCityCouchbaseRepository;
import org.springframework.boot.autoconfigure.data.couchbase.city.City;
import org.springframework.boot.autoconfigure.data.couchbase.city.ReactiveCityRepository;
import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link CouchbaseReactiveRepositoriesAutoConfiguration}.
 *
 * @author Alex Derkach
 */
public class CouchbaseReactiveRepositoriesAutoConfigurationTests {

	private AnnotationConfigApplicationContext context;

	@After
	public void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void couchbaseNotAvailable() {
		load(null);
		assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0);
	}

	@Test
	public void defaultRepository() {
		load(DefaultConfiguration.class);
		assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(1);
	}

	@Test
	public void imperativeRepositories() {
		load(DefaultConfiguration.class,
				"spring.data.couchbase.repositories.type=imperative");
		assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0);
	}

	@Test
	public void disabledRepositories() {
		load(DefaultConfiguration.class, "spring.data.couchbase.repositories.type=none");
		assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0);
	}

	@Test
	public void noRepositoryAvailable() {
		load(NoRepositoryConfiguration.class);
		assertThat(this.context.getBeansOfType(ReactiveCityRepository.class)).hasSize(0);
	}

	@Test
	public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
		load(CustomizedConfiguration.class);
		assertThat(this.context.getBeansOfType(ReactiveCityCouchbaseRepository.class))
				.isEmpty();
	}

	private void load(Class<?> config, String... environment) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		TestPropertyValues.of(environment).applyTo(context);
		if (config != null) {
			context.register(config);
		}
		context.register(PropertyPlaceholderAutoConfiguration.class,
				CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class,
				CouchbaseRepositoriesAutoConfiguration.class,
				CouchbaseReactiveDataAutoConfiguration.class,
				CouchbaseReactiveRepositoriesAutoConfiguration.class);
		context.refresh();
		this.context = context;
	}

	@Configuration
	@TestAutoConfigurationPackage(City.class)
	@Import(CouchbaseTestConfigurer.class)
	static class DefaultConfiguration {

	}

	@Configuration
	@TestAutoConfigurationPackage(EmptyDataPackage.class)
	@Import(CouchbaseTestConfigurer.class)
	protected static class NoRepositoryConfiguration {

	}

	@Configuration
	@TestAutoConfigurationPackage(CouchbaseReactiveRepositoriesAutoConfigurationTests.class)
	@EnableCouchbaseRepositories(basePackageClasses = CityCouchbaseRepository.class)
	@Import(CouchbaseDataAutoConfigurationTests.CustomCouchbaseConfiguration.class)
	protected static class CustomizedConfiguration {

	}

}


text:
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>CSS table model: initial table spacing</title>
  <style type="text/css">
   float { float: left; background: red; }
   table { display: table; }
   row { display: table-row; }
   cell { display: table-cell; background: green; color: white; text-align: center; }
  </style>
 </head>
 <body>
  <float xmlns="http://www.example.org/">
   <cell>THERE</cell>
   <row>
    <table>
     <cell>SHOULD B</cell>
     <cell>E N</cell>
     <cell>O RED</cell>
    </table>
   </row>
   <cell>ANYWHERE</cell>
  </float>
 </body>
</html>


text: package passlib


text:
namespace ash {
namespace test {

class TestShellDelegate : public ShellDelegate {
 public:
  TestShellDelegate();
  virtual ~TestShellDelegate();

  // Overridden from ShellDelegate:
  virtual bool IsUserLoggedIn() OVERRIDE;
  virtual bool IsSessionStarted() OVERRIDE;
  virtual void LockScreen() OVERRIDE;
  virtual void UnlockScreen() OVERRIDE;
  virtual bool IsScreenLocked() const OVERRIDE;
  virtual void Shutdown() OVERRIDE;
  virtual void Exit() OVERRIDE;
  virtual void NewTab() OVERRIDE;
  virtual void NewWindow(bool incognito) OVERRIDE;
  virtual void OpenFileManager(bool as_dialog) OVERRIDE;
  virtual void OpenCrosh() OVERRIDE;
  virtual void OpenMobileSetup(const std::string& service_path) OVERRIDE;
  virtual void RestoreTab() OVERRIDE;
  virtual bool RotatePaneFocus(Shell::Direction direction) OVERRIDE;
  virtual void ShowKeyboardOverlay() OVERRIDE;
  virtual void ShowTaskManager() OVERRIDE;
  virtual content::BrowserContext* GetCurrentBrowserContext() OVERRIDE;
  virtual void ToggleSpokenFeedback() OVERRIDE;
  virtual bool IsSpokenFeedbackEnabled() const OVERRIDE;
  virtual app_list::AppListViewDelegate* CreateAppListViewDelegate() OVERRIDE;
  virtual void StartPartialScreenshot(
      ScreenshotDelegate* screenshot_delegate) OVERRIDE;
  virtual LauncherDelegate* CreateLauncherDelegate(
      ash::LauncherModel* model) OVERRIDE;
  virtual SystemTrayDelegate* CreateSystemTrayDelegate(SystemTray* t) OVERRIDE;
  virtual UserWallpaperDelegate* CreateUserWallpaperDelegate() OVERRIDE;
  virtual aura::client::UserActionClient* CreateUserActionClient() OVERRIDE;
  virtual void OpenFeedbackPage() OVERRIDE;
  virtual void RecordUserMetricsAction(UserMetricsAction action) OVERRIDE;

 private:
  bool locked_;
  bool spoken_feedback_enabled_;

  DISALLOW_COPY_AND_ASSIGN(TestShellDelegate);
};

}  // namespace test
}  // namespace ash

#endif  // ASH_TEST_TEST_SHELL_DELEGATE_H_