text:
set -euo pipefail

if test $# -gt 0; then
    echo "$0 does not accept arguments" >&2
    exit 32
fi

# Supervisord is not running
if ! test -f /tmp/supervisor.sock; then
    exit 0
fi

# Check if all Hadoop services are running
FAILED=$(supervisorctl status | grep -v RUNNING || true)

if [ "$FAILED" == "" ]; then
  exit 0
else
  echo "Some of the services are failing: ${FAILED}"
  exit 1
fi


text:
"""
    2016-06-18, 2016M-1.0 lzj
    Magnitude calibration according to catalog
    For bok

"""

import numpy as np
from astropy.io import fits
from common import *
from .constant import const

def magcalibrate(red_path, bare_fits,
                 mag_catalog="catalog/HM1998", match_mode=1, mag_match_distan=0.002,
                 ver_from=None, ver_to=None, overwrite=False):
    """ Magnitude calibrate.
    argument:
        red_path: path of output science path
        bare_fits: fits file without path and extension
        mag_catalog: use which magnitude catalog
        match_mode: mode of choose matched star, default 1 for auto, 0 for manual, 2 for all
        mag_match_distan: distance limit for matching, default 0.002 deg, 7.2 arcsec
        ver_from: version which data come from
        ver_to: version which data write to
        overwrite: is set, overwrite existing output files
    returns:
        n_mag for ok, 0 or -1 for error
    """
    # process global debug level
    global debug
    if "debug" not in globals():
        debug = 0
    # version prefix
    ver_from_fix = "" if ver_from is None else "." + ver_from
    ver_to_fix = "" if ver_to is None else "." + ver_to

pass

redpajama_set_name: RedPajamaGithub


text:
/* System includes */
#include <stdio.h>
#include <stdint.h>

/* CMSIS / hardware includes */
#include "system_stm32f4xx.h"

/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"

/* Demo includes. */
#include "basic_io.h"

#include "debug.h"
/* Used as a loop counter to create a very crude delay. */
#define mainDELAY_LOOP_COUNT		(0xffffff)

/* The task functions. */
void vTask1(void *pvParameters);
void vTask2(void *pvParameters);

/*-----------------------------------------------------------*/

int main(void)
{
	/* System Initialization. */
	SystemInit();
	SystemCoreClockUpdate();
	// Create the debug task & print example number and system core clock.
	vDebugInit(1);
	/*
	vDebugPrintf("Example: 1\r\n");
	vDebugPrintf("System Core Clock is running at: %dMHz\r\n",SystemCoreClock/1000000);
	*/

	/* Create one of the two tasks. */
	xTaskCreate(	vTask1,		/* Pointer to the function that implements the task. */
					(const signed char * const)"Task 1",	/* Text name for the task.  This is to facilitate debugging only. */
					200,		/* Stack depth in words. */
					NULL,		/* We are not using the task parameter. */
					1,			/* This task will run at priority 1. */
					NULL);		/* We are not using the task handle. */

	/* Create the other task in exactly the same way. */
	xTaskCreate(vTask2, (const signed char * const)"Task 2", 200, NULL, 1, NULL);

	/* Start the scheduler so our tasks start executing. */
	vTaskStartScheduler();

	/* If all is well we will never reach here as the scheduler will now be
	running.  If we do reach here then it is likely that there was insufficient
	heap available for the idle task to be created. */
	while(1);
}
/*-----------------------------------------------------------*/

void vTask1(void *pvParameters)
{
(void)pvParameters;
const char *pcTaskName = "Task 1 is running\r\n";
volatile unsigned long ul;

	/* As per most tasks, this task is implemented in an infinite loop. */
	while(1)
	{
		/* Print out the name of this task. */
		vPrintString(pcTaskName);

		/* Delay for a period. */
		for(ul = 0; ul < mainDELAY_LOOP_COUNT; ul++)
		{
			/* This loop is just a very crude delay implementation.  There is
			nothing to do in here.  Later exercises will replace this crude
			loop with a proper delay/sleep function. */
		}
	}
}
/*-----------------------------------------------------------*/

void vTask2(void *pvParameters)
{
(void)pvParameters;
const char *pcTaskName = "Task 2 is running\r\n";
volatile unsigned long ul;

	/* As per most tasks, this task is implemented in an infinite loop. */
	while(1)
	{
		/* Print out the name of this task. */
		vPrintString(pcTaskName);

		/* Delay for a period. */
		for(ul = 0; ul < mainDELAY_LOOP_COUNT; ul++)
		{
			/* This loop is just a very crude delay implementation.  There is
			nothing to do in here.  Later exercises will replace this crude
			loop with a proper delay/sleep function. */
		}
	}
}
/*-----------------------------------------------------------*/

void vApplicationMallocFailedHook(void)
{
	/* This function will only be called if an API call to create a task, queue
	or semaphore fails because there is too little heap RAM remaining - and
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. */
	while(1);
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook(xTaskHandle *pxTask, signed char *pcTaskName)
{
(void)pxTask;
(void)pcTaskName;
	/* This function will only be called if a task overflows its stack.  Note
	that stack overflow checking does slow down the context switch
	implementation and will only be performed if configCHECK_FOR_STACK_OVERFLOW
	is set to either 1 or 2 in FreeRTOSConfig.h. */
	while(1);
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook(void)
{
	/* This example does not use the idle hook to perform any processing.  The
	idle hook will only be called if configUSE_IDLE_HOOK is set to 1 in
	FreeRTOSConfig.h. */
}
/*-----------------------------------------------------------*/

void vApplicationTickHook(void)
{
	/* This example does not use the tick hook to perform any processing.   The
	tick hook will only be called if configUSE_TICK_HOOK is set to 1 in
	FreeRTOSConfig.h. */
}


text:
from msrest.paging import Paged

class WcfRelayPaged(Paged):
    """
    A paging container for iterating over a list of :class:`WcfRelay <azure.mgmt.relay.models.WcfRelay>` object
    """

    _attribute_map = {
        'next_link': {'key': 'nextLink', 'type': 'str'},
        'current_page': {'key': 'value', 'type': '[WcfRelay]'}
    }

    def __init__(self, *args, **kwargs):

        super(WcfRelayPaged, self).__init__(*args, **kwargs)


text:
#include <iGlobals.h>

int MPI_Group_difference(MPI_Group group1, MPI_Group group2, MPI_Group *newgroup) {
   iGroup *pGroup1 = mpiData.group[group1];
   iGroup *pGroup2 = mpiData.group[group2];
   iGroup *nGroup = new iGroup(IGROUP_CREATE_DIFF, pGroup1, pGroup2);
   (*newgroup) = nGroup->getId();
   if ((*newgroup) == MPI_GROUP_EMPTY) {
      delete nGroup;
   }
   return MPI_SUCCESS;
}


text:
<#
.Synopsis
    Returns all custom lists for a user.
.DESCRIPTION
    Returns all custom lists for a user.
.EXAMPLE
    PS C:\> Get-TraktUserProfile -Id 'sean'

    Description
    -----------
    This example shows how to retrieve the user profile information from sean from Trakt.TV.
.INPUTS
    None
.OUTPUTS
    PSCustomObject
.NOTES
    None
.COMPONENT
    None
.ROLE
    None
.FUNCTIONALITY
    The functionality that best describes this cmdlet
#>
function Remove-TraktUserList
{
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param (
        # Id help description
        [Parameter(Mandatory=$true)]
        [String]
        $Id,

        # ListId help description
        [Parameter(Mandatory=$true)]
        [Object]
        $ListId
    )

    process
    {
        # LINK: http://docs.trakt.apiary.io/#reference/users/list/delete-a-user's-custom-list

        $uri = 'users/{0}/lists/{1}' -f $Id, $ListId

        Invoke-Trakt -Uri $uri -Method ([Microsoft.PowerShell.Commands.WebRequestMethod]::Delete)
    }
}


text:
from __future__ import unicode_literals

import json
import os
import time

from pgoapi.utilities import f2i
from pokemongo_bot import inventory

from pokemongo_bot.constants import Constants
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.base_dir import _base_dir
from utils import distance, format_time, fort_details
from pokemongo_bot.datastore import Datastore

SPIN_REQUEST_RESULT_SUCCESS = 1
SPIN_REQUEST_RESULT_OUT_OF_RANGE = 2
SPIN_REQUEST_RESULT_IN_COOLDOWN_PERIOD = 3
SPIN_REQUEST_RESULT_INVENTORY_FULL = 4

class SpinFort(Datastore, BaseTask):
    SUPPORTED_TASK_API_VERSION = 1

    def __init__(self, bot, config):
        super(SpinFort, self).__init__(bot, config)
    def initialize(self):
        self.ignore_item_count = self.config.get("ignore_item_count", False)
        self.spin_wait_min = self.config.get("spin_wait_min", 2)
        self.spin_wait_max = self.config.get("spin_wait_max", 3)

    def should_run(self):
        has_space_for_loot = inventory.Items.has_space_for_loot()
        if not has_space_for_loot and not self.ignore_item_count:
            self.emit_event(
                'inventory_full',
                formatted="Inventory is full. You might want to change your config to recycle more items if this message appears consistently."
            )
        return self.ignore_item_count or has_space_for_loot

    def work(self):
        forts = self.get_forts_in_range()

        if not self.should_run() or len(forts) == 0:
            return WorkerResult.SUCCESS

        fort = forts[0]

        lat = fort['latitude']
        lng = fort['longitude']

        details = fort_details(self.bot, fort['id'], lat, lng)
        fort_name = details.get('name', 'Unknown')

        response_dict = self.bot.api.fort_search(
            fort_id=fort['id'],
            fort_latitude=lat,
            fort_longitude=lng,
            player_latitude=f2i(self.bot.position[0]),
            player_longitude=f2i(self.bot.position[1])
        )

        if ('responses' in response_dict) and ('FORT_SEARCH' in response_dict['responses']):
            spin_details = response_dict['responses']['FORT_SEARCH']
            spin_result = spin_details.get('result', -1)

            if (spin_result == SPIN_REQUEST_RESULT_SUCCESS) or (spin_result == SPIN_REQUEST_RESULT_INVENTORY_FULL):
                self.bot.softban = False
                experience_awarded = spin_details.get('experience_awarded', 0)
                items_awarded = self.get_items_awarded_from_fort_spinned(response_dict)

                if experience_awarded or items_awarded:
                    self.emit_event(
                        'spun_pokestop',
                        formatted="Spun pokestop {pokestop}. Experience awarded: {exp}. Items awarded: {items}",
                        data={
                            'pokestop': fort_name,
                            'exp': experience_awarded,
                            'items': items_awarded
                        }
                    )
                else:
                    self.emit_event(
                        'pokestop_empty',
                        formatted='Found nothing in pokestop {pokestop}.',
                        data={'pokestop': fort_name}
                    )
                with self.bot.database as conn:
                    c = conn.cursor()
                    c.execute("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='pokestop_log'")
                result = c.fetchone()
                while True:
                    if result[0] == 1:
                        conn.execute('''INSERT INTO pokestop_log (pokestop, exp, items) VALUES (?, ?, ?)''', (fort_name, str(experience_awarded), str(items_awarded)))
                        break
                    else:
                        self.emit_event(
                        'pokestop_log',
                        sender=self,
                        level='info',
                        formatted="pokestop_log table not found, skipping log"
                        )
                        break
                pokestop_cooldown = spin_details.get(
                    'cooldown_complete_timestamp_ms')
                self.bot.fort_timeouts.update({fort["id"]: pokestop_cooldown})
                self.bot.recent_forts = self.bot.recent_forts[1:] + [fort['id']]
            elif spin_result == SPIN_REQUEST_RESULT_OUT_OF_RANGE:
                self.emit_event(
                    'pokestop_out_of_range',
                    formatted="Pokestop {pokestop} out of range.",
                    data={'pokestop': fort_name}
                )
            elif spin_result == SPIN_REQUEST_RESULT_IN_COOLDOWN_PERIOD:
                pokestop_cooldown = spin_details.get(
                    'cooldown_complete_timestamp_ms')
                if pokestop_cooldown:
                    self.bot.fort_timeouts.update({fort["id"]: pokestop_cooldown})
                    seconds_since_epoch = time.time()
                    minutes_left = format_time(
                        (pokestop_cooldown / 1000) - seconds_since_epoch
                    )
                    self.emit_event(
                        'pokestop_on_cooldown',
                        formatted="Pokestop {pokestop} on cooldown. Time left: {minutes_left}.",
                        data={'pokestop': fort_name, 'minutes_left': minutes_left}
                    )
            else:
                self.emit_event(
                    'unknown_spin_result',
                    formatted="Unknown spint result {status_code}",
                    data={'status_code': str(spin_result)}
                )
            if 'chain_hack_sequence_number' in response_dict['responses'][
                    'FORT_SEARCH']:
                action_delay(self.spin_wait_min, self.spin_wait_max)
                return response_dict['responses']['FORT_SEARCH'][
                    'chain_hack_sequence_number']
            else:
                self.emit_event(
                    'pokestop_searching_too_often',
                    formatted="Possibly searching too often, take a rest."
                )
                if spin_result == 1 and not items_awarded and not experience_awarded and not pokestop_cooldown:
                    self.bot.softban = True
                    self.emit_event(
                        'softban',
                        formatted='Probably got softban.'
                    )
                    with self.bot.database as conn:
                        c = conn.cursor()
                        c.execute("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='softban_log'")
                    result = c.fetchone()

                    if result[0] == 1:
                        source = str("PokemonCatchWorker")
                        status = str("Possible Softban")
                        conn.execute('''INSERT INTO softban_log (status, source) VALUES (?, ?)''', (status, source))
                    else:
                        self.emit_event(
                        'softban_log',
                        sender=self,
                        level='info',
                        formatted="softban_log table not found, skipping log"
                        )

                self.bot.fort_timeouts[fort["id"]] = (time.time() + 300) * 1000  # Don't spin for 5m

                return WorkerResult.ERROR
        action_delay(self.spin_wait_min, self.spin_wait_max)

        if len(forts) > 1:
            return WorkerResult.RUNNING

        return WorkerResult.SUCCESS

    def get_forts_in_range(self):
        forts = self.bot.get_forts(order_by_distance=True)
        forts = filter(lambda fort: fort["id"] not in self.bot.fort_timeouts, forts)
        if self.bot.config.replicate_gps_xy_noise:
            forts = filter(lambda fort: distance(
                self.bot.noised_position[0],
                self.bot.noised_position[1],
                fort['latitude'],
                fort['longitude']
            ) <= Constants.MAX_DISTANCE_FORT_IS_REACHABLE, forts)
        else:
            forts = filter(lambda fort: distance(
                self.bot.position[0],
                self.bot.position[1],
                fort['latitude'],
                fort['longitude']
            ) <= Constants.MAX_DISTANCE_FORT_IS_REACHABLE, forts)

        return forts

    def get_items_awarded_from_fort_spinned(self, response_dict):
        items_awarded = response_dict['responses']['FORT_SEARCH'].get('items_awarded', {})
        if items_awarded:
            tmp_count_items = {}
            for item_awarded in items_awarded:

                item_awarded_id = item_awarded['item_id']
                item_awarded_name = inventory.Items.name_for(item_awarded_id)
                item_awarded_count = item_awarded['item_count']

                if not item_awarded_name in tmp_count_items:
                    tmp_count_items[item_awarded_name] = item_awarded_count
                else:
                    tmp_count_items[item_awarded_name] += item_awarded_count

                self._update_inventory(item_awarded)

            return tmp_count_items

    # TODO : Refactor this class, hide the inventory update right after the api call
    def _update_inventory(self, item_awarded):
        inventory.items().get(item_awarded['item_id']).add(item_awarded['item_count'])


text:
package org.papoose.store.memory;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.BundleException;

import org.papoose.core.AutostartSetting;
import org.papoose.core.spi.BundleStore;

/**
 *
 */
class BundleMemoryStore implements BundleStore
{
    private final static String CLASS_NAME = BundleMemoryStore.class.getName();
    private final static Logger LOGGER = Logger.getLogger(CLASS_NAME);
    private final long bundleId;
    private final String location;
    private long lastModified;
    private AutostartSetting setting;

    BundleMemoryStore(long bundleId, String location) throws BundleException
    {
        assert bundleId >= 0;
        assert location != null && location.trim().length() > 0;

        this.bundleId = bundleId;
        this.location = location;
        this.lastModified = System.currentTimeMillis();
        this.setting = AutostartSetting.STOPPED;

        if (LOGGER.isLoggable(Level.CONFIG))
        {
            LOGGER.config("Bundle id: " + bundleId);
            LOGGER.config("Location: " + location);
        }
    }

    public long getBundleId()
    {
        return bundleId;
    }

    public File getDataRoot()
    {
        throw new UnsupportedOperationException("Memory based bundle store does not support data roots");
    }

    public long getLastModified()
    {
        return lastModified;
    }

    public void markModified()
    {
        lastModified = System.currentTimeMillis();
    }

    public String getLocation()
    {
        return location;
    }

    public AutostartSetting getAutostart()
    {
        return setting;
    }

    public void setAutoStart(AutostartSetting setting)
    {
        this.setting = setting;
    }
}


text:
//*****************************************************************************
//
// usci_i2c.h - Driver for the USCI_I2C Module.
//
//*****************************************************************************

#ifndef __MSP430WARE_USCI_I2C_H__
#define __MSP430WARE_USCI_I2C_H__

#include "inc/hw_memmap.h"

#ifdef __MSP430_HAS_USCI_Bx__

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef __cplusplus
extern "C"
{
#endif

//******************************************************************************
//
// The following is a struct that is passed to USCI_I2C_initMaster()
//
//******************************************************************************
typedef struct USCI_I2C_initMasterParam {
        uint8_t selectClockSource;
        uint32_t i2cClk;
        uint32_t dataRate;
} USCI_I2C_initMasterParam;

//*****************************************************************************
//
// The following are values that can be passed to the selectClockSource
// parameter for functions: USCI_I2C_masterInit().
//
//*****************************************************************************
#define USCI_I2C_CLOCKSOURCE_ACLK                                  UCSSEL__ACLK
#define USCI_I2C_CLOCKSOURCE_SMCLK                                UCSSEL__SMCLK

//*****************************************************************************
//
// The following are values that can be passed to the dataRate parameter for
// functions: USCI_I2C_masterInit().
//
//*****************************************************************************
#define USCI_I2C_SET_DATA_RATE_400KBPS                                   400000
#define USCI_I2C_SET_DATA_RATE_100KBPS                                   100000

//*****************************************************************************
//
// The following are values that can be passed to the mode parameter for
// functions: USCI_I2C_setMode().
//
//*****************************************************************************
#define USCI_I2C_TRANSMIT_MODE                                             UCTR
#define USCI_I2C_RECEIVE_MODE                                              0x00

//*****************************************************************************
//
// The following are values that can be passed to the mask parameter for
// functions: USCI_I2C_enableInterrupt(), USCI_I2C_disableInterrupt(),
// USCI_I2C_clearInterruptFlag(), and USCI_I2C_getInterruptStatus() as well as
// returned by the USCI_I2C_getInterruptStatus() function.
//
//*****************************************************************************
#define USCI_I2C_STOP_INTERRUPT                                         UCSTPIE
#define USCI_I2C_START_INTERRUPT                                        UCSTTIE
#define USCI_I2C_RECEIVE_INTERRUPT                                       UCRXIE
#define USCI_I2C_TRANSMIT_INTERRUPT                                      UCTXIE
#define USCI_I2C_NAK_INTERRUPT                                         UCNACKIE
#define USCI_I2C_ARBITRATIONLOST_INTERRUPT                               UCALIE

//*****************************************************************************
//
// The following are values that can be passed toThe following are values that
// can be returned by the USCI_I2C_isBusy() function and the
// USCI_I2C_isBusBusy() function.
//
//*****************************************************************************
#define USCI_I2C_BUS_BUSY                                               UCBBUSY
#define USCI_I2C_BUS_NOT_BUSY                                              0x00

//*****************************************************************************
//
// The following are values that can be passed toThe following are values that
// can be returned by the USCI_I2C_masterIsStartSent() function.
//
//*****************************************************************************
#define USCI_I2C_SENDING_START                                          UCTXSTT
#define USCI_I2C_START_SEND_COMPLETE                                       0x00

//*****************************************************************************
//
// The following are values that can be passed toThe following are values that
// can be returned by the USCI_I2C_masterIsStopSent() function.
//
//*****************************************************************************
#define USCI_I2C_SENDING_STOP                                           UCTXSTP
#define USCI_I2C_STOP_SEND_COMPLETE                                        0x00

//*****************************************************************************
//
// Prototypes for the APIs.
//
//*****************************************************************************
extern void USCI_I2C_initMaster(uint16_t baseAddress,
                                USCI_I2C_initMasterParam *param);

extern void USCI_I2C_slaveInit(uint16_t baseAddress,
                               uint8_t slaveAddress);

extern void USCI_I2C_enable(uint16_t baseAddress);

extern void USCI_I2C_disable(uint16_t baseAddress);

extern void USCI_I2C_setSlaveAddress(uint16_t baseAddress,
                                     uint8_t slaveAddress);

extern void USCI_I2C_setMode(uint16_t baseAddress,
                             uint8_t mode);

extern void USCI_I2C_slaveDataPut(uint16_t baseAddress,
                                  uint8_t transmitData);

extern uint8_t USCI_I2C_slaveDataGet(uint16_t baseAddress);

extern uint8_t USCI_I2C_isBusBusy(uint16_t baseAddress);

extern uint8_t USCI_I2C_isBusy(uint16_t baseAddress);

extern uint8_t USCI_I2C_masterIsStopSent(uint16_t baseAddress);

extern uint8_t USCI_I2C_masterIsStartSent(uint16_t baseAddress);

extern void USCI_I2C_masterSendStart(uint16_t baseAddress);

extern void USCI_I2C_enableInterrupt(uint16_t baseAddress,
                                     uint8_t mask);

extern void USCI_I2C_disableInterrupt(uint16_t baseAddress,
                                      uint8_t mask);

extern void USCI_I2C_clearInterruptFlag(uint16_t baseAddress,
                                        uint8_t mask);

extern uint8_t USCI_I2C_getInterruptStatus(uint16_t baseAddress,
                                           uint8_t mask);

extern void USCI_I2C_masterSendSingleByte(uint16_t baseAddress,
                                          uint8_t txData);

extern bool USCI_I2C_masterSendSingleByteWithTimeout(uint16_t baseAddress,
                                                     uint8_t txData,
                                                     uint32_t timeout);

extern void USCI_I2C_masterMultiByteSendStart(uint16_t baseAddress,
                                              uint8_t txData);

extern bool USCI_I2C_masterMultiByteSendStartWithTimeout(uint16_t baseAddress,
                                                         uint8_t txData,
                                                         uint32_t timeout);

extern void USCI_I2C_masterMultiByteSendNext(uint16_t baseAddress,
                                             uint8_t txData);

extern bool USCI_I2C_masterMultiByteSendNextWithTimeout(uint16_t baseAddress,
                                                        uint8_t txData,
                                                        uint32_t timeout);

extern void USCI_I2C_masterMultiByteSendFinish(uint16_t baseAddress,
                                               uint8_t txData);

extern bool USCI_I2C_masterMultiByteSendFinishWithTimeout(uint16_t baseAddress,
                                                          uint8_t txData,
                                                          uint32_t timeout);

extern void USCI_I2C_masterMultiByteSendStop(uint16_t baseAddress);

extern bool USCI_I2C_masterMultiByteSendStopWithTimeout(uint16_t baseAddress,
                                                        uint32_t timeout);

extern void USCI_I2C_masterMultiByteReceiveStart(uint16_t baseAddress);

extern uint8_t USCI_I2C_masterMultiByteReceiveNext(uint16_t baseAddress);

extern uint8_t USCI_I2C_masterMultiByteReceiveFinish(uint16_t baseAddress);

extern bool USCI_I2C_masterMultiByteReceiveFinishWithTimeout(uint16_t baseAddress,
                                                             uint8_t *rxData,
                                                             uint32_t timeout);

extern void USCI_I2C_masterMultiByteReceiveStop(uint16_t baseAddress);

extern void USCI_I2C_masterSingleReceiveStart(uint16_t baseAddress);

extern bool USCI_I2C_masterSingleReceiveStartWithTimeout(uint16_t baseAddress,
                                                         uint32_t timeout);

extern uint8_t USCI_I2C_masterSingleReceive(uint16_t baseAddress);

extern uint32_t USCI_I2C_getReceiveBufferAddressForDMA(uint16_t baseAddress);

extern uint32_t USCI_I2C_getTransmitBufferAddressForDMA(uint16_t baseAddress);

//*****************************************************************************
//
// DEPRECATED APIS.
//
//*****************************************************************************
#define USCI_I2C_masterIsSTOPSent                     USCI_I2C_masterIsStopSent

//*****************************************************************************
//
// The following are deprecated APIs.
//
//*****************************************************************************
extern void USCI_I2C_masterInit(uint16_t baseAddress,
                                uint8_t selectClockSource,
                                uint32_t i2cClk,
                                uint32_t dataRate);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif
#endif // __MSP430WARE_USCI_I2C_H__


text:
package com.abstractthis.statewalker;

//The MIT License (MIT)
//
//Copyright (c) 2013 David Smith <www.abstractthis.com>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

/**
 * This unchecked exception represents trouble during state machine execution.
 *
 * @author dshmif
 */
public class StateExecuteException extends RuntimeException {
	private static final long serialVersionUID = -4390551082080142424L;

	public StateExecuteException() {
        super();
    }

    public StateExecuteException(String msg) {
        super(msg);
    }

    public StateExecuteException(Throwable cause) {
        super(cause);
    }

    public StateExecuteException(String msg, Throwable cause) {
        super(msg, cause);
    }

}


text:
import { createDuration } from '../duration/create';
import { createLocal } from '../create/local';

export function from(time, withoutSuffix) {
    if (!this.isValid()) {
        return this.localeData().invalidDate();
    }
    return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
}

export function fromNow(withoutSuffix) {
    return this.from(createLocal(), withoutSuffix);
}


text:
Imports System.Drawing
Imports System.Windows.Forms
Imports Grasshopper.GUI

Public MustInherit Class ImageComponentBase
    Inherits OwlComponentBase

    Private _typedatt As ImageComponent_Attributes = m_attributes
    MustOverride Sub DrawBackground(ByRef BackImage As Bitmap)
    MustOverride Sub DrawForeground(ByRef ForeImage As Bitmap)

    Sub New(Name As String, Nickname As String, Description As String, SubCategory As String)
        MyBase.New(Name, Nickname, Description, SubCategory)
    End Sub

    Sub New(Name As String, Nickname As String, Description As String, Category As String, SubCategory As String)
        MyBase.New(Name, Nickname, Description, Category, SubCategory)
    End Sub

    ''' <summary>
    ''' A place to setup the component attributes regarding the image and its properties.
    ''' </summary>
    ''' <param name="atts"></param>
    MustOverride Sub OnAttributesCreation(ByRef atts As ImageComponent_Attributes)

    Public Overrides Sub CreateAttributes()
        m_attributes = New ImageComponent_Attributes(Me)
        ImageAttributes = m_attributes
        OnAttributesCreation(ImageAttributes)
        ImageAttributes.UpdateImages()
    End Sub

    Public Sub Refresh(Optional immediate As Boolean = True)
        ImageAttributes.UpdateImages()
        If immediate Then Me.OnDisplayExpired(True)
        If immediate Then ImageAttributes.ExpireLayout()
    End Sub

    Protected Overrides Sub AppendAdditionalComponentMenuItems(menu As ToolStripDropDown)
        If ImageAttributes.Resizeable Then
            Dim thiswidth As ToolStripMenuItem = Menu_AppendItem(menu, "Width")
            Dim thisheight As ToolStripMenuItem = Menu_AppendItem(menu, "Height")
            Dim thisres As ToolStripMenuItem = Menu_AppendItem(menu, "Resolution")

            Menu_AppendTextItem(thiswidth.DropDown, ImageAttributes.FrameWidth, AddressOf OnWidthKeyDown, AddressOf OnWidthTextChanged, True)
            Menu_AppendTextItem(thisheight.DropDown, ImageAttributes.FrameHeight, AddressOf OnHeightKeyDown, AddressOf OnHeightTextChanged, True)
            Menu_AppendTextItem(thisres.DropDown, ImageAttributes.Resolution, AddressOf OnResolutionKeyDown, AddressOf OnResolutionTextChanged, True)

            Menu_AppendItem(menu, "Lock Size", AddressOf OnLocking, True, ImageAttributes.LockedSize)
            Menu_AppendSeparator(menu)
        End If

        Menu_AppendItem(menu, "Save Image", AddressOf ImageAttributes.SaveForeground, True)

        MyBase.AppendAdditionalComponentMenuItems(menu)
    End Sub

    Private Sub OnLocking()
        ImageAttributes.LockedSize = Not ImageAttributes.LockedSize
    End Sub

    ''' <summary>
    ''' Changes the size and updates the images.
    ''' </summary>
    ''' <param name="NewFrameWidth"></param>
    ''' <param name="NewFrameHeight"></param>
    ''' <param name="Immediate"></param>
    Public Sub ChangeSize(NewFrameWidth As Integer, NewFrameHeight As Integer, Optional Immediate As Boolean = True)
        ImageAttributes.Resize(Math.Min(ImageAttributes.MaxWidth, Math.Max(NewFrameWidth, ImageAttributes.MinWidth)),
        Math.Min(ImageAttributes.MaxHeight, Math.Max(NewFrameHeight, ImageAttributes.MinHeight)), ImageAttributes.Resolution, Immediate)
    End Sub

    Public Sub ChangeResolution(Value As Single, Optional Immediate As Boolean = True)
        Value = Math.Min(30, Math.Max(Value, 1))
        ImageAttributes.Resize(ImageAttributes.FrameWidth, ImageAttributes.FrameHeight, Value, Immediate)
    End Sub

    Private Sub OnWidthTextChanged(sender As GH_MenuTextBox, text As String)
        sender.Text = JustDigits(text)
    End Sub

    Private Sub OnWidthKeyDown(sender As GH_MenuTextBox, e As KeyEventArgs)
        If e.KeyCode = Keys.Enter And sender.Text <> "" Then
            ChangeSize(CInt(sender.Text), ImageAttributes.FrameHeight, ImageAttributes.Resolution)
        End If
    End Sub

    Private Sub OnHeightTextChanged(sender As GH_MenuTextBox, text As String)
        sender.Text = JustDigits(text)
    End Sub

    Private Sub OnHeightKeyDown(sender As GH_MenuTextBox, e As KeyEventArgs)
        If e.KeyCode = Keys.Enter And sender.Text <> "" Then
            ChangeSize(ImageAttributes.FrameWidth, CInt(sender.Text))
        End If
    End Sub

    Private Sub OnResolutionTextChanged(sender As GH_MenuTextBox, text As String)
        sender.Text = JustDigits(text)
    End Sub

    Private Sub OnResolutionKeyDown(sender As GH_MenuTextBox, e As KeyEventArgs)
        If e.KeyCode = Keys.Enter And sender.Text <> "" Then
            ChangeResolution(CInt(sender.Text))
        End If
    End Sub

    Private Function JustDigits(S As String) As String
        Dim ns As String = ""
        For Each c As Char In S
            If Char.IsDigit(c) Then ns &= c
        Next
        Return ns
    End Function

    Public Property ImageAttributes As ImageComponent_Attributes
        Get
            Return _typedatt
        End Get
        Set(value As ImageComponent_Attributes)
            _typedatt = value
        End Set
    End Property
End Class


text:
package com.facebook.buck.cxx;

import com.facebook.buck.io.FileScrubber;
import com.facebook.buck.rules.Tool;
import com.google.common.collect.ImmutableList;

public interface Archiver extends Tool {

  ImmutableList<FileScrubber> getScrubbers();

  boolean supportsThinArchives();

  ImmutableList<String> getArchiveOptions(boolean isThinArchive);

  ImmutableList<String> outputArgs(String outputPath);

  boolean isRanLibStepRequired();
}


text:
var gulp = require('gulp');
var path = require('path');
var zip = require('gulp-zip');
var minimist = require('minimist');
var fs = require('fs');

var knownOptions = {
	string: 'packageName',
	string: 'packagePath',
	default: {packageName: "Package.zip", packagePath: path.join(__dirname, '_package')}
}

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('default', function () {

	var packagePaths = ['**',
					'!**/_package/**',
					'!**/typings/**',
					'!typings',
					'!_package',
					'!gulpfile.js']

	//add exclusion patterns for all dev dependencies
	var packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
	var devDeps = packageJSON.devDependencies;

	for(var propName in devDeps)
	{
		var excludePattern1 = "!**/node_modules/" + propName + "/**";
		var excludePattern2 = "!**/node_modules/" + propName;
		packagePaths.push(excludePattern1);
		packagePaths.push(excludePattern2);
	}

    return gulp.src(packagePaths)
        .pipe(zip(options.packageName))
        .pipe(gulp.dest(options.packagePath));
});


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<title>Adding & Removing Properties</title>

	<link href="../css/c03.css" rel="stylesheet">

TravelWorthy

hotel facilities

Pool

Gym


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenopeziza distinguenda var. nigrofoliacea Rehm

### Remarks
null


text:
package opencl.generator

import benchmarks.DotProduct
import lift.arithmetic.SizeVar
import opencl.executor.{Execute, Executor, TestWithExecutor, Utils}
import org.junit.Assert._
import org.junit.Test

object TestDotProduct extends TestWithExecutor

class TestDotProduct {

  val N = SizeVar("N")
  val M = SizeVar("M")

  private def dotProd(left: Array[Float], right: Array[Float]): Float = {
    (left,right).zipped.map(_*_).sum
  }

  @Test def DOT_PRODUCT_SIMPLE(): Unit = {

    val inputSize = 1024
    val leftInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)
    val rightInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)

    val (output, runtime) = Execute(inputSize)[Array[Float]](DotProduct.dotProductSimple, leftInputData, rightInputData)

    println("output.length = " + output.length)
    println("output(0) = " + output(0))
    println("runtime = " + runtime)

    assertEquals(dotProd(leftInputData, rightInputData), output.sum, 0.0)
  }

  @Test def DOT_PRODUCT_CPU(): Unit = {

    val inputSize = 262144
    val leftInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)
    val rightInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)

    val (firstOutput, _) = {
      val (output, runtime) =
        Execute(inputSize)[Array[Float]](DotProduct.dotProductCPU1, leftInputData, rightInputData)

      println("output.size = " + output.length)
      println("output(0) = " + output(0))
      println("runtime = " + runtime)

      assertEquals(dotProd(leftInputData, rightInputData), output.sum, 0.0)

      (output, runtime)
    }

    {
      val (output, runtime) = Execute(firstOutput.length)[Array[Float]](DotProduct.dotProductCPU2, firstOutput)

      println("output(0) = " + output(0))
      println("runtime = " + runtime)

      assertEquals(dotProd(leftInputData, rightInputData), output.sum, 0.0)
    }
  }

  @Test def DOT_PRODUCT(): Unit = {

    // TODO: Workaround for AMD GPUs. See issue 42.
    if (Utils.isAmdGpu)
      AllocateLocalMemoryStatically(false)

    val inputSize = 262144
    val leftInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)
    val rightInputData = Array.fill(inputSize)(util.Random.nextInt(5).toFloat)

    val (firstOutput, _) = Execute(inputSize)[Array[Float]](DotProduct.dotProduct1, leftInputData, rightInputData)

    val (output, _) = Execute(firstOutput.length)[Array[Float]](DotProduct.dotProduct2, firstOutput)

    AllocateLocalMemoryStatically(true)
    assertEquals(dotProd(leftInputData, rightInputData), firstOutput.sum, 0.0)
    assertEquals(dotProd(leftInputData, rightInputData), output.sum, 0.0)
  }

}


text:
class FixIndexesOnEmsEvents < ActiveRecord::Migration[4.2]
  def up
    if find_index_by_name(:ems_events, "index_ems_events_on_vm_id")
      rename_index :ems_events, "index_ems_events_on_vm_id",      "index_ems_events_on_vm_or_template_id"
    end
    if find_index_by_name(:ems_events, "index_ems_events_on_dest_vm_id")
      rename_index :ems_events, "index_ems_events_on_dest_vm_id", "index_ems_events_on_dest_vm_or_template_id"
    end
  end

  def down
    rename_index :ems_events, "index_ems_events_on_vm_or_template_id",      "index_ems_events_on_vm_id"
    rename_index :ems_events, "index_ems_events_on_dest_vm_or_template_id", "index_ems_events_on_dest_vm_id"
  end

  def find_index_by_name(table, name)
    indexes(table).find { |i| i.name == name }
  end
end


text:
package org.apache.calcite.util;

import org.apache.calcite.runtime.Resources;
import org.apache.calcite.runtime.Resources.BooleanProp;
import org.apache.calcite.runtime.Resources.Default;
import org.apache.calcite.runtime.Resources.IntProp;
import org.apache.calcite.runtime.Resources.Resource;
import org.apache.calcite.runtime.Resources.StringProp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Objects;
import java.util.Properties;

/**
 * Provides an environment for debugging information, et cetera, used by
 * saffron.
 *
 *
It is a singleton, accessed via the {@link #INSTANCE} object. It is
 * populated from System properties if saffron is invoked via a
 * main() method, from a javax.servlet.ServletContext if
 * saffron is invoked from a servlet, and so forth. If there is a file called
 * "saffron.properties" in the current directory, it is read too.
 *
 *
Every property used in saffron code must have a method in this interface.
 * The method must return a sub-class of
 * {@link org.apache.calcite.runtime.Resources.Prop}. The javadoc
 * comment must describe the name of the property (for example,
 * "net.sf.saffron.connection.PoolSize") and the default value, if any.
 * Developers, please make sure that this remains so!
 *
 * @deprecated As of release 1.19,
 * replaced by {@link org.apache.calcite.config.CalciteSystemProperty}
 */
@Deprecated
public interface SaffronProperties {
  /**
   * The boolean property "saffron.opt.allowInfiniteCostConverters" determines
   * whether the optimizer will consider adding converters of infinite cost in
   * order to convert a relational expression from one calling convention to
   * another. The default value is true.
   */
  @Resource("saffron.opt.allowInfiniteCostConverters")
  @Default("true")
  BooleanProp allowInfiniteCostConverters();

  /**
   * The string property "saffron.default.charset" is the name of the default
   * character set. The default is "ISO-8859-1". It is used in
   * {@link org.apache.calcite.sql.validate.SqlValidator}.
   */
  @Resource("saffron.default.charset")
  @Default("ISO-8859-1")
  StringProp defaultCharset();

  /**
   * The string property "saffron.default.nationalcharset" is the name of the
   * default national character set which is used with the N'string' construct
   * which may or may not be different from the {@link #defaultCharset}. The
   * default is "ISO-8859-1". It is used in
   * {@link org.apache.calcite.sql.SqlLiteral#SqlLiteral}
   */
  @Resource("saffron.default.nationalcharset")
  @Default("ISO-8859-1")
  StringProp defaultNationalCharset();

  /**
   * The string property "saffron.default.collation.name" is the name of the
   * default collation. The default is "ISO-8859-1$en_US". Used in
   * {@link org.apache.calcite.sql.SqlCollation} and
   * {@link org.apache.calcite.sql.SqlLiteral#SqlLiteral}
   */
  @Resource("saffron.default.collation.name")
  @Default("ISO-8859-1$en_US")
  StringProp defaultCollation();

  /**
   * The string property "saffron.default.collation.strength" is the strength
   * of the default collation. The default is "primary". Used in
   * {@link org.apache.calcite.sql.SqlCollation} and
   * {@link org.apache.calcite.sql.SqlLiteral#SqlLiteral}
   */
  @Resource("saffron.default.collation.strength")
  @Default("primary")
  StringProp defaultCollationStrength();

  /**
   * The string property "saffron.metadata.handler.cache.maximum.size" is the
   * maximum size of the cache of metadata handlers. A typical value is
   * the number of queries being concurrently prepared multiplied by the number
   * of types of metadata.
   *
   *
If the value is less than 0, there is no limit. The default is 1,000.
   */
  @Resource("saffron.metadata.handler.cache.maximum.size")
  @Default("1000")
  IntProp metadataHandlerCacheMaximumSize();

  SaffronProperties INSTANCE = Helper.instance();

  /** Helper class. */
  class Helper {
    private Helper() {}

    /**
     * Retrieves the singleton instance of {@link SaffronProperties}.
     */
    static SaffronProperties instance() {
      Properties properties = new Properties();

      // read properties from the file "saffron.properties", if it exists in classpath
      try (InputStream stream = Objects.requireNonNull(Helper.class.getClassLoader(), "classLoader")
          .getResourceAsStream("saffron.properties")) {
        if (stream != null) {
          properties.load(stream);
        }
      } catch (IOException e) {
        throw new RuntimeException("while reading from saffron.properties file", e);
      } catch (RuntimeException e) {
        if (!"java.security.AccessControlException".equals(e.getClass().getName())) {
          throw e;
        }
      }

      // copy in all system properties which start with "saffron."
      Properties source = System.getProperties();
      for (Object objectKey : Collections.list(source.keys())) {
        String key = (String) objectKey;
        String value = Objects.requireNonNull(
            source.getProperty(key),
            () -> "value for " + key);
        if (key.startsWith("saffron.") || key.startsWith("net.sf.saffron.")) {
          properties.setProperty(key, value);
        }
      }
      return Resources.create(properties, SaffronProperties.class);
    }
  }
}


text:
package org.apache.metron.common.transformation;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.apache.metron.common.dsl.ErrorListener;
import org.apache.metron.common.dsl.ParseException;
import org.apache.metron.common.dsl.VariableResolver;
import org.apache.metron.common.transformation.generated.TransformationLexer;
import org.apache.metron.common.transformation.generated.TransformationParser;

import static org.apache.commons.lang3.StringUtils.isEmpty;

public class TransformationProcessor {

  public Object parse(String rule, VariableResolver resolver) {
    if (rule == null || isEmpty(rule.trim())) {
      return null;
    }
    ANTLRInputStream input = new ANTLRInputStream(rule);
    TransformationLexer lexer = new TransformationLexer(input);
    lexer.removeErrorListeners();
    lexer.addErrorListener(new ErrorListener());
    TokenStream tokens = new CommonTokenStream(lexer);
    TransformationParser parser = new TransformationParser(tokens);

    TransformationCompiler treeBuilder = new TransformationCompiler(resolver);
    parser.addParseListener(treeBuilder);
    parser.removeErrorListeners();
    parser.addErrorListener(new ErrorListener());
    parser.transformation();
    return treeBuilder.getResult();
  }

  public boolean validate(String rule) throws ParseException {
    return validate(rule, true);
  }
  public boolean validate(String rule, boolean throwException) throws ParseException {
    try {
      parse(rule, x -> null);
      return true;
    }
    catch(Throwable t) {
      if(throwException) {
        throw new ParseException("Unable to parse " + rule + ": " + t.getMessage(), t);
      }
      else {
        return false;
      }
    }
  }
}


text:
package com.disbrain.dbmslayer.messages;

import java.sql.Connection;

public class CloseDbmsConnectionRequest {
    public final Connection connection;
    public final boolean shall_evict;

    public CloseDbmsConnectionRequest(boolean shall_evict, Connection conn) {
        this.shall_evict = shall_evict;
        connection = conn;
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Promosi_pegawai extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		if ($this->session->userdata('level_user') != 'Manajer')
		{
			redirect('auth/users');
		}

		$this->load->model('nilai_pegawai_model','nilai_pegawai');
	}

	public function index()
	{
		// $data[''] = $this->
		$this->template->manajer('promosi_pegawai','script',$data);
	}

}

/* End of file Promosi_pegawai */
/* Location: ./application/modules/manajer/controllers/Promosi_pegawai */


text:
using System;
class AgeAfter10Years
{
    static void Main()
    {
        int currentYear = DateTime.Now.Year;
        Console.WriteLine("Enter your age in {0}", currentYear);

        int age = int.Parse(Console.ReadLine());
        Console.WriteLine("After 10 years in, {0}, you'll be {1} years old", currentYear + 10, age + 10);
    }
}


text:
var expect = require('expect.js'),
    path = require('path'),
    fs = require('fs'),
    thunkify = require('thunkify'),
    Q = require('q'),
    gochan = require('..'),
    setImmediate = global.setImmediate || process.nextTick;

function fixture(filename) {
  return path.join(__dirname, 'fixtures', filename);
}

describe('gochan', function() {
  it('should be able to use put and get functions', function(done) {
    var ch = gochan();

    var result = [];
    setImmediate(function () {
      result.push('before');
      ch.put(42, function () {
        result.push('after');
        expect(result).to.eql(['before', 'received 42', 'after']);
        done();
      });
    });

    setImmediate(function () {
      ch.get(function (err, value) {
        if (err) return done(err);
        result.push('received ' + value);
      });
    });
  });

  it('should be able to put values without callbacks', function(done) {
    var ch = gochan();
    for (var i = 0; i < 5; i++) {
      ch.put(i);
    }

    var results = [];
    var j = 0;
    (function next() {
      if (j++ < 5) {
        ch.get(function (err, value) {
          if (err) return done(err);
          results.push(value);
          setImmediate(next);
        });
      } else {
        expect(results).to.eql([0, 1, 2, 3, 4]);
        done();
      }
    })();
  });

  it('should be able to do async node IO', function(done) {
    var ch = gochan();
    ch.put(function (cb) {
      fs.readFile(fixture('sample.txt'), { encoding: 'utf8' }, cb);
    });

    ch.get(function (err, value) {
      if (err) return done(err);
      expect(value).to.be.a('string');
      expect(value.length).to.equal(32);
      done();
    });
  });

  it('should be able to use thunkify', function(done) {
    var ch = gochan();
    var readFile = thunkify(fs.readFile);
    ch.put(readFile(fixture('sample.txt'), { encoding: 'utf8' }));

    ch.get(function (err, value) {
      if (err) return done(err);
      expect(value).to.be.a('string');
      expect(value.length).to.equal(32);
      done();
    });
  });

  it('should be able to put promises on the channel', function(done) {
    var ch = gochan();
    function makepromise(val) {
      var d = Q.defer();
      setImmediate(function () {
        d.resolve(val);
      });
      return d.promise;
    }

    ch.put(makepromise(42));
    ch.get(function (err, value) {
      if (err) return done(err);
      expect(value).to.equal(42);
      done();
    });
  });

  it('should be able to get promises from the channel', function(done) {
    var ch = gochan();
    var readFile = thunkify(fs.readFile);
    ch.put(readFile(fixture('sample.txt'), { encoding: 'utf8' }));

    ch.get().then(function (value) {
      expect(value).to.be.a('string');
      expect(value.length).to.equal(32);
      done();
    });
  });

  it('should be able to get the length of the channel', function(done) {
    var ch = gochan();
    ch.put(1);
    expect(ch.length()).to.equal(1);
    ch.put(2);
    expect(ch.length()).to.equal(2);
    ch.get(function (err, value) {
      expect(ch.length()).to.equal(1);
      done();
    });
  });

  it('should be able to select between multiple channels', function(done) {
    var a = gochan();
    var b = gochan();

    gochan.select([a, b], function (err, ch) {
      expect(ch).to.equal(a);
      done();
    });

    a.put(42);
  });

  it('should be able to put with promises', function(done) {
    var ch = gochan();
    ch.put(42).then(function (value) {
      expect(value).to.equal(42);
      done();
    });
  });

  it('should be able to have channel sizes', function(done) {
    var ch = gochan(1);
    ch.put(42, function () {
      expect(ch.length()).to.equal(1);
      setTimeout(function () {
        ch.get(function (err, value) {
          expect(value).to.equal(42);
        });
      }, 50);
    });
    ch.put(84, function (err) {
      expect(ch.length()).to.equal(1);
      ch.get(function (err, value) {
        expect(value).to.equal(84);
        done();
      });
    });
  });

  it('should be able to queue up gets efficiently', function(done) {
    var ch = gochan();
    ch.get(function (err, value) {
      expect(value).to.equal(42);
      ch.put(84);
    });
    ch.get(function (err, value) {
      expect(value).to.equal(84);
      done();
    });
    setTimeout(function () {
      ch.put(42);
    }, 50);
  });
});


text:
<?php

namespace EZ\Pagination\ClassesConcrete;

use EZ\Pagination\ClassesAbstract\CurrentPageAbstract;

/**
 * @package EZ\Pagination\ClassesConcrete
 */
class LiCurrentPage extends CurrentPageAbstract
{
    /**
     * Get complete page link layout.
     *
     * @return string
     */
    public function getLayout()
    {
//      decide to choose class
        $current_page = empty($this->class)
            ? "
{$this->text}
"
            : "
class}'>{$this->text}
";

        return $current_page;
    }
}


text:
Ext.define('Slate.model.course.SectionParticipant', {
    extend: 'Ext.data.Model',
    requires: [
        'Slate.proxy.courses.SectionParticipants',
        'Ext.data.identifier.Negative'
    ],

    // model config
    idProperty: 'ID',
    identifier: 'negative',

    fields: [
        {
            name: 'ID',
            type: 'int',
            allowNull: true
        },
        {
            name: 'Class',
            type: 'string',
            defaultValue: 'Slate\\Courses\\SectionParticipant'
        },
        {
            name: 'Created',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true
        },
        {
            name: 'CreatorID',
            type: 'int',
            allowNull: true
        },
        {
            name: 'CourseSectionID',
            type: 'int'
        },
        {
            name: 'PersonID',
            type: 'int'
        },
        {
            name: 'Person'
        },
        {
            name: 'Role',
            type: 'string'
        },
        {
            name: 'StartDate',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true
        },
        {
            name: 'EndDate',
            type: 'date',
            dateFormat: 'timestamp',
            allowNull: true
        },
        {
            name: 'Cohort',
            type: 'string',
            allowNull: true
        },

        // virtual fields
        {
            name: 'PersonFirstName',
            mapping: 'Person.FirstName'
        },
        {
            name: 'PersonLastName',
            mapping: 'Person.LastName'
        },
        {
            name: 'PersonFullName',
            calculate: function(data) {
                return data.PersonFirstName + ' ' + data.PersonLastName;
            }
        },
        {
            name: 'isInactive',
            persist: false,
            depends: ['StartDate', 'EndDate'],
            convert: function(v, rec) {
                var start = rec.get('StartDate'),
                    end = rec.get('EndDate');

                return Boolean(
                    (start && start.getTime() > Date.now()) ||
                    (end && end.getTime() < Date.now())
                );
            }
        }
    ],

    proxy: 'slate-courses-participants'
});


text:
module Dynflow
  class Action::Suspended
    attr_reader :execution_plan_id, :step_id

    def initialize(action)
      @world             = action.world
      @execution_plan_id = action.execution_plan_id
      @step_id           = action.run_step_id
    end

    def event(event, future = Future.new)
      @world.event execution_plan_id, step_id, event, future
    end

    def <<(event = nil)
      event event
    end

    alias_method :ask, :event
  end
end


text:
"""Tests for `multi_process_runner`."""

import ctypes
import json
import os
import sys
import threading
import time
import unittest

from absl import logging
from absl.testing import parameterized

from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import multi_process_runner
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.eager import context
from tensorflow.python.eager import test

def fn_that_adds_task_type_in_return_data():
  return multi_worker_test_base.get_task_type()

def fn_that_errors():
  raise ValueError('This is an error.')

def fn_that_does_nothing():
  pass

def fn_that_adds_simple_return_data():
  return 'dummy_data'

def fn_that_returns_args_and_kwargs(*args, **kwargs):
  return list(args) + list(kwargs.items())

def fn_with_barrier():
  return multi_process_runner.get_barrier()

def fn_that_returns_pid():
  return os.getpid()

V = None

def fn_that_sets_global(val):
  global V
  old_val = V
  V = val
  return old_val

@combinations.generate(combinations.combine(required_gpus=0))
class MultiProcessRunnerTest(test.TestCase, parameterized.TestCase):

  def _worker_idx(self):
    config_task = json.loads(os.environ['TF_CONFIG'])['task']
    return config_task['index']

  def test_multi_process_runner(self):
    mpr_result = multi_process_runner.run(
        fn_that_adds_task_type_in_return_data,
        multi_worker_test_base.create_cluster_spec(
            num_workers=2, num_ps=3, has_chief=True))

    job_count_dict = {'worker': 2, 'ps': 3, 'chief': 1}
    for data in mpr_result.return_value:
      job_count_dict[data] -= 1

    self.assertEqual(job_count_dict['worker'], 0)
    self.assertEqual(job_count_dict['ps'], 0)
    self.assertEqual(job_count_dict['chief'], 0)

  def test_multi_process_runner_error_propagates_from_subprocesses(self):
    runner = multi_process_runner.MultiProcessRunner(
        fn_that_errors,
        multi_worker_test_base.create_cluster_spec(num_workers=1, num_ps=1),
        max_run_time=20)
    runner.start()
    with self.assertRaisesRegex(ValueError, 'This is an error.'):
      runner.join()

  def test_multi_process_runner_queue_emptied_between_runs(self):
    cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
    return_value = multi_process_runner.run(fn_that_adds_simple_return_data,
                                            cluster_spec).return_value
    self.assertTrue(return_value)
    self.assertEqual(return_value[0], 'dummy_data')
    self.assertEqual(return_value[1], 'dummy_data')
    return_value = multi_process_runner.run(fn_that_does_nothing,
                                            cluster_spec).return_value
    self.assertFalse(return_value)

  def test_multi_process_runner_args_passed_correctly(self):
    return_value = multi_process_runner.run(
        fn_that_returns_args_and_kwargs,
        multi_worker_test_base.create_cluster_spec(num_workers=1),
        args=('a', 'b'),
        kwargs={
            'c_k': 'c_v'
        }).return_value
    self.assertEqual(return_value[0][0], 'a')
    self.assertEqual(return_value[0][1], 'b')
    self.assertEqual(return_value[0][2], ('c_k', 'c_v'))

  def test_stdout_captured(self):

    def simple_print_func():
      print('This is something printed.', flush=True)
      return 'This is returned data.'

    mpr_result = multi_process_runner.run(
        simple_print_func,
        multi_worker_test_base.create_cluster_spec(num_workers=2),
        return_output=True)
    std_stream_results = mpr_result.stdout
    return_value = mpr_result.return_value
    self.assertIn('[worker-0]:    This is something printed.\n',
                  std_stream_results)
    self.assertIn('[worker-1]:    This is something printed.\n',
                  std_stream_results)
    self.assertIn('This is returned data.', return_value)

  def test_termination(self):

    def fn():
      for i in range(0, 10):
        print(
            'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)
        time.sleep(5)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(num_workers=2),
        return_output=True)
    mpr.start()
    time.sleep(5)
    mpr.terminate('worker', 0)

    std_stream_results = mpr.join().stdout

    # Worker 0 is terminated in the middle, so it should not have iteration 9
    # printed.
    self.assertIn('[worker-0]:    index 0, iteration 0\n', std_stream_results)
    self.assertNotIn('[worker-0]:    index 0, iteration 9\n',
                     std_stream_results)
    self.assertIn('[worker-1]:    index 1, iteration 0\n', std_stream_results)
    self.assertIn('[worker-1]:    index 1, iteration 9\n', std_stream_results)

  def test_termination_and_start_single_process(self):

    def fn():
      for i in range(0, 10):
        print(
            'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)
        time.sleep(1)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(num_workers=2),
        return_output=True)
    mpr.start()
    time.sleep(3)
    mpr.terminate('worker', 0)
    mpr.start_single_process('worker', 0)
    std_stream_results = mpr.join().stdout

    # Worker 0 is terminated in the middle, but a new worker 0 is added, so it
    # should still have iteration 9 printed. Moreover, iteration 0 of worker 0
    # should happen twice.
    self.assertLen(
        [s for s in std_stream_results if 'index 0, iteration 0' in s], 2)
    self.assertIn('[worker-0]:    index 0, iteration 9\n', std_stream_results)
    self.assertIn('[worker-1]:    index 1, iteration 0\n', std_stream_results)
    self.assertIn('[worker-1]:    index 1, iteration 9\n', std_stream_results)

  def test_streaming(self):

    def fn():
      for i in range(5):
        logging.info('(logging) %s-%d, i: %d',
                     multi_worker_test_base.get_task_type(), self._worker_idx(),
                     i)
        print(
            '(print) {}-{}, i: {}'.format(
                multi_worker_test_base.get_task_type(), self._worker_idx(), i),
            flush=True)
        time.sleep(1)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(
            has_chief=True, num_workers=2, num_ps=2),
        return_output=True)
    mpr._dependence_on_chief = False

    mpr.start()
    mpr.start_single_process('worker', 2)
    mpr.start_single_process('ps', 2)
    mpr_result = mpr.join()

    list_to_assert = mpr_result.stdout

    for job in ['chief']:
      for iteration in range(5):
        self.assertTrue(
            any('(logging) {}-0, i: {}'.format(job, iteration) in line
                for line in list_to_assert))
        self.assertTrue(
            any('(print) {}-0, i: {}'.format(job, iteration) in line
                for line in list_to_assert))

    for job in ['worker', 'ps']:
      for iteration in range(5):
        for task in range(3):
          self.assertTrue(
              any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line
                  for line in list_to_assert))
          self.assertTrue(
              any('(print) {}-{}, i: {}'.format(job, task, iteration) in line
                  for line in list_to_assert))
        task = 3
        self.assertFalse(
            any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line
                for line in list_to_assert))
        self.assertFalse(
            any('(print) {}-{}, i: {}'.format(job, task, iteration) in line
                for line in list_to_assert))

  def test_start_in_process_as(self):

    def fn():
      for i in range(5):
        logging.info('%s-%d, i: %d', multi_worker_test_base.get_task_type(),
                     self._worker_idx(), i)
        time.sleep(1)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(
            has_chief=True, num_workers=1),
        return_output=True)

    def eval_func():
      time.sleep(1)
      mpr.start_single_process(task_type='evaluator', task_id=0)

    eval_thread = threading.Thread(target=eval_func)
    eval_thread.start()
    mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
    eval_thread.join()
    list_to_assert = mpr.join().stdout
    for job in ['worker', 'evaluator']:
      for iteration in range(5):
        self.assertTrue(
            any('{}-0, i: {}'.format(job, iteration) in line
                for line in list_to_assert))

  def test_terminate_all_does_not_ignore_error(self):
    mpr = multi_process_runner.MultiProcessRunner(
        fn_that_errors,
        multi_worker_test_base.create_cluster_spec(num_workers=2),
        return_output=True)
    mpr.start()
    time.sleep(60)
    mpr.terminate_all()
    with self.assertRaisesRegex(ValueError, 'This is an error.'):
      mpr.join()

  def test_barrier(self):
    multi_process_runner.run(
        fn_with_barrier,
        cluster_spec=multi_worker_test_base.create_cluster_spec(
            has_chief=True, num_workers=1),
    )

  def test_barrier_called_in_main_process(self):
    with self.assertRaises(ValueError):
      multi_process_runner.get_barrier()

  def test_stdout_available_when_timeout(self):

    def fn():
      logging.info('something printed')
      time.sleep(10000)  # Intentionally make the test timeout.

    with self.assertRaises(multi_process_runner.SubprocessTimeoutError) as cm:
      mpr = multi_process_runner.MultiProcessRunner(
          fn,
          multi_worker_test_base.create_cluster_spec(num_workers=1),
          return_output=True)
      mpr.start()
      mpr.join(timeout=60)
    mpr.terminate_all()

    list_to_assert = cm.exception.mpr_result.stdout
    self.assertTrue(
        any('something printed' in line for line in list_to_assert))

  def test_seg_fault_raises_error(self):

    if multi_process_runner.is_oss() or sys.version_info >= (3, 7):
      self.skipTest('TODO(b/171004637): Failing in OSS and Python 3.7+')

    def fn_expected_to_seg_fault():
      ctypes.string_at(0)  # Intentionally made seg fault.

    with self.assertRaises(
        multi_process_runner.UnexpectedSubprocessExitError) as cm:
      multi_process_runner.run(
          fn_expected_to_seg_fault,
          multi_worker_test_base.create_cluster_spec(num_workers=1),
          return_output=True)
    self.assertIn('Subprocess worker-0 exited with exit code',
                  str(cm.exception))
    list_to_assert = cm.exception.mpr_result.stdout
    self.assertTrue(
        any('Segmentation fault' in line for line in list_to_assert))

  def test_seg_fault_in_chief_raises_error(self):

    if multi_process_runner.is_oss() or sys.version_info >= (3, 7):
      self.skipTest('TODO(b/171004637): Failing in OSS and Python 3.7+')

    def fn_expected_to_seg_fault():
      if multi_worker_test_base.get_task_type() == 'worker':
        time.sleep(10000)
      ctypes.string_at(0)  # Intentionally made seg fault.

    with self.assertRaises(
        multi_process_runner.UnexpectedSubprocessExitError) as cm:
      multi_process_runner.run(
          fn_expected_to_seg_fault,
          multi_worker_test_base.create_cluster_spec(
              has_chief=True, num_workers=1),
          return_output=True)
    self.assertIn('Subprocess chief-0 exited with exit code',
                  str(cm.exception))
    list_to_assert = cm.exception.mpr_result.stdout
    self.assertTrue(
        any('Segmentation fault' in line for line in list_to_assert))

  def test_exit_code_is_reported_by_chief_subprocess(self):

    def fn_expected_to_exit_with_20():
      if multi_worker_test_base.get_task_type() == 'worker':
        time.sleep(10000)
      sys.exit(20)

    mpr = multi_process_runner.MultiProcessRunner(
        fn_expected_to_exit_with_20,
        multi_worker_test_base.create_cluster_spec(
            has_chief=True, num_workers=1))
    mpr.start()

    with self.assertRaisesRegex(
        multi_process_runner.UnexpectedSubprocessExitError,
        'Subprocess chief-0 exited with exit code 20'):
      mpr.join()

  def test_exit_code_is_reported_by_subprocess(self):

    def fn_expected_to_exit_with_10():
      sys.exit(10)

    mpr = multi_process_runner.MultiProcessRunner(
        fn_expected_to_exit_with_10,
        multi_worker_test_base.create_cluster_spec(num_workers=1))
    mpr.start()

    with self.assertRaisesRegex(
        multi_process_runner.UnexpectedSubprocessExitError,
        'Subprocess worker-0 exited with exit code 10'):
      mpr.join()

  def test_auto_restart(self):

    def fn(counter):
      counter.value += 1
      if counter.value == 1:
        raise ValueError

    manager = multi_process_runner.manager()
    counter = manager.Value(int, 0)
    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(num_workers=1),
        args=(counter,),
        auto_restart=True)
    mpr.start()
    mpr.join()
    self.assertEqual(counter.value, 2)

  def test_auto_restart_and_timeout(self):

    def fn():
      logging.info('Running')
      time.sleep(1)
      raise ValueError

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(num_workers=1),
        auto_restart=True,
        return_output=True)
    mpr.start()
    with self.assertRaises(ValueError) as cm:
      mpr.join(timeout=10)
    self.assertGreater(
        sum(['Running' in msg for msg in cm.exception.mpr_result.stdout]), 1)

  def test_auto_restart_and_chief(self):
    # If the chief has exited with zero exit code, auto restart should stop
    # restarting other tasks even if they fail.

    def fn():
      time.sleep(1)
      if multi_worker_test_base.get_task_type() != 'chief':
        raise ValueError

    manager = multi_process_runner.manager()
    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(
            has_chief=True, num_workers=1),
        auto_restart=True)
    mpr.start()
    with self.assertRaises(ValueError):
      mpr.join(timeout=10)

  def test_auto_restart_failure_immediate_after_restart(self):
    # Test the case when worker-0 fails immediately after worker-1 restarts.

    def fn():
      time.sleep(5)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(
            has_chief=False, num_workers=2),
        auto_restart=True)
    mpr.start()
    pid = mpr.get_process_id('worker', 1)
    mpr.terminate('worker', 1)
    while mpr.get_process_id('worker', 1) == pid:
      time.sleep(0.1)
    mpr.terminate('worker', 0)
    mpr.join(timeout=20)

  def test_auto_restart_terminate(self):
    # Tasks terminated by the user should also be restarted.

    def fn(counter):
      counter.value += 1
      if counter.value == 1:
        time.sleep(100)

    manager = multi_process_runner.manager()
    counter = manager.Value(int, 0)

    mpr = multi_process_runner.MultiProcessRunner(
        fn,
        multi_worker_test_base.create_cluster_spec(
            has_chief=False, num_workers=1),
        args=(counter,),
        auto_restart=True)
    mpr.start()
    time.sleep(3)
    mpr.terminate('worker', 0)
    mpr.join(timeout=20)
    self.assertEqual(counter.value, 2)

  def test_error_reporting_overrides_timeout_reporting(self):

    def fn():
      if self._worker_idx() == 1:
        time.sleep(10000)
      raise ValueError('Worker 0 errored')

    mpr = multi_process_runner.MultiProcessRunner(
        fn, multi_worker_test_base.create_cluster_spec(num_workers=2))
    mpr.start()

    with self.assertRaisesRegex(
        ValueError,
        'Worker 0 errored'):
      mpr.join(timeout=20)

  def test_process_exists(self):

    def fn():
      time.sleep(100000)

    mpr = multi_process_runner.MultiProcessRunner(
        fn, multi_worker_test_base.create_cluster_spec(num_workers=1))
    mpr.start()
    self.assertTrue(mpr.process_exists('worker', 0))
    mpr.terminate('worker', 0)
    # Worker 0 should exit at some point, or else the test would time out.
    while mpr.process_exists('worker', 0):
      time.sleep(1)

  def test_timeout_none(self):

    if multi_process_runner.is_oss():
      self.skipTest('Intentionally skipping longer test in OSS.')

    def fn():
      time.sleep(250)
      raise ValueError('Worker 0 errored')

    mpr = multi_process_runner.MultiProcessRunner(
        fn, multi_worker_test_base.create_cluster_spec(num_workers=1))

    mpr.start()
    with self.assertRaisesRegex(ValueError, 'Worker 0 errored'):
      mpr.join(timeout=None)

_global_pool = multi_process_runner.MultiProcessPoolRunner(
    multi_worker_test_base.create_cluster_spec(num_workers=2))

class MultiProcessPoolRunnerTest(test.TestCase):

  def test_same_process_across_runs(self):
    cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
    runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
    pid = runner.run(fn_that_returns_pid)
    for _ in range(3):
      self.assertAllEqual(runner.run(fn_that_returns_pid), pid)

  def test_exceptions_in_sub_process(self):
    cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
    runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
    pid = runner.run(fn_that_returns_pid)
    with self.assertRaisesRegex(ValueError, 'This is an error.'):
      runner.run(fn_that_errors)
    self.assertAllEqual(runner.run(fn_that_returns_pid), pid)

  def test_tf_config(self):
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=True, num_workers=2)
    runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
    result = runner.run(fn_that_adds_task_type_in_return_data)

    job_count_dict = {'worker': 2, 'chief': 1}
    for data in result:
      job_count_dict[data] -= 1

    self.assertEqual(job_count_dict['worker'], 0)
    self.assertEqual(job_count_dict['chief'], 0)

  @unittest.expectedFailure
  def test_exception_in_main_process(self):
    # When there's an exception in the main process, __del__() is not called.
    # This test is to verify MultiProcessPoolRunner can cope with __del__() not
    # being called.
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=True, num_workers=2)
    runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec)
    runner.run(fn_that_returns_pid)
    raise ValueError('failure')

  def test_initializer(self):
    cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
    runner = multi_process_runner.MultiProcessPoolRunner(
        cluster_spec, initializer=lambda: fn_that_sets_global(1))
    result = runner.run(fn_that_sets_global, args=(2,))
    self.assertAllEqual(result, [1, 1])

  def test_global_pool(self):
    _global_pool.run(fn_that_does_nothing)

  def test_nested_pool(self):

    def fn():
      # This runs in sub processes, so they are each using their own
      # MultiProcessPoolRunner.
      _global_pool.run(fn_that_does_nothing)

    _global_pool.run(fn)

@combinations.generate(combinations.combine(required_physical_gpus=2))
class MultiProcessRunnerMultiGPUTest(test.TestCase, parameterized.TestCase):

  def test_not_share_gpu(self):
    num_gpus = len(context.context().list_physical_devices('GPU'))
    if num_gpus != 2 and num_gpus != 4:
      self.skipTest('requires 2 or 4 GPUs')
    cluster_spec = multi_worker_test_base.create_cluster_spec(
        has_chief=True, num_workers=1)

    # Verify that CUDA_VISIBLE_DEVICES are different on each worker.

    def cuda_visible_devices_fn():
      return os.getenv('CUDA_VISIBLE_DEVICES')

    runner = multi_process_runner.MultiProcessRunner(
        cuda_visible_devices_fn, cluster_spec, share_gpu=False)
    runner.start()
    result = runner.join()
    if num_gpus == 2:
      self.assertAllEqual(sorted(result.return_value), ['0', '1'])
    else:
      self.assertAllEqual(sorted(result.return_value), ['0,2', '1,3'])

    # Verify that CUDA_VISIBLE_DEVICES works.

    def num_gpus_fn():
      return len(context.context().list_physical_devices('GPU'))

    runner = multi_process_runner.MultiProcessRunner(
        num_gpus_fn, cluster_spec, share_gpu=False)
    runner.start()
    result = runner.join()
    if num_gpus == 2:
      self.assertAllEqual(result.return_value, [1, 1])
    else:
      self.assertAllEqual(result.return_value, [2, 2])

if __name__ == '__main__':
  multi_process_runner.test_main()


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>buffered_write_stream::read_some</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../buffered_write_stream.html" title="buffered_write_stream">
<link rel="prev" href="peek/overload2.html" title="buffered_write_stream::peek (2 of 2 overloads)">
<link rel="next" href="read_some/overload1.html" title="buffered_write_stream::read_some (1 of 2 overloads)">

Home
Libraries
People
FAQ
More

buffered_write_stream::read_some

Read
          some data from the stream. Returns the number of bytes read. Throws an
          exception on failure.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);
  » more...

          Read some data from the stream. Returns the number of bytes read or 0 if
          an error occurred.

template<
    typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers,
    boost::system::error_code & ec);
  » more...

Copyright © 2003-2018 Christopher M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
import React from 'react';

import Layout from './Layout';
import routes from '../routes';

class App extends React.Component {

  render() {
    return (
      <Layout>
        {routes}
      </Layout>
    );
  }
}

export default App;


text:
print "Content-type: text/html\n\n";

my $run = 'r.pl';                            # the script we are running each time..
my $base_path = '../content/';                              # where content folders as seen deom cgi-bin (this script)..
my $url_path = '/content/';                                 # content folders as seen from the url..
my $appname = 'History project';                                  # browser page title
my $page_title = 'History project';                               # the page title..
my $okext = '(htm|doc|rtf|pdf|xls|csv|txt)';                # file extensions we are happy to display..
my $pagename = '';                                          # global strings holding current page/folder info..
my $pageurl = '';
#------------------------------------------------------------------------ work out what to do based on passed params ---
my $buffer = '';
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});   # get form values..
$buffer .= ';'.$ENV{'QUERY_STRING'};   # get the commandline URL input..
my @params = split(';',$buffer); # split into bits.. # first bit is folder, second bit is image number.. eg wrl.pl?Places;1
$params[1]='Home' if($params[1] eq '');
my $matchfolder = $params[1]; # the string/s we will use o identify if we are in the right folder..
$matchfolder =~ s/\//\|/g;
my $body = '';   # this will contain the body div
my $filelist = ''; # this will contain the list of files int the folder..
my $content = &read_folder;  # read folder contents of $params[0]..
my $fullpath = ''; # holds the full path the the selected folder..
print $content;

#------------------------------------------------------------------------ functions ------------------------------------

sub read_folder() { # reads the contents of the folder specfied in params, and do something special if a second param was passed..
  my $ret = '';
  my $this_folder = $base_path.$params[1];                  # concat the base path to the specific path eg '../content/' . 'Buildings'
  my $img_counter = 0;                                      # count of images found in a folder..
  my $pager = '';                                           # this will contain the pager (next priv)..
  my $prev = '';                                            # link to prev image..
  my $next = '';                                            # link to next image..
  my $menu = &build_menu($base_path,'');                        # this will contain the menu..
  my $selected = '';                                        # is the current pager number selected..
  $pageurl = $params[1] if($pageurl eq '');                 # use passed page name fornew URLs if we have not aclculated a better one..
  if(open(IN,'<'.$base_path.$fullpath.'/index.html')){
    my @bodytext = <IN>;
    $body = join('',@bodytext);
    close(IN);
    $body = &clean_body($body);
  }
  $params[2]=1 if(($body eq '')&&($params[2] eq ''));                                           # pretend we had asked for the first image..
  if($params[2] > 0){                                         # we want to see this image number so replace the body with it..
    #&debug("$params[2] $base_path$fullpath");
    if(opendir(DIR, "$base_path$fullpath")){
      my @all_files = sort readdir(DIR);   # read all files from this folder..
      closedir DIR;

      foreach my $this_file(@all_files) {                       # loop through each file
        if($this_file =~ m/(.+)\.jpg/i){                         # if its a dat file eg "player1_100_180.dat"
          $img_counter++;                                       # another image found..
          $selected = '';
          if($img_counter eq $params[2]){                       # same image as the one we want to display?
            $body = "";
            $selected = ' pagerselected';
          }
          $pager .= "$img_counter ";
        }
      }
    }
  }else{
    $body .= "

";
    if(opendir(DIR, "$base_path$fullpath")){
      my @all_files = sort readdir(DIR);   # read all files from this folder..
      closedir DIR;
      foreach my $this_file(@all_files) {                       # loop through each file
        if($this_file =~ m/(.+)\.($okext)/i){                         # if its a dat file eg "player1_100_180.dat"
          my $fname = $1; # the file name with extension..
          my $fext = $2; #the file extension..
          my $fsize = -s $base_path.$fullpath.$this_file;
          $fsize = int($fsize/1024)+1;
          if($fname =~ /index/i){
          }else{
            $body .= "
$fname ($fsize"."k $fext) ";
          }
        }
      }
    }
    $body .= "

";

  }
  if($img_counter > 1){
    $prev = ($params[2] == 1) ? $img_counter : $params[2] - 1;
    $next = ($params[2] == $img_counter) ? $1 : $params[2] + 1;
    $prev = "previous ";
    $next = "next ";
  }else{
    $pager = '';
  }

  if(open(IN,'<'.$base_path.'ripple.html')){
    my @bodytext = <IN>;
    $ret = join('',@bodytext);
    close(IN);
    eval('$ret = "'.$ret.'"'); # convert variables into values..
  }else{
   $ret = 'Cant find template '.$base_path.'ripple.html';
  }
  return $ret;
}

sub build_menu {  # returns a string of all folders in the specified folder..
  my $parent = $_[0]; # the parent folder this is a sub-folder of..
  my $urlparent = $_[1];
  my $ret = '';
  my %folders;
  my $selected = '';
  if(opendir(DIR, $parent)){
    my @all_files = sort readdir(DIR);   # read all files from this folder..
    closedir DIR;
    foreach my $this_file(@all_files) {  # loop through each file
      if($this_file =~ m/\./i){          # if its a . .. or file.ext then ignore it..
      }else{
        $folders{$this_file}=1;
      }
    }
    my @keys = sort keys %folders;
    foreach my $key (@keys){
     $selected = '';
     $tkey = $key;
     if($key =~ /.._(.+)/){ $tkey = $1; }     # cleanup displayable folder name
     #&debug("($tkey =~ /$matchfolder/i)");
     if($tkey =~ /$matchfolder/i){
        $fullpath .= "$key/";  # build up a string of he full absolte apth to the current folder..
        $params[1] = $key; # make sure the exact folder name is used here..
        $selected =  'menuselected'; # will match any bit of the folder name so '?about' will find 'AA_About Us'
        $pagename = $tkey; # use the cleaned up name for the page title..
        $pageurl = ($pageurl eq '') ? $tkey : "$pageurl/$tkey"; # build up a nice path string for the URL ef About/Something
        #&debug("fullpath = $fullpath");
      }
      $ret .= "
$tkey
";
      if($key =~ /$matchfolder/i){
        $ret .= "
".&build_menu("$parent/$key","$urlparent$tkey/")."
";
      }
    }
  }else{
    $ret = 'menu not found';
  }
  return $ret;
}

sub clean_body { # cleansup the content of a file read in for the body (as clean word junk and parse curly-bracket links..
  my $ret = $_[0];
     while ($ret =~ (/{(.+?)}/igsx)) {                      # Find matching code
       my $full_text = $1;                                       # remember the full text for replacement later..
       ($file_name,$link_text) = split(/\~/,$full_text,2);     # split off {About us~Check out stuff about us}
       if($file_name =~ /url/i){
				 $link_variable =&get_url($link_text); # get the $link_text and use it as the $link_variable..
				 #&rem("\n$full_text\n = $link_variable\n\n");
			 }else{
				 $show_name = $file_name;
				 $show_name =~ s/_/ /g;
				 if($file_name =~ /(.+)=(.+)/){
					 #$link_folder,$link_name,$show_name
					 $link_name = $1;
					 $link_file = $2;
					 $show_name = $link_file;
					 $show_name =~ s/\.(.+)//;
					 $show_name = $link_text if($link_text ne '');          # use user selected link text..
					 $link_variable = "\$show_name\<\/a\>";
				 }else{
					 $show_name = $link_text if($link_text ne '');          # use user selected link text..
					 $link_variable = "\$show_name\<\/a\>";
				 }
			 }
       $link_variable =~ s/\s+$//; ## ADD 18/07/05 wm so trailing spaces are removed..
       $full_text =~ s/\./\\\./g;
       $full_text =~ s/\?/\\\?/g;
       $full_text =~ s/\&/\\\&/g;
       $full_text =~ s/\+/\\\+/g;
       $full_text =~ s/\)/\\\)/g;
       $full_text =~ s/\(/\\\(/g;
			 #$link_variable =~ s/item\>/item class='item'\>/g;
			 $link_variable =~ s/dc://g;
			 $link_variable =~ s/\<(\w+)\>/\<$1 \>/g;
			 $link_variable =~ s/\<\\(\w+)\>/\<\\$1 \>/g;
       my @content = split(/\>/,$link_variable);
			 $link_variable = join(">\n",@content).'>';

       $ret =~ (s#{$full_text}#$link_variable#gsi);         # Replace matching code
			 #&rem("s/{$full_text}/$link_variable/gsi");

     }

  return $ret;
}

sub get_url { # returns a web page from the passed URL..
  use IO::Socket;
  my $path = $_[0];
	$path =~ s/http:\/\///; # remove leading protocol..
  my ($host,$document) = split('/',$_[0],2);
  my $remote = IO::Socket::INET->new(Proto=>"tcp",PeerAddr=>$host,PeerPort=>"http(80)");
  if($remote){
    $remote->autoflush(1);
    print $remote ("GET /$document HTTP/1.0\nHost: $host\nUser-Agent: Mozilla\015\012\015\012");
    my @lines = <$remote>;
    close $remote;
    my $c=0;
    shift @lines while($c++ < 5);
    my $ret = join(' ',@lines);
    # cleanup the resulting file for display..
    #$ret =~ s/=(.?)\//=$1http\:\/\/$host\//ig; #"'
    #$ret =~ s/<(|\/)html>//ig; #"'
    #$ret =~ s/<(|\/)body>//ig; #"'
		$ret =~ s/\&lt\;/\</ig;
		$ret =~ s/\&gt\;/\>/ig;
		$ret =~ s/\'//g;
		$ret =~ s/\&quot\;/\"/ig;

		#$ret =~ s/rdf\:/ /ig;
		#$ret =~ s/\n/ /ig;
		#$ret =~ s/\r/ /ig;
		($junk,$ret) = split(/item?/,$ret,2); # =~ s/(.+item?)/\<zitem/;
		($ret,$junk) = split(/\<\/channel/,$ret,2);
    #print '<item'.$ret;
    return '<item'.$ret;
  }
}

sub debug {
  print "DEBUG: $_[0]
";
}

sub rem {
  print "\n\n";
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.bookmarks;

import android.support.v4.widget.DrawerLayout;

import org.chromium.chrome.browser.favicon.LargeIconBridge;
import org.chromium.chrome.browser.snackbar.SnackbarManager;
import org.chromium.chrome.browser.widget.selection.SelectionDelegate;
import org.chromium.components.bookmarks.BookmarkId;

/**
 * Interface used by UI components in the main bookmarks UI to broadcast UI change notifications
 * and get bookmark data model.
 */
interface BookmarkDelegate {

    /**
     * Delegate used to open urls for main fragment on tablet.
     */
    interface BookmarkStateChangeListener {
        /**
         * Let the tab containing bookmark manager load the url and later handle UI updates.
         * @param url The url to open in tab.
         */
        public void onBookmarkUIStateChange(String url);
    }

    /**
     * Returns whether the bookmarks UI will be shown in a dialog, instead of a NativePage. This is
     * typically true on phones and false on tablets, but not always, e.g. in multi-window mode or
     * after upgrading to the new bookmarks.
     */
    boolean isDialogUi();

    /**
     * Corresponds to "All Items" list item in the side drawer. Shows all bookmarks.
     */
    void openAllBookmarks();

    /**
     * Corresponds to any folder named list item in the side drawer. Shows bookmarks under the
     * folder.
     * @param folder Parent folder that contains bookmarks to show as its children.
     */
    void openFolder(BookmarkId folder);

    /**
     * @return The SelectionDelegate responsible for tracking selected bookmarks.
     */
    SelectionDelegate<BookmarkId> getSelectionDelegate();

    /**
     * Notifies the current mode set event to the given observer. For example, if the current mode
     * is MODE_ALL_BOOKMARKS, it calls onAllBookmarksModeSet.
     */
    void notifyStateChange(BookmarkUIObserver observer);

    /**
     * @return Whether there is a drawer.
     */
    boolean doesDrawerExist();

    /**
     * Close drawer if it's visible.
     */
    void closeDrawer();

    /**
     * @return The current drawer layout instance, if it exists.
     */
    DrawerLayout getDrawerLayout();

    /**
     * Closes the Bookmark UI (if on phone) and opens the given bookmark.
     * @param bookmark       bookmark to open.
     * @param launchLocation The UI location where user tried to open bookmark. It is one of
     *                       {@link BookmarkLaunchLocation} values
     */
    void openBookmark(BookmarkId bookmark, int launchLocation);

    /**
     * Shows the search UI.
     */
    void openSearchUI();

    /**
     * Dismisses the search UI.
     */
    void closeSearchUI();

    /**
     * Add an observer to bookmark UI changes.
     */
    void addUIObserver(BookmarkUIObserver observer);

    /**
     * Remove an observer of bookmark UI changes.
     */
    void removeUIObserver(BookmarkUIObserver observer);

    /**
     * @return Bookmark data model associated with this UI.
     */
    BookmarkModel getModel();

    /**
     * @return Current UIState of bookmark main UI. If no mode is stored,
     *         {@link BookmarkUIState#STATE_LOADING} is returned.
     */
    int getCurrentState();

    /**
     * @return LargeIconBridge instance. By sharing the instance, we can also share the cache.
     */
    LargeIconBridge getLargeIconBridge();

    /**
     * @return SnackbarManager instance.
     */
    SnackbarManager getSnackbarManager();
}