text:
layout: post
title: "Enable GPU support for Tensorflow on Mac OS X"
date: 2016-11-07
categories: ['Setup & Environment']
---

Origin post: https://github.com/srikanthpagadala/srikanthpagadala.github.io/blob/master/_posts/2016-11-07-enable-gpu-support-for-tensorflow-on-macos.md

As soon as I started working on relatively serious Deep Neural Networks such as [Handwritten Digit Recognition](/notes/2016/11/07/handwritten-digit-recognition-using-convolutional-neural-networks) or [Object Recognition in CIFAR-10](/notes/2016/11/07/object-recognition-in-cifar10-with-convolutional-neural-networks), I realized that my 3 year old MacBook's CPU is not enough. It took 9 hrs to complete Handwritten Digit Recognition project on my below laptop.

<pre>
Model Name: MacBook Pro (Retina, Mid 2012)
Model Identifier: MacBookPro10,1
Processor Name:	Intel Core i7
Processor Speed: 2.7 GHz
Number of Processors: 1
Total Number of Cores: 4
L2 Cache (per Core): 256 KB
L3 Cache: 8 MB
Memory: 16 GB
OS Version: macOS Sierra, 10.12.1

Graphics Cards:
 Intel HD Graphics 4000
 NVIDIA GeForce GT 650M
</pre>

Obvious solution is to put GPUs of my laptop to use.

As of this writting, official instructions for setting up GPU environment for Tensorflow on Mac OS X are bit dated. Hence this blog post. Let us get started.

## Update:

*Official Tensorflow [instructions](https://www.tensorflow.org/get_started/os_setup#optional-setup-gpu-for-mac) are upto date now. Please follow official instructions. Tensorflow now provides easy to install GPU binary package for Mac OS X. Below instructions are still good, if you want to install from latest Tensorflow sources.*

## Prerequisites

Make sure to update your homebrew formulas

```bash
brew update
```

Coreutils for Mac OS X.

```bash
brew install coreutils swig
```

Install Bazel

```bash
brew install bazel
```

Cuda Libraries for macosx. You can install cuda from homebrew using cask.

```bash
brew cask install cuda
```

Make sure that the installed cuda version is 8.0 (latest, as of this writing) you can check the version with

```bash
brew cask info cuda
```

```
cuda: 8.0.55
https://developer.nvidia.com/cuda-zone
/usr/local/Caskroom/cuda/8.0.55 (23 files, 1.3G)
From: https://github.com/caskroom/homebrew-cask/blob/master/Casks/cuda.rb
==> Name
Nvidia CUDA
==> Artifacts
```

You need NVIDIA's Cuda Neural Network library libCudnn. You have to register and download it from the [website](https://developer.nvidia.com/cudnn).

Download the file: cudnn-8.0-osx-x64-v5.1-tgz

Once downloaded you need to manually copy the files over the /usr/local/cuda/ directory

```bash
tar xzvf ~/Downloads/cudnn-8.0-osx-x64-v5.1-tgz
sudo mv -v cuda/lib/libcudnn* /usr/local/cuda/lib
sudo mv -v cuda/include/cudnn.h /usr/local/cuda/include
```

add in your ~/.bash_profile the reference to /usr/local/cuda/lib. You will need it to run the python scripts.

```bash
export DYLD_LIBRARY_PATH=/usr/local/cuda/lib:$DYLD_LIBRARY_PATH
```

Now let's make sure that we are able to compile cuda programs. If you have the latest Xcode Installed (8.2 as the time of this post) nvcc will not work and will give an error like:

```bash
nvcc fatal : The version ('70300') of the host compiler ('Apple clang') is not supported
```

In order to fix this you need to:

1. download Xcode 7.2.1 from the apple developer [website](https://developer.apple.com/download/more/)
2. create a new directory /Applications/XCode7.2.1/
3. copy the entire XCode.App inside /Applications/XCode7.2.1
4. run sudo xcode-select -s /Applications/XCode7.2.1/Xcode.app/

You should be able to compile the deviceQuery utility found inside the cuda sdk repository. Let's compile the deviceQuery utility to figure out the CUDA_CAPABILITY supported by our graphics card.

```bash
cd /usr/local/cuda/samples
sudo make -C 1_Utilities/deviceQuery
```

And now we run it:

```bash
cd /usr/local/cuda/samples/
./bin/x86_64/darwin/release/deviceQuery
```

The output will look like:

```bash
./bin/x86_64/darwin/release/deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "GeForce GT 650M"
  CUDA Driver Version / Runtime Version          8.0 / 8.0
  CUDA Capability Major/Minor version number:    3.0
  Total amount of global memory:                 1024 MBytes (1073414144 bytes)
  ( 2) Multiprocessors, (192) CUDA Cores/MP:     384 CUDA Cores
  GPU Max Clock rate:                            900 MHz (0.90 GHz)
  Memory Clock rate:                             2508 Mhz
  Memory Bus Width:                              128-bit
  L2 Cache Size:                                 262144 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 65536
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  2048
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (2147483647, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)
  Run time limit on kernels:                     Yes
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 1 / 0
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 8.0, CUDA Runtime Version = 8.0, NumDevs = 1, Device0 = GeForce GT 650M
Result = PASS
```

Here you can confirm that the driver is set to 8.0 and you can find also the cuda capability of your GPU, CUDA Capability Major/Minor version number: 3.0 in my case, so we can set this property when we configure tensorflow.

## Checkout tensorflow

```bash
git clone --recurse-submodules https://github.com/tensorflow/tensorflow
cd tensorflow
git checkout master
```

Then we need to configure it.

I use Anaconda for the python distribution. Notice that you need to set the right TF_CUDA_COMPUTE_CAPABILITES value from the previous deviceQuery operation.

```bash
PYTHON_BIN_PATH=$HOME/anaconda/bin/python CUDA_TOOLKIT_PATH="/usr/local/cuda" CUDNN_INSTALL_PATH="/usr/local/cuda" TF_UNOFFICIAL_SETTING=1 TF_NEED_CUDA=1 TF_CUDA_COMPUTE_CAPABILITIES="3.0" TF_CUDNN_VERSION="5" TF_CUDA_VERSION="8.0" TF_CUDA_VERSION_TOOLKIT=8.0 ./configure
```

Now we are ready to build tensorflow pip package. This may take a while.

```bash
bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
pip install --upgrade --ignore-installed  /tmp/tensorflow_pkg/tensorflow-*.whl
```
**Problem 1 - Missing Files**

If needed create symlinks for missing files:

```
sudo ln -s libcudnn.5.dylib libcudnn.5
sudo ln -s libcudnn.5.dylib libcudnn.dylib
sudo ln -s libcudnn.5.dylib libcudnn5.dylib
```

**Problem 2 - Library not loaded: @rpath/libcudart.**

file "touch" solution described [here](https://github.com/tensorflow/tensorflow/issues/4187) worked for me.

Now move to another directory and run a test script:

```
import tensorflow as tf

# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)

# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

# Runs the op.
print sess.run(c)
```

You should see output like this. You can see that Tensorflow has automatically started using GPU.

```
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcublas.8.0.dylib locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcudnn.5.dylib locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcufft.8.0.dylib locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcuda.1.dylib locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcurand.8.0.dylib locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] OS X does not support NUMA - returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_device.cc:885] Found device 0 with properties:
name: GeForce GT 650M
major: 3 minor: 0 memoryClockRate (GHz) 0.9
pciBusID 0000:01:00.0
Total memory: 1023.69MiB
Free memory: 688.47MiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 650M, pci bus id: 0000:01:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 650M, pci bus id: 0000:01:00.0
I tensorflow/core/common_runtime/direct_session.cc:255] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 650M, pci bus id: 0000:01:00.0

MatMul: (MatMul): /job:localhost/replica:0/task:0/gpu:0
I tensorflow/core/common_runtime/simple_placer.cc:827] MatMul: (MatMul)/job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/gpu:0
I tensorflow/core/common_runtime/simple_placer.cc:827] b: (Const)/job:localhost/replica:0/task:0/gpu:0
a: (Const): /job:localhost/replica:0/task:0/gpu:0
I tensorflow/core/common_runtime/simple_placer.cc:827] a: (Const)/job:localhost/replica:0/task:0/gpu:0
[[ 22.  28.]
 [ 49.  64.]]
```

**Problem 1 - Segmentation fault**

If you get a segmentation fault 11 when you perform "import tensorflow as tf" here's a [link](https://github.com/tensorflow/tensorflow/issues/2278) to the fix.

```
sudo ln -s /usr/local/cuda/lib/libcuda.dylib /usr/local/cuda/lib/libcuda.1.dylib
```

You can read more about using GPUs, in tensorflow in the official GPU [article](https://www.tensorflow.org/versions/master/how_tos/using_gpu/index.html).

## Credit

This post is adaptation of original post [here](https://gist.github.com/Mistobaan/dd32287eeb6859c6668d), which is bit dated as of this writing.

## Result

After this change, preliminary tests revealed that my Handwritten Digit Recognition project would still take 3-4 hrs. So my joy of getting GPU setup to work was very short lived. I decided to bring in big guns - move to the AWS cloud.

Next: [Develop and Evaluate Large Deep Learning Models with Keras on AWS](/notes/2016/11/13/develop-and-evaluate-large-deep-learning-models-with-keras-on-aws)


text:
@extends('layouts.main')

@section('content')

      <form>

          <input id="search" type="search" required>
          search
          close

      </form>

    @foreach($circles as $circle)

{{$circle['name']}}

{{$circle['description']}}

          <button onclick="window.location.href = '/circle/{{$circle['id']}}'" class="btn btn-second waves-effect waves-light">详情</button>
          <form name='joinForm{{$circle['id']}}' action = "/circle/join/{{$circle['id']}}/{{$current_user['username']}}" method="post">
            {!! csrf_field() !!}
            <button type='submit' class="btn @if($circle['is_join']==0)btn-pink join-btn@else joined-btn @endif waves-effect waves-light">@if($circle['is_join']==0)加入@else已加入@endif</button>
          </form>

            watch_later

创建于 {{$circle['created_at']}}

            people

{{$circle['people_now']}} / {{$circle['people_num']}} 人

    @endforeach

@stop

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Minimalism\Test\Coroutine;

use function Minimalism\Coroutine\fork;
use function Minimalism\Coroutine\go;
use function Minimalism\Coroutine\getTask;
use Minimalism\Coroutine\Time;

require __DIR__ . "/../../vendor/autoload.php";

$task = go(function() {
    yield fork(function() {
        yield fork(function() {
            yield Time::sleep(100);
        });
    });
    yield fork(function() {
        yield fork(function() {
            yield fork(function() {
                yield fork(function() {
                    yield fork(function() {
                        yield;
                    });
                });
            });
            yield fork(function() {
                yield fork(function() {
                    yield fork(function() {
                        yield;
                    });
                    yield fork(function() {
                        // echo (yield getTask());
                        yield;
                    });
                });
            });
        });
    });
    yield fork(function() {
        yield;
    });
});

$a = <<<RAW
Completed *
 |-0:Completed
 | \-0:Running
 |-1:Completed
 | \-0:Completed
 |   |-0:Completed
 |   | \-0:Completed
 |   |   \-0:Completed
 |   \-1:Completed
 |     \-0:Completed
 |       |-0:Completed
 |       \-1:Completed
 \-2:Completed
RAW;

ob_start();
echo $task;
$b = ob_get_clean();

assert(trim($a) === trim($b));


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

<title>BaseTest</title>
<meta name="date" content="2014-06-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.nvonop.selenium.framework.utilities

Class BaseTest

java.lang.Object

org.nvonop.selenium.framework.utilities.BaseTest

Direct Known Subclasses:

ControlTests

public class BaseTest
extends java.lang.Object

This class contains the base functionality for instantiating a thread safe
 web browser for a test. Tests should be able to run in parallel with no
 issues.

Author:

nvonop

Constructor Summary

Constructors

Constructor and Description

BaseTest()

Method Summary

Methods

Modifier and Type
Method and Description

void
closeWebdriver()

This method closes the browser associated with the ThreadLocal WebDriver
 object.

org.openqa.selenium.WebDriver
getWebDriver()

This method returns a ,ThreadLocal> WebDriver object

void
setLocalWebdriver(java.lang.String browser,
                 java.lang.String version,
                 java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run on a users local machine.

void
setRemoteWebdriver(java.lang.String browser,
                  java.lang.String version,
                  java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run remotely on a grid of test
 machines.

void
setSauceWebdriver(java.lang.String browser,
                 java.lang.String version,
                 java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run on Sauce Labs cloud
 infrastructure.

void
setWebDriver(java.lang.String browser,
            java.lang.String version,
            java.lang.String platform)

This method provides a way of initialising a ThreadLocal WebDriver object
 in a consistent way regardless of where the test will run.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BaseTest

public BaseTest()

Method Detail

closeWebdriver

public void closeWebdriver()

This method closes the browser associated with the ThreadLocal WebDriver
 object. It also the WebDriver instance for the ThreadLocal value to null.

setLocalWebdriver

public void setLocalWebdriver(java.lang.String browser,
                     java.lang.String version,
                     java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run on a users local machine.

Parameters:

browser - This can be set to "chrome", "internet explorer" or "firefox"

version - This should be set to reflect the browser required. It is only
            used when matching capabilities for a RemoteWebDriver object
            however.

platform - This should be set to whatever platform the test is required
            to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
            matching capabilities for a RemoteWebDriver object however.

setSauceWebdriver

public void setSauceWebdriver(java.lang.String browser,
                     java.lang.String version,
                     java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run on Sauce Labs cloud
 infrastructure.

Parameters:

browser - This can be set to "chrome", "internet explorer" or "firefox"

version - This should be set to reflect the browser required. It is only
            used when matching capabilities for a RemoteWebDriver object
            however.

platform - This should be set to whatever platform the test is required
            to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
            matching capabilities for a RemoteWebDriver object however.

setRemoteWebdriver

public void setRemoteWebdriver(java.lang.String browser,
                      java.lang.String version,
                      java.lang.String platform)

This method initialises the ThreadLocal WebDriver object according to the
 supplied parameters to enable tests to run remotely on a grid of test
 machines.

Parameters:

browser - This can be set to "chrome", "internet explorer" or "firefox"

version - This should be set to reflect the browser required. It is only
            used when matching capabilities for a RemoteWebDriver object
            however.

platform - This should be set to whatever platform the test is required
            to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
            matching capabilities for a RemoteWebDriver object however.

setWebDriver

public void setWebDriver(java.lang.String browser,
                java.lang.String version,
                java.lang.String platform)

This method provides a way of initialising a ThreadLocal WebDriver object
 in a consistent way regardless of where the test will run. The following
 system properties must be set to "true" or "false" for this method to
 function correctly: LOCAL_DRIVER, REMOTE_DRIVER, SAUCE_DRIVER. Setting
 one of the properties to "true" will ensure the ThreadLocal WebDriver
 object is initialised appropriately.

Parameters:

browser - This can be set to "chrome", "internet explorer" or "firefox"

version - This should be set to reflect the browser required. It is only
            used when matching capabilities for a RemoteWebDriver object
            however.

platform - This should be set to whatever platform the test is required
            to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
            matching capabilities for a RemoteWebDriver object however.

getWebDriver

public org.openqa.selenium.WebDriver getWebDriver()

This method returns a ,ThreadLocal> WebDriver object

Parameters:

browser - This can be set to "chrome", "internet explorer" or "firefox"

version - This should be set to reflect the browser required. It is only
            used when matching capabilities for a RemoteWebDriver object
            however.

platform - This should be set to whatever platform the test is required
            to run on e.g. "WINDOWS", "MAC", "LINUX". It is only used when
            matching capabilities for a RemoteWebDriver object however.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import nastran_pch_reader

parser = nastran_pch_reader.PchParser('test-data/sol101.pch')

# summary of the forces at the elements
for element in [3000, 3001]:
    print('Element force at %d' % element)
    for subcase in parser.get_subcases():
        forces = parser.get_forces(subcase)
        fx, fy, fz, mx, my, mz = forces[element]
        print('\t subcase',subcase, '=>', (fx, fy, fz))


text:
package apps::mulesoft::restapi::mode::servers;

use base qw(centreon::plugins::templates::counter);

use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);

sub custom_status_output {
    my ($self, %options) = @_;

    return sprintf('Id: %s, Status: %s', $self->{result_values}->{id}, $self->{result_values}->{status});
}

sub set_counters {
    my ($self, %options) = @_;

    $self->{maps_counters_type} = [
        { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output' },
        { name => 'servers', type => 1, cb_prefix_output => 'prefix_server_output', message_multiple => 'All servers are ok' }
    ];

    $self->{maps_counters}->{global} = [
        { label => 'total', nlabel => 'mulesoft.servers.total.count', set => {
                key_values      => [ { name => 'total' }  ],
                output_template => '%s',
                perfdatas       => [ { template => '%d', min => 0 } ]
            }
        },
        { label => 'running', nlabel => 'mulesoft.servers.status.running.count', set => {
                key_values      => [ { name => 'running' }  ],
                output_template => 'running : %s',
                perfdatas       => [ { template => '%d', min => 0 } ]
            }
        },
        { label => 'disconnected', nlabel => 'mulesoft.servers.status.disconnected.count', set => {
                key_values      => [ { name => 'disconnected' }  ],
                output_template => 'disconnected : %s',
                perfdatas       => [ { template => '%d', min => 0 } ]
            }
        }
   ];

    $self->{maps_counters}->{servers} = [
        { label => 'status', threshold => 0, set => {
            key_values => [ { name => 'id' }, { name => 'status' }, { name => 'name'}, { name => 'display' } ],
                closure_custom_output => $self->can('custom_status_output'),
                closure_custom_perfdata => sub { return 0; },
                closure_custom_threshold_check => \&catalog_status_threshold
            }
        }
    ];
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'filter-name:s'     => { name => 'filter_name' },
        'warning-status:s'  => { name => 'warning_status', default => '' },
        'critical-status:s' => { name => 'critical_status', default => '' },
    });

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::check_options(%options);

    $self->change_macros(macros => ['warning_status', 'critical_status']);
}

sub prefix_global_output {
    my ($self, %options) = @_;

    return 'Total servers :';
}

sub prefix_server_output {
    my ($self, %options) = @_;

    return "Server '" . $options{instance_value}->{name} . "' ";
}

sub manage_selection {
    my ($self, %options) = @_;

    $self->{global} = { started => 0, stopped => 0, failed => 0 };
    $self->{servers} = {};
    my $result = $options{custom}->list_objects(api_type => 'arm', endpoint => '/servers');
    foreach ('running', 'disconnected') { $self->{global}->{$_} = 0; };

    foreach my $server (@{$result}) {
        next if ( defined($self->{option_results}->{filter_name})
            && $self->{option_results}->{filter_name} ne ''
            && $server->{name} !~ /$self->{option_results}->{filter_name}/ );

        $self->{servers}->{$server} = {
            display     => $server,
            id          => $server->{id},
            name        => $server->{name},
            status      => $server->{status},
        };

        $self->{global}->{running}++ if $server->{status} =~ m/RUNNING/;
        $self->{global}->{disconnected}++ if $server->{status} =~ m/DISCONNECTED/;
    }

    if (scalar(keys %{$self->{servers}}) <= 0) {
        $self->{output}->add_option_msg(short_msg => "No server found.");
        $self->{output}->option_exit();
    }

    $self->{global}->{total} = scalar (keys %{$self->{servers}});
}

1;

__END__

=head1 MODE

Check Mulesoft Anypoint Servers status.

Example:
perl centreon_plugins.pl --plugin=apps::mulesoft::restapi::plugin --mode=servers
--environment-id='1234abc-56de-78fg-90hi-1234abcdefg' --organization-id='1234abcd-56ef-78fg-90hi-1234abcdefg'
--api-username='myapiuser' --api-password='myapipassword' --verbose

More information on'https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/'.

=over 8

=item B<--filter-name>

Filter by server name (Regexp can be used).
Example: --filter-name='^server1$'

=item B<--warning-status>

Set warning threshold for status (Default: '').
Threshold can be matched on %{name}, %{id} or %{status} and Regexp can be used.
Typical syntax: --warning-status='%{status} ne "RUNNING"'

=item B<--critical-status>

Set warning threshold for status (Default: '').
Threshold can be matched on %{name}, %{id} or %{status} and Regexp can be used.
Typical syntax: --critical-status='%{status} =~ m/DISCONNECTED/'

=back

=cut


text:
    {% if page.layout != "about" %}

        {% assign name = site.name | split: ' ' %}
        {{ name | first }} {{ name | last }}

    {% endif %}

        about

		publications

        {% for page in site.pages %}
          {% if page.title and page.url != "/" %}
            {{ page.title }}
          {% endif %}
        {% endfor %}


text:
declare module io {

	export module argonjs {

		export module vuforia {

			interface IVuforiaControl {

				onInitARDone(result: number): void;
			}

			export class VuforiaControl implements io.argonjs.vuforia.IVuforiaControl {

				constructor(implementation: io.argonjs.vuforia.IVuforiaControl);

				public onInitARDone(result: number): void;
			}

			export class VuforiaGLView extends android.opengl.GLSurfaceView {

				constructor(context: android.content.Context);

				init(translucent: boolean, depth: number, stencil: number);
			}

			export class VuforiaRenderer implements android.opengl.GLSurfaceView.Renderer {

				public mIsActive: boolean;

				onSurfaceCreated(gl: any, config: android.opengl.EGLConfig);

				onSurfaceChanged(gl: any, width: number, height: number);

				onDrawFrame(gl: any);

				updateRenderingPrimitives();
			}

			export class VuforiaSession {

				static init(control: VuforiaControl): void;

				static setLicenseKey(activity: android.app.Activity, licenseKey: string);

				static scaleFactor() : number;

				static setScaleFactor(f:number) : void;
			}
		}
	}
}

declare module com {

	export module vuforia {

		export class CameraCalibration {

			constructor();

			getDistortionParameters(): Vec4F;

			getFieldOfViewRads(): Vec2F;

			getFocalLength(): Vec2F;

			getPrincipalPoint(): Vec2F;

			getSize(): Vec2F;
		}

		export class CameraDevice {

			static getInstance(): CameraDevice;

			constructor();

			init(camera: CameraDeviceDirection): boolean;

			deinit(): boolean;

			getCameraCalibration(): CameraCalibration;

			getCameraDirection(): CameraDeviceDirection;

			getNumVideoModes(): number;

			getVideoMode(nIndex: number): VideoMode;

			selectVideoMode(index: number): boolean;

			setFlashTorchMode(on: boolean): boolean;

			setFocusMode(focusMode: CameraDeviceFocusMode): boolean;

			start(): boolean;

			stop(): boolean;
		}

		export const enum CameraDeviceDirection {

			Default = 0,

			Back = 1,

			Front = 2
		}

		export const enum CameraDeviceFocusMode {

			Normal = 0,

			TriggerAuto = 1,

			ContinuousAuto = 2,

			Infinite = 3,

			Macro = 4
		}

		export const enum CameraDeviceMode {

			Default = -1,

			OptimizeSpeed = -2,

			OpimizeQuality = -3
		}

		export const enum CoordinateSystemType {

			Unknown = 0,

			Camera = 1,

			World = 2
		}

		export class CylinderTarget extends ObjectTarget {
		}

		export class CylinderTargetResult extends ObjectTargetResult {

			getTrackable(): Trackable;
		}

		export class DataSet {

			constructor();

			createMultiTarget(name: string): MultiTarget;

			destroy(trackable: Trackable): boolean;

			exists(path: string, storageType: StorageType): boolean;

			getNumTrackables(): number;

			getTrackable(idx: number): Trackable;

			hasReachedTrackableLimit(): boolean;

			isActive(): boolean;

			load(path: string, storageType: StorageType): boolean;
		}

		export class Device {

			static getInstance(): Device;

			constructor();

			getMode(): DeviceMode;

			getRenderingPrimitives(): RenderingPrimitives;

			getSelectedViewer(): ViewerParameters;

			getType(): number;

			getViewerList(): ViewerParametersList;

			isViewerActive(): boolean;

			selectViewer(vp: ViewerParameters): boolean;

			setConfigurationChanged(): void;

			setMode(m: DeviceMode): boolean;

			setViewerActive(active: boolean): void;
		}

		export const enum DeviceMode {

			AR = 0,

			VR = 1
		}

		export class DeviceTracker extends Tracker {

			//static deinitTracker(): boolean;

			//static getInstance(): DeviceTracker;

			//static initTracker(): boolean;
		}

		export const enum FPSHint {

			None = 0,

			NoVideoBackground = 1,

			PowerEfficiency = 2,

			Fast = 4,

			DefaultFlags = 0
		}

		export class Frame  {

			constructor();

			getImage(idx: number): Image|undefined;

			getIndex(): number;

			getNumImages(): number;

			getTimeStamp(): number;
		}

		export class HandheldTransformModel extends TransformModel {
		}

		export class HeadTransformModel extends TransformModel {
		}

		export const enum Hint {

			MaxSimultaneousImageTargets = 0,

			MaxSimultaneousObjectTargets = 1,

			DelayedLoadingObjectDatasets = 2
		}

		export class Image {

			constructor();

			getBufferHeight(): number;

			getBufferWidth(): number;

			getFormat(): PixelFormat;

			getHeight(): number;

			getPixels(): undefined; // ByteBuffer

			getStride(): number;

			getWidth(): number;
		}

		export class ImageTarget extends ObjectTarget {
		}

		export class ImageTargetResult extends ObjectTargetResult {

			getTrackable(): Trackable;
		}

		export const enum InitResult {

			SUCCESS = 100,

			ERROR = -1,

			DEVICE_NOT_SUPPORTED = -2,

			NO_CAMERA_ACCESS = -3,

			LICENSE_ERROR_MISSING_KEY = -4,

			LICENSE_ERROR_INVALID_KEY = -5,

			LICENSE_ERROR_NO_NETWORK_PERMANENT = -6,

			LICENSE_ERROR_NO_NETWORK_TRANSIENT = -7,

			LICENSE_ERROR_CANCELED_KEY = -8,

			LICENSE_ERROR_PRODUCT_TYPE_MISMATCH = -9,

			EXTERNAL_DEVICE_NOT_DETECTED = -10
		}

		export class Marker extends Trackable {
		}

		export class MarkerResult extends TrackableResult {

			getTrackable(): Marker;
		}

		export class Matrix34F {
			getData(): number[];
		}

		export class Matrix44F {
			getData(): number[];
		}

		export class Mesh {

			constructor();

			//getNormalCoordinates(): interop.Reference<number>;

			getNormals(): undefined; // ByteBuffer

			getNumTriangles(): number;

			getNumVertices(): number;

			//getPositionCoordinates(): interop.Reference<number>;

			getPositions(): undefined; // ByteBuffer

			getTriangles(): undefined; // ByteBuffer

			//getUVCoordinates(): interop.Reference<number>;

			getUVs(): undefined; // ByteBuffer

			hasNormals(): boolean;

			hasPositions(): boolean;

			hasUVs(): boolean;
		}

		export class MultiTarget extends ObjectTarget {
		}

		export class MultiTargetResult extends ObjectTargetResult {

			getTrackable(): Trackable;
		}

		export class ObjectTarget extends Trackable {
			getUniqueTargetId(): string;
			getSize(): Vec3F;
		}

		export class ObjectTargetResult extends TrackableResult {

			getTrackable(): Trackable;
		}

		export class ObjectTracker extends Tracker {

			static getClassType() : number;

			createDataSet() : DataSet;

			activateDataSet(dataset: DataSet): boolean;

			deactivateDataSet(dataset: DataSet): boolean;

			destroyDataSet(dataset: DataSet): boolean;

			getActiveDataSet(idx: number): DataSet;

			getActiveDataSetCount(): number;

			persistExtendedTracking(on: boolean): boolean;

			resetExtendedTracking(): boolean;
		}

		export const enum PixelFormat {

			Unknown = 0,

			RGB565 = 1,

			RGB888 = 2,

			GRAYSCALE = 4,

			YUV = 8,

			RGBA8888 = 16,

			INDEXED = 32
		}

		export class Renderer {

			static getInstance(): Renderer;

			getRecommendedFps(flags: FPSHint): number;

			getVideoBackgroundConfig(): VideoBackgroundConfig;

			setTargetFps(fps: number): boolean;

			setVideoBackgroundConfig(cfg: VideoBackgroundConfig): void;
		}

		export class RenderingPrimitives {

			constructor();

			getDistortionTextureMesh(viewID: View): Mesh;

			getDistortionTextureSize(viewID: View): Vec2I;

			getDistortionTextureViewport(viewID: View): Vec4I;

			getEyeDisplayAdjustmentMatrix(viewID: View): Matrix34F;

			getNormalizedViewport(viewID: View): Vec4F;

			getProjectionMatrix(viewID: View, csType: CoordinateSystemType): Matrix34F;

			getRenderingViews(): ViewList;

			getVideoBackgroundMesh(viewID: View): Mesh;

			getVideoBackgroundProjectionMatrix(viewID: View, csType: CoordinateSystemType): Matrix34F;

			getViewport(viewID: View): Vec4I;
		}

		/*
		export const enum Rotation {

			IOS_90 = 128,

			IOS_180 = 256,

			IOS_270 = 512,

			IOS_0 = 1024
		}
		*/

		export class RotationalDeviceTracker extends DeviceTracker {

			//static getInstance(): RotationalDeviceTracker;

			getDefaultHandheldModel(): HandheldTransformModel;

			getDefaultHeadModel(): HeadTransformModel;

			getModelCorrection(): TransformModel;

			getPosePrediction(): boolean;

			recenter(): boolean;

			setModelCorrection(transformationmodel: TransformModel): boolean;

			setPosePrediction(enable: boolean): boolean;
		}

		export class State {

			constructor();

			getFrame(): Frame;

			getNumTrackableResults(): number;

			getNumTrackables(): number;

			getTrackable(idx: number): Trackable;

			getTrackableResult(idx: number): TrackableResult;
		}

		export const enum StorageType {

			App = 0,

			AppResource = 1,

			Absolute = 2
		}

		export class Tool {

			static convertPerspectiveProjection2GLMatrix(projection: Matrix34F, nearPlane: number, farPlane: number): Matrix44F;

			static convertPose2GLMatrix(pose: Matrix34F);
		}

		export class Trackable {

			static getClassType(): number;

			constructor();

			getId(): number;

			getName(): string;

			getType(): number;

			getUserData(): Object;

			isConst(): boolean;

			isExtendedTrackingStarted(): boolean;

			setUserData(userData: interop.Pointer): boolean;

			startExtendedTracking(): boolean;

			stopExtendedTracking(): boolean;
		}

		export class TrackableResult {

			static getClassType(): number;

			constructor();

			getPose(): Matrix34F;

			getTimeStamp(): number;

			getStatus(): TrackableResultStatus;

			getTrackable(): Trackable;

			getType(): number;
		}

		export const enum TrackableResultStatus {

			Unknown = 0,

			Undefined = 1,

			Detected = 2,

			Tracked = 3,

			ExtendedTracked = 4
		}

		export class Tracker {

			constructor();

			start(): boolean;

			stop(): void;
		}

		export class TrackerManager {

			static getInstance(): TrackerManager;

			initTracker(type: number): Tracker;

			getTracker(type: number): Tracker;

			deinitTracker(type: number): boolean;
		}

		export class TransformModel {

			constructor();
		}

		export class Vec2F {
			constructor(v0: number, v1: number);
			getData(): number[];
		}

		export class Vec2I {
			constructor(v0: number, v1: number);
			getData(): number[];
		}

		export class Vec3F {
			constructor(v0: number, v1: number, v2: number);
			getData(): number[];
		}

		export class Vec4F {
			constructor(v0: number, v1: number, v2: number, v3: number);
			getData(): number[];
		}

		export class Vec4I {
			constructor(v0: number, v1: number, v2: number, v3: number);
			getData(): number[];
		}

		export module Vuforia {

			interface IUpdateCallbackInterface {

				Vuforia_onUpdate(state: State);
			}

			class UpdateCallbackInterface implements com.vuforia.Vuforia.IUpdateCallbackInterface {

				constructor(implementation: com.vuforia.Vuforia.IUpdateCallbackInterface);

				public Vuforia_onUpdate(state: State);
			}
		}

		export class Vuforia {

			static getLibraryVersion(): string;

			static deinit();

			static onPause();

			static onResume();

			static onSurfaceCreated();

			static onSurfaceChanged(width: number, height: number);

			static registerCallback(object: Vuforia.UpdateCallbackInterface);

			static requiresAlpha(): boolean;

			static setHint(hint: number, value: number): boolean;
		}

		export class VideoBackgroundConfig {

			getEnabled(): boolean;

			getPosition(): Vec2I;

			getSize(): Vec2I;

			getReflection(): VideoBackgroundReflection;

			setEnabled(value: boolean);

			setPosition(value: Vec2I);

			setSize(value: Vec2I);

			setReflection(value: VideoBackgroundReflection);
		}

		export const enum VideoBackgroundReflection {

			Default = 0,

			On = 1,

			Off = 2
		}

		export class VideoMode {

			getWidth(): number;

			getHeight(): number;

			getFramerate(): number;
		}

		export const enum View {

			Singular = 0,

			LeftEye = 1,

			RightEye = 2,

			PostProcess = 3,

			Count = 4
		}

		export class ViewList {

			constructor();

			contains(view: View): boolean;

			getNumViews(): number;

			getView(idx: number): View;
		}

		export class ViewerParameters {

			constructor();

			containsMagnet(): boolean;

			getButtonType(): ViewerParamtersButtonType;

			getDistortionCoefficient(idx: number): number;

			getFieldOfView(): Vec4F;

			getInterLensDistance(): number;

			getLensCentreToTrayDistance(): number;

			getManufacturer(): string;

			getName(): string;

			getNumDistortionCoefficients(): number;

			getScreenToLensDistance(): number;

			getTrayAlignment(): ViewerParamtersTrayAlignment;

			getVersion(): number;
		}

		export class ViewerParametersList {

			constructor();

			get(idx: number): ViewerParameters;

			get(name: string, manufacturer: string): ViewerParameters;

			setSDKFilter(filter: string): void;

			size(): number;
		}

		export const enum ViewerParamtersButtonType {

			None = 0,

			Magnet = 1,

			FingerTouch = 2,

			ButtonTouch = 3
		}

		export const enum ViewerParamtersTrayAlignment {

			Bottom = 0,

			Centre = 1,

			Top = 2
		}

		export class Word extends Trackable {
		}

		export class WordResult extends TrackableResult {

			getTrackable(): Trackable;
		}
	}
}


text:
$LOAD_PATH.unshift File.expand_path("#{File.dirname(__FILE__)}/../lib/")
require 'messagebird'

# ACCESS_KEY = 'YOUR KEY HERE'

unless defined?(ACCESS_KEY)
  puts 'You need to set an ACCESS_KEY constant in this file'
  exit 1
end

begin
  # Create a MessageBird client with the specified ACCESS_KEY.
  client = MessageBird::Client.new(ACCESS_KEY)

  # Fetch the HLR object for the specified HLR_ID.
  numbers = client.number_fetch_all(limit: 5)

  # Print the object information.
  puts 'The folling number was returned as a Number object'
  puts

  if numbers.positive?
    numbers.items.each do |number|
      puts "  number     : #{number.number}"
      puts "    country  : #{number.country}"
      puts "    region   : #{number.region}"
      puts "    locality : #{number.locality}"
      puts "    features : #{number.features}"
      puts "    tags     : #{number.tags}"
      puts "    type     : #{number.type}"
      puts "    status     : #{number.status}"
    end
  else
    puts 'No records returned'
  end
rescue MessageBird::ErrorException => e
  puts
  puts 'An error occured while requesting the lookup:'
  puts

  e.errors.each do |error|
    puts "  code        : #{error.code}"
    puts "  description : #{error.description}"
    puts "  parameter   : #{error.parameter}"
    puts
  end
end


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

public class Mover : MonoBehaviour {

	public float speed;
	public Camera mainCamera;
	public GameObject crosshair;
	public GameObject generatedCrosshair;
	private Rigidbody rb;

	// Use this for initialization
	void Start () {
		rb = GetComponent<Rigidbody> ();
		rb.velocity = CalculateSpeedVectorNormal() * speed;
		SpawnHelperCrosshair ();
	}

	Vector3 CalculateSpeedVectorNormal() {
		return transform.forward;
	}

	Vector3 CalculateSpeedVectorSpecial() {
		Vector3 rbPos = rb.position;
		Vector3 cameraPos = mainCamera.transform.position;
		Vector3 normalVector = new Vector3 (rbPos.x - cameraPos.x, 0.0f, Mathf.Abs (cameraPos.z - rbPos.z));
		return normalVector.normalized;
	}

	void SpawnHelperCrosshair () {
		Vector3 crosshairPos = new Vector3 (rb.position.x, rb.position.y, 0);
		this.generatedCrosshair = Instantiate (crosshair, crosshairPos, Quaternion.identity);
	}

	void OnDestroy() {
		Destroy (this.generatedCrosshair);
	}

}


text:
export const extractSalesforceId = (rawSalesforceId) => {
  // We must extract the ID from a full Salesforce URL. It is 15 or 18 characters.
  // Old Salesforce URLs may look like this: https://cs54.salesforce.com/c1f1f010013YOsu?srPos=2&srKp=a0f
  let salesforceId = rawSalesforceId.replace(/\?.*/, '');
  // New Salesforce URLs look like: https://wikied.lightning.force.com/one/one.app#/sObject/a0f1a000003yDoIAAU/view
  if (salesforceId.length !== 15 && salesforceId.length !== 18) {
    salesforceId = salesforceId.replace(/\/view/, '');
    salesforceId = salesforceId.match(/.*\/([\w\d]+)$/)[1];
  }
  return salesforceId;
};


text:
package com.thoughtworks.go.service;

import com.thoughtworks.go.serverhealth.HealthStateScope;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.util.SystemEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.thoughtworks.go.CurrentGoCDVersion.docsUrl;

@Component
public class ConfigRepositoryGCWarningService {
    private final ConfigRepository configRepository;
    private final ServerHealthService serverHealthService;
    private final SystemEnvironment systemEnvironment;
    private static final String SCOPE = "GC";
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRepositoryGCWarningService.class.getName());

    @Autowired
    public ConfigRepositoryGCWarningService(ConfigRepository configRepository, ServerHealthService serverHealthService, SystemEnvironment systemEnvironment) {
        this.configRepository = configRepository;
        this.serverHealthService = serverHealthService;
        this.systemEnvironment = systemEnvironment;
    }

    public void checkRepoAndAddWarningIfRequired() {
        try {
            if (configRepository.getLooseObjectCount() >= systemEnvironment.get(SystemEnvironment.GO_CONFIG_REPO_GC_LOOSE_OBJECT_WARNING_THRESHOLD)) {
                String message = "Action required: Run 'git gc' on config.git repo";
                String description = "Number of loose objects in your Configuration repository(config.git) has grown beyond " +
                        "the configured threshold. As the size of config repo increases, the config save operations tend to slow down " +
                        "drastically. It is recommended that you run 'git gc' from " +
                        "'<go server installation directory>/db/config.git/' to address this problem. Go can do this " +
                        "automatically on a periodic basis if you enable automatic GC. read more...";

                serverHealthService.update(ServerHealthState.warningWithHtml(message, description, HealthStateType.general(HealthStateScope.forConfigRepo(SCOPE))));
                LOGGER.warn("{}:{}", message, description);
            } else {
                serverHealthService.removeByScope(HealthStateScope.forConfigRepo(SCOPE));

            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}


text:
require 'spec_helper'

describe Spree::Reimbursement, type: :model do

  let(:order) {FactoryGirl.create(:shipped_order)}
  let(:stock_location) {create(:stock_location)}
  let(:return_authorization_reason) { create(:return_authorization_reason)}
  let!(:default_refund_reason) { Spree::RefundReason.find_or_create_by!(name: Spree::RefundReason::RETURN_PROCESSING_REASON, mutable: false) }

  before do
    MyConfigPreferences.set_preferences
  end

  before :each do
    @order = FactoryGirl.create(:shipped_order)
    payment = create(:payment, amount: @order.total, order: @order, state: 'completed')
    return_authorization = Spree::ReturnAuthorization.create(:order => @order, :stock_location => stock_location, :reason => return_authorization_reason)
    @inventory_unit = @order.shipments.first.inventory_units.first
    return_item = return_authorization.return_items.create(inventory_unit: @inventory_unit)
    customer_return = return_authorization.return_items.first.build_customer_return(stock_location: stock_location)
    customer_return.return_items << return_item
    customer_return.save!
    @customer_return = customer_return
  end
  let(:reimbursement) { create(:reimbursement, customer_return: @customer_return, order: @order, return_items: [@customer_return.return_items.first])}
  subject { reimbursement.perform! }

  describe "#avalara_eligible" do
    it "should return true" do
      expect(reimbursement.avalara_eligible).to eq(true)
    end
  end
  describe "#avalara_lookup" do
    it "should return lookup_avatax" do
      expect(reimbursement.avalara_lookup).to eq(:lookup_avatax)
    end
    it "creates new avalara_transaction" do
      expect{reimbursement}.to change{Spree::AvalaraTransaction.count}.by(1)
    end
  end
  describe "#avalara_capture" do
    it "creates new avalara_transaction" do
      expect{reimbursement.avalara_capture}.to change{Spree::AvalaraTransaction.count}.by(1)
    end
  end
  context "finalized" do
    describe "#pending" do
      it "returns inital state of authorized" do
        expect(reimbursement.reimbursement_status).to eq("pending")
      end
    end

    describe "#reimbursed" do
      it "should update reimbursement state" do
        expect{subject}.to change{reimbursement.reimbursement_status}.to eq("reimbursed")
      end
    end
  end
end


text:
<?php

class SimplePie_First_Item_Description_Test_RSS_092_DC_11_Description extends SimplePie_First_Item_Description_Test
{
	function data()
	{
		$this->data =
'<rss version="0.92" xmlns:dc="http://purl.org/dc/elements/1.1/">
	<channel>
		<item>
			<dc:description>Item Description</dc:description>
		</item>
	</channel>
</rss>';
	}

	function expected()
	{
		$this->expected = 'Item Description';
	}
}

?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout

HashChangeEvent

HashChangeEvent

HashChangeEvent

polymer_app_layout_template

polymer_app_layout

HashChangeEvent

HashChangeEvent

constructor
 HashChangeEvent

polymer_app_layout_template

polymer_app_layout

HashChangeEvent

Static properties

supported

Properties

bubbles

cancelable

clipboardData

currentTarget

defaultPrevented

eventPhase

matchingTarget

newUrl

oldUrl

path

target

timeStamp

type

Constructors

HashChangeEvent

Methods

preventDefault

stopImmediatePropagation

stopPropagation

                HashChangeEvent(

            String type,
{bool canBubble: true,
bool cancelable: true,
String oldUrl,
String newUrl}

        )

Not documented.

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


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

namespace ZippyNet.Html.Form
{
    /// <summary>
    /// Компонент  тэга  <textarea>;
    /// </summary>
    public class TextArea : TextInput
    {

        public  TextArea(string id):base(id)
        {

        }
        public override void getRequestData()
        {
            this.getTag().InnerHtml = this.text;
        }

        public override string AjaxAnswer()
        {
            return "$('#" + this.id + "').text('" + this.text + "')";
        }
    }
}


text:
title: Atom Shell is now Electron
author: kevinsawicki
date: '2015-04-23'
---

Atom Shell is now called Electron. You can learn more about Electron and what people are building with it at its new home [electron.atom.io][electron].

---

[![electron](https://cloud.githubusercontent.com/assets/671378/7396651/b7fae482-ee57-11e4-97a2-053515654c75.png)][electron]

Electron is the cross-platform application shell we originally built for the [Atom editor][atom] to handle the Chromium/Node.js event loop integration and native APIs.

When we got started, our goal wasn't just to support the needs of a text editor. We also wanted to create a straightforward framework that would allow people to use web technologies to build cross-platform desktop apps with all of the native trimmings.

In two years, Electron has grown immensely. It now includes automatic app updates, Windows installers, crash reporting, notifications, and other useful native app features — all exposed through JavaScript APIs. And we have more in the works. We plan to extract even more libraries from Atom to make building a native app with web technologies as easy as possible.

So far, individual developers, early-stage startups, and large companies have built apps on Electron. They've created a huge range of apps — including chat apps, database explorers, map designers, collaborative design tools, and mobile prototyping apps.

Check out the new [electron.atom.io][electron] to see more of the apps people have built on Electron or take a look at the [docs][docs] to learn more about what else you can make.

If you've already gotten started, we'd love to chat with you about the apps you're building on Electron. Email [electron@github.com](mailto:electron@github.com?Subject=Electron) to tell us more. You can also follow the new [@ElectronJS](https://twitter.com/electronjs) Twitter account to stay connected with the project.

:zap: :blue_heart: :electric_plug:

[atom]: https://atom.io
[docs]: https://github.com/electron/electron/tree/master/docs#readme
[electron]: http://electron.atom.io


text:
// Copyright © Microsoft Open Technologies, Inc.
//
// All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
// ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
// PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache License, Version 2.0 for the specific language
// governing permissions and limitations under the License.

namespace Microsoft.Azure.ActiveDirectory.GraphClient
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.Azure.ActiveDirectory.GraphClient.ErrorHandling;
    using Newtonsoft.Json;

    /// <summary>
    /// Aad group object.
    /// </summary>
    public partial class Group : DirectoryObject
    {
        /// <summary>
        /// Validate the group properties for create / update.
        /// </summary>
        /// <param name="isCreate">Is this a create operation?</param>
        public override void ValidateProperties(bool isCreate)
        {
            base.ValidateProperties(isCreate);

            if (this.MailEnabled.HasValue && this.MailEnabled.Value)
            {
                throw new PropertyValidationException("MailEnabled groups cannot be created through Graph Api.");
            }
        }
    }
}


text:
  To:
  {{output.toAddress || output.address}}

  Amount:
  {{output.amountStr}}
  ({{output.alternativeAmountStr}})

  Note:
  {{output.message}}


text:
namespace relm {

// utility function for sending an integer type
template <class T>
int write_int(caf::io::broker* self,
              caf::io::connection_handle hdl, T value) {
  using unsigned_type = typename std::make_unsigned<T>::type;
  auto cpy = static_cast<T>(htonl(static_cast<unsigned_type>(value)));
  self->write(hdl, sizeof(T), &cpy);
  self->flush(hdl);
  return sizeof(T);
}
int write_int(caf::io::broker* self,
              caf::io::connection_handle hdl, uint64_t value);

// utility function for reading an integer from incoming data
template <class T>
int read_int(const void* data, T& storage) {
  using unsigned_type = typename std::make_unsigned<T>::type;
  memcpy(&storage, data, sizeof(T));
  storage = static_cast<T>(ntohl(static_cast<unsigned_type>(storage)));
  return sizeof(T);
}
int read_int(const void* data, uint64_t& storage);

caf::behavior broker_impl(caf::io::broker* self,
                          caf::io::connection_handle hdl,
                          const caf::actor& buddy);
caf::behavior server(caf::io::broker* self,
                     const caf::actor& buddy);

} // namespace relm


text:
from datetime import date
import pandas as pd
from StringIO import StringIO
from urllib2 import urlopen

class Yahoo(object):

    # Taken from http://www.jarloo.com/yahoo_finance/
    yahoo_query_params = {
        'ticker': 's',
        'average_daily_volume': 'a2',
        'dividend_yield': 'y',
        'dividend_per_share': 'd',
        'earnings_per_share': 'e',
        'est_eps_yr': 'e7',
        'est_eps_next_yr': 'e8',
        'ex_dividend_date': 'q',
        'market_cap': 'j1',
        'price_earnings_ratio': 'r',
        'short_ratio': 's7',
        'volume': 'v',
        '52w_low': 'j',
        '52w_high': 'k'
    }

    def __init__(self, chunk_size=500):
        self.chunk_size = chunk_size
        self.market_cap_pattern = '(\d+[\.]\d+)([MB])'

    @staticmethod
    def _convert_market_cap(str_value):
        if type(str_value) != str:
            return -1.
        last_char = str_value[-1]
        if last_char in ['B', 'M']:
            base = float(str_value[:-1])
            multiplier = 10.**9 if last_char == 'B' else 10.**6
            return base * multiplier
        return float(str_value)

    def _fetch_fields(self, symbols, fields):
        def chunker(symbols):
            i = 0
            while i < len(symbols):
                count_chunk = min(self.chunk_size, len(symbols) - i)
                yield symbols[i:(i + count_chunk)]
                i += count_chunk
        dfs = []
        for chunk in chunker(symbols):
            request = 'http://download.finance.yahoo.com/d/quotes.csv?s={}&f={}'.format(','.join(chunk), fields)
            raw_dat = urlopen(request).read()
            df = pd.read_csv(StringIO(raw_dat), header=None)
            dfs.append(df)
        ret = pd.concat(dfs)
        return ret

    def batch_snapshot(self, tickers):
        """
        Retrieves financial information for a batch of stock symbols.

        Args:
            tickers (list<str>): list of stock symbols
        Returns:
            pandas.Dataframe: dataframe with one row per symbol.
        """
        ret = self._fetch_fields(tickers, ''.join(Yahoo.yahoo_query_params.values()))
        ret.columns = Yahoo.yahoo_query_params.keys()
        for col in ['ex_dividend_date']:
            ret[col] = pd.to_datetime(ret[col])
        ret['market_cap'] = [self._convert_market_cap(mc) for mc in ret.market_cap]
        return ret

    @staticmethod
    def _history_call(ticker, from_date, to_date, params):
        base_url = 'http://ichart.finance.yahoo.com/table.csv'
        params.update({'s': ticker,
                  'a': from_date.month - 1,
                  'b': from_date.day,
                  'c': from_date.year,
                  'd': to_date.month - 1,
                  'e': to_date.day,
                  'f': to_date.year
                  })
        url = '{}?{}'.format(base_url, '&'.join('{}={}'.format(k, params[k]) for k in params))
        raw_dat = urlopen(url).read()
        df = pd.read_csv(StringIO(raw_dat), parse_dates=[0])
        return df

    def historic_close(self, tickers, from_date=date(2010, 1, 1), to_date=date.today(), join_type='outer'):
        """
        Extracts the adjusted close for a set of tickers.

        Args:
            tickers (list(str)): stock symbol
            from_date (date): start date
            to_date (date): end date
            join_type (str): type of join
        Returns:
            Dataframe indexed by date with one column by stock ticker.
        """
        def fetch_adj_close(ticker, from_date, to_date):
            dat = self._single_historic_ohlc(ticker, from_date, to_date)
            dat['Date'] = pd.to_datetime(dat.Date, infer_datetime_format=True)
            dat.set_index('Date', inplace=True)
            dat.sort_index(inplace=True)
            ret = dat[['Adj Close']]
            ret.columns = [ticker]
            return ret

        dats = [fetch_adj_close(ticker, from_date=from_date, to_date=to_date) for ticker in tickers]
        return dats[0].join(dats[1:], how=join_type)

    def _single_historic_ohlc(self, ticker, from_date=date(2010, 1, 1), to_date=date.today()):
        return self._history_call(ticker, from_date, to_date, {'g': 'd'})

    def historic_dividends(self, ticker, from_date=date(2010, 1, 1), to_date=date.today()):
        """
        Extracts the dividend payout history for an individual stock.

        Args:
            ticker (str): stock symbol
            from_date (date): start date
            to_date (date): end date
        Returns:
            pandas.DataFrame: dataframe with dates and dividends.
        """
        return self._history_call(ticker, from_date, to_date, {'g': 'v'})


text:
package lu.kremi151.algebraparser.function;

import lu.kremi151.algebraparser.annotation.FunctionMeta;
import lu.kremi151.algebraparser.component.AFunction;
import lu.kremi151.algebraparser.exception.AlgebraException;
import lu.kremi151.algebraparser.interfaces.AObject;

@FunctionMeta(argsLength=1,argsMinimum=1)
public class ATangent extends AFunction
{

	public ATangent(AObject[] args){
		super(args);
	}

	@Override
	public double getResult(double x) throws AlgebraException
	{
		return Math.tan(getInner().getResult(x));
	}

	@Override
	public String getStringRepresentation()
	{
		return "tan(" + getInner().getStringRepresentation() + ")";
	}

}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from "react-helmet";
import t from './_lang.json';
import hero640 from './img/devops-640w.jpg';
import hero960 from './img/devops-960w.jpg';
import hero1280 from './img/devops-1280w.jpg';
import hero1920 from './img/devops-1920w.jpg';
import hero2560 from './img/devops-2560w.jpg';
import hero3840 from './img/devops-3840w.jpg';

import Hero from '../../../components/Hero/Hero';

export class DevOpsPage extends Component {
  render() {
    let { lang } = this.props;

    return (
      <div className="devops">
        <Helmet>
          <title>{t[lang.id].title}</title>
        </Helmet>
        <Hero lang={lang} title={t[lang.id].title}
          hero640={hero640} hero960={hero960} hero1280={hero1280}
          hero1920={hero1920} hero2560={hero2560} hero3840={hero3840}>
        </Hero>
      </div>
    )
  }
}

DevOpsPage.propTypes = {
  lang: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    lang: state.lang
  };
}

export default connect(mapStateToProps)(DevOpsPage);


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/runtimeconfig/v1beta1/resources.proto

package com.google.cloud.runtimeconfig.v1beta1;

public interface EndConditionOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.cloud.runtimeconfig.v1beta1.EndCondition)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The cardinality of the `EndCondition`.
   *

   *
   * optional .google.cloud.runtimeconfig.v1beta1.EndCondition.Cardinality cardinality = 1;
   */
  com.google.cloud.runtimeconfig.v1beta1.EndCondition.Cardinality getCardinality();
  /**
   *

   * The cardinality of the `EndCondition`.
   *

   *
   * optional .google.cloud.runtimeconfig.v1beta1.EndCondition.Cardinality cardinality = 1;
   */
  com.google.cloud.runtimeconfig.v1beta1.EndCondition.CardinalityOrBuilder getCardinalityOrBuilder();

  public com.google.cloud.runtimeconfig.v1beta1.EndCondition.ConditionCase getConditionCase();
}


text:
package org.apache.jasper.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * Adapter class that wraps an Enumeration around a Java2
 * collection classes object Iterator so that existing APIs
 * returning Enumerations can easily run on top of the new collections.
 * Constructors are provided to easily create such wrappers.
 *
 * @author Craig R. McClanahan
 * @deprecated Replaced by java.util.Collections#enumeration(..)
 */
@Deprecated
public final class Enumerator<T> implements Enumeration<T> {

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

    /**
     * Return an Enumeration over the values returned by the
     * specified Iterator.
     *
     * @param iterator Iterator to be wrapped
     */
    public Enumerator(Iterator<T> iterator) {

        super();
        this.iterator = iterator;

    }

    /**
     * Return an Enumeration over the values returned by the
     * specified Iterator.
     *
     * @param iterator Iterator to be wrapped
     * @param clone true to clone iterator
     */
    public Enumerator(Iterator<T> iterator, boolean clone) {

        super();
        if (!clone) {
            this.iterator = iterator;
        } else {
            List<T> list = new ArrayList<T>();
            while (iterator.hasNext()) {
                list.add(iterator.next());
            }
            this.iterator = list.iterator();
        }

    }

    // ----------------------------------------------------- Instance Variables

    /**
     * The Iterator over which the Enumeration
     * represented by this class actually operates.
     */
    private Iterator<T> iterator = null;

    // --------------------------------------------------------- Public Methods

    /**
     * Tests if this enumeration contains more elements.
     *
     * @return true if and only if this enumeration object
     *  contains at least one more element to provide, false
     *  otherwise
     */
    @Override
    public boolean hasMoreElements() {

        return (iterator.hasNext());

    }

    /**
     * Returns the next element of this enumeration if this enumeration
     * has at least one more element to provide.
     *
     * @return the next element of this enumeration
     *
     * @exception NoSuchElementException if no more elements exist
     */
    @Override
    public T nextElement() throws NoSuchElementException {

        return (iterator.next());

    }

}


text:
TScreenEmbeded* Screen = NULL;

// The glu quadric we'll render (a simple cylinder)
GLUquadricObj *quadric = NULL;

// Window dimensions
int Width = 800;
int Height = 600;

// This function is located in sdlkey.cpp and will translate
// keyboard messages for GUIde
extern TKey TranslateKey(int);

//-------------------------------------------------------------------
//  Init()
//  Initialize a 3D scene and GUIde
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
void Init(void)
{
	// Init the quadric (a 3D cylinder)
	quadric = gluNewQuadric();
	gluQuadricNormals(quadric, GLU_SMOOTH);
	gluQuadricTexture(quadric, GL_TRUE);

	// Create the GUIde's TScreen object. Give to it the dimensions
	// of our screen
	Screen = new TScreenEmbeded;
	Screen->Create(TRect(0, 0, Width, Height), "../res/skins/aqua.xml");

	// Create the main form, without any caption
	TForm1* Form1 = new TForm1;
	Form1->Create(NULL, TRect(0, 0, Width, Height), false);
	Form1->SetMain(true);
}

//-------------------------------------------------------------------
//  Exit()
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
void Exit(void)
{
	// Delete GUIde's TScreen object. It's no need to delete the
	// controls because GUIde will take care of them
	if(Screen != NULL)
		delete Screen;
}

//-------------------------------------------------------------------
//  DrawScene()
//  Render the 3D scene and GUIde
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
void DrawScene(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glViewport(0, 0, Width, Height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0, (float)(Width)/(float)(Height), 0.1f, 500.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0, 0, -15);
	glRotatef(0, 1.0f, 0.0f, 0.0f);
	glRotatef(-45, 0.0f, 1.0f, 0.0f);
    glRotatef(0, 0.0f, 0.0f, 1.0f);

	// Enable lighting and depth test because GUIde disables them
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_DEPTH_TEST);

	// Just a simple cylinder
	gluCylinder(quadric, 4.0f, 4.0f, 4.0f, 16, 2);

	// Render the GUIde at the top of your 3D scene
	Screen->Render();
}

//-------------------------------------------------------------------
//  HandleEvent()
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
int HandleEvent(SDL_Event *event)
{
	int done = 0;
	TMessage msg;
	switch(event->type)
	{
		case SDL_MOUSEMOTION:
			msg.Msg	= CM_MOUSEMOVE;
			msg.LParam	= MAKELONG(event->motion.x, event->motion.y);
			break;
		case SDL_MOUSEBUTTONDOWN:
		case SDL_MOUSEBUTTONUP:
			if(event->button.state == SDL_PRESSED)
				msg.Msg	= CM_MOUSEDOWN;
			else
				msg.Msg	= CM_MOUSEUP;
			msg.LParam	= MAKELONG(event->motion.x, event->motion.y);
			break;
	    case SDL_KEYDOWN:
			msg.Msg		= CM_KEYDOWN;
			msg.LParam	= TranslateKey((int)event->key.keysym.sym);

			// We want to exit when the ESC key is pressed
			if(event->key.keysym.sym == SDLK_ESCAPE)
				done = 1;
			break;
		case SDL_KEYUP:
			msg.Msg		= CM_KEYUP;
			msg.LParam	= TranslateKey((int)event->key.keysym.sym);
			break;
	    case SDL_QUIT:
			done = 1;
			break;
	}

	// Pass the input to the TScreen object
	if(Screen != NULL)
		Screen->HandleInputMessage(&msg);

	return(done);
}

//-------------------------------------------------------------------
//  Run()
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
int Run(void)
{
	int done = 0;

	// Initialize SDL video
	if(SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError());
		exit(1);
	}

	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );    // tell SDL that the GL drawing is going to be double buffered
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16);      // size of depth buffer
    SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0);     // we aren't going to use the stencil buffer
    SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 0);   // this and the next three lines set the bits allocated per pixel -
    SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 0); // - for the accumulation buffer to 0
    SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 0);
    SDL_GL_SetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, 0);

	// Set video mode
	if(SDL_SetVideoMode( Width, Height, 16, SDL_OPENGL ) == NULL)
	{
		fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(1);
	}

	// Set the window manager title bar
	SDL_WM_SetCaption("SDL GL test", "testgl");

	// Hide mouse cursor because GUIde will render its own one
	SDL_ShowCursor(0);

	// Initilize our specific stuff
	Init();

	// Loop until done
	while(!done)
	{
		// Render our scene
		DrawScene();

		// Swap OpenGL buffers
		SDL_GL_SwapBuffers();

		// Check for error conditions
		GLenum gl_error = glGetError();
		if(gl_error != GL_NO_ERROR)
			fprintf( stderr, "testgl: OpenGL error: %d\n", gl_error);

		// Print SDL errors
		char* sdl_error = SDL_GetError();
		if(sdl_error[0] != '\0')
		{
			fprintf(stderr, "testgl: SDL error '%s'\n", sdl_error);
			SDL_ClearError();
		}

		// Check if there's a pending event
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			done = HandleEvent(&event);
		}
	}

	// Clean up our specific stuff
	Exit();

	// Destroy our GL context, etc
	SDL_Quit();

	return(0);
}

//-------------------------------------------------------------------
//  Run()
//  19-Oct-2004   rzv    created
//-------------------------------------------------------------------
int main(int argc, char *argv[])
{
 	Run();

	return 0;
}


text:
Changelog
=========

0.5.26
------
* Use python-future instead of six as compatibility library
* Now distributing a wheel package
* Bug fix: Confirmation prompts crash on Python 2

0.5.25
------
* Bug fix: Compatibility errors with Python 3

0.5.24
------
* Bug fix: Support key conditions where field has a ``-`` in the name

0.5.23
------
* Bug fix: Default encoding error on mac

Dropping support for python 2.6

0.5.22
------
* Bug fix: Can now run any CLI command using ``-c "command"``

0.5.21
------
* Bug fix: Crash fix when resizing terminal with 'watch' command active
* 'Watch' columns will dynamically resize to fit terminal width

0.5.20
------
* Bug fix: When saving to JSON floats are no longer cast to ints
* Bug fix: Reserved words are correctly substituted when using WHERE ... IN

0.5.19
------
* Locked in the version of pyparsing after 2.1.5 broke compatibility again.

0.5.18
------
* Bug fix: Correct name substitution/selection logic
* Swapped out ``bin/run_dql.py`` for ``bin/install.py``. Similar concept, better execution.

0.5.17
------
* Bug fix: Can't display Binary data

0.5.16
------
* Bug fix: Can't use boolean values in update statements

0.5.15
------
* Gracefully handle missing imports on Windows

0.5.14
------
* Missing curses library won't cause ImportError

0.5.13
------
* Fix bug where query would sometimes display 'No Results' even when results were found.

0.5.12
------
* Differentiate LIMIT and SCAN LIMIT
* Options and query syntax for ``throttling`` the consumed throughput
* Crash fixes and other small robustness improvements

0.5.11
------
* SELECT <attributes> can now use full expressions

0.5.10
------
* LOAD command to insert records from a file created with ``SELECT ... SAVE``
* Default SAVE format is pickle
* SAVE command can gzip the file

0.5.9
-----
* Don't print results to console when saving to a file
* 'auto' pagesize to adapt to terminal height
* When selecting specific attributes with KEYS IN only those attributes are fetched
* ORDER BY queries spanning multiple pages no longer stuck on first page
* Column formatter fits column widths more intelligently
* Smart formatter is smarter about switching to Expanded mode

0.5.8
-----
* Tab completion for Mac OS X

0.5.7
-----
* ``run_dql.py`` locks in a version
* Display output auto-detects terminal width

0.5.6
-----
* Format option saves properly
* WHERE expressions can compare fields to fields (e.g. ``WHERE foo > bar``)
* Always perform batch_get after querying/scanning an index that doesn't project all attributes

0.5.5
-----
* General bug fixes
* Self contained ``run_dql.py`` script

0.5.4
-----
* Fixes for ``watch`` display
* SELECT can save the results to a file

0.5.3
-----
* ALTER commands can specify IF (NOT) EXISTS
* New ``watch`` command to monitor table consumed capacities
* SELECT can fetch attributes that aren't projected onto the queried index
* SELECT can ORDER BY non-range-key attributes

0.5.2
-----
* EXPLAIN <query> will print out the DynamoDB calls that will be made when you run the query
* ANALYZE <query> will run the query and print out consumed capacity information

0.5.1
-----
* Pretty-format non-item query return values (such as count)
* Disable passing AWS credentials on the command line

0.5.0
-----
* **Breakage**: New syntax for SELECT, SCAN, UPDATE, DELETE
* **Breakage**: Removed COUNT query (now ``SELECT count(*)``)
* **Breakage**: Removed the ability to embed python in queries
* New alternative syntax for INSERT
* ALTER can create and drop global indexes
* Queries and updates now use the most recent DynamoDB expressions API
* Unified options in CLI under the ``opt`` command

0.4.1
-----
* Update to maintain compatibility with new versions of botocore and dynamo3
* Improving CloudWatch support (which is used to get consumed table capacity)

0.4.0
-----
* **Breakage**: Dropping support for python 3.2 due to lack of botocore support
* Feature: Support for JSON data types

0.3.2
-----
* Bug fix: Allow '.' in table names of DUMP SCHEMA command
* Bug fix: Passing a port argument to local connection doesn't crash
* Bug fix: Prompt says 'localhost' when connected to DynamoDB local

0.3.1
-----
* Bug fix: Allow '.' in table names

0.3.0
-----
* Feature: SELECT and COUNT can have FILTER clause
* Feature: FILTER clause may OR constraints together

0.2.1
-----
* Bug fix: Crash when printing 'COUNT' queries

0.2.0
-----
* Feature: Python 3 support

0.1.0
-----
* First public release


text:
#include <aws/securityhub/model/AwsEksClusterLoggingDetails.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SecurityHub
{
namespace Model
{

AwsEksClusterLoggingDetails::AwsEksClusterLoggingDetails() :
    m_clusterLoggingHasBeenSet(false)
{
}

AwsEksClusterLoggingDetails::AwsEksClusterLoggingDetails(JsonView jsonValue) :
    m_clusterLoggingHasBeenSet(false)
{
  *this = jsonValue;
}

AwsEksClusterLoggingDetails& AwsEksClusterLoggingDetails::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ClusterLogging"))
  {
    Array<JsonView> clusterLoggingJsonList = jsonValue.GetArray("ClusterLogging");
    for(unsigned clusterLoggingIndex = 0; clusterLoggingIndex < clusterLoggingJsonList.GetLength(); ++clusterLoggingIndex)
    {
      m_clusterLogging.push_back(clusterLoggingJsonList[clusterLoggingIndex].AsObject());
    }
    m_clusterLoggingHasBeenSet = true;
  }

  return *this;
}

JsonValue AwsEksClusterLoggingDetails::Jsonize() const
{
  JsonValue payload;

  if(m_clusterLoggingHasBeenSet)
  {
   Array<JsonValue> clusterLoggingJsonList(m_clusterLogging.size());
   for(unsigned clusterLoggingIndex = 0; clusterLoggingIndex < clusterLoggingJsonList.GetLength(); ++clusterLoggingIndex)
   {
     clusterLoggingJsonList[clusterLoggingIndex].AsObject(m_clusterLogging[clusterLoggingIndex].Jsonize());
   }
   payload.WithArray("ClusterLogging", std::move(clusterLoggingJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace SecurityHub
} // namespace Aws


text:
import fs from "fs";
import test from "tape";
import path from "path";
import load from "load-json-file";
import write from "write-json-file";
import truncate from "@turf/truncate";
import { featureCollection } from "@turf/helpers";
import lineSlice from "./index";

const directories = {
  in: path.join(__dirname, "test", "in") + path.sep,
  out: path.join(__dirname, "test", "out") + path.sep,
};

const fixtures = fs.readdirSync(directories.in).map((filename) => {
  return {
    filename,
    name: path.parse(filename).name,
    geojson: load.sync(directories.in + filename),
  };
});

test("turf-line-slice", (t) => {
  for (const { filename, geojson, name } of fixtures) {
    const [linestring, start, stop] = geojson.features;
    const sliced = truncate(lineSlice(start, stop, linestring));
    sliced.properties["stroke"] = "#f0f";
    sliced.properties["stroke-width"] = 6;
    const results = featureCollection(geojson.features);
    results.features.push(sliced);

    if (process.env.REGEN) write.sync(directories.out + filename, results);
    t.deepEquals(results, load.sync(directories.out + filename), name);
  }
  t.end();
});


text:
package com.huawei.esdk.fusionmanager.local.model.net;

/**
 * 根据ID查询IP带宽模板返回信息
 * <p>
 * @since eSDK Cloud V100R003C30
 */
public class QueryIPBWTemplateByIdResp extends IPBWTemplate
{
    /**
     * 错误码。
     */
    private String code;

    /**
     * 错误信息。
     */
    private String message;

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }
}


text:
import logging
from math import floor
import os.path
import time
from traceback import format_tb
from zipfile import ZipFile

from panda.tasks.base import AbortableTask
from csvkit import CSVKitWriter
from django.conf import settings
from django.utils import simplejson as json
from django.utils.timezone import now
from django.utils.translation import ugettext
from livesettings import config_value

from panda import solr
from panda.utils.notifications import notify

SOLR_PAGE_SIZE = 500

class ExportSearchTask(AbortableTask):
    """
    Task to export all search results to a batch of CSV files.
    """
    name = 'panda.tasks.export.search'

    def run(self, query, task_status_id, filename=None, *args, **kwargs):
        """
        Execute export.
        """
        from panda.models import Dataset, TaskStatus

        log = logging.getLogger(self.name)
        log.info('Beginning export, query: %s' % query)

        task_status = TaskStatus.objects.get(id=task_status_id)
        task_status.begin('Preparing to import')

        if not filename:
            filename = 'search_export_%s' % (now().isoformat())

        zip_name = '%s.zip' % filename

        path = os.path.join(settings.EXPORT_ROOT, filename)
        zip_path = os.path.join(settings.EXPORT_ROOT, zip_name)

        try:
            os.makedirs(os.path.realpath(path))
        except:
            pass

        zipfile = ZipFile(zip_path, 'w')

        response = solr.query_grouped(
            settings.SOLR_DATA_CORE,
            query,
            'dataset_slug',
            offset=0,
            limit=1000,
            group_limit=0,
            group_offset=0
        )
        groups = response['grouped']['dataset_slug']['groups']

        datasets = {}

        for group in groups:
            dataset_slug = group['groupValue']
            count = group['doclist']['numFound']

            datasets[dataset_slug] = count

        total_n = 0
        throttle = config_value('PERF', 'TASK_THROTTLE')

        for dataset_slug in datasets:
            try:
                dataset = Dataset.objects.get(slug=dataset_slug)
            except Dataset.DoesNotExist:
                log.warning('Skipping part of export due to Dataset being deleted, dataset_slug: %s' % dataset_slug)

                continue

            filename = '%s.csv' % dataset_slug
            file_path = os.path.join(path, filename)

            f = open(file_path, 'w')
            writer = CSVKitWriter(f)

            # Header
            writer.writerow([c['name'] for c in dataset.column_schema])

            response = solr.query(
                settings.SOLR_DATA_CORE,
                query,
                offset=0,
                limit=0
            )

            # Update dataset and total counts for progress tracking
            datasets[dataset_slug] = response['response']['numFound']
            total_count = sum(datasets.values())

            n = 0

            while n < datasets[dataset_slug]:

                response = solr.query(
                    settings.SOLR_DATA_CORE,
                    'dataset_slug:%s AND (%s)' % (dataset_slug, query),
                    offset=n,
                    limit=SOLR_PAGE_SIZE
                )

                results = response['response']['docs']

                for row in results:
                    data = json.loads(row['data'])

                    writer.writerow(data)

                task_status.update(ugettext('%.0f%% complete') % floor(float(total_n) / float(total_count) * 100))

                if self.is_aborted():
                    task_status.abort(ugettext('Aborted after exporting %.0f%%') % floor(float(total_n) / float(total_count) * 100))

                    log.warning('Export aborted, query: %s' % query)

                    return

                n += SOLR_PAGE_SIZE
                total_n += response['response']['numFound']

                time.sleep(throttle)

            f.close()

            # Add to zip and nuke temp file
            zipfile.write(file_path, filename)
            os.remove(file_path)

        # Finish zip file and nuke temp directory
        zipfile.close()
        os.rmdir(path)

        task_status.update(ugettext('100% complete'))

        log.info('Finished export, query: %s' % query)

        return zip_name

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        """
        Save final status, results, etc.
        """
        from panda.models import TaskStatus

        query = args[0]
        task_status = TaskStatus.objects.get(id=args[1])

        self.send_notifications(query, task_status, retval, einfo)

    def send_notifications(self, query, task_status, retval, einfo):
        """
        Send user notifications this task has finished.
        """
        from panda.models import Export

        export = None
        extra_context = { 'query': query }
        url = None

        if einfo:
            if isinstance(einfo, tuple):
                tb = '\n'.join(format_tb(einfo[2]))
            else:
                tb = einfo.traceback

            task_status.exception(
                ugettext('Export failed'),
                u'%s\n\nTraceback:\n%s' % (unicode(retval), tb)
            )

            template_prefix = 'export_search_failed'
            extra_context['error'] = unicode(retval)
            extra_context['traceback'] = tb
            notification_type = 'Error'
        elif self.is_aborted():
            template_prefix = 'export_search_aborted'
            notification_type = 'Info'
        else:
            task_status.complete(ugettext('Export complete'))

            export = Export.objects.create(
                filename=retval,
                original_filename=retval,
                size=os.path.getsize(os.path.join(settings.EXPORT_ROOT, retval)),
                creator=task_status.creator,
                creation_date=task_status.start,
                dataset=None)

            extra_context['related_export'] = export

            url = '#export/%i' % export.id

            template_prefix = 'export_search_complete'
            notification_type = 'Info'

        if task_status.creator:
            notify(
                task_status.creator,
                template_prefix,
                notification_type,
                url,
                extra_context=extra_context
            )