text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Doozr - Base - Service - Multiple - Facade
*
* Facade.php - Generic facade for multi instance services
*
* PHP versions 5.5
*
* LICENSE:
* Doozr - The lightweight PHP-Framework for high-performance websites
*
* Copyright (c) 2005 - 2016, Benjamin Carl - All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
*   this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
*   this list of conditions and the following disclaimer in the documentation
*   and/or other materials provided with the distribution.
* - All advertising materials mentioning features or use of this software
*   must display the following acknowledgment: This product includes software
*   developed by Benjamin Carl and other contributors.
* - Neither the name Benjamin Carl nor the names of other contributors
*   may be used to endorse or promote products derived from this
*   software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please feel free to contact us via e-mail: opensource@clickalicious.de
*
* @category   Doozr
* @package    Doozr_Base
* @subpackage Doozr_Base_Service
* @author     Benjamin Carl <opensource@clickalicious.de>
* @copyright  2005 - 2016 Benjamin Carl
* @license    http://www.opensource.org/licenses/bsd-license.php The BSD License
* @version    SVN: $Id$
* @link       http://clickalicious.github.com/Doozr/
*/

require_once DOOZR_DOCUMENT_ROOT.'Doozr/Base/Service/Multiple.php';

/**
 * Doozr - Base - Service - Multiple - Facade
 *
 * Generic facade for multi instance services
 *
 * @category   Doozr
 * @package    Doozr_Base
 * @subpackage Doozr_Base_Service
 * @author     Benjamin Carl <opensource@clickalicious.de>
 * @copyright  2005 - 2016 Benjamin Carl
 * @license    http://www.opensource.org/licenses/bsd-license.php The BSD License
 * @version    Git: $Id$
 * @link       http://clickalicious.github.com/Doozr/
 */
class Doozr_Base_Service_Multiple_Facade extends Doozr_Base_Service_Multiple
{
    /**
     * Contains an instance of the class/object decorated
     *
     * @var object
     * @access protected
     * @static
     */
    private static $_realObject;

    /**
     * setter for decorated object
     *
     * This method is intend to act as setter for $_realObject.
     *
     * @param object $instance An instance of a class to decorate
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return void
     * @access protected
     */
    protected function setRealObject($instance)
    {
        self::$_realObject = $instance;
    }

    /**
     * getter for decorated object
     *
     * This method is intend to act as getter for $_realObject.
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return object An instance of a class
     * @access protected
     */
    protected function getRealObject()
    {
        return self::$_realObject;
    }

    /**
     * generic facade - for all non-implemented methods
     *
     * This method is intend to act as generic facade - for all non-implemented methods
     *
     * @param string $signature The signature (name of the method) originally called
     * @param mixed  $arguments The arguments used for call (can be either an ARRAY of values or NULL)
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return mixed Result of called method if exists, otherwise NULL
     * @access public
     */
    public function __call($signature, $arguments)
    {
        if ($arguments) {
            $result = call_user_func_array(
                array(self::$_realObject, $signature),
                $arguments
            );
        } else {
            $result = call_user_func(
                array(self::$_realObject, $signature)
            );
        }

        //
        return $result;
    }

    /**
     * generic facade - for all non-implemented static methods
     *
     * This method is intend to act as generic facade - for all non-implemented static methods
     *
     * @param string $signature The signature (name of the method) originally called
     * @param mixed  $arguments The arguments used for call (can be either an ARRAY of values or NULL)
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return mixed Result of called method if exists, otherwise NULL
     * @access public
     * @static
     */
    public static function __callStatic($signature, $arguments)
    {
        $targetClassName = get_class(self::$_realObject);

        if ($arguments) {
            $result = call_user_func_array(
                $targetClassName.'::'.$signature,
                $arguments
            );
        } else {
            $result = call_user_func(
                array($targetClassName, $signature)
            );
        }

        //
        return $result;
    }

    /**
     * generic getter for dispatching to decorated object
     *
     * This method is intend to act as generic getter for dispatching to decorated object.
     *
     * @param string $property The property to return
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return mixed The data from property
     * @access public
     */
    public function __get($property)
    {
        if ($property != '_realObject') {
            return self::$_realObject->{$property};
        }
    }

    /**
     * generic setter for dispatching to decorated object
     *
     * This method is intend to act as generic setter for dispatching to decorated object.
     *
     * @param string $property The property to set
     * @param mixed  $value    The value to set
     *
     * @author Benjamin Carl <opensource@clickalicious.de>
     * @return mixed The data from property
     * @access public
     */
    public function __set($property, $value)
    {
        if ($property != '_realObject') {
            return self::$_realObject->{$property} = $value;
        }
    }
}


text:
import sys
import base64
import hashlib
import hmac
import time

from libcloud.utils.py3 import PY3
from libcloud.utils.py3 import b
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import next
from libcloud.utils.py3 import urlparse
from libcloud.utils.py3 import urlencode
from libcloud.utils.py3 import urlquote
from libcloud.utils.py3 import urlunquote

if PY3:
    from io import FileIO as file

from libcloud.utils.files import read_in_chunks, guess_file_mime_type
from libcloud.common.base import ConnectionUserAndKey, XmlResponse
from libcloud.common.types import LibcloudError

from libcloud.storage.base import Object, Container, StorageDriver, CHUNK_SIZE
from libcloud.storage.types import ContainerAlreadyExistsError, \
    ContainerDoesNotExistError, ContainerIsNotEmptyError, \
    ObjectDoesNotExistError

def collapse(s):
    return ' '.join([x for x in s.split(' ') if x])

class AtmosError(LibcloudError):
    def __init__(self, code, message, driver=None):
        super(AtmosError, self).__init__(value=message, driver=driver)
        self.code = code

class AtmosResponse(XmlResponse):
    def success(self):
        return self.status in (httplib.OK, httplib.CREATED, httplib.NO_CONTENT,
                               httplib.PARTIAL_CONTENT)

    def parse_error(self):
        tree = self.parse_body()

        if tree is None:
            return None

        code = int(tree.find('Code').text)
        message = tree.find('Message').text
        raise AtmosError(code=code, message=message,
                         driver=self.connection.driver)

class AtmosConnection(ConnectionUserAndKey):
    responseCls = AtmosResponse

    def add_default_headers(self, headers):
        headers['x-emc-uid'] = self.user_id
        headers['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                        time.gmtime())
        headers['x-emc-date'] = headers['Date']

        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/octet-stream'
        if 'Accept' not in headers:
            headers['Accept'] = '*/*'

        return headers

    def pre_connect_hook(self, params, headers):
        headers['x-emc-signature'] = self._calculate_signature(params, headers)

        return params, headers

    def _calculate_signature(self, params, headers):
        pathstring = urlunquote(self.action)
        if pathstring.startswith(self.driver.path):
            pathstring = pathstring[len(self.driver.path):]
        if params:
            if type(params) is dict:
                params = list(params.items())
            pathstring += '?' + urlencode(params)
        pathstring = pathstring.lower()

        xhdrs = [(k, v) for k, v in list(headers.items()) if
                 k.startswith('x-emc-')]
        xhdrs.sort(key=lambda x: x[0])

        signature = [
            self.method,
            headers.get('Content-Type', ''),
            headers.get('Range', ''),
            headers.get('Date', ''),
            pathstring,
        ]
        signature.extend([k + ':' + collapse(v) for k, v in xhdrs])
        signature = '\n'.join(signature)
        key = base64.b64decode(self.key)
        signature = hmac.new(b(key), b(signature), hashlib.sha1).digest()
        return base64.b64encode(b(signature)).decode('utf-8')

class AtmosDriver(StorageDriver):
    connectionCls = AtmosConnection

    host = None
    path = None
    api_name = 'atmos'
    supports_chunked_encoding = True
    website = 'http://atmosonline.com/'
    name = 'atmos'

    DEFAULT_CDN_TTL = 60 * 60 * 24 * 7  # 1 week

    def __init__(self, key, secret=None, secure=True, host=None, port=None):
        host = host or self.host
        super(AtmosDriver, self).__init__(key, secret, secure, host, port)

    def iterate_containers(self):
        result = self.connection.request(self._namespace_path(''))
        entries = self._list_objects(result.object, object_type='directory')
        for entry in entries:
            extra = {
                'object_id': entry['id']
            }
            yield Container(entry['name'], extra, self)

    def get_container(self, container_name):
        path = self._namespace_path(container_name) + '/?metadata/system'
        try:
            result = self.connection.request(path)
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1003:
                raise
            raise ContainerDoesNotExistError(e, self, container_name)
        meta = self._emc_meta(result)
        extra = {
            'object_id': meta['objectid']
        }
        return Container(container_name, extra, self)

    def create_container(self, container_name):
        path = self._namespace_path(container_name) + '/'
        try:
            self.connection.request(path, method='POST')
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1016:
                raise
            raise ContainerAlreadyExistsError(e, self, container_name)
        return self.get_container(container_name)

    def delete_container(self, container):
        try:
            self.connection.request(self._namespace_path(container.name) + '/',
                                    method='DELETE')
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code == 1003:
                raise ContainerDoesNotExistError(e, self, container.name)
            elif e.code == 1023:
                raise ContainerIsNotEmptyError(e, self, container.name)
        return True

    def get_object(self, container_name, object_name):
        container = self.get_container(container_name)
        object_name_cleaned = self._clean_object_name(object_name)
        path = self._namespace_path(container_name) + '/' + object_name_cleaned

        try:
            result = self.connection.request(path + '?metadata/system')
            system_meta = self._emc_meta(result)

            result = self.connection.request(path + '?metadata/user')
            user_meta = self._emc_meta(result)
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1003:
                raise
            raise ObjectDoesNotExistError(e, self, object_name)

        last_modified = time.strptime(system_meta['mtime'],
                                      '%Y-%m-%dT%H:%M:%SZ')
        last_modified = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                      last_modified)
        extra = {
            'object_id': system_meta['objectid'],
            'last_modified': last_modified
        }
        data_hash = user_meta.pop('md5', '')
        return Object(object_name, int(system_meta['size']), data_hash, extra,
                      user_meta, container, self)

    def upload_object(self, file_path, container, object_name, extra=None,
                      verify_hash=True):
        upload_func = self._upload_file
        upload_func_kwargs = {'file_path': file_path}
        method = 'PUT'

        extra = extra or {}
        object_name_cleaned = self._clean_object_name(object_name)
        request_path = self._namespace_path(container.name) + '/' +\
            object_name_cleaned
        content_type = extra.get('content_type', None)

        try:
            self.connection.request(request_path + '?metadata/system')
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1003:
                raise
            method = 'POST'

        result_dict = self._upload_object(
            object_name=object_name,
            content_type=content_type,
            upload_func=upload_func,
            upload_func_kwargs=upload_func_kwargs,
            request_path=request_path,
            request_method=method,
            headers={}, file_path=file_path)

        bytes_transferred = result_dict['bytes_transferred']

        if extra is None:
            meta_data = {}
        else:
            meta_data = extra.get('meta_data', {})
        meta_data['md5'] = result_dict['data_hash']
        user_meta = ', '.join([k + '=' + str(v) for k, v in
                               list(meta_data.items())])
        self.connection.request(request_path + '?metadata/user', method='POST',
                                headers={'x-emc-meta': user_meta})
        result = self.connection.request(request_path + '?metadata/system')
        meta = self._emc_meta(result)
        del meta_data['md5']
        extra = {
            'object_id': meta['objectid'],
            'meta_data': meta_data,
        }

        return Object(object_name, bytes_transferred, result_dict['data_hash'],
                      extra, meta_data, container, self)

    def upload_object_via_stream(self, iterator, container, object_name,
                                 extra=None):
        if isinstance(iterator, file):
            iterator = iter(iterator)

        data_hash = hashlib.md5()
        generator = read_in_chunks(iterator, CHUNK_SIZE, True)
        bytes_transferred = 0
        try:
            chunk = next(generator)
        except StopIteration:
            chunk = ''

        path = self._namespace_path(container.name + '/' + object_name)
        method = 'PUT'

        if extra is not None:
            content_type = extra.get('content_type', None)
        else:
            content_type = None
        if not content_type:
            content_type, _ = guess_file_mime_type(object_name)

            if not content_type:
                raise AttributeError(
                    'File content-type could not be guessed and' +
                    ' no content_type value provided')

        try:
            self.connection.request(path + '?metadata/system')
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1003:
                raise
            method = 'POST'

        while True:
            end = bytes_transferred + len(chunk) - 1
            data_hash.update(b(chunk))
            headers = {
                'x-emc-meta': 'md5=' + data_hash.hexdigest(),
                'Content-Type': content_type,
            }

            if len(chunk) > 0 and bytes_transferred > 0:
                headers['Range'] = 'Bytes=%d-%d' % (bytes_transferred, end)
                method = 'PUT'

            result = self.connection.request(path, method=method, data=chunk,
                                             headers=headers)
            bytes_transferred += len(chunk)

            try:
                chunk = next(generator)
            except StopIteration:
                break
            if len(chunk) == 0:
                break

        data_hash = data_hash.hexdigest()

        if extra is None:
            meta_data = {}
        else:
            meta_data = extra.get('meta_data', {})
        meta_data['md5'] = data_hash
        user_meta = ', '.join([k + '=' + str(v) for k, v in
                               list(meta_data.items())])
        self.connection.request(path + '?metadata/user', method='POST',
                                headers={'x-emc-meta': user_meta})

        result = self.connection.request(path + '?metadata/system')

        meta = self._emc_meta(result)
        extra = {
            'object_id': meta['objectid'],
            'meta_data': meta_data,
        }

        return Object(object_name, bytes_transferred, data_hash, extra,
                      meta_data, container, self)

    def download_object(self, obj, destination_path, overwrite_existing=False,
                        delete_on_failure=True):
        path = self._namespace_path(obj.container.name + '/' + obj.name)
        response = self.connection.request(path, method='GET', raw=True)

        return self._get_object(obj=obj, callback=self._save_object,
                                response=response,
                                callback_kwargs={
                                    'obj': obj,
                                    'response': response.response,
                                    'destination_path': destination_path,
                                    'overwrite_existing': overwrite_existing,
                                    'delete_on_failure': delete_on_failure
                                },
                                success_status_code=httplib.OK)

    def download_object_as_stream(self, obj, chunk_size=None):
        path = self._namespace_path(obj.container.name + '/' + obj.name)
        response = self.connection.request(path, method='GET', raw=True)

        return self._get_object(obj=obj, callback=read_in_chunks,
                                response=response,
                                callback_kwargs={
                                    'iterator': response.response,
                                    'chunk_size': chunk_size
                                },
                                success_status_code=httplib.OK)

    def delete_object(self, obj):
        path = self._namespace_path(obj.container.name) + '/' +\
            self._clean_object_name(obj.name)
        try:
            self.connection.request(path, method='DELETE')
        except AtmosError:
            e = sys.exc_info()[1]
            if e.code != 1003:
                raise
            raise ObjectDoesNotExistError(e, self, obj.name)
        return True

    def enable_object_cdn(self, obj):
        return True

    def get_object_cdn_url(self, obj, expiry=None, use_object=False):
        """
        Return an object CDN URL.

        :param obj: Object instance
        :type  obj: :class:`Object`

        :param expiry: Expiry
        :type expiry: ``str``

        :param use_object: Use object
        :type use_object: ``bool``

        :rtype: ``str``
        """
        if use_object:
            path = '/rest/objects' + obj.meta_data['object_id']
        else:
            path = '/rest/namespace/' + obj.container.name + '/' + obj.name

        if self.secure:
            protocol = 'https'
        else:
            protocol = 'http'

        expiry = str(expiry or int(time.time()) + self.DEFAULT_CDN_TTL)
        params = [
            ('uid', self.key),
            ('expires', expiry),
        ]
        params.append(('signature', self._cdn_signature(path, params, expiry)))

        params = urlencode(params)
        path = self.path + path
        return urlparse.urlunparse((protocol, self.host, path, '', params, ''))

    def _cdn_signature(self, path, params, expiry):
        key = base64.b64decode(self.secret)
        signature = '\n'.join(['GET', path.lower(), self.key, expiry])
        signature = hmac.new(key, signature, hashlib.sha1).digest()

        return base64.b64encode(signature)

    def _list_objects(self, tree, object_type=None):
        listing = tree.find(self._emc_tag('DirectoryList'))
        entries = []
        for entry in listing.findall(self._emc_tag('DirectoryEntry')):
            file_type = entry.find(self._emc_tag('FileType')).text
            if object_type is not None and object_type != file_type:
                continue
            entries.append({
                'id': entry.find(self._emc_tag('ObjectID')).text,
                'type': file_type,
                'name': entry.find(self._emc_tag('Filename')).text
            })
        return entries

    def _clean_object_name(self, name):
        return urlquote(name.encode('ascii'))

    def _namespace_path(self, path):
        return self.path + '/rest/namespace/' + urlquote(path.encode('ascii'))

    def _object_path(self, object_id):
        return self.path + '/rest/objects/' + object_id.encode('ascii')

    @staticmethod
    def _emc_tag(tag):
        return '{http://www.emc.com/cos/}' + tag

    def _emc_meta(self, response):
        meta = response.headers.get('x-emc-meta', '')
        if len(meta) == 0:
            return {}
        meta = meta.split(', ')
        return dict([x.split('=', 1) for x in meta])

    def iterate_container_objects(self, container):
        headers = {'x-emc-include-meta': '1'}
        path = self._namespace_path(container.name) + '/'
        result = self.connection.request(path, headers=headers)
        entries = self._list_objects(result.object, object_type='regular')
        for entry in entries:
            metadata = {'object_id': entry['id']}
            yield Object(entry['name'], 0, '', {}, metadata, container, self)

redpajama_set_name: RedPajamaGithub


text:
using System;
using QuickGraph.Algorithms;

namespace GraphSharp.Algorithms
{
	/// <summary>
	/// Simple algorithm interface which is not connected to any graph.
	/// </summary>
	public interface IAlgorithm
	{
		object SyncRoot { get;}
		ComputationState State { get;}

		void Compute();
		void Abort();

		event EventHandler StateChanged;
		event EventHandler Started;
		event EventHandler Finished;
		event EventHandler Aborted;
	}
}


text:
#include "pocl_cl.h"

CL_API_ENTRY cl_int CL_API_CALL
POname(clRetainMemObject)(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0
{
  POCL_RETAIN_OBJECT(memobj);
  return CL_SUCCESS;
}
POsym(clRetainMemObject)


text: My first p5js game..


text:
using Microsoft.Xna.Framework;
using SFML.Window;

namespace GlitchGame.Entities.Projectiles
{
    public class NerfBall : Bullet
    {
        public override bool DirectionalRotation { get { return false; } }

        public NerfBall(Ship parent, Vector2 offset, Vector2 speed)
            : base(parent, offset, speed, "nerfball.png")
        {
            var texSize = Sprite.Texture.Size;
            Sprite.Origin = new Vector2f(texSize.X / 2f, texSize.Y / 2f);
        }

        public override void Hit(Ship ship)
        {
            base.Hit(ship);

            ship.Health -= 2.5f * HealthDamageMultiplier(ship);
            ship.Energy -= 7.5f * EnergyDamageMultiplier(ship);

            var d = Program.Random.NextDouble() <= 0.75 ? 1f : -1f;
            ship.NerfMultiplier -= 0.05f * Size * d;
        }
    }
}


text:
function foo() {
  Array(-1);
};
%PrepareFunctionForOptimization(foo);
assertThrows(foo, RangeError);
assertThrows(foo, RangeError);
%OptimizeFunctionOnNextCall(foo);
assertThrows(foo, RangeError);


text:
package com.facebook.infrastructure.utils;

import java.nio.ByteBuffer;

/**
 * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik (
 * pmalik@facebook.com )
 */

public class BasicUtilities {
  public static byte[] longToByteArray(long arg) {
    byte[] retVal = new byte[8];
    ByteBuffer bb = ByteBuffer.wrap(retVal);
    bb.putLong(arg);
    return retVal;
  }

  public static long byteArrayToLong(byte[] arg) {
    ByteBuffer bb = ByteBuffer.wrap(arg);
    return bb.getLong();
  }

  public static byte[] intToByteArray(int arg) {
    byte[] retVal = new byte[4];
    ByteBuffer bb = ByteBuffer.wrap(retVal);
    bb.putInt(arg);
    return retVal;
  }

  public static int byteArrayToInt(byte[] arg) {
    ByteBuffer bb = ByteBuffer.wrap(arg);
    return bb.getInt();
  }

  public static byte[] shortToByteArray(short arg) {
    byte[] retVal = new byte[2];
    ByteBuffer bb = ByteBuffer.wrap(retVal);
    bb.putShort(arg);
    return retVal;
  }

  public static short byteArrayToShort(byte[] arg) {
    ByteBuffer bb = ByteBuffer.wrap(arg);
    return bb.getShort();
  }
}


text:
package slackapi

import (
	context "context"
	gomock "github.com/golang/mock/gomock"
	reflect "reflect"
)

// MockClient is a mock of Client interface
type MockClient struct {
	ctrl     *gomock.Controller
	recorder *MockClientMockRecorder
}

// MockClientMockRecorder is the mock recorder for MockClient
type MockClientMockRecorder struct {
	mock *MockClient
}

// NewMockClient creates a new mock instance
func NewMockClient(ctrl *gomock.Controller) *MockClient {
	mock := &MockClient{ctrl: ctrl}
	mock.recorder = &MockClientMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockClient) EXPECT() *MockClientMockRecorder {
	return m.recorder
}

// GetUserProfile mocks base method
func (m *MockClient) GetUserProfile(ctx context.Context, userID string) (*UserProfile, error) {
	ret := m.ctrl.Call(m, "GetUserProfile", ctx, userID)
	ret0, _ := ret[0].(*UserProfile)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// GetUserProfile indicates an expected call of GetUserProfile
func (mr *MockClientMockRecorder) GetUserProfile(ctx, userID interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserProfile", reflect.TypeOf((*MockClient)(nil).GetUserProfile), ctx, userID)
}


text:
require 'spec_helper.rb'

describe 'OriginationUrl' do
  it "can fetch" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                         .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives fetch responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "weight": 1,
          "date_updated": "2015-01-02T11:23:45Z",
          "enabled": true,
          "friendly_name": "friendly_name",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "priority": 1,
          "sip_url": "sip://sip-box.com:1234",
          "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "2015-01-02T11:23:45Z",
          "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()

    expect(actual).to_not eq(nil)
  end

  it "can delete" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                         .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'delete',
        url: 'https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives delete responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        204,
      nil,
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()

    expect(actual).to eq(true)
  end

  it "can create" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                         .origination_urls.create(weight: 1, priority: 1, enabled: true, friendly_name: "friendly_name", sip_url: "https://example.com")
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {
        'Weight' => 1,
        'Priority' => 1,
        'Enabled' => true,
        'FriendlyName' => "friendly_name",
        'SipUrl' => "https://example.com",
    }
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls',
        data: values,
    ))).to eq(true)
  end

  it "receives create responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        201,
      %q[
      {
          "weight": 1,
          "date_updated": "2015-01-02T11:23:45Z",
          "enabled": true,
          "friendly_name": "friendly_name",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "priority": 1,
          "sip_url": "sip://sip-box.com:1234",
          "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "2015-01-02T11:23:45Z",
          "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls.create(weight: 1, priority: 1, enabled: true, friendly_name: "friendly_name", sip_url: "https://example.com")

    expect(actual).to_not eq(nil)
  end

  it "can read" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                         .origination_urls.list()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls',
    ))).to eq(true)
  end

  it "receives read_full responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "meta": {
              "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0",
              "key": "origination_urls",
              "next_page_url": null,
              "page": 0,
              "page_size": 1,
              "previous_page_url": null,
              "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0"
          },
          "origination_urls": [
              {
                  "weight": 1,
                  "date_updated": "2015-01-02T11:23:45Z",
                  "enabled": true,
                  "friendly_name": "friendly_name",
                  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "priority": 1,
                  "sip_url": "sip://sip-box.com:1234",
                  "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "date_created": "2015-01-02T11:23:45Z",
                  "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
              }
          ]
      }
      ]
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls.list()

    expect(actual).to_not eq(nil)
  end

  it "receives read_empty responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "meta": {
              "first_page_url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0",
              "key": "origination_urls",
              "next_page_url": null,
              "page": 0,
              "page_size": 1,
              "previous_page_url": null,
              "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls?PageSize=1&Page=0"
          },
          "origination_urls": []
      }
      ]
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls.list()

    expect(actual).to_not eq(nil)
  end

  it "can update" do
    @holodeck.mock(Twilio::TwilioResponse.new(500, ''))

    expect {
      @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                         .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update()
    }.to raise_exception(Twilio::REST::TwilioException)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    ))).to eq(true)
  end

  it "receives update responses" do
    @holodeck.mock(Twilio::TwilioResponse.new(
        200,
      %q[
      {
          "weight": 2,
          "date_updated": "2015-01-02T11:23:45Z",
          "enabled": false,
          "friendly_name": "updated_name",
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "priority": 2,
          "sip_url": "sip://sip-updated.com:4321",
          "sid": "OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "2015-01-02T11:23:45Z",
          "trunk_sid": "TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "url": "https://trunking.twilio.com/v1/Trunks/TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/OriginationUrls/OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.trunking.v1.trunks("TRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                                .origination_urls("OUaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update()

    expect(actual).to_not eq(nil)
  end
end


text:
using base::UserMetricsAction;

namespace {

// A bitfield formed from values in AutoImportState to record the state of
// AutoImport. This is used in testing to verify import startup actions that
// occur before an observer can be registered in the test.
uint16_t g_auto_import_state = first_run::AUTO_IMPORT_NONE;

// Flags for functions of similar name.
bool g_should_show_welcome_page = false;
bool g_should_do_autofill_personal_data_manager_first_run = false;

// This class acts as an observer for the ImporterProgressObserver::ImportEnded
// callback. When the import process is started, certain errors may cause
// ImportEnded() to be called synchronously, but the typical case is that
// ImportEnded() is called asynchronously. Thus we have to handle both cases.
class ImportEndedObserver : public importer::ImporterProgressObserver {
 public:
  ImportEndedObserver() : ended_(false) {}
  ~ImportEndedObserver() override {}

  // importer::ImporterProgressObserver:
  void ImportStarted() override {}
  void ImportItemStarted(importer::ImportItem item) override {}
  void ImportItemEnded(importer::ImportItem item) override {}
  void ImportEnded() override {
    ended_ = true;
    if (!callback_for_import_end_.is_null())
      callback_for_import_end_.Run();
  }

  void set_callback_for_import_end(const base::Closure& callback) {
    callback_for_import_end_ = callback;
  }

  bool ended() const {
    return ended_;
  }

 private:
  // Set if the import has ended.
  bool ended_;

  base::Closure callback_for_import_end_;

  DISALLOW_COPY_AND_ASSIGN(ImportEndedObserver);
};

// Helper class that performs delayed first-run tasks that need more of the
// chrome infrastructure to be up and running before they can be attempted.
class FirstRunDelayedTasks : public content::NotificationObserver {
 public:
  enum Tasks {
    NO_TASK,
    INSTALL_EXTENSIONS
  };

  explicit FirstRunDelayedTasks(Tasks task) {
    if (task == INSTALL_EXTENSIONS) {
      registrar_.Add(this,
                     extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
                     content::NotificationService::AllSources());
    }
    registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
                   content::NotificationService::AllSources());
  }

  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override {
    // After processing the notification we always delete ourselves.
    if (type == extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED) {
      Profile* profile = content::Source<Profile>(source).ptr();
      ExtensionService* service =
          extensions::ExtensionSystem::Get(profile)->extension_service();
      DoExtensionWork(service);
    }
    delete this;
  }

 private:
  // Private ctor forces it to be created only in the heap.
  ~FirstRunDelayedTasks() override {}

  // The extension work is to basically trigger an extension update check.
  // If the extension specified in the master pref is older than the live
  // extension it will get updated which is the same as get it installed.
  void DoExtensionWork(ExtensionService* service) {
    if (service)
      service->updater()->CheckNow(extensions::ExtensionUpdater::CheckParams());
  }

  content::NotificationRegistrar registrar_;
};

// Installs a task to do an extensions update check once the extensions system
// is running.
void DoDelayedInstallExtensions() {
  new FirstRunDelayedTasks(FirstRunDelayedTasks::INSTALL_EXTENSIONS);
}

void DoDelayedInstallExtensionsIfNeeded(
    installer::MasterPreferences* install_prefs) {
  base::DictionaryValue* extensions = 0;
  if (install_prefs->GetExtensionsBlock(&extensions)) {
    DVLOG(1) << "Extensions block found in master preferences";
    DoDelayedInstallExtensions();
  }
}

// Sets the |items| bitfield according to whether the import data specified by
// |import_type| should be be auto imported or not.
void SetImportItem(PrefService* user_prefs,
                   const char* pref_path,
                   int import_items,
                   int dont_import_items,
                   importer::ImportItem import_type,
                   int* items) {
  // Work out whether an item is to be imported according to what is specified
  // in master preferences.
  bool should_import = false;
  bool master_pref_set =
      ((import_items | dont_import_items) & import_type) != 0;
  bool master_pref = ((import_items & ~dont_import_items) & import_type) != 0;

  if (import_type == importer::HISTORY ||
      (import_type != importer::FAVORITES &&
       first_run::internal::IsOrganicFirstRun())) {
    // History is always imported unless turned off in master_preferences.
    // Search engines and home page are imported in organic builds only
    // unless turned off in master_preferences.
    should_import = !master_pref_set || master_pref;
  } else {
    // Bookmarks are never imported, unless turned on in master_preferences.
    // Search engine and home page import behaviour is similar in non organic
    // builds.
    should_import = master_pref_set && master_pref;
  }

  // If an import policy is set, import items according to policy. If no master
  // preference is set, but a corresponding recommended policy is set, import
  // item according to recommended policy. If both a master preference and a
  // recommended policy is set, the master preference wins. If neither
  // recommended nor managed policies are set, import item according to what we
  // worked out above.
  if (master_pref_set)
    user_prefs->SetBoolean(pref_path, should_import);

  if (!user_prefs->FindPreference(pref_path)->IsDefaultValue()) {
    if (user_prefs->GetBoolean(pref_path))
      *items |= import_type;
  } else {
    // no policy (recommended or managed) is set
    if (should_import)
      *items |= import_type;
  }

  user_prefs->ClearPref(pref_path);
}

// Launches the import, via |importer_host|, from |source_profile| into
// |target_profile| for the items specified in the |items_to_import| bitfield.
// This may be done in a separate process depending on the platform, but it will
// always block until done.
void ImportFromSourceProfile(const importer::SourceProfile& source_profile,
                             Profile* target_profile,
                             uint16_t items_to_import) {
  // Deletes itself.
  ExternalProcessImporterHost* importer_host =
      new ExternalProcessImporterHost;
  // Don't show the warning dialog if import fails.
  importer_host->set_headless();

  ImportEndedObserver observer;
  importer_host->set_observer(&observer);
  importer_host->StartImportSettings(source_profile,
                                     target_profile,
                                     items_to_import,
                                     new ProfileWriter(target_profile));
  // If the import process has not errored out, block on it.
  if (!observer.ended()) {
    base::RunLoop loop;
    observer.set_callback_for_import_end(loop.QuitClosure());
    loop.Run();
    observer.set_callback_for_import_end(base::Closure());
  }
}

// Imports bookmarks from an html file whose path is provided by
// |import_bookmarks_path|.
void ImportFromFile(Profile* profile,
                    const std::string& import_bookmarks_path) {
  importer::SourceProfile source_profile;
  source_profile.importer_type = importer::TYPE_BOOKMARKS_FILE;

  const base::FilePath::StringType& import_bookmarks_path_str =
#if defined(OS_WIN)
      base::UTF8ToUTF16(import_bookmarks_path);
#else
      import_bookmarks_path;
#endif
  source_profile.source_path = base::FilePath(import_bookmarks_path_str);

  ImportFromSourceProfile(source_profile, profile, importer::FAVORITES);
  g_auto_import_state |= first_run::AUTO_IMPORT_BOOKMARKS_FILE_IMPORTED;
}

// Imports settings from the first profile in |importer_list|.
void ImportSettings(Profile* profile,
                    scoped_ptr<ImporterList> importer_list,
                    int items_to_import) {
  const importer::SourceProfile& source_profile =
      importer_list->GetSourceProfileAt(0);
  // If no items to import then skip entirely.
  if (!items_to_import)
    return;

  // Ensure that importers aren't requested to import items that they do not
  // support. If there is no overlap, skip.
  items_to_import &= source_profile.services_supported;
  if (items_to_import) {
    ImportFromSourceProfile(source_profile, profile, items_to_import);
  }

  g_auto_import_state |= first_run::AUTO_IMPORT_PROFILE_IMPORTED;
}

GURL UrlFromString(const std::string& in) {
  return GURL(in);
}

void ConvertStringVectorToGURLVector(
    const std::vector<std::string>& src,
    std::vector<GURL>* ret) {
  ret->resize(src.size());
  std::transform(src.begin(), src.end(), ret->begin(), &UrlFromString);
}

bool IsOnWelcomePage(content::WebContents* contents) {
  // We have to check both the GetURL() similar to the other checks below, but
  // also the original request url because the welcome page we use is a
  // redirect.
  GURL welcome_page(l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL));
  return contents->GetURL() == welcome_page ||
         (contents->GetController().GetVisibleEntry() &&
          contents->GetController()
                  .GetVisibleEntry()
                  ->GetOriginalRequestURL() == welcome_page);
}

// Show the first run search engine bubble at the first appropriate opportunity.
// This bubble may be delayed by other UI, like global errors and sync promos.
class FirstRunBubbleLauncher : public content::NotificationObserver {
 public:
  // Show the bubble at the first appropriate opportunity. This function
  // instantiates a FirstRunBubbleLauncher, which manages its own lifetime.
  static void ShowFirstRunBubbleSoon();

 private:
  FirstRunBubbleLauncher();
  ~FirstRunBubbleLauncher() override;

  // content::NotificationObserver:
  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override;

  content::NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(FirstRunBubbleLauncher);
};

// static
void FirstRunBubbleLauncher::ShowFirstRunBubbleSoon() {
  SetShowFirstRunBubblePref(first_run::FIRST_RUN_BUBBLE_SHOW);
  // This FirstRunBubbleLauncher instance will manage its own lifetime.
  new FirstRunBubbleLauncher();
}

FirstRunBubbleLauncher::FirstRunBubbleLauncher() {
  registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
                 content::NotificationService::AllSources());

  // This notification is required to observe the switch between the sync setup
  // page and the general settings page.
  registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
                 content::NotificationService::AllSources());
}

FirstRunBubbleLauncher::~FirstRunBubbleLauncher() {}

void FirstRunBubbleLauncher::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(type == content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME ||
         type == chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED);

  Browser* browser = chrome::FindBrowserWithWebContents(
      content::Source<content::WebContents>(source).ptr());
  if (!browser || !browser->is_type_tabbed())
    return;

  // Check the preference to determine if the bubble should be shown.
  PrefService* prefs = g_browser_process->local_state();
  if (!prefs || prefs->GetInteger(prefs::kShowFirstRunBubbleOption) !=
      first_run::FIRST_RUN_BUBBLE_SHOW) {
    delete this;
    return;
  }

  content::WebContents* contents =
      browser->tab_strip_model()->GetActiveWebContents();

  // Suppress the first run bubble if a Gaia sign in page or the sync setup
  // page is showing.
  if (contents && (contents->GetURL().GetOrigin().spec() ==
                       chrome::kChromeUIChromeSigninURL ||
                   gaia::IsGaiaSignonRealm(contents->GetURL().GetOrigin()) ||
                   contents->GetURL() ==
                       chrome::GetSettingsUrl(chrome::kSyncSetupSubPage) ||
                   IsOnWelcomePage(contents))) {
    return;
  }

  if (contents && contents->GetURL().SchemeIs(content::kChromeUIScheme)) {
#if defined(OS_WIN)
    // Suppress the first run bubble if 'make chrome metro' flow is showing.
    if (contents->GetURL().host_piece() == chrome::kChromeUIMetroFlowHost)
      return;
#endif

    // Suppress the first run bubble if the NTP sync promo bubble is showing
    // or if sign in is in progress.
    if (contents->GetURL().host_piece() == chrome::kChromeUINewTabHost) {
      Profile* profile =
          Profile::FromBrowserContext(contents->GetBrowserContext());
      SigninManagerBase* manager =
          SigninManagerFactory::GetForProfile(profile);
      bool signin_in_progress = manager && manager->AuthInProgress();
      bool is_promo_bubble_visible =
          profile->GetPrefs()->GetBoolean(prefs::kSignInPromoShowNTPBubble);

      if (is_promo_bubble_visible || signin_in_progress)
        return;
    }
  }

  // Suppress the first run bubble if a global error bubble is pending.
  GlobalErrorService* global_error_service =
      GlobalErrorServiceFactory::GetForProfile(browser->profile());
  if (global_error_service->GetFirstGlobalErrorWithBubbleView() != NULL)
    return;

  // Reset the preference and notifications to avoid showing the bubble again.
  prefs->SetInteger(prefs::kShowFirstRunBubbleOption,
                    first_run::FIRST_RUN_BUBBLE_DONT_SHOW);

  // Show the bubble now and destroy this bubble launcher.
  browser->ShowFirstRunBubble();
  delete this;
}

static base::LazyInstance<base::FilePath> master_prefs_path_for_testing
    = LAZY_INSTANCE_INITIALIZER;

// Loads master preferences from the master preference file into the installer
// master preferences. Returns the pointer to installer::MasterPreferences
// object if successful; otherwise, returns NULL.
installer::MasterPreferences* LoadMasterPrefs() {
  base::FilePath master_prefs_path;
  if (!master_prefs_path_for_testing.Get().empty())
    master_prefs_path = master_prefs_path_for_testing.Get();
  else
    master_prefs_path = base::FilePath(first_run::internal::MasterPrefsPath());
  if (master_prefs_path.empty())
    return NULL;
  installer::MasterPreferences* install_prefs =
      new installer::MasterPreferences(master_prefs_path);
  if (!install_prefs->read_from_file()) {
    delete install_prefs;
    return NULL;
  }

  return install_prefs;
}

// Makes chrome the user's default browser according to policy or
// |make_chrome_default_for_user| if no policy is set.
void ProcessDefaultBrowserPolicy(bool make_chrome_default_for_user) {
  // Only proceed if chrome can be made default unattended. The interactive case
  // (Windows 8+) is handled by the first run default browser prompt.
  if (shell_integration::CanSetAsDefaultBrowser() ==
      shell_integration::SET_DEFAULT_UNATTENDED) {
    // The policy has precedence over the user's choice.
    if (g_browser_process->local_state()->IsManagedPreference(
            prefs::kDefaultBrowserSettingEnabled)) {
      if (g_browser_process->local_state()->GetBoolean(
          prefs::kDefaultBrowserSettingEnabled)) {
        shell_integration::SetAsDefaultBrowser();
      }
    } else if (make_chrome_default_for_user) {
      shell_integration::SetAsDefaultBrowser();
    }
  }
}

}  // namespace

namespace first_run {
namespace internal {

FirstRunState g_first_run = FIRST_RUN_UNKNOWN;

void SetupMasterPrefsFromInstallPrefs(
    const installer::MasterPreferences& install_prefs,
    MasterPrefs* out_prefs) {
  ConvertStringVectorToGURLVector(
      install_prefs.GetFirstRunTabs(), &out_prefs->new_tabs);

  install_prefs.GetInt(installer::master_preferences::kDistroPingDelay,
                       &out_prefs->ping_delay);

  bool value = false;
  if (install_prefs.GetBool(
          installer::master_preferences::kDistroImportSearchPref, &value)) {
    if (value) {
      out_prefs->do_import_items |= importer::SEARCH_ENGINES;
    } else {
      out_prefs->dont_import_items |= importer::SEARCH_ENGINES;
    }
  }

  // If we're suppressing the first-run bubble, set that preference now.
  // Otherwise, wait until the user has completed first run to set it, so the
  // user is guaranteed to see the bubble iff he or she has completed the first
  // run process.
  if (install_prefs.GetBool(
          installer::master_preferences::kDistroSuppressFirstRunBubble,
          &value) && value)
    SetShowFirstRunBubblePref(FIRST_RUN_BUBBLE_SUPPRESS);

  if (install_prefs.GetBool(
          installer::master_preferences::kDistroImportHistoryPref,
          &value)) {
    if (value) {
      out_prefs->do_import_items |= importer::HISTORY;
    } else {
      out_prefs->dont_import_items |= importer::HISTORY;
    }
  }

  std::string not_used;
  out_prefs->homepage_defined = install_prefs.GetString(
      prefs::kHomePage, &not_used);

  if (install_prefs.GetBool(
          installer::master_preferences::kDistroImportHomePagePref,
          &value)) {
    if (value) {
      out_prefs->do_import_items |= importer::HOME_PAGE;
    } else {
      out_prefs->dont_import_items |= importer::HOME_PAGE;
    }
  }

  // Bookmarks are never imported unless specifically turned on.
  if (install_prefs.GetBool(
          installer::master_preferences::kDistroImportBookmarksPref,
          &value)) {
    if (value)
      out_prefs->do_import_items |= importer::FAVORITES;
    else
      out_prefs->dont_import_items |= importer::FAVORITES;
  }

  if (install_prefs.GetBool(
          installer::master_preferences::kMakeChromeDefaultForUser,
          &value) && value) {
    out_prefs->make_chrome_default_for_user = true;
  }

  if (install_prefs.GetBool(
          installer::master_preferences::kSuppressFirstRunDefaultBrowserPrompt,
          &value) && value) {
    out_prefs->suppress_first_run_default_browser_prompt = true;
  }

  install_prefs.GetString(
      installer::master_preferences::kDistroImportBookmarksFromFilePref,
      &out_prefs->import_bookmarks_path);

  out_prefs->compressed_variations_seed =
      install_prefs.GetCompressedVariationsSeed();
  out_prefs->variations_seed = install_prefs.GetVariationsSeed();
  out_prefs->variations_seed_signature =
      install_prefs.GetVariationsSeedSignature();

  install_prefs.GetString(
      installer::master_preferences::kDistroSuppressDefaultBrowserPromptPref,
      &out_prefs->suppress_default_browser_prompt_for_version);

  if (install_prefs.GetBool(
          installer::master_preferences::kDistroWelcomePageOnOSUpgradeEnabled,
          &value) &&
      !value) {
    out_prefs->welcome_page_on_os_upgrade_enabled = false;
  }
}

bool GetFirstRunSentinelFilePath(base::FilePath* path) {
  base::FilePath user_data_dir;
  if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
    return false;
  *path = user_data_dir.Append(chrome::kFirstRunSentinel);
  return true;
}

bool CreateSentinel() {
  base::FilePath first_run_sentinel;
  return GetFirstRunSentinelFilePath(&first_run_sentinel) &&
      base::WriteFile(first_run_sentinel, "", 0) != -1;
}

// -- Platform-specific functions --

#if !defined(OS_LINUX) && !defined(OS_BSD)
bool IsOrganicFirstRun() {
  std::string brand;
  google_brand::GetBrand(&brand);
  return google_brand::IsOrganicFirstRun(brand);
}
#endif

}  // namespace internal

MasterPrefs::MasterPrefs()
    : ping_delay(0),
      homepage_defined(false),
      do_import_items(0),
      dont_import_items(0),
      make_chrome_default_for_user(false),
      suppress_first_run_default_browser_prompt(false),
      welcome_page_on_os_upgrade_enabled(true) {
}

MasterPrefs::~MasterPrefs() {}

bool IsChromeFirstRun() {
  if (internal::g_first_run == internal::FIRST_RUN_UNKNOWN) {
    internal::g_first_run = internal::FIRST_RUN_FALSE;
    const base::CommandLine* command_line =
        base::CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kForceFirstRun) ||
        (!command_line->HasSwitch(switches::kNoFirstRun) &&
         !internal::IsFirstRunSentinelPresent())) {
      internal::g_first_run = internal::FIRST_RUN_TRUE;
    }
  }
  return internal::g_first_run == internal::FIRST_RUN_TRUE;
}

#if defined(OS_MACOSX)
bool IsFirstRunSuppressed(const base::CommandLine& command_line) {
  return command_line.HasSwitch(switches::kNoFirstRun);
}
#endif

bool IsMetricsReportingOptIn() {
#if defined(OS_CHROMEOS)
  return false;
#elif defined(OS_ANDROID)
  return chrome::GetChannel() == version_info::Channel::STABLE;
#elif defined(OS_MACOSX)
  return chrome::GetChannel() != version_info::Channel::CANARY;
#elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS)
  // Treat BSD and SOLARIS like Linux to not break those builds, although these
  // platforms are not officially supported by Chrome.
  return true;
#elif defined(OS_WIN)
  // TODO(jwd): Get this data directly from the download page.
  // Metrics reporting for Windows is initially enabled on the download page. If
  // it's opt-in or out can change without changes to Chrome. We should get this
  // information directly from the download page for it to be accurate.
  return chrome::GetChannel() == version_info::Channel::STABLE;
#endif
}

void CreateSentinelIfNeeded() {
  if (IsChromeFirstRun())
    internal::CreateSentinel();
}

std::string GetPingDelayPrefName() {
  return base::StringPrintf("%s.%s",
                            installer::master_preferences::kDistroDict,
                            installer::master_preferences::kDistroPingDelay);
}

void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterIntegerPref(GetPingDelayPrefName().c_str(), 0);
}

bool SetShowFirstRunBubblePref(FirstRunBubbleOptions show_bubble_option) {
  PrefService* local_state = g_browser_process->local_state();
  if (!local_state)
    return false;
  if (local_state->GetInteger(
          prefs::kShowFirstRunBubbleOption) != FIRST_RUN_BUBBLE_SUPPRESS) {
    // Set the new state as long as the bubble wasn't explicitly suppressed
    // already.
    local_state->SetInteger(prefs::kShowFirstRunBubbleOption,
                            show_bubble_option);
  }
  return true;
}

void SetShouldShowWelcomePage() {
  g_should_show_welcome_page = true;
}

bool ShouldShowWelcomePage() {
  bool retval = g_should_show_welcome_page;
  g_should_show_welcome_page = false;
  return retval;
}

void SetShouldDoPersonalDataManagerFirstRun() {
  g_should_do_autofill_personal_data_manager_first_run = true;
}

bool ShouldDoPersonalDataManagerFirstRun() {
  bool retval = g_should_do_autofill_personal_data_manager_first_run;
  g_should_do_autofill_personal_data_manager_first_run = false;
  return retval;
}

void LogFirstRunMetric(FirstRunBubbleMetric metric) {
  UMA_HISTOGRAM_ENUMERATION("FirstRun.SearchEngineBubble", metric,
                            NUM_FIRST_RUN_BUBBLE_METRICS);
}

void SetMasterPrefsPathForTesting(const base::FilePath& master_prefs) {
  master_prefs_path_for_testing.Get() = master_prefs;
}

ProcessMasterPreferencesResult ProcessMasterPreferences(
    const base::FilePath& user_data_dir,
    MasterPrefs* out_prefs) {
  DCHECK(!user_data_dir.empty());

  scoped_ptr<installer::MasterPreferences> install_prefs(LoadMasterPrefs());

  // Default value in case master preferences is missing or corrupt, or
  // ping_delay is missing.
  out_prefs->ping_delay = 90;
  if (install_prefs.get()) {
    if (!internal::ShowPostInstallEULAIfNeeded(install_prefs.get()))
      return EULA_EXIT_NOW;

    if (!chrome_prefs::InitializePrefsFromMasterPrefs(
            profiles::GetDefaultProfileDir(user_data_dir),
            install_prefs->master_dictionary())) {
      DLOG(ERROR) << "Failed to initialize from master_preferences.";
    }

    DoDelayedInstallExtensionsIfNeeded(install_prefs.get());

    internal::SetupMasterPrefsFromInstallPrefs(*install_prefs, out_prefs);
  }

  return FIRST_RUN_PROCEED;
}

void AutoImport(
    Profile* profile,
    bool homepage_defined,
    int import_items,
    int dont_import_items,
    const std::string& import_bookmarks_path) {
  base::FilePath local_state_path;
  PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
  bool local_state_file_exists = base::PathExists(local_state_path);

  // It may be possible to do the if block below asynchronously. In which case,
  // get rid of this RunLoop. http://crbug.com/366116.
  base::RunLoop run_loop;
  scoped_ptr<ImporterList> importer_list(new ImporterList());
  importer_list->DetectSourceProfiles(
      g_browser_process->GetApplicationLocale(),
      false,  // include_interactive_profiles?
      run_loop.QuitClosure());
  run_loop.Run();

  // Do import if there is an available profile for us to import.
  if (importer_list->count() > 0) {
    if (internal::IsOrganicFirstRun()) {
      // Home page is imported in organic builds only unless turned off or
      // defined in master_preferences.
      if (homepage_defined) {
        dont_import_items |= importer::HOME_PAGE;
        if (import_items & importer::HOME_PAGE)
          import_items &= ~importer::HOME_PAGE;
      }
      // Search engines are not imported automatically in organic builds if the
      // user already has a user preferences directory.
      if (local_state_file_exists) {
        dont_import_items |= importer::SEARCH_ENGINES;
        if (import_items & importer::SEARCH_ENGINES)
          import_items &= ~importer::SEARCH_ENGINES;
      }
    }

    PrefService* user_prefs = profile->GetPrefs();
    int items = 0;

    SetImportItem(user_prefs,
                  prefs::kImportHistory,
                  import_items,
                  dont_import_items,
                  importer::HISTORY,
                  &items);
    SetImportItem(user_prefs,
                  prefs::kImportHomepage,
                  import_items,
                  dont_import_items,
                  importer::HOME_PAGE,
                  &items);
    SetImportItem(user_prefs,
                  prefs::kImportSearchEngine,
                  import_items,
                  dont_import_items,
                  importer::SEARCH_ENGINES,
                  &items);
    SetImportItem(user_prefs,
                  prefs::kImportBookmarks,
                  import_items,
                  dont_import_items,
                  importer::FAVORITES,
                  &items);

    importer::LogImporterUseToMetrics(
        "AutoImport", importer_list->GetSourceProfileAt(0).importer_type);

    ImportSettings(profile, std::move(importer_list), items);
  }

  if (!import_bookmarks_path.empty()) {
    ImportFromFile(profile, import_bookmarks_path);
  }

  content::RecordAction(UserMetricsAction("FirstRunDef_Accept"));

  g_auto_import_state |= AUTO_IMPORT_CALLED;
}

void DoPostImportTasks(Profile* profile, bool make_chrome_default_for_user) {
  // Only set default browser after import as auto import relies on the current
  // default browser to know what to import from.
  ProcessDefaultBrowserPolicy(make_chrome_default_for_user);

  // Display the first run bubble if there is a default search provider.
  TemplateURLService* template_url =
      TemplateURLServiceFactory::GetForProfile(profile);
  if (template_url && template_url->GetDefaultSearchProvider())
    FirstRunBubbleLauncher::ShowFirstRunBubbleSoon();
  SetShouldShowWelcomePage();
  SetShouldDoPersonalDataManagerFirstRun();

  internal::DoPostImportPlatformSpecificTasks(profile);
}

uint16_t auto_import_state() {
  return g_auto_import_state;
}

}  // namespace first_run


text:
<!DOCTYPE html>

  <title th:text="${title}">Title</title>
  <link rel="shortcut icon" href="/static/media/favicons/favicon.ico" type="image/x-icon"/>
  <link rel="stylesheet" type="text/css" th:href="@{/static/css/bootstrap.min.css}"/>

  <link rel="stylesheet" type="text/css" th:href="@{/static/css/main.css}"/>
  <link rel="stylesheet" type="text/css" th:href="@{/static/css/my.css}"/>
  <link rel="stylesheet" type="text/css" th:href="@{/static/media/glyphicons-halflings-regular.ttf  }"/>
  <link rel="stylesheet" type="text/css" th:href="@{/static/media/glyphicons-halflings-regular.woff  }"/>
  <link rel="stylesheet" type="text/css" th:href="@{/static/media/glyphicons-halflings-regular.woff2 }"/>

  <link rel="stylesheet" type="text/css" th:href="@{/static/css/ie10-viewport-bug-workaround.css}"/>

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

              </button>

 Home

Logout

Title

Fake content


text:
package io.demor.nuts.lib.api;

import io.demor.nuts.lib.ReflectUtils;
import io.demor.nuts.lib.net.ApiInvokeHandler;
import io.demor.nuts.lib.net.ApiRequest;
import io.demor.nuts.lib.net.ApiResponse;
import io.demor.nuts.lib.net.INet;
import rx.Observable;
import rx.Subscriber;

import java.lang.reflect.Method;

public class RxApiHandler extends ApiInvokeHandler {

    public RxApiHandler(INet net) {
        super(net);
    }

    @Override
    protected Object methodReturn(final ApiRequest request, final int retryCount, final Method method, final Object[] args) throws Exception {
        final Class<?> returnClz = method.getReturnType();

        if (returnClz.isAssignableFrom(Observable.class)) {
            return Observable.create(new Observable.OnSubscribe<Object>() {
                @Override
                public void call(Subscriber<? super Object> subscriber) {
                    subscriber.onStart();
                    final ApiResponse response = execute(request, retryCount, method, args);
                    if (response.isSuccess()) {
                        subscriber.onNext(mNet.createResponse((Class) ReflectUtils.getGenericType(method.getGenericReturnType()), response));
                    } else {
                        subscriber.onError(response.getException());
                    }
                    subscriber.onCompleted();
                }
            });
        } else {
            return super.methodReturn(request, retryCount, method, args);
        }
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Service from './Service'

/* Service configuration. */
const token = ''
const service = new Service('http://127.0.0.1:5000/v1', token);

/* Render main application. */
ReactDOM.render(
  <App service={service} />,
  document.getElementById('root')
);


text:
var peerByOption: PeerJs.Peer = new Peer({
    key: 'peerKey',
    debug: 3,
    logFunction: ()=>{
    }
});

peerByOption.listAllPeers(function(items){
    for(var i in items){
        console.log(decodeURI(items[i]));
    }
});

var peerById: PeerJs.Peer = new Peer("peerid");

var peerByIdAndOption: PeerJs.Peer = new Peer(
    "peerId",
    {
        key: 'peerKey',
        debug: 3,
        logFunction: ()=>{
        }
    });

var id = peerByOption.id;
var connections = peerByOption.connections;
var flag = peerByOption.disconnected;
flag = peerByOption.destroyed;

peerByOption.disconnect();
peerByOption.destroy();

var connection = peerById.connect("id", {
    label: 'chat',
    serialization: 'none',
    metadata: {message: 'hi i want to chat with you!'}
});

var call = peerById.call('callto-id', (<any>window).localStream);

var openHandler=()=> console.log("open");
peerById.on("open", openHandler);
peerById.on("connection", (c)=> console.log("connection"));
peerById.on("call", (media)=> console.log("call"));
peerById.on("close", ()=> console.log("close"));
peerById.on("disconnected", ()=> console.log("disconnected"));
peerById.on("error", (err)=> console.log(err));
peerById.off("open", openHandler);


text:
import React from 'react';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';
import { createRefetchContainer, graphql } from 'react-relay';

import UpdateUserMutation from '../mutations/UpdateUser';

const useStyles = makeStyles(theme => ({
  field: {
    '&:not(:last-child)': {
      marginBottom: theme.spacing(1),
    },
  },
}));

function UserSettingsDialog(props) {
  const { me, relay, ...other } = props;
  const [state, setState] = React.useState({ errors: {} });
  const s = useStyles();

  React.useEffect(() => {
    relay.refetch({ mounted: true });
  }, []);

  React.useEffect(() => {
    setState({ ...me, errors: {} });
  }, [JSON.stringify(me)]);

  function handleChange(event) {
    const { name, value } = event.target;
    setState(x => ({ ...x, [name]: value }));
  }

  function handleSubmit(event) {
    event.preventDefault();
    setState(x => (x.errors ? { ...x, errors: {} } : x));

    UpdateUserMutation.commit(
      relay.environment,
      {
        id: state.id,
        displayName: state.displayName,
        email: state.email,
      },
      errors => {
        if (errors) {
          setState(x => ({ ...x, errors }));
        } else {
          props.onClose();
        }
      },
    );
  }

  return (
    <Dialog maxWidth="xs" fullWidth {...other}>
      <DialogTitle>User Settings</DialogTitle>
      <DialogContent>
        <form id="user-settings-form" onSubmit={handleSubmit}>
          <TextField
            className={s.field}
            name="displayName"
            label="Display Name"
            value={state.displayName}
            onChange={handleChange}
            error={Boolean(state.errors.displayName)}
            helperText={
              state.errors.displayName
                ? state.errors.displayName.join(' ')
                : ' '
            }
            InputLabelProps={{ shrink: true }}
            fullWidth
          />
          <TextField
            className={s.field}
            name="email"
            type="email"
            label="Email"
            value={state.email}
            onChange={handleChange}
            error={Boolean(state.errors.email)}
            helperText={state.errors.email ? state.errors.email.join(' ') : ' '}
            InputLabelProps={{ shrink: true }}
            fullWidth
          />
        </form>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.onClose}>Cancel</Button>
        <Button type="submit" form="user-settings-form">
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default createRefetchContainer(
  UserSettingsDialog,
  {
    me: graphql`
      fragment UserSettingsDialog_me on User
        @argumentDefinitions(
          mounted: { type: "Boolean", defaultValue: false }
        ) {
        id
        photoURL @include(if: $mounted)
        displayName @include(if: $mounted)
        email @include(if: $mounted)
      }
    `,
  },
  graphql`
    query UserSettingsDialogQuery($mounted: Boolean!) {
      me {
        ...UserSettingsDialog_me @arguments(mounted: $mounted)
      }
    }
  `,
);


text:
"""
PhyRawIO is a class to handle Phy spike sorting data.
Ported from:
https://github.com/SpikeInterface/spikeextractors/blob/
f20b1219eba9d3330d5d7cd7ce8d8924a255b8c2/spikeextractors/
extractors/phyextractors/phyextractors.py

Author: Regimantas Jurkus
"""

from .baserawio import (BaseRawIO, _signal_channel_dtype, _signal_stream_dtype,
                        _spike_channel_dtype, _event_channel_dtype)

import numpy as np
from pathlib import Path
import re
import csv
import ast
import warnings

class PhyRawIO(BaseRawIO):
    """
    Class for reading Phy data.

    Usage:
        >>> import neo.rawio
        >>> r = neo.rawio.PhyRawIO(dirname='/dir/to/phy/folder')
        >>> r.parse_header()
        >>> print(r)
        >>> spike_timestamp = r.get_spike_timestamps(block_index=0,
        ... seg_index=0, spike_channel_index=0, t_start=None, t_stop=None)
        >>> spike_times = r.rescale_spike_timestamp(spike_timestamp, 'float64')

    """
    extensions = []
    rawmode = 'one-dir'

    def __init__(self, dirname='', load_amplitudes=False, load_pcs=False):
        BaseRawIO.__init__(self)
        self.dirname = dirname
        self.load_pcs = load_pcs
        self.load_amplitudes = load_amplitudes

    def _source_name(self):
        return self.dirname

    def _parse_header(self):
        phy_folder = Path(self.dirname)

        self._spike_times = np.load(phy_folder / 'spike_times.npy')
        self._spike_templates = np.load(phy_folder / 'spike_templates.npy')

        if (phy_folder / 'spike_clusters.npy').is_file():
            self._spike_clusters = np.load(phy_folder / 'spike_clusters.npy')
        else:
            self._spike_clusters = self._spike_templates

        self._amplitudes = None
        if self.load_amplitudes:
            if (phy_folder / 'amplitudes.npy').is_file():
                self._amplitudes = np.squeeze(np.load(phy_folder / 'amplitudes.npy'))
            else:
                warnings.warn('Amplitudes requested but "amplitudes.npy"'
                              'not found in the data folder.')

        self._pc_features = None
        self._pc_feature_ind = None
        if self.load_pcs:
            if ((phy_folder / 'pc_features.npy').is_file()
                    and (phy_folder / 'pc_feature_ind.npy').is_file()):
                self._pc_features = np.squeeze(np.load(phy_folder / 'pc_features.npy'))
                self._pc_feature_ind = np.squeeze(np.load(phy_folder / 'pc_feature_ind.npy'))
            else:
                warnings.warn('PCs requested but "pc_features.npy" and/or'
                              '"pc_feature_ind.npy" not found in the data folder.')

        # SEE: https://stackoverflow.com/questions/4388626/
        #  python-safe-eval-string-to-bool-int-float-none-string
        if (phy_folder / 'params.py').is_file():
            with (phy_folder / 'params.py').open('r') as f:
                contents = f.read()
            metadata = dict()
            contents = contents.replace('\n', ' ')
            pattern = re.compile(r'(\S*)[\s]?=[\s]?(\S*)')
            elements = pattern.findall(contents)
            for key, value in elements:
                metadata[key.lower()] = ast.literal_eval(value)

        self._sampling_frequency = metadata['sample_rate']

        clust_ids = np.unique(self._spike_clusters)
        self.unit_labels = list(clust_ids)

        self._t_start = 0.
        self._t_stop = max(self._spike_times).item() / self._sampling_frequency

        signal_streams = []
        signal_streams = np.array(signal_streams, dtype=_signal_stream_dtype)

        signal_channels = []
        signal_channels = np.array(signal_channels,
                                   dtype=_signal_channel_dtype)

        spike_channels = []
        for i, clust_id in enumerate(clust_ids):
            unit_name = f'unit {clust_id}'
            unit_id = f'{clust_id}'
            wf_units = ''
            wf_gain = 0
            wf_offset = 0.
            wf_left_sweep = 0
            wf_sampling_rate = 0
            spike_channels.append((unit_name, unit_id, wf_units, wf_gain,
                                  wf_offset, wf_left_sweep, wf_sampling_rate))
        spike_channels = np.array(spike_channels, dtype=_spike_channel_dtype)

        event_channels = []
        event_channels = np.array(event_channels, dtype=_event_channel_dtype)

        self.header = {}
        self.header['nb_block'] = 1
        self.header['nb_segment'] = [1]
        self.header['signal_streams'] = signal_streams
        self.header['signal_channels'] = signal_channels
        self.header['spike_channels'] = spike_channels
        self.header['event_channels'] = event_channels

        self._generate_minimal_annotations()

        csv_tsv_files = [x for x in phy_folder.iterdir() if
                         x.suffix == '.csv' or x.suffix == '.tsv']

        # annotation_lists is list of list of dict (python==3.8)
        # or list of list of ordered dict (python==3.6)
        # SEE: https://docs.python.org/3/library/csv.html#csv.DictReader
        annotation_lists = [self._parse_tsv_or_csv_to_list_of_dict(file)
                            for file in csv_tsv_files]

        bl_ann = self.raw_annotations['blocks'][0]
        bl_ann['name'] = "Block #0"
        seg_ann = bl_ann['segments'][0]
        seg_ann['name'] = 'Seg #0 Block #0'
        for index, clust_id in enumerate(clust_ids):
            spiketrain_an = seg_ann['spikes'][index]

            # Add cluster_id annotation
            spiketrain_an['cluster_id'] = clust_id

            # Loop over list of list of dict and annotate each st
            for annotation_list in annotation_lists:
                clust_key, *property_names = tuple(annotation_list[0].keys())
                for property_name in property_names:
                    if property_name == 'KSLabel':
                        annotation_name = 'quality'
                    else:
                        annotation_name = property_name.lower()
                    for annotation_dict in annotation_list:
                        if int(annotation_dict[clust_key]) == clust_id:
                            spiketrain_an[annotation_name] = \
                                annotation_dict[property_name]
                            break

            cluster_mask = (self._spike_clusters == clust_id).flatten()

            current_templates = self._spike_templates[cluster_mask].flatten()
            unique_templates = np.unique(current_templates)
            spiketrain_an['templates'] = unique_templates
            spiketrain_an['__array_annotations__']['templates'] = current_templates

            if self._amplitudes is not None:
                spiketrain_an['__array_annotations__']['amplitudes'] = \
                    self._amplitudes[cluster_mask]

            if self._pc_features is not None:
                current_pc_features = self._pc_features[cluster_mask]
                _, num_pcs, num_pc_channels = current_pc_features.shape
                for pc_idx in range(num_pcs):
                    for channel_idx in range(num_pc_channels):
                        key = 'channel{channel_idx}_pc{pc_idx}'.format(channel_idx=channel_idx,
                                                                       pc_idx=pc_idx)
                        spiketrain_an['__array_annotations__'][key] = \
                                current_pc_features[:, pc_idx, channel_idx]

            if self._pc_feature_ind is not None:
                spiketrain_an['pc_feature_ind'] = self._pc_feature_ind[unique_templates]

    def _segment_t_start(self, block_index, seg_index):
        assert block_index == 0
        return self._t_start

    def _segment_t_stop(self, block_index, seg_index):
        assert block_index == 0
        return self._t_stop

    def _get_signal_size(self, block_index, seg_index, channel_indexes=None):
        return None

    def _get_signal_t_start(self, block_index, seg_index, channel_indexes):
        return None

    def _get_analogsignal_chunk(self, block_index, seg_index, i_start, i_stop,
                                channel_indexes):
        return None

    def _spike_count(self, block_index, seg_index, spike_channel_index):
        assert block_index == 0
        spikes = self._spike_clusters
        unit_label = self.unit_labels[spike_channel_index]
        mask = spikes == unit_label
        nb_spikes = np.sum(mask)
        return nb_spikes

    def _get_spike_timestamps(self, block_index, seg_index,
                              spike_channel_index, t_start, t_stop):
        assert block_index == 0
        assert seg_index == 0

        unit_label = self.unit_labels[spike_channel_index]
        mask = self._spike_clusters == unit_label
        spike_timestamps = self._spike_times[mask]

        if t_start is not None:
            start_frame = int(t_start * self._sampling_frequency)
            spike_timestamps = \
                spike_timestamps[spike_timestamps >= start_frame]
        if t_stop is not None:
            end_frame = int(t_stop * self._sampling_frequency)
            spike_timestamps = spike_timestamps[spike_timestamps < end_frame]

        return spike_timestamps

    def _rescale_spike_timestamp(self, spike_timestamps, dtype):
        spike_times = spike_timestamps.astype(dtype)
        spike_times /= self._sampling_frequency
        return spike_times

    def _get_spike_raw_waveforms(self, block_index, seg_index,
                                 spike_channel_index, t_start, t_stop):
        return None

    def _event_count(self, block_index, seg_index, event_channel_index):
        return None

    def _get_event_timestamps(self, block_index, seg_index,
                              event_channel_index, t_start, t_stop):
        return None

    def _rescale_event_timestamp(self, event_timestamps, dtype):
        return None

    def _rescale_epoch_duration(self, raw_duration, dtype):
        return None

    @staticmethod
    def _parse_tsv_or_csv_to_list_of_dict(filename):
        list_of_dict = list()
        letter_pattern = re.compile('[a-zA-Z]')
        float_pattern = re.compile(r'-?\d*\.')
        with open(filename) as csvfile:
            if filename.suffix == '.csv':
                reader = csv.DictReader(csvfile, delimiter=',')
            elif filename.suffix == '.tsv':
                reader = csv.DictReader(csvfile, delimiter='\t')
            else:
                raise ValueError("Function parses only .csv or .tsv files")
            line = 0

            for row in reader:
                if line == 0:
                    cluster_id_key, *annotation_keys = tuple(row.keys())
                # Convert cluster ID to int
                row[cluster_id_key] = int(row[cluster_id_key])
                # Convert strings without letters
                for key in annotation_keys:
                    value = row[key]
                    if not len(value):
                        row[key] = None
                    elif letter_pattern.match(value) is None:
                        if float_pattern.match(value) is None:
                            row[key] = int(value)
                        else:
                            row[key] = float(value)

                list_of_dict.append(row)
                line += 1

        return list_of_dict


text:
/**************************************************************************//**
 * @file     scuart.c
 * @brief    N9H30 series Smartcard UART mode (SCUART) driver source file
 *
 * @note
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (C) 2018 Nuvoton Technology Corp. All rights reserved.
*****************************************************************************/
#include "N9H30.h"
#include "nu_scuart.h"

/** @addtogroup N9H30_Device_Driver N9H30 Device Driver
  @{
*/

/** @addtogroup N9H30_SCUART_Driver SCUART Driver
  @{
*/

/** @addtogroup N9H30_SCUART_EXPORTED_FUNCTIONS SCUART Exported Functions
  @{
*/

/**
  * @brief Disable smartcard uart interface.
  * @param sc Smartcard module number
  * @return None
  * @details The function is used to disable smartcard interface UART mode.
  */
void SCUART_Close(UINT sc)
{
    if (sc == 0)
    {
        outpw(REG_SC0_INTEN, 0);
        outpw(REG_SC0_UARTCTL, 0);
        outpw(REG_SC0_CTL, 0);
    }
    else
    {
        outpw(REG_SC1_INTEN, 0);
        outpw(REG_SC1_UARTCTL, 0);
        outpw(REG_SC1_CTL, 0);
    }
}

/// @cond HIDDEN_SYMBOLS
/**
  * @brief This function returns module clock of specified SC interface
  * @param[in] sc Smartcard module number
  * @return Module clock of specified SC interface
  */
static uint32_t SCUART_GetClock(UINT sc)
{
    uint32_t u32Div;

    if (sc == 0)
        u32Div = ((inpw(REG_CLK_DIVCTL6) >> 24) & 0xF) + 1;
    else
        u32Div = ((inpw(REG_CLK_DIVCTL6) >> 28) & 0xF) + 1;

    return 12000000 / u32Div;
}
/// @endcond HIDDEN_SYMBOLS

/**
  * @brief Enable smartcard uart interface.
  * @param[in] sc Smartcard module number
  * @param[in] u32baudrate Target baudrate of smartcard module.
  * @return Actual baudrate of smartcard mode.
  * @details This function use to enable smartcard module UART mode and set baudrate.
  * @note This function configures character width to 8 bits, 1 stop bit, and no parity.
  *       And can use \ref SCUART_SetLineConfig function to update these settings.
  */
UINT SCUART_Open(UINT sc, UINT u32baudrate)
{
    uint32_t u32Clk = SCUART_GetClock(sc), u32Div;

    // Calculate divider for target baudrate
    u32Div = (u32Clk + (u32baudrate >> 1) - 1) / u32baudrate - 1;

    if (sc == 0)
    {
        outpw(REG_SC0_CTL, SC_CTL_SCEN_Msk | SC_CTL_NSB_Msk);   // Enable smartcard interface and stop bit = 1
        outpw(REG_SC0_UARTCTL, SCUART_CHAR_LEN_8 | SCUART_PARITY_NONE | SC_UARTCTL_UARTEN_Msk); // Enable UART mode, disable parity and 8 bit per character
        outpw(REG_SC0_ETUCTL, u32Div);
    }
    else
    {
        outpw(REG_SC1_CTL, SC_CTL_SCEN_Msk | SC_CTL_NSB_Msk);   // Enable smartcard interface and stop bit = 1
        outpw(REG_SC1_UARTCTL, SCUART_CHAR_LEN_8 | SCUART_PARITY_NONE | SC_UARTCTL_UARTEN_Msk); // Enable UART mode, disable parity and 8 bit per character
        outpw(REG_SC1_ETUCTL, u32Div);
    }

    return (u32Clk / (u32Div + 1));
}

/**
  * @brief Read data from smartcard UART interface.
  * @param[in] sc Smartcard module number
  * @param[in] pu8RxBuf The buffer to store receive the data.
  * @param[in] u32ReadBytes Target number of characters to receive.
  * @return Actual character number reads to buffer.
  * @details The function is used to read Rx data from RX FIFO.
  * @note This function does not block and return immediately if there's no data available.
  */
UINT SCUART_Read(UINT sc, char *pu8RxBuf, UINT u32ReadBytes)
{
    uint32_t u32Count;

    if (sc == 0)
    {
        for (u32Count = 0; u32Count < u32ReadBytes; u32Count++)
        {
            if (inpw(REG_SC0_STATUS) & SC_STATUS_RXEMPTY_Msk)  // no data available
            {
                break;
            }
            pu8RxBuf[u32Count] = inpw(REG_SC0_DAT);    // get data from FIFO
        }
    }
    else
    {
        for (u32Count = 0; u32Count < u32ReadBytes; u32Count++)
        {
            if (inpw(REG_SC1_STATUS) & SC_STATUS_RXEMPTY_Msk)  // no data available
            {
                break;
            }
            pu8RxBuf[u32Count] = inpw(REG_SC1_DAT);    // get data from FIFO
        }

    }

    return u32Count;
}

/**
  * @brief This function use to config smartcard UART mode line setting.
  * @param[in] sc Smartcard module number
  * @param[in] u32Baudrate Target baudrate of smartcard module. If this value is 0, UART baudrate will not change.
  * @param[in] u32DataWidth The data length, could be:
  *                 - \ref SCUART_CHAR_LEN_5
  *                 - \ref SCUART_CHAR_LEN_6
  *                 - \ref SCUART_CHAR_LEN_7
  *                 - \ref SCUART_CHAR_LEN_8
  * @param[in] u32Parity The parity setting, could be:
  *                 - \ref SCUART_PARITY_NONE
  *                 - \ref SCUART_PARITY_ODD
  *                 - \ref SCUART_PARITY_EVEN
  * @param[in] u32StopBits The stop bit length, could be:
  *                 - \ref SCUART_STOP_BIT_1
  *                 - \ref SCUART_STOP_BIT_2
  * @return Actual baudrate of smartcard.
  * @details Smartcard UART mode is operated in LIN data frame.
  */
UINT SCUART_SetLineConfig(UINT sc, UINT u32Baudrate, UINT u32DataWidth, UINT u32Parity, UINT  u32StopBits)
{

    uint32_t u32Clk = SCUART_GetClock(sc), u32Div;

    if (u32Baudrate == 0)   // keep original baudrate setting
    {
        u32Div = (sc == 0) ? inpw(REG_SC0_ETUCTL) & 0xFFF : inpw(REG_SC1_ETUCTL) & 0xFFF;
    }
    else
    {
        // Calculate divider for target baudrate
        u32Div = (u32Clk + (u32Baudrate >> 1) - 1) / u32Baudrate - 1;
        if (sc == 0)
            outpw(REG_SC0_ETUCTL, u32Div);
        else
            outpw(REG_SC1_ETUCTL, u32Div);
    }

    if (sc == 0)
    {
        outpw(REG_SC0_CTL, u32StopBits | SC_CTL_SCEN_Msk);  // Set stop bit
        outpw(REG_SC0_UARTCTL, u32Parity | u32DataWidth | SC_UARTCTL_UARTEN_Msk);   // Set character width and parity
    }
    else
    {
        outpw(REG_SC1_CTL, u32StopBits | SC_CTL_SCEN_Msk);  // Set stop bit
        outpw(REG_SC1_UARTCTL, u32Parity | u32DataWidth | SC_UARTCTL_UARTEN_Msk);   // Set character width and parity
    }
    return (u32Clk / (u32Div + 1));
}

/**
  * @brief This function use to set receive timeout count.
  * @param[in] sc Smartcard module number
  * @param[in] u32TOC Rx timeout counter, using baudrate as counter unit. Valid range are 0~0x1FF,
  *                   set this value to 0 will disable timeout counter.
  * @return None
  * @details The time-out counter resets and starts counting whenever the RX buffer received a
  *          new data word. Once the counter decrease to 1 and no new data is received or CPU
  *          does not read any data from FIFO, a receiver time-out interrupt will be generated.
  */
void SCUART_SetTimeoutCnt(UINT sc, UINT u32TOC)
{
    if (sc == 0)
        outpw(REG_SC0_RXTOUT, u32TOC);
    else
        outpw(REG_SC1_RXTOUT, u32TOC);
}

/**
  * @brief Write data to smartcard UART interface.
  * @param[in] sc Smartcard module number
  * @param[in] pu8TxBuf The buffer containing data to send to transmit FIFO.
  * @param[in] u32WriteBytes Number of data to send.
  * @return None
  * @details This function is to write data into transmit FIFO to send data out.
  * @note This function blocks until all data write into FIFO.
  */
void SCUART_Write(UINT sc, char *pu8TxBuf, UINT u32WriteBytes)
{
    uint32_t u32Count;

    if (sc == 0)
    {
        for (u32Count = 0; u32Count != u32WriteBytes; u32Count++)
        {
            while (inpw(REG_SC0_STATUS) & SC_STATUS_TXFULL_Msk); // Wait 'til FIFO not full
            outpw(REG_SC0_DAT, pu8TxBuf[u32Count]);    // Write 1 byte to FIFO
        }
    }
    else
    {
        for (u32Count = 0; u32Count != u32WriteBytes; u32Count++)
        {
            while (inpw(REG_SC0_STATUS) & SC_STATUS_TXFULL_Msk); // Wait 'til FIFO not full
            outpw(REG_SC1_DAT, pu8TxBuf[u32Count]);    // Write 1 byte to FIFO
        }
    }
}

/*@}*/ /* end of group N9H30_SCUART_EXPORTED_FUNCTIONS */

/*@}*/ /* end of group N9H30_SCUART_Driver */

/*@}*/ /* end of group N9H30_Device_Driver */

/*** (C) COPYRIGHT 2018 Nuvoton Technology Corp. ***/


text:
from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app  # noqa

__version__ = '0.1.0'
__version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')])


text:
package org.apache.camel.opentelemetry;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

public class ClientRecipientListRouteTest extends CamelOpenTelemetryTestSupport {

    private static SpanTestData[] testdata = {
            new SpanTestData().setLabel("seda:a server").setUri("seda://a").setOperation("a")
                    .setParentId(3),
            new SpanTestData().setLabel("seda:b server").setUri("seda://b").setOperation("b")
                    .setParentId(3),
            new SpanTestData().setLabel("seda:c server").setUri("seda://c").setOperation("c")
                    .setParentId(3),
            new SpanTestData().setLabel("direct:start server").setUri("direct://start").setOperation("start")
    };

    public ClientRecipientListRouteTest() {
        super(testdata);
    }

    @Test
    public void testRoute() throws Exception {
        template.requestBody("direct:start", "Hello");

        verify();
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").recipientList(constant("seda:a,seda:b,seda:c")).routeId("start");

                from("seda:a").routeId("a")
                        .log("routing at ${routeId}");

                from("seda:b").routeId("b")
                        .log("routing at ${routeId}")
                        .delay(simple("${random(1000,2000)}"));

                from("seda:c").routeId("c")
                        .log("routing at ${routeId}")
                        .delay(simple("${random(0,100)}"));
            }
        };
    }
}


text:
package at.ac.tuwien.dbai.pdfwrap.operator;

import at.ac.tuwien.dbai.pdfwrap.pdfread.PDFObjectExtractor;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.util.PDFOperator;

import java.awt.*;
import java.io.IOException;
import java.util.List;

/**
 * Implementation of content stream operator for PDFObjectExtractor.
 *
 * Adapted from PDFBox code
 * @author Ben Litchfield, ben@benlitchfield.com
 * @author Tamir Hassan, pdfanalyser@tamirhassan.com
 * @version PDF Analyser 0.9
 */
public class SetStrokingRGBColor extends org.apache.pdfbox.util.operator.SetStrokingRGBColor
{
    /**
     * RG Set color space for stroking operations.
      The operator that is being executed.
      List
      If an error occurs while processing the font.
     */
    public void process(PDFOperator operator, List arguments) throws IOException
    {
        super.process( operator, arguments );
        PDFObjectExtractor drawer = (PDFObjectExtractor)context;
        COSNumber r = (COSNumber)arguments.get( 0 );
        COSNumber g = (COSNumber)arguments.get( 1 );
        COSNumber b = (COSNumber)arguments.get( 2 );
        drawer.setStrokingColor( new Color( r.floatValue(), g.floatValue(), b.floatValue() ) );
    }
}


text:
require_relative '../../spec_helper'
require_relative 'shared/to_i'
require_relative 'shared/integer_rounding'

describe "Integer#round" do
  it_behaves_like :integer_to_i, :round
  it_behaves_like :integer_rounding_positive_precision, :round

  ruby_version_is ""..."2.5" do # Not just since 2.4
    it "rounds itself as a float if passed a positive precision" do
      [2, -4, 10**70, -10**100].each do |v|
        v.round(42).should eql(v.to_f)
      end
    end
  end

  # redmine:5228
  it "returns itself rounded if passed a negative value" do
    +249.round(-2).should eql(+200)
    -249.round(-2).should eql(-200)
    (+25 * 10**70 - 1).round(-71).should eql(+20 * 10**70)
    (-25 * 10**70 + 1).round(-71).should eql(-20 * 10**70)
  end

  it "returns itself rounded to nearest if passed a negative value" do
    +250.round(-2).should eql(+300)
    -250.round(-2).should eql(-300)
    (+25 * 10**70).round(-71).should eql(+30 * 10**70)
    (-25 * 10**70).round(-71).should eql(-30 * 10**70)
  end

  platform_is_not wordsize: 32 do
    it "raises a RangeError when passed a big negative value" do
      -> { 42.round(fixnum_min) }.should raise_error(RangeError)
    end
  end

  it "raises a RangeError when passed Float::INFINITY" do
    -> { 42.round(Float::INFINITY) }.should raise_error(RangeError)
  end

  it "raises a RangeError when passed a beyond signed int" do
    -> { 42.round(1<<31) }.should raise_error(RangeError)
  end

  it "raises a TypeError when passed a String" do
    -> { 42.round("4") }.should raise_error(TypeError)
  end

  it "raises a TypeError when its argument cannot be converted to an Integer" do
    -> { 42.round(nil) }.should raise_error(TypeError)
  end

  it "calls #to_int on the argument to convert it to an Integer" do
    obj = mock("Object")
    obj.should_receive(:to_int).and_return(0)
    42.round(obj)
  end

  it "raises a TypeError when #to_int does not return an Integer" do
    obj = mock("Object")
    obj.stub!(:to_int).and_return([])
    -> { 42.round(obj) }.should raise_error(TypeError)
  end

  it "returns different rounded values depending on the half option" do
    25.round(-1, half: :up).should      eql(30)
    25.round(-1, half: :down).should    eql(20)
    25.round(-1, half: :even).should    eql(20)
    25.round(-1, half: nil).should      eql(30)
    35.round(-1, half: :up).should      eql(40)
    35.round(-1, half: :down).should    eql(30)
    35.round(-1, half: :even).should    eql(40)
    35.round(-1, half: nil).should      eql(40)
    (-25).round(-1, half: :up).should   eql(-30)
    (-25).round(-1, half: :down).should eql(-20)
    (-25).round(-1, half: :even).should eql(-20)
    (-25).round(-1, half: nil).should   eql(-30)
  end

  ruby_version_is "2.4"..."2.5" do
    it "returns itself as a float if passed a positive precision and the half option" do
      35.round(1, half: :up).should      eql(35.0)
      35.round(1, half: :down).should    eql(35.0)
      35.round(1, half: :even).should    eql(35.0)
    end
  end

  ruby_version_is "2.5" do
    it "returns itself if passed a positive precision and the half option" do
      35.round(1, half: :up).should      eql(35)
      35.round(1, half: :down).should    eql(35)
      35.round(1, half: :even).should    eql(35)
    end
  end

  it "raises ArgumentError for an unknown rounding mode" do
    -> { 42.round(-1, half: :foo) }.should raise_error(ArgumentError, /invalid rounding mode: foo/)
    -> { 42.round(1, half: :foo) }.should raise_error(ArgumentError, /invalid rounding mode: foo/)
  end
end


text:
<?php

namespace Rhubarb\Leaf\Table\Examples\BasicUsage;

use Rhubarb\Leaf\Leaves\Leaf;

class CellFormatting extends Leaf
{
    /** @var CellFormattingModel $model **/
    protected $model;

    protected function getViewClass()
    {
        return CellFormattingView::class;
    }

    protected function createModel()
    {
        return new CellFormattingModel();
    }
}