text:
#ifndef PYTHON_ZSTANDARD_H
#define PYTHON_ZSTANDARD_H

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <pythoncapi_compat.h>
#include "structmember.h"

#define ZSTD_STATIC_LINKING_ONLY
#define ZDICT_STATIC_LINKING_ONLY

#ifdef ZSTD_SINGLE_FILE
#include <zstdlib.c>

/* We use private APIs from pool.h. We can't rely on availability
   of this header or symbols when linking against the system libzstd.
   But we know it works when using the bundled single file library. */
#define HAVE_ZSTD_POOL_APIS
#else
#include <zdict.h>
#include <zstd.h>
#endif

/* Remember to change the string in zstandard/__init__.py, rust-ext/src/lib.rs,
   and debian/changelog as well */
#define PYTHON_ZSTANDARD_VERSION "0.19.0"

typedef enum {
    compressorobj_flush_finish,
    compressorobj_flush_block,
} CompressorObj_Flush;

/*
   Represents a ZstdCompressionParameters type.

   This type holds all the low-level compression parameters that can be set.
*/
typedef struct {
    PyObject_HEAD ZSTD_CCtx_params *params;
} ZstdCompressionParametersObject;

extern PyTypeObject ZstdCompressionParametersType;

/*
   Represents a FrameParameters type.

   This type is basically a wrapper around ZSTD_frameParams.
*/
typedef struct {
    PyObject_HEAD unsigned long long frameContentSize;
    unsigned long long windowSize;
    unsigned dictID;
    char checksumFlag;
} FrameParametersObject;

extern PyTypeObject FrameParametersType;

/*
   Represents a ZstdCompressionDict type.

   Instances hold data used for a zstd compression dictionary.
*/
typedef struct {
    PyObject_HEAD

        /* Pointer to dictionary data. Owned by self. */
        void *dictData;
    /* Size of dictionary data. */
    size_t dictSize;
    ZSTD_dictContentType_e dictType;
    /* k parameter for cover dictionaries. Only populated by train_cover_dict().
     */
    unsigned k;
    /* d parameter for cover dictionaries. Only populated by train_cover_dict().
     */
    unsigned d;
    /* Digested dictionary, suitable for reuse. */
    ZSTD_CDict *cdict;
    ZSTD_DDict *ddict;
} ZstdCompressionDict;

extern PyTypeObject ZstdCompressionDictType;

/*
   Represents a ZstdCompressor type.
*/
typedef struct {
    PyObject_HEAD

        /* Number of threads to use for operations. */
        unsigned int threads;
    /* Pointer to compression dictionary to use. NULL if not using dictionary
       compression. */
    ZstdCompressionDict *dict;
    /* Compression context to use. Populated during object construction. */
    ZSTD_CCtx *cctx;
    /* Compression parameters in use. */
    ZSTD_CCtx_params *params;
} ZstdCompressor;

extern PyTypeObject ZstdCompressorType;

typedef struct {
    PyObject_HEAD

        ZstdCompressor *compressor;
    ZSTD_outBuffer output;
    int finished;
} ZstdCompressionObj;

extern PyTypeObject ZstdCompressionObjType;

typedef struct {
    PyObject_HEAD

        ZstdCompressor *compressor;
    PyObject *writer;
    ZSTD_outBuffer output;
    size_t outSize;
    int entered;
    int closing;
    char closed;
    int writeReturnRead;
    int closefd;
    unsigned long long bytesCompressed;
} ZstdCompressionWriter;

extern PyTypeObject ZstdCompressionWriterType;

typedef struct {
    PyObject_HEAD

        ZstdCompressor *compressor;
    PyObject *reader;
    Py_buffer buffer;
    Py_ssize_t bufferOffset;
    size_t inSize;
    size_t outSize;

    ZSTD_inBuffer input;
    ZSTD_outBuffer output;
    int finishedOutput;
    int finishedInput;
    PyObject *readResult;
} ZstdCompressorIterator;

extern PyTypeObject ZstdCompressorIteratorType;

typedef struct {
    PyObject_HEAD

        ZstdCompressor *compressor;
    PyObject *reader;
    Py_buffer buffer;
    size_t readSize;
    int closefd;

    int entered;
    char closed;
    unsigned long long bytesCompressed;

    ZSTD_inBuffer input;
    ZSTD_outBuffer output;
    int finishedInput;
    int finishedOutput;
    PyObject *readResult;
} ZstdCompressionReader;

extern PyTypeObject ZstdCompressionReaderType;

typedef struct {
    PyObject_HEAD

        ZstdCompressor *compressor;
    ZSTD_inBuffer input;
    ZSTD_outBuffer output;
    Py_buffer inBuffer;
    int finished;
    size_t chunkSize;
} ZstdCompressionChunker;

extern PyTypeObject ZstdCompressionChunkerType;

typedef enum {
    compressionchunker_mode_normal,
    compressionchunker_mode_flush,
    compressionchunker_mode_finish,
} CompressionChunkerMode;

typedef struct {
    PyObject_HEAD

        ZstdCompressionChunker *chunker;
    CompressionChunkerMode mode;
} ZstdCompressionChunkerIterator;

extern PyTypeObject ZstdCompressionChunkerIteratorType;

typedef struct {
    PyObject_HEAD

        ZSTD_DCtx *dctx;
    ZstdCompressionDict *dict;
    size_t maxWindowSize;
    ZSTD_format_e format;
} ZstdDecompressor;

extern PyTypeObject ZstdDecompressorType;

typedef struct {
    PyObject_HEAD

        ZstdDecompressor *decompressor;
    size_t outSize;
    int finished;
    PyObject *unused_data;
} ZstdDecompressionObj;

extern PyTypeObject ZstdDecompressionObjType;

typedef struct {
    PyObject_HEAD

        /* Parent decompressor to which this object is associated. */
        ZstdDecompressor *decompressor;
    /* Object to read() from (if reading from a stream). */
    PyObject *reader;
    /* Size for read() operations on reader. */
    size_t readSize;
    /* Whether a read() can return data spanning multiple zstd frames. */
    int readAcrossFrames;
    /* Buffer to read from (if reading from a buffer). */
    Py_buffer buffer;
    /* Whether to close the inner object on close() */
    int closefd;

    /* Whether the context manager is active. */
    int entered;
    /* Whether we've closed the stream. */
    char closed;

    /* Number of bytes decompressed and returned to user. */
    unsigned long long bytesDecompressed;

    /* Tracks data going into decompressor. */
    ZSTD_inBuffer input;

    /* Holds output from read() operation on reader. */
    PyObject *readResult;

    /* Whether all input has been sent to the decompressor. */
    int finishedInput;
    /* Whether all output has been flushed from the decompressor. */
    int finishedOutput;
} ZstdDecompressionReader;

extern PyTypeObject ZstdDecompressionReaderType;

typedef struct {
    PyObject_HEAD

        ZstdDecompressor *decompressor;
    PyObject *writer;
    size_t outSize;
    int entered;
    int closing;
    char closed;
    int writeReturnRead;
    int closefd;
} ZstdDecompressionWriter;

extern PyTypeObject ZstdDecompressionWriterType;

typedef struct {
    PyObject_HEAD

        ZstdDecompressor *decompressor;
    PyObject *reader;
    Py_buffer buffer;
    Py_ssize_t bufferOffset;
    size_t inSize;
    size_t outSize;
    size_t skipBytes;
    ZSTD_inBuffer input;
    ZSTD_outBuffer output;
    Py_ssize_t readCount;
    int finishedInput;
    int finishedOutput;
} ZstdDecompressorIterator;

extern PyTypeObject ZstdDecompressorIteratorType;

typedef struct {
    int errored;
    PyObject *chunk;
} DecompressorIteratorResult;

typedef struct {
    /* The public API is that these are 64-bit unsigned integers. So these can't
     * be size_t, even though values larger than SIZE_MAX or PY_SSIZE_T_MAX may
     * be nonsensical for this platform. */
    unsigned long long offset;
    unsigned long long length;
} BufferSegment;

typedef struct {
    PyObject_HEAD

        PyObject *parent;
    BufferSegment *segments;
    Py_ssize_t segmentCount;
} ZstdBufferSegments;

extern PyTypeObject ZstdBufferSegmentsType;

typedef struct {
    PyObject_HEAD

        PyObject *parent;
    void *data;
    Py_ssize_t dataSize;
    unsigned long long offset;
} ZstdBufferSegment;

extern PyTypeObject ZstdBufferSegmentType;

typedef struct {
    PyObject_HEAD

        Py_buffer parent;
    void *data;
    unsigned long long dataSize;
    BufferSegment *segments;
    Py_ssize_t segmentCount;
    int useFree;
} ZstdBufferWithSegments;

extern PyTypeObject ZstdBufferWithSegmentsType;

/**
 * An ordered collection of BufferWithSegments exposed as a squashed collection.
 *
 * This type provides a virtual view spanning multiple BufferWithSegments
 * instances. It allows multiple instances to be "chained" together and
 * exposed as a single collection. e.g. if there are 2 buffers holding
 * 10 segments each, then o[14] will access the 5th segment in the 2nd buffer.
 */
typedef struct {
    PyObject_HEAD

        /* An array of buffers that should be exposed through this instance. */
        ZstdBufferWithSegments **buffers;
    /* Number of elements in buffers array. */
    Py_ssize_t bufferCount;
    /* Array of first offset in each buffer instance. 0th entry corresponds
       to number of elements in the 0th buffer. 1st entry corresponds to the
       sum of elements in 0th and 1st buffers. */
    Py_ssize_t *firstElements;
} ZstdBufferWithSegmentsCollection;

extern PyTypeObject ZstdBufferWithSegmentsCollectionType;

int set_parameter(ZSTD_CCtx_params *params, ZSTD_cParameter param, int value);
int set_parameters(ZSTD_CCtx_params *params,
                   ZstdCompressionParametersObject *obj);
int to_cparams(ZstdCompressionParametersObject *params,
               ZSTD_compressionParameters *cparams);
FrameParametersObject *get_frame_parameters(PyObject *self, PyObject *args,
                                            PyObject *kwargs);
int ensure_ddict(ZstdCompressionDict *dict);
int ensure_dctx(ZstdDecompressor *decompressor, int loadDict);
ZstdCompressionDict *train_dictionary(PyObject *self, PyObject *args,
                                      PyObject *kwargs);
ZstdBufferWithSegments *
BufferWithSegments_FromMemory(void *data, unsigned long long dataSize,
                              BufferSegment *segments, Py_ssize_t segmentsSize);
Py_ssize_t
BufferWithSegmentsCollection_length(ZstdBufferWithSegmentsCollection *);
int cpu_count(void);
size_t roundpow2(size_t);
int safe_pybytes_resize(PyObject **obj, Py_ssize_t size);
void set_io_unsupported_operation(void);

#endif


text:
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include "epoll_wrapper.h"
#include "tee_logging.h"

static int epollfd;

static int wrap_epoll_ctl(int fd, struct epoll_event *event, int op)
{
	if (epoll_ctl(epollfd, op, fd, event)) {
		OT_LOG(LOG_ERR, "Failed on epoll_ctl operation: 0x%x: %s", op, strerror(errno));
		return -1;
	}

	return 0;
}

int init_epoll()
{
	epollfd = epoll_create(10);
	if (epollfd < 0) {
		OT_LOG(LOG_ERR, "Failed to create epoll fd: %s", strerror(errno));
		return -1;
	}

	return 0;
}

int epoll_reg_fd(int fd, uint32_t events)
{
	struct epoll_event event = {0};

	event.events = events;
	event.data.fd = fd;

	return wrap_epoll_ctl(fd, &event, EPOLL_CTL_ADD);
}

int epoll_reg_data(int fd, uint32_t events, void *data)
{
	struct epoll_event event = {0};

	event.events = events;
	event.data.ptr = data;

	return wrap_epoll_ctl(fd, &event, EPOLL_CTL_ADD);
}

int epoll_unreg(int fd)
{
	struct epoll_event event = {0};
	event.events = EPOLLIN;

	return wrap_epoll_ctl(fd, &event, EPOLL_CTL_DEL);
}

int wrap_epoll_wait(struct epoll_event *events, int max_events)
{
	return epoll_wait(epollfd, events, max_events, -1);
}

void cleanup_epoll()
{
	close(epollfd);
}

redpajama_set_name: RedPajamaGithub


text:
/** @file
    @brief Internal API to locate the current OSVR Server on the file system.

    @date 2016

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

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

#ifndef INCLUDED_LocateServer_h_GUID_7D10F12E_2A83_48BB_7581_ED7A7F5188AC
#define INCLUDED_LocateServer_h_GUID_7D10F12E_2A83_48BB_7581_ED7A7F5188AC

// Internal Includes
#include <osvr/Util/GetEnvironmentVariable.h>
#include <osvr/Util/PlatformConfig.h>

// Library/third-party includes
// - none

// Standard includes
#include <string>

namespace osvr {
    namespace client {

        /** @brief INTERNAL ONLY - get the current server directory, if available. */
        inline boost::optional<std::string> getServerBinaryDirectoryPath() {
            auto server = osvr::util::getEnvironmentVariable("OSVR_SERVER_ROOT");
            if (!server || server->empty()) {
                return server;
            }
            const char lastChar = server->back();
            if (lastChar == '/' || lastChar == '\\') {
                server->pop_back();
            }
            return server;
        }

        /** @brief INTERNAL ONLY - get the path to the server executable, if available. */
        inline boost::optional<std::string> getServerBinaryPath() {
            const auto binPath = getServerBinaryDirectoryPath();
            if (binPath) {
#if defined(OSVR_WINDOWS)
                static const std::string pathExtension = ".exe";
                static const std::string pathSep = "\\";
#else
                static const std::string pathExtension = "";
                static const std::string pathSep = "/";
#endif
                return *binPath + pathSep + "osvr_server" + pathExtension;
            }
            return boost::none;
        }

        /** @brief INTERNAL ONLY - get the path to the server launcher executable, if available. */
        inline boost::optional<std::string> getServerLauncherBinaryPath() {
            return getServerBinaryPath();
        }
    }
}

#endif // INCLUDED_LocateServer_h_GUID_7D10F12E_2A83_48BB_7581_ED7A7F5188AC


text:
#pragma once

#include <pal/SessionID.h>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

class ScriptExecutionContext;
class SocketStreamHandle;
class SocketStreamHandleClient;
class URL;

class WEBCORE_EXPORT SocketProvider : public ThreadSafeRefCounted<SocketProvider> {
public:
    static Ref<SocketProvider> create() { return adoptRef(*new SocketProvider); }
    virtual Ref<SocketStreamHandle> createSocketStreamHandle(const URL&, SocketStreamHandleClient&, PAL::SessionID, const String& credentialPartition);
    virtual ~SocketProvider() { };
};

}


text:
package org.hawkular.inventory.base.spi;

import org.hawkular.inventory.api.model.StructuredData;
import org.hawkular.inventory.paths.RelativePath;

/**
 * This is essentially a marker class to distinguish a fully loaded structured data from the "bare" shallow variant that
 * doesn't contain the potential children (see for example
 * {@link org.hawkular.inventory.api.Data.Single#flatData(RelativePath)}).
 *
 * <p>When calling {@link InventoryBackend#convert(Object, Class)}, with {@link StructuredData}, the whole structured
 * data is loaded. On the other hand calling it with {@code ShallowStructuredData} will make the convert method not load
 * the potential children of the structured data.
 *
 * @author Lukas Krejci
 * @since 0.3.0
 */
public final class ShallowStructuredData {

    private final StructuredData data;

    public ShallowStructuredData(StructuredData data) {
        this.data = data;
    }

    public StructuredData getData() {
        return data;
    }
}


text:
import pecan

from tuskar.api.controllers.v2.plans import PlansController
from tuskar.api.controllers.v2.roles import RolesController

class Controller(object):
    """Version 2 API controller root."""

    plans = PlansController()
    roles = RolesController()

    @pecan.expose('json')
    def index(self):
        return {
            'version': {
                'status': 'development',
                'media-types': [{'base': 'application/json'}],
                'id': 'v2.0',
                'links': [{
                    'href': '/v2/',
                    'rel': 'self',
                }]
            }
        }


text:
angular.module('app')
  .controller('AppController', function () {
  });


text:
/**
 * @description
 *  Assertion with the period values
 *  Should pass!
 *
 * @export
 */
export default function (): void;


text:
/* tslint:disable:max-line-length */
import * as React from 'react';
import SvgIcon from "./SvgIcon";

interface Pallet {
  primary: string;
}

class Cancel extends SvgIcon {
  public displayName: string = 'Cancel';
  public group(style: any, pallet: Pallet): JSX.Element {
    return (
      <g>
        <path d="M 1 1, L 23 23" stroke={pallet.primary} fill="transparent" strokeWidth="3" />
        <path d="M 1 23, L 23 1" stroke={pallet.primary} fill="transparent" strokeWidth="3" />
      </g>
    );
  }
  public render() {
    const pallet: Pallet = {
      primary: this.props.pallet.primary || this.context.muiTheme.icon.color,
    };
    const style = {
      ...this.styles,
      ...this.context.muiTheme.icon,
      ...this.props.style,
    };
    return this.svg(this.group(style, pallet), this.props.className, style, this.props.viewBox, this.props.transform);
  }
}

export default Cancel;


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

namespace Len.Framework.Speed.Domain
{
    public interface IDomainRepository
    {
        //AggregateRoot GetById<TAggregateRootId>(Type aggregateRootType, TAggregateRootId id);

        //TAggregateRoot GetById<TAggregateRoot, TAggregateRootId>(TAggregateRootId id) where TAggregateRoot : AggregateRoot;

        //void Save(AggregateRoot aggregate);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"

    android:padding="6dip">
    <!-- TaskObject Name -->
    <TextView
        android:id="@+id/nametext"

        android:layout_width="wrap_content"
        android:layout_height="26dip"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textStyle="bold"
        android:textColor="#fff"/>

    <!-- Actual TaskObject Name Data -->
    <TextView
        android:id="@+id/namedata"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/nametext"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textColor="#95a0ae"/>

    <!-- Description Tag -->
    <TextView
        android:id="@+id/detailstext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/nametext"
        android:singleLine="false"
        android:textStyle="bold"
        android:textColor="#95a0ae"/>
    <!-- This is the actual description -->
    <TextView
        android:id="@+id/detailsdata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_below="@id/detailstext"
        android:singleLine="false"
        android:textColor="#95a0ae"/>
</RelativeLayout>


text:
        <md-content layout-padding>
            <md-whiteframe class="md-whiteframe-z2 md-whiteframe-background" layout="column">

Change password

                <md-divider></md-divider>

                <form name="userForm" data-ng-submit="changeUserPassword()" class="signin form-horizontal" autocomplete="off">
                    <fieldset>

                            <md-input-container flex>
                                <md-icon>
                                    vpn_key
                                </md-icon>
                                <input type="password" required id="currentPassword" name="currentPassword" data-ng-model="passwordDetails.currentPassword" placeholder="Current Password">
                            </md-input-container>
                            <md-input-container flex>
                                <md-icon>
                                    vpn_key
                                </md-icon>
                                <input type="password" required id="newPassword" name="newPassword" data-ng-model="passwordDetails.newPassword" placeholder="New Password">
                            </md-input-container>

                            <md-input-container flex>
                                <md-icon>
                                    vpn_key
                                </md-icon>
                                <input type="password" required id="verifyPassword" name="verifyPassword" data-ng-model="passwordDetails.verifyPassword" placeholder="Repeat Password">
                            </md-input-container>

Passwords don't match.

                            <button type="submit" class="md-button md-raised md-primary">change password</button> Or
                    Cancel

                        Password Changed Successfully

                    </fieldset>
                </form>
            </md-whiteframe>
        </md-content>


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./components/Modal/index"));
var index_1 = require("./components/Modal/index");
exports.default = index_1.Modal;

//# sourceMappingURL=Modal.js.map


text:
[![Build Status](https://img.shields.io/travis/com/tidepool-org/blip.svg)](https://travis-ci.com/tidepool-org/blip)

Blip is a web app for type 1 diabetes (T1D) built on top of the [Tidepool](http://tidepool.org/) platform. It allows patients and their "care team" (family, doctors) to visualize their diabetes device data (from insulin pumps, BGMs, and/or CGMs) and message each other.

This README is focused on just the details of getting blip running locally. For more detailed information aimed at those working on the development of blip, please see the [developer guide](docs/StartHere.md).

* * * * *

### Table of contents

- [Before you start](#beforeyoustart)
- [Install](#install)
- [Running locally](#running-locally)
   - ["Verifying" the e-mail of a new account locally](#getting-past-e-mail-verification-for-a-user-created-locally)
   - [Creating a special account to bypass e-mail verification](#creating-a-user-without-email-verification)
- [Running against `dev`](#running-against-dev)
- [Config](#config)
- [Debugging](#debugging)
- [Running the tests](#running-the-tests)
- [Build and deployment](#build-and-deployment)

* * * * *

## Before you start

If this is the first time you're looking at Tidepool locally start with the [tidepool-org/development](https://github.com/tidepool-org/development) repository to setup before continuing here.

## Install

Requirements:

- [Node.js](http://nodejs.org/ 'Node.js') version 6.x
- [npm](https://www.npmjs.com/ 'npm') version 4.x or higher

Clone this repo [from GitHub](https://github.com/tidepool-org/blip 'GitHub: blip'), then install the dependencies:

After cloning this repository to your local machine, first make sure that you have node `6.x` and npm `4.x` installed. If you have a different major version of node installed, consider using [nvm](https://github.com/creationix/nvm 'GitHub: Node Version Manager') to manage and switch between multiple node (& npm) installations. If you have npm `3.x` installed (as it is by default with node `6.x`), then you can update to the latest npm `4.x` with `npm install -g npm@4`.

It's not an absolute requirement, but it is preferable to have [Yarn](https://yarnpkg.com 'Yarn') installed, as it provides dependency management features above and beyond what npm provides. Just follow [Yarn's installation instructions](https://yarnpkg.com/en/docs/install 'Yarn installation instructions') (hint: for Mac users with Homebrew installed, it's just `brew install yarn`).

Once your environment is setup with node `6.x` and npm `4.x` install the dependencies with Yarn:

```bash
$ yarn install
```

Or with npm if you're choosing not to use Yarn:

```bash
$ npm install
```

## Running locally

If you're running the entire Tidepool platform locally with docker as per [tidepool-org/development](https://github.com/tidepool-org/development/#starting), you can start blip using your local platform with:

```bash
$ docker-compose up -d
```

If you're running the entire Tidepool platform locally without docker, you can start blip using your local platform with:

```bash
$ source config/local.sh
$ npm start
```

Open your web browser and navigate to `http://localhost:3000/`.

(See also: [recipe for running blip locally with hot module replacement](http://developer.tidepool.io/docs/front-end/recipes.html#a-running-the-platform-locally-with-runservers-but-blip-with-hot-module-replacement-hmr-via-webpack 'Tidepool developer portal: front end recipes').)

The `npm start` command runs the Webpack dev server which includes hot module reloading (HMR) capabilities. Essentially changes within React components should be updated "hot" in your browser *without* a page refresh. Sometimes this doesn't work, but in such cases the dev console will include a message from the Webpack dev server indicating that you need to do a full refresh to see your changes.

### Redux dev tools

Blip includes several Redux developer tools: the original time-travel dev tools UI, a console action logger, and a mutation tracker for catching mutations to the state tree (which should be immutable). The last of these in particular is a performance killer (though *none* of them could even be said to have a *negligible* effect on performance). By default when running for local development with `npm start` (which means `NODE_ENV` is `development`), the `DEV_TOOLS` flag will be `true`, and all of these dev tools will be active. Because they affect performance profoundly, this may not always be desirable. To turn *off* the dev tools in development, kill the Webpack dev server (i.e, the `npm start` process), run `export DEV_TOOLS=false`, then start up blip again with `npm start`.

**NB:** Due to differences in the `development` versus `production` builds of React itself (most notably PropTypes validation), performance of the app whenever `NODE_ENV` is `development` will *never* be as good as it is in the production build under a `NODE_ENV` of `production`. If you're concerned about the performance of a particular feature, the only way to test with good fidelity is with the production build, which you can do locally according to [these instructions below](#testing-the-production-build-locally).

### Getting past e-mail verification for a user created locally

When running locally with `runservers` or with the [docker-based setup](https://github.com/tidepool-org/development), no e-mail will be sent to a sign-up e-mail address, and so a workaround is needed to get past the e-mail verification step for a newly created local account being used for development. What you need to do is construct the login URL that is provided in a link in the verification e-mail *manually* by finding the correct key for the e-mail confirmation.

If you're developing locally, you can find the key by looking in the local `server.log` (located at the root level of where you've cloned all the Tidepool repositories).

If you're developing with the docker setup, you can find the key in the logs of the `hydrophone` container. It will look something like
```
2018/06/07 16:17:17 Sending email confirmation to foo@bar.com with key aSuzGcwq4kPRyb6pwQnTcSKVTt_V6CtL
```
[Kitematic](https://kitematic.com/) is an easy-to-use tool for inspecting the logs of your docker containers. You can find the link to it's installer in Docker's menu.

You can also find the key in your Mongo database. The steps for the latter are:

- start a Mongo shell in a fresh Terminal window with `mongo`
- switch to the `confirm` database with `use confirm`
- find the pending account with `db.confirmations.find({status: 'pending'});`
- copy the `_id` from the pending confirmation record with an `email` matching the account you've just created

After you've found the key, you can provide it as a `signupKey` parameter in the login URL: `http://localhost:3000/login?signupKey=<key>`

### Creating a user without e-mail verification

When running locally, there is also workaround so you don't have to verify the e-mail address of a new user: if you create a new user and add the localhost secret +skip to the e-mail address - e.g. `me+skip@something.org` - this will then allow you to login straightaway, skipping the e-mail verification step.

**NB: The UI is *not* guaranteed to display correctly for +skip-created users on all pages, and so 💣 *THIS WORKFLOW IS NOT CURRENTLY RECOMMENDED* 💣. For now, you must create a normal account (without +skip) if you want to work on the sign-up flow, although we have plans to fix the way the +skip workaround operates on the platform to address this.**

## Running against `dev`

By default—that is, if you don't `source` a different configuration, such as the `local.sh` configuration for local development with runservers referenced above—if you simply run `npm start` in this repository after installing the dependencies, blip will start up running against Tidepool's "dev" server environment.

## Config

Configuration values are set with environment variables (see `config/local.sh`).

You can set environment variables manually using `export VAR=value`, or use a bash script. For example:

```bash
$ source config/local.sh
```

Ask the project owners to provide you with config scripts for different environments, or you can create one of your own if you have a custom environment. It is recommended to put all config scripts in the `config/` directory, where they will be ignored by Git.

## Debugging

The app uses the [bows](http://latentflip.com/bows/) library to log debugging messages to the browser's console. It is disabled by default (which makes it production-friendly). To see the messages type `localStorage.debug = true` in the browser console and refresh the page. Create a logger for a particular app module by giving it a name, such as:

```javascript
app.foo = {
  log: bows('Foo'),
  bar: function() {
    this.log('Walked into a bar');
  }
};
```

## Running the tests

We use [Mocha](https://mochajs.org/) with [Chai](http://chaijs.com/) for our test framework inside [Karma](https://karma-runner.github.io/) as our test runner, as well as [Sinon.JS](http://sinonjs.org/) and [Sinon-Chai](https://github.com/domenic/sinon-chai) for spies and stubs. Our tests currently run on [PhantomJS](http://phantomjs.org/), a headless WebKit browser, or Chrome (locally only).

To run the unit tests, use:

```bash
$ npm test
```

To run the unit tests in Chrome, use:

```bash
$ npm run browser-tests
```

To run the unit tests in watch mode, use:

```bash
$ npm run test-watch
```

## Build and deployment

The app is built as a static site in the `dist/` directory.

We use [Shio](https://github.com/tidepool-org/shio) to deploy, so we separate the build in two.

Shio's `build.sh` script will take care of building the app itself with:

```bash
$ npm run build-app
```

Shio's `start.sh` script then builds the config from environment variables as a separate file with:

```bash
$ source config/env.sh
$ npm run build-config
```

After that, the app is ready to be served using the static web server included in this repo:

```bash
$ npm run server
```

### Testing the production build locally

You can also build everything at once locally to test the production build by simply running:

```bash
$ source config/local.sh
$ npm run build
$ npm run server
```


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.tienganhthatde.chat" version="2.4" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" android-versionCode="8">
	<name>Chat English</name>
	<description>Chat với người lạ by English. Hỗ trợ việc luyện tập giao tiếp Tiếng Anh.
Sản phẩm của Tiếng Anh Thật Dễ.
Fb: https://www.facebook.com/tienganhthatde
Web: http://tienganhthatde.com
WebApp: http://tienganhthatde.com/chat/
	</description>
	<author href="http://tienganhthatde.com" email="s@swind.vn">
		sWind Technology and Media .Ltd;
	</author>
	<content src="index.html" />
	<access origin="*" />

	<preference name="DisallowOverscroll" value="true" />
	<preference name="fullscreen" value="false" />
	<preference name="webviewbounce" value="true" />
	<preference name="stay-in-webview" value="true" />

	<preference name="BackupWebStorage" value="none" />

	<platform name="ios">
		<!-- iOS 7.0+ -->
		<!-- iPhone / iPod Touch  -->
		<icon src="res/ios/icon-60.png" width="60" height="60" />
		<icon src="res/ios/icon-60@2x.png" width="120" height="120" />
		<!-- iPad -->
		<icon src="res/ios/icon-76.png" width="76" height="76" />
		<icon src="res/ios/icon-76@2x.png" width="152" height="152" />
		<!-- iOS 6.1 -->
		<!-- Spotlight Icon -->
		<icon src="res/ios/icon-40.png" width="40" height="40" />
		<icon src="res/ios/icon-40@2x.png" width="80" height="80" />
		<!-- iPhone / iPod Touch -->
		<icon src="res/ios/icon.png" width="57" height="57" />
		<icon src="res/ios/icon@2x.png" width="114" height="114" />
		<!-- iPad -->
		<icon src="res/ios/icon-72.png" width="72" height="72" />
		<icon src="res/ios/icon-72@2x.png" width="144" height="144" />
		<!-- iPhone Spotlight and Settings Icon -->
		<icon src="res/ios/icon-small.png" width="29" height="29" />
		<icon src="res/ios/icon-small@2x.png" width="58" height="58" />
		<!-- iPad Spotlight and Settings Icon -->
		<icon src="res/ios/icon-50.png" width="50" height="50" />
		<icon src="res/ios/icon-50@2x.png" width="100" height="100" />
	   </platform>

	<!--

	<icon src="www/icon.png"/>

	<icon src="www/images/res-android/drawable-ldpi/icon.png" platform="android" density="ldpi"/>
	<icon src="www/images/res-android/drawable-mdpi/icon.png" platform="android" density="mdpi"/>
	<icon src="www/images/res-android/drawable-hdpi/icon.png" platform="android" density="hdpi"/>
	<icon src="www/images/res-android/drawable-xhdpi/icon.png" platform="android" density="xhdpi"/>

	-->

	<!--
	<preference name="DisallowOverscroll" value="true" />
	<preference name="fullscreen" value="false" />
	<preference name="webviewbounce" value="true" />
	<preference name="stay-in-webview" value="yes" />

	<gap:plugin name="com.phonegap.plugins.facebookconnect" version="0.4.0">
		<param name="APP_ID" value="1449890398617312" />
		<param name="APP_NAME" value="Chat với người lạ by English" />
	</gap:plugin>
	<gap:plugin name="com.ququplay.websocket.websocket" version="0.1.0" />
	<gap:plugin name="com.ionic.keyboard" version="1.0.2" />
	<gap:plugin name="org.apache.cordova.device" version="0.2.8" />
	<gap:plugin name="org.apache.cordova.inappbrowser" version="0.2.4" />
	-->

</widget>


text:
from copy import copy
from collections import OrderedDict

import numpy as np
import pandas as pd
from sklearn.metrics import average_precision_score, auc, roc_auc_score
from sklearn.metrics import precision_recall_curve
from sklearn.linear_model import LogisticRegressionCV
from sklearn.cross_validation import StratifiedShuffleSplit
import matplotlib.pyplot as plt
import matplotlib
from IPython.display import display, HTML
matplotlib.style.use('../../src/roam.mplstyle')

def generate_data_and_constant_predictions(n, frac_positive):
    """
    Generates data in a fixed positive:negative ratio, and returns the
    data and scores from a dummy model that predicts 0.5 for all examples.

    Parameters
    ----------
    n : int
        Number of examples

    frac_positive : float
        Fraction of the examples that are positive

    Returns
    -------
    observations : list
        Consisting of (frac_positive * n) 1s, and (n - (frac_positive * n)) 0s

    constant_predictions : list
        Same length as observations
    """
    n_positive = int(frac_positive * n)
    n_negative = n - n_positive
    observations = [1 for _ in range(n_positive)] + \
                   [0 for _ in range(n_negative)]
    constant_predictions = [0.5 for _ in range(n_positive + n_negative)]
    return observations, constant_predictions

def plot_recall_precision_from_predictions(true, scores, **kwargs):
    """
    Computes precision and recall from some observations and scores assigned
    to them, and plots a precision-recall curve.

    Parameters
    ----------
    true : list
        Must be binary (i.e. 1s and 0s).

    scores : list
        Consisting of floats.

    kwargs : optional
        See plot_axes.

    """
    p, r, thresholds = precision_recall_curve(true, scores)
    plot_recall_precision(p, r, **kwargs)

def plot_recall_precision(p, r, **kwargs):
    """
    Plots a precision-recall graph from a series of operating points.

    Parameters
    ----------
    p : list
        Precision.

    r : recall
        Recall.

    kwargs : optional
        See plot_axes.

    Returns
    -------

    """
    fig, ax = plt.subplots(1, 1, figsize=(7, 4))
    plot_axes(ax, p, r, legend_text='IAP', **kwargs)
    plt.show()

def plot_axes(
        ax, y, x,
        interpolation=None,
        marker_size=30,
        title=None,
        legend_text='Area'):
    """
    Plots a graph on axes provided.

    Parameters
    ----------
    ax : matplotlib axes

    y : list

    x : list

    interpolation : None (default) or string ['linear', 'step']

    marker_size : float (default: 30)

    title : None or string

    legend_text : string (default: 'Area')
        Text to include on the legend before showing the area. Only used
        if interpolation is not None.
    """
    ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False)
    # Show first and last points more visably
    ax.scatter([x[i] for i in [0, -1]], [y[i] for i in [0, -1]],
               marker='x', linewidths=2, s=100, clip_on=False)
    ax.set_xlim((-0.05, 1.05))
    ax.set_ylim((-0.08, 1.08))
    ax.set_xlabel('Recall')
    ax.set_ylabel('Precision')
    if title is not None:
        ax.set_title(title, fontsize=20)
    if interpolation is not None:
        if interpolation == 'linear':
            ax.plot(x, y)
            area = auc(x, y)
            ax.fill_between(x, 0, y, alpha=0.2,
                            label='{} = {:5.4f}'.format(legend_text, area))
            leg = ax.legend()
            leg.get_frame().set_linewidth(0.0)
        elif interpolation == 'step':
            p_long = [v for v in y for _ in (0, 1)][:-1]
            r_long = [v for v in x for _ in (0, 1)][1:]
            ax.plot(r_long, p_long)
            area = auc_using_step(x, y)
            ax.fill_between(r_long, 0, p_long, alpha=0.2,
                            label='{} = {:5.4f}'.format(legend_text, area))
            leg = ax.legend()
            leg.get_frame().set_linewidth(0.0)
        else:
            print("Interpolation value of '{}' not recognised. "
                  "Choose from 'linear', 'quadrature'.".format(interpolation))

def compare_recall_precisions_from_predictions(true, score_dict, **kwargs):
    """
    Show two graphs side-by-side for two different sets of scores, against the
    same true observations.

    Parameters
    ----------
    true : list

    score_dict : dict
        Consisting of `{name: scores}` where `name` is a string and
        `scores` is a list of floats.

    kwargs : optional
        See plot_axes.
    """
    pr = OrderedDict()
    for name, score in score_dict.items():
        p, r, threshold = precision_recall_curve(true, score)
        pr[name] = [p, r]
    compare_recall_precision_graph(pr, **kwargs)

def compare_recall_precision_graph(pr_dict, title=None, **kwargs):
    """

    Parameters
    ----------
    pr_dict : dict
        Consisting of `{name: pr}` where `name` is a string and
        `pr` is a tuple of precision and recall values.

    title : string

    kwargs : optional
        See plot_axes.
    """
    fig, ax = plt.subplots(1, 2, figsize=(15, 4))
    for side, (name, [p, r]) in enumerate(pr_dict.items()):
        plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs)
    if title is not None:
        fig.suptitle(title, fontsize=20, y=1.05)
    plt.show()

def operating_points(ranking):
    """
    Computes lists of precision and recall from an ordered list of observations.

    Parameters
    ----------
    ranking : list
        Entries should be binary (0 or 1) and in descending order
        (i.e. top-ranked is first).

    Returns
    -------
    precision : list

    recall : list
    """
    precision, recall = list(), list()
    for pos in range(len(ranking)):
        p, r = precision_recall_from_ranking(ranking, pos)
        precision.append(p)
        recall.append(r)
    return precision, recall

def precision_recall_from_ranking(ranking, position):
    """
    Computes the precision and recall of a particular assignment of labelled
    observations to a positive and negative class, where the positive class
    comes first in the list, and the negative class comes second, and the
    split point is specified.

    Parameters
    ----------
    ranking : list
        Ordered list of binary observations.

    position : int
        Position to split the list into positive and negative.

    Returns
    -------
    precision : float

    recall : float
    """
    if position == 0:
        precision = 1.0
        recall = 0.0
    else:
        ranking = np.array(ranking)
        precision = (ranking[:position] == 1).sum() / position
        recall = (ranking[:position] == 1).sum() / (ranking == 1).sum()
    return precision, recall

def auc_using_step(recall, precision):
    return sum([(recall[i] - recall[i+1]) * precision[i]
                for i in range(len(recall) - 1)])

def roam_average_precision(y_true, y_score, sample_weight=None):
    precision, recall, thresholds = precision_recall_curve(
        y_true, y_score, sample_weight=sample_weight)
    return auc_using_step(recall, precision)

def generate_positive_semi_definite_matrix(n_dim):
    """
    Creates a positive semi-definite matrix.

    Parameters
    ----------
    n_dim : int

    Returns
    -------
    np.array : (n_dim, n_dim)
    """
    cov = np.random.randn(n_dim, n_dim)
    return np.dot(cov, cov.T)

def subsample(X, y, frac_positive):
    """
    Subsamples a feature matrix and target vector to ensure that a specified
    fraction of the target values are positive.

    Parameters
    ----------
    X : np.array (n, m)

    y : np.array (n, )

    frac_positive : float

    Returns
    -------
    X : np.array (n', m)
        Some subset of the rows of the input X (i.e. n' <= n)

    y : np.array (n', )
        Some subset of the rows of the input y (i.e. n' <= n)
    """
    positive_idx = np.arange(len(y))[y == 1]
    negative_idx = np.arange(len(y))[y == 0]
    num_positive = int(frac_positive * len(negative_idx))
    positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False)
    indices_to_use = np.concatenate([positive_idx, negative_idx])
    np.random.shuffle(indices_to_use)
    return X[indices_to_use], y[indices_to_use]

def generate_continuous_data_and_targets(
        n_dim,
        n_samples,
        mixing_factor=0.025,
        frac_positive=0.1):
    """
    Generates a multivariate Gaussian-distributed dataset and a response
    variable that is conditioned on a weighted sum of the data.

    Parameters
    ----------
    n_dim : int

    n_samples : int

    mixing_factor : float
        'Squashes' the weighted sum into the linear regime of a sigmoid.
        Smaller numbers squash closer to 0.5.

    Returns
    -------
    X : np.array
        (n_samples, n_dim)

    y : np.array
        (n_samples, )
    """
    cov = generate_positive_semi_definite_matrix(n_dim)
    X = np.random.multivariate_normal(
            mean=np.zeros(n_dim),
            cov=cov,
            size=n_samples)
    weights = np.random.randn(n_dim)
    y_probs = sigmoid(mixing_factor * np.dot(X, weights))
    y = np.random.binomial(1, p=y_probs)
    X, y = subsample(X, y, frac_positive)
    return X, y

def sigmoid(x):
    """
    Computes sigmoid(x) for some activation x.

    Parameters
    ----------
    x : float

    Returns
    -------
    sigmoid(x) : float
    """
    return 1 / (1 + np.exp(-x))

def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05,
                             mixing_factor=0.025):
    """
    Generates some data and trains a logistic regression model.

    Parameters
    ----------
    n_dim : int
        Number of dimensions for the training data.

    n_samples : int
        Number of observations.

    frac_positive : float

    mixing_factor : float
        Numbers nearer to 0 make the task more challenging.

    Returns
    -------
    y : np.array (n_test, )
        True observed values in the test set.

    y_scores : np.array (n_test, )
        Model predictions of the test samples.

    roc_auc : float
        ROC AUC score on the test data
    """
    X, y = generate_continuous_data_and_targets(
            n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive,
            mixing_factor=mixing_factor)
    splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42)
    train_idx, test_idx = list(splits)[0]
    lr = LogisticRegressionCV()
    lr.fit(X[train_idx], y[train_idx])
    y_scores = lr.predict_proba(X[test_idx])[:, 1]
    roc_auc = roc_auc_score(y[test_idx], y_scores)
    return y[test_idx], y_scores, roc_auc


text:
<?php

namespace Petrol\Tests\files;

use Petrol\Core\Contracts\Filler;
use Petrol\Core\Database\Connection;

class FillerWrongVariables extends Filler
{
    /**
     * Database connection class.
     *
     * @var     Connection
     */
    protected $connection;

    /**
     * Database filling method.
     * If 'auto', Petrol will automatically insert one row every line.
     * If 'manual', you must call insertRow($data) on $this->connection to insert a row.
     *
     * @var     string  ['auto, 'manual']
     */
    protected $fill = 'auto';

    /**
     * The file to be parsed by parser class.
     * File must be in Petrol/src/Files.
     *
     * @var     string
     */
    protected $file = 'test';

     /**
     * The database table to be filled.
     *
     * @var     string
     */
    protected $table = 'test';

    /**
     * All database table columns except id.
     * Must exactly match database tables.
     * Database tables must include an auto incrementing id column.
     *
     * @var     array
     */
    protected $columns = [
        'name',
        'email',
        'address'
    ];

    /**
     * Variables to be called before loop begins.
     * These variables will be stored on the object and can be
     * accessed with $this->key.
     *
     * @var     array
     */
    protected $variables = 'test';

    /**
     * Construct.
     *
     * @param   Connection  $connection
     */
    public function __construct(Connection $connection)
    {
        $this->connection = $connection;

        parent::__construct();
    }

    /**
     * Parse the file.
     *
     * @param   string  $line  [individual lines from file]
     * @return  array  $data  [array of columns => values for line]
     */
    protected function parse($line)
    {
        $items = explode('/', $line);

        $trimmed_items = [];

        foreach ($items as $item) {
            array_push($trimmed_items, trim($item));
        }

        $data = array_combine($this->columns, $trimmed_items);

        return $data;
    }
}


text:
package io.sarl.eclipse.runtime;

/**
 * Exception in a SRE operation.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
public class SREException extends RuntimeException {

	private static final long serialVersionUID = 4435195594095001001L;

	/** Constructor.
	 * @param message error message.
	 */
	public SREException(String message) {
		super(message);
	}

	/** Constructor.
	 * @parma installation - the source of the exception.
	 * @param message error message.
	 * @param cause the cause of the error.
	 */
	public SREException(String message, Throwable cause) {
		super(message, cause);
	}

	/** Constructor.
	 * @parma installation - the source of the exception.
	 * @param cause the cause of the error.
	 */
	public SREException(Throwable cause) {
		super(cause);
	}

}


text:
Deface::Override.new(
  virtual_path: "spree/shared/_order_details",
  name: "replace_payment_info",
  insert_bottom: ".payment-info",
  partial: "spree/checkout/payment/order_details"
)


text:
module AmaValidators
  VERSION = "0.0.13"
end


text:
FactoryGirl.define do
  factory :post do
    author
    sequence :title do |n|
      n.to_s + Forgery(:lorem_ipsum).words(10, :random => true)
    end
    sequence :body do |n|
      n.to_s + Forgery(:lorem_ipsum).words(250, :random => true)
    end
    published true
  end
end


text:
class WorksheetsController < ApplicationController
  before_action :set_worksheet, only: [:show, :edit, :update, :destroy]

  # GET /worksheets
  # GET /worksheets.json
  def index
    @worksheets = Worksheet.all
  end

  # GET /worksheets/1
  # GET /worksheets/1.json
  def show
  end

  # GET /worksheets/new
  def new
    @worksheet = Worksheet.new
  end

  # GET /worksheets/1/edit
  def edit
  end

  # POST /worksheets
  # POST /worksheets.json
  def create
    @worksheet = Worksheet.new(worksheet_params)

    respond_to do |format|
      if @worksheet.save
        format.html { redirect_to @worksheet, notice: 'Worksheet was successfully created.' }
        format.json { render action: 'show', status: :created, location: @worksheet }
      else
        format.html { render action: 'new' }
        format.json { render json: @worksheet.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /worksheets/1
  # PATCH/PUT /worksheets/1.json
  def update
    respond_to do |format|
      if @worksheet.update(worksheet_params)
        format.html { redirect_to @worksheet, notice: 'Worksheet was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @worksheet.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /worksheets/1
  # DELETE /worksheets/1.json
  def destroy
    @worksheet.destroy
    respond_to do |format|
      format.html { redirect_to worksheets_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_worksheet
      @worksheet = Worksheet.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def worksheet_params
      params.require(:worksheet).permit(:primaryKey, :EST_KEY, :EST_LINE1, :EST_LINE2, :EST_LINE3, :EST_LINE4, :EST_AMT1, :EST_AMT2, :EST_AMT3, :EST_AMT4, :EST_RESOURCE1, :EST_RESOURCE2, :EST_RESOURCE3, :EST_RESOURCE4, :EST_RATE1, :EST_RATE2, :EST_RATE3, :EST_RATE4, :EST_HRS1, :EST_HRS2, :EST_HRS3, :EST_HRS4, :EST_JOB_NUM, :EST_COLUMN, :EST_TASK, :EST_MARKUP, :EST_REV, :EST_ADDED_BY, :EST_ADDED_WHEN, :EST_EDITED_BY, :EST_EDITED_WHEN)
    end
end


text:
CABALSANDBOX := ".cabal-sandbox"

.PHONY: bench clean haddock hpc init install repl run test

all: install hpc bench haddock run

bench: install
	cabal configure --enable-benchmarks
	cabal build
	cabal bench --benchmark-options="-o report.html"

clean:
	cabal clean
	if test -d .cabal-sandbox; then cabal sandbox delete; fi
	if test -d .hpc; then rm -r .hpc; fi

haddock:
	cabal configure
	cabal build
	cabal haddock --hyperlink-source
	# dist/doc/html/threase/index.html

hpc: test
	hpc report dist/hpc/tix/hspec/hspec.tix
	hpc markup --destdir=tmp dist/hpc/tix/hspec/hspec.tix
init:
	cabal update
	cabal sandbox init

install: init
	cabal install --enable-benchmarks --enable-tests --flags=documentation --only-dependencies

repl:
	cabal configure
	cabal build
	cabal repl

test: install
	cabal configure --enable-tests
	cabal build
	cabal test


text:
import logging
import os
import importlib
from json import dumps as jsonToString

#Google Imports
import webapp2
from google.appengine.ext.webapp import template

#Library Imports
from requests import codes

class Handler( webapp2.RequestHandler ):
	def get( self, **params ):
		self.exceptionWrapper( params, "get" )

	def post( self, **params ):
		self.exceptionWrapper( params, "post" )

	def delete( self, **params ):
		self.exceptionWrapper( params, "delete" )

	def exceptionWrapper( self, params, method ):
		try:
			self.common( params, method )
		except Exception as e:
			import traceback
			stack = traceback.format_exc()
			logging.error( "Error" )
			logging.error( "Params: " + str( params ) )
			logging.error( "Method: " + str( method ) )
			logging.error( stack )
			self.response.set_status( codes.internal_server_error )

	def common( self, params, method ):
		logging.debug( "Base Handler" )

		#Fetch config from derived class
		config = self.GetConfig()

		logging.debug( "Params: " + str( params ) )
		if "handler" in params:
			branch = None
			handlerConfig = config[ params[ "handler" ] ]
			if method in handlerConfig:
				methodConfig = handlerConfig[ method ]

				if "branch" in params and params[ "branch" ] in methodConfig:
					branch = methodConfig[ params[ "branch" ] ]
				elif "default" in methodConfig:
					branch = methodConfig[ "default" ]

			branch = self.ProcessBranch( branch )
			if branch is None:
				return

			# Import library
			lib = importlib.import_module( handlerConfig[ "lib" ] )

			# Create handler
			handler = lib.Handler( self.app, self.request )

			# Call branch
			getattr( handler, branch )( params )

			if isinstance( handler.response.data, basestring ):
				data = handler.response.data
			else:
				data = jsonToString( handler.response.data )

			self.response.set_status( handler.response.status )
			self.response.write( data )
		else:
			logging.warning( "Invalid handler or method" )
			self.response.set_status( codes.not_found )

	def ProcessBranch( self, branch ):
		if branch is None:
			logging.warning( "Invalid branch" )
			self.response.set_status( codes.not_found )
			return None

		elif isinstance( branch, dict ):
			if "out" in branch:
				out = branch[ "out" ]
				if "headers" in out:
					headers = out[ "headers" ]
					for key in headers:
						self.response.headers[ key ] = headers[ key ]
			return branch[ "func" ]
		return branch


text:
import { TestBed, inject, async, fakeAsync, tick} from '@angular/core/testing';
import { HttpModule, Http, BaseRequestOptions, RequestOptions, XHRBackend, Response, ResponseOptions, ConnectionBackend } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { RouteAdviceService } from './route-advice.service';

describe('RouteAdviceService', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [RouteAdviceService, {provide: XHRBackend, useClass: MockBackend}]
    });
  }));

  var start = '-73.5_40.0';
  var end = '139.5_35.0';

  it('should ...', inject([RouteAdviceService], (service: RouteAdviceService) => {
    expect(service).toBeTruthy();
  }));

  it('should get route advice', fakeAsync(inject([RouteAdviceService, XHRBackend], (service: RouteAdviceService, mockBackend) => {
    mockBackend.connections.subscribe((connection) => this.lastConnection = connection);
    let result: String[];
    service.getRouteAdvice(start, end).then((waypoints: String[]) => result = waypoints);
    this.lastConnection.mockRespond(new Response(new ResponseOptions({
      body: JSON.stringify({waypoints: ['1', '2']}),
    })));
    tick();
    expect(result).toEqual({waypoints: ['1', '2']})

  })))

});


text:
/**
 * 版本修订记录
 * 创建:2012-12-6
 * 版本:
 *
 * 修订1:  说明:
 * 修订2:  说明:
 */
package org.howsun.dao;

import java.util.ArrayList;
import java.util.List;

import org.howsun.util.Collections;

/**
 * 描述:
 * @author howsun
 * @version 3.0
 * Building Time 2012-12-6
 *
 */
public class RQLConditionbind {

	protected StringBuilder rql = new StringBuilder();

	protected List<Object> params = new ArrayList<Object>(0);

	public RQLConditionbind() {
		super();
	}

	public RQLConditionbind(StringBuilder rql, List<Object> params) {
		super();
		this.rql = rql;
		this.params = params;
	}

	public void addRQL(String rql){
		this.rql.append(rql);
	}

	public void addParam(Object param){
		this.params.add(param);
	}

	public StringBuilder getRql() {
		return rql;
	}

	public List<Object> getParams() {
		return params;
	}

	public String getCondition(){
		return getRql() != null ? (getRql().length() > 0 ? getRql().toString() : null) : null;
	}
	public Object[] getParams_(){
		return Collections.notEmpty(getParams()) ? getParams().toArray() : null;
	}

}


text:
<?php
/**
 * This example shows the implementation for a "change email"
 * command on a User entity. The command accepts a user id
 * and a new email address. The change is delegated to the
 * user object where the "DomainObjectChanged" event is raised.
 *
 * A listener picks up this event and displays the changed e-mail.
 */

namespace MyApp;

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

use LidskaSila\Glow\DomainEventProvider;
use LidskaSila\Glow\Bus\DirectCommandBus;
use LidskaSila\Glow\Bus\InMemoryEventMessageBus;
use LidskaSila\Glow\Bus\IdentityMap\SimpleIdentityMap;
use LidskaSila\Glow\Bus\IdentityMap\EventProviderQueue;
use LidskaSila\Glow\Bus\EventMessageHandlerFactory;
use LidskaSila\Glow\DefaultCommand;
use LidskaSila\Glow\DomainObjectChanged;

class User extends DomainEventProvider
{
    private $email = "old@beberlei.de";

    public function changeEmail($email)
    {
        $this->raise(new DomainObjectChanged("ChangeEmail", array("email" => $email, "oldEmail" => $this->email)));

        $this->email = $email;
    }
}

class ChangeEmailCommand extends DefaultCommand
{
    public $id;
    public $email;
}

class UserService
{
    private $map;
    private $users;

    public function __construct(SimpleIdentityMap $map)
    {
        $this->map = $map;
    }

    public function changeEmail(ChangeEmailCommand $command)
    {
        $user = $this->findUserById($command->id);
        $user->changeEmail($command->email);
    }

    private function findUserById($id)
    {
        if (!isset($this->users[$id])) {
            // here would normally be a database call or something
            $this->users[$id] = new User();
            $this->map->add($this->users[$id]);
        }
        return $this->users[$id];
    }
}

class MyEventHandler
{
    public function onChangeEmail(DomainObjectChanged $event)
    {
        echo "E-Mail changed from " . $event->oldEmail . " to " . $event->email . "\n";
    }
}

// 1. Setup the Library with InMemory Handlers
$messageBus  = new InMemoryEventMessageBus();
$identityMap = new SimpleIdentityMap();
$queue = new EventProviderQueue($identityMap);
$commandBus  = new DirectCommandBus(array(
    new EventMessageHandlerFactory($messageBus, $queue)
));

// 2. Register a command service and an event handler
$userService      = new UserService($identityMap);
$someEventHandler = new MyEventHandler();

$commandBus->register('MyApp\ChangeEmailCommand', $userService);
$messageBus->register($someEventHandler);

// 3. Invoke command!
$commandBus->handle(new ChangeEmailCommand(array('id' => 1234, 'email' => 'kontakt@beberlei.de')));
$commandBus->handle(new ChangeEmailCommand(array('id' => 1234, 'email' => 'info@beberlei.de')));


text:
package security

type Cipher interface {
	Encrypt(src string) (string, error)

	Decrypt(src string) (string, error)
}


text:
#include "ABI43_0_0ComponentDescriptorProviderRegistry.h"

namespace ABI43_0_0facebook {
namespace ABI43_0_0React {

void ComponentDescriptorProviderRegistry::add(
    ComponentDescriptorProvider provider) const {
  std::unique_lock<better::shared_mutex> lock(mutex_);

  /*
  // TODO: T57583139
  The assert is temporarily disabled to reduce the volume of the signal.
  assert(
      componentDescriptorProviders_.find(provider.handle) ==
          componentDescriptorProviders_.end() &&
      "Attempt to register an already registered ComponentDescriptorProvider.");
  */

  if (componentDescriptorProviders_.find(provider.handle) !=
      componentDescriptorProviders_.end()) {
    // Re-registering a provider makes no sense because it's copyable: already
    // registered one is as good as any new can be.
    return;
  }

  componentDescriptorProviders_.insert({provider.handle, provider});

  for (auto const &weakRegistry : componentDescriptorRegistries_) {
    auto registry = weakRegistry.lock();
    if (!registry) {
      continue;
    }

    registry->add(provider);
  }
}

void ComponentDescriptorProviderRegistry::setComponentDescriptorProviderRequest(
    ComponentDescriptorProviderRequest componentDescriptorProviderRequest)
    const {
  std::shared_lock<better::shared_mutex> lock(mutex_);
  componentDescriptorProviderRequest_ = componentDescriptorProviderRequest;
}

void ComponentDescriptorProviderRegistry::request(
    ComponentName componentName) const {
  ComponentDescriptorProviderRequest componentDescriptorProviderRequest;

  {
    std::shared_lock<better::shared_mutex> lock(mutex_);
    componentDescriptorProviderRequest = componentDescriptorProviderRequest_;
  }

  if (componentDescriptorProviderRequest) {
    componentDescriptorProviderRequest(componentName);
  }
}

ComponentDescriptorRegistry::Shared
ComponentDescriptorProviderRegistry::createComponentDescriptorRegistry(
    ComponentDescriptorParameters const &parameters) const {
  std::shared_lock<better::shared_mutex> lock(mutex_);

  auto registry =
      std::make_shared<ComponentDescriptorRegistry const>(parameters, *this);

  for (auto const &pair : componentDescriptorProviders_) {
    registry->add(pair.second);
  }

  componentDescriptorRegistries_.push_back(registry);

  return registry;
}

} // namespace ABI43_0_0React
} // namespace ABI43_0_0facebook


text:
set names utf8;
CREATE TABLE t (s1 STRING COLLATE utf8_en_cs, s2 STRING COLLATE utf8_tr_cs);
insert into t values('i','h');
insert into t values('a','A');
SELECT s1, s2 FROM t WHERE s1 > s2 + 'abc';
drop table t;
CREATE TABLE t (s1 STRING COLLATE utf8_en_cs, s2 STRING COLLATE utf8_tr_cs, s3 STRING COLLATE utf8_en_ci);
insert into t values('i','h','g');
SELECT s1, s2 FROM t WHERE s1 > s2 + s3;
drop table t;
set names iso88591;
commit;
--+ holdcas off;


text:
package org.apache.flink.test.accumulators;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.accumulators.Accumulator;
import org.apache.flink.api.common.accumulators.DoubleCounter;
import org.apache.flink.api.common.accumulators.LongCounter;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.test.util.MiniClusterWithClientResource;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.TestLogger;

import org.junit.ClassRule;
import org.junit.Test;

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

/**
 * Tests cases where accumulators:
 *  a) throw errors during runtime
 *  b) are not compatible with existing accumulator.
 */
public class AccumulatorErrorITCase extends TestLogger {
	private static final String FAULTY_CLONE_ACCUMULATOR = "faulty-clone";
	private static final String FAULTY_MERGE_ACCUMULATOR = "faulty-merge";
	private static final String INCOMPATIBLE_ACCUMULATORS_NAME = "incompatible-accumulators";

	@ClassRule
	public static final MiniClusterWithClientResource MINI_CLUSTER_RESOURCE = new MiniClusterWithClientResource(
		new MiniClusterResourceConfiguration.Builder()
			.setNumberTaskManagers(2)
			.setNumberSlotsPerTaskManager(3)
			.build());

	public static Configuration getConfiguration() {
		Configuration config = new Configuration();
		config.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "12m");
		return config;
	}

	@Test
	public void testFaultyAccumulator() throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		env.getConfig().disableSysoutLogging();

		// Test Exception forwarding with faulty Accumulator implementation
		env.generateSequence(0, 10000)
			.map(new FaultyAccumulatorUsingMapper())
			.output(new DiscardingOutputFormat<>());

		assertAccumulatorsShouldFail(env.execute());
	}

	@Test
	public void testInvalidTypeAccumulator() throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		env.getConfig().disableSysoutLogging();

		// Test Exception forwarding with faulty Accumulator implementation
		env.generateSequence(0, 10000)
			.map(new IncompatibleAccumulatorTypesMapper())
			.map(new IncompatibleAccumulatorTypesMapper2())
			.output(new DiscardingOutputFormat<>());

		try {
			env.execute();
			fail("Should have failed.");
		} catch (JobExecutionException e) {
			assertTrue("Root cause should be:",
					e.getCause() instanceof Exception);
			assertTrue("Root cause should be:",
					e.getCause().getCause() instanceof UnsupportedOperationException);
		}
	}

	@Test
	public void testFaultyMergeAccumulator() throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		env.getConfig().disableSysoutLogging();

		// Test Exception forwarding with faulty Accumulator implementation
		env.generateSequence(0, 10000)
			.map(new FaultyMergeAccumulatorUsingMapper())
			.output(new DiscardingOutputFormat<>());

		assertAccumulatorsShouldFail(env.execute());
	}

	/* testFaultyAccumulator */

	private static class FaultyAccumulatorUsingMapper extends RichMapFunction<Long, Long> {
		private static final long serialVersionUID = 42;

		@Override
		public void open(Configuration parameters) throws Exception {
			getRuntimeContext().addAccumulator(FAULTY_CLONE_ACCUMULATOR, new FaultyCloneAccumulator());
		}

		@Override
		public Long map(Long value) throws Exception {
			return -1L;
		}
	}

	private static class FaultyCloneAccumulator extends LongCounter {
		private static final long serialVersionUID = 42;

		@Override
		public LongCounter clone() {
			throw new CustomException();
		}
	}

	/* testInvalidTypeAccumulator */

	private static class IncompatibleAccumulatorTypesMapper extends RichMapFunction<Long, Long> {
		private static final long serialVersionUID = 42;

		@Override
		public void open(Configuration parameters) throws Exception {
			getRuntimeContext().addAccumulator(INCOMPATIBLE_ACCUMULATORS_NAME, new LongCounter());
		}

		@Override
		public Long map(Long value) throws Exception {
			return -1L;
		}
	}

	private static class IncompatibleAccumulatorTypesMapper2 extends RichMapFunction<Long, Long> {
		private static final long serialVersionUID = 42;

		@Override
		public void open(Configuration parameters) throws Exception {
			getRuntimeContext().addAccumulator(INCOMPATIBLE_ACCUMULATORS_NAME, new DoubleCounter());
		}

		@Override
		public Long map(Long value) throws Exception {
			return -1L;
		}
	}

	/** */

	private static class FaultyMergeAccumulatorUsingMapper extends RichMapFunction<Long, Long> {
		private static final long serialVersionUID = 42;

		@Override
		public void open(Configuration parameters) throws Exception {
			getRuntimeContext().addAccumulator(FAULTY_MERGE_ACCUMULATOR, new FaultyMergeAccumulator());
		}

		@Override
		public Long map(Long value) throws Exception {
			return -1L;
		}
	}

	private static class FaultyMergeAccumulator extends LongCounter {
		private static final long serialVersionUID = 42;

		@Override
		public void merge(Accumulator<Long, Long> other) {
			throw new CustomException();
		}

		@Override
		public LongCounter clone() {
			return new FaultyMergeAccumulator();
		}
	}

	private static class CustomException extends RuntimeException {
		private static final long serialVersionUID = 42;
	}

	private static void assertAccumulatorsShouldFail(JobExecutionResult result) {
		try {
			result.getAllAccumulatorResults();
			fail("Should have failed");
		}
		catch (Exception ex) {
			assertTrue(ExceptionUtils.findThrowable(ex, CustomException.class).isPresent());
		}
	}
}


text:
r"""Main routine to calculate ROUGE scores across text files.

Designed to replicate scores computed by the ROUGE perl implementation as
closely as possible.

Output is a text file in CSV format.

Sample usage:

rouge ---rouge_types=rouge1,rouge2,rougeL \
    --target_filepattern=*.targets \
    --prediction_fliepattern=*.decodes \
    --output_filename=scores.csv \
    --use_stemmer

Which is equivalent to calling the perl ROUGE script as:

ROUGE-1.5.5.pl -m -e ./data -n 2 -a /tmp/rouge/settings.xml

Where settings.xml provides target and decode text.
"""

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

from absl import app
from absl import flags
from compare_mt.rouge import io
from compare_mt.rouge import rouge_scorer
from compare_mt.rouge import scoring

flags.DEFINE_string("target_filepattern", None,
                    "Files containing target text.")
flags.DEFINE_string("prediction_filepattern", None,
                    "Files containing prediction text.")
flags.DEFINE_string("output_filename", None,
                    "File in which to write calculated ROUGE scores as a CSV.")
flags.DEFINE_string("delimiter", "\n",
                    "Record delimiter  in files.")
flags.DEFINE_list("rouge_types", ["rouge1", "rouge2", "rougeL"],
                  "List of ROUGE types to calculate.")
flags.DEFINE_boolean("use_stemmer", False,
                     "Whether to use Porter stemmer to remove common suffixes.")
flags.DEFINE_boolean("aggregate", True,
                     "Write aggregates if this is set to True")

FLAGS = flags.FLAGS

def main(argv):
  if len(argv) > 1:
    raise app.UsageError("Too many command-line arguments.")
  scorer = rouge_scorer.RougeScorer(FLAGS.rouge_types, FLAGS.use_stemmer)
  aggregator = scoring.BootstrapAggregator() if FLAGS.aggregate else None
  io.compute_scores_and_write_to_csv(
      FLAGS.target_filepattern,
      FLAGS.prediction_filepattern,
      FLAGS.output_filename,
      scorer,
      aggregator,
      delimiter=FLAGS.delimiter)

if __name__ == "__main__":
  flags.mark_flag_as_required("target_filepattern")
  flags.mark_flag_as_required("prediction_filepattern")
  flags.mark_flag_as_required("output_filename")
  app.run(main)


text:
require 'rspec'
require 'untangle/rspec'

class SomeProcess
  extend Untangle
  dependency :billing_service

  def bill(users)
    users.each do |user|
      billing_service.bill(user) if user.subscribed?
    end
  end
end

describe 'rspec integration' do
  subject { SomeProcess.new }

  context 'manual exposure' do
    let(:billing_service) { SomeProcess.injector.get(:billing_service) }

    it 'allows for access through the injector' do
      subscriber = stub(:subscribed? => true)

      billing_service.should_receive(:bill).with(subscriber)

      subject.bill([subscriber])
    end

    it 'should raise mock exception when an unexpected call happens' do
      subscriber = stub(:subscribed? => true)

      lambda do
        subject.bill([subscriber])
      end.should raise_error(RSpec::Mocks::MockExpectationError, /Mock "billing_service" received unexpected message :bill/)
    end
  end

  context 'automatic exposure' do
    include SomeProcess.untangled_dependencies

    it 'allows for direct access' do
      subscriber = stub(:subscribed? => true)

      billing_service.should_receive(:bill).with(subscriber)

      subject.bill([subscriber])
    end
  end
end


text:
const merge = require('webpack-merge');
const base = require('./webpack.base.js');

module.exports = merge(base, {
	mode: 'development',
	devtool: 'source-map'
});


text:
import { combineReducers } from 'redux';
import {
  LOAD_PROPOSAL_LIST_START,
  LOAD_PROPOSAL_LIST_ERROR,
  LOAD_PROPOSAL_LIST_SUCCESS,
  LOAD_PROPOSAL_SUCCESS,
  CREATE_PROPOSAL_SUCCESS,
  UPDATE_PROPOSAL_SUCCESS,
  SSE_UPDATE_SUCCESS,
} from '../constants';

const handlePageInfo = (state, action) => {
  if (state.endCursor && !action.savePageInfo) {
    return state;
  }
  return { ...state, ...action.pagination };
};

const createList = filter => {
  const handleStateChange = (state, action) => {
    const proposal = action.payload.entities.proposals[action.payload.result];
    let updatedState = proposal.state;
    if (updatedState === 'voting') {
      updatedState = 'active';
    }
    return updatedState === filter
      ? [...new Set([...state, proposal.id])]
      : state.filter(pId => pId !== proposal.id);
  };
  const ids = (state = [], action) => {
    switch (action.type) {
      case CREATE_PROPOSAL_SUCCESS:
      case LOAD_PROPOSAL_SUCCESS: {
        return filter === action.filter
          ? [...new Set([...state, action.payload.result])]
          : state;
      }
      case SSE_UPDATE_SUCCESS: {
        const activity =
          action.payload.entities.activities[action.payload.result];
        if (!activity.type === 'proposal') {
          return state;
        }
        return filter === action.proposalFilter
          ? [...new Set([activity.objectId, ...state])]
          : state;
      }
      case UPDATE_PROPOSAL_SUCCESS: {
        return handleStateChange(state, action);
      }
      case LOAD_PROPOSAL_LIST_SUCCESS: {
        return filter === action.filter
          ? [...new Set([...state, ...(action.payload.result || [])])]
          : state;
      }

      default:
        return state;
    }
  };
  const isFetching = (state = false, action) => {
    if (action.filter !== filter) {
      return state;
    }
    switch (action.type) {
      case LOAD_PROPOSAL_LIST_START:
        return true;
      case LOAD_PROPOSAL_LIST_SUCCESS:
      case LOAD_PROPOSAL_LIST_ERROR:
        return false;
      default:
        return state;
    }
  };

  const errorMessage = (state = null, action) => {
    if (action.filter !== filter) {
      return state;
    }
    switch (action.type) {
      case LOAD_PROPOSAL_LIST_ERROR:
        return action.message;
      case LOAD_PROPOSAL_LIST_START:
      case LOAD_PROPOSAL_LIST_SUCCESS:
        return null;

      default:
        return state;
    }
  };
  const pageInfo = (state = { endCursor: '' }, action) => {
    if (action.filter !== filter) {
      return state;
    }
    switch (action.type) {
      case LOAD_PROPOSAL_LIST_SUCCESS:
        return handlePageInfo(state, action);

      default:
        return state;
    }
  };
  return combineReducers({
    ids,
    isFetching,
    errorMessage,
    pageInfo,
  });
};

export default createList;
export const getIds = state => state.ids;
export const getIsFetching = state => state.isFetching;
export const getErrorMessage = state => state.errorMessage;
export const getPageInfo = state => ({
  pagination: state.pageInfo,
  errorMessage: state.errorMessage,
  pending: state.isFetching,
});


text:
package com.ge.predix.acs.zone.management;

import java.util.Collections;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.ge.predix.acs.config.InMemoryDataSourceConfig;
import com.ge.predix.acs.encryption.Encryptor;
import com.ge.predix.acs.rest.AttributeAdapterConnection;
import com.ge.predix.acs.rest.AttributeConnector;
import com.ge.predix.acs.testutils.TestActiveProfilesResolver;
import com.ge.predix.acs.zone.management.dao.ZoneEntity;
import com.ge.predix.acs.zone.management.dao.ZoneRepository;

@EnableAutoConfiguration
@ContextConfiguration(classes = { InMemoryDataSourceConfig.class, Encryptor.class })
@ActiveProfiles(resolver = TestActiveProfilesResolver.class)
@TestPropertySource("/application.properties")
public class ZoneRepositoryTest extends AbstractTransactionalTestNGSpringContextTests {

    @Autowired
    private ZoneRepository zoneRepository;

    @Test
    public void testAddConnector() throws Exception {
        createZoneWithConnectorAndAssert();
    }

    @Test
    public void testUpdateConnector() throws Exception {
        ZoneEntity zone = createZoneWithConnectorAndAssert();

        AttributeConnector expectedConnector = new AttributeConnector();
        expectedConnector.setIsActive(true);
        expectedConnector.setAdapters(Collections.singleton(new AttributeAdapterConnection("http://some-adapter.com",
                "http://some-uaa.com", "some-client", "some-secret")));
        zone.setResourceAttributeConnector(expectedConnector);

        this.zoneRepository.save(zone);

        // Assert that zone connectors and adapters are updated
        AttributeConnector actualConnector = this.zoneRepository.getByName(zone.getName())
                .getResourceAttributeConnector();
        Assert.assertEquals(actualConnector, expectedConnector);
        Assert.assertEquals(actualConnector.getAdapters(), expectedConnector.getAdapters());
    }

    @Test
    public void testDeleteConnector() throws Exception {
        ZoneEntity zone = createZoneWithConnectorAndAssert();

        zone.setResourceAttributeConnector(null);
        this.zoneRepository.save(zone);
        Assert.assertNull(this.zoneRepository.getByName(zone.getName()).getResourceAttributeConnector());
    }

    private ZoneEntity createZoneWithConnectorAndAssert() throws Exception {
        AttributeConnector expectedConnector = new AttributeConnector();
        Set<AttributeAdapterConnection> expectedAdapters = Collections.singleton(
                new AttributeAdapterConnection("http://my-adapter.com", "http://my-uaa", "my-client", "my-secret"));
        expectedConnector.setAdapters(expectedAdapters);
        expectedConnector.setMaxCachedIntervalMinutes(24);
        ZoneEntity zone = new ZoneEntity();
        zone.setName("azone");
        zone.setSubdomain("asubdomain");
        zone.setDescription("adescription");
        zone.setResourceAttributeConnector(expectedConnector);
        this.zoneRepository.save(zone);
        ZoneEntity acutalZone = this.zoneRepository.getByName("azone");
        Assert.assertEquals(acutalZone.getSubjectAttributeConnector(), null);
        Assert.assertEquals(acutalZone.getResourceAttributeConnector(), expectedConnector);
        Assert.assertEquals(acutalZone.getResourceAttributeConnector().getAdapters(), expectedAdapters);
        return zone;
    }
}