text:
The Ember Data store provides an interface for retrieving records of a single
type.

### Retrieving a Single Record

Use `store.findRecord()` to retrieve a record by its type and ID. This will
return a promise that fulfills with the requested record:

```javascript
var post = this.store.findRecord('post', 1); // => GET /posts/1
```

Use `store.peekRecord()` to retrieve a record by its type and ID, without making
a network request. This will return the record only if it is already present in
the store:

```javascript
var post = this.store.peekRecord('post', 1); // => no network request
```

### Retrieving Multiple Records

Use `store.findAll()` to retrieve all of the records for a given type:

```javascript
var posts = this.store.findAll('post'); // => GET /posts
```

Use `store.peekAll()` to retrieve all of the records for a given type that are
already loaded into the store, without making a network request:

```javascript
var posts = this.store.peekAll('post'); // => no network request
```

`store.findAll()` returns a `DS.PromiseArray` that fulfills to a
`DS.RecordArray` and `store.peekAll` directly returns a `DS.RecordArray`.

It's important to note that `DS.RecordArray` is not a JavaScript array.  It is
an object that implements [`Ember.Enumerable`][1]. This is important because,
for example, if you want to retrieve records by index, the `[]` notation will
not work--you'll have to use `objectAt(index)` instead.

[1]: http://emberjs.com/api/classes/Ember.Enumerable.html

### Querying for Multiple Records

Ember Data provides the ability to query for records that meet certain criteria. Calling `store.query()`
will make a `GET` request with the passed object serialized as query params. This method returns
`DS.PromiseArray` in the same way as `find`.

For example, we could search for all `person` models who have the name of
`Peter`:

```javascript
var peters = this.store.query('person', { name: 'Peter' }); // => GET to /persons?name=Peter
```

### Integrating with the Route's Model Hook

As discussed in [Specifying a Route's Model][3], routes are
responsible for telling their template which model to render.

[3]: ../../routing/specifying-a-routes-model

`Ember.Route`'s `model` hook supports asynchronous values
out-of-the-box. If you return a promise from the `model` hook, the
router will wait until the promise has fulfilled to render the
template.

This makes it easy to write apps with asynchronous data using Ember
Data. Just return the requested record from the `model` hook, and let
Ember deal with figuring out whether a network request is needed or not.

```app/router.js
var Router = Ember.Router.extend({});

Router.map(function() {
  this.route('posts');
  this.route('post', { path: ':post_id' });
});

export default Router;
```

```app/routes/posts.js
export default Ember.Route.extend({
  model() {
    return this.store.findAll('post');
  }
});
```

```app/routes/post.js
export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('post', params.post_id);
  }
})
```


text:
package com.bj58.spat.gaea.server.components.protocol;

public class TestEntity {

	private Boolean fBoolean;
	private Byte fByte;
	private Character fCharacter;
	private Double fDouble;
	private Float fFloat;
	private Integer fInteger;
	private Long fLong;
	private Short fShort;
	private String fString;
	private boolean fboolean;
	private byte fbyte;
	private char fchar;
	private double fdouble;
	private float ffloat;
	private int fint;
	private long flong;
	private short fshort;
	private Object fObject;

	public Boolean getFBoolean() {
		return fBoolean;
	}

	public void setFBoolean(Boolean boolean1) {
		fBoolean = boolean1;
	}

	public Byte getFByte() {
		return fByte;
	}

	public void setFByte(Byte byte1) {
		fByte = byte1;
	}

	public Character getFCharacter() {
		return fCharacter;
	}

	public void setFCharacter(Character character) {
		fCharacter = character;
	}

	public Double getFDouble() {
		return fDouble;
	}

	public void setFDouble(Double double1) {
		fDouble = double1;
	}

	public Float getFFloat() {
		return fFloat;
	}

	public void setFFloat(Float float1) {
		fFloat = float1;
	}

	public Integer getFInteger() {
		return fInteger;
	}

	public void setFInteger(Integer integer) {
		fInteger = integer;
	}

	public Long getFLong() {
		return fLong;
	}

	public void setFLong(Long long1) {
		fLong = long1;
	}

	public Short getFShort() {
		return fShort;
	}

	public void setFShort(Short short1) {
		fShort = short1;
	}

	public String getFString() {
		return fString;
	}

	public void setFString(String string) {
		fString = string;
	}

	public boolean isFboolean() {
		return fboolean;
	}

	public void setFboolean(boolean fboolean) {
		this.fboolean = fboolean;
	}

	public byte getFbyte() {
		return fbyte;
	}

	public void setFbyte(byte fbyte) {
		this.fbyte = fbyte;
	}

	public char getFchar() {
		return fchar;
	}

	public void setFchar(char fchar) {
		this.fchar = fchar;
	}

	public double getFdouble() {
		return fdouble;
	}

	public void setFdouble(double fdouble) {
		this.fdouble = fdouble;
	}

	public float getFfloat() {
		return ffloat;
	}

	public void setFfloat(float ffloat) {
		this.ffloat = ffloat;
	}

	public int getFint() {
		return fint;
	}

	public void setFint(int fint) {
		this.fint = fint;
	}

	public long getFlong() {
		return flong;
	}

	public void setFlong(long flong) {
		this.flong = flong;
	}

	public short getFshort() {
		return fshort;
	}

	public void setFshort(short fshort) {
		this.fshort = fshort;
	}

	public Object getFObject() {
		return fObject;
	}

	public void setFObject(Object object) {
		fObject = object;
	}

	public static TestEntity createInstrance() {
		TestEntity te = new TestEntity();
		te.setFboolean(true);
		te.setFBoolean(new Boolean(true));
		te.setFbyte((byte) 1);
		te.setFByte(new Byte((byte) 255));
		te.setFchar((char) 'a');
		te.setFCharacter(new Character((char) 'z'));
		te.setFdouble(123456.789D);
		te.setFDouble(new Double(987.123456D));
		te.setFfloat(123.456F);
		te.setFFloat(new Float(123456.789F));
		te.setFint(123456);
		te.setFInteger(new Integer(654321));
		te.setFlong(123456789L);
		te.setFLong(new Long(987654321L));
		te.setFshort((short) 123);
		te.setFShort(new Short((short) 123));
		te.setFString("hello world");

		TestEntityII teII = new TestEntityII();
		teII.setId(1);
		teII.setTitle("titletitletitle");
		te.setFObject(teII);
		return te;
	}
}

redpajama_set_name: RedPajamaGithub


text:
[![npm version](https://badge.fury.io/js/%40resolve-js%2Fruntime-single-process.svg)](https://badge.fury.io/js/%40resolve-js%2Fruntime-single-process)

This package contains a runtime backend server that targets a standalone server or local machine.

## Available Options

You can specify the following options to configure the runtime:

- `importMode`- Specifies whether to use static or dynamic imports between the application's modules.
- `host` - Specifies the network host on which to listen for connections. Defaults to `'0.0.0.0'`.
- `port` - Specifies the server application's port.

## Usage

```js
// config.prod.js
const prodConfig = {
  runtime: {
    module: '@resolve-js/runtime-single-process',
    options: {
      host: declareRuntimeEnv('HOST', 'localhost'),
      port: declareRuntimeEnv('PORT', '3000'),
    },
  },
  ...
}
```

![Analytics](https://ga-beacon.appspot.com/UA-118635726-1/packages-resolve-runtime-single-process-readme?pixel)


text:
// +build !ignore_autogenerated

// Code generated by conversion-gen. DO NOT EDIT.

package v1alpha1

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	config "k8s.io/component-base/config"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
	if err := s.AddConversionFunc((*config.ClientConnectionConfiguration)(nil), (*ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(a.(*config.ClientConnectionConfiguration), b.(*ClientConnectionConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*config.DebuggingConfiguration)(nil), (*DebuggingConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(a.(*config.DebuggingConfiguration), b.(*DebuggingConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*config.LeaderElectionConfiguration)(nil), (*LeaderElectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(a.(*config.LeaderElectionConfiguration), b.(*LeaderElectionConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*ClientConnectionConfiguration)(nil), (*config.ClientConnectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(a.(*ClientConnectionConfiguration), b.(*config.ClientConnectionConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*DebuggingConfiguration)(nil), (*config.DebuggingConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(a.(*DebuggingConfiguration), b.(*config.DebuggingConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*LeaderElectionConfiguration)(nil), (*config.LeaderElectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(a.(*LeaderElectionConfiguration), b.(*config.LeaderElectionConfiguration), scope)
	}); err != nil {
		return err
	}
	return nil
}

func autoConvert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in *ClientConnectionConfiguration, out *config.ClientConnectionConfiguration, s conversion.Scope) error {
	out.Kubeconfig = in.Kubeconfig
	out.AcceptContentTypes = in.AcceptContentTypes
	out.ContentType = in.ContentType
	out.QPS = in.QPS
	out.Burst = in.Burst
	return nil
}

func autoConvert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in *config.ClientConnectionConfiguration, out *ClientConnectionConfiguration, s conversion.Scope) error {
	out.Kubeconfig = in.Kubeconfig
	out.AcceptContentTypes = in.AcceptContentTypes
	out.ContentType = in.ContentType
	out.QPS = in.QPS
	out.Burst = in.Burst
	return nil
}

func autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

func autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

func autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_Pointer_bool_To_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	out.ResourceName = in.ResourceName
	out.ResourceNamespace = in.ResourceNamespace
	return nil
}

func autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_bool_To_Pointer_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	out.ResourceName = in.ResourceName
	out.ResourceNamespace = in.ResourceNamespace
	return nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.wisdom.coffee</groupId>
    <artifactId>wisdom-coffeeshop-project</artifactId>
    <version>1.0</version>

    <properties>
        <wisdom.version>0.7-SNAPSHOT</wisdom.version>
    </properties>

    <packaging>pom</packaging>

    <modules>
        <module>coffee-shop-api</module>
        <module>arabica-coffee-provider</module>
        <module>wisdom-coffee-shop</module>
        <module>fortune-coffee</module>
    </modules>
</project>


text:
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE QuasiQuotes         #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Test.Prelude.Maybe (tests) where

import           Stg.Marshal
import           Stg.Parser.QuasiQuoter
import qualified Stg.Prelude            as Stg

import Test.Machine.Evaluate.TestTemplates.MarshalledValue
import Test.Orphans                                        ()
import Test.Tasty

tests :: TestTree
tests = testGroup "Maybe"
    [ testMaybe ]

testMaybe :: TestTree
testMaybe = marshalledValueTest defSpec
    { testName = "maybe"
    , sourceSpec = \(nothingCase, maybeInt :: Maybe Integer, offset) -> MarshalSourceSpec
        { resultVar = "main"
        , expectedValue = maybe nothingCase (+offset) maybeInt
        , source = mconcat
            [ toStg "nothingCase" nothingCase
            , toStg "maybeInt" maybeInt
            , toStg "offset" offset
            , Stg.maybe
            , Stg.add
            , [stg|
                main = \ =>
                    let addOffset = \x -> add x offset
                    in maybe nothingCase addOffset maybeInt |]]}}


text:
class Solution {
public:
    // O(nlogn) time, O(n) space.
    bool isCovered(vector<vector<int>>& ranges, int left, int right) {
        std::sort(ranges.begin(), ranges.end(), [](const vector<int>& left, const vector<int>& right)->bool {
           if (left[0] != right[0]) {
               return (left[0] < right[0]);
           }
           return (left[1] < right[1]);
        });

        std::priority_queue<int, vector<int>, std::greater<int>> min_heap;
        int last_closed = std::numeric_limits<int>::min();
        int running_count = 0;

        for (const vector<int>& range : ranges) {
            int curr_open = range[0];
            int curr_close = range[1];

            while (!min_heap.empty() && min_heap.top() < curr_open) {
                last_closed = min_heap.top();
                min_heap.pop();
                running_count--;
            }

            if (running_count == 0 && left > last_closed && left < curr_open) { return false; }
            if (running_count == 0 && right > last_closed && right < curr_open) { return false; }
            if (running_count == 0 && left <= last_closed && right >= curr_open
                && (curr_open - last_closed > 1)) {return false;}

            running_count++;  // for current open
            min_heap.push(curr_close);
        }

        while (!min_heap.empty()) {
            last_closed = min_heap.top();
            min_heap.pop();
            running_count--;
        }
        if (left > last_closed || right > last_closed) return false;
        return true;
    }
};


text:
"""Tests for common layers."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Dependency imports

import numpy as np
from tensor2tensor.layers import common_layers

import tensorflow as tf

class CommonLayersTest(tf.test.TestCase):

  def testStandardizeImages(self):
    x = np.random.rand(5, 7, 7, 3)
    with self.test_session() as session:
      y = common_layers.standardize_images(tf.constant(x))
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 7, 3))

  def testImageAugmentation(self):
    x = np.random.rand(500, 500, 3)
    with self.test_session() as session:
      y = common_layers.image_augmentation(tf.constant(x))
      res = session.run(y)
    self.assertEqual(res.shape, (299, 299, 3))

  def testSaturatingSigmoid(self):
    x = np.array([-120.0, -100.0, 0.0, 100.0, 120.0], dtype=np.float32)
    with self.test_session() as session:
      y = common_layers.saturating_sigmoid(tf.constant(x))
      res = session.run(y)
    self.assertAllClose(res, [0.0, 0.0, 0.5, 1.0, 1.0])

  def testFlatten4D3D(self):
    x = np.random.random_integers(1, high=8, size=(3, 5, 2))
    with self.test_session() as session:
      y = common_layers.flatten4d3d(common_layers.embedding(x, 10, 7))
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (3, 5 * 2, 7))

  def testEmbedding(self):
    x = np.random.random_integers(1, high=8, size=(3, 5))
    with self.test_session() as session:
      y = common_layers.embedding(x, 10, 16)
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (3, 5, 16))

  def testShakeShake(self):
    x = np.random.rand(5, 7)
    with self.test_session() as session:
      x = tf.constant(x, dtype=tf.float32)
      y = common_layers.shakeshake([x, x, x, x, x])
      session.run(tf.global_variables_initializer())
      inp, res = session.run([x, y])
    self.assertAllClose(res, inp)

  def testConv(self):
    x = np.random.rand(5, 7, 1, 11)
    with self.test_session() as session:
      y = common_layers.conv(tf.constant(x, dtype=tf.float32), 13, (3, 1))
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 5, 1, 13))

  def testConv1d(self):
    x = np.random.rand(5, 7, 11)
    with self.test_session() as session:
      y = common_layers.conv1d(tf.constant(x, dtype=tf.float32), 13, 1)
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 13))

  def testSeparableConv(self):
    x = np.random.rand(5, 7, 1, 11)
    with self.test_session() as session:
      y = common_layers.separable_conv(
          tf.constant(x, dtype=tf.float32), 13, (3, 1))
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 5, 1, 13))

  def testSubSeparableConv(self):
    for sep in [0, 1, 2, 4]:
      x = np.random.rand(5, 7, 1, 12)
      with self.test_session() as session:
        with tf.variable_scope("sep_%d" % sep):
          y = common_layers.subseparable_conv(
              tf.constant(x, dtype=tf.float32), 16, (3, 1), separability=sep)
        session.run(tf.global_variables_initializer())
        res = session.run(y)
      self.assertEqual(res.shape, (5, 5, 1, 16))

  def testConvBlock(self):
    x = np.random.rand(5, 7, 1, 11)
    with self.test_session() as session:
      y = common_layers.conv_block(
          tf.constant(x, dtype=tf.float32),
          13, [(1, (3, 3)), (1, (3, 3))],
          padding="SAME",
          normalizer_fn=common_layers.noam_norm)
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 1, 13))

  def testSeparableConvBlock(self):
    x = np.random.rand(5, 7, 1, 11)
    with self.test_session() as session:
      y = common_layers.separable_conv_block(
          tf.constant(x, dtype=tf.float32),
          13, [(1, (3, 3)), (1, (3, 3))],
          padding="SAME")
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 1, 13))

  def testSubSeparableConvBlock(self):
    for sep in [0, 1, 2, 4]:
      x = np.random.rand(5, 7, 1, 12)
      with self.test_session() as session:
        with tf.variable_scope("sep_%d" % sep):
          y = common_layers.subseparable_conv_block(
              tf.constant(x, dtype=tf.float32),
              16, [(1, (3, 3)), (1, (3, 3))],
              padding="SAME",
              separability=sep)
        session.run(tf.global_variables_initializer())
        res = session.run(y)
      self.assertEqual(res.shape, (5, 7, 1, 16))

  def testPool(self):
    x = np.random.rand(5, 8, 1, 11)
    with self.test_session() as session:
      y = common_layers.pool(
          tf.constant(x, dtype=tf.float32), (2, 2), "AVG", "SAME")
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 8, 1, 11))

  def testConvBlockDownsample(self):
    x = np.random.rand(5, 7, 1, 11)
    with self.test_session() as session:
      y = common_layers.conv_block_downsample(
          tf.constant(x, dtype=tf.float32), (3, 1), (2, 1), "SAME")
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 4, 1, 27))

  def testSimpleAttention(self):
    x = np.random.rand(5, 7, 1, 11)
    y = np.random.rand(5, 9, 1, 11)
    with self.test_session() as session:
      a = common_layers.simple_attention(
          tf.constant(x, dtype=tf.float32), tf.constant(y, dtype=tf.float32))
      session.run(tf.global_variables_initializer())
      res = session.run(a)
    self.assertEqual(res.shape, (5, 7, 1, 11))

  def testGetTimingSignal(self):
    length = 7
    num_timescales = 10
    with self.test_session() as session:
      a = common_layers.get_timing_signal(length, num_timescales=num_timescales)
      session.run(tf.global_variables_initializer())
      res = session.run(a)
    self.assertEqual(res.shape, (length, 2 * num_timescales))

  def testAddTimingSignal(self):
    batch = 5
    length = 7
    height = 3
    depth = 35
    x = np.random.rand(batch, length, height, depth)
    with self.test_session() as session:
      a = common_layers.add_timing_signal(tf.constant(x, dtype=tf.float32))
      session.run(tf.global_variables_initializer())
      res = session.run(a)
    self.assertEqual(res.shape, (batch, length, height, depth))

  def testAttention1D(self):
    batch = 5
    target_length = 7
    source_length = 13
    source_depth = 9
    target_depth = 11
    attention_size = 21
    output_size = 15
    num_heads = 7
    source = np.random.rand(batch, source_length, source_depth)
    target = np.random.rand(batch, target_length, target_depth)
    mask = np.random.rand(batch, target_length, source_length)
    with self.test_session() as session:
      a = common_layers.attention_1d_v0(
          tf.constant(source, dtype=tf.float32),
          tf.constant(target, dtype=tf.float32), attention_size, output_size,
          num_heads, tf.constant(mask, dtype=tf.float32))
      session.run(tf.global_variables_initializer())
      res = session.run(a)
    self.assertEqual(res.shape, (batch, target_length, output_size))

  def testMultiscaleConvSum(self):
    x = np.random.rand(5, 9, 1, 11)
    with self.test_session() as session:
      y = common_layers.multiscale_conv_sum(
          tf.constant(x, dtype=tf.float32),
          13, [((1, 1), (5, 5)), ((2, 2), (3, 3))],
          "AVG",
          padding="SAME")
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 9, 1, 13))

  def testConvGRU(self):
    x = np.random.rand(5, 7, 3, 11)
    with self.test_session() as session:
      y = common_layers.conv_gru(tf.constant(x, dtype=tf.float32), (1, 3), 11)
      z = common_layers.conv_gru(
          tf.constant(x, dtype=tf.float32), (1, 3), 11, padding="LEFT")
      session.run(tf.global_variables_initializer())
      res1 = session.run(y)
      res2 = session.run(z)
    self.assertEqual(res1.shape, (5, 7, 3, 11))
    self.assertEqual(res2.shape, (5, 7, 3, 11))

  def testLayerNorm(self):
    x = np.random.rand(5, 7, 11)
    with self.test_session() as session:
      y = common_layers.layer_norm(tf.constant(x, dtype=tf.float32), 11)
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 11))

  def testConvLSTM(self):
    x = np.random.rand(5, 7, 11, 13)
    with self.test_session() as session:
      y = common_layers.conv_lstm(tf.constant(x, dtype=tf.float32), (1, 3), 13)
      session.run(tf.global_variables_initializer())
      res = session.run(y)
    self.assertEqual(res.shape, (5, 7, 11, 13))

  def testPadToSameLength(self):
    x1 = np.random.rand(5, 7, 11)
    x2 = np.random.rand(5, 9, 11)
    with self.test_session() as session:
      a, b = common_layers.pad_to_same_length(
          tf.constant(x1, dtype=tf.float32), tf.constant(x2, dtype=tf.float32))
      c, d = common_layers.pad_to_same_length(
          tf.constant(x1, dtype=tf.float32),
          tf.constant(x2, dtype=tf.float32),
          final_length_divisible_by=4)
      res1, res2 = session.run([a, b])
      res1a, res2a = session.run([c, d])
    self.assertEqual(res1.shape, (5, 9, 11))
    self.assertEqual(res2.shape, (5, 9, 11))
    self.assertEqual(res1a.shape, (5, 12, 11))
    self.assertEqual(res2a.shape, (5, 12, 11))

  def testShiftLeft(self):
    x1 = np.zeros((5, 7, 1, 11))
    x1[:, 0, :] = np.ones_like(x1[:, 0, :])
    expected = np.zeros((5, 7, 1, 11))
    expected[:, 1, :] = np.ones_like(expected[:, 1, :])
    with self.test_session() as session:
      a = common_layers.shift_right(tf.constant(x1, dtype=tf.float32))
      actual = session.run(a)
    self.assertAllEqual(actual, expected)

  def testConvStride2MultiStep(self):
    x1 = np.random.rand(5, 32, 16, 11)
    with self.test_session() as session:
      a = common_layers.conv_stride2_multistep(
          tf.constant(x1, dtype=tf.float32), 4, 16)
      session.run(tf.global_variables_initializer())
      actual = session.run(a[0])
    self.assertEqual(actual.shape, (5, 2, 1, 16))

  def testDeconvStride2MultiStep(self):
    x1 = np.random.rand(5, 2, 1, 11)
    with self.test_session() as session:
      a = common_layers.deconv_stride2_multistep(
          tf.constant(x1, dtype=tf.float32), 4, 16)
      session.run(tf.global_variables_initializer())
      actual = session.run(a)
    self.assertEqual(actual.shape, (5, 32, 1, 16))

  def testApplyNormLayer(self):
    with self.test_session() as session:
      x1 = np.random.rand(5, 2, 1, 11)
      x2 = common_layers.apply_norm(
          tf.constant(x1, dtype=tf.float32), "layer", depth=11, epsilon=1e-6)
      session.run(tf.global_variables_initializer())
      actual = session.run(x2)
    self.assertEqual(actual.shape, (5, 2, 1, 11))

  def testApplyNormNoam(self):
    with self.test_session() as session:
      x1 = np.random.rand(5, 2, 1, 11)
      x2 = common_layers.apply_norm(
          tf.constant(x1, dtype=tf.float32), "noam", depth=11, epsilon=1e-6)
      session.run(tf.global_variables_initializer())
      actual = session.run(x2)
    self.assertEqual(actual.shape, (5, 2, 1, 11))

  def testApplyNormBatch(self):
    with self.test_session() as session:
      x1 = np.random.rand(5, 2, 1, 11)
      x2 = common_layers.apply_norm(
          tf.constant(x1, dtype=tf.float32), "batch", depth=11, epsilon=1e-6)
      session.run(tf.global_variables_initializer())
      actual = session.run(x2)
    self.assertEqual(actual.shape, (5, 2, 1, 11))

  def testApplyNormNone(self):
    with self.test_session() as session:
      x1 = np.random.rand(5, 2, 1, 11)
      x2 = common_layers.apply_norm(
          tf.constant(x1, dtype=tf.float32), "none", depth=11, epsilon=1e-6)
      session.run(tf.global_variables_initializer())
      actual = session.run(x2)
    self.assertEqual(actual.shape, (5, 2, 1, 11))
    self.assertAllClose(actual, x1, atol=1e-03)

  def testGlobalPool1d(self):
    x1 = np.random.rand(5, 4, 11)
    no_mask = np.ones((5, 4))
    full_mask = np.zeros((5, 4))

    with self.test_session() as session:
      x1_ = tf.Variable(x1, dtype=tf.float32)
      no_mask_ = tf.Variable(no_mask, dtype=tf.float32)
      full_mask_ = tf.Variable(full_mask, dtype=tf.float32)

      none_mask_max = common_layers.global_pool_1d(x1_)
      no_mask_max = common_layers.global_pool_1d(x1_, mask=no_mask_)
      result1 = tf.reduce_sum(none_mask_max - no_mask_max)

      full_mask_max = common_layers.global_pool_1d(x1_, mask=full_mask_)
      result2 = tf.reduce_sum(full_mask_max)

      none_mask_avr = common_layers.global_pool_1d(x1_, "AVR")
      no_mask_avr = common_layers.global_pool_1d(x1_, "AVR", no_mask_)
      result3 = tf.reduce_sum(none_mask_avr - no_mask_avr)

      full_mask_avr = common_layers.global_pool_1d(x1_, "AVR", full_mask_)
      result4 = tf.reduce_sum(full_mask_avr)

      session.run(tf.global_variables_initializer())
      actual = session.run([result1, result2, result3, result4])
    self.assertAllEqual(actual[:3], [0.0, 0.0, 0.0])

  def testLinearSetLayer(self):
    x1 = np.random.rand(5, 4, 11)
    cont = np.random.rand(5, 13)
    with self.test_session() as session:
      x1_ = tf.Variable(x1, dtype=tf.float32)
      cont_ = tf.Variable(cont, dtype=tf.float32)

      simple_ff = common_layers.linear_set_layer(32, x1_)
      cont_ff = common_layers.linear_set_layer(32, x1_, context=cont_)

      session.run(tf.global_variables_initializer())
      actual = session.run([simple_ff, cont_ff])
    self.assertEqual(actual[0].shape, (5, 4, 32))
    self.assertEqual(actual[1].shape, (5, 4, 32))

  def testRavanbakhshSetLayer(self):
    x1 = np.random.rand(5, 4, 11)
    with self.test_session() as session:
      x1_ = tf.Variable(x1, dtype=tf.float32)
      layer = common_layers.ravanbakhsh_set_layer(32, x1_)
      session.run(tf.global_variables_initializer())
      actual = session.run(layer)
    self.assertEqual(actual.shape, (5, 4, 32))

  def testPaddingCrossEntropyFactored(self):
    vocab_size = 19
    rows = 5
    cols = 4
    depth = 11
    label_smoothing = 0.1
    features = np.random.rand(rows, cols, depth)
    weights = np.random.rand(vocab_size, depth)
    labels = np.random.randint(0, vocab_size - 1, size=(rows, cols))
    with self.test_session() as session:
      features = tf.to_float(features)
      weights = tf.to_float(weights)
      labels = tf.to_int32(labels)
      logits = tf.matmul(
          tf.reshape(features, [rows * cols, depth]), weights, transpose_b=True)
      logits = tf.reshape(logits, [rows, cols, vocab_size])
      loss_num, loss_den = common_layers.padded_cross_entropy(
          logits, labels, label_smoothing=label_smoothing, reduce_sum=False)
      factored_logits = common_layers.FactoredTensor(features, weights)
      loss_num_f, loss_den_f = common_layers.padded_cross_entropy_factored(
          factored_logits,
          labels=labels,
          label_smoothing=label_smoothing,
          reduce_sum=False)
      num, den, num_f, den_f = session.run(
          [loss_num, loss_den, loss_num_f, loss_den_f])
    self.assertEqual(num.shape, (rows, cols))
    self.assertEqual(den.shape, (rows, cols))
    self.assertEqual(num_f.shape, (rows, cols))
    self.assertEqual(den_f.shape, (rows, cols))
    self.assertAllClose(num, num_f)
    self.assertAllClose(den, den_f)

  def testPaddingCrossEntropyFactoredGrad(self):
    vocab_size = 19
    rows = 5
    cols = 4
    depth = 11
    label_smoothing = 0.1
    features = np.random.rand(rows, cols, depth)
    weights = np.random.rand(vocab_size, depth)
    labels = np.random.randint(0, vocab_size - 1, size=(rows, cols))
    with self.test_session() as session:
      features = tf.to_float(features)
      weights = tf.to_float(weights)
      labels = tf.to_int32(labels)
      logits = tf.matmul(
          tf.reshape(features, [rows * cols, depth]), weights, transpose_b=True)
      logits = tf.reshape(logits, [rows, cols, vocab_size])
      loss_num, loss_den = common_layers.padded_cross_entropy(
          logits, labels, label_smoothing=label_smoothing, reduce_sum=False)
      factored_logits = common_layers.FactoredTensor(features, weights)
      loss_num_factored, loss_den_factored = (
          common_layers.padded_cross_entropy_factored(
              factored_logits,
              labels=labels,
              label_smoothing=label_smoothing,
              reduce_sum=False))
      df, dw = tf.gradients(ys=[loss_num, loss_den], xs=[features, weights])
      df_factored, dw_factored = tf.gradients(
          ys=[loss_num_factored, loss_den_factored], xs=[features, weights])
      actual_df, actual_dw, actual_df_factored, actual_dw_factored = (
          session.run([df, dw, df_factored, dw_factored]))
    self.assertEqual(actual_df.shape, (rows, cols, depth))
    self.assertEqual(actual_dw.shape, (vocab_size, depth))
    self.assertEqual(actual_df_factored.shape, (rows, cols, depth))
    self.assertEqual(actual_dw_factored.shape, (vocab_size, depth))
    self.assertAllClose(actual_df, actual_df_factored)
    self.assertAllClose(actual_dw, actual_dw_factored)

  def testFactoredTensorImplicitConversion(self):
    a = np.random.rand(3, 4, 5)
    b = np.random.rand(6, 5)
    c = np.random.rand(3, 4, 6)
    with self.test_session() as session:
      # a factored representation of a Tensor of shape (3, 4, 6)
      factored = common_layers.FactoredTensor(tf.to_float(a), tf.to_float(b))
      # implicitly converts factored to a Tensor (performing the matmul)
      d = factored + tf.to_float(c)
      out = session.run(d)
    self.assertEqual(out.shape, (3, 4, 6))

  def testConvHiddenReluMemoryEfficient(self):
    batch = 3
    length = 23
    io_size = 16
    filter_size = 7
    x = np.random.rand(batch, length, io_size)
    dy = np.random.rand(batch, length, io_size)
    with self.test_session() as session:
      x = tf.to_float(x)
      dy = tf.to_float(dy)
      f1 = tf.get_variable("f1", [1, io_size, filter_size])
      f2 = tf.get_variable("f2", [1, filter_size, io_size])
      norm_scale, norm_bias = common_layers.layer_norm_vars(io_size)
      y = common_layers.conv_hidden_relu_memory_efficient(
          x, filter_size, forget=False,
          test_vars=(f1, f2, norm_scale, norm_bias))
      y_forget = common_layers.conv_hidden_relu_memory_efficient(
          x, filter_size, forget=True,
          test_vars=(f1, f2, norm_scale, norm_bias))
      dx, df1, df2, dnorm_scale, dnorm_bias = tf.gradients(
          ys=[y], xs=[x, f1, f2, norm_scale, norm_bias], grad_ys=[dy])
      dx_f, df1_f, df2_f, dnorm_scale_f, dnorm_bias_f = tf.gradients(
          ys=[y_forget], xs=[x, f1, f2, norm_scale, norm_bias], grad_ys=[dy])
      session.run(tf.global_variables_initializer())
      (y, y_forget,
       dx, df1, df2, dnorm_scale, dnorm_bias,
       dx_f, df1_f, df2_f, dnorm_scale_f, dnorm_bias_f) = session.run(
           [y, y_forget,
            dx, df1, df2, dnorm_scale, dnorm_bias,
            dx_f, df1_f, df2_f, dnorm_scale_f, dnorm_bias_f])
    self.assertAllClose(y, y_forget)
    self.assertAllClose(df2, df2_f)
    self.assertAllClose(df1, df1_f)
    self.assertAllClose(dnorm_scale, dnorm_scale_f)
    self.assertAllClose(dnorm_bias, dnorm_bias_f)
    self.assertAllClose(dx, dx_f)

class FnWithCustomGradTest(tf.test.TestCase):

  def testCorrectness(self):

    w = tf.random_uniform([6, 10])

    def fn(a, b, c):
      return tf.layers.dense(
          a,
          10,
          use_bias=False,
          kernel_initializer=lambda shape, dtype, partition_info: w
      ) + tf.matmul(b, c)

    def grad_fn(inputs, variables, outputs, grad_outputs):
      outputs = outputs[0]
      grad_outputs = grad_outputs[0]
      grad_inputs = tf.gradients(outputs, inputs, grad_ys=grad_outputs)
      grad_vars = tf.gradients(outputs, variables, grad_ys=grad_outputs)
      return grad_inputs, grad_vars

    custom_fn = common_layers.fn_with_custom_grad(grad_fn)(fn)

    a = tf.random_uniform([11, 6])
    b = tf.random_uniform([11, 7])
    c = tf.random_uniform([7, 10])

    out = fn(a, b, c)
    custom_out = custom_fn(a, b, c)
    self.assertEqual(out.get_shape().as_list(),
                     custom_out.get_shape().as_list())

    loss = tf.reduce_mean(out)
    custom_loss = tf.reduce_mean(custom_out)

    grads = tf.gradients(loss, [a, b, c] + [tf.trainable_variables()[0]])
    custom_grads = tf.gradients(custom_loss,
                                [a, b, c] + [tf.trainable_variables()[1]])

    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      out_val, custom_out_val, grads_val, custom_grads_val = sess.run(
          [out, custom_out, grads, custom_grads])
      self.assertAllClose(out_val, custom_out_val)
      for g1, g2 in zip(grads_val, custom_grads_val):
        self.assertAllClose(g1, g2)

  def testCustomGrad(self):

    def fn(a, b, c):
      return tf.layers.dense(a, 10, use_bias=False) + tf.matmul(b, c)

    def grad_fn(inputs, variables, unused_outputs, unused_grad_outputs):
      grad_inputs = [tf.ones_like(t) * (i + 1.) for i, t in enumerate(inputs)]
      grad_vars = [
          tf.ones_like(t) * (i + len(inputs) + 1.)
          for i, t in enumerate(variables)
      ]
      return grad_inputs, grad_vars

    a = tf.random_uniform([11, 6])
    b = tf.random_uniform([11, 7])
    c = tf.random_uniform([7, 10])
    w = tf.random_uniform([6, 10])
    out = common_layers.fn_with_custom_grad(grad_fn)(fn)(a, b, c)
    loss = tf.reduce_mean(out)
    grads = tf.gradients(loss, [a, b, c, tf.trainable_variables()[0]])
    expected_grads = [
        tf.ones_like(t) * (i + 1.) for i, t in enumerate([a, b, c, w])
    ]
    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      g_val, eg_val = sess.run([grads, expected_grads])
      for g1, g2 in zip(g_val, eg_val):
        self.assertAllClose(g1, g2)

if __name__ == "__main__":
  tf.test.main()


text:
/*!
 * \file dcxwindow.cpp
 * \brief blah
 *
 * blah
 *
 * \author David Legault ( clickhere at scriptsdb dot org )
 * \version 1.0
 *
 * \b Revisions
 *
 * © ScriptsDB.org - 2006
 */

#include "defines.h"
#include "dcxwindow.h"

 /*!
  * \brief Constructor
  *
  * \param mHwnd Window Handle
  * \param mID Window ID
  */

DcxWindow::DcxWindow(const HWND mHwnd, const UINT mID) noexcept
	: m_Hwnd(mHwnd), m_ID(mID), m_hZeroRgn(CreateRectRgn(0, 0, 0, 0))
{
}

/*!
 * \brief Constructor
 *
 * \param mID Window ID
 */

DcxWindow::DcxWindow(const UINT mID) noexcept
	: DcxWindow(nullptr, mID)
{
}

/*!
 * \brief Destructor
 *
 * Destructor
 */

DcxWindow::~DcxWindow() noexcept
{
	if (m_hZeroRgn)
		DeleteRgn(m_hZeroRgn);
}

/*!
 * \brief blah
 *
 * blah
 */

bool DcxWindow::isStyle(const WindowStyle Styles) const noexcept
{
	return dcx_testflag(dcxGetWindowStyle(m_Hwnd), Styles);	// this makes sure ALL flags match not just some.
}

/*!
 * \brief blah
 *
 * blah
 */

WindowStyle DcxWindow::removeStyle(const WindowStyle Styles) noexcept
{
	const auto winStyles = dcxGetWindowStyle(m_Hwnd);
	return dcxSetWindowStyle(m_Hwnd, winStyles & ~Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

WindowStyle DcxWindow::addStyle(const WindowStyle Styles) noexcept
{
	const auto winStyles = dcxGetWindowStyle(m_Hwnd);
	return dcxSetWindowStyle(m_Hwnd, winStyles | Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

WindowStyle DcxWindow::setStyle(const WindowStyle Styles) noexcept
{
	return dcxSetWindowStyle(m_Hwnd, Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

bool DcxWindow::isExStyle(const WindowExStyle Styles) const noexcept
{
	return dcx_testflag(dcxGetWindowExStyle(m_Hwnd), Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

WindowExStyle DcxWindow::removeExStyle(const WindowExStyle Styles) noexcept
{
	const auto winStyles = dcxGetWindowExStyle(m_Hwnd);
	return dcxSetWindowExStyle(m_Hwnd, winStyles & ~Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

WindowExStyle DcxWindow::addExStyle(const WindowExStyle Styles) noexcept
{
	const auto winStyles = dcxGetWindowExStyle(m_Hwnd);
	return dcxSetWindowExStyle(m_Hwnd, winStyles | Styles);
}

/*!
 * \brief blah
 *
 * blah
 */

WindowExStyle DcxWindow::setExStyle(const WindowExStyle Styles) noexcept
{
	return dcxSetWindowExStyle(m_Hwnd, Styles);
}

dcxWindowStyles DcxWindow::parseBorderStyles(const TString& tsFlags) noexcept
{
	const XSwitchFlags xflags(tsFlags);
	WindowStyle Styles(WindowStyle::None);
	WindowExStyle ExStyles(WindowExStyle::None);

	// no +sign, missing params
	if (!xflags[TEXT('+')])
		return { Styles, ExStyles };

	if (xflags[TEXT('b')])
		Styles |= WS_BORDER;
	if (xflags[TEXT('c')])
		ExStyles |= WS_EX_CLIENTEDGE;
	if (xflags[TEXT('d')])
		Styles |= WS_DLGFRAME;
	if (xflags[TEXT('f')])
		ExStyles |= WS_EX_DLGMODALFRAME;
	if (xflags[TEXT('s')])
		ExStyles |= WS_EX_STATICEDGE;
	if (xflags[TEXT('w')])
		ExStyles |= WS_EX_WINDOWEDGE;

	return { Styles, ExStyles };
}

/*!
 * \brief blah
 *
 * blah
 */

const UINT& DcxWindow::getID() const noexcept
{
	return m_ID;
}

/*!
 * \brief blah
 *
 * blah
 */

const HWND& DcxWindow::getHwnd() const noexcept
{
	return m_Hwnd;
}

/*!
 * \brief blah
 *
 * blah
 */

void DcxWindow::redrawWindow() const noexcept
{
	RedrawWindow(m_Hwnd, nullptr, nullptr, RDW_INTERNALPAINT | RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_ERASE/*|RDW_FRAME|RDW_UPDATENOW*/);
}

/*
 * Redraw Window using a buffered method to avoid flicker of children etc..
 * Vista Style has issues with this, as it relies on the WM_PAINT, anyway, its not needed for Vista style.
 * Composited windows already have buffered draw.
*/
// TODO: this changes the border style of children upon resize of dialog.
void DcxWindow::redrawBufferedWindow()
{
	if (this->isExStyle(WindowExStyle::Composited))
	{
		this->redrawWindow();
		return;
	}

	const auto hdc = GetWindowDC(m_Hwnd);

	if (!hdc)
		return;
	Auto(ReleaseDC(m_Hwnd, hdc));

#if DCX_USE_WRAPPERS
	const Dcx::dcxWindowRect rc(m_Hwnd);

	const Dcx::dcxHDCBuffer hBuffer(hdc, rc);

	SendMessage(m_Hwnd, WM_PRINT, reinterpret_cast<WPARAM>(hBuffer.get()), PRF_NONCLIENT | PRF_CLIENT | PRF_CHILDREN | PRF_CHECKVISIBLE | PRF_ERASEBKGND);

	BitBlt(hdc, 0, 0, rc.Width(), rc.Height(), hBuffer.get(), 0, 0, SRCCOPY);
#else
	if (RECT rc{}; GetWindowRect(m_Hwnd, &rc))
	{
		if (const auto hBuffer = CreateHDCBuffer(hdc, &rc); hBuffer)
		{
			Auto(DeleteHDCBuffer(hBuffer));

			SendMessage(m_Hwnd, WM_PRINT, (WPARAM)* hBuffer, PRF_NONCLIENT | PRF_CLIENT | PRF_CHILDREN | PRF_CHECKVISIBLE | PRF_ERASEBKGND);

			BitBlt(hdc, 0, 0, (rc.right - rc.left), (rc.bottom - rc.top), *hBuffer, 0, 0, SRCCOPY);
		}
	}
#endif
	ValidateRect(m_Hwnd, nullptr);
}

void DcxWindow::redrawBufferedWindowClient()
{
	if (this->isExStyle(WindowExStyle::Composited))
	{
		this->redrawWindow();
		return;
	}

	const auto hdc = GetDC(m_Hwnd);

	if (!hdc)
		return;
	Auto(ReleaseDC(m_Hwnd, hdc));

#if DCX_USE_WRAPPERS
	const Dcx::dcxClientRect rc(m_Hwnd);

	const Dcx::dcxHDCBuffer hBuffer(hdc, rc);

	SendMessage(m_Hwnd, WM_PRINTCLIENT, reinterpret_cast<WPARAM>(hBuffer.get()), PRF_CLIENT | PRF_CHILDREN | PRF_CHECKVISIBLE | PRF_ERASEBKGND);

	BitBlt(hdc, 0, 0, rc.Width(), rc.Height(), hBuffer.get(), 0, 0, SRCCOPY);
#else
	if (RECT rc{}; GetClientRect(m_Hwnd, &rc))
	{
		if (const auto hBuffer = CreateHDCBuffer(hdc, &rc); hBuffer)
		{
			Auto(DeleteHDCBuffer(hBuffer));

			SendMessage(m_Hwnd, WM_PRINTCLIENT, (WPARAM)*hBuffer, PRF_CLIENT | PRF_CHILDREN | PRF_CHECKVISIBLE | PRF_ERASEBKGND);

			BitBlt(hdc, 0, 0, (rc.right - rc.left), (rc.bottom - rc.top), *hBuffer, 0, 0, SRCCOPY);
		}
	}
#endif
	ValidateRect(m_Hwnd, nullptr);
}

void DcxWindow::HandleChildSizing(SizingTypes sz) const noexcept
{
	if (dcx_testflag(sz, SizingTypes::ReBar))
		for (auto bars = FindWindowEx(m_Hwnd, nullptr, DCX_REBARCTRLCLASS, nullptr); bars; bars = FindWindowEx(m_Hwnd, bars, DCX_REBARCTRLCLASS, nullptr))
			SendMessage(bars, WM_SIZE, 0U, 0);

	if (dcx_testflag(sz, SizingTypes::Status))
		for (auto bars = FindWindowEx(m_Hwnd, nullptr, DCX_STATUSBARCLASS, nullptr); bars; bars = FindWindowEx(m_Hwnd, bars, DCX_STATUSBARCLASS, nullptr))
			SendMessage(bars, WM_SIZE, 0U, 0);

	if (dcx_testflag(sz, SizingTypes::Panel))
		for (auto bars = FindWindowEx(m_Hwnd, nullptr, DCX_PANELCLASS, nullptr); bars; bars = FindWindowEx(m_Hwnd, bars, DCX_PANELCLASS, nullptr))
			SendMessage(bars, WM_SIZE, 0U, 0);

	if (dcx_testflag(sz, SizingTypes::Toolbar))
		for (auto bars = FindWindowEx(m_Hwnd, nullptr, DCX_TOOLBARCLASS, nullptr); bars; bars = FindWindowEx(m_Hwnd, bars, DCX_TOOLBARCLASS, nullptr))
			SendMessage(bars, WM_SIZE, 0U, 0);
}

/*!
 * \brief blah
 *
 * blah
 */

PTCHAR DcxWindow::parseCursorType(const TString& cursor)
{
	const static std::map<std::hash<TString>::result_type, PTCHAR> IDC_map{
		{ TEXT("appstarting"_hash), IDC_APPSTARTING },
		{ TEXT("arrow"_hash), IDC_ARROW },
		{ TEXT("cross"_hash), IDC_CROSS },
		{ TEXT("hand"_hash), IDC_HAND },
		{ TEXT("help"_hash), IDC_HELP },
		{ TEXT("ibeam"_hash), IDC_IBEAM },
		{ TEXT("no"_hash), IDC_NO },
		{ TEXT("sizeall"_hash), IDC_SIZEALL },
		{ TEXT("sizenesw"_hash), IDC_SIZENESW },
		{ TEXT("sizens"_hash), IDC_SIZENS },
		{ TEXT("sizenwse"_hash), IDC_SIZENWSE },
		{ TEXT("sizewe"_hash), IDC_SIZEWE },
		{ TEXT("uparrow"_hash), IDC_UPARROW },
		{ TEXT("wait"_hash), IDC_WAIT }
	};

	if (const auto got = IDC_map.find(std::hash<TString>{}(cursor)); got != IDC_map.end())
		return got->second;
	return nullptr;
}

/*!
 * \brief blah
 *
 * blah
 */

DcxResourceFlags DcxWindow::parseCursorFlags(const TString& flags) noexcept
{
	DcxResourceFlags iFlags{ DcxResourceFlags::None };
	const XSwitchFlags xflags(flags);

	// no +sign, missing params
	if (!xflags[TEXT('+')])
		return iFlags;

	if (xflags[TEXT('f')])	// load file
		iFlags = DcxResourceFlags::FROMFILE;
	else if (xflags[TEXT('r')])	// load resource
		iFlags = DcxResourceFlags::FROMRESSOURCE;

	return iFlags;
}

UINT DcxWindow::parseCursorArea(const TString& flags) noexcept
{
	UINT iFlags = 0;
	const XSwitchFlags xflags(flags);

	// no +sign, missing params
	if (!xflags[TEXT('+')])
		return iFlags;

	// can't use +f or +r
	if (xflags[TEXT('c')])	// client area
		iFlags = HTCLIENT;
	if (xflags[TEXT('m')])	// menu area
		iFlags = HTMENU;
	if (xflags[TEXT('s')])	// sysmenu area
		iFlags = HTSYSMENU;
	if (xflags[TEXT('a')])	// caption area
		iFlags = HTCAPTION;
	if (xflags[TEXT('S')])	// size button area
		iFlags = HTSIZE;
	if (xflags[TEXT('h')])	// horiz scroll area
		iFlags = HTHSCROLL;
	if (xflags[TEXT('v')])	// vert scroll area
		iFlags = HTVSCROLL;
	if (xflags[TEXT('M')])	// min button area
		iFlags = HTMINBUTTON;
	if (xflags[TEXT('x')])	// max button area
		iFlags = HTMAXBUTTON;
	if (xflags[TEXT('C')])	// close button area
		iFlags = HTCLOSE;
	if (xflags[TEXT('n')])	// nowhere area
		iFlags = HTNOWHERE;
	if (xflags[TEXT('H')])	// help button area
		iFlags = HTHELP;
	if (xflags[TEXT('l')])	// left area
		iFlags = HTLEFT;
	if (xflags[TEXT('R')])	// right area
		iFlags = HTRIGHT;
	if (xflags[TEXT('t')])	// top area
		iFlags = HTTOP;
	if (xflags[TEXT('b')])	// bottom area
		iFlags = HTBOTTOM;

	if (xflags[TEXT('L')])	// topleft area
		iFlags = HTTOPLEFT;
	if (xflags[TEXT('Q')])	// topright area
		iFlags = HTTOPRIGHT;
	if (xflags[TEXT('T')])	// bottomleft area
		iFlags = HTBOTTOMLEFT;
	if (xflags[TEXT('B')])	// bottomright area
		iFlags = HTBOTTOMRIGHT;
	if (xflags[TEXT('X')])	// border area
		iFlags = HTBORDER;

	return iFlags;
}

HIMAGELIST DcxWindow::createImageList(const bool bBigIcons) noexcept
{
	const auto sz = (bBigIcons ? DcxIconSizes::LargeIcon : DcxIconSizes::SmallIcon);

	auto himl = ImageList_Create(gsl::narrow_cast<int>(sz), gsl::narrow_cast<int>(sz), ILC_COLOR32 | ILC_MASK, 1, 0);

	if (himl)
		ImageList_SetBkColor(himl, RGB(255, 255, 255));

	return himl;
}

//LRESULT DcxWindow::CallDefaultProc(HWND mHwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) noexcept
//{
//	if (!m_hDefaultWindowProc)
//		return DefWindowProc(mHwnd, uMsg, wParam, lParam);
//
//	return CallWindowProc(m_hDefaultWindowProc, mHwnd, uMsg, wParam, lParam);
//}


text:
import asyncio

import ampdclient

def onchange(message):
    print('Message received ' + str(message))

@asyncio.coroutine
def start():
    mpd_client = yield from ampdclient.connect('192.168.1.12', 6600)
    mpd_client.cb_onchange = onchange

    print('Pausing')
    yield from mpd_client.pause(ampdclient.PAUSE_ON)
    resp = yield from mpd_client.status()
    print('Response {}'.format(resp))
    yield from asyncio.sleep(2)

    print('Resume playing')
    yield from mpd_client.pause(ampdclient.PAUSE_OFF)
    resp = yield from mpd_client.status()
    print('Response {}'.format(resp))
    yield from asyncio.sleep(2)

    print('Stopping')
    yield from mpd_client.stop()
    resp = yield from mpd_client.status()
    print('Response {}'.format(resp))
    yield from asyncio.sleep(2)

    print('Playing')
    yield from mpd_client.stop()
    resp = yield from mpd_client.play()
    print('Response {}'.format(resp))
    yield from asyncio.sleep(2)

    # If you pass anything else than PAUSE_OFF / PAUSE_ON (i.e. 0 or 1) an
    # exception is raised.
    try:
        yield from mpd_client.pause(5)
    except ampdclient.MpdCommandException as e:
        print('Exception for wrong pause argument: {}'.format(e))

    yield from mpd_client.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(start())


text:
import math

from PyQt4.QtCore import QRectF, QPointF
from PyQt4.QtGui import QGraphicsPathItem, QPen, QBrush, QColor, QPainterPath, QGraphicsItem

from port_item import PortItem

def anchors(count, startAngle, arcLen, radiusOut, radiusIn):
    angleIncr = arcLen / float(count + 1)
    radius = radiusIn + (radiusOut - radiusIn) / 2.0

    deg2rad = math.pi / 180.0

    points = list()
    angle = startAngle + angleIncr
    for i in xrange(count):
        x = radius * math.cos(angle*deg2rad)
        y = radius * math.sin(angle*deg2rad)
        points.append(QPointF(x, y))
        angle += angleIncr

    return points

class BaseConnectorItem(QGraphicsPathItem):

    IOTypeIn = 1
    IOTypeOut = 1 << 1

    def __init__(self, radiusOut, raiusIn, angle, arcLen, parent=None):
        QGraphicsPathItem.__init__(self, parent=parent)
        self._radiusOut = radiusOut
        self._raiusIn = raiusIn
        self._angle = angle
        self._arcLen = arcLen

        self._pen = QPen(QColor('#000000'))
        self._pen.setWidth(1)
        self.setPen(self._pen)

        self._hoverPen = QPen(QColor('#000000'))
        self._hoverPen.setWidth(2)

        brush = QBrush(QColor('#FF9966'))
        self.setBrush(brush)

        rectOut = QRectF(-radiusOut, -radiusOut, radiusOut*2.0, radiusOut*2.0)
        rectIn = QRectF(-raiusIn, -raiusIn, raiusIn*2.0, raiusIn*2.0)

        startAngle = angle - arcLen/2.0
        endAngle = angle + arcLen/2.0

        path = QPainterPath()
        path.arcMoveTo(rectIn, startAngle)
        path.arcTo(rectOut, startAngle, arcLen)
        path.arcTo(rectIn, endAngle, 0)
        path.arcTo(rectIn, endAngle, -arcLen)

        self.setPath(path)

        self._isHover = False

        self._ioDragFirstPos = None

    def ioType(self):
        return self._ioType

    def setIsHover(self, isHover):
        self._isHover = isHover
        pen = self._hoverPen if isHover else self._pen
        self.setPen(pen)
        self.update()

    def hoverEnterEvent(self, event):
        event.accept()
        self.setIsHover(True)
        QGraphicsPathItem.hoverEnterEvent(self, event)

    def hoverLeaveEvent(self, event):
        event.accept()
        self.setIsHover(False)
        QGraphicsPathItem.hoverLeaveEvent(self, event)

class IOConnectorItem(BaseConnectorItem):

    def __init__(self, name, portNames, angle, arcLen, ioType, parent=None):
        BaseConnectorItem.__init__(self, 50, 45, angle, arcLen, parent=parent)

        self._ioType = ioType
        self._name = name
        if parent is None:
            self._fullname = None
        else:
            self._fullname = str(self.parentItem().name()) + ':' + self._name

        self._connections = dict()
        self._ports = dict()

        connCount = len(portNames)
        startAngle = angle - arcLen / 2.0
        portPos = anchors(connCount, startAngle, arcLen, 50, 45)
        for i in xrange(connCount):
            name = portNames[i]
            port = PortItem(name, 3, parent=self)
            port.setPos(portPos[i])
            self._ports[name] = port

        self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True)

    def setParentItem(self, parent):
        BaseConnectorItem.setParentItem(self, parent)
        if parent is None:
            self._fullname = self._name
        else:
            self._fullname = str(self.parentItem().name()) + ':' + self._name

        for port in self._ports.itervalues():
            port.setParentFullName(self._fullname)

    def name(self):
        return self._name

    def fullname(self):
        return self._fullname

    def portNames(self):
        return self._ports.keys()

    def connections(self):
        return self._connections

    def addConnection(self, portName, conn):
        if portName in self._connections:
            return False

        self._connections[portName] = conn
        self._addConnection(portName, conn)
        return True

    def _addConnection(self, portName, conn):
        raise NotImplementedError()

    def removeConnection(self, connection):
        for name, conn in self._connections.iteritems():
            if conn == connection:
                del self._connections[name]
                return

        raise RuntimeError('%s connection is not present' % connection.name())

    def removeConnectionByPortName(self, portName):
        if portName not in self._connections:
            raise RuntimeError('%s port is not connected or present' % portName)

        del self._connections[portName]

    def removeAllConnections(self):
        self._connections = dict()

    def isConnected(self, portName):
        return portName in self._connections

    def connectionCount(self):
        return len(self._connections)

    def portCount(self):
        return len(self._ports)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemScenePositionHasChanged:
            self.updateConnectionItems()

        return BaseConnectorItem.itemChange(self, change, value)

    def updateConnectionItems(self):
        raise NotImplementedError()

class InputConnectorItem(IOConnectorItem):

    def __init__(self, name, connectionNames, parent=None):
        IOConnectorItem.__init__(self, name, connectionNames, 180, 80, BaseConnectorItem.IOTypeIn, parent=parent)

    def updateConnectionItems(self):
        ports = self._ports
        for name, connItem in self._connections.iteritems():
            pos = ports[name].scenePos()
            connItem.setEnd(pos)

    def _addConnection(self, portName, conn):
        port = self._ports[portName]
        pos = port.scenePos()
        conn.setEnd(pos)
        conn.setEndPortName(port.fullname())

class OutputConnectorItem(IOConnectorItem):

    def __init__(self, name, connectionNames, parent=None):
        IOConnectorItem.__init__(self, name, connectionNames, 0, 80, BaseConnectorItem.IOTypeOut, parent=parent)

    def updateConnectionItems(self):
        parent = self.parentItem()
        ports = self._ports
        for name, connItem in self._connections.iteritems():
            pos = parent.mapToScene(ports[name].pos())
            connItem.setStart(pos)

    def _addConnection(self, portName, conn):
        port = self._ports[portName]
        pos = port.scenePos()
        conn.setStart(pos)
        conn.setStartPortName(port.fullname())


text:
package net.mwplay.bmob;

import java.util.List;

import org.robovm.apple.foundation.NSError;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSObjectProtocol;

public interface BmobBQLObjectResultBlock {
	 void invoke(BQLQueryResult result,NSError error);
}


text:
package org.finra.datagenerator.scaffolding.random.predicate

import org.finra.datagenerator.scaffolding.config.Configuration
import org.finra.datagenerator.scaffolding.utils.Logging
import org.finra.datagenerator.scaffolding.random.randomizers._

/**
  * Created by dkopel on 12/6/16.
  */
object BuiltInPredicates extends Logging {
    def predicates(implicit conf: Configuration): Set[RandomPredicate[_]] = {
        // Scala class random predicates
        ClassRandomGenerator.findClassRandomPredicates ++
        // Java class random predicates
        ClassRandomGenerator.findJavaClassRandomPredicates ++
        // Explicitly defined randomizers
        Set[RandomPredicate[_]](
            ClassRandomPredicate(
                (rc: RandomContext) => rc.jpr.ints.nextInt(),
                classOf[java.lang.Integer],
                classOf[Int],
                classOf[Integer]
            ),
            ClassRandomPredicate(
                new BigIntegerRandomizer,
                classOf[java.math.BigInteger],
                classOf[BigInt]
            ),
            ClassRandomPredicate(
                new BigDecimalRandomizer,
                classOf[java.math.BigDecimal],
                classOf[scala.math.BigDecimal]
            ),
            ClassRandomPredicate(
                (rc: RandomContext) => rc.jpr.booleans.nextBoolean(),
                classOf[java.lang.Boolean],
                classOf[Boolean]
            ),
            ClassRandomPredicate(
                (rc: RandomContext) => rc.jpr.chars.nextAlphaNumeric(),
                classOf[java.lang.Character],
                classOf[Char]
            ),
            ClassRandomPredicate(
                (rc: RandomContext) => rc.jpr.strings.nextString(),
                classOf[java.lang.String],
                classOf[String]
            ),
            ClassRandomPredicate(
                () => java.util.UUID.randomUUID(),
                classOf[java.util.UUID]
            )
        )
    }
}


text:
using System.Runtime.InteropServices;
using System.Xml.Serialization;

namespace Diadoc.Api.Com
{
	[ComVisible(true)]
	[Guid("94C79296-8301-4886-A865-C45363FD71F7")]
	[XmlType(TypeName = "CustomDataPatchOperation", Namespace = "https://diadoc-api.kontur.ru")]
	public enum CustomDataPatchOperation
	{
		Set = 0,
		Remove = 1
	}
}


text:
var test = require('tape');
var resolve = require('../');

test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) {
    t.plan(1);

    var resolverDir = 'C:\\a\\b\\c\\d';

    resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) {
        t.equal(true, !!err);
    });

});


text:
'use strict';

const Npc = require('./Npc');
const EntityFactory = require('./EntityFactory');

/**
 * Stores definitions of npcs to allow for easy creation/cloning
 */
class MobFactory extends EntityFactory {
  /**
   * Create a new instance of a given npc definition. Resulting npc will not
   * have its default inventory.  If you want to also populate its default
   * contents you must manually call `npc.hydrate(state)`
   *
   * @param {Area}   area
   * @param {string} entityRef
   * @return {Npc}
   */
  create(area, entityRef) {
    const npc = this.createByType(area, entityRef, Npc);
    npc.area = area;
    return npc;
  }
}

module.exports = MobFactory;


text:
package org.elasticsearch.xpack.ql.expression.predicate.nulls;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.ql.expression.gen.processor.Processor;

import java.io.IOException;
import java.util.Objects;
import java.util.function.Predicate;

public class CheckNullProcessor implements Processor {

    public enum CheckNullOperation implements Predicate<Object> {

        IS_NULL(Objects::isNull, "IS NULL"),
        IS_NOT_NULL(Objects::nonNull, "IS NOT NULL");

        private final Predicate<Object> process;
        private final String symbol;

        CheckNullOperation(Predicate<Object> process, String symbol) {
            this.process = process;
            this.symbol = symbol;
        }

        public String symbol() {
            return symbol;
        }

        @Override
        public String toString() {
            return symbol;
        }

        @Override
        public boolean test(Object o) {
            return process.test(o);
        }
    }

    public static final String NAME = "nckn";

    private final CheckNullOperation operation;

    CheckNullProcessor(CheckNullOperation operation) {
        this.operation = operation;
    }

    public CheckNullProcessor(StreamInput in) throws IOException {
        this(in.readEnum(CheckNullOperation.class));
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeEnum(operation);
    }

    @Override
    public Object process(Object input) {
        return operation.test(input);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CheckNullProcessor that = (CheckNullProcessor) o;
        return operation == that.operation;
    }

    @Override
    public int hashCode() {
        return Objects.hash(operation);
    }
}


text:
class BombActivationPacket: public Packetizer
{
public:
	BombActivationPacket();
	virtual Packet pack() final;
	virtual void unpack( Packet& p_packet ) final;

public:
	int netsyncId;

};


text:
jQuery(document).ready(function($){
	//check media query
	var mediaQuery = window.getComputedStyle(document.querySelector('.cd-background-wrapper'), '::before').getPropertyValue('content').replace(/"/g, ''),
		//define store some initial variables
		halfWindowH = $(window).height()*0.5,
		halfWindowW = $(window).width()*0.5,
		//define a max rotation value (X and Y axises)
		maxRotationY = 5,
		maxRotationX = 3,
		aspectRatio;

	//detect if hero <img> has been loaded and evaluate its aspect-ratio
	$('.cd-floating-background').find('img').eq(0).load(function() {
		aspectRatio = $(this).width()/$(this).height();
  		if( mediaQuery == 'web' && $('html').hasClass('preserve-3d') ) initBackground();
	}).each(function() {
		//check if image was previously load - if yes, trigger load event
  		if(this.complete) $(this).load();
	});

	//detect mouse movement
	$('.cd-background-wrapper').on('mousemove', function(event){
		if( mediaQuery == 'web' && $('html').hasClass('preserve-3d') ) {
			window.requestAnimationFrame(function(){
				moveBackground(event);
			});
		}
	});

	//on resize - adjust .cd-background-wrapper and .cd-floating-background dimentions and position
	$(window).on('resize', function(){
		mediaQuery = window.getComputedStyle(document.querySelector('.cd-background-wrapper'), '::before').getPropertyValue('content').replace(/"/g, '');
		if( mediaQuery == 'web' && $('html').hasClass('preserve-3d') ) {
			window.requestAnimationFrame(function(){
				halfWindowH = $(window).height()*0.5,
				halfWindowW = $(window).width()*0.5;
				initBackground();
			});
		} else {
			$('.cd-background-wrapper').attr('style', '');
			$('.cd-floating-background').attr('style', '').removeClass('is-absolute');
		}
	});

	function initBackground() {
		var wrapperHeight = Math.ceil(halfWindowW*2/aspectRatio),
			proportions = ( maxRotationY > maxRotationX ) ? 1.1/(Math.sin(Math.PI / 2 - maxRotationY*Math.PI/180)) : 1.1/(Math.sin(Math.PI / 2 - maxRotationX*Math.PI/180)),
			newImageWidth = Math.ceil(halfWindowW*2*proportions),
			newImageHeight = Math.ceil(newImageWidth/aspectRatio),
			newLeft = halfWindowW - newImageWidth/2,
			newTop = (wrapperHeight - newImageHeight)/2;

		//set an height for the .cd-background-wrapper
		$('.cd-background-wrapper').css({
			'height' : wrapperHeight,
		});
		//set dimentions and position of the .cd-background-wrapper
		$('.cd-floating-background').addClass('is-absolute').css({
			'left' : newLeft,
			'top' : newTop,
			'width' : newImageWidth,
		});
	}

	function moveBackground(event) {
		var rotateY = ((-event.pageX+halfWindowW)/halfWindowW)*maxRotationY,
			rotateX = ((event.pageY-halfWindowH)/halfWindowH)*maxRotationX;

		if( rotateY > maxRotationY) rotateY = maxRotationY;
		if( rotateY < -maxRotationY ) rotateY = -maxRotationY;
		if( rotateX > maxRotationX) rotateX = maxRotationX;
		if( rotateX < -maxRotationX ) rotateX = -maxRotationX;

		$('.cd-floating-background').css({
			'-moz-transform': 'rotateX(' + rotateX + 'deg' + ') rotateY(' + rotateY + 'deg' + ') translateZ(0)',
		    '-webkit-transform': 'rotateX(' + rotateX + 'deg' + ') rotateY(' + rotateY + 'deg' + ') translateZ(0)',
			'-ms-transform': 'rotateX(' + rotateX + 'deg' + ') rotateY(' + rotateY + 'deg' + ') translateZ(0)',
			'-o-transform': 'rotateX(' + rotateX + 'deg' + ') rotateY(' + rotateY + 'deg' + ') translateZ(0)',
			'transform': 'rotateX(' + rotateX + 'deg' + ') rotateY(' + rotateY + 'deg' + ') translateZ(0)',
		});
	}
});

/* 	Detect "transform-style: preserve-3d" support, or update csstransforms3d for IE10 ? #762
	https://github.com/Modernizr/Modernizr/issues/762 */
(function getPerspective(){
  var element = document.createElement('p'),
      html = document.getElementsByTagName('html')[0],
      body = document.getElementsByTagName('body')[0],
      propertys = {
        'webkitTransformStyle':'-webkit-transform-style',
        'MozTransformStyle':'-moz-transform-style',
        'msTransformStyle':'-ms-transform-style',
        'transformStyle':'transform-style'
      };

    body.insertBefore(element, null);

    for (var i in propertys) {
        if (element.style[i] !== undefined) {
            element.style[i] = "preserve-3d";
        }
    }

    var st = window.getComputedStyle(element, null),
        transform = st.getPropertyValue("-webkit-transform-style") ||
                    st.getPropertyValue("-moz-transform-style") ||
                    st.getPropertyValue("-ms-transform-style") ||
                    st.getPropertyValue("transform-style");

    if(transform!=='preserve-3d'){
      html.className += ' no-preserve-3d';
    } else {
    	html.className += ' preserve-3d';
    }
    document.body.removeChild(element);

})();


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Android OpenGL ES</string>
</resources>


text:
Tools for logging an optimisation procedure. Specially designed to work with scipy and GPflow.

See the `./examples/` directory to see how to use.

### Use within other repositories
I usually add this as a git subtree:

```
git remote add st-opt_tools git@github.com:markvdw/opt_tools.git
git subtree add --prefix=opt_tools/ st-opt_tools master
```

Updates can be pulled and pushed using:

```
git subtree pull --prefix=opt_tools st-opt_tools master
git subtree push --prefix=opt_tools st-opt_tools master
```

### Changelog
- v2.0 (06/01/2017): Tasks are now separated out from the helper classes.
- v1.0


text:
<?php
namespace Craft;

class FeedMe_FeedModel extends BaseModel
{
    // Public Methods
    // =========================================================================

    public function __toString()
    {
        return Craft::t($this->name);
    }

    public function getDuplicateHandleFriendly()
    {
        return FeedMeDuplicate::getFrieldly($this->duplicateHandle);
    }

    // Protected Methods
    // =========================================================================

    protected function defineAttributes()
    {
        return array(
            'id'                => AttributeType::Number,
            'name'              => AttributeType::String,
            'feedUrl'           => AttributeType::Uri,
            'feedType'          => array(AttributeType::Enum, 'values' => array(
                FeedMe_FeedType::XML,
                FeedMe_FeedType::RSS,
                FeedMe_FeedType::ATOM,
                FeedMe_FeedType::JSON,
            )),
            'primaryElement'    => AttributeType::String,
            'elementType'       => AttributeType::String,
            'elementGroup'      => AttributeType::Mixed,
            'locale'            => AttributeType::String,
            'duplicateHandle'   => AttributeType::Mixed,
            'fieldMapping'          => AttributeType::Mixed,
            'fieldDefaults'         => AttributeType::Mixed,
            'fieldElementMapping'   => AttributeType::Mixed,
            'fieldElementDefaults'  => AttributeType::Mixed,
            'fieldUnique'           => AttributeType::Mixed,
            'passkey'               => AttributeType::String,
            'backup'                => AttributeType::Bool,
        );
    }
}


text:
#ifndef _EI_EPMD_H
#define _EI_EPMD_H

#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK ((u_long) 0x7F000001)
#endif

#ifndef EI_DIST_HIGH
#define EI_DIST_HIGH 5 /* R4 and later */
#define EI_DIST_LOW  1 /* R3 and earlier */
#endif

#ifndef EPMD_PORT
#define EPMD_PORT 4369
#endif

#ifndef EPMDBUF
#define EPMDBUF 512
#endif

#ifndef EI_MYPROTO
#define EI_MYPROTO 0 /* tcp/ip */
#endif

/* epmd r4 */
#ifndef EI_EPMD_ALIVE2_REQ
#define EI_EPMD_ALIVE2_REQ  120
#define EI_EPMD_ALIVE2_RESP 121
#define EI_EPMD_PORT2_REQ   122
#define EI_EPMD_PORT2_RESP  119
#define EI_EPMD_STOP_REQ      's'
#endif

/* internal functions */
int ei_epmd_connect_tmo(struct in_addr *inaddr, unsigned ms);
int ei_epmd_publish(int port, const char *alive);
int ei_epmd_publish_tmo(int port, const char *alive, unsigned ms);
int ei_epmd_port(struct in_addr *inaddr, const char *alive, int *dist);
int ei_epmd_port_tmo(struct in_addr *inaddr, const char *alive, int *dist, unsigned ms);

#endif /* _EI_EPMD_H */


text:
package io.digdag.core.database.migrate;

import org.skife.jdbi.v2.Handle;

public class Migration_20200803184355_ReplacePartialIndexOnSessionAttempts
        implements Migration
{
    @Override
    public void migrate(Handle handle, MigrationContext context)
    {
        if (context.isPostgres()) {
            // Don't use "create index concurrently" here since the following "drop index" should be issued after the completion of the index creation
            handle.update("create index session_attempts_on_state_flags_and_created_at_partial on session_attempts (id, created_at) where state_flags = 0");
            handle.update("drop index session_attempts_on_state_flags_and_created_at");
        }
        else {
            // H2 does not support partial index
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_sub_action_dark_touch"/>
    <item android:state_pressed="false" android:drawable="@drawable/button_sub_action_dark"/>
</selector><!-- From: file:/Users/oguzbilgener/dev/CircularFloatingActionMenu/library/src/main/res/drawable/button_sub_action_dark_selector.xml -->


text:
package com.go.tea.parsetree;

import com.go.tea.compiler.SourceInfo;
import com.go.tea.compiler.Token;
import com.go.tea.compiler.Type;

/******************************************************************************
 * A BinaryExpression contains a left expression, a right expression and
 * an operator. BinaryExpressions never evaluate to null.
 *
 * @author Brian S O'Neill
 * @version
 * <!--$$Revision:--> 25 <!-- $-->, <!--$$JustDate:-->  9/07/00 <!-- $-->
 */
public abstract class BinaryExpression extends Expression {
    private Token mOperator;
    private Expression mLeft;
    private Expression mRight;

    public BinaryExpression(SourceInfo info,
                            Token operator,
                            Expression left,
                            Expression right) {
        super(info);

        mOperator = operator;
        mLeft = left;
        mRight = right;
    }

    public Object clone() {
        BinaryExpression be = (BinaryExpression)super.clone();
        be.mLeft = (Expression)mLeft.clone();
        be.mRight = (Expression)mRight.clone();
        return be;
    }

    public boolean isExceptionPossible() {
        if (mLeft != null) {
            if (mLeft.isExceptionPossible()) {
                return true;
            }
            Type type = mLeft.getType();
            if (type != null && type.isNullable()) {
                return true;
            }
        }

        if (mRight != null) {
            if (mRight.isExceptionPossible()) {
                return true;
            }
            Type type = mRight.getType();
            if (type != null && type.isNullable()) {
                return true;
            }
        }

        return false;
    }

    public void setType(Type type) {
        // BinaryExpressions never evaluate to null.
        super.setType(type.toNonNull());
    }

    public Token getOperator() {
        return mOperator;
    }

    public Expression getLeftExpression() {
        return mLeft;
    }

    public Expression getRightExpression() {
        return mRight;
    }

    public void setLeftExpression(Expression left) {
        mLeft = left;
    }

    public void setRightExpression(Expression right) {
        mRight = right;
    }
}


text:
local m = {}

local util = require "scheme.util"
local types = require "scheme.types"

local ensure = util.ensure
local expect = util.expect
local expect_argc = util.expect_argc
local expect_argc_min = util.expect_argc_min
local expect_argc_max = util.expect_argc_max

local number_new = types.number.new
local char_new = types.char.new
local str_new = types.str.new
local bool_new = types.boolean.new

--[[
-- String stuff
--]]
m["to-string"] = function(self, env, args)
    expect_argc(self, 1, #args)

    return str_new(tostring(args[1]))
end

m["format"] = function(self, env, args)
    expect_argc_min(self, 1, #args)
    expect(args[1], "string")

    local i = 1

    return str_new(args[1]:getval()
        :gsub("(~.)", function(typ)
            if typ == "~~" then
                return "~"
            elseif typ == "~%" then
                return "\n"
            elseif typ == "~a" or typ == "~s" then
                i = i + 1

                ensure(self, i <= #args,
                    "argument-error",
                    "too few format arguments provided")

                local arg = args[i]

                if typ == "~s" then
                    return util.write_repr(arg)
                else
                    return util.display_repr(arg)
                end
            else
                return typ
            end
        end))
end

m["string-length"] = function(self, env, args)
    expect_argc(self, 1, #args)
    expect(args[1], "string")

    return number_new(#args[1]:getval())
end

m["string-null?"] = function(self, env, args)
    expect_argc(self, 1, #args)
    expect(args[1], "string")

    return bool_new(#args[1]:getval() == 0)
end

m["string-append"] = function(self, env, args)
    local res = ""

    for _, str in ipairs(args) do
        expect(str, "string")

        res = res .. str:getval()
    end

    return str_new(res)
end

m["string-join"] = function(self, env, args)
    expect_argc_min(self, 1, #args)
    expect_argc_max(self, 2, #args)

    expect(args[1], "list")

    local res = {}
    local sep = " "

    if #args == 2 then
        expect(args[2], {"char", "string"})

        sep = args[2]:getval()
    end

    for _, str in ipairs(args[1]:getval()) do
        expect(str, "string")

        table.insert(res, str:getval())
    end

    return str_new(table.concat(res, sep))
end

m["string-split"] = function(self, env, args)
    expect_argc_min(self, 1, #args)
    expect(args[1], "string")

    local sep = "%s"

    if #args == 2 then
        expect(args[2], {"char", "string"})

        sep = util.literal_pattern(args[2]:getval())
    end

    return types.toscheme(util.split_string(args[1]:getval(), sep))
end

m["string-trim"] = function(self, env, args)
    expect_argc_min(self, 1, #args)
    expect(args[1], "string")

    local sep_a, sep_b = "^%s*", "%s*$"

    if #args == 2 then
        expect(args[2], {"char", "string"})

        sep_a = "^" .. util.literal_pattern(args[2]:getval())
        sep_b = util.literal_pattern(args[2]:getval()) .. "$"
    end

    return str_new(args[1]:getval():gsub(sep_a, ""):gsub(sep_b, ""))
end

m["string-ref"] = function(self, env, args)
    expect_argc(self, 2, #args)
    expect(args[1], "string")
    expect(args[2], "number")
    ensure(args[2], (args[2]:getval() + 1) <= #args[1]:getval(),
        "argument-error",
        "string index out of bounds")

    local ind = args[2]:getval() + 1

    return char_new(args[1]:getval():sub(ind, ind))
end

m["substring"] = function(self, env, args)
    expect_argc_min(self, 2, #args)
    expect(args[1], "string")
    expect(args[2], "number")

    local str = args[1]:getval()
    local sstart, send = args[2]:getval(), #str

    ensure(args[2], sstart <= #str,
        "argument-error",
        "string index out of bounds")

    if #args == 3 then
        expect(args[3], "number")

        send = args[3]:getval()

        ensure(args[3], send >= sstart,
            "argument-error",
            "end must be greater or equal to start")

        ensure(args[3], sstart <= #str,
            "argument-error",
            "string index out of bounds")
    end

    return str_new(str:sub(sstart + 1, send))
end

return m


text:
topics = ["housing", "services", "missed connections", "finances", "job opportunites"]

topics.each do |item|
  Category.create(title: item.capitalize)
end

Article.create(price: '10', description: 'im testing test1', title: 'test1', email: 'fake1@gmail.com', category_id: 1)
Article.create(price: '25', description: 'im testing test2', title: 'test2', email: 'fake2@gmail.com', category_id: 1)


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>TaskOutputs (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.gradle.api.tasks

Interface TaskOutputs

public interface TaskOutputs

A TaskOutputs represents the outputs of a task.

You can obtain a TaskOutputs instance using Task.getOutputs().

Method Summary

Methods

Modifier and Type
Method and Description

TaskOutputs
dir(Object path)

Registers an output directory for this task.

TaskOutputs
file(Object path)

Registers some output file for this task.

TaskOutputs
files(Object... paths)

Registers some output files for this task.

FileCollection
getFiles()

Returns the output files of this task.

boolean
getHasOutput()

Returns true if this task has declared any outputs.

void
upToDateWhen(Closure upToDateClosure)

Adds a predicate to determine whether the outputs of this task are up-to-date.

void
upToDateWhen(Spec<? super Task> upToDateSpec)

Adds a predicate to determine whether the outputs of this task are up-to-date.

Method Detail

upToDateWhen

void upToDateWhen(Closure upToDateClosure)

Adds a predicate to determine whether the outputs of this task are up-to-date. The given closure is executed
 at task execution time. The closure is passed the task as a parameter. If the closure returns false, the task
 outputs are considered out-of-date and the task will be executed.

You can add multiple such predicates. The task outputs are considered out-of-date when any predicate returns
 false.

Parameters:

upToDateClosure - The closure to use to determine whether the task outputs are up-to-date.

upToDateWhen

void upToDateWhen(Spec<? super Task> upToDateSpec)

Adds a predicate to determine whether the outputs of this task are up-to-date. The given spec is evaluated at
 task execution time. If the spec returns false, the task outputs are considered out-of-date and the task will be
 executed.

You can add multiple such predicates. The task outputs are considered out-of-date when any predicate returns
 false.

Parameters:

upToDateSpec - The spec to use to determine whether the task outputs are up-to-date.

getHasOutput

boolean getHasOutput()

Returns true if this task has declared any outputs. Note that a task may be able to produce output files and
 still have an empty set of output files.

Returns:

true if this task has declared any outputs, otherwise false.

getFiles

FileCollection getFiles()

Returns the output files of this task.

Returns:

The output files. Returns an empty collection if this task has no output files.

files

TaskOutputs files(Object... paths)

Registers some output files for this task.

Parameters:

paths - The output files. The given paths are evaluated as per Project.files(Object...).

Returns:

this

file

TaskOutputs file(Object path)

Registers some output file for this task.

Parameters:

path - The output file. The given path is evaluated as per Project.file(Object).

Returns:

this

dir

TaskOutputs dir(Object path)

Registers an output directory for this task.

Parameters:

path - The output directory. The given path is evaluated as per Project.file(Object).

Returns:

this

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@interface HRWServerVoiceSearchClothRequest : HRWServerRequest
- (instancetype)initWithUserId:(NSString *)userId filters:(NSArray *)filters typeId:(NSString *)typeId offset:(int)offset limit:(int)limit;
@end


text:
package ru.karamoff.mcdrive.services;

import ru.karamoff.mcdrive.models.Order;

import java.util.List;

public interface OrderService {
    List<Order> getAllOrders();
}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\LearningPathItem\Template;

use Chamilo\Core\Repository\Common\Template\TemplateConfiguration;
use Chamilo\Core\Repository\Common\Template\TemplateParser;
use Chamilo\Core\Repository\Common\Template\TemplateTranslation;
use Chamilo\Core\Repository\ContentObject\LearningPathItem\Storage\DataClass\LearningPathItem;
use DOMXPath;

class Template extends \Chamilo\Core\Repository\Common\Template\Template implements TemplateParser
{

    /**
     *
     * @param DOMXPath $dom_xpath
     * @return \core\repository\content_object\learning_path_item\Template
     */
    public static function parse(DOMXPath $dom_xpath)
    {
        $template_configuration = TemplateConfiguration::get($dom_xpath);
        $template_translation = TemplateTranslation::get($dom_xpath);

        $content_object = new LearningPathItem();

        return new self($template_configuration, $content_object, $template_translation);
    }
}


text:
using base::android::ScopedJavaLocalRef;
using navigation_interception::InterceptNavigationDelegate;

namespace xwalk {

namespace {

const void* kXWalkContentUserDataKey = &kXWalkContentUserDataKey;

class XWalkContentUserData : public base::SupportsUserData::Data {
 public:
  explicit XWalkContentUserData(XWalkContent* ptr) : content_(ptr) {}

  static XWalkContent* GetContents(content::WebContents* web_contents) {
    if (!web_contents)
      return NULL;
    XWalkContentUserData* data = reinterpret_cast<XWalkContentUserData*>(
        web_contents->GetUserData(kXWalkContentUserDataKey));
    return data ? data->content_ : NULL;
  }

 private:
  XWalkContent* content_;
};

}  // namespace

XWalkContent::XWalkContent(JNIEnv* env,
                           jobject obj,
                           jobject web_contents_delegate,
                           jobject contents_client_bridge)
    : java_ref_(env, obj),
      web_contents_delegate_(
          new XWalkWebContentsDelegate(env, web_contents_delegate)),
      contents_client_bridge_(
          new XWalkContentsClientBridge(env, contents_client_bridge)) {
}

XWalkContent::~XWalkContent() {
}

// static
XWalkContent* XWalkContent::FromWebContents(
    content::WebContents* web_contents) {
  return XWalkContentUserData::GetContents(web_contents);
}

jint XWalkContent::GetWebContents(
    JNIEnv* env, jobject obj, jobject intercept_navigation_delegate) {
  if (!web_contents_) {
    web_contents_.reset(CreateWebContents(env, intercept_navigation_delegate));

    render_view_host_ext_.reset(
        new XWalkRenderViewHostExt(web_contents_.get()));
  }
  return reinterpret_cast<jint>(web_contents_.get());
}

content::WebContents* XWalkContent::CreateWebContents(
    JNIEnv* env, jobject intercept_navigation_delegate) {
  RuntimeContext* runtime_context =
      XWalkContentBrowserClient::GetRuntimeContext();
  content::WebContents* web_contents = content::WebContents::Create(
      content::WebContents::CreateParams(runtime_context));

  web_contents->SetUserData(kXWalkContentUserDataKey,
                            new XWalkContentUserData(this));

  XWalkContentsClientBridgeBase::Associate(web_contents,
      contents_client_bridge_.get());
  InterceptNavigationDelegate::Associate(web_contents,
      make_scoped_ptr(new InterceptNavigationDelegate(
          env, intercept_navigation_delegate)));
  web_contents->SetDelegate(web_contents_delegate_.get());
  return web_contents;
}

void XWalkContent::ClearCache(
    JNIEnv* env,
    jobject obj,
    jboolean include_disk_files) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  render_view_host_ext_->ClearCache();

  if (include_disk_files) {
    RemoveHttpDiskCache(web_contents_->GetBrowserContext(),
                        web_contents_->GetRoutingID());
  }
}

ScopedJavaLocalRef<jstring> XWalkContent::DevToolsAgentId(JNIEnv* env,
                                                          jobject obj) {
  content::RenderViewHost* rvh = web_contents_->GetRenderViewHost();
  scoped_refptr<content::DevToolsAgentHost> agent_host(
      content::DevToolsAgentHost::GetOrCreateFor(rvh));
  return base::android::ConvertUTF8ToJavaString(env, agent_host->GetId());
}

void XWalkContent::Destroy(JNIEnv* env, jobject obj) {
  delete this;
}

ScopedJavaLocalRef<jstring> XWalkContent::GetVersion(JNIEnv* env,
                                                     jobject obj) {
  return base::android::ConvertUTF8ToJavaString(env, XWALK_VERSION);
}

static jint Init(JNIEnv* env, jobject obj, jobject web_contents_delegate,
    jobject contents_client_bridge) {
  XWalkContent* xwalk_core_content =
    new XWalkContent(env, obj, web_contents_delegate, contents_client_bridge);
  return reinterpret_cast<jint>(xwalk_core_content);
}

bool RegisterXWalkContent(JNIEnv* env) {
  return RegisterNativesImpl(env) >= 0;
}

}  // namespace xwalk


text:
class MockImporterBridge : public ImporterBridge {
 public:
  MockImporterBridge();

  MOCK_METHOD2(AddBookmarks,
               void(const std::vector<ImportedBookmarkEntry>&,
                    const std::u16string&));
  MOCK_METHOD1(AddHomePage, void(const GURL&));
  MOCK_METHOD1(SetFavicons, void(const favicon_base::FaviconUsageDataList&));
  MOCK_METHOD2(SetHistoryItems,
               void(const std::vector<ImporterURLRow>&, importer::VisitSource));
  MOCK_METHOD2(SetKeywords,
               void(const std::vector<importer::SearchEngineInfo>&, bool));
  MOCK_METHOD1(SetPasswordForm, void(const importer::ImportedPasswordForm&));
  MOCK_METHOD1(SetAutofillFormData,
               void(const std::vector<ImporterAutofillFormDataEntry>&));
  MOCK_METHOD0(NotifyStarted, void());
  MOCK_METHOD1(NotifyItemStarted, void(importer::ImportItem));
  MOCK_METHOD1(NotifyItemEnded, void(importer::ImportItem));
  MOCK_METHOD0(NotifyEnded, void());
  MOCK_METHOD1(GetLocalizedString, std::u16string(int));

 private:
  ~MockImporterBridge() override;
};

#endif  // CHROME_COMMON_IMPORTER_MOCK_IMPORTER_BRIDGE_H_


text:
<!DOCTYPE html>

    <title>ContactDetailsConfiguration Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

HillListsBackupLibrary Docs (100% documented)

View on GitHub

        HillListsBackupLibrary Reference

        ContactDetailsConfiguration Structure Reference

            Guides

                Backup File Analysis

            Enumerations

                BackupError

                BackupKey

                – AscentsKey

                HeightUnitLength

                HillListContentSortingConfiguration

                HillListsSortingConfiguration

            Protocols

                Backup

            Structures

                AscendedHill

                Ascent

                BackupConfiguration

                – Mode

                – Destination

                BackupImporter

                ContactDetailsConfiguration

                HillList

                – Classification

                – Region

                – Flag

                LocationConfiguration

                MapViewConfiguration

                – Vendor

                – Style

                Metadata

                MiscellaneousConfiguration

                SortingConfigurations

                UnitsConfiguration

ContactDetailsConfiguration

public struct ContactDetailsConfiguration

A type representing a set of contact details used for sharing data from the
app.

                    exportEmailAddress

The address used when exporting data in CSV format by email.

Declaration

Swift

public let exportEmailAddress: String

                    locationEmailAddress

The address used when sharing location information by email.

Declaration

Swift

public let locationEmailAddress: String

                    locationSMSNumber

The phone number used when sharing location information by SMS.

Declaration

Swift

public let locationSMSNumber: String

© 2018 Mark Scott. All rights reserved. (Last updated: 2018-10-02)

Generated by jazzy ♪♫ v0.9.3, a Realm project.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Irony.Parsing;

namespace CalcLang.Interpreter
{
    [Serializable]
    public class ScriptException : Exception
    {
        public SourceInfo Location;
        public ScriptStackTrace ScriptStackTrace;
        public object Payload;

        public ScriptException(string message) : this(message, null)
        {
        }

        public ScriptException(string message, Exception inner) : this(message, inner, SourceLocation.Empty, null)
        {
        }

        public ScriptException(string message, Exception inner, SourceInfo location, ScriptStackTrace stack) : base(message, inner)
        {
            Location = location;
            ScriptStackTrace = stack;
        }

        public static ScriptException CreateScriptException(object payload, SourceInfo location, ScriptStackTrace stack)
            => new ScriptException(payload as string ?? "ScriptException", null, location, stack) { Payload = payload };

        public override string ToString()
        {
            var msg = Message;
            if (Payload is DataTable)
            {
                var dt = (DataTable)Payload;
                var exType = dt.GetString(null, "ExceptionType").ToString();
                msg = dt.GetString(null, "Message").ToString();
                if (msg != null && msg.Length > 0)
                    msg = exType + ": " + msg;
                else
                    msg = exType;
            }
            return msg + Environment.NewLine + ScriptStackTrace.ToString();
        }

        public object ToScriptObject()
        {
            var ret = new DataTable();
            if (Payload is DataTable)
            {
                foreach (var e in ((DataTable)Payload).GetStringIndexDict())
                {
                    ret.SetString(null, e.Key, e.Value);
                }
            }
            else
            {
                ret.SetString(null, "Message", Payload);
            }

            var dataStackTrace = new DataTable();
            int index = 0;
            foreach (var e in ScriptStackTrace.CallStack)
            {
                var stackEntry = new DataTable();
                stackEntry.SetString(null, "Name", e.Name);
                stackEntry.SetString(null, "ParamCount", e.ParamCount);
                if (e.ParamNames != null)
                    stackEntry.SetString(null, "ParamNames", new DataTable(e.ParamNames, null));
                else
                    stackEntry.SetString(null, "ParamNames", new DataTable());
                stackEntry.SetString(null, "CallLocation", new DataTable(
                    new Dictionary<string, object>()
                    {
                        ["Filename"] = e.CallLocation.FileName,
                        ["Column"] = e.CallLocation.SourceLocation.Column,
                        ["Line"] = e.CallLocation.SourceLocation.Line,
                        ["Position"] = e.CallLocation.SourceLocation.Position
                    }, null));
                stackEntry.SetString(null, "HasParamsArg", e.HasParamsArg);

                dataStackTrace.SetInt(null, index++, stackEntry);
            }

            ret.SetString(null, "Stacktrace", dataStackTrace);

            ret.SetString(null, "Location", new DataTable(
                new Dictionary<string, object>()
                {
                    ["Filename"] = Location.FileName,
                    ["Column"] = Location.SourceLocation.Column,
                    ["Line"] = Location.SourceLocation.Line,
                    ["Position"] = Location.SourceLocation.Position
                }, null));

            return ret;
        }
    }
}


text:
module HP
  module Cloud
    class CLI < Thor

      map %w(addresses:allocate) => 'addresses:add'

      desc "addresses:add", "Allocate a new public IP address."
      long_desc <<-DESC
  Add or allocate a new public IP address from the pool of available IP addresses.  If a network is not specified, the first external network found will be used.

Examples:
  hpcloud addresses:add # Add a new public IP address to external network
  hpcloud addresses:add -n netty # Add a new IP address to `netty`

Aliases: addresses:allocate
      DESC
      method_option :network,
                    :type => :string, :aliases => '-n',
                    :desc => 'Name or id of the network associated with this IP.'
      method_option :port,
                    :type => :string, :aliases => '-p',
                    :desc => 'Name or id of the port associated with this IP.'
      method_option :fixed_ip,
                    :type => :string,
                    :desc => 'Fixed IP address to associate with this IP.'
      method_option :floating_ip,
                    :type => :string,
                    :desc => 'Floating IP to assign.'
      CLI.add_common_options
      define_method "addresses:add" do
        cli_command(options) {
          address = FloatingIpHelper.new(Connection.instance)
          address.set_network(options[:network])
          address.port = options[:port]
          address.fixed_ip = options[:fixed_ip]
          address.floating_ip = options[:floating_ip]
          if address.save
            @log.display "Created a public IP address '#{address.ip}'."
          else
            @log.fatal address.cstatus
          end
        }
      end
    end
  end
end


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

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@drawable/customer" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="95dp">

        <TextView
            android:id="@+id/tv_commoditydescription"
            android:layout_width="350dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/commoditydescription"
            android:textSize="16sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tv_commoditydescription"
            android:layout_marginLeft="10dp"
            android:text="@string/the_price"
            android:textColor="#FF6600" />

        <TextView
            android:id="@+id/customer_chat"
            android:layout_width="67dp"
            android:layout_height="23dp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="12dp"
            android:layout_marginTop="65dp"
            android:background="@drawable/service"
            android:gravity="center"
            android:text="客服聊天"
            android:textColor="#ffffff"
            android:textSize="12sp" />
    </RelativeLayout>

</LinearLayout>