text:
// 发布监控账号信息
Meteor.publish('monitors', function(filterKey, options) {
  check(filterKey, String);
  check(options, Object);

  if (!filterKey) {
    return Monitors.find({}, options);
  }

  var key = new RegExp(filterKey);
  // 由过滤关键字找到匹配的部门id
  var station = Stations.find({name: key}).fetch().map(function(e) {
    return e._id;
  });
  console.log('station selected: ' + JSON.stringify(station));
  var query = {};
  if (station.length) {
    query = {$or: [{'profile.name': key}, {stationId: {$in: station}}]};
  } else {
    query = {'profile.name': key};
  }
  // 由匹配的部门名称找到所有的账号的id,以及直接匹配用户名称的账号id
  var users = Meteor.users.find(query, options).fetch().map(function(e) {
    return e._id;
  });
  console.log('users selected: ' + JSON.stringify(users));
  query = {$or: [{senderId: {$in: users}}, {receiverId: {$in: users}}]};
  return Monitors.find(query, options);
});

// 发布消息
Meteor.publish('messages', function (query, options) {
  check(query, Object);
  check(options, Object);

  var selector = {};
  //var userId = Meteor.userId();
  var userId = this.userId;
  // 如果不是管理员用户,则只发布当前用户发出或收到的消息
  var user = Meteor.users.findOne(userId);
  //console.log('当前用户级别:' + user && user.grade);
  if (user && user.grade != 3) {
    selector.$or = [{creatorId: userId}, {receiverId: userId}];
  }
  var filterKey = query.filterKey;
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    if (selector.$or) {
      selector.$and = [
        {$or: selector.$or},
        {$or: [{headline: key}, {content: key}]}
      ];
    } else {
      selector.$or = [{headline: key}, {content: key}];
    }
  }
  query = _.omit(query, 'filterKey');
  selector = _.extend(selector, query);
  console.log('message find selector: ' + JSON.stringify(selector));
  return Messages.find(selector, options);
});

// 发布特定订单关联的资金收支记录
Meteor.publish('capitalsByOrder', function (query, options) {
  check(query, {orderId: String});
  check(options, Object);

  return Capitals.find(query, options);
});

// 发布资金收支记录
Meteor.publish('capitals', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);

  var query = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    // 从客户名单集合中找到名称匹配关键字的客户的_id
    var customer = Customers.find({name: key}).fetch();
    customer = customer.map(function (e) {
      return e._id;
    });
    // 从固定客户集合collections中找到名称匹配关键字的条目对应_id
    var employee = Employees.find({name: key}).fetch();
    //console.log('station: ' + JSON.stringify(station));
    employee = employee.map(function (e) {
      return e._id;
    });
    customer = customer.concat(employee);
    // 从员工集合employees中找出匹配关键字的条目对应_id
    query.$or = [
      {type: key}, {partnerId: key},
      {partnerId: {$in: customer}}, {comment: key}];
  }
  return Capitals.find(query, options);
});

// 发布特定订单关联的库存变更信息
Meteor.publish('deliveriesByOrder', function (query, options) {
  check(query, {orderId: String});
  check(options, Object);

  return Deliveries.find(query, options);
});

// 发布库存变更信息
Meteor.publish('deliveries', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);

  var query = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    /*
    // 从客户名单集合中找到名称匹配关键字的客户的_id
    var customer = Customers.find({name: key}).fetch();
    customer = customer.map(function (e) {
      return e._id;
    });
    // 从固定客户集合collections中找到名称匹配关键字的条目对应_id
    var employee = Employees.find({name: key}).fetch();
    //console.log('station: ' + JSON.stringify(station));
    employee = employee.map(function (e) {
      return e._id;
    });
    customer = customer.concat(employee);
    */
    // 从员工集合employees中找出匹配关键字的条目对应_id
    query.$or = [{type: key}, {comment: key}];
  }
  return Deliveries.find(query, options);
});

// 发布订单信息
Meteor.publish('orders', function (query, options) {
  // query可能包含filterKey和_id或period
  check(query, Object);
  check(options, Object);

  var selector = {};
  var user = Meteor.users.findOne(this.userId);
  if (!user) {
    return [];
  }

  // 验证用户权限
  if (user.grade != '3') {
    selector.stationId = user.stationId;
  }

  var _id = query._id;
  var filterKey = query.filterKey;
  if (_id) {
    selector = _id;
  } else if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    // 从客户名单集合中找到名称匹配关键字的客户的_id
    var customer = Customers.find({name: key}).fetch();
    customer = customer.map(function (e) {
      return e._id;
    });
    // 从销售分部collection中找到名称匹配关键字的销售分部对应_id
    var station = Stations.find({name: key}).fetch();
    //console.log('station: ' + JSON.stringify(station));
    station = station.map(function (e) {
      return e._id;
    });
    selector = {
      $or: [
        {code: key}, {type: key}, {customerId: {$in: customer}},
        {phone: key}, {address: key}, {stationId: {$in: station}},
        {status: key}, {comment: key}
      ]
    };
  } else if (query.hasOwnProperty('period')) {
    console.log('query period: ' + query['period']);
    selector = setTimeSpan(query['period']);
  } else if (filterKey === undefined) {
    selector = '';
  }
  return Orders.find(selector, options);
});

// 发布账号信息
Meteor.publish('accounts', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);

  //console.log('account: ' + this.userId);
  // 验证用户是否已经登录
  if (!this.userId) {
    // 用户未登录
    return [];
  }
  var user = Meteor.users.findOne(this.userId);
  if (!user || user.grade <= 1) {
    // 不是系统管理员和特权用户账号,则只发布当前登录用户的信息
    return Meteor.users.find(this.userId);
  }

  var selector = {};
  // 如果是特权用户而不是系统管理员账号,需要限制在对应部门内
  if (user.grade == 2) {
    selector.stationId = user.stationId;
  }
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    // 从销售分部collection中找到名称匹配关键字的销售分部对应_id
    var station = Stations.find({name: key}).fetch();
    //console.log('accounts publish, station: ' + JSON.stringify(station));
    station = station.map(function (e) {
      return e._id;
    });
    selector.$or = [
      {_id: this.userId}, {username: key},
      {nickname: key}, {emails: {$elemMatch: {address: key}}},
      {comment: key}, {stationId: {$in: station}}
    ];
  }
  //console.log('user count: ' + Meteor.users.find(selector, options).count());
  return Meteor.users.find(selector, options);
});

// 发布各国货币信息
Meteor.publish('currencies', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);
  var selector = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    selector = {
      $or: [
        {symbol: key}, {name: key}, {country: key},
        {rate: filterKey}, {memo: key}
      ]
    };
  }
  return Currencies.find(selector, options);
});

// 发布产品型号信息
Meteor.publish('products', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);
  var selector = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    selector = {
      $or: [
        {code: key}, {name: key}, {model: key}, {batch: key},
        {'price.value': parseFloat(filterKey)}, {'price.currency': key},
        {comment: key}, {memo: key}
      ]
    };
  }
  return Products.find(selector, options);
});

// 发布内部员工信息
Meteor.publish('employees', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);

  var selector = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    // 从销售分部collection中找到名称匹配关键字的销售分部对应_id
    var station = Stations.find({name: key}).fetch();
    //console.log('station: ' + JSON.stringify(station));
    station = station.map(function (e) {
      return e._id;
    });
    selector = {
      $or: [
        {code: key}, {name: key}, {sex: key}, {title: key}, {phone: key},
        {email: key}, {'salary.value': parseFloat(filterKey)},
        {'salary.currency': key}, {stationId: {$in: station}}, {memo: key}
      ]
    };
  }
  return Employees.find(selector, options);
});

// 发布客户名单信息
Meteor.publish('customers', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);
  var selector = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    selector = {
      $or: [
        {code: key}, {name: key}, {company: key}, {title: key},
        {phone: key}, {email: key}, {address: key}, {memo: key}
      ]
    };
  }
  return Customers.find(selector, options);
});

// 发布销售分部信息
Meteor.publish('stations', function (filterKey, options) {
  check(filterKey, String);
  check(options, Object);
  var selector = {};
  if (filterKey) {
    var key = new RegExp(filterKey, 'i');
    selector = {
      $or: [
        {code: key}, {name: key}, {manager: key},
        {address: key}, {comment: key}, {memo: key}
      ]
    };
  }
  return Stations.find(selector, options);
});

///////////////////////////////////////////////////
// 一下内容共参考,正式版将删除

Meteor.publish('posts', function (options) {
  check(options, {
    sort: Object,
    limit: Number
  });
  return Posts.find({}, options);
});

Meteor.publish('singlePost', function (id) {
  check(id, String);
  return Posts.find(id);
});

Meteor.publish('comments', function (postId) {
  check(postId, String);
  return Comments.find({postId: postId});
});

Meteor.publish('notifications', function () {
  return Notifications.find({userId: this.userId, read: false});
});


text:
import React       from 'react'
import { shallow } from 'enzyme'

import Money from '../index'

//-----------  Tests  -----------//

describe('<Money />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});

redpajama_set_name: RedPajamaGithub


text:
package org.ovirt.engine.core.common.utils;

public interface IObjectDescriptorContainer {
    boolean canUpdateField(Object obj, String fieldName, Enum<?> status);
}


text:
"""Hacks to handle subsetting of chromosomes for heterogeneity analysis.

This puts ugly chromosome naming assumptions that restrict heterogeneity estimations
to autosomal chromosomes in a single place.
"""
from bcbio import utils
from bcbio.bam import ref
from bcbio.distributed.transaction import file_transaction

def is_autosomal(chrom):
    """Keep chromosomes that are a digit 1-22, or chr prefixed digit chr1-chr22
    """
    try:
        int(chrom)
        return True
    except ValueError:
        try:
            int(str(chrom.replace("chr", "")))
            return True
        except ValueError:
            return False

def is_autosomal_or_x(chrom):
    return is_autosomal(chrom) or chrom in ["X", "chrX"]

def autosomal_or_x_coords(ref_file):
    out = []
    for contig in ref.file_contigs(ref_file):
        if is_autosomal_or_x(contig.name):
            out.append((contig.name, 0, contig.size))
    return out

def bed_to_standardonly(in_file, data, headers=None):
    out_file = "%s-stdchrs%s" % utils.splitext_plus(in_file)
    if not utils.file_exists(out_file):
        with file_transaction(data, out_file) as tx_out_file:
            with open(in_file) as in_handle:
                with open(tx_out_file, "w") as out_handle:
                    for line in in_handle:
                        if is_autosomal(line.split()[0]) or (headers and line.startswith(headers)):
                            out_handle.write(line)
    return out_file


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2014 Stephen Connolly.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>7</version>
  </parent>

  <groupId>io.github.stephenc.maven</groupId>
  <artifactId>rfmm-maven-plugin</artifactId>
  <version>1.1-SNAPSHOT</version>
  <packaging>maven-plugin</packaging>

  <name>Release From My Machine Maven Plugin</name>
  <description>
    If you have some secret resources that cannot be checked into source control,
    this plugin will ensure they are picked up when using the maven release plugin.
  </description>
  <url>http://stephenc.github.com/rfmm-maven-plugin</url>
  <inceptionYear>2014</inceptionYear>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>stephenc</id>
      <name>Stephen Connolly</name>
      <roles>
        <role>Developer</role>
      </roles>
    </developer>
  </developers>

  <prerequisites>
    <maven>2.2.1</maven>
  </prerequisites>

  <scm>
    <connection>scm:git:git://github.com/stephenc/rfmm-maven-plugin.git</connection>
    <developerConnection>scm:git:git@github.com:stephenc/rfmm-maven-plugin.git</developerConnection>
    <url>http://github.com/stephenc/rfmm-maven-plugin/tree/master/</url>
    <tag>HEAD</tag>
  </scm>
  <issueManagement>
    <system>github</system>
    <url>http://github.com/stephenc/rfmm-maven-plugin/issues</url>
  </issueManagement>

  <properties>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <project.build.outputEncoding>UTF-8</project.build.outputEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mavenVersion>2.2.1</mavenVersion>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-project</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.shared</groupId>
      <artifactId>maven-filtering</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-artifact</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-artifact-manager</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>${mavenVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-utils</artifactId>
      <version>3.0.15</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-interpolation</artifactId>
      <version>1.19</version>
    </dependency>

    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-container-default</artifactId>
      <version>1.0-alpha-9-stable-1</version>
    </dependency>
    <!-- dependencies to annotations -->
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>3.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>2.5</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-gpg-plugin</artifactId>
          <version>1.4</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-invoker-plugin</artifactId>
          <version>1.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.4</version>
        </plugin>
        <plugin>
          <artifactId>maven-plugin-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
          </configuration>
          <executions>
            <execution>
              <id>mojo-descriptor</id>
              <goals>
                <goal>descriptor</goal>
              </goals>
            </execution>
            <execution>
              <id>help-mojo</id>
              <goals>
                <goal>helpmojo</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.4.2</version>
          <configuration>
            <providerImplementations>
              <git>jgit</git>
            </providerImplementations>
          </configuration>
          <dependencies>
            <dependency>
              <groupId>org.apache.maven.scm</groupId>
              <artifactId>maven-scm-provider-jgit</artifactId>
              <version>1.9</version>
            </dependency>
          </dependencies>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
        </plugin>
        <plugin>
          <artifactId>maven-scm-plugin</artifactId>
          <version>1.9</version>
          <configuration>
            <providerImplementations>
              <git>jgit</git>
            </providerImplementations>
          </configuration>
          <dependencies>
            <dependency>
              <groupId>org.apache.maven.scm</groupId>
              <artifactId>maven-scm-provider-jgit</artifactId>
              <version>1.9</version>
            </dependency>
          </dependencies>
        </plugin>
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.16</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>mrm-maven-plugin</artifactId>
          <version>1.0-beta-1</version>
          <configuration>
            <propertyName>repository.proxy.url</propertyName>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
          <compilerArgument>-g</compilerArgument>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>mrm-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>start</goal>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-invoker-plugin</artifactId>
        <executions>
          <execution>
            <id>integration-test</id>
            <goals>
              <goal>install</goal>
              <goal>run</goal>
            </goals>
            <configuration>
              <!--<streamLogs>false</streamLogs>-->
              <!--<debug>true</debug>-->
            </configuration>
          </execution>
        </executions>
        <configuration>
          <projectsDirectory>src/it</projectsDirectory>
          <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
          <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
          <settingsFile>src/it/settings.xml</settingsFile>
          <showErrors>true</showErrors>
          <streamLogs>true</streamLogs>
          <postBuildHookScript>verify.bsh</postBuildHookScript>
          <filterProperties>
            <repository.proxy.url>${repository.proxy.url}</repository.proxy.url>
          </filterProperties>
          <mavenOpts>-Xmx256m</mavenOpts>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
[![Platform iOS](https://img.shields.io/badge/platform-iOS-blue.svg?style=flat)](http://developer.apple.com/ios)
[![Language](http://img.shields.io/badge/language-swift-orange.svg?style=flat)](https://developer.apple.com/swift)
[![Swift 3 Compatible](https://img.shields.io/badge/swift3-compatible-4BC51D.svg?style=flat)](https://swift.org/blog/swift-3-0-released/)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/yoha/Notes/blob/master/LICENSE)
[![Issues](https://img.shields.io/github/issues/yoha/Thoughtless.svg?style=flat)](https://github.com/yoha/Thoughtless/issues)

## An iOS app that lets user quickly jot down thoughts with Markdown support.

![NotesTableViewController](http://i.imgur.com/JCgRD1W.png)
![NonEmptyNotesViewController](http://i.imgur.com/jzkSqv2.png)
![MarkdownNotesWebViewController](http://i.imgur.com/JhMLKl6.png)

![MarkdownUserGuide](http://i.imgur.com/ZwuuL0u.png)
![EditNotesTableViewController](http://i.imgur.com/ykeO1DE.png)
![EmptyNotesViewController](http://i.imgur.com/fsIg0uY.png)

## Description

Perhaps you are often in a situation where you want to jot down a thought that crosses your mind as quickly as you can so that

1. You don't have to keep trying to remember it.
2. You can move on to anticipate the next stream of thoughts.

In those cases, Thoughtless, as its name implies, can help you store your thoughts quickly if you have a busy mind like I do.

#### Features:

- Immediate text entry mode every time you launch the app for a quick dump of thought.
- Text formatting via Markdown.
- Markdown's characters access on keyboard.
- Search your thoughts.
- Various swipe gestures for intuitive in-app navigation.

ps: Make sure your device has iCloud pre-enabled.

## Installation Instructions

1. Install [Xcode 8](https://developer.apple.com/xcode/)
2. Download [Thoughtless source code](https://github.com/yoha/Thoughtless/releases/latest)
3. Open `Thoughtless.xcworkspace` in Xcode
4. Open Xcode's Preferences -> Accounts -> add your Apple ID
5. In Xcode's project navigator, click Thoughtless on the very top and go to Targets list -> Thoughtless -> General -> Identity and add a word to the end of the entry in Bundle Identifier to make it unique. Also select your Apple ID in Signing -> Team
6. Connect your iPhone or iPad and select it in Xcode's Product menu -> Destination
7. Press CMD+R or Product -> Run to install Thoughtless

## Credits

3rd Party Libraries used in this app:
- [CFAlertViewController](https://github.com/Codigami/CFAlertViewController) by [Crowdfire](https://github.com/Codigami)
- [HidingNavigationBar](https://github.com/tristanhimmelman/HidingNavigationBar) by [Tristan Himmelman](https://github.com/tristanhimmelman)
- [IQKeyboardManager](https://github.com/hackiftekhar/IQKeyboardManager) by [Mohd Iftekhar Qurashi](https://github.com/hackiftekhar)
- [SwiftHEXColors](https://github.com/thii/SwiftHEXColors) by [Thi](https://github.com/thii)

Icons used in this app:
- [Thought Bubble](http://www.flaticon.com/free-icon/thought-bubble_65491) by [Freepik](http://www.flaticon.com/authors/freepik)
- Icon pack by [Icons8](http://icons8.com)

## License

MIT License

Copyright (c) 2017 Yohannes Wijaya. All respective rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Management.Automation;
using System.Security.Permissions;
using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.Azure.Commands.Automation.Model;

namespace Microsoft.Azure.Commands.Automation.Cmdlet
{
    /// <summary>
    /// Creates an azure automation Schedule.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureAutomationSchedule", DefaultParameterSetName = ByDaily)]
    [OutputType(typeof(Schedule))]
    public class NewAzureAutomationSchedule : AzureAutomationBaseCmdlet
    {
        /// <summary>
        /// The one time schedule parameter set.
        /// </summary>
        private const string ByOneTime = "ByOneTime";

        /// <summary>
        /// The daily schedule parameter set.
        /// </summary>
        private const string ByDaily = "ByDaily";

        /// <summary>
        /// The hourly schedule parameter set.
        /// </summary>
        private const string ByHourly = "ByHourly";

        /// <summary>
        /// Initializes a new instance of the <see cref="NewAzureAutomationSchedule"/> class.
        /// </summary>
        public NewAzureAutomationSchedule()
        {
            this.ExpiryTime = Constants.DefaultScheduleExpiryTime;
        }

        /// <summary>
        /// Gets or sets the schedule name.
        /// </summary>
        [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true,
            HelpMessage = "The schedule name.")]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the schedule start time.
        /// </summary>
        [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true,
            HelpMessage = "The schedule start time.")]
        [ValidateNotNull]
        public DateTime StartTime { get; set; }

        /// <summary>
        /// Gets or sets the schedule description.
        /// </summary>
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The schedule description.")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the switch parameter to create a one time schedule.
        /// </summary>
        [Parameter(ParameterSetName = ByOneTime, Mandatory = true, HelpMessage = "To create a one time schedule.")]
        public SwitchParameter OneTime { get; set; }

        /// <summary>
        /// Gets or sets the schedule expiry time.
        /// </summary>
        [Parameter(ParameterSetName = ByDaily, Mandatory = false, HelpMessage = "The schedule expiry time.")]
        [Parameter(ParameterSetName = ByHourly, Mandatory = false, HelpMessage = "The schedule expiry time.")]
        public DateTime ExpiryTime { get; set; }

        /// <summary>
        /// Gets or sets the daily schedule day interval.
        /// </summary>
        [Parameter(ParameterSetName = ByDaily, Mandatory = true, HelpMessage = "The daily schedule day interval.")]
        [ValidateRange(1, int.MaxValue)]
        public int DayInterval { get; set; }

        /// <summary>
        /// Gets or sets the hourly schedule hour interval.
        /// </summary>
        [Parameter(ParameterSetName = ByHourly, Mandatory = true, HelpMessage = "The hourly schedule hour interval.")]
        [ValidateRange(1, int.MaxValue)]
        public int HourInterval { get; set; }

        /// <summary>
        /// Execute this cmdlet.
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        protected override void AutomationExecuteCmdlet()
        {
            // Assume local time if DateTimeKind.Unspecified
            if (this.StartTime.Kind == DateTimeKind.Unspecified)
            {
                this.StartTime = DateTime.SpecifyKind(this.StartTime, DateTimeKind.Local);
            }

            if (this.ExpiryTime.Kind == DateTimeKind.Unspecified)
            {
                this.ExpiryTime = DateTime.SpecifyKind(this.ExpiryTime, DateTimeKind.Local);
            }

            if (this.OneTime.IsPresent)
            {
                // ByOneTime
                var oneTimeSchedule = new OneTimeSchedule
                {
                    Name = this.Name,
                    StartTime = this.StartTime,
                    Description = this.Description,
                    ExpiryTime = this.ExpiryTime
                };

                Schedule schedule = this.AutomationClient.CreateSchedule(this.AutomationAccountName, oneTimeSchedule);
                this.WriteObject(schedule);
            }
            else if (this.DayInterval >= 1)
            {
                // ByDaily
                var dailySchedule = new DailySchedule
                {
                    Name = this.Name,
                    StartTime = this.StartTime,
                    DayInterval = this.DayInterval,
                    Description = this.Description,
                    ExpiryTime = this.ExpiryTime
                };

                Schedule schedule = this.AutomationClient.CreateSchedule(this.AutomationAccountName, dailySchedule);
                this.WriteObject(schedule);
            }
            else if (this.HourInterval >= 1)
            {
                // ByHourly
                var hourlySchedule = new HourlySchedule
                {
                    Name = this.Name,
                    StartTime = this.StartTime,
                    HourInterval = this.HourInterval,
                    Description = this.Description,
                    ExpiryTime = this.ExpiryTime
                };

                Schedule schedule = this.AutomationClient.CreateSchedule(this.AutomationAccountName, hourlySchedule);
                this.WriteObject(schedule);
            }
        }
    }
}


text:
package jb5n.api.properties;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import jb5n.api.JB5nException;
import jb5n.api.JB5nException.Reason;
import jb5n.api.Message;
import jb5n.internal.MessageResourceVerification;

public class JB5nPropertiesSync {

    public static class JB5nPropertiesSyncResult {
        private List<String> missingResourceKeys = new LinkedList<String>();

        public List<String> getMissingResourceKeys() {
            return missingResourceKeys;
        }
    }

    public static <T> JB5nPropertiesSyncResult sync(Class<T> clazz, Locale locale, ClassLoader classLoader) {
        JB5nPropertiesSyncResult result = new JB5nPropertiesSyncResult();
        MessageResourceVerification.verify(clazz, locale, classLoader);
        String resourceBundleName = JB5nPropertiesInvocationHandler.deriveResourceBundleName(clazz);
        ResourceBundle resourceBundle = null;
        try {
            resourceBundle = ResourceBundle.getBundle(resourceBundleName, locale, classLoader);
        } catch (MissingResourceException e) {
            throw new JB5nException(Reason.MissingResource, String.format("Resource bundle '%s' is missing: %s.", resourceBundleName, e.getMessage()), e);
        }
        List<String> missingResourceKeys = result.getMissingResourceKeys();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            Message messageAnnotationFromMethod = method.getAnnotation(Message.class);
            String resourceKey = JB5nPropertiesInvocationHandler.deriveResourceKey(methodName, messageAnnotationFromMethod);
            try {
                resourceBundle.getString(resourceKey);
            } catch (MissingResourceException e) {
                missingResourceKeys.add(resourceKey);
            }
        }
        return result;
    }
}


text:
#ifndef STDLIB_RANDOM_BASE_RANDI_H
#define STDLIB_RANDOM_BASE_RANDI_H

// Note: keep project includes in alphabetical order...
#include <stdarg.h>
#include "stdlib/random/base.h"

/*
* If C++, prevent name mangling so that the compiler emits a binary file having undecorated names, thus mirroring the behavior of a C compiler.
*/
#ifdef __cplusplus
extern "C" {
#endif

/**
* Enumeration of pseudorandom number generators for generating integer values.
*/
enum STDLIB_BASE_RANDOM_RANDI_PRNG {
	// Linear congruential pseudorandom number generator (LCG):
	STDLIB_BASE_RANDOM_RANDI_MINSTD = 0,

	// Linear congruential pseudorandom number generator (LCG) with shuffled output:
	STDLIB_BASE_RANDOM_RANDI_MINSTD_SHUFFLE = 1,

	// 32-bit Mersenne Twister pseudorandom number generator:
	STDLIB_BASE_RANDOM_RANDI_MT19937 = 2
};

/**
* Returns a pointer to a dynamically allocated PRNG.
*/
struct BasePRNGObject * stdlib_base_random_randi_allocate( const int nargs, ... );

/**
* Returns a pseudorandom integer.
*/
uint64_t stdlib_base_random_randi( struct BasePRNGObject *obj );

/**
* Frees a PRNG's allocated memory.
*/
void stdlib_base_random_randi_free( struct BasePRNGObject *obj );

#ifdef __cplusplus
}
#endif

#endif // !STDLIB_RANDOM_BASE_RANDI_H


text:
<?php

namespace Facebook\Helpers;

use Facebook\Entities\FacebookApp;
use Facebook\Entities\SignedRequest;
use Facebook\Entities\AccessToken;
use Facebook\FacebookClient;

/**
 * Class FacebookSignedRequestFromInputHelper
 * @package Facebook
 */
abstract class FacebookSignedRequestFromInputHelper
{

  /**
   * @var SignedRequest|null The SignedRequest entity.
   */
  protected $signedRequest;

  /**
   * @var FacebookApp The FacebookApp entity.
   */
  protected $app;

  /**
   * @var string|null Random string to prevent CSRF.
   */
  public $state;

  /**
   * Initialize the helper and process available signed request data.
   *
   * @param FacebookApp $app The FacebookApp entity.
   */
  public function __construct(FacebookApp $app)
  {
    $this->app = $app;

    $this->instantiateSignedRequest();
  }

  /**
   * Instantiates a new SignedRequest entity.
   *
   * @param string|null
   */
  public function instantiateSignedRequest($rawSignedRequest = null)
  {
    $rawSignedRequest = $rawSignedRequest ?: $this->getRawSignedRequest();

    if (!$rawSignedRequest) {
      return;
    }

    $this->signedRequest = new SignedRequest($rawSignedRequest, $this->state, $this->app->getSecret());
  }

  /**
   * Returns an AccessToken entity from the signed request.
   *
   * @param FacebookClient $client The Facebook client.
   *
   * @return AccessToken|null
   *
   * @throws \Facebook\Exceptions\FacebookSDKException
   */
  public function getAccessToken(FacebookClient $client)
  {
    if ($this->signedRequest && $this->signedRequest->hasOAuthData()) {
      $code = $this->signedRequest->get('code');
      $accessToken = $this->signedRequest->get('oauth_token');

      if ($code && !$accessToken) {
        return AccessToken::getAccessTokenFromCode($code, $this->app, $client);
      }

      $expiresAt = $this->signedRequest->get('expires', 0);
      return new AccessToken($accessToken, $expiresAt);
    }
    return null;
  }

  /**
   * Returns the SignedRequest entity.
   *
   * @return SignedRequest|null
   */
  public function getSignedRequest()
  {
    return $this->signedRequest;
  }

  /**
   * Returns the user_id if available.
   *
   * @return string|null
   */
  public function getUserId()
  {
    return $this->signedRequest ? $this->signedRequest->getUserId() : null;
  }

  /**
   * Get raw signed request from input.
   *
   * @return string|null
   */
  abstract public function getRawSignedRequest();

  /**
   * Get raw signed request from GET input.
   *
   * @return string|null
   */
  public function getRawSignedRequestFromGet()
  {
    if (isset($_GET['signed_request'])) {
      return $_GET['signed_request'];
    }

    return null;
  }

  /**
   * Get raw signed request from POST input.
   *
   * @return string|null
   */
  public function getRawSignedRequestFromPost()
  {
    if (isset($_POST['signed_request'])) {
      return $_POST['signed_request'];
    }

    return null;
  }

  /**
   * Get raw signed request from cookie set from the Javascript SDK.
   *
   * @return string|null
   */
  public function getRawSignedRequestFromCookie()
  {
    if (isset($_COOKIE['fbsr_' . $this->app->getId()])) {
      return $_COOKIE['fbsr_' . $this->app->getId()];
    }
    return null;
  }

}


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using TournamentTracker.Data;

namespace TournamentTracker.Data.Migrations
{
    [DbContext(typeof(TournamentTrackerDbContext))]
    [Migration("20160612041902_columnRenames")]
    partial class columnRenames
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.0-rc2-20896")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
                {
                    b.Property<string>("Id");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Name")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedName")
                        .HasName("RoleNameIndex");

                    b.ToTable("AspNetRoles");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("RoleId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("RoleId");

                    b.ToTable("AspNetRoleClaims");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserClaims");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
                {
                    b.Property<string>("LoginProvider");

                    b.Property<string>("ProviderKey");

                    b.Property<string>("ProviderDisplayName");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("LoginProvider", "ProviderKey");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserLogins");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("RoleId");

                    b.HasKey("UserId", "RoleId");

                    b.HasIndex("RoleId");

                    b.HasIndex("UserId");

                    b.ToTable("AspNetUserRoles");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("LoginProvider");

                    b.Property<string>("Name");

                    b.Property<string>("Value");

                    b.HasKey("UserId", "LoginProvider", "Name");

                    b.ToTable("AspNetUserTokens");
                });

            modelBuilder.Entity("TournamentTracker.Models.ApplicationUser", b =>
                {
                    b.Property<string>("Id");

                    b.Property<int>("AccessFailedCount");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Email")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<bool>("EmailConfirmed");

                    b.Property<bool>("LockoutEnabled");

                    b.Property<DateTimeOffset?>("LockoutEnd");

                    b.Property<string>("NormalizedEmail")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedUserName")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("PasswordHash");

                    b.Property<string>("PhoneNumber");

                    b.Property<bool>("PhoneNumberConfirmed");

                    b.Property<double>("PlayerElo");

                    b.Property<int>("PlayerLoses");

                    b.Property<string>("PlayerName");

                    b.Property<int>("PlayerWins");

                    b.Property<string>("SecurityStamp");

                    b.Property<bool>("TwoFactorEnabled");

                    b.Property<string>("UserName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedEmail")
                        .HasName("EmailIndex");

                    b.HasIndex("NormalizedUserName")
                        .HasName("UserNameIndex");

                    b.ToTable("AspNetUsers");
                });

            modelBuilder.Entity("TournamentTracker.Models.Challenge", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("MatchId");

                    b.Property<string>("ReceivingPlayerId");

                    b.Property<int>("ReceivingPlayerStatus");

                    b.Property<string>("SendingPlayerId");

                    b.Property<int>("SendingPlayerStatus");

                    b.Property<int>("Type");

                    b.HasKey("Id");

                    b.HasIndex("MatchId");

                    b.HasIndex("ReceivingPlayerId");

                    b.HasIndex("SendingPlayerId");

                    b.ToTable("Challenges");
                });

            modelBuilder.Entity("TournamentTracker.Models.Match", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<DateTime?>("CompletionDate");

                    b.Property<string>("MatchWinnerId");

                    b.Property<string>("PlayerOneId");

                    b.Property<int>("PlayerOneScore");

                    b.Property<string>("PlayerTwoId");

                    b.Property<int>("PlayerTwoScore");

                    b.Property<int?>("Status");

                    b.HasKey("Id");

                    b.HasIndex("PlayerOneId");

                    b.HasIndex("PlayerTwoId");

                    b.ToTable("Matches");
                });

            modelBuilder.Entity("TournamentTracker.Models.Notification", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Message");

                    b.Property<string>("ReceivingPlayerId");

                    b.Property<string>("SendingPlayerId");

                    b.Property<int>("Status");

                    b.HasKey("Id");

                    b.HasIndex("ReceivingPlayerId");

                    b.HasIndex("SendingPlayerId");

                    b.ToTable("Notifications");
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
                        .WithMany()
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
                {
                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
                {
                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
                {
                    b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
                        .WithMany()
                        .HasForeignKey("RoleId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("TournamentTracker.Models.Challenge", b =>
                {
                    b.HasOne("TournamentTracker.Models.Match")
                        .WithMany()
                        .HasForeignKey("MatchId");

                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("ReceivingPlayerId");

                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("SendingPlayerId");
                });

            modelBuilder.Entity("TournamentTracker.Models.Match", b =>
                {
                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("PlayerOneId");

                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("PlayerTwoId");
                });

            modelBuilder.Entity("TournamentTracker.Models.Notification", b =>
                {
                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("ReceivingPlayerId");

                    b.HasOne("TournamentTracker.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("SendingPlayerId");
                });
        }
    }
}


text:
using namespace tiledb;

TEST_CASE("Status: Test ok") {
  Status st = Status::Ok();
  CHECK(st.ok());
  st = Status::Error("err msg");
  CHECK(!st.ok());
}

TEST_CASE("Status: Test code and message") {
  Status ok = Status::Ok();
  CHECK(StatusCode::Ok == ok.code());

  Status err = Status::Error("err msg");
  CHECK(StatusCode::Error == err.code());
  CHECK_THAT(err.message(), Catch::Equals("err msg"));
}

TEST_CASE("Status: Test to_string") {
  Status ok = Status::Ok();
  CHECK_THAT(ok.to_string(), Catch::Equals("Ok"));

  Status err = Status::Error("err msg");
  CHECK_THAT(err.to_string(), Catch::Equals("Error: err msg"));
}

TEST_CASE("Status: Test code_to_string") {
  Status ok = Status::Ok();
  CHECK_THAT(ok.code_to_string(), Catch::Equals("Ok"));

  Status err = Status::Error("err message");
  CHECK_THAT(err.code_to_string(), Catch::Equals("Error"));
}

TEST_CASE("Status: Test posix_code") {
  Status st = Status::Ok();
  // check that posix code is < 0 by default
  CHECK(st.posix_code() == -1);

  st = Status::Error("err msg");
  CHECK(st.posix_code() == -1);
}


text:
Design
------------

.. toctree::
  :maxdepth: 1

  motivation/index_en.rst
  execution/index_en.rst
  concepts/index_en.rst
  data_type/index_en.rst
  memory/index_en.rst
  muti_devices/index_en.rst
  dynamic_rnn/index_en.rst
  concurrent/index_en.rst
  algorithm/index_en.rst
  network/index_en.rst
  modules/index_en.rst
  interface/index_en.rst
  dist_train/index_en.rst


text:
namespace IntervalOfNunbers
{
    using System;

    class Entry
    {
        static void Main(string[] args)
        {
            int start = int.Parse(Console.ReadLine());
            int finish = int.Parse(Console.ReadLine());

            if (finish < start)
            {
                int temp = finish;
                finish = start;
                start = temp;
            }

            for (int i = start; i <= finish; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}


text:
class Deck
  require_relative 'card'
  attr_accessor :cards # for testing. find a better way

  def initialize
    @cards = _cards
    @used_cards = []
  end

  def sample num
    @cards.sample num
  end

  def remove cards
    used cards
  end

  def self.starting_size
    81
  end

  def used(cards)
    @used_cards << cards
    _remove_from_available_cards cards
 end

  def _remove_from_available_cards(cards)
    @cards = @cards - cards
  end

  def draw_cards(num)
    cards = @cards.sample num
    _remove_from_available_cards cards
    @used_cards << cards
    cards
  end

  def _cards
    Card::Number.map do|n|
      Card::Symbol.constants.map do|sy|
        Card::Shading.constants.map do|sh|
          Card::Color.constants.map do|c|
            Card.new(n, sy, sh, c)
          end
        end
      end
    end.flatten
  end
end


text:
<?php

require '../classes/Floorplanner.php';
require 'config.php';

session_start();

$fp = Floorplanner::connect($config['api_key']);

$page = (empty($_GET['page'])) ? 1 : intval($_GET['page']);
if ($page < 1) $page = 1;

$user  = $fp->getUser($_GET['user_id']);
$projects = $user->getProjects();
?>

 User info

 E-mail: <a href="mailto:<?=htmlspecialchars($user->email)?>"><?=htmlspecialchars($user->email)?>

 Projects

<?php foreach ($projects as $project) : ?>

<a href="project.php?project_id=<?=$project->id?>"><?=$project->name?>

<?php endforeach; ?>


text:
package main

import (
	"fmt"
	"os"
	"path"
	"sync"
	"testing"
	"time"

	storage "github.com/01org/ciao/ciao-storage"
	"github.com/01org/ciao/payloads"
	"github.com/01org/ciao/ssntp"
	"github.com/01org/ciao/testutil"
	"gopkg.in/yaml.v2"
)

var standardCfg = vmConfig{
	Cpus:        2,
	Mem:         370,
	Disk:        8000,
	Instance:    "testInstance",
	Image:       "testImage",
	Legacy:      true,
	VnicMAC:     "02:00:e6:f5:af:f9",
	VnicIP:      "192.168.8.2",
	ConcIP:      "192.168.42.21",
	SubnetIP:    "192.168.8.0/21",
	TennantUUID: "67d86208-000-4465-9018-fe14087d415f",
	ConcUUID:    "67d86208-b46c-4465-0000-fe14087d415f",
	VnicUUID:    "67d86208-b46c-0000-9018-fe14087d415f",
}

// instanceTestState implements virtualizer and serverConn
type instanceTestState struct {
	t               *testing.T
	instance        string
	statsArray      [3]int
	sf              payloads.ErrorStopFailure
	stf             payloads.ErrorStartFailure
	df              payloads.ErrorDeleteFailure
	rf              payloads.ErrorRestartFailure
	avf             payloads.ErrorAttachVolumeFailure
	dvf             payloads.ErrorDetachVolumeFailure
	connect         bool
	monitorCh       chan interface{}
	errorCh         chan struct{}
	monitorClosedCh chan struct{}
	failStartVM     bool
	ac              *agentClient
}

func (v *instanceTestState) init(cfg *vmConfig, instanceDir string) {

}

func (v *instanceTestState) checkBackingImage() error {
	return nil
}

func (v *instanceTestState) downloadBackingImage() error {
	return nil
}

func (v *instanceTestState) createImage(bridge string, userData, metaData []byte) error {
	return nil
}

func (v *instanceTestState) deleteImage() error {
	return nil
}

func (v *instanceTestState) startVM(vnicName, ipAddress, cephID string) error {
	if v.failStartVM {
		return fmt.Errorf("Failed to start VM")
	}
	return nil
}

func (v *instanceTestState) monitorVM(closedCh chan struct{}, connectedCh chan struct{},
	wg *sync.WaitGroup, boot bool) chan interface{} {

	// Need to be careful here not to modify any state inside v before
	// we've closed the channel.

	v.monitorClosedCh = closedCh

	monitorCh := make(chan interface{})
	v.monitorCh = monitorCh
	if v.connect {
		close(connectedCh)
	}
	return monitorCh
}

func (v *instanceTestState) stats() (disk, memory, cpu int) {
	return v.statsArray[0], v.statsArray[1], v.statsArray[2]
}

func (v *instanceTestState) connected() {

}

func (v *instanceTestState) lostVM() {
}

func (v *instanceTestState) SendError(error ssntp.Error, payload []byte) (int, error) {
	switch error {
	case ssntp.StopFailure:
		err := yaml.Unmarshal(payload, &v.sf)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall stop error %v", err)
		}
	case ssntp.StartFailure:
		err := yaml.Unmarshal(payload, &v.stf)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall start error %v", err)
		}
	case ssntp.DeleteFailure:
		err := yaml.Unmarshal(payload, &v.df)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall delete error %v", err)
		}
	case ssntp.RestartFailure:
		err := yaml.Unmarshal(payload, &v.rf)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall restart error %v", err)
		}
	case ssntp.AttachVolumeFailure:
		err := yaml.Unmarshal(payload, &v.avf)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall attach volume error %v", err)
		}
	case ssntp.DetachVolumeFailure:
		err := yaml.Unmarshal(payload, &v.dvf)
		if err != nil {
			v.t.Fatalf("Failed to unmarshall detach volume error %v", err)
		}
	}

	if v.errorCh != nil {
		close(v.errorCh)
	}

	return 0, nil
}

func (v *instanceTestState) SendEvent(event ssntp.Event, payload []byte) (int, error) {
	return 0, nil
}

func (v *instanceTestState) Dial(config *ssntp.Config, ntf ssntp.ClientNotifier) error {
	return nil
}

func (v *instanceTestState) SendStatus(status ssntp.Status, payload []byte) (int, error) {
	return 0, nil
}

func (v *instanceTestState) SendCommand(cmd ssntp.Command, payload []byte) (int, error) {
	return 0, nil
}

func (v *instanceTestState) Role() ssntp.Role {
	return ssntp.AGENT | ssntp.NETAGENT
}

func (v *instanceTestState) UUID() string {
	return ""
}

func (v *instanceTestState) Close() {

}

func (v *instanceTestState) isConnected() bool {
	return true
}

func (v *instanceTestState) setStatus(status bool) {

}

func (v *instanceTestState) cleanUpInstance() {
	_ = os.RemoveAll(path.Join(instancesDir, v.instance))
}

func (v *instanceTestState) verifyStatsUpdate(t *testing.T, cmd interface{}) {
	stats := cmd.(*ovsStatsUpdateCmd)
	if stats.diskUsageMB != v.statsArray[0] || stats.memoryUsageMB != v.statsArray[1] ||
		stats.CPUUsage != v.statsArray[2] || stats.instance != v.instance {
		t.Fatal("Incorrect statistics received")
	}
}

func (v *instanceTestState) expectStatsUpdate(t *testing.T, ovsCh <-chan interface{}) bool {
	var cmd interface{}
	select {
	case cmd = <-ovsCh:
	case <-time.After(time.Second):
		t.Error("Timed out waiting for ovsStatsUpdateCmd")
		return false
	}
	stats, ok := cmd.(*ovsStatsUpdateCmd)
	if !ok {
		t.Error("Unexpected Command received on ovsCh")
	}
	if stats.diskUsageMB != v.statsArray[0] || stats.memoryUsageMB != v.statsArray[1] ||
		stats.CPUUsage != v.statsArray[2] || stats.instance != v.instance {
		t.Error("Incorrect statistics received")
		return false
	}
	return true
}

func (v *instanceTestState) deleteInstance(t *testing.T, ovsCh chan interface{},
	cmdCh chan<- interface{}) bool {

	v.errorCh = make(chan struct{})
	select {
	case cmdCh <- &insDeleteCmd{}:
	case <-time.After(time.Second):
		t.Error("Timed out sending Stop command")
		return false
	}

	for {
		select {
		case <-v.errorCh:
			v.errorCh = nil
			t.Error("Delete command Failed")
			return false
		case ovsCmd := <-ovsCh:
			switch ovsCmd.(type) {
			case *ovsStatusCmd:
				return true
			case *ovsStatsUpdateCmd:
			default:
				t.Error("Unexpected commands received on ovsCh")
				return false
			}
		case monCmd := <-v.monitorCh:
			if _, stopCmd := monCmd.(virtualizerStopCmd); !stopCmd {
				t.Errorf("Invalid monitor command found %t, expected virtualizerStopCmd", monCmd)
				return false
			}
		case <-time.After(time.Second):
			t.Error("Timed out waiting for ovsStatsUpdateCmd")
			return false
		}
	}
}

func (v *instanceTestState) ClusterConfiguration() (payloads.Configure, error) {
	return payloads.Configure{}, nil
}

func cleanupShutdownFail(t *testing.T, instance string, doneCh chan struct{}, ovsCh chan interface{}, wg *sync.WaitGroup) {
	_ = os.RemoveAll(path.Join(instancesDir, instance))

	shutdownInstanceLoop(doneCh, ovsCh, wg, t)
	t.FailNow()
}

func waitForStateChange(t *testing.T, ovsState ovsRunningState, ovsCh chan interface{}) bool {
	for {
		select {
		case ovsCmd := <-ovsCh:
			switch stChange := ovsCmd.(type) {
			case *ovsStateChange:
				if stChange.state != ovsState {
					t.Errorf("ovs state %d expected.  Found state %d",
						ovsState, stChange.state)
					return false
				}
				return true
			case *ovsStatsUpdateCmd:
			default:
				t.Error("Unexpected commands received on ovsCh")
				return false
			}
		case <-time.After(time.Second):
			t.Error("Timed out waiting for overseer channel")
			return false
		}
	}
}

func (v *instanceTestState) startInstance(t *testing.T, ovsCh chan interface{},
	cmdCh chan<- interface{}, cfg *vmConfig, errorOk bool) bool {

	v.errorCh = make(chan struct{})
	select {
	case cmdCh <- &insStartCmd{cfg: cfg, rcvStamp: time.Now()}:
	case <-time.After(time.Second):
		t.Error("Timed out sending Stop command")
		return false
	}

DONE:
	for {
		select {
		case <-v.errorCh:
			v.errorCh = nil
			if !errorOk {
				t.Error("Start command Failed")
				return false
			}
			return true
		case ovsCmd := <-ovsCh:
			switch ovsCmd.(type) {
			case *ovsStatusCmd:
				break DONE
			case *ovsStatsUpdateCmd:
			default:
				t.Error("Unexpected commands received on ovsCh")
				return false
			}
		case <-time.After(time.Second):
			t.Error("Timed out waiting for ovsStatsUpdateCmd")
			return false
		}
	}

	if !v.connect {
		return true
	}

	if !waitForStateChange(t, ovsRunning, ovsCh) {
		return false
	}

	return v.expectStatsUpdate(t, ovsCh)
}

func (v *instanceTestState) restartInstance(t *testing.T, ovsCh chan interface{},
	cmdCh chan<- interface{}, errorOk bool) bool {

	v.errorCh = make(chan struct{})
	select {
	case cmdCh <- &insRestartCmd{}:
	case <-time.After(time.Second):
		t.Error("Timed out sending Restart command")
		return false
	}

	for {
		select {
		case <-v.errorCh:
			v.errorCh = nil
			if !errorOk {
				t.Error("Restart command Failed")
			}
			return false
		case ovsCmd := <-ovsCh:
			switch stChange := ovsCmd.(type) {
			case *ovsStateChange:
				if stChange.state != ovsRunning {
					t.Errorf("ovsRunning expected.  Found state %d", stChange.state)
					return false
				}
				return true
			case *ovsStatsUpdateCmd:
			default:
				t.Error("Unexpected commands received on ovsCh")
				return false
			}
		case <-time.After(time.Second):
			t.Error("Timed out waiting for ovsStatsUpdateCmd")
			return false
		}
	}
}

func shutdownInstanceLoop(doneCh chan struct{}, ovsCh chan interface{}, wg *sync.WaitGroup,
	t *testing.T) {
	close(doneCh)

	timeout := time.After(time.Second * 5)
DONE:
	for {
		select {
		case <-ovsCh:
		case <-timeout:
			t.Error("Timedout waiting for instance loop to exit")
			break DONE
		case <-func() chan struct{} {
			ch := make(chan struct{})
			go func() {
				wg.Wait()
				close(ch)
			}()
			return ch
		}():
			break DONE
		}
	}
}

// Checks that an instance loop can be started and shutdown
//
// We just check that the instanceLoop can be started and shutdown.  No commands are
// actually executed by the instance.
//
// It should be possible to start and stop the instanceLoop without any problems.
func TestStartInstanceLoop(t *testing.T) {
	var wg sync.WaitGroup
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:          t,
		instance:   "testInstance",
		statsArray: [3]int{10, 128, 10},
	}
	cfg := &vmConfig{}
	cmdWrapCh := make(chan *cmdWrapper)
	ac := &agentClient{conn: state, cmdCh: cmdWrapCh}
	_ = startInstanceWithVM(state.instance, cfg, &wg, doneCh, ac, ovsCh, state, &storage.NoopDriver{})
	ok := state.expectStatsUpdate(t, ovsCh)
	shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
	if !ok {
		t.FailNow()
	}
}

// Checks an instance loop can be deleted before an instance is launched.
//
// We start the instance loop and then delete the instance straight away.
//
// The instanceLoop should start and should then terminate cleanly once the
// deleteCmd is received.  Note delete works here, even though we haven't
// actually started an instance.
func TestDeleteInstanceLoop(t *testing.T) {
	var wg sync.WaitGroup
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:          t,
		instance:   "testInstance",
		statsArray: [3]int{10, 128, 10},
		errorCh:    make(chan struct{}),
	}
	cfg := &vmConfig{}
	cmdWrapCh := make(chan *cmdWrapper)
	ac := &agentClient{conn: state, cmdCh: cmdWrapCh}
	cmdCh := startInstanceWithVM(state.instance, cfg, &wg, doneCh, ac, ovsCh, state, &storage.NoopDriver{})

	ok := state.expectStatsUpdate(t, ovsCh)
	if !ok {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}
	wg.Wait()
}

// Check we cannot stop an instance that is not running.
//
// We start the instance loop and then try to stop the instance straight away.
// When this fails we delete the instance.
//
//  We should receive a SSNTP stopErr and the instance loop should close.
func TestStopNotRunning(t *testing.T) {
	var wg sync.WaitGroup
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:          t,
		instance:   "testInstance",
		statsArray: [3]int{10, 128, 10},
		errorCh:    make(chan struct{}),
	}
	cfg := &vmConfig{}
	cmdWrapCh := make(chan *cmdWrapper)
	ac := &agentClient{conn: state, cmdCh: cmdWrapCh}
	cmdCh := startInstanceWithVM(state.instance, cfg, &wg, doneCh, ac, ovsCh, state, &storage.NoopDriver{})

	ok := state.expectStatsUpdate(t, ovsCh)
	if !ok {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}

	select {
	case cmdCh <- &insStopCmd{}:
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timed out sending Stop command")
	}

	select {
	case <-state.errorCh:
		state.errorCh = nil
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timed out waiting for error channel")
	}

	if state.sf.InstanceUUID != state.instance ||
		state.sf.Reason != payloads.StopAlreadyStopped {
		t.Error("Invalid Stop error returned")
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}
	wg.Wait()
}

func startVMWithCFG(t *testing.T, wg *sync.WaitGroup, cfg *vmConfig, connect bool, errorOk bool) (*instanceTestState, chan interface{}, chan<- interface{}, chan struct{}) {
	networking = false
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:          t,
		instance:   "testInstance",
		statsArray: [3]int{10, 128, 10},
		connect:    connect,
	}
	state.ac = &agentClient{conn: state, cmdCh: make(chan *cmdWrapper)}
	cmdCh := startInstanceWithVM(state.instance, cfg, wg, doneCh, state.ac, ovsCh, state, &storage.NoopDriver{})
	if !state.expectStatsUpdate(t, ovsCh) {
		shutdownInstanceLoop(doneCh, ovsCh, wg, t)
		t.FailNow()
	}

	if !state.startInstance(t, ovsCh, cmdCh, cfg, errorOk) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, wg)
	}
	return state, ovsCh, cmdCh, doneCh
}

// Check we can start an instance that is not running.
//
// We start the instance loop and then try to start an instance.  Our test virtualizer
// closes the connected channel to indicate that the instance is running.  We then
// check to see whether we receive the state change notification at which point we
// delete the instance.
//
// The instance is started and deleted correctly and the instanceLoop should close
// down cleanly.
func TestStartNotRunning(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check we can delete an instance which has been started but has not yet connected.
//
// We start the instance loop and then try to start an instance.  The key point here
// is that we do not close the connected channel, simulating a qemu instance for
// example that has not yet started up.  We then delete the instance.
//
// The instance is started and deleted correctly and the instanceLoop should close
// down cleanly.
func TestDeleteNoConnect(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, false, false)

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		_ = os.RemoveAll(path.Join(instancesDir, cfg.Instance))
		close(doneCh)
		t.FailNow()
	}

	wg.Wait()
}

// Check we can shut down the instance loop cleanly when we have a running instance.
//
// We start the instance loop and then try to start an instance.  Our test virtualizer
// closes the connected channel to indicate that the instance is running.  We then
// close the doneCh channel simulating a launcher exit.  We need to explicitly delete
// the instance directory, so the subsequent tests don't fail.
//
// The instance is started correctly and the instanceLoop shuts down cleanly.
func TestLoopShutdownWithRunningInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	_, ovsCh, _, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	shutdownInstanceLoop(doneCh, ovsCh, &wg, t)

	// We need to remove the instance manually to have a clean setup for the
	// subsequent tests.

	_ = os.RemoveAll(path.Join(instancesDir, cfg.Instance))
}

// Check we can restart an instance
//
// We start the instance loop and then try to restart an instance.  Our test virtualizer
// closes the connected channel to indicate that the instance is running.  We then
// check to see whether we receive the state change notification at which point we
// close the doneCh.
//
// The instance should start correctly.  We should receive an error when attempting
// to restart the instance.  The instanceLoop should quit cleanly.
func TestRestart(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:          t,
		instance:   "testInstance",
		statsArray: [3]int{10, 128, 10},
		connect:    true,
	}
	cmdWrapCh := make(chan *cmdWrapper)
	ac := &agentClient{conn: state, cmdCh: cmdWrapCh}
	cmdCh := startInstanceWithVM(state.instance, &cfg, &wg, doneCh, ac, ovsCh, state, &storage.NoopDriver{})
	ok := state.expectStatsUpdate(t, ovsCh)
	if !ok {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}

	if !state.restartInstance(t, ovsCh, cmdCh, false) {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}

	shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
}

// Check we can handle a restart error
//
// We start the instanceLoop and then try to restart an instance.  This attempt
// will fail as we've configured startVm to return an error.  We then shutdown
// the instance loop.
//
// The instanceLoop should start correctly, the restartCommand should fail with
// the correct error and the instanceLoop should close down cleanly.
func TestRestartFail(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	doneCh := make(chan struct{})
	ovsCh := make(chan interface{})
	state := &instanceTestState{
		t:           t,
		instance:    "testInstance",
		statsArray:  [3]int{10, 128, 10},
		connect:     true,
		failStartVM: true,
	}
	cmdWrapCh := make(chan *cmdWrapper)
	ac := &agentClient{conn: state, cmdCh: cmdWrapCh}
	cmdCh := startInstanceWithVM(state.instance, &cfg, &wg, doneCh, ac, ovsCh, state, &storage.NoopDriver{})
	ok := state.expectStatsUpdate(t, ovsCh)
	if !ok {
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.FailNow()
	}

	if state.restartInstance(t, ovsCh, cmdCh, true) {
		t.Error("Restart was expected to Fail")
	}

	if state.rf.Reason != payloads.RestartLaunchFailure {
		t.Errorf("Invalid restart error found %s, expected %s",
			state.rf.Reason, payloads.RestartLaunchFailure)
	}

	shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
}

// Check we get an error when starting an instance with an invalid image
//
// We start the instance loop and then try to start an instance with an invalid
// config. This should cause a sudicide command to get sent to the acCmd channel.
// We'll extract this command and send it back down our instance channel,
// which should kill the instanceLoop.
//
// The instanceLoop should start correctly but the start command should fail.
// The suicide command recevied from the acCmd channel should terminate the
// instanceLoop cleanly.
func TestStartBadImage(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	cfg.Image = ""

	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, true)
	if state.stf.Reason != payloads.InvalidData {
		t.Errorf("Incorrect error returned. Reported %s, expected %s",
			string(state.stf.Reason), string(payloads.ImageFailure))
	}

	select {
	case acCmd := <-state.ac.cmdCh:
		state.errorCh = make(chan struct{})
		select {
		case cmdCh <- acCmd.cmd:
		case <-time.After(time.Second):
			shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
			t.Fatal("Timed out sending suicide command")
		}
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timedout waiting from suicide command")
	}
	wg.Wait()

	select {
	case <-state.errorCh:
		state.errorCh = nil
		t.Error("Suicide Delete failed unexpectedly")
	default:
	}
}

func sendCommandDuringSuicide(t *testing.T, testCmd interface{}) *instanceTestState {
	var wg sync.WaitGroup
	cfg := standardCfg
	cfg.Image = ""

	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, true)
	if state.stf.Reason != payloads.InvalidData {
		t.Errorf("Incorrect error returned. Reported %s, expected %s",
			string(state.stf.Reason), string(payloads.ImageFailure))
	}

	var acCmd *cmdWrapper
	select {
	case acCmd = <-state.ac.cmdCh:
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timedout waiting from suicide command")
	}

	state.errorCh = make(chan struct{})
	select {
	case cmdCh <- testCmd:
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timed out sending command during suicide")
	}

	select {
	case <-state.errorCh:
		state.errorCh = nil
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timed out waiting on error channel")
	}

	select {
	case cmdCh <- acCmd.cmd:
	case <-time.After(time.Second):
		shutdownInstanceLoop(doneCh, ovsCh, &wg, t)
		t.Fatal("Timed out sending suicide command")
	}

	wg.Wait()

	select {
	case <-state.errorCh:
		state.errorCh = nil
		t.Fatal("Suicide Delete failed unexpectedly")
	default:
	}

	return state
}

// Test deleting an instance that failed to start and is suiciding.
//
// We start the instance loop and then try to start an instance. This should cause
// a suicide command to get sent to the acCmd channel.  We then send a delete
// command to the instance (without the suicide flag set).  This command should
// fail.  We then send the real suicide command received from the acCmd channel,
// which should succeed.
//
// The instanceLoop should start, the start command and the first delete command
// should fail.  The second delete (suicide) should succeed and the loop should
// exit.
func TestDeleteNoInstance(t *testing.T) {
	state := sendCommandDuringSuicide(t, &insDeleteCmd{})
	if state.df.Reason != payloads.DeleteNoInstance {
		t.Errorf("Incorrect error returned. Reported %s, expected %s",
			string(state.df.Reason), string(payloads.DeleteNoInstance))
	}
}

// Test restarting an instance that failed to start and is suiciding.
//
// We start the instance loop and then try to start an instance. This should cause
// a suicide command to get sent to the acCmd channel.  We then send a restart
// command to the instance.  This command should fail.  We then send the suicide
// command received from the acCmd channel, which should succeed.
//
// The instanceLoop should start, the start command and the restart command
// should fail.  The delete (suicide) should succeed and the loop should
// exit.
func TestRestartNoInstance(t *testing.T) {
	state := sendCommandDuringSuicide(t, &insRestartCmd{})
	if state.rf.Reason != payloads.RestartNoInstance {
		t.Errorf("Incorrect error returned. Reported %s, expected %s",
			string(state.rf.Reason), string(payloads.RestartNoInstance))
	}
}

// Test stopping an instance that failed to start and is suiciding.
//
// We start the instance loop and then try to start an instance. This should cause
// a suicide command to get sent to the acCmd channel.  We then send a stop
// command to the instance.  This command should fail.  We then send the suicide
// command received from the acCmd channel, which should succeed.
//
// The instanceLoop should start, the start command and the stop command
// should fail.  The delete (suicide) should succeed and the loop should
// exit.
func TestStopNoInstance(t *testing.T) {
	state := sendCommandDuringSuicide(t, &insStopCmd{})
	if state.sf.Reason != payloads.StopNoInstance {
		t.Errorf("Incorrect error returned. Reported %s, expected %s",
			string(state.sf.Reason), string(payloads.StopNoInstance))
	}
}

// Check the instanceLoop copes when an instance is dropped.
//
// We start the instance loop and then try to start an instance.  Our test virtualizer
// closes the connected channel to indicate that the instance is running.  We then close
// the monitorCloseCh channel informing the instanceLoop that the instance has dropped.
// We then delete the instance.
//
// The instanceLoop and then instance should start correctly.  We should receive
// a state change notification when we simulate the instances untimely demise.
// The instance should then be deleted correctly and the instanceLoop should exit
// cleanly.
func TestLostInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	close(state.monitorClosedCh)

	if !waitForStateChange(t, ovsStopped, ovsCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	// This gets closed by the instanceLoop and so will become available
	// in the deleteInstance select loop if we don't set it to nil.
	state.monitorCh = nil

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check we get an error when starting a running instance.
//
// We start the instance loop and then try to start an instance.  Our test virtualizer
// closes the connected channel to indicate that the instance is running.  We then
// send another start command and delete the instance.
//
// The instanceLoop and then instance should start correctly.  The second start
// command should fail.  The instance should then be deleted correctly and
// the instanceLoop should exit cleanly.
func TestStartRunningInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	if !state.startInstance(t, ovsCh, cmdCh, &cfg, true) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	if state.stf.Reason != payloads.AlreadyRunning {
		t.Errorf("Invalid Error received.  Expected %s found %s",
			string(state.stf.Reason), string(payloads.AlreadyRunning))
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check we can add a volume to an instance
//
// We start the instance loop, add a volume, wait for the instance statistics
// and then delete the instance.
//
// The instanceLoop and then instance should start correctly.  The volume should
// be correctly attached and the stats command should verify this.  The instance
// should be correctly deleted.
func TestAttachVolumeToInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	select {
	case cmdCh <- &insAttachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case monCmd := <-state.monitorCh:
		monCmd.(virtualizerAttachCmd).responseCh <- nil
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach volume command result")
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check that adding an existing volume fails
//
// We start the instance loop, add a volume, add the volume a second time
// and then delete the instance.
//
// The instanceLoop and then instance should start correctly.  The volume should
// be correctly attached the first time.  The second attempt should fail. The
// instance should be correctly deleted.
func TestAttachExistingVolumeToInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	select {
	case cmdCh <- &insAttachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case monCmd := <-state.monitorCh:
		monCmd.(virtualizerAttachCmd).responseCh <- nil
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach volume command result")
	}

	select {
	case <-state.errorCh:
		t.Error("Initial Volume attach failed")
	case cmdCh <- &insAttachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case <-state.errorCh:
		if state.avf.Reason != payloads.AttachVolumeAlreadyAttached {
			t.Errorf("Unexpected error.  Expected %s got %s",
				payloads.AttachVolumeAlreadyAttached, state.avf.Reason)
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach to fail")
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check we can detach a volume from an instance
//
// We start the instance loop, add a volume, wait for the instance statistics,
// detach the volume, wait for more statistics and then delete the instance.
//
// The instanceLoop and then instance should start correctly.  The volume should
// be correctly attached and the stats command should verify this.  The volume
// should be successfully detached, verified again by stats, and the instance
// should be correctly deleted.
func TestDetachVolumeFromInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	select {
	case cmdCh <- &insAttachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case monCmd := <-state.monitorCh:
		monCmd.(virtualizerAttachCmd).responseCh <- nil
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach volume command result")
	}

	select {
	case cmdCh <- &insDetachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case monCmd := <-state.monitorCh:
		monCmd.(virtualizerDetachCmd).responseCh <- nil
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach volume command result")
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}

// Check that detaching a nonexistent volume fails
//
// We start the instance loop, detach a volume delete the instance.
//
// The instanceLoop and then instance should start correctly.  The volume should
// be fail to be detached as it doesn't exist. The instance should be correctly
// deleted.
func TestDetachNonexistingVolumeFromInstance(t *testing.T) {
	var wg sync.WaitGroup
	cfg := standardCfg
	state, ovsCh, cmdCh, doneCh := startVMWithCFG(t, &wg, &cfg, true, false)

	select {
	case cmdCh <- &insDetachVolumeCmd{testutil.VolumeUUID}:
	case <-time.After(time.Second):
		t.Error("Timed out sending attach volume command")
	}

	select {
	case <-state.errorCh:
		if state.dvf.Reason != payloads.DetachVolumeNotAttached {
			t.Errorf("Unexpected error.  Expected %s got %s",
				payloads.DetachVolumeNotAttached, state.dvf.Reason)
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for attach to fail")
	}

	if !state.deleteInstance(t, ovsCh, cmdCh) {
		cleanupShutdownFail(t, cfg.Instance, doneCh, ovsCh, &wg)
	}

	wg.Wait()
}


text:
import unittest2

from datafeeds.usfirst_legacy_team_details_parser import UsfirstLegacyTeamDetailsParser

@unittest2.skip
class TestUsfirstLegacyTeamDetailsParser(unittest2.TestCase):
    def test_parse(self):
        with open('test_data/usfirst_legacy_html/usfirst_team_details_frc177_2012.html', 'r') as f:
            team, _ = UsfirstLegacyTeamDetailsParser.parse(f.read())

        self.assertEqual(team["address"], u"South Windsor, CT\xa0 USA")
        self.assertEqual(team["name"], "UTC Power/Ensign Bickford Aerospace & Defense & South Windsor High School")
        self.assertEqual(team["nickname"], "Bobcat Robotics")
        self.assertEqual(team["team_number"], 177)
        self.assertEqual(team["rookie_year"], 1995)
        self.assertEqual(team["website"], "http://www.bobcatrobotics.org")


text:
* Fix shim to add list of export modules.

## 0.2.2

* Add shim file to allow `import Pretender from 'pretender';`.
* Fix repo URL's (rjackson -> rwjblue).

## 0.2.1

* Remove hard-coded list of files to include (in package.json).

## 0.2.0

* Remove vendored code (instead, install via bower in postinstall hook).
* Export a POJO (allows us to inherit from ember-cli's Addon model).
* Add repo url to package.json.


text:
namespace Agencies.Shared
{
	public class VerifyResult
	{
		public bool IsIdentical { get; set; }

		public float Confidence { get; set; }
	}
}


text:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Difi.SikkerDigitalPost.Klient.Tester.Fakes
{
    internal class FakeResponseHandler : DelegatingHandler
    {
        public Action<HttpRequestMessage> TestingAction { get; set; }

        public HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;

        public HttpContent HttpContent { get; set; } = new StringContent("Sucess");

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage requestMessage, CancellationToken cancellationToken)
        {
            TestingAction?.Invoke(requestMessage);

            var response = new HttpResponseMessage
            {
                Content = HttpContent,
                StatusCode = StatusCode
            };

            return await Task.FromResult(response).ConfigureAwait(false);
        }
    }
}