text:
This directory contains an idiomatic C++ client library for the
[Connectors API][cloud-service-docs], a service that enables users to create and
manage connections to Google Cloud services and third-party business
applications.

While this library is **GA**, please note that the Google Cloud C++ client
libraries do **not** follow [Semantic Versioning](https://semver.org/).

## Supported Platforms

- Windows, macOS, Linux
- C++14 (and higher) compilers (we test with GCC >= 7.3, Clang >= 6.0, and
  MSVC >= 2017)
- Environments with or without exceptions
- Bazel (>= 4.0) and CMake (>= 3.5) builds

## Documentation

- Official documentation about the [Connectors API][cloud-service-docs] service
- [Reference doxygen documentation][doxygen-link] for each release of this
  client library
- Detailed header comments in our [public `.h`][source-link] files

## Quickstart

The [quickstart/](quickstart/README.md) directory contains a minimal environment
to get started using this client library in a larger project. The following
"Hello World" program is used in this quickstart, and should give you a taste of
this library.

<!-- inject-quickstart-start -->

```cc
#include "google/cloud/connectors/connectors_client.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " project-id location-id\n";
    return 1;
  }

  namespace connectors = ::google::cloud::connectors;
  auto client =
      connectors::ConnectorsClient(connectors::MakeConnectorsConnection());

  auto const parent =
      std::string{"projects/"} + argv[1] + "/locations/" + argv[2];
  for (auto r : client.ListConnections(parent)) {
    if (!r) throw std::move(r).status();
    std::cout << r->DebugString() << "\n";
  }

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}
```

<!-- inject-quickstart-end -->

- Packaging maintainers or developers who prefer to install the library in a
  fixed directory (such as `/usr/local` or `/opt`) should consult the
  [packaging guide](/doc/packaging.md).

* Developers that prefer using a package manager such as
  [vcpkg](https://vcpkg.io), [Conda](https://conda.io),
  or [Conan](https://conan.io) should follow the instructions for their package
  manager.

- Developers wanting to use the libraries as part of a larger CMake or Bazel
  project should consult the [quickstart guides](#quickstart) for the library
  or libraries they want to use.
- Developers wanting to compile the library just to run some examples or
  tests should read the current document.
- Contributors and developers to `google-cloud-cpp` should consult the guide to
  [set up a development workstation][howto-setup-dev-workstation].

## Contributing changes

See [`CONTRIBUTING.md`](/CONTRIBUTING.md) for details on how to
contribute to this project, including how to build and test your changes
as well as how to properly format your code.

## Licensing

Apache 2.0; see [`LICENSE`](/LICENSE) for details.

[cloud-service-docs]: https://cloud.google.com/apigee/docs/api-platform/connectors/about-connectors
[doxygen-link]: https://googleapis.dev/cpp/google-cloud-connectors/latest/
[howto-setup-dev-workstation]: /doc/contributor/howto-guide-setup-development-workstation.md
[source-link]: https://github.com/googleapis/google-cloud-cpp/tree/main/google/cloud/connectors


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.iOS.DOM
{
	/// <summary>
	/// Returns the root DOM node to the caller.
	/// </summary>
	[Command(ProtocolName.DOM.GetDocument)]
	[SupportedBy("iOS")]
	public class GetDocumentCommand: ICommand<GetDocumentCommandResponse>
	{
	}
}

redpajama_set_name: RedPajamaGithub


text:
declare module "gulp-ml-admin/dist/lib/gulpDatabase"{
    import tmp = require('dist/lib/gulpDatabase');
    export = tmp;
}

declare module "gulp-ml-admin/dist/lib/gulpDatabaseSpecGenerator"{
    import tmp = require('dist/lib/gulpDatabaseSpecGenerator');
    export = tmp;
}

declare module "gulp-ml-admin/dist/lib/index"{
    import tmp = require('dist/lib/index');
    export = tmp;
}

declare module "gulp-ml-admin"{
    import tmp = require('dist/lib/index');
    export = tmp;
}


text:
package pos;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the pos package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _TagWordResponse_QNAME = new QName("http://pos/", "tag_wordResponse");
    private final static QName _TagWord_QNAME = new QName("http://pos/", "tag_word");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: pos
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link TagWordResponse }
     *
     */
    public TagWordResponse createTagWordResponse() {
        return new TagWordResponse();
    }

    /**
     * Create an instance of {@link TagWord }
     *
     */
    public TagWord createTagWord() {
        return new TagWord();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link TagWordResponse }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://pos/", name = "tag_wordResponse")
    public JAXBElement<TagWordResponse> createTagWordResponse(TagWordResponse value) {
        return new JAXBElement<TagWordResponse>(_TagWordResponse_QNAME, TagWordResponse.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link TagWord }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://pos/", name = "tag_word")
    public JAXBElement<TagWord> createTagWord(TagWord value) {
        return new JAXBElement<TagWord>(_TagWord_QNAME, TagWord.class, null, value);
    }

}


text:
package net.ssehub.kernel_haven.util.io.void_io;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**
 * Tests for the util.io.void_io package.
 *
 * @author Adam
 */
@RunWith(Suite.class)
@SuiteClasses({
    VoidTableCollectionTest.class,
    VoidTableReaderTest.class,
    VoidTableWriterTest.class,
    })
public class AllVoidIoTests {

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Notiser 131: 168 (1978)

#### Original name
Christiansenia mycetophila var. mycetophila (Peck) Ginns & Sunhede

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 - Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
 -
 - 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.
 -->
<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912"
           targetNamespace="urn:m1app:example:1.0"
           xmlns:bean="urn:switchyard-config:test-bean:1.0"
           xmlns:soap="urn:switchyard-config:test-soap:1.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
               urn:switchyard-config:test-bean:1.0 test/bean/bean.xsd
               urn:switchyard-config:test-soap:1.0 test/soap/soap.xsd"
           name="m1app">
    <service name="M1AppService" promote="SimpleService">
       <soap:binding.soap>
           <soap:port secure="true">MyWebService/SOAPPort</soap:port>
           <soap:wsdl description="foobar">service.wsdl</soap:wsdl>
           <soap:portNum>${foo:5500}</soap:portNum>
       </soap:binding.soap>
    </service>
    <reference name="SomeOtherService" promote="SimpleService/AnotherService" multiplicity="1..1">
       <soap:binding.soap>
           <soap:wsdl>http://exmample.org:8080/services/SomeOtherService?wsdl</soap:wsdl>
       </soap:binding.soap>
    </reference>
    <component name="SimpleService">
       <bean:implementation.bean class="org.switchyard.example.m1app.SimpleBean"/>
       <service name="SimpleService">
           <interface.java interface="org.switchyard.example.m1app.SimpleService"/>
       </service>
       <reference name="anotherService">
           <interface.java interface="org.switchyard.example.m1app.AnotherService"/>
       </reference>
       <property name="composite.foo" value="should be overridden by composite property"/>
       <property name="component.foo" value="component.bar"/>
       <property name="component.userName" value="component.${user.name}"/>
    </component>
    <component name="AnotherService">
       <bean:implementation.bean class="org.switchyard.example.m1app.AnotherBean"/>
       <service name="AnotherService">
           <interface.java interface="org.switchyard.example.m1app.AnotherService"/>
       </service>
    </component>
    <property name="composite.foo" value="composite.bar"/>
    <property name="composite.userName" value="composite.${user.name}"/>
</composite>


text:
layout: post
title:  "Python - Random Sampling"
date:   2017-04-17 18:34:10 +0700
categories: [python, example, random, sampling]
---

# Objective: Introducing a few methods to do random sampling in Python

## 1. The basics

~~~python
random.random(), random.randrange(), random.shuffle, random.choice(), random.sample()

import random
#to produce deterministic results, set the seed
#e.g., random.seed(10)

# a random number between 0 and 1
print(random.random())

# 4 random numbers between 0 and 1
print([random.random() for _ in range(4)])

# a random integer in [0,3)
print(random.randrange(3))

# a random integer in (3,6)
print(random.randrange(3, 6))

# randomly shuffle an array:
up_to_five = list(range(5))
random.shuffle(up_to_five)
print(up_to_five)

# randomly choose one element from a list
my_fav_city = random.choice(["Evanston", "Chicago", "Thousand Oaks"])
print(my_fav_city)
~~~

## 2. Choose k random numbers from a list (with or without replacement)

~~~python
source = list(range(10))
# randomly choose 7 numbers from a list (with replacement)
choose7_withReplacement = [random.choice(source)
                           for _ in range(7)]
print(choose7_withReplacement)
~~~

~~~python
# randomly choose 7 numbers from a list (without replacement)
choose7_withOutReplacement = random.sample(source, 7)
print(choose7_withOutReplacement)
~~~

## 3. Online sampling: Choose k random numbers from a stream of numbers with size n, where n can grow as we process; n can be very large so that the list won't fit into memory, or n can be unknown.

## Idea: [Reservoir Sampling.](https://en.wikipedia.org/wiki/Reservoir_sampling/)

Below, we implement the most common method: Algorithm R

S[1..n] is the stream to process, R[1..k] will contain the returned k random samples.

~~~python
#Assume we have a Stream object with the following methods:
class Stream(object):
    def __init__(self, n):# n is the current length of the stream
        self.n = n

    def hasNext(self):#return 1 if the stream continues
        #assume the stream end at 100 (unknown to user)
        return 1 if self.n <= 100 else 0

    def getNext(self):#return a random next number
        #assume the streamn consists of numbers 0,1,...,9
        return random.randrange(10) if self.hasNext() else None

    def update(self):#increase the stream length by 1
        self.n += 1

    def leng(self): #return length of current stream
        return self.n
~~~

#### Now, let's run the experiment:

~~~python
def ReservoirSample(S, k):
    R = [None] * k
    i = S.leng() # length of stream so far
    #basically, i=0 to start with

    while S.hasNext(): #while the Stream continues to generate number
        if i < k: #the first k elements 0...k-1 get assigned first
            R[i] = S.getNext()
        else: #i>=k, replace previous assigned element
            j = random.randrange(0,i) #random from 0 to i-1 inclusive
            if j <= k-1:
                R[j] = S.getNext()

        S.update() # length of the stream is increased by 1
        i = S.leng()

    return R

def experiment(): #main function
    k = 50 #number of samples we want to pick
    S = Stream(0) #initialize the length of stream to 0
    samples = ReservoirSample(S, k)
    print(samples)

if __name__ == "__main__":
    experiment()
~~~

## Analysis: Why does the above Algorithm R work? In other words, prove that the algorithm returns each value in the stream with probability k/i, when i is the current length of the stream:

* First of all, the latest ith element is selected with probability k/i (done).
* Now: P[the jth element from 1 to i-1 (inclusive) is replaced] = (k/i) (1/k) = 1/i. You can also see this directly from j = random.randrange(0,i), which returns a number between 0 and i-1 thus each number is chosen with probability 1/i.
* Thus, P[the jth element between 1 and i is NOT replaced] = 1-1/i = (i-1)/i
* Now, using induction: Assuming when the stream is at length i-1, each element is selected with probability k/(i-1) (verify that this is true for i=1,2). Now:
    * P[the jth element survives after the latest round] = P[it survives in previous round] * P[it is not replaced in this round] = (k/(i-1)) ((i-1)/i) = k/i (done!)

----------------
_Reference:_ [Reservoir Sampling.](https://en.wikipedia.org/wiki/Reservoir_sampling/)


text:
{{#template name="pkg_ecmascript"}}
## `ecmascript`

This package lets you use new JavaScript language features that are part
of the [ECMAScript 2015
specification](http://www.ecma-international.org/ecma-262/6.0/) but are
not yet supported by all engines or browsers. Unsupported syntax is
automatically translated into standard JavaScript that behaves the same
way.

[This video](https://www.youtube.com/watch?v=05Z6YGiZKmE) from the July
2015 Meteor Devshop gives an overview of how the package works, and what
it provides.

### Usage

The `ecmascript` package registers a compiler plugin that transpiles
ECMAScript 2015+ to ECMAScript 5 (standard JS) in all `.js` files. By
default, this package is pre-installed for all new apps and packages.

To add this package to an existing app, run the following command from
your app directory:

```bash
meteor add ecmascript
```

To add the `ecmascript` package to an existing package, include the
statement `api.use('ecmascript');` in the `Package.onUse` callback in your
`package.js` file:

```js
Package.onUse(function (api) {
  api.use('ecmascript');
});
```

### Supported ES2015 Features

#### Syntax

The `ecmascript` package uses [Babel](http://babeljs.io/) to compile
ES2015 syntax to ES5 syntax. Many but not all ES2015 features can be
simulated by Babel, and `ecmascript` enables most of the features
supported by Babel.

Here is a list of the Babel transformers that are currently enabled:

* [`es3.propertyLiterals`](https://babeljs.io/docs/advanced/transformers/es3/property-literals/)

  Makes it safe to use reserved keywords like `catch` as unquoted keys in
  object literals. For example, `{ catch: 123 }` is translated to `{ "catch": 123 }`.

* [`es3.memberExpressionLiterals`](https://babeljs.io/docs/advanced/transformers/es3/member-expression-literals/)

  Makes it safe to use reserved keywords as property names. For
  example, `object.catch` is translated to `object["catch"]`.

* [`es6.arrowFunctions`](http://babeljs.io/docs/learn-es2015/#arrows)

  Provides a shorthand for function expressions. For example,
  `[1, 2, 3].map(x => x + 1)` evaluates to `[2, 3, 4]`. If `this` is used
  in the body of the arrow function, it will be automatically bound to the
  value of `this` in the enclosing scope.

* [`es6.literals`](http://babeljs.io/docs/learn-es2015/#binary-and-octal-literals)

  Adds support for binary and octal numeric literals. For example,
  `0b111110111 === 503` and `0o767 === 503`.

* [`es6.templateLiterals`](http://babeljs.io/docs/learn-es2015/#template-strings)

  Enables multi-line strings delimited by backticks instead of quotation
  marks, with variable interpolation:
  ```js
  var name = "Ben";
  var message = `My name is:
  ${name}`;
  ```

* [`es6.classes`](http://babeljs.io/docs/learn-es2015/#classes)

  Enables `class` syntax:
  ```js
  class Base {
    constructor(a, b) {
      this.value = a * b;
    }
  }

  class Derived extends Base {
    constructor(a, b) {
      super(a + 1, b + 1);
    }
  }

  var d = new Derived(2, 3);
  d.value; // 12
  ```

* [`es6.constants`](https://babeljs.io/docs/learn-es2015/#let-const)

  Allows defining block-scoped variables that are not allowed to be
  redefined:
  ```js
  const GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;

  // This reassignment will be forbidden by the compiler:
  GOLDEN_RATIO = "new value";
  ```

* [`es6.blockScoping`](http://babeljs.io/docs/learn-es2015/#let-const)

  Enables the `let` and `const` keywords as alternatives to `var`. The key
  difference is that variables defined using `let` or `const` are
  visible only within the block where they are declared, rather than being
  visible anywhere in the enclosing function. For example:
  ```js
  function example(condition) {
    let x = 0;
    if (condition) {
      let x = 1;
      console.log(x);
    } else {
      console.log(x);
      x = 2;
    }
    return x;
  }

  example(true); // logs 1, returns 0
  example(false); // logs 0, returns 2
  ```

* [`es6.properties.shorthand`](https://babeljs.io/docs/learn-es2015/#enhanced-object-literals)

  Allows omitting the value of an object literal property when the desired
  value is held by a variable that has the same name as the property
  key. For example, instead of writing `{ x: x, y: y, z: "asdf" }` you can
  just write `{ x, y, z: "asdf" }`. Methods can also be written without
  the `: function` property syntax:
  ```js
  var obj = {
    oldWay: function (a, b) { ... },
    newWay(a, b) { ... }
  };
  ```

* [`es6.properties.computed`](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals)

  Allows object literal properties with dynamically computed keys:
  ```js
  var counter = 0;
  function getKeyName() {
    return "key" + counter++;
  }

  var obj = {
    [getKeyName()]: "zero",
    [getKeyName()]: "one",
  };

  obj.key0; // "zero"
  obj.key1; // "one"
  ```

* [`es6.parameters`](http://babeljs.io/docs/learn-es2015/#default-rest-spread)

  Default expressions for function parameters, evaluated whenever the parameter
  is `undefined`, `...rest` parameters for capturing remaining
  arguments without using the `arguments` object:
  ```js
  function add(a = 0, ...rest) {
    rest.forEach(n => a += n);
    return a;
  }

  add(); // 0
  add(1, 2, 3); // 6
  ```

* [`es6.spread`](http://babeljs.io/docs/learn-es2015/#default-rest-spread)

  Allows an array of arguments to be interpolated into a list of arguments
  to a function call, `new` expression, or array literal, without using
  `Function.prototype.apply`:
  ```js
  add(1, ...[2, 3, 4], 5); // 15
  new Node("name", ...children);
  [1, ...[2, 3, 4], 5]; // [1, 2, 3, 4, 5]
  ```

* [`es6.forOf`](http://babeljs.io/docs/learn-es2015/#iterators-for-of)

  Provides an easy way to iterate over the elements of a collection:
  ```js
  let sum = 0;
  for (var x of [1, 2, 3]) {
    sum += x;
  }
  x; // 6
  ```

* [`es6.destructuring`](http://babeljs.io/docs/learn-es2015/#destructuring)

  Destructuring is the technique of using an array or object pattern on
  the left-hand side of an assignment or declaration, in place of the
  usual variable or parameter, so that certain sub-properties of the value
  on the right-hand side will be bound to identifiers that appear within the
  pattern. Perhaps the simplest example is swapping two variables without
  using a temporary variable:
  ```js
  [a, b] = [b, a];
  ```
  Extracting a specific property from an object:
  ```js
  let { username: name } = user;
  // is equivalent to
  let name = user.username;
  ```
  Instead of taking a single opaque `options` parameter, a function can
  use an object destructuring pattern to name the expected options:
  ```js
  function run({ command, args, callback }) { ... }

  run({
    command: "git",
    args: ["status", "."],
    callback(error, status) { ... },
    unused: "whatever"
  });
  ```

* [`es7.objectRestSpread`](https://github.com/sebmarkbage/ecmascript-rest-spread)

  Supports catch-all `...rest` properties in object literal declarations
  and assignments:
  ```js
  let { x, y, ...rest } = { x: 1, y: 2, a: 3, b: 4 };
  x; // 1
  y; // 2
  rest; // { a: 3, b: 4 }
  ```
  Also enables `...spread` properties in object literal expressions:
  ```js
  let n = { x, y, ...rest };
  n; // { x: 1, y: 2, a: 3, b: 4 }
  ```

* [`es7.trailingFunctionCommas`](https://github.com/jeffmo/es-trailing-function-commas)

  Allows the final parameter of a function to be followed by a comma,
  provided that parameter is not a `...rest` parameter.

* [`flow`](https://babeljs.io/docs/advanced/transformers/other/flow/)

  Permits the use of [Flow](http://flowtype.org/) type annotations. These
  annotations are simply stripped from the code, so they have no effect on
  the code's behavior, but you can run the `flow` tool over your code to
  check the types if desired.

#### Polyfills

The ECMAScript 2015 standard library has grown to include new APIs and
data structures, some of which can be implemented ("polyfilled") using
JavaScript that runs in all engines and browsers today. Here are three new
constructors that are guaranteed to be available when the `ecmascript`
package is installed:

* [`Promise`](https://github.com/meteor/promise)

  A `Promise` allows its owner to wait for a value that might not be
  available yet. See [this tutorial](https://www.promisejs.org/) for more
  details about the API and motivation. The Meteor `Promise`
  implementation is especially useful because it runs all callback
  functions in recycled `Fiber`s, so you can use any Meteor API, including
  those that yield (e.g. `HTTP.get`, `Meteor.call`, or `MongoCollection`),
  and you never have to call `Meteor.bindEnvironment`.

* [`Map`](https://github.com/zloirock/core-js#map)

  An associative key-value data structure where the keys can be any
  JavaScript value (not just strings). Lookup and insertion take constant
  time.

* [`Set`](https://github.com/zloirock/core-js#set)

  A collection of unique JavaScript values of any type. Lookup and
  insertion take constant time.

* [`Symbol`](https://github.com/zloirock/core-js#ecmascript-6-symbol)

  An implementation of the global
  [`Symbol`](http://www.2ality.com/2014/12/es6-symbols.html)s namespace
  that enables a number of other ES2015 features, such as `for`-`of` loops
  and `Symbol.iterator` methods: `[1,2,3][Symbol.iterator]()`.

* Polyfills for the following [`Object`](https://github.com/zloirock/core-js#ecmascript-6-object)-related methods:
  * `Object.assign`
  * `Object.is`
  * `Object.setPrototypeOf`
  * `Object.prototype.toString` (fixes `@@toStringTag` support)

  Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).

* Polyfills for the following [`String`](https://github.com/zloirock/core-js#ecmascript-6-string)-related methods:
  * `String.fromCodePoint`
  * `String.raw`
  * `String.prototype.includes`
  * `String.prototype.startsWith`
  * `String.prototype.endsWith`
  * `String.prototype.repeat`
  * `String.prototype.codePointAt`
  * `String.prototype.trim`

  Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String).

* Polyfills for the following [`Array`](https://github.com/zloirock/core-js#ecmascript-6-array)-related methods:
  * `Array.from`
  * `Array.of`
  * `Array.prototype.copyWithin`
  * `Array.prototype.fill`
  * `Array.prototype.find`
  * `Array.prototype.findIndex`

  Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).

* Polyfills for the following [`Function`](https://github.com/zloirock/core-js#ecmascript-6-function)-related properties:
  * `Function.prototype.name` (fixes IE9+)
  * `Function.prototype[Symbol.hasInstance]` (fixes IE9+)

  Complete reference [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).

{{/template}}


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/system/sink_command.hpp"

#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/defaults.hpp"
#include "vast/detail/assert.hpp"
#include "vast/error.hpp"
#include "vast/expression.hpp"
#include "vast/logger.hpp"
#include "vast/scope_linked.hpp"
#include "vast/system/accountant.hpp"
#include "vast/system/node_control.hpp"
#include "vast/system/query_status.hpp"
#include "vast/system/read_query.hpp"
#include "vast/system/signal_monitor.hpp"
#include "vast/system/spawn_or_connect_to_node.hpp"
#include "vast/system/tracker.hpp"

#include <caf/event_based_actor.hpp>
#include <caf/scoped_actor.hpp>
#include <caf/settings.hpp>
#include <caf/stateful_actor.hpp>
#include <caf/typed_event_based_actor.hpp>

#include <csignal>
#include <iostream>
#include <memory>
#include <string>
#include <string_view>

using namespace std::chrono_literals;
using namespace caf;

namespace vast::system {

caf::message sink_command(const command::invocation& invocation,
                          actor_system& sys, caf::actor snk) {
  // Get a convenient and blocking way to interact with actors.
  scoped_actor self{sys};
  auto guard = caf::detail::make_scope_guard(
    [&] { self->send_exit(snk, exit_reason::user_shutdown); });
  // Read query from input file, STDIN or CLI arguments.
  auto query = read_query(invocation, "export.read");
  if (!query)
    return caf::make_message(std::move(query.error()));
  // Transform expression if needed, e.g., for PCAP sink.
  if (invocation.name() == "pcap") {
    VAST_DEBUG(invocation.full_name, "restricts expression to PCAP packets");
    // We parse the query expression first, work on the AST, and then render
    // the expression again to avoid performing brittle string manipulations.
    auto expr = to<expression>(*query);
    if (!expr)
      return make_message(expr.error());
    auto attr = caf::atom_from_string("type");
    auto extractor = attribute_extractor{attr};
    auto pred = predicate{extractor, equal, data{"pcap.packet"}};
    auto ast = conjunction{std::move(pred), std::move(*expr)};
    *query = to_string(ast);
    VAST_DEBUG(&invocation, "transformed expression to", *query);
  }
  // Get VAST node.
  auto node_opt
    = spawn_or_connect_to_node(self, invocation.options, content(sys.config()));
  if (auto err = caf::get_if<caf::error>(&node_opt))
    return caf::make_message(std::move(*err));
  auto& node = caf::holds_alternative<caf::actor>(node_opt)
               ? caf::get<caf::actor>(node_opt)
               : caf::get<scope_linked_actor>(node_opt).get();
  VAST_ASSERT(node != nullptr);
  // Start signal monitor.
  std::thread sig_mon_thread;
  auto signal_guard = system::signal_monitor::run_guarded(
    sig_mon_thread, sys, defaults::system::signal_monitoring_interval, self);
  auto spawn_exporter
    = command::invocation{invocation.options, "spawn exporter", {*query}};
  VAST_DEBUG(&invocation, "spawns exporter with parameters:", spawn_exporter);
  auto exp = spawn_at_node(self, node, spawn_exporter);
  if (!exp)
    return caf::make_message(std::move(exp.error()));
  // Register the accountant at the Sink.
  auto components = get_node_components(self, node, {"accountant"});
  if (!components)
    return caf::make_message(std::move(components.error()));
  auto& [accountant] = *components;
  if (accountant) {
    VAST_DEBUG(invocation.full_name, "assigns accountant to new sink");
    self->send(snk, actor_cast<accountant_type>(accountant));
  }
  // Start the exporter.
  self->send(*exp, system::sink_atom::value, snk);
  self->send(*exp, system::run_atom::value);
  // Register self as the statistics actor.
  self->send(*exp, system::statistics_atom::value, self);
  self->send(snk, system::statistics_atom::value, self);
  self->monitor(snk);
  self->monitor(*exp);
  guard.disable();
  caf::error err;
  auto waiting_for_final_report = false;
  auto stop = false;
  self
    ->do_receive(
      [&](down_msg& msg) {
        stop = true;
        if (msg.source == node) {
          VAST_DEBUG_ANON(__func__, "received DOWN from node");
          self->send_exit(snk, exit_reason::user_shutdown);
          self->send_exit(*exp, exit_reason::user_shutdown);
        } else if (msg.source == *exp) {
          VAST_DEBUG(invocation.full_name, "received DOWN from exporter");
          self->send_exit(snk, exit_reason::user_shutdown);
        } else if (msg.source == snk) {
          VAST_DEBUG(invocation.full_name, "received DOWN from sink");
          self->send_exit(*exp, exit_reason::user_shutdown);
          stop = false;
          waiting_for_final_report = true;
        } else {
          VAST_ASSERT(!"received DOWN from inexplicable actor");
        }
        if (msg.reason && msg.reason != exit_reason::user_shutdown) {
          VAST_WARNING(invocation.full_name, "received error message:",
                       self->system().render(msg.reason));
          err = std::move(msg.reason);
        }
      },
      [&](performance_report report) {
        // Log a set of named measurements.
        VAST_DEBUG(invocation.full_name, "received performance report");
#if VAST_LOG_LEVEL >= VAST_LOG_LEVEL_INFO
        for (const auto& [name, measurement] : report) {
          if (auto rate = measurement.rate_per_sec(); std::isfinite(rate))
            VAST_INFO(name, "processed", measurement.events,
                      "events at a rate of", static_cast<uint64_t>(rate),
                      "events/sec in", to_string(measurement.duration));
          else
            VAST_INFO(name, "processed", measurement.events, "events");
        }
#endif
      },
      [&](std::string name, query_status query) {
        // Log the query status.
        VAST_DEBUG(invocation.full_name, "received query status from", name);
#if VAST_LOG_LEVEL >= VAST_LOG_LEVEL_INFO
        if (auto rate
            = measurement{query.runtime, query.processed}.rate_per_sec();
            std::isfinite(rate))
          VAST_INFO(name, "processed", query.processed,
                    "candidates at a rate of", static_cast<uint64_t>(rate),
                    "candidates/sec and shipped", query.shipped, "results in",
                    to_string(query.runtime));
        else
          VAST_INFO(name, "processed", query.processed, "candidates",
                    "and shipped", query.shipped, "results in",
                    to_string(query.runtime));
#endif
        if (waiting_for_final_report)
          stop = true;
      },
      [&](system::signal_atom, int signal) {
        VAST_DEBUG(invocation.full_name, "got " << ::strsignal(signal));
        if (signal == SIGINT || signal == SIGTERM) {
          self->send_exit(*exp, exit_reason::user_shutdown);
          self->send_exit(snk, exit_reason::user_shutdown);
        }
      })
    .until([&] { return stop; });
  if (err)
    return caf::make_message(std::move(err));
  return caf::none;
}

} // namespace vast::system


text:
General

 Overview

		{% if session.su == 'Yes' %}

Pcap Total

 Packets

 Sessions

{% endif %}

Setting

			{% if session.su == 'Yes' %}
 Users
{% endif %}

 About


text:
@interface NSString (Util)
- (CGFloat)heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width;
- (CGFloat)widthWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height;

- (CGSize)sizeWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height;

+ (NSString *)reverseString:(NSString *)strSrc;
@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.network.models.TagsObject;
import java.util.HashMap;
import java.util.Map;

/** Samples for FirewallPolicies UpdateTags. */
public final class FirewallPoliciesUpdateTagsSamples {
    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/FirewallPolicyPatch.json
     */
    /**
     * Sample code: Update FirewallPolicy Tags.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void updateFirewallPolicyTags(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .networks()
            .manager()
            .serviceClient()
            .getFirewallPolicies()
            .updateTagsWithResponse(
                "myResourceGroup",
                "firewallPolicy",
                new TagsObject().withTags(mapOf("key1", "value1", "key2", "value2")),
                Context.NONE);
    }

    @SuppressWarnings("unchecked")
    private static <T> Map<String, T> mapOf(Object... inputs) {
        Map<String, T> map = new HashMap<>();
        for (int i = 0; i < inputs.length; i += 2) {
            String key = (String) inputs[i];
            T value = (T) inputs[i + 1];
            map.put(key, value);
        }
        return map;
    }
}


text:
using System.Collections.Generic;
using ZWaveLib.Nodes;

namespace ZWaveLib.Commands
{
    public class ControlerHardResetCommand : ZWaveCommandAbstract
    {
        public ControlerHardResetCommand()
            : base("HardReset", "Hard Reset the Z Wave Controller (Warning: Will erase all data in the controller, pairing will need to be done again after the hard reset)", "")
        { }

        protected override bool RunImplementation(IDictionary<string, string> arguments)
        {
            ZWaveInterface.Manager.ResetController(((IZWaveHomeNode)Node).HomeId.Value);
            return true;
        }
    }
}


text:
<!DOCTYPE html>

<title>Challenge 7</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

               Community

Recent Activity

Member Forum

Member List

Member Groups

Pet Help

Pets for Sale

Pet Services


text:
struct WebPreferences;

namespace blink {
class WebFrame;
class WebPlugin;
class WebURLRequest;
struct WebPluginParams;
}

namespace content {
class ContextMenuClient;
class RenderView;
struct ContextMenuParams;
struct WebPluginInfo;

// This interface wraps functionality, which is specific to frames, such as
// navigation. It provides communication with a corresponding RenderFrameHost
// in the browser process.
class CONTENT_EXPORT RenderFrame : public IPC::Listener,
                                   public IPC::Sender {
 public:
  // Returns the RenderView associated with this frame.
  virtual RenderView* GetRenderView() = 0;

  // Get the routing ID of the frame.
  virtual int GetRoutingID() = 0;

   // Gets WebKit related preferences associated with this frame.
  virtual WebPreferences& GetWebkitPreferences() = 0;

  // Shows a context menu with the given information. The given client will
  // be called with the result.
  //
  // The request ID will be returned by this function. This is passed to the
  // client functions for identification.
  //
  // If the client is destroyed, CancelContextMenu() should be called with the
  // request ID returned by this function.
  //
  // Note: if you end up having clients outliving the RenderFrame, we should add
  // a CancelContextMenuCallback function that takes a request id.
  virtual int ShowContextMenu(ContextMenuClient* client,
                              const ContextMenuParams& params) = 0;

  // Cancels a context menu in the event that the client is destroyed before the
  // menu is closed.
  virtual void CancelContextMenu(int request_id) = 0;

  // Create a new NPAPI/Pepper plugin depending on |info|. Returns NULL if no
  // plugin was found.
  virtual blink::WebPlugin* CreatePlugin(
      blink::WebFrame* frame,
      const WebPluginInfo& info,
      const blink::WebPluginParams& params) = 0;

  // The client should handle the navigation externally.
  virtual void LoadURLExternally(
      blink::WebFrame* frame,
      const blink::WebURLRequest& request,
      blink::WebNavigationPolicy policy) = 0;

 protected:
  virtual ~RenderFrame() {}

 private:
  // This interface should only be implemented inside content.
  friend class RenderFrameImpl;
  RenderFrame() {}
};

}  // namespace content

#endif  // CONTENT_PUBLIC_RENDERER_RENDER_FRAME_H_


text:
require 'test_helper'

class SimpleTaskTest < ActiveSupport::TestCase
  test "if all attributes are empty, it should be invalid" do
    task_list = TaskList.create(title: 'Test Task List')
    simple_task = SimpleTask.new
    task_list.tasks << simple_task
    assert simple_task.invalid?
    assert simple_task.errors[:description].any?
    assert simple_task.errors[:priority].any?
  end

  test "if all attributes are present, it should be valid" do
    task_list = TaskList.create(title: 'Test Task List')
    simple_task = SimpleTask.new
    task_list.tasks << simple_task
    simple_task.description = "This is a test simple task."
    simple_task.priority = 2
    assert simple_task.valid?
  end

  test "any statuses other than pending or done are invalid" do
    task_list = TaskList.create(title: 'Test Task List')
    simple_task = SimpleTask.new
    task_list.tasks << simple_task
    simple_task.description = "This is a test simple task."
    simple_task.priority = 2

    # Initial status should be pending.
    assert simple_task.valid?

    simple_task.status = 'done'
    assert simple_task.valid?

    simple_task.status = 'another_status'
    assert simple_task.invalid?
    assert simple_task.errors[:status].any?
  end
end


text:
import sbt._
import Keys._
import Import._

object B extends Build
{
	override def rootProject = Some(d)

	lazy val c = Project("c", file("c")) settings(
		TaskKey[Unit]("taskC") := {}
	)
	lazy val d = Project("d", file("d")) settings(
		TaskKey[Unit]("taskD") := {}
	)
}


text:
require 'butter_sand'
require 'butter_sand/api/events'
require 'butter_sand/error'
require 'faraday'
require 'faraday_middleware'
require 'faraday/response/raise_butter_sand_error'

module ButterSand
  class Client
    include ButterSand::API::Events

    ROOT_URL = 'https://www.rokkatei-eshop.com/'

    def get(path)
      request(:get, path)
    end

    private

    def request(method, path)
      response = connection.send(method.to_sym, path)
      response.body
    end

    def connection
      @connection ||= Faraday.new ROOT_URL, :ssl => {:verify => false} do |conn|
        conn.use Faraday::Response::RaiseButterSandError
        conn.use Faraday::Adapter::NetHttp
      end
    end
  end
end


text:
namespace PasPasPas.Globals.Types {

    /// <summary>
    ///     character type
    /// </summary>
    public interface ICharType : IOrdinalType, IMangledNameTypeSymbol {

        /// <summary>
        ///     char type kind
        /// </summary>
        CharTypeKind Kind { get; }

    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Jb. nassau. Ver. Naturk. 27-28: 21 (1874)

#### Original name
Septoria adoxae Fuckel, 1874

### Remarks
null


text:
using namespace ngraph;

struct Type
{
    enum
    {
        DATA = 0,
        WEIGHTS,
        BIAS,
    };
};

// constructs (x*W + bias)
static std::shared_ptr<pattern::Matcher>
    construct_rnn_input_linear_transformation(std::shared_ptr<pattern::op::Label> labels[])
{
    auto skip = std::make_shared<pattern::op::Skip>(labels[Type::DATA],
                                                    pattern::has_class<op::v0::Reshape>());
    auto dot = std::make_shared<op::v0::Dot>(skip, labels[Type::WEIGHTS]);
    auto add_bias = std::make_shared<op::v1::Add>(dot, labels[Type::BIAS]);
    return std::make_shared<pattern::Matcher>(add_bias);
}

static std::shared_ptr<Node> construct_data_pattern(std::shared_ptr<pattern::op::Label> data_slice)
{
    auto reshape_slice =
        std::make_shared<op::v0::Reshape>(data_slice, AxisVector{0, 1, 2}, Shape{2, 4});
    auto W = std::make_shared<pattern::op::Label>(element::f32, Shape{4, 1});
    auto dot = std::make_shared<op::v0::Dot>(reshape_slice, W);
    auto broadcast = std::make_shared<pattern::op::Label>(element::f32, dot->get_output_shape(0));
    return dot + broadcast;
}

static std::shared_ptr<Node>
    construct_weights_pattern(std::shared_ptr<pattern::op::Label> weights_reshape)
{
    auto X = std::make_shared<pattern::op::Label>(element::f32, Shape{2, 4});
    auto dot = std::make_shared<op::v0::Dot>(X, weights_reshape);
    auto broadcast = std::make_shared<pattern::op::Label>(element::f32, dot->get_output_shape(0));
    return dot + broadcast;
}

static std::shared_ptr<Node>
    construct_bias_pattern(std::shared_ptr<pattern::op::Label> bias_broadcast)
{
    auto dot_label = std::make_shared<pattern::op::Label>(element::f32, Shape{2, 1});
    return dot_label + bias_broadcast;
}

bool runtime::cpu::pass::CPURnnMatFusion::run_on_function(std::shared_ptr<Function> function)
{
    bool modify_graph = false;

    //--------------------------------------------------------
    // Construct pattern version_1 for RNN input linear transformation
    auto data_slice = std::make_shared<pattern::op::Label>(
        element::f32, Shape{1, 2, 4}, pattern::has_class<op::v0::Slice>());
    auto data_pattern = construct_data_pattern(data_slice);

    auto weights_reshape = std::make_shared<pattern::op::Label>(
        element::f32, Shape{4, 1}, pattern::has_class<op::v0::Reshape>());
    auto weights_pattern = construct_weights_pattern(weights_reshape);

    // we don't really need a broadcast node but
    // labelling a Broadcast allows us to extract
    // params from all 3 labels in the same fashion
    //(i.e. via get_argument(0))
    auto bias_broadcast = std::make_shared<pattern::op::Label>(
        element::f32, Shape{2, 1}, pattern::has_class<op::v0::Broadcast>());
    auto bias_pattern = construct_bias_pattern(bias_broadcast);

    const size_t NUM_MMB_ARGS = 3;
    std::shared_ptr<pattern::op::Label> labels_v1[] = {data_slice, weights_reshape, bias_broadcast};
    // Matchers' ordering is important! Don't change!
    std::shared_ptr<pattern::Matcher> matchers_v1[] = {
        std::make_shared<pattern::Matcher>(data_pattern),
        std::make_shared<pattern::Matcher>(weights_pattern),
        std::make_shared<pattern::Matcher>(bias_pattern)};

    // this DS will be used to hold the matched attributes from matchers_v1
    std::map<std::shared_ptr<Node>, NodeVector> op_seg_map; // add to list of params
    std::map<NodeVector, NodeVector> param_list;
    //--------------------------------------------------------

    //--------------------------------------------------------
    // Construct pattern version_2 for RNN input linear transformation
    auto input_data = std::make_shared<pattern::op::Label>(
        element::f32, Shape{10, 50}, pattern::has_class<op::v0::Parameter>());
    auto W = std::make_shared<pattern::op::Label>(
        element::f32, Shape{50, 400}, pattern::has_class<op::v0::Reshape>());
    auto b = std::make_shared<pattern::op::Label>(
        element::f32, Shape{10, 400}, pattern::has_class<op::v0::Broadcast>());
    std::shared_ptr<pattern::op::Label> labels_v2[] = {input_data, W, b};
    auto matcher_v2 = construct_rnn_input_linear_transformation(labels_v2);

    // this DS will be used to hold the matched attributes from matcher_v2
    std::map<std::shared_ptr<Node>, NodeVector> map_weights_to_pattern;
    std::map<std::pair<std::shared_ptr<Node>, std::shared_ptr<Node>>, OutputVector>
        map_weights_bias_to_data;
    //--------------------------------------------------------

    for (auto n : function->get_ordered_ops())
    {
        NodeVector params;
        NodeVector matched_nodes;

        // checks if the graph matches to pattern defined in the matcher_v2
        if (matcher_v2->match(n))
        {
            auto matched_weight = matcher_v2->get_pattern_map()[W]->get_argument(0);
            auto matched_data = matcher_v2->get_pattern_map()[input_data];
            auto matched_bias = matcher_v2->get_pattern_map()[b]->get_argument(0);
            std::vector<size_t> supported_ranks{2, 3};

            if (!ngraph::is_valid_rank(matcher_v2->get_match_root(), supported_ranks))
            {
                NGRAPH_DEBUG << "Add (mat_fusion_v2) " << matcher_v2->get_match_root()->get_name()
                             << " isn't 2D or 3D";
                continue;
            }
            if (!ngraph::is_valid_rank(matched_weight, supported_ranks))
            {
                NGRAPH_DEBUG << "Weights (mat_fusion_v2) " << matched_weight << " isn't 2D or 3D";
                continue;
            }

            if (!ngraph::is_valid_rank(matched_data, supported_ranks))
            {
                NGRAPH_DEBUG << "Data (mat_fusion_v2) " << matched_data << " isn't 2D or 3D";
                continue;
            }

            map_weights_to_pattern[matched_weight].push_back(matcher_v2->get_match_root());
            map_weights_bias_to_data[std::make_pair(matched_weight, matched_bias)].push_back(
                matched_data);
        }

        for (size_t i = 0; i < NUM_MMB_ARGS; i++)
        {
            auto matcher = matchers_v1[i];
            if (matcher->match(n))
            {
                // if we get all 3 matches they will all fall
                // in the right spots (e.g. DATA, WEIGHTS, BIAS) since matchers are ordered
                // if we have less than 3 matches we skip this node anyways
                auto matched = matcher->get_pattern_map()[labels_v1[i]];
                params.push_back(matched->get_argument(0));
                matched_nodes.push_back(matched);
            }

            if (params.size() != NUM_MMB_ARGS)
            {
                continue;
            }

            // we have a full set for the current Add (n) i.e. data, weights, bias
            op_seg_map.insert(std::make_pair(n, matched_nodes));
            param_list[params].push_back(n);
        }
    }

    // remove params with single combo op (meaning no need to combine slicing)
    for (auto it = param_list.cbegin(); it != param_list.cend();)
    {
        if (it->second.size() < 2)
        {
            it = param_list.erase(it);
        }
        else
        {
            ++it;
        }
    }

    auto callback_matcher_v2 = [&]() -> void {
        // fuse the input vector to a matrix
        for (auto& it : map_weights_bias_to_data)
        {
            auto weights = it.first.first;
            auto bias = it.first.second;

            // if there's just one data node skip the optimization
            if (it.second.size() < 2)
            {
                return;
            }

            if (map_weights_to_pattern[weights].size() !=
                map_weights_bias_to_data[std::make_pair(weights, bias)].size())
            {
                NGRAPH_DEBUG << "number of input data param's doesnt match the number of matched "
                                "pattern root "
                             << "nodes";
                return;
            }
            auto& w_shape = weights->get_output_shape(0);
            if (w_shape.size() != 2)
            {
                NGRAPH_DEBUG << "weights shape for linear transformation of input is not 2D";
                return;
            }

            auto& data_param_nodes = it.second;
            // we will not fuse if the batch_size are not same across all inputs of time step
            for (auto& node : data_param_nodes)
            {
                if (shape_size(data_param_nodes[0].get_shape()) != shape_size(node.get_shape()))
                {
                    return;
                }
            }
            // now concat the parameter hashed to the same weights
            auto concated_data = std::make_shared<op::v0::Concat>(data_param_nodes, 0);

            auto& data_shape = concated_data->get_output_shape(0);
            auto data_order = ngraph::get_default_order(concated_data->get_output_shape(0));

            // insert reshape on the concated data to make it 2D, if its 3D
            std::shared_ptr<Node> input_reshape_node = nullptr;
            if (data_shape.size() == 3)
            {
                input_reshape_node = std::make_shared<op::v0::Reshape>(
                    concated_data, data_order, Shape{data_shape[0] * data_shape[1], data_shape[2]});
            }
            auto new_input_node = data_shape.size() == 2 ? concated_data : input_reshape_node;
            NGRAPH_CHECK(new_input_node);
            auto w_reshape_node = std::make_shared<op::v0::Reshape>(
                weights, AxisVector{1, 0}, Shape{w_shape[1], w_shape[0]});
            auto new_dot = std::make_shared<op::v0::Dot>(new_input_node, w_reshape_node);
            auto bias_broadcast_node =
                std::make_shared<op::v0::Broadcast>(bias, new_dot->get_output_shape(0), AxisSet{0});
            auto new_add_bias = std::make_shared<op::v1::Add>(new_dot, bias_broadcast_node);

            // now slice the new_add and feed the corrosponding root nodes
            auto batch_size = new_add_bias->get_output_shape(0)[0] / data_param_nodes.size();
            auto shape_axis_1 = new_add_bias->get_output_shape(0)[1];
            size_t start_index = 0;
            size_t end_index = batch_size;
            for (auto& matched_root_node : map_weights_to_pattern[weights])
            {
                std::shared_ptr<Node> slice_node = std::make_shared<op::v0::Slice>(
                    new_add_bias, Coordinate{start_index, 0}, Coordinate{end_index, shape_axis_1});

                if (matched_root_node->get_output_shape(0).size() != 2)
                {
                    NGRAPH_CHECK(matched_root_node->get_output_shape(0).size() == 3);
                    slice_node = std::make_shared<op::v0::Reshape>(
                        slice_node, AxisVector{0, 1}, matched_root_node->get_output_shape(0));
                }
                start_index += batch_size;
                end_index += batch_size;
                NGRAPH_DEBUG << "Replacing op " << matched_root_node->get_name() << " with "
                             << slice_node->get_name() << std::endl;
                function->replace_node(matched_root_node, slice_node);
            }
            modify_graph = true;
        }
    };

    auto callback_matcher_v1 = [&]() -> void {
        // Expecting input data shape D=[x, y, z], weights W=[u, v], bias B = [w]
        // where y is the time step. We are computing R=dot(D,W)=[x,y,v]. We can reshape D to
        // D'=[x*y, z], then we have dot(D',W), result
        // in R=[x*y, v], then add(R,B). We need to slice the result by strided by time steps.
        // iterate each unique set of parameters, replace original operations
        for (auto& p : param_list)
        {
            NodeVector params = p.first;
            NodeVector& op_nodes = p.second;

            // we will sort the captured Add(Dot(X, W) + B) as per the slice ordering of X
            // this will simplify the replace_node logic
            auto compare_slices = [&](const std::shared_ptr<Node> node1,
                                      const std::shared_ptr<Node> node2) {
                const auto node1_slice =
                    std::static_pointer_cast<op::v0::Slice>(op_seg_map[node1].at(Type::DATA));

                const auto node2_slice =
                    std::static_pointer_cast<op::v0::Slice>(op_seg_map[node2].at(Type::DATA));

                return (node1_slice->get_lower_bounds() < node2_slice->get_lower_bounds() &&
                        node1_slice->get_upper_bounds() < node2_slice->get_upper_bounds());
            };
            std::sort(op_nodes.begin(), op_nodes.end(), compare_slices);

            // we fuse all the data slices captured in the pattern to make bigger GEMM call
            auto fuse_data_slices = [&]() {
                OutputVector data_slices;
                for (auto& op : op_nodes)
                {
                    auto data_node = op_seg_map.at(op).at(Type::DATA);
                    data_slices.push_back(data_node);
                }
                return std::make_shared<op::v0::Concat>(data_slices, 0);
            };
            auto data_node = op_nodes.size() > 1 ? fuse_data_slices() : params.at(Type::DATA);
            auto weights_node = params.at(Type::WEIGHTS);
            auto bias_node = params.at(Type::BIAS);
            auto& data_shape = data_node->get_output_shape(0);

            // construct new op nodes
            auto data_reshape_node = std::make_shared<op::v0::Reshape>(
                data_node,
                AxisVector{0, 1, 2},
                Shape{data_shape[0] * data_shape[1], data_shape[2]});

            auto old_weights_reshape_node = op_seg_map.at(op_nodes.at(0)).at(Type::WEIGHTS);
            auto weights_reshape_node =
                old_weights_reshape_node->copy_with_new_inputs({weights_node});
            auto dot_node = std::make_shared<op::v0::Dot>(data_reshape_node, weights_reshape_node);
            const auto& dot_shape = dot_node->get_output_shape(0);

            auto bias_broadcast_node =
                std::make_shared<op::v0::Broadcast>(bias_node, dot_shape, AxisSet{0});
            auto add_node = std::make_shared<op::v1::Add>(dot_node, bias_broadcast_node);
            const auto& add_shape = add_node->get_output_shape(0);

            size_t num_timesteps = op_nodes.size();
            size_t batch_size = add_shape[0] / num_timesteps;
            size_t feature_size = add_shape[1];
            // create a slice for each user of the dot op matching the original dot op's output
            for (size_t i = 0, start_index = 0; i < op_nodes.size(); i++, start_index += batch_size)
            {
                // calculate the lower and upper bounds for the slice of the new fused node
                // ((<x0 | x1..|xt>*W)+b), which will used to replace the nodes matched in the
                // pattern
                const Coordinate lower_bounds{start_index, 0};
                const Coordinate upper_bounds{start_index + batch_size, feature_size};

                auto slice_node =
                    std::make_shared<op::v0::Slice>(add_node, lower_bounds, upper_bounds);

                // replace old nodes
                function->replace_node(op_nodes[i], slice_node);
            }
            modify_graph = true;
        }
    };

    // Based the matched pattern, this callback's fuse the input across time steps and replaces with
    // single DOT operation <X0|X1|X2|..... Xt>*W
    callback_matcher_v2();
    callback_matcher_v1();
    return modify_graph;
}

#define TI(x) std::type_index(typeid(x))

// Moved set_or_check_if_same and fuse_group_convolution, fuse_batch_mat_mul_transpose
// to core pass batch_fusion


text:
package v1beta1

import (
	"github.com/google/knative-gcp/pkg/reconciler/testing"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	duckv1 "knative.dev/pkg/apis/duck/v1"

	"github.com/google/knative-gcp/pkg/apis/events/v1beta1"
)

// CloudPubSubSourceOption enables further configuration of a CloudPubSubSource.
type CloudPubSubSourceOption func(*v1beta1.CloudPubSubSource)

// NewCloudPubSubSource creates a CloudPubSubSource with CloudPubSubSourceOptions
func NewCloudPubSubSource(name, namespace string, so ...CloudPubSubSourceOption) *v1beta1.CloudPubSubSource {
	ps := &v1beta1.CloudPubSubSource{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
			UID:       "test-pubsub-uid",
		},
	}
	for _, opt := range so {
		opt(ps)
	}
	return ps
}

func WithCloudPubSubSourceSink(gvk metav1.GroupVersionKind, name string) CloudPubSubSourceOption {
	return func(ps *v1beta1.CloudPubSubSource) {
		ps.Spec.Sink = duckv1.Destination{
			Ref: &duckv1.KReference{
				APIVersion: testing.ApiVersion(gvk),
				Kind:       gvk.Kind,
				Name:       name,
			},
		}
	}
}

func WithCloudPubSubSourceServiceAccount(kServiceAccount string) CloudPubSubSourceOption {
	return func(ps *v1beta1.CloudPubSubSource) {
		ps.Spec.ServiceAccountName = kServiceAccount
	}
}

func WithCloudPubSubSourceTopic(topicID string) CloudPubSubSourceOption {
	return func(ps *v1beta1.CloudPubSubSource) {
		ps.Spec.Topic = topicID
	}
}


text:
require 'hamlit/engine'
require 'hamlit/template'
require 'hamlit/version'

begin
  require 'hamlit/railtie'
rescue LoadError
end


text:
Slider

    <input type="radio" name="slider" id="slider-choice-1"/>Choice 1<input type="radio" name="slider" id="slider-choice-2"/>Choice 2<input type="radio" name="slider" id="slider-choice-3"/>Choice 3<input type="radio" name="slider" id="slider-choice-4"/>Choice 4


text:
/*
 * 文件名称:          ExpertController.java
 * 版权所有@ 2014-2016 无锡开云信息技术有限公司
 * 编译器:           JDK1.8
 * 时间:             上午9:38:15
 */
package com.ky.tao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ky.tao.common.utils.KYDateKit;
import com.ky.tao.db.model.Demand;
import com.ky.tao.entity.in.BaseDelete;
import com.ky.tao.entity.in.DemandSearch;
import com.ky.tao.service.DemandService;
import com.ky.tao.utils.Const;

/**
 * 流水 REST API
 *

 *

 * Version:        V1.0.0
 *

 * 作者:           liangjinjing
 *

 * 日期:           2016年10月29日
 *

 * 负责人:         liangjinjing
 *

 *

 */
@RestController
@RequestMapping(value="/demand")
public class DemandController
{
    @Autowired
    public DemandService demandService;

    /**
     *
     * @param expert
     * @return
     */
    @RequestMapping(value="/add", method=RequestMethod.POST)
    @ResponseBody
    public Object add(@RequestBody Demand demand)
    {
        demand.setCreateTime(KYDateKit.getCurrentDatetime());
        return demandService.insert(demand);
    }

    /**s
     *
     * @param expert
     * @return
     */
    @RequestMapping(value="/update", method=RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody Demand demand)
    {
        return demandService.update(demand);
    }

    /**
     *
     * @param ids
     * @return
     */
   @RequestMapping(value="/delete", method=RequestMethod.POST)
   @ResponseBody
    public Object delete(@RequestBody BaseDelete delete)
    {
        return demandService.delete(delete.getIds());
    }

    /**
     *
     * @param expert
     * @return
     */
    @RequestMapping(value="/search", method=RequestMethod.POST)
    @ResponseBody
    public Object search(@RequestBody DemandSearch search)
    {
        search.setOffset(Const.PAGE_SIZE * (search.getPageNumber() - 1));
        return demandService.search(search);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    @ResponseBody
    public Object findById(@PathVariable("id") long id)
    {
        return demandService.findById(id);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value="/user/{id}", method=RequestMethod.GET)
    @ResponseBody
    public Object findByUserId(@PathVariable("id") long id)
    {
        return demandService.findByUserId(id);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value="/expert/{id}", method=RequestMethod.GET)
    @ResponseBody
    public Object findByExpertId(@PathVariable("id") long id)
    {
        return demandService.findByExpertId(id);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value="/broker/{id}", method=RequestMethod.GET)
    @ResponseBody
    public Object findByBrokerUserId(@PathVariable("id") long id)
    {
        return demandService.findByBrokerUserId(id);
    }

}


text:
/*global describe,it,expect,spyOn*/

const ConfigPlugin = require('../lib/config-webpack-plugin');
const config1 = require('./fixture/config1');
const mergedConfig = require('./fixture/merged-config');
const webpackRunner = require('./helper/webpack-runner');

describe('config-webpack-plugin', () => {

    it('should be a function', () => {
        expect(typeof ConfigPlugin).toBe('function');
    });

    it('should complain when no configuration file is specified', () => {
        expect(() => new ConfigPlugin()).toThrow();
    });

    it('should invoke `apply` when webpack is resolving modules', (done) => {
        let plugin = new ConfigPlugin('./test/fixture/config1.js');
        spyOn(plugin, 'apply').and.callThrough();

        webpackRunner.run(plugin, () => {
            expect(plugin.apply).toHaveBeenCalled();
            done();
        });
    });

    it('should invoke `intercept` when webpack try to resolve the specified configuration file', (done) => {
        let plugin = new ConfigPlugin('./test/fixture/config1.js');
        spyOn(plugin, 'intercept').and.callThrough();

        webpackRunner.run(plugin, () => {
            expect(plugin.intercept).toHaveBeenCalled();
            done();
        });
    });

    it('should not do anything with the specified configuration file when plugin is not installed', (done) => {
        webpackRunner.run(null, (output) => {
            expect(output).toEqual(config1);
            done();
        });
    });

    it('should not do anything with the specified configuration file when there is no matching environment variables', (done) => {
        let plugin = new ConfigPlugin('./test/fixture/config1.js');
        webpackRunner.run(plugin, (output) => {
            expect(output).toEqual(config1);
            done();
        });
    });

    it('should modify the source of the specified configuration file when there is a matching environment variable', (done) => {
        try {
            process.env.name = 'intercepted';
            let plugin = new ConfigPlugin('./test/fixture/config1.js');
            webpackRunner.run(plugin, (output) => {
                expect(output.name).toBe('intercepted');
                done();
            });
        } finally {
            delete process.env.name;
        }
    });

    it('should merge multiple configuration files', (done) => {
        let plugins = new ConfigPlugin([
            './test/fixture/config1.js',
            './test/fixture/config2.js'
        ]);
        webpackRunner.run(plugins, (output) => {
            expect(output).toEqual(mergedConfig);
            done();
        });
    });
});


text:
package exemplo;

import java.util.List;
import negocio.*;
import persistencia.*;

/**
 *
 * @author julio, bernardo, agustini
 */
public class ExemploConsole {
    public static void main(String[] args) throws Exception {
        System.out.println("Inicializando driver...");
        InicializadorBancoDados.inicializar();

        //Utilize o seguinte código somente a primeira vez que executar
        //System.out.println("Criando BD...");
        //InicializadorBancoDados.criarBd();

         //Manipulando autores
        AutorDAO daoAutor = new AutorDAOderby();
        //System.out.println("Inserir autores...");
        //daoAutor.inserir(new Autor(1, "John", "Doe"));
        //daoAutor.inserir(new Autor(2, "Mary", "Doe"));
        //daoAutor.inserir(new Autor(3, "Mrs", "Smith"));
        System.out.println("Listando autores...");
        List<Autor> autores = daoAutor.buscarTodos();
        for(Autor autor : autores) {
            System.out.println(autor);
        }
        System.out.println("Listando autores por nome...");
        /*List<Autor>*/ autores = daoAutor.buscarPorUltimoNome("Doe");
        for(Autor autor : daoAutor.buscarTodos()) {
            System.out.println(autor);
        }

        System.out.println("Buscando autor...");
        System.out.println(daoAutor.buscarPorCodigo(1));
        System.out.println("Alterando autor...");
        Autor a = daoAutor.buscarPorCodigo(1);
        a.setPrimeiroNome("Vitor");
        daoAutor.alterar(a);
        System.out.println(daoAutor.buscarPorCodigo(1));

        //Manipulacao de editoras
        EditoraDAO daoEditora = new EditoraDAOderby();
        //System.out.println("Inserir editoras...");
        //daoEditora.inserir(new Editora(1, "Editora Campus"));
        //daoEditora.inserir(new Editora(2, "Editora Pearson"));
        //daoEditora.inserir(new Editora(3, "editora McGraw-Hill"));

        System.out.println("\nListando editoras...");
        List<Editora> editoras = daoEditora.buscarTodos();
        for(Editora ed : editoras) {
            System.out.println(ed);
        }
        /*
        System.out.println("\nBuscando editora e corrige o nome...");
        Editora ed = daoEditora.buscarPorCodigo(1);

        System.out.println(ed);

        System.out.println("Alterando  nome...");
        ed.setNome("Editora Campos - Elsevier");
        daoEditora.alterar(ed);
        System.out.println("\nno banco, alterado: \n"+daoEditora.buscarPorCodigo(1));

        // inserção de chave duplicada
        try {
            daoEditora.inserir(new Editora(3, "Erro"));
        } catch (DAOEditoraException ex) {
           System.out.println("\nerro: \n"+ex.getMessage());
        }
        */

        // Manipulacao de livros

        LivroDAO daoLivro = new LivroDAOderby();
        //System.out.println("Inserindo livros");
        //Editora ed1 = daoEditora.buscarPorCodigo(1);
        //Autor aut1 = daoAutor.buscarPorCodigo(1);

        //daoLivro.inserir(new Livro(1,"Java for dummys",2013,ed1,aut1));
        //daoLivro.inserir(new Livro(2,"Camada de persistencia",2011,ed1,
        //                     daoAutor.buscarPorCodigo(2)));
        //daoLivro.inserir(new Livro(3,"Padrao DAO",2012,
        //                     daoEditora.buscarPorCodigo(3),
        //                     daoAutor.buscarPorCodigo(2)));
        //Livro livro4 = new Livro(4,"Varios autores",2012,
        //                     daoEditora.buscarPorCodigo(3),
        //                     daoAutor.buscarPorCodigo(1));
        //livro4.addAutor(daoAutor.buscarPorCodigo(2));
        //livro4.addAutor(daoAutor.buscarPorCodigo(3));
        //daoLivro.inserir(livro4);

        System.out.println("\nListando livros...");
        List<Livro> livros = daoLivro.buscarTodos();
        for(Livro l : livros) {
            System.out.println(l);
        }

        System.out.println("\nBuscando livro pelo código...");
        System.out.println("(cod=4) " + daoLivro.buscarPorCodigo(4));
        System.out.println("(cod=7) " + daoLivro.buscarPorCodigo(7));

         System.out.println("\nBuscando livro pela editora...");
        System.out.println("(ed=1) " + daoLivro.buscarPorEditora(1));
        System.out.println("(ed=7) " + daoLivro.buscarPorEditora(7));
        /*
        Livro livro2 = daoLivro.buscarPorCodigo(2);
        Autor autor2 = daoAutor.buscarPorCodigo(3);
        System.out.println("\nAltera dados do livro...");
        livro2.setTitulo("Duro de Matar 52");
        livro2.setAno(2032);
        livro2.setEditora(daoEditora.buscarPorCodigo(1));
        livro2.addAutor(aut1);

        daoLivro.alterar(livro2);

        System.out.println(daoLivro.buscarPorCodigo(2));
        */
    }
}


text:
import java.util.Scanner;
/*
 * B. Simple Game
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a.

Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.

Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.

More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that  is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).

Input
The first line contains two integers n and m (1 ≤ m ≤ n ≤ 10^9) — the range of numbers in the game, and the number selected by Misha respectively.

Output
Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.
 */
public class SimpleGame {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int N = input.nextInt();
		int M = input.nextInt();
		if (N == 1 & M == 1) {
			System.out.println(1);
		} else {
			input.nextLine();
			double mid = (N + 1) / 2.0;
			if (M >= mid - 0.1) {
				// guard against rounding error. If there is a tie, we always
				// want M to be slightly larger.
				System.out.println(M - 1);
			} else {
				System.out.println(M + 1);
			}
		}
	}
}


text:
clock = require("clock")
test = require("tap").test("csv")
test:plan(9)
test:ok(clock.realtime() > 0, "realtime")
test:ok(clock.thread() > 0, "thread")
test:ok(clock.monotonic() > 0, "monotonic")
test:ok(clock.proc() > 0, "proc")
test:ok(clock.realtime64() > 0, "realtime64")
test:ok(clock.thread64() > 0, "thread64")
test:ok(clock.monotonic64() > 0, "monotonic64")
test:ok(clock.proc64() > 0, "proc64")

test:ok(clock.monotonic() <= clock.monotonic(), "time is monotonic")
test:ok(math.abs(clock.realtime() - os.time()) < 2, "clock.realtime ~ os.time")


text:
FROM library/golang
MAINTAINER liuzheng712<liuzheng712@gmail.com>

ADD sources.list /etc/apt/sources.list
ADD ./gvm-installer /tmp/gvm-installer
RUN apt-get -qqy update
RUN apt-get install -qqy sshfs bison
RUN mkdir /root/test &&\
    bash /tmp/gvm-installer &&\
    /bin/bash -c "source /root/.gvm/scripts/gvm"

WORKDIR /root/test


text:
import { guid }  from '../../helpers/object';

export const helpers = {
    guid: guid
};

export const ADD_NOTIFICATION = 'ADD_NOTIFICATION';
export const addNotification = (type, message) => (
    {
        type: ADD_NOTIFICATION,
        payload: {
            id: helpers.guid(),
            type,
            message
        }
    }
);

export const REMOVE_NOTIFICATION = 'REMOVE_NOTIFICATION';
export const removeNotification = (id) => (
    {
        type: REMOVE_NOTIFICATION,
        payload: {
            id
        }
    }
);

export const REMOVE_ALL_NOTIFICATIONS = 'REMOVE_ALL_NOTIFICATIONS';
export const removeAllNotifications = () => (
    {
        type: REMOVE_ALL_NOTIFICATIONS,
        payload: {}
    }
);


text:
using System.Collections;
using System.Collections.Generic;

namespace MikiUtilities.Collections.Generic
{
    public class SortedList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
    {

        private List<T> _wrapped;
        private IComparer<T> _comparer;

        public T this[int index]
        {
            get
            {
                return ((IList<T>)_wrapped)[index];
            }

            set
            {
                ((IList<T>)_wrapped)[index] = value;
            }
        }

        #region CONSTRUCTORS
        public SortedList()
        {
            _wrapped = new List<T>();
            _comparer = Comparer<T>.Default;
        }

        public SortedList(IEnumerable<T> toCopy)
        {
            _wrapped = new List<T>(toCopy);
            _wrapped.Sort();
            _comparer = Comparer<T>.Default;
        }

        public SortedList(int capacity)
        {
            _wrapped = new List<T>(capacity);
            _comparer = Comparer<T>.Default;
        }

        public SortedList(IComparer<T> comparer)
        {
            _comparer = comparer;
            _wrapped = new List<T>();
        }

        public SortedList(IEnumerable<T> toCopy, IComparer<T> comparer)
        {
            _comparer = comparer;
            _wrapped = new List<T>(toCopy);
            _wrapped.Sort(_comparer);
        }

        public SortedList(int capacity, IComparer<T> comparer)
        {
            _comparer = comparer;
            _wrapped = new List<T>(capacity);
        }
        #endregion

        public int Count
        {
            get
            {
                return _wrapped.Count;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                return ((IList<T>)_wrapped).IsReadOnly;
            }
        }

        public void Add(T item)
        {
            int i = 0;
            for (i = 0; i < _wrapped.Count; i++)
                if (_comparer.Compare(_wrapped[i], item) > 0)
                    break;
            _wrapped.Insert(i, item);
        }

        public void Clear()
        {
            _wrapped.Clear();
        }

        public bool Contains(T item)
        {
            return _wrapped.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _wrapped.CopyTo(array, arrayIndex);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _wrapped.GetEnumerator();
        }

        public int IndexOf(T item)
        {
            return _wrapped.IndexOf(item);
        }

        public bool Remove(T item)
        {
            return _wrapped.Remove(item);
        }

        public void RemoveAt(int index)
        {
            _wrapped.RemoveAt(index);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _wrapped.GetEnumerator();
        }
    }
}


text:
package com.twilight.h264.decoder;

public class MotionEstContext {
	/**
	 * Motion estimation context.
	 */
    public DSPContext.Ih264_qpel_mc_func[][] qpel_put; //[16][4];
    public DSPContext.Ih264_qpel_mc_func[][]qpel_avg;  //[16][4];

    /*
    uint8_t *scratchpad;               ///< data area for the ME algo, so that the ME does not need to malloc/free
    uint8_t *best_mb;
    uint8_t *temp_mb[2];
    uint8_t *temp;
    */

    public int[] scratchpad;               ///< data area for the ME algo, so that the ME does not need to malloc/free
    public int[] best_mb;
    public int[][] temp_mb;
    public int[] temp;

    //uint32_t *map;                     ///< map to avoid duplicate evaluations
    //uint32_t *score_map;               ///< map to store the scores
    public int[] map;                     ///< map to avoid duplicate evaluations
    public int[] score_map;               ///< map to store the scores

}


text:
package net.luxvacuos.voxel.client.core.states;

import net.luxvacuos.lightengine.universal.core.states.AbstractState;
import net.luxvacuos.voxel.universal.world.IWorld;

public class WorldSimulationState extends AbstractState {
	//Network Handler Interface (localhost, LAN, Web)
	private IWorld world;
	//private Client client;

	public WorldSimulationState() {
		super(StateNames.WORLD_SIM);
	}

	@Override
	public void update( float arg1) {
	}

}


text:
class CreateTalent < ActiveRecord::Migration
  def change
    create_table :talents do |t|
      t.string :title
      t.text :description
      t.integer :category_id
      t.integer :user_id
      t.boolean :recommended, :default => false
      t.string :state, :default => 'published'
      t.string :permalink

      t.timestamps
    end
  end
end


text:
package io.novaordis.release.sequences;

import io.novaordis.release.MockConfiguration;
import io.novaordis.release.MockOS;
import io.novaordis.release.MockReleaseApplicationRuntime;
import io.novaordis.release.clad.ConfigurationLabels;
import io.novaordis.release.model.MockProject;
import io.novaordis.release.model.ArtifactType;
import io.novaordis.utilities.Files;
import io.novaordis.utilities.UserErrorException;
import io.novaordis.utilities.os.OS;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * @author Ovidiu Feodorov <ovidiu@novaordis.com>
 * @since 11/17/16
 */
public class InstallSequenceTest extends SequenceTest {

    // Constants -------------------------------------------------------------------------------------------------------

    private static final Logger log = LoggerFactory.getLogger(InstallSequenceTest.class);

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    private File scratchDirectory;
    @SuppressWarnings("FieldCanBeLocal")
    private File baseDirectory;

    // Constructors ----------------------------------------------------------------------------------------------------

    // Public ----------------------------------------------------------------------------------------------------------

    @Before
    public void before() throws Exception {

        String projectBaseDirName = System.getProperty("basedir");
        scratchDirectory = new File(projectBaseDirName, "target/test-scratch");
        assertTrue(scratchDirectory.isDirectory());

        baseDirectory = new File(System.getProperty("basedir"));
        assertTrue(baseDirectory.isDirectory());

        System.setProperty("os.class", MockOS.class.getName());
    }

    @After
    public void after() throws Exception {

        ((MockOS) io.novaordis.utilities.os.OS.getInstance()).reset();
        System.clearProperty("os.class");

        assertTrue(Files.rmdir(scratchDirectory, false));
    }

    // execute() -------------------------------------------------------------------------------------------------------

    @Test
    public void execute_TheArtifactIsAJavaLibrary() throws Exception {

        InstallSequence is = new InstallSequence();

        MockProject mp = new MockProject("1.0");

        mp.addArtifact(ArtifactType.JAR_LIBRARY, new File("mock.jar"), null);

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(new MockConfiguration());

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        assertFalse(is.execute(c));
    }

    @Test
    public void execute_ArtifactRepositoryRootNotConfigured() throws Exception {

        InstallSequence is = new InstallSequence();

        MockProject mp = new MockProject("1.0");

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(new MockConfiguration());

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File("/does/not/matter.zip"), null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("the local artifact repository root not configured", msg);
        }
    }

    @Test
    public void execute_ArtifactRepositoryRootNotAValidDirectory() throws Exception {

        InstallSequence is = new InstallSequence();

        MockConfiguration mc = new MockConfiguration();
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, "/I/am/sure/there/is/no/such/directory");
        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        MockProject mp = new MockProject("1.0");
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File("/does/not/matter.zip"), null);

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("the local artifact repository root .* is not a valid directory"));
        }
    }

    @Test
    public void execute_DistributionFileNotAvailableInTheArtifactRepositoryNorLocally() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());

        MockProject mp = new MockProject("1.0");
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION,
                new File("I/am/sure/there/is/no/such/file/in/repository.zip"),
                new File("I/am/sure/there/is/no/such/file/locally.zip"));

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("binary distribution artifact not found in the artifact repository, nor in the local work area"));
        }
    }

    @Test
    public void execute_RuntimeDirectoryNotConfigured() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, "test.zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("the runtime directory not configured", msg);
        }
    }

    @Test
    public void execute_RuntimeDirectoryNotAValidDirectory() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, "test.zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, "/I/am/sure/there/is/no/such/directory");

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("the runtime directory .* is not a valid directory"));
        }
    }

    @Test
    public void execute_RuntimeDirectoryNotWritable() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, "test.zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        assertTrue(Files.chmod(rd, "r--r--r--"));

        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("the runtime directory .* is not writable"));
        }
    }

    @Test
    public void execute_ArtifactExtractionInRuntimeDirectoryFails() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, "test.zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        MockOS mockOS = (MockOS) OS.getInstance();
        mockOS.allCommandsFail();

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("failed to extract.*"));
        }
    }

    @Test
    public void execute_NoEmbeddedInstallationScript() throws Exception {

        InstallSequence is = new InstallSequence();

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, "test.zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);

        MockOS mockOS = (MockOS) OS.getInstance();
        mockOS.allCommandsSucceedByDefault();

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertTrue(msg.matches("no installation script .* found or the file is not executable"));
        }
    }

    @Test
    public void execute_EmbeddedInstallationScriptFails() throws Exception {

        InstallSequence is = new InstallSequence();

        String distributionFileName = "test-distribution-1.0";

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, distributionFileName + ".zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);
        mr.setBinaryDistributionTopLevelDirectoryName(distributionFileName);

        MockOS mockOS = (MockOS) OS.getInstance();
        mockOS.allCommandsSucceedByDefault();

        //
        // the only command that fails is the installation script
        //
        mockOS.addToCommandsThatFail(".install");

        //
        // make sure the script is "found" as unzip is jut mock
        //

        File installationScript = new File(rd, distributionFileName + "/bin/.install");
        assertTrue(Files.write(installationScript, "#/bin/bash\n\necho ."));
        assertTrue(Files.chmod(installationScript, "r-xr--r--"));

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        try {

            is.execute(c);
            fail("should throw exception");
        }
        catch(UserErrorException e) {

            String msg = e.getMessage();
            log.info(msg);
            assertEquals("installation failed", msg);
        }
    }

    @Test
    public void execute_Success_RepositoryFile() throws Exception {

        InstallSequence is = new InstallSequence();

        String distributionFileName = "test-distribution-1.0";

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();
        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());

        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());
        MockProject mp = new MockProject("1.0");
        File distributionFile = new File(localArtifactRepositoryRoot, distributionFileName + ".zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File(distributionFile.getName()), null);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);
        mr.setBinaryDistributionTopLevelDirectoryName(distributionFileName);

        MockOS mockOS = (MockOS) OS.getInstance();
        mockOS.allCommandsSucceedByDefault();

        //
        // successful execution
        //
        mockOS.allCommandsSucceedByDefault();

        //
        // make sure the script is "found" as unzip is jut mock
        //

        File installationScript = new File(rd, distributionFileName + "/bin/.install");
        assertTrue(Files.write(installationScript, "#/bin/bash\n\necho ."));
        assertTrue(Files.chmod(installationScript, "r-xr--r--"));

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        assertTrue(is.execute(c));

        List<String> commands = mockOS.getHistory();
        assertEquals(2, commands.size());

        String command = commands.get(0);
        assertTrue(command.startsWith("unzip"));

        String command2 = commands.get(1);
        assertEquals(".install", command2);
    }

    @Test
    public void execute_Success_LocalFile() throws Exception {

        InstallSequence is = new InstallSequence();

        String distributionFileName = "test-distribution-1.0";

        //
        // the local artifact repository root must be configured and exist
        //
        MockConfiguration mc = new MockConfiguration();

        File localArtifactRepositoryRoot = new File(scratchDirectory, "mock-artifact-repository");
        assertTrue(localArtifactRepositoryRoot.mkdir());
        mc.set(ConfigurationLabels.LOCAL_ARTIFACT_REPOSITORY_ROOT, localArtifactRepositoryRoot.getAbsolutePath());

        File targetDirSimulation = new File(scratchDirectory, "project/release/target");
        assertTrue(targetDirSimulation.mkdirs());

        MockProject mp = new MockProject("1.0");

        File distributionFile = new File(targetDirSimulation, distributionFileName + ".zip");
        assertTrue(Files.write(distributionFile, "..."));
        mp.addArtifact(ArtifactType.BINARY_DISTRIBUTION, new File("does-not-matter.zip"), distributionFile);

        File rd = new File(scratchDirectory, "test-runtime-dir");
        assertTrue(rd.mkdir());
        mc.set(ConfigurationLabels.INSTALLATION_DIRECTORY, rd.getAbsolutePath());

        MockReleaseApplicationRuntime mr = new MockReleaseApplicationRuntime(mc);
        mr.setBinaryDistributionTopLevelDirectoryName(distributionFileName);

        MockOS mockOS = (MockOS) OS.getInstance();
        mockOS.allCommandsSucceedByDefault();

        //
        // successful execution
        //
        mockOS.allCommandsSucceedByDefault();

        //
        // make sure the script is "found" as unzip is jut mock
        //

        File installationScript = new File(rd, distributionFileName + "/bin/.install");
        assertTrue(Files.write(installationScript, "#/bin/bash\n\necho ."));
        assertTrue(Files.chmod(installationScript, "r-xr--r--"));

        SequenceExecutionContext c = new SequenceExecutionContext(mr, mp, null, null);

        assertTrue(is.execute(c));

        List<String> commands = mockOS.getHistory();
        assertEquals(2, commands.size());

        String command = commands.get(0);
        assertTrue(command.startsWith("unzip"));

        String command2 = commands.get(1);
        assertEquals(".install", command2);
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    @Override
    protected InstallSequence getSequenceToTest() throws Exception {

        return new InstallSequence();
    }

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}


text:
from __future__ import print_function, division

from .sed import *
from .cube import *