text:
import requests

from .models import *
from .endpoints import *
from .errors import *

from functools import partial
from json import dumps
import os
import binascii

class API(object):

    def __init__(self, username=None, password=None, device_token=None, DEBUG=False):
        self.username = username
        self.password = password
        self._session_id = None
        self.DEBUG = DEBUG
        self.device_token = device_token or binascii.b2a_hex(os.urandom(32))

        self._make_dynamic_methods()

        if self.username and self.password:
            self.user = self.login(
                username=username, password=password, device_token=self.device_token)

    def _make_dynamic_methods(self):
        for endpoint in list(ENDPOINTS.keys()):
            def _inner(endpoint, *args, **kwargs):
                return self.api_call(endpoint, *args, **kwargs)
            _inner.__name__ = endpoint
            setattr(self, _inner.__name__, partial(_inner, endpoint))

    def build_request_url(self, protocol, host, endpoint):
        url = '%s://%s/%s' % (protocol, host, endpoint)
        # encode url params
        return url

    def api_call(self, endpoint, *args, **kwargs):
        metadata = ENDPOINTS[endpoint]

        params = self.check_params(metadata, kwargs)

        response = self.do_request(metadata, params)

        if metadata['model'] is None:
            return response
        else:
            model = metadata['model'].from_json(response)
            model.connect_api(self)
            return model

    def check_params(self, metadata, kwargs):
        missing_params = []
        url_params = []

        # page, size and anchor are data_params for get requests

        for param in metadata['url_params']:
            p = kwargs.get(param)
            if p is None:
                missing_params.append(param)
            else:
                url_params.append(p)
                del kwargs[param]
        if missing_params:
            raise ParameterError(
                'Missing URL parameters: [%s]' % ', '.join(missing_params))

        # url_params shouldnt have default params, I guess
        data_params = kwargs
        if metadata.get('default_params', []) != []:
            default_params = dict(metadata['default_params'])
            data_params = dict(list(default_params.items()) + list(kwargs.items()))

        missing_params = []
        for param in metadata['required_params']:
            p = data_params.get(param)
            if p is None:
                missing_params.append(param)
        if missing_params:
            raise ParameterError(
                'Missing required parameters: [%s]' % ', '.join(missing_params))

        # Check for unsupported params?

        return {'url': url_params, 'data': data_params}

    def do_request(self, metadata, params):
        headers = HEADERS.copy()
        if params['url'] != []:
            endpoint = metadata['endpoint'] % tuple(params['url'])
        else:
            endpoint = metadata['endpoint']

        host = API_HOST
        # Upload methods, change host to specific host
        if metadata.get('host'):
            host = metadata['host']

        url = self.build_request_url(PROTOCOL, host, endpoint)

        built_params = built_data = None
        built_data = data = params['data']

        if metadata['request_type'] == 'get':
            built_params = data
        elif metadata['request_type'] == 'post':
            if metadata.get('json'):
                built_data = dumps(data)
                headers['Content-Type'] = 'application/json; charset=utf-8'
        elif data.get('filename'):
            if data['filename'].split('.')[-1] == 'mp4':
                headers['Content-Type'] = 'video/mp4'
            else:
                headers['Content-Type'] = 'image/jpeg'
            built_data = open(data['filename'], 'rb')

        if self._session_id:
            headers['vine-session-id'] = self._session_id

        if(self.DEBUG):
            # pip install mitmproxy
            # mitmproxy
            http_proxy = "http://localhost:8080"
            https_proxy = "http://localhost:8080"

            proxies = {
                "http": http_proxy,
                "https": https_proxy,
            }

            # cafile='~/.mitmproxy/mitmproxy-ca-cert.pem'
            cafile = False
            response = requests.request(
                metadata['request_type'], url, params=built_params, data=built_data, headers=headers, verify=cafile, proxies=proxies)
            print('REQUESTED: %s [%s]' % (url, response.status_code))
        else:
            response = requests.request(
                metadata['request_type'], url, params=built_params, data=built_data, headers=headers)

        if response.headers.get('X-Upload-Key'):
            return response.headers['X-Upload-Key']

        if response.status_code in [200, 400, 404, 420]:
            try:
                json = response.json()
            except:
                raise VineError(
                    1000, 'Vine replied with non-json content:\n' + response.text)

            if json['success'] is not True:
                raise VineError(json['code'], json['error'])
            return json['data']
        else:
            raise VineError(response.status_code, response.text)

    def authenticate(self, user):
        self.user = user
        self._session_id = user.key
        self._user_id = user.id


text:
/* globals RocketChatFileEmojiCustomInstance */
Meteor.methods({
	insertOrUpdateEmoji(emojiData) {
		if (!RocketChat.authz.hasPermission(this.userId, 'manage-emoji')) {
			throw new Meteor.Error('not_authorized');
		}

		if (!s.trim(emojiData.name)) {
			throw new Meteor.Error('error-the-field-is-required', 'The field Name is required', { method: 'insertOrUpdateEmoji', field: 'Name' });
		}

		//let nameValidation = new RegExp('^[0-9a-zA-Z-_+;.]+$');
		//let aliasValidation = new RegExp('^[0-9a-zA-Z-_+;., ]+$');

		//allow all characters except colon, whitespace, comma, >, <, &, ", ', /, \, (, )
		//more practical than allowing specific sets of characters; also allows foreign languages
		const nameValidation = /[\s,:><&"'\/\\\(\)]/;
		const aliasValidation = /[:><&"'\/\\\(\)]/;

		//silently strip colon; this allows for uploading :emojiname: as emojiname
		emojiData.name = emojiData.name.replace(/:/g, '');
		emojiData.aliases = emojiData.aliases.replace(/:/g, '');

		if (nameValidation.test(emojiData.name)) {
			throw new Meteor.Error('error-input-is-not-a-valid-field', `${ emojiData.name } is not a valid name`, { method: 'insertOrUpdateEmoji', input: emojiData.name, field: 'Name' });
		}

		if (emojiData.aliases) {
			if (aliasValidation.test(emojiData.aliases)) {
				throw new Meteor.Error('error-input-is-not-a-valid-field', `${ emojiData.aliases } is not a valid alias set`, { method: 'insertOrUpdateEmoji', input: emojiData.aliases, field: 'Alias_Set' });
			}
			emojiData.aliases = emojiData.aliases.split(/[\s,]/);
			emojiData.aliases = emojiData.aliases.filter(Boolean);
			emojiData.aliases = _.without(emojiData.aliases, emojiData.name);
		} else {
			emojiData.aliases = [];
		}

		let matchingResults = [];

		if (emojiData._id) {
			matchingResults = RocketChat.models.EmojiCustom.findByNameOrAliasExceptID(emojiData.name, emojiData._id).fetch();
			for (const alias of emojiData.aliases) {
				matchingResults = matchingResults.concat(RocketChat.models.EmojiCustom.findByNameOrAliasExceptID(alias, emojiData._id).fetch());
			}
		} else {
			matchingResults = RocketChat.models.EmojiCustom.findByNameOrAlias(emojiData.name).fetch();
			for (const alias of emojiData.aliases) {
				matchingResults = matchingResults.concat(RocketChat.models.EmojiCustom.findByNameOrAlias(alias).fetch());
			}
		}

		if (matchingResults.length > 0) {
			throw new Meteor.Error('Custom_Emoji_Error_Name_Or_Alias_Already_In_Use', 'The custom emoji or one of its aliases is already in use', { method: 'insertOrUpdateEmoji' });
		}

		if (!emojiData._id) {
			//insert emoji
			const createEmoji = {
				name: emojiData.name,
				aliases: emojiData.aliases,
				extension: emojiData.extension
			};

			const _id = RocketChat.models.EmojiCustom.create(createEmoji);

			RocketChat.Notifications.notifyLogged('updateEmojiCustom', {emojiData: createEmoji});

			return _id;
		} else {
			//update emoji
			if (emojiData.newFile) {
				RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`));
				RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.previousExtension }`));
				RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.extension }`));
				RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`));

				RocketChat.models.EmojiCustom.setExtension(emojiData._id, emojiData.extension);
			} else if (emojiData.name !== emojiData.previousName) {
				const rs = RocketChatFileEmojiCustomInstance.getFileWithReadStream(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`));
				if (rs !== null) {
					RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`));
					const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${ emojiData.name }.${ emojiData.previousExtension }`), rs.contentType);
					ws.on('end', Meteor.bindEnvironment(() =>
						RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`))
						));
					rs.readStream.pipe(ws);
				}
			}

			if (emojiData.name !== emojiData.previousName) {
				RocketChat.models.EmojiCustom.setName(emojiData._id, emojiData.name);
			}

			if (emojiData.aliases) {
				RocketChat.models.EmojiCustom.setAliases(emojiData._id, emojiData.aliases);
			} else {
				RocketChat.models.EmojiCustom.setAliases(emojiData._id, []);
			}

			RocketChat.Notifications.notifyLogged('updateEmojiCustom', {emojiData});

			return true;
		}
	}
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ZFTestApigilityDb\EventListener;

use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use ZF\Apigility\Doctrine\Server\Event\DoctrineResourceEvent;

class ArtistAggregateListener implements ListenerAggregateInterface
{
    protected $listeners = [];

    public function attach(EventManagerInterface $events, $priority = 1)
    {
        $this->listeners[] = $events->attach(
            DoctrineResourceEvent::EVENT_CREATE_POST,
            [$this, 'createPost']
        );
    }

    public function createPost(DoctrineResourceEvent $event)
    {
        $objectManager = $event->getObjectManager();

        $event->getEntity();
        $event->getData();
        $event->getResourceEvent();
        $event->getEntityClassName();
        $event->getEntityId();
    }

    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            if ($events->detach($listener)) {
                unset($this->listeners[$index]);
            }
        }
    }
}


text:
package ru.agolovin;

import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;

/**
 * @param <T> Generic
 * @param <V> Generic
 * @author agolovin (agolovin@list.ru)
 * @version $Id$
 * @since 0.1
 */

public class MyMap<T, V> implements Iterable<V> {

    /**
     * Map capacity.
     */
    private static final int CAPACITY = 64;
    /**
     * node array.
     */
    private Node<T, V>[] nodes;

    /**
     * Array size.
     */
    private int size = 0;

    /**
     * Constructor.
     */
    MyMap() {
        this.nodes = new Node[CAPACITY];
    }

    /**
     * Insert element in the map.
     *
     * @param key   Generic
     * @param value Generic
     * @return boolean result
     */
    boolean insert(T key, V value) {
        boolean result = false;
        int hashKey = hash(key);
        int pos = getPosition(hashKey, nodes.length);
        if (nodes[pos] == null) {
            nodes[pos] = new Node<>(hashKey, key, value, null);
            size++;
            result = true;
        } else {
            Node<T, V> temp = nodes[pos];
            if (key.equals(temp.getKey())) {
                temp.setValue(value);
                result = true;
            }
        }
        return result;
    }

    /**
     * Get value from map by key.
     *
     * @param key generic
     * @return value generic
     */
    V get(T key) {
        V result = null;
        int hash = hash(key);
        int pos = getPosition(hash, nodes.length);
        if (nodes[pos] != null) {
            result = nodes[pos].getValue();
        }
        return result;
    }

    /**
     * delete element from map.
     *
     * @param key Generic
     * @return boolean result
     */
    boolean delete(T key) {
        boolean result = false;
        int hashKey = hash(key);
        Node<T, V> p;
        Node<T, V> node = null;
        p = this.nodes[getPosition(hashKey, this.nodes.length)];
        if (this.nodes.length > 0 && p != null) {
            if (p.hash == hashKey && (p.key == key || (key != null && key.equals(p.key)))) {
                node = p;
            }
        }
        if (node != null) {
            this.nodes[getPosition(hashKey, this.nodes.length)] = node.next;
            --size;
            result = true;
        }
        return result;
    }

    /**
     * Generate hash for map.
     *
     * @param key Generic
     * @return int hash
     */
    private int hash(Object key) {
        int h = key.hashCode();
        return h ^ (h >>> 16);
    }

    /**
     * Get position to insert.
     *
     * @param hashValue int
     * @param length    int
     * @return position int
     */
    private int getPosition(int hashValue, int length) {
        return (length - 1) & hashValue;
    }

    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {

            private int nextIndex = 0;

            @Override
            public boolean hasNext() {
                boolean has = false;
                int position = nextIndex;
                while (!has && position < nodes.length) {
                    if (nodes[position] != null) {
                        has = true;
                    } else {
                        position++;
                    }
                }
                return has;
            }

            @Override
            public V next() {
                Node<T, V> nextEntry = null;
                for (int i = nextIndex; i < nodes.length; i++) {
                    Node<T, V> element = nodes[i];
                    if (element != null) {
                        nextEntry = element;
                        nextIndex = i + 1;
                        break;
                    }
                }
                if (nextEntry == null) {
                    throw new NoSuchElementException();
                }
                return nextEntry.getValue();
            }
        };
    }

    /**
     * Node.
     *
     * @param <H> generic
     * @param <L> generic
     */
    static class Node<H, L> implements Map.Entry<H, L> {

        /**
         * Next node.
         */
        private Node<H, L> next;

        /**
         * temp key.
         */
        private H key;

        /**
         * temp value.
         */
        private L value;

        /**
         * int hash.
         */
        private int hash;

        /**
         * Constructor.
         *
         * @param hash  int
         * @param key   int
         * @param value int
         * @param next  node
         */
        Node(int hash, H key, L value, Node<H, L> next) {
            this.next = next;
            this.key = key;
            this.value = value;
            this.hash = hash;
        }

        /**
         * Get next node.
         *
         * @return next node
         */
        Node<H, L> getNext() {
            return this.next;
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Node<H, L> node = (Node<H, L>) o;
            return hash == node.hash
                    && Objects.equals(key, node.key)
                    && Objects.equals(value, node.value);
        }

        @Override
        public H getKey() {
            return this.key;
        }

        @Override
        public L setValue(L value) {
            this.value = value;
            return this.value;
        }

        @Override
        public L getValue() {
            return this.value;
        }
    }
}


text:
module.exports = function(grunt) {
  'use strict';

  var buildFn = function(env) {
    if (!this.data.tasks) {
      grunt.log.error('You must provide a \'tasks\' property');
      return false;
    }

    switch (grunt.util.kindOf(this.data.tasks)) {
      case 'string':
      case 'array':
        grunt.task.run(this.data.tasks);
        break;
      default:
        grunt.log.error('\'tasks\' property must be of type Array or String');
        return false;
    }
  }

  grunt.registerMultiTask(
    'build-base',
    'Build all the base files.',
    buildFn
  );
  grunt.registerMultiTask(
    'build-jade',
    'Build jade files and templates.',
    buildFn
  );
}


text:
#import "NSEnumerator.h"

@class NSMutableArray;

@interface _MFMailboxUidEnumerator : NSEnumerator
{
    NSMutableArray *_mailboxes;
    unsigned long long _index;
}

- (id)nextObject;
- (id)initWithMailbox:(id)arg1;
- (void)dealloc;

@end


text:
package com.winprocom.coolweather.gson;

/**
 * Created by liuzq on 2017/3/22.
 */
public class AQI {
    public AQICity city;

    public class AQICity {
        public String aqi;
        public String pm25;
    }
}


text:
package task

import (
	"testing"

	"context"
	"errors"
	"time"
)

type testTask struct {
	done   context.CancelFunc
	test   string
	result bool
	wait   time.Duration
}

func (tt *testTask) Key() string {
	return "test"
}

func (tt *testTask) Err() error {
	if tt.result {
		return nil
	}
	return errors.New(tt.test)
}

func (tt *testTask) Do(ctx context.Context) error {
	if tt.done != nil {
		defer tt.done()
	}
	wait := tt.wait
	if wait == 0 {
		<-time.After(time.Second)
	} else {
		<-time.After(wait)
	}
	return tt.Err()
}

func TestBaseAsyncTasker_AddTask(t *testing.T) {
	at := NewTaskService()
	at.Run()
	<-at.Ready()
	defer at.Stop()

	ctx, cancel := context.WithCancel(context.Background())
	err := at.Add(ctx, nil)
	if err == nil {
		t.Fatalf("add nil task should be error")
	}
	cancel()

	testCtx1, testC1 := context.WithCancel(context.Background())
	err = at.Add(testCtx1, &testTask{
		done: testC1,
		test: "test1",
	})
	if testCtx1.Err() == nil || err == nil || err.Error() != "test1" {
		t.Fatalf("first time add task should be sync")
	}
	lt, _ := at.LatestHandled("test")
	if lt.Err().Error() != "test1" {
		t.Fatalf("should get first handled task 'test1'")
	}

	testCtx2, testC2 := context.WithTimeout(context.Background(), 3*time.Second)
	err = at.Add(testCtx2, &testTask{
		done: testC2,
		test: "test2",
	})
	if err.Error() != "test1" {
		t.Fatalf("second time add task should return prev result")
	}
	<-testCtx2.Done()
	// pkg/task/executor.go:53
	<-time.After(time.Millisecond)
	lt, _ = at.LatestHandled("test")
	if lt.Err().Error() != "test2" {
		t.Fatalf("should get second handled task 'test2'")
	}
}

func TestBaseAsyncTasker_Stop(t *testing.T) {
	at := NewTaskService()
	at.Stop()
	at.Run()

	_, cancel := context.WithCancel(context.Background())
	err := at.Add(context.Background(), &testTask{
		done:   cancel,
		test:   "test stop",
		result: true,
	})
	if err != nil {
		t.Fatalf("add task should be ok")
	}
	_, cancel = context.WithCancel(context.Background())
	err = at.Add(context.Background(), &testTask{
		done:   cancel,
		test:   "test stop",
		wait:   3 * time.Second,
		result: true,
	})
	if err != nil {
		t.Fatalf("add task should be ok")
	}
	<-time.After(time.Second)
	at.Stop()

	err = at.Add(context.Background(), &testTask{result: true})
	if err != nil {
		t.Fatalf("add task should be ok when Tasker is stopped")
	}

	at.Stop()
}


text:
		Section

{{section.name}}

		Day

{{section.day}}

		Start Time

{{section.start | date: 'shortTime'}}

		End Time

{{section.end | date: 'shortTime'}}

			Posted on

			by


text:
package jsyntaxpane.util;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Don't we all need one of those?
 *
 * @author Ayman Al-Sairafi
 */
public class StringUtils {

    /**
     * Perfrom a String startsWith match with support for CamelCase.
     * @param word full word
     * @param abbr abbriviated word
     * @return true if the word startsWith abbr, or if any uppercase char in abbr
     * matches the next uppercase char in word
     *
     * FIXME: not so effecient as it creates a StringBuilder, but works
     * FIXME: add {@code Comparator<String, String>}
     */
    public static boolean camelCaseMatch(String word, String abbr) {
        StringBuilder sb = new StringBuilder();
        sb.append(word.charAt(0));
        for (int i = 1; i < word.length(); i++) {
            char c = word.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(c);
            }
        }
        String cc = sb.toString();
        if (cc.startsWith(abbr)) {
            return true;
        } else {
            return word.startsWith(abbr);
        }
    }

    static class CamelCaseCompare implements Comparator<String>, Serializable {

        @Override
        public int compare(String o1, String o2) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}


text:
function options = HyBRset(varargin)
%
%   OPTIONS = HyBRset(varargin)
%
%   Create/alter options structure for HyBR code.
%   OPTIONS = HyBRset('PARAM1',VALUE1,'PARAM2',VALUE2,...)
%     creates an options structure in which the named parameters have
%     the specified values.  Any unspecified parameters are set to []
%     (parameters with value [] indicate to use the default value for that
%     parameter when passed to the HyBR function). It is sufficient to type
%     only the leading characters that uniquely identify the parameter.
%     Case is ignored for parameter names.
%     NOTE: For values that are strings, the complete string is required.
%
%   OPTIONS = HyBRset(OLDOPTS,'PARAM1',VALUE1,...) creates a copy of
%     OLDOPTS with the named parameters altered with the specified values.
%
%   OPTIONS = HyBRset(OLDOPTS,NEWOPTS) combines an existing options structure
%     OLDOPTS with a new options structure NEWOPTS.  Any parameters in NEWOPTS
%     with non-empty values overwrite the corresponding old parameters in
%     OLDOPTS.
%
%   HyBRset with no input arguments and no output arguments displays all
%     parameter names and their possible values, with defaults shown in {}
%
%   OPTIONS = HyBRset(with no input arguments) creates an options structure
%     where all the fields are set to [].
%
%   OPTIONS = HyBRset('HyBR') creates an options structure with all
%     the parameter names and default values relevant to 'HyBR'. That is,
%           HyBRset('HyBR')
%   or
%           HyBRset(@HyBR)
%   returns an options structure containing all the parameter names and
%   default values relevant to the function 'HyBR'.
%
% HyBRset PARAMETERS for MATLAB: ( default parameter in {} )
%   InSolv - Solver for the inner problem: [ none | TSVD | {Tikhonov} ]
%   RegPar - Either (a) a value for the regularization parameter
%                           [ real non-negative scalar ]
%                   (b) a method for choosing a reg. parameter
%                           [ GCV | {WGCV} ]
%                       where  (i) 'GCV' - standard GCV
%                              (ii) 'WGCV' - weighted GCV
%                   (c) finds the optimal reg. parameter:
%                           [ optimal ]     (requires x_true)
%   Omega - If RegPar = 'WGCV', then omega must be either:
%                           [ non-negative scalar | {adapt} ]
%            where  (a) non-negative scalar - a value for omega
%                   (b) adapt - uses the adaptive method
%   Iter - Maximum number of Lanczos iterations
%                   [positive integer | {[]} ]
%   Reorth - Reorthogonalize Lanczos subspaces: [ on | {off} ]
%   x_true - True solution : [ array | {off} ]
%                Returns error with respect to x_true at each iteration
%                and is used to compute 'optimal' regularization parameters
%   BegReg - Begin regularization after this iteration:
%                [ positive integer | {2} ]
%       Vx - Extra space needed for finding optimal reg. parameters [{[]}]
%  FlatTol - Tolerance for detecting flatness in the GCV curve as a
%               stopping criteria
%               [ non-negative scalar | {10^-6}]
%   MinTol - Window of iterations for detecting a minimum of the GCV curve
%               as a stopping criteria
%               [ positive integer | {3}]
%   ResTol - Residual tolerance for stopping the LBD iterations
%                   [[non-negative scalar, non-negative scalar]  | {[10^-6, 10^-6]}]
%
%   Examples:
%     To create OPTIONS with the default options for HyBR
%       OPTIONS = HyBRset('HyBR');
%     To create an OPTIONS structure with RegPar = 'WGCV' and Omega = .5
%       OPTIONS = HyBRset('RegPar','WGCV', 'Omega',.5);
%     To change the maximum iterations to 150 in OPTIONS
%       OPTIONS = HyBRset(OPTIONS,'Iter',150);
%
%   See also HyBR.
%
%   J.Chung and J. Nagy 3/2007
%

% Print out possible values of properties.
if (nargin == 0) && (nargout == 0)
    fprintf('            InSolv: [ none | TSVD | {Tikhonov} ]\n');
    fprintf('            RegPar: [ non-negative scalar | GCV | {WGCV} | optimal ]\n');
    fprintf('             Omega: [ non-negative scalar | {adapt} ]\n');
    fprintf('              Iter: [ positive integer  | {[]} ]\n');
    fprintf('            Reorth: [ on | {off} ]\n');
    fprintf('            x_true: [ array | {off} ]\n');
    fprintf('            BegReg: [ positive integer | {2} ]\n');
    fprintf('                Vx: [ {[ ]} ]\n');
    fprintf('           FlatTol: [  non-negative scalar | {10^-6}  ]\n');
    fprintf('            MinTol: [  positive integer | {3}  ]\n');
    fprintf('            ResTol: [  non-negative scalar | {[10^-6 10^-6]}  ]\n');
    return;
end

% Create a struct of all the fields
allfields = {'InSolv'; 'RegPar';'Omega';'Iter';'Reorth'; ...
    'x_true';'BegReg'; 'Vx'; 'FlatTol'; 'MinTol'; 'ResTol'};

% create cell array
structinput = cell(2,length(allfields));
% fields go in first row
structinput(1,:) = allfields';
% []'s go in second row
structinput(2,:) = {[]};
% turn it into correctly ordered comma separated list and call struct
options = struct(structinput{:});

numberargs = nargin; % we might change this value, so assign it

% If we pass in a function name then return the defaults.
if (numberargs==1) && (ischar(varargin{1}) || isa(varargin{1},'function_handle') )
    if ischar(varargin{1})
        funcname = lower(varargin{1});
        if ~exist(funcname)
            error('Undefined function.  Please use HyBRset(@HyBR).')
        end
    elseif isa(varargin{1},'function_handle')
        funcname = func2str(varargin{1});
    end
    try
      optionsfcn = feval(varargin{1},'defaults');
    catch
        error('HyBRset ONLY works with HyBR.  Please use HyBRset(@HyBR).')
    end
    % The defaults from the HyBR functions don't include all the fields
    % typically, so run the rest of HyBRset as if called with
    % HyBRset(options,optionsfcn) to get all the fields.
    varargin{1} = options;
    varargin{2} = optionsfcn;
    numberargs = 2;
end

Names = allfields;
m = size(Names,1);
names = lower(Names);

i = 1;
while i <= numberargs
    arg = varargin{i};
    if ischar(arg)                         % arg is an option name
        break;
    end
    if ~isempty(arg)                      % [] is a valid options argument
        if ~isa(arg,'struct')
            error(['Expected argument %d to be a string parameter name ' ...
                'or an options structure \n created with HyBRset.'], i);
        end
        for j = 1:m
            if any(strcmp(fieldnames(arg),Names{j,:}))
                val = arg.(Names{j,:});
            else
                val = [];
            end
            if ~isempty(val)
                if ischar(val)
                    val = lower(deblank(val));
                end
                checkfield(Names{j,:},val)
                options.(Names{j,:}) = val;
            end
        end
    end
    i = i + 1;
end

% A finite state machine to parse name-value pairs.
if rem(numberargs-i+1,2) ~= 0
    error('Arguments must occur in name-value pairs.');
end

expectval = 0;                          % start expecting a name, not a value
while i <= numberargs
    arg = varargin{i};

    if ~expectval
        if ~ischar(arg)
            error('Expected argument %d to be a string parameter name.', i);
        end

        lowArg = lower(arg);
        j = strmatch(lowArg,names);
        if isempty(j)                       % if no matches
            error( sprintf('Invalid parameter name ''%s'' ', arg));
        elseif length(j) > 1                % if more than one match
            % Check for any exact matches (in case any names are subsets of others)
            k = strmatch(lowArg,names,'exact');
            if length(k) == 1
                j = k;
            else
                error(sprintf('Ambiguous parameter name ''%s'' ', arg));
            end
        end
        expectval = 1;                      % we expect a value next

    else
        if ischar(arg)
            arg = lower(deblank(arg));
        end
        checkfield(Names{j,:},arg);
        options.(Names{j,:}) = arg;
        expectval = 0;
    end
    i = i + 1;
end

if expectval
    error( 'Expected value for parameter ''%s''.', arg);
end

%----SUBFUNCTION---------------------------------------------
function checkfield(field,value)
%CHECKFIELD Check validity of structure field contents.
%   CHECKFIELD('field',V) checks the contents of the specified
%   value V to be valid for the field 'field'.
%

% empty matrix is always valid
if isempty(value)
    return
end

% See if 'field' is a valid field.
validfield = true;
switch field
    case {'InSolv'} % none, tsvd, tikhonov
        [validvalue, errmsg] = InSolvetype(field,value);
    case {'RegPar'} % real non-negative scalar, gcv, wgcv, optimal
        [validvalue, errmsg] = RegPartype(field,value);
    case {'Omega'} % real non-negative scalar, adapt
        [validvalue, errmsg] = Omegatype(field,value);
    case {'Iter'} % real positive integer
        [validvalue, errmsg] = PosInteger(field,value);
    case {'Reorth'} % off, on
        [validvalue, errmsg] = onOffType(field,value);
    case {'x_true'} % numeric array, off
        [validvalue, errmsg] = x_truetype(field,value);
    case {'BegReg'}% real positive integer
        [validvalue, errmsg] = PosInteger(field,value);
    case {'Vx'}% user should NOT change this
        error('Parameter ''Vx'' should not be changed.');
    case {'FlatTol'}% real non-negative scalar
        [validvalue, errmsg] = nonNegscalar(field,value);
    case {'MinTol'}% real positive integer
        [validvalue, errmsg] = PosInteger(field,value);
    case {'ResTol'}% real non-negative vector of length 2
        [validvalue, errmsg] = nonNeg2vector(field,value);
  otherwise
        validfield = false;
        validvalue = false;
        errmsg = sprintf('Unrecognized parameter name ''%s''.', field);
end

if validvalue
    return;
else
  error(errmsg)
end

%------------------------------------------------------------------------

function [valid, errmsg] = InSolvetype(field,value)
% One of these strings: tsvd, tikhonov, none
valid =  ischar(value) && any(strcmp(value,{'tsvd','tikhonov','none'}));
if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be ''tsvd'', ''tikhonov'' or ''none''.',field);
else
  errmsg = '';
end

%--------------------------------------------------------------------------

function [valid, errmsg] = RegPartype(field,value)
% One of these: real nonnegative scalar, GCV, WGCV, optimal
valid =  (isreal(value) && isscalar(value) && (value >= 0)) | (ischar(value) && any(strcmp(value,{'gcv', 'wgcv', 'optimal'})));

if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a non-negative scalar or ''GCV'' or ''WGCV'' or ''optimal''.',field);
else
  errmsg = '';
end

%--------------------------------------------------------------------------

function [valid, errmsg] = Omegatype(field,value)
% One of these: real non-negative scalar, adapt
valid =  (isreal(value) && isscalar(value) && (value >= 0) )| (ischar(value) && any(strcmp(value,{'adapt'})));

if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a non-negative scalar or ''adapt''.',field);
else
  errmsg = '';
end

%------------------------------------------------------------------------

function [valid, errmsg] = PosInteger(field,value)
% Any positive real integer
valid =  isreal(value) && isscalar(value) && (value > 0) && value == floor(value) ;

if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a positive real integer.',field);
else
  errmsg = '';
end

%-----------------------------------------------------------------------

function [valid, errmsg] = onOffType(field,value)
% One of these strings: on, off
valid =  ischar(value) && any(strcmp(value,{'on';'off'}));
if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be ''off'' or ''on''.',field);
else
  errmsg = '';
end

%-----------------------------------------------------------------------

function [valid, errmsg] = x_truetype(field,value)
% Either a numeric array, or off
valid =  isnumeric(value) | (ischar(value) && any(strcmp(value,{'off'})));
if ~valid
    errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a numeric array or ''off''.',field);
else
  errmsg = '';
end

%------------------------------------------------------------------------

function [valid, errmsg] = nonNegscalar(field,value)
% Any real non-negative scalar
valid =  isreal(value) && isscalar(value) && (value >= 0);

if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a real non-negative scalar.',field);
else
  errmsg = '';
end

%------------------------------------------------------------------------

function [valid, errmsg] = nonNeg2vector(field,value)
% Any real non-negative scalar
valid =  isreal(value) && isvector(value) && sum(value>=0)==length(value) && (length(value)==2);

if ~valid
 errmsg = sprintf('Invalid value for OPTIONS parameter %s: must be a real non-negative vector of length 2.',field);
else
  errmsg = '';
end


text:
package api

import (
	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
)

const (
// These are internal finalizer values to Origin
	FinalizerOrigin kapi.FinalizerName = "openshift.io/origin"

// ServiceBrokerNew is create by administrator.
	ServiceBrokerNew ServiceBrokerPhase = "New"

// ServiceBrokerRunning indicates that servicebroker service working well.
	ServiceBrokerActive ServiceBrokerPhase = "Active"

// ServiceBrokerFailed indicates that servicebroker stopped.
	ServiceBrokerFailed ServiceBrokerPhase = "Failed"

// ServiceBrokerDeleting indicates that servicebroker is going to be deleted.
	ServiceBrokerDeleting ServiceBrokerPhase = "Deleting"

// ServiceBrokerLastPingTime indicates that servicebroker last ping time.
	PingTimer string = "ServiceBroker/LastPing"

// ServiceBrokerNewRetryTimes indicates that new servicebroker retry times.
	ServiceBrokerNewRetryTimes string = "ServiceBroker/NewRetryTimes"

// ServiceBrokerLastRefreshBSTime indicates that servicebroker last refresh backingservice time.
	RefreshTimer string = "ServiceBroker/LastRefresh"
)

type ServiceBrokerPhase string

type ServiceBroker struct {
	unversioned.TypeMeta
	kapi.ObjectMeta

	// Spec defines the behavior of the Namespace.
	Spec ServiceBrokerSpec

	// Status describes the current status of a Namespace
	Status ServiceBrokerStatus
}

type ServiceBrokerList struct {
	unversioned.TypeMeta
	unversioned.ListMeta

	Items []ServiceBroker
}

type ServiceBrokerSpec struct {
	Url      string
	Name     string
	UserName string
	Password string

	Finalizers []kapi.FinalizerName
}

type ServiceBrokerStatus struct {
	Phase ServiceBrokerPhase
}

const (
	ServiceBrokerLabel = "asiainfo.io/servicebroker"
)


text:
(function (tree) {

    tree.debugInfo = function (env, ctx) {
        var result = "";
        if (env.dumpLineNumbers && !env.compress) {
            switch (env.dumpLineNumbers) {
                case 'comments':
                    result = tree.debugInfo.asComment(ctx);
                    break;
                case 'mediaquery':
                    result = tree.debugInfo.asMediaQuery(ctx);
                    break;
                case 'all':
                    result = tree.debugInfo.asComment(ctx) + tree.debugInfo.asMediaQuery(ctx);
                    break;
            }
        }
        return result;
    };

    tree.debugInfo.asComment = function (ctx) {
        return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n';
    };

    tree.debugInfo.asMediaQuery = function (ctx) {
        return '@media -sass-debug-info{filename{font-family:' +
            ('file://' + ctx.debugInfo.fileName).replace(/([.:/\\])/g, function (a) {
                if (a == '\\') {
                    a = '\/';
                }
                return '\\' + a
            }) +
            '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n';
    };

    tree.find = function (obj, fun) {
        for (var i = 0, r; i < obj.length; i++) {
            if (r = fun.call(obj, obj[i])) {
                return r
            }
        }
        return null;
    };
    tree.jsify = function (obj) {
        if (Array.isArray(obj.value) && (obj.value.length > 1)) {
            return '[' + obj.value.map(function (v) {
                    return v.toCSS(false)
                }).join(', ') + ']';
        } else {
            return obj.toCSS(false);
        }
    };

})(require('./tree'));


text:
void
LocalToleranceFunction::clear() {

	_groundTruthLabels.clear();
	_reconstructionLabels.clear();
	_cells = boost::make_shared<std::vector<cell_t> >();
	_possibleGroundTruthMatches.clear();
	_possibleReconstructionMatches.clear();
	_cellsByRecToGtLabel.clear();
}

std::set<float>&
LocalToleranceFunction::getReconstructionLabels() {

	return _reconstructionLabels;
}

std::set<float>&
LocalToleranceFunction::getGroundTruthLabels() {

	return _groundTruthLabels;
}

void
LocalToleranceFunction::registerPossibleMatch(float gtLabel, float recLabel) {

	_possibleGroundTruthMatches[gtLabel].insert(recLabel);
	_possibleReconstructionMatches[recLabel].insert(gtLabel);
	_groundTruthLabels.insert(gtLabel);
	_reconstructionLabels.insert(recLabel);
}

std::set<float>&
LocalToleranceFunction::getPossibleMatchesByGt(float gtLabel) {

	return _possibleGroundTruthMatches[gtLabel];
}

std::set<float>&
LocalToleranceFunction::getPossibleMathesByRec(float recLabel) {

	return _possibleReconstructionMatches[recLabel];
}


text:
// ReSharper disable once CheckNamespace
namespace Quartz
{
    public static class TestConstants
    {
        static TestConstants()
        {
            SqlServerUser = Environment.GetEnvironmentVariable("MSSQL_USER") ?? "sa";
            SqlServerPassword = Environment.GetEnvironmentVariable("MSSQL_PASSWORD") ?? "Quartz!DockerP4ss";
            // we cannot use trusted connection as it's not available for Linux provider
            SqlServerConnectionString = $"Server=localhost;Database=quartznet;User Id={SqlServerUser};Password={SqlServerPassword};";
            SqlServerConnectionStringMOT = $"Server=localhost,1444;Database=quartznet;User Id={SqlServerUser};Password={SqlServerPassword};";
        }

        public static string SqlServerUser { get; }
        public static string SqlServerPassword { get; }

        public static string SqlServerConnectionString { get; }
        public static string SqlServerConnectionStringMOT { get; }

        public const string DefaultSerializerType = "json";

        public const string DefaultSqlServerProvider = "SqlServer";
    }
}


text:
from helpers import assert_equality

def plot():
    from matplotlib import pyplot as plt

    a = [pow(10, i) for i in range(10)]
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.semilogy(a, color="blue", lw=0.25, base=2)

    plt.grid(b=True, which="major", color="g", linestyle="-", linewidth=0.25)
    plt.grid(b=True, which="minor", color="r", linestyle="--", linewidth=0.5)
    return fig

def test():
    assert_equality(plot, __file__[:-3] + "_reference.tex")
    return


text:
namespace remoting {

class MockSignalingTracker : public SignalingTracker {
 public:
  MockSignalingTracker();
  ~MockSignalingTracker() override;

  MOCK_METHOD0(OnChannelActive, void());
  MOCK_CONST_METHOD0(IsChannelActive, bool());
  MOCK_CONST_METHOD0(GetLastReportedChannelActiveDuration, base::TimeDelta());
};

}  // namespace remoting

#endif  // REMOTING_SIGNALING_MOCK_SIGNALING_TRACKER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.9.1" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0     http://pear.php.net/dtd/tasks-1.0.xsd     http://pear.php.net/dtd/package-2.0     http://pear.php.net/dtd/package-2.0.xsd">
	<name>${project.name}</name>
	<channel>${project.channel}</channel>
	<summary>A modular and lightweight stack-based framework based on ideas from Ruby's Rack and Ruby on Rails 3</summary>
	<description>
    Description goes here
  </description>
	<lead>
		<name>Martin Wernståhl</name>
		<user>m4rw3r</user>
		<email>m4rw3r@gmail.com</email>
		<active>yes</active>
	</lead>
	<date>${build.date}</date>
	<time>${build.time}</time>
	<version>
		<release>${project.majorVersion}.${project.minorVersion}.${project.patchLevel}</release>
		<api>${project.majorVersion}.${project.minorVersion}</api>
	</version>
	<stability>
		<release>alpha</release>
		<api>alpha</api>
	</stability>
	<license>All rights reserved.</license>
	<notes>
    No notes.
  </notes>
	<contents>
		<dir baseinstalldir="/" name="/">
${contents}
    </dir>
	</contents>
	<dependencies>
		<required>
			<php>
				<min>5.3.0</min>
			</php>
			<pearinstaller>
				<min>1.6.0</min>
			</pearinstaller>
			<package>
				<name>Autoloader</name>
				<channel>pear.gradwell.com</channel>
				<min>2.0.0</min>
				<max>2.999.9999</max>
			</package>
			<extension>
				<name>Reflection</name>
			</extension>
			<extension>
				<name>tokenizer</name>
			</extension>
			<extension>
				<name>SPL</name>
			</extension>
			<extension>
				<name>pcre</name>
			</extension>
		</required>
		<optional>
			<package>
				<name>phix</name>
				<channel>pear.gradwell.com</channel>
				<min>0.1.0</min>
				<max>0.999.9999</max>
			</package>
			<extension>
				<name>iconv</name>
			</extension>
		</optional>
	</dependencies>
	<phprelease/>
	<changelog>
		<release>
			<version>
				<release>X.Y.Z</release>
				<api>X.Y</api>
			</version>
			<stability>
				<release>stable</release>
				<api>stable</api>
			</stability>
			<date>Your release date</date>
			<license>All rights reserved</license>
			<notes>
      </notes>
		</release>
	</changelog>
</package>


text:
"""Component that will help set the Microsoft face for verify processing."""
import logging

import voluptuous as vol

from homeassistant.components.image_processing import (
    ATTR_CONFIDENCE,
    CONF_CONFIDENCE,
    CONF_ENTITY_ID,
    CONF_NAME,
    CONF_SOURCE,
    PLATFORM_SCHEMA,
    ImageProcessingFaceEntity,
)
from homeassistant.components.microsoft_face import DATA_MICROSOFT_FACE
from homeassistant.const import ATTR_NAME
from homeassistant.core import split_entity_id
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_GROUP = "group"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_GROUP): cv.slugify})

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Microsoft Face identify platform."""
    api = hass.data[DATA_MICROSOFT_FACE]
    face_group = config[CONF_GROUP]
    confidence = config[CONF_CONFIDENCE]

    entities = []
    for camera in config[CONF_SOURCE]:
        entities.append(
            MicrosoftFaceIdentifyEntity(
                camera[CONF_ENTITY_ID],
                api,
                face_group,
                confidence,
                camera.get(CONF_NAME),
            )
        )

    async_add_entities(entities)

class MicrosoftFaceIdentifyEntity(ImageProcessingFaceEntity):
    """Representation of the Microsoft Face API entity for identify."""

    def __init__(self, camera_entity, api, face_group, confidence, name=None):
        """Initialize the Microsoft Face API."""
        super().__init__()

        self._api = api
        self._camera = camera_entity
        self._confidence = confidence
        self._face_group = face_group

        if name:
            self._name = name
        else:
            self._name = "MicrosoftFace {0}".format(split_entity_id(camera_entity)[1])

    @property
    def confidence(self):
        """Return minimum confidence for send events."""
        return self._confidence

    @property
    def camera_entity(self):
        """Return camera entity id from process pictures."""
        return self._camera

    @property
    def name(self):
        """Return the name of the entity."""
        return self._name

    async def async_process_image(self, image):
        """Process image.

        This method is a coroutine.
        """
        detect = []
        try:
            face_data = await self._api.call_api("post", "detect", image, binary=True)

            if face_data:
                face_ids = [data["faceId"] for data in face_data]
                detect = await self._api.call_api(
                    "post",
                    "identify",
                    {"faceIds": face_ids, "personGroupId": self._face_group},
                )

        except HomeAssistantError as err:
            _LOGGER.error("Can't process image on Microsoft face: %s", err)
            return

        # Parse data
        known_faces = []
        total = 0
        for face in detect:
            total += 1
            if not face["candidates"]:
                continue

            data = face["candidates"][0]
            name = ""
            for s_name, s_id in self._api.store[self._face_group].items():
                if data["personId"] == s_id:
                    name = s_name
                    break

            known_faces.append(
                {ATTR_NAME: name, ATTR_CONFIDENCE: data["confidence"] * 100}
            )

        self.async_process_faces(known_faces, total)


text:
create table CMECreditType (
	id serial,

	shortname varchar(255) not null,
	title varchar(255) not null,

	primary key (id)
);

create index CMECreditType_shortname_index on CMECreditType(shortname);


text:
export class Links {
  readonly self?: string;
  readonly doc?: string;

  constructor(self?: string, doc?: string) {
    this.self = self;
    this.doc  = doc;
  }

  static fromJSON(links: any) {
    return new Links(Links.href(links.self), Links.href(links.doc));
  }

  private static href(link: any) {
    return link ? link.href : undefined;
  }
}


text:
<!DOCTYPE html>

        <title>Recommandations</title>
        <meta charset="UTF-8">
        <link rel="shortcut icon" href="image/kerkar.png" type="image/x-icon" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="heanderAndFooter.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="/resources/demos/style.css">

Recommandations

            Acceuil
            Parcours
            Experience profesionelle
            Recommandations
            Publications
            Projets
            Liens
            Contact

Lettre de recommandation en informatique (IRT SystemX)

L'IRT SystemX,Accélérateur de la Transformation Numérique

  Un Institut de Recherche Technologique (IRT) est un institut thématique interdisciplinaire qui développe des filières économiques liées à son domaine au travers d'un partenariat stratégique public-privé équilibré. Pour cela, il pilote des programmes de recherche couplés à des plates-formes technologiques, effectue des travaux de recherche et de développement au meilleur niveau international, contribue à l'ingénierie des formations initiales et continues (formation professionnelle qualifiante et/ou diplômante) ; et veille à la valorisation des résultats obtenus

                            Lettre de recommandation

Lettre de recommandation en électrotechnique (EDF)

Électricité de France (EDF)

                        Électricité de France (EDF) est le premier producteur et fournisseur d'électricité en France et dans le monde5.
                        En 2015, son chiffre d'affaires était de 75,006 milliards d' € pour un résultat net de 1,4 milliards d' €. En 2012, EDF avait réalisé 46,2 % de son chiffre d'affaires hors de France.

                            Lettre de recommandation.pdf

Lettre de recommandation en informatique industrielle (FST Nancy)

Master Ingénierie électrique, électronique et informatique industrielle (I2E2I)

                        la mention I2E2I vise à apporter une formation de haut niveau dans le domaine de l'électrotechnique, de l'électronique, de l'informatique industrielle, de la mesure et de la gestion énergétique ainsi que de la physique instrumentale. La mention couvre un spectre large de qualifications dans différents domaines applicatifs.

                            Lettre de recommandation

            par KERKAR Arezki


text:
var StringBuilder = require('utility.strings');

var MessageBus = {
    log: function (m) { StringBuilder.log('message-bus', m)},
    noop: {
        event: 'noop'
    },
    ReceiveNext: function (type) {
        Memory.requests = Memory.requests || [];

        if (Memory.requests.length) {
            for (var i = 0; i < Memory.requests.length; ++i) {
                if (Memory.requests[i].resource == type) {
                    var request = Memory.requests.splice(i, 1);
                    return request[0];
                }
            }
        }

        return null;
    },
    RedoRequest: function (request) {
        Memory.requests.unshift(request);
    },
    Request: function (sender, request) {
        Memory.requests = Memory.requests || [];

        Memory.requests.push({
            sender: sender,
            resource: request
        });
    },
    ReceiveRequest: function () {
        Memory.requests = Memory.requests || [];

        if (Memory.requests.length) {
            return Memory.requests.shift();
        }

        return null;
    },
    Send: function (payload) {
        console.log(payload.id + ' requested ' + payload.event);
        Memory.messages.push(payload);
    },
    Read: function () {
        if (!Memory.messages) {
            Memory.messages = [];
        }
        if (Memory.messages.length) {
            return Memory.messages.shift();
        }

        return this.noop;
    }
};

module.exports = MessageBus;


text:
'use strict';

exports.__esModule = true;

var _Formats;

exports.default = viewLabel;

var _constants = require('./constants');

var _formats = require('../formats');

var _formats2 = _interopRequireDefault(_formats);

var _localizer = require('../localizer');

var _localizer2 = _interopRequireDefault(_localizer);

var _Views = require('../Views');

var _Views2 = _interopRequireDefault(_Views);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Formats = (_Formats = {}, _Formats[_constants.views.MONTH] = 'monthHeaderFormat', _Formats[_constants.views.WEEK] = 'dayRangeHeaderFormat', _Formats[_constants.views.DAY] = 'dayHeaderFormat', _Formats[_constants.views.AGENDA] = 'agendaHeaderFormat', _Formats[_constants.views.MULTI] = 'dayHeaderFormat', _Formats);

function viewLabel(date, view, formats, culture) {
  var View = _Views2.default[view];
  var headerSingle = view === _constants.views.MONTH || view === _constants.views.DAY || view === _constants.views.MULTI;

  formats = (0, _formats2.default)(formats || {});

  var headerFormat = formats[Formats[view]];

  return headerSingle ? _localizer2.default.format(date, headerFormat, culture) : _localizer2.default.format(View.range(date, { culture: culture }), headerFormat, culture);
}
module.exports = exports['default'];


text:
package io.compgen.ngsutils.bam.filter;

import htsjdk.samtools.SAMRecord;
import io.compgen.ngsutils.bam.support.ReadUtils;

public class UniqueMapping extends AbstractBamFilter {

    public UniqueMapping(BamFilter parent, boolean verbose) {
        super(parent, verbose);
    }

    @Override
    public boolean keepRead(SAMRecord read) {
        return ReadUtils.isReadUniquelyMapped(read);
    }
}


text:
__author__ = 'Erik'

import pygame
import os
from pygame import *
from PlayerWeapons import *

class Drawable:
    def draw(self):
        pass

class PlayerSpaceShip(Drawable, pygame.sprite.Sprite):

    max_left_acceleration = -20
    max_right_acceleration = 20

    max_up_acceleration = -20
    max_down_acceleration = 20

    acceleration_increase = 2
    acceleration_decay = 1

    color = 0xFF0000

    INITIAL_HEALTH = 100
    health = INITIAL_HEALTH

    playerShots = []
    plasmaCooldown = 12
    rocketCooldown = 60

    plasmaReady = 0
    rocketReady = 0

    width = 70
    height = 53
    accelerationX = 0
    accelerationY = 0

    def update(self):
        pass

    def __init__(self, screen, enemies):
        self.enemies = enemies
        self.imageMiddle, self.rect = self.load_image('player.png', -1)
        self.imageLeft, self.rect = self.load_image('playerLeft.png', -1)
        self.imageRight, self.rect = self.load_image('playerRight.png', -1)
        self.image, self.rect = self.load_image('player.png', -1)
        pygame.sprite.Sprite.__init__(self)
        self.screen = screen
        self.screenWidth = screen.get_width()
        self.screenHeight = screen.get_height()
        self.laser_sound_effect = pygame.mixer.Sound(os.path.join('sounds', "spacegun10.wav"))
        self.torpedo_sound_effect = pygame.mixer.Sound(os.path.join('sounds', "spacegun02.wav"))
        self.explosion_sound_effect = pygame.mixer.Sound(os.path.join('sounds', "action05.wav"))
        self.reset()
        self.allsprites = pygame.sprite.RenderPlain()

    def load_image(self, name, colorkey=None):
        fullname = os.path.join('data', name)
        try:
            image = pygame.image.load(fullname)
        except pygame.error, message:
            print 'Cannot load image:', name
            raise SystemExit, message
        image = image.convert()
        if colorkey is not None:
            if colorkey is -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, RLEACCEL)
        return image, image.get_rect()

    def isHitByWeapon(self, object):
        removeList = []
        found = False
        for shot in self.playerShots:
            if self.overlap2(shot, object):
                self.playerShots.remove(shot)
                self.allsprites.remove(shot)
                self.explosion_sound_effect.play()
                found = True
        for shot in removeList:
            self.playerShots.remove(shot)
        return found

    def overlap2(self,first, other):
        return (first.x <= (other.x+other.width) and other.x <= (first.x+first.width) and first.y <= (other.y+other.height) and other.y <= (first.y+first.height))

    def overlap(self, other):
        return (self.x <= (other.x+other.width) and other.x <= (self.x+self.width) and self.y <= (other.y+other.height) and other.y <= (self.y+self.height))

    def isHitByShot(self, shot):
        if self.overlap(shot):
            self.health -= 3
            self.accelerationY += 10
            self.explosion_sound_effect.play()
            return True
        return False

    def draw(self):
        if self.accelerationX > 0:
            self.image = self.imageRight
        elif self.accelerationX < 0:
            self.image = self.imageLeft
        else:
            self.image = self.imageMiddle
        self.updatePosition(),
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        if self.rocketReady > 0:
            self.rocketReady = self.rocketReady - 1
        if self.plasmaReady > 0:
            self.plasmaReady = self.plasmaReady - 1
        for shot in self.playerShots:
            shot.draw()

        self.allsprites.update()
        self.allsprites.draw(self.screen)
        #pygame.draw.rect(self.screen, self.color, self.rect, 0)

    def updatePosition(self):
        if (self.x+self.accelerationX+self.width) > self.screenWidth:
            self.x = self.screenWidth-self.width
            self.accelerationX = -(self.accelerationX*1.5)
        elif (self.x+self.accelerationX) < 0:
            self.x = 0
            self.accelerationX = -(self.accelerationX*1.5)
        else:
            self.x = self.x + self.accelerationX

        if (self.y+self.accelerationY+self.height) > self.screenHeight:
            self.y = self.screenHeight-self.height
            self.accelerationY = -(self.accelerationY*1.5)
        elif (self.y+self.accelerationY) < 0:
            self.y = 0
            self.accelerationY = -(self.accelerationY*1.5)
        else:
            self.y = self.y + self.accelerationY

        if self.accelerationX > 0:
            if (self.accelerationX - self.acceleration_decay) < 0:
                self.accelerationX = 0
            else:
                self.accelerationX = self.accelerationX - self.acceleration_decay
        elif self.accelerationX < 0:
            if (self.accelerationX + self.acceleration_decay) > 0:
                self.accelerationX = 0
            else:
                self.accelerationX+=self.acceleration_decay

        if self.accelerationY > 0:
            if (self.accelerationY - self.acceleration_decay) < 0:
                self.accelerationY = 0
            else:
                self.accelerationY = self.accelerationY - self.acceleration_decay
        elif self.accelerationY < 0:
            if (self.accelerationY + self.acceleration_decay) > 0:
                self.accelerationY = 0
            else:
                self.accelerationY+=self.acceleration_decay

        #Scale down to max acceleration
        if self.accelerationX > self.max_right_acceleration*1.5:
            self.accelerationX = self.max_right_acceleration
        elif self.accelerationX < self.max_left_acceleration*1.5:
            self.accelerationX = self.max_left_acceleration

        if self.accelerationY > self.max_down_acceleration*1.5:
            self.accelerationY = self.max_down_acceleration
        elif self.accelerationY < self.max_up_acceleration*1.5:
            self.accelerationY = self.max_up_acceleration

    def moveUp(self):
        if self.accelerationY > self.max_up_acceleration:
            self.accelerationY = self.accelerationY - self.acceleration_increase

    def moveDown(self):
        if self.accelerationY < self.max_down_acceleration:
            self.accelerationY= self.accelerationY + self.acceleration_increase

    def moveLeft(self):
        if self.accelerationX > self.max_left_acceleration:
            self.accelerationX= self.accelerationX - self.acceleration_increase

    def moveRight(self):
        if self.accelerationX < self.max_right_acceleration:
            self.accelerationX= self.accelerationX + self.acceleration_increase

    def reset(self):
        self.health = self.INITIAL_HEALTH
        self.y = self.screenHeight - 200
        self.x = self.screenWidth/2

    def firePlasma(self):
        if self.plasmaReady <= 0:
            self.laser_sound_effect.play()
            self.playerShots.append(PlasmaShot(self.screen, self.x, self.y+(self.height)+20))
            self.playerShots.append(PlasmaShot(self.screen, self.x+(self.width)-4, self.y+(self.height)+20))
            self.plasmaReady = self.plasmaCooldown

    def fireRocket(self, enemies):
        if self.rocketReady <= 0:
            self.torpedo_sound_effect.play()
            rocket = RocketShot(self.screen, self.x+(self.width/2), self.y+(self.height/2), enemies)
            self.playerShots.append(rocket)
            self.allsprites.add(rocket)
            self.rocketReady = self.rocketCooldown

    def isPositionInside(self, x, y):
        if y > self.y and y < self.y+self.height:
            if x > self.x and x < self.x+self.width:
                return True
        return False

    def checkBossHit(self, object):
        removeList = []
        found = False
        for shot in self.playerShots:
            if self.overlap2(shot, object):
                self.playerShots.remove(shot)
                self.allsprites.remove(shot)
                self.explosion_sound_effect.play()
                found = True
        for shot in removeList:
            self.playerShots.remove(shot)
        return found


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.GDSEventJobs = exports.GDSServiceAPI = exports.GDSUtil = exports.GDSDomainPaginateHelper = exports.GDSDomainDTO = exports.GDSDatabaseTest = exports.GDSDomainAPI = exports.GDSServices = exports.GDSServer = exports.GDSDatabase = exports.GDSAppLogger = exports.GDSResource = exports.Delete = exports.Put = exports.Post = exports.Get = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _Express = require('./api/Express');

Object.defineProperty(exports, 'Get', {
  enumerable: true,
  get: function get() {
    return _Express.Get;
  }
});
Object.defineProperty(exports, 'Post', {
  enumerable: true,
  get: function get() {
    return _Express.Post;
  }
});
Object.defineProperty(exports, 'Put', {
  enumerable: true,
  get: function get() {
    return _Express.Put;
  }
});
Object.defineProperty(exports, 'Delete', {
  enumerable: true,
  get: function get() {
    return _Express.Delete;
  }
});

var _events = require('./events/events');

var _services = require('./services/services');

var _AppLogger2 = require('./logger/AppLogger');

var _AppLogger3 = _interopRequireDefault(_AppLogger2);

var _databaseConfig = require('./database/database-config');

var _databaseConfig2 = _interopRequireDefault(_databaseConfig);

var _databaseTestConfig = require('./database/database-test-config');

var _databaseTestConfig2 = _interopRequireDefault(_databaseTestConfig);

var _domainApi = require('./services/domain-api');

var _domainApi2 = _interopRequireDefault(_domainApi);

var _domainDto = require('./services/domain-dto');

var _domainDto2 = _interopRequireDefault(_domainDto);

var _domainRequestHelper = require('./services/domain-request-helper');

var _getDateRange = require('./util/get-date-range');

var _getDateRange2 = _interopRequireDefault(_getDateRange);

var _getJsonFieldValue = require('./util/get-json-field-value');

var _getJsonFieldValue2 = _interopRequireDefault(_getJsonFieldValue);

var _logger = require('./logger/logger');

var _logger2 = _interopRequireDefault(_logger);

var _Resource = require('./api/Resource');

var _Resource2 = _interopRequireDefault(_Resource);

var _server = require('./server/server');

var _server2 = _interopRequireDefault(_server);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var GDSResource = exports.GDSResource = _Resource2.default;

var GDSAppLogger = exports.GDSAppLogger = function (_AppLogger) {
  _inherits(GDSAppLogger, _AppLogger);

  function GDSAppLogger(message) {
    _classCallCheck(this, GDSAppLogger);

    return _possibleConstructorReturn(this, (GDSAppLogger.__proto__ || Object.getPrototypeOf(GDSAppLogger)).call(this, message));
  }

  return GDSAppLogger;
}(_AppLogger3.default);

var GDSDatabase = exports.GDSDatabase = function (_DatabaseConfig) {
  _inherits(GDSDatabase, _DatabaseConfig);

  function GDSDatabase() {
    _classCallCheck(this, GDSDatabase);

    return _possibleConstructorReturn(this, (GDSDatabase.__proto__ || Object.getPrototypeOf(GDSDatabase)).apply(this, arguments));
  }

  return GDSDatabase;
}(_databaseConfig2.default);

var GDSServer = exports.GDSServer = function (_ServerConfig) {
  _inherits(GDSServer, _ServerConfig);

  function GDSServer() {
    _classCallCheck(this, GDSServer);

    return _possibleConstructorReturn(this, (GDSServer.__proto__ || Object.getPrototypeOf(GDSServer)).apply(this, arguments));
  }

  return GDSServer;
}(_server2.default);

var GDSServices = exports.GDSServices = function (_ServicesConfig) {
  _inherits(GDSServices, _ServicesConfig);

  function GDSServices() {
    _classCallCheck(this, GDSServices);

    return _possibleConstructorReturn(this, (GDSServices.__proto__ || Object.getPrototypeOf(GDSServices)).apply(this, arguments));
  }

  return GDSServices;
}(_services.ServicesConfig);

var GDSDomainAPI = exports.GDSDomainAPI = function (_DomainAPIModel) {
  _inherits(GDSDomainAPI, _DomainAPIModel);

  function GDSDomainAPI() {
    _classCallCheck(this, GDSDomainAPI);

    var _this5 = _possibleConstructorReturn(this, (GDSDomainAPI.__proto__ || Object.getPrototypeOf(GDSDomainAPI)).call(this));

    _this5.setDomainName(process.env.DOMAIN_NAME);
    return _this5;
  }

  return GDSDomainAPI;
}(_domainApi2.default);

var GDSDatabaseTest = exports.GDSDatabaseTest = function (_DatabaseTestConfig) {
  _inherits(GDSDatabaseTest, _DatabaseTestConfig);

  function GDSDatabaseTest() {
    _classCallCheck(this, GDSDatabaseTest);

    return _possibleConstructorReturn(this, (GDSDatabaseTest.__proto__ || Object.getPrototypeOf(GDSDatabaseTest)).apply(this, arguments));
  }

  return GDSDatabaseTest;
}(_databaseTestConfig2.default);

var GDSDomainDTO = exports.GDSDomainDTO = function (_DomainDtoModel) {
  _inherits(GDSDomainDTO, _DomainDtoModel);

  function GDSDomainDTO() {
    _classCallCheck(this, GDSDomainDTO);

    return _possibleConstructorReturn(this, (GDSDomainDTO.__proto__ || Object.getPrototypeOf(GDSDomainDTO)).apply(this, arguments));
  }

  return GDSDomainDTO;
}(_domainDto2.default);

var GDSDomainPaginateHelper = exports.GDSDomainPaginateHelper = function (_DomainPaginateHelper) {
  _inherits(GDSDomainPaginateHelper, _DomainPaginateHelper);

  function GDSDomainPaginateHelper() {
    _classCallCheck(this, GDSDomainPaginateHelper);

    return _possibleConstructorReturn(this, (GDSDomainPaginateHelper.__proto__ || Object.getPrototypeOf(GDSDomainPaginateHelper)).apply(this, arguments));
  }

  return GDSDomainPaginateHelper;
}(_domainRequestHelper.DomainPaginateHelper);

var GDSUtil = exports.GDSUtil = function () {
  function GDSUtil() {
    _classCallCheck(this, GDSUtil);
  }

  _createClass(GDSUtil, [{
    key: 'getDateRange',
    value: function getDateRange(dateFormat) {
      return new _getDateRange2.default(dateFormat);
    }
  }, {
    key: 'getLogger',
    value: function getLogger(callback) {
      return new _logger2.default(callback);
    }
  }, {
    key: 'initEvents',
    value: function initEvents(callback) {
      return new _events.Events(callback);
    }
  }, {
    key: 'getJsonValue',
    value: function getJsonValue(jsonOject, exp, callback) {
      new _getJsonFieldValue2.default(jsonOject, exp, callback);
    }
  }, {
    key: 'isJson',
    value: function isJson(json) {
      var isjson = true;
      try {
        JSON.parse(json);
      } catch (err) {
        isjson = false;
      }
      return isjson;
    }
  }]);

  return GDSUtil;
}();

var GDSServiceAPI = exports.GDSServiceAPI = function (_Services) {
  _inherits(GDSServiceAPI, _Services);

  function GDSServiceAPI() {
    _classCallCheck(this, GDSServiceAPI);

    return _possibleConstructorReturn(this, (GDSServiceAPI.__proto__ || Object.getPrototypeOf(GDSServiceAPI)).apply(this, arguments));
  }

  return GDSServiceAPI;
}(_services.Services);

var GDSEventJobs = exports.GDSEventJobs = function (_EventJobs) {
  _inherits(GDSEventJobs, _EventJobs);

  function GDSEventJobs() {
    _classCallCheck(this, GDSEventJobs);

    return _possibleConstructorReturn(this, (GDSEventJobs.__proto__ || Object.getPrototypeOf(GDSEventJobs)).apply(this, arguments));
  }

  return GDSEventJobs;
}(_events.EventJobs);


text:
import java.nio.charset.StandardCharsets;

import static java.nio.charset.StandardCharsets.*;

class Test {
  void test(byte[] bytes) throws Exception {
    int UTF_8 = 1;
    String string = new String(bytes, StandardCharsets.UTF_8);
    System.out.println(string);
    string.getBytes(UTF_16);
  }
}


text:
<?php

require dirname(__DIR__) . '/vendor/autoload.php';

use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
use Icicle\Socket\Server\Server;
use Icicle\Socket\Server\DefaultServerFactory;
use Icicle\Socket\Socket;

$server = (new DefaultServerFactory())->create('127.0.0.1', 8080, ['backlog' => 1024]);

$generator = function (Server $server) {
    $generator = function (Socket $socket) {
        try {
            $data = yield from $socket->read();

            $microtime = sprintf("%0.4f", microtime(true));
            $message = "Received the following request ({$microtime}):\r\n\r\n{$data}";
            $length = strlen($message);

            $data  = "HTTP/1.1 200 OK\r\n";
            $data .= "Content-Type: text/plain\r\n";
            $data .= "Content-Length: {$length}\r\n";
            $data .= "Connection: close\r\n";
            $data .= "\r\n";
            $data .= $message;

            yield from $socket->write($data);
        } finally {
            $socket->close();
        }
    };

    while ($server->isOpen()) {
        $coroutine = new Coroutine(
            $generator(yield from $server->accept())
        );
    }
};

$coroutine = new Coroutine($generator($server));

$coroutine->cleanup(function () use ($server) {
    $server->close();
});

echo "Server started.\n";

Loop\run();


text:
"""
    Atom
A wrapped DexLang value.

Scalar values can be converted to julia objects using [`juliaize`](@ref), or `convert`.
Functions can be called directly, if you pass in atoms,
or they can be compiled and made usable on julia objects by using [`NativeFunction`](@ref).
"""
struct Atom
    ptr::Ptr{HsAtom}
    ctx::Ptr{HsContext}
end

Base.show(io::IO, atom::Atom) = show(io, print(atom.ptr))

"""
    juliaize(x)

Get the corresponding Julia object from some Dex object.
The inverse of [`dexize`](@ref).
"""
juliaize(x::CAtom) = bust_union(x)
juliaize(x::Ptr{HsAtom}) = juliaize(CAtom(x))
juliaize(x::Atom) = juliaize(x.ptr)
Base.convert(::Type{T}, atom::Atom) where {T<:Number} = convert(T, juliaize(atom))

"""
    dexize(x)

Get the corresponding Dex object from some Julia object.
The inverse of [`juliaize`](@ref).
"""
dexize(x) = Atom(from_CAtom(Ref(CAtom(x))), PRELUDE)
# ^ Always defined in PRELUDE as it could be defined anywhere that has all the bindings,
# but because it has no bindings anywhere will do

Base.convert(::Type{Atom}, atom::Number) = dexize(atom)

function (self::Atom)(args...)
    # TODO: Make those calls more hygenic
    env = self.ctx
    pieces = (self, args...)
    for (i, atom) in enumerate(pieces)
        # NB: Atoms can contain arbitrary references
        if atom.ctx !== PRELUDE && atom.ctx !== self.ctx
            throw(ArgumentError("Mixing atoms coming from different Dex modules is not supported yet!"))
        end
        old_env, env = env, insert(env, "julia_arg$i", atom.ptr)
        destroy_context(old_env)
    end
    return evaluate(join("julia_arg" .* string.(eachindex(pieces)), " "), self.ctx, env)
end

mutable struct DexModule
    # Needs to be mutable struct so can attach finalizer
    ctx::Ptr{HsContext}
end

"""
    DexModule(str)

For running 1 or more Dex expressions, and keeping the state.
You can get them back out of the module using `getproperty`.
They are returned as [`DexCall.Atom`](@ref)s.

# Example:

```julia
julia> m = DexModule(raw"""
       x = 42
       y = 2 * x
       """)
DexModule(Ptr{DexCall.HsContext} @0x0000000000000031)

julia> m.x
"42"

julia> m.y
"84"
```
"""
function DexModule(source::AbstractString)
    ctx = dex_eval(PRELUDE, source)
    ctx == C_NULL && throw_from_dex()
    m =  DexModule(ctx)
    finalizer(m) do _m
        destroy_context(getfield(_m, :ctx))
    end
    return m
end

function Base.getproperty(m::DexModule, name::Symbol)
    ctx = getfield(m, :ctx)
    ret = lookup(ctx, string(name))
    ret == C_NULL && throw_from_dex()
    return Atom(ret, ctx)
end

@doc raw"""
    evaluate(str)

A friendly function for running Dex code.
The string `str` must contain a single Dex expression.
Return a [`DexCall.Atom`](@ref)
# Example:
```julia
julia> evaluate(raw"sum $ for i. exp [log 2.0, log 4.0].i")
"6."
```
"""
function evaluate(str, _module=PRELUDE, env=_module)
    result = eval_expr(env, str)
    result == C_NULL && throw_from_dex()
    return Atom(result, _module)
end


text:
$(document).ready(function(){

	 var docw = $(document).width() - 600;
	 $("#slider_arrow_right").click(function(){
		$("#sidebar_box_wrapper").animate({
			scrollLeft: $("#sidebar_box_wrapper").scrollLeft() + docw
		}, 1000,function(){});
	 });
	 $("#slider_arrow_left").click(function(){
		$("#sidebar_box_wrapper").animate({
			scrollLeft: $("#sidebar_box_wrapper").scrollLeft() - docw
		}, 1000,function(){});
	 });

});


text:
import { ClientFunction, Selector } from 'testcafe';

const page = 'http://localhost:3000/fixtures/multiple-windows/pages/i6242/index.html';

const getLocation = ClientFunction(() => window.location.href);

fixture `Download in separate window`
    .page(page);

test('Download in separate window', async t => {
    const downloadButton = Selector('a');

    await t
        .click(downloadButton)
        .expect(getLocation()).eql(page)
        .click(downloadButton)
        .expect(getLocation()).eql(page)
        .openWindow(page);
});


text:
package com.xinra.growthlectures.service;

import com.google.common.collect.Streams;
import com.xinra.growthlectures.Util;
import com.xinra.growthlectures.entity.Lecturer;
import com.xinra.growthlectures.entity.LecturerRepository;
import com.xinra.nucleus.service.DtoFactory;
import groovy.transform.CompileStatic;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@CompileStatic
@Service
class LecturerServiceImpl extends GrowthlecturesServiceImpl implements LecturerService {

  @Autowired
  private DtoFactory dtoFactory;

  @Autowired
  private LecturerRepository lecturerRepo;

  public ContainerDto getRandomLecturer() {

    Long lecturersCount = lecturerRepo.count();
    int randomIndex = (int) (Math.random() * lecturersCount);
    Page<Lecturer> lecturerList = lecturerRepo.findAll(new PageRequest(randomIndex, 1));
    Lecturer randomLecturer = null;
    for (Lecturer l : lecturerList) {
      randomLecturer = l;
    }
    return convertLecturer(randomLecturer);
  }

  public List<ContainerDto> getPopularLecturers(int limit) {
    List<Lecturer> popularLecturers = lecturerRepo.findByOrderByName(new PageRequest(0, limit));
    return popularLecturers.stream().map(this::convertLecturer).collect(Collectors.toList());
  }

  public ContainerDto getLecturerBySlug(String slug) throws SlugNotFoundException {

    Lecturer lecture = lecturerRepo.findOneBySlug(slug);
    if (lecture == null) {
      throw new SlugNotFoundException(slug);
    }
    return convertLecturer(lecture);
  }

  public List<ContainerDto> getAllLecturers() {
    return Streams.stream(lecturerRepo.findAll())
            .map(this::convertLecturer)
            .collect(Collectors.toList());
  }

  public boolean doesExists(String slug) {
    Lecturer lecturer = lecturerRepo.findBySlug(slug);
    if (lecturer == null) {
      return false;
    }
    return true;
  }

  public NamedDto createLecturer(NamedDto newLecurerDto) {

    Lecturer newLecturer = new Lecturer();

    String name = Util.normalize(newLecurerDto.getName());
    String slug = Util.normalize(newLecurerDto.getSlug());
    newLecturer.setName(name);
    newLecturer.setSlug(slug);
    lecturerRepo.save(newLecturer);

    return newLecurerDto;
  }

  private ContainerDto convertLecturer(Lecturer l) {

    if (l == null) {
      return null;
    }

    ContainerDto returnDto = dtoFactory.createDto(ContainerDto.class);
    returnDto.setName(l.getName());
    returnDto.setSlug(l.getSlug());
    returnDto.setAmount(l.getLectures().size());

    return returnDto;

  }
}


text:
package server

import (
	"bytes"
	"compress/gzip"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/cockroachdb/cockroach/pkg/base"
	"github.com/cockroachdb/cockroach/pkg/config"
	"github.com/cockroachdb/cockroach/pkg/internal/client"
	"github.com/cockroachdb/cockroach/pkg/keys"
	"github.com/cockroachdb/cockroach/pkg/roachpb"
	"github.com/cockroachdb/cockroach/pkg/server/serverpb"
	"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
	"github.com/cockroachdb/cockroach/pkg/storage"
	"github.com/cockroachdb/cockroach/pkg/testutils"
	"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
	"github.com/cockroachdb/cockroach/pkg/util"
	"github.com/cockroachdb/cockroach/pkg/util/hlc"
	"github.com/cockroachdb/cockroach/pkg/util/httputil"
	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
	"github.com/gogo/protobuf/jsonpb"
	"github.com/pkg/errors"
)

var nodeTestBaseContext = testutils.NewNodeTestBaseContext()

// TestSelfBootstrap verifies operation when no bootstrap hosts have
// been specified.
func TestSelfBootstrap(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, err := serverutils.StartServerRaw(base.TestServerArgs{})
	if err != nil {
		t.Fatal(err)
	}
	defer s.Stopper().Stop(context.TODO())
}

// TestServerStartClock tests that a server's clock is not pushed out of thin
// air. This used to happen - the simple act of starting was causing a server's
// clock to be pushed because we were introducing bogus future timestamps into
// our system.
func TestServerStartClock(t *testing.T) {
	defer leaktest.AfterTest(t)()

	// Set a high max-offset so that, if the server's clock is pushed by
	// MaxOffset, we don't hide that under the latency of the Start operation
	// which would allow the physical clock to catch up to the pushed one.
	params := base.TestServerArgs{
		Knobs: base.TestingKnobs{
			Store: &storage.StoreTestingKnobs{
				MaxOffset: time.Second,
			},
		},
	}
	s, _, _ := serverutils.StartServer(t, params)
	defer s.Stopper().Stop(context.TODO())

	// Run a command so that we are sure to touch the timestamp cache. This is
	// actually not needed because other commands run during server
	// initialization, but we cannot guarantee that's going to stay that way.
	get := &roachpb.GetRequest{
		Span: roachpb.Span{Key: roachpb.Key("a")},
	}
	if _, err := client.SendWrapped(
		context.Background(), s.KVClient().(*client.DB).GetSender(), get,
	); err != nil {
		t.Fatal(err)
	}

	now := s.Clock().Now()
	// We rely on s.Clock() having been initialized from hlc.UnixNano(), which is a
	// bit fragile.
	physicalNow := hlc.UnixNano()
	serverClockWasPushed := (now.Logical > 0) || (now.WallTime > physicalNow)
	if serverClockWasPushed {
		t.Fatalf("time: server %s vs actual %d", now, physicalNow)
	}
}

// TestPlainHTTPServer verifies that we can serve plain http and talk to it.
// This is controlled by -cert=""
func TestPlainHTTPServer(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
		// The default context uses embedded certs.
		Insecure: true,
	})
	defer s.Stopper().Stop(context.TODO())

	var data serverpb.JSONResponse
	testutils.SucceedsSoon(t, func() error {
		return getStatusJSONProto(s, "metrics/local", &data)
	})

	ctx := s.RPCContext()
	ctx.Insecure = false
	if err := getStatusJSONProto(s, "metrics/local", &data); !testutils.IsError(err, "http: server gave HTTP response to HTTPS client") {
		t.Fatalf("unexpected error %v", err)
	}
}

func TestSecureHTTPRedirect(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
	defer s.Stopper().Stop(context.TODO())
	ts := s.(*TestServer)

	httpClient, err := s.GetHTTPClient()
	if err != nil {
		t.Fatal(err)
	}
	// Avoid automatically following redirects.
	httpClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
		return http.ErrUseLastResponse
	}

	origURL := "http://" + ts.Cfg.HTTPAddr
	expURL := url.URL{Scheme: "https", Host: ts.Cfg.HTTPAddr, Path: "/"}

	if resp, err := httpClient.Get(origURL); err != nil {
		t.Fatal(err)
	} else {
		resp.Body.Close()
		if resp.StatusCode != http.StatusPermanentRedirect {
			t.Errorf("expected status code %d; got %d", http.StatusPermanentRedirect, resp.StatusCode)
		}
		if redirectURL, err := resp.Location(); err != nil {
			t.Error(err)
		} else if a, e := redirectURL.String(), expURL.String(); a != e {
			t.Errorf("expected location %s; got %s", e, a)
		}
	}

	if resp, err := httpClient.Post(origURL, "text/plain; charset=utf-8", nil); err != nil {
		t.Fatal(err)
	} else {
		resp.Body.Close()
		if resp.StatusCode != http.StatusPermanentRedirect {
			t.Errorf("expected status code %d; got %d", http.StatusPermanentRedirect, resp.StatusCode)
		}
		if redirectURL, err := resp.Location(); err != nil {
			t.Error(err)
		} else if a, e := redirectURL.String(), expURL.String(); a != e {
			t.Errorf("expected location %s; got %s", e, a)
		}
	}
}

// TestAcceptEncoding hits the server while explicitly disabling
// decompression on a custom client's Transport and setting it
// conditionally via the request's Accept-Encoding headers.
func TestAcceptEncoding(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
	defer s.Stopper().Stop(context.TODO())
	client, err := s.GetHTTPClient()
	if err != nil {
		t.Fatal(err)
	}

	testData := []struct {
		acceptEncoding string
		newReader      func(io.Reader) io.Reader
	}{
		{"",
			func(b io.Reader) io.Reader {
				return b
			},
		},
		{httputil.GzipEncoding,
			func(b io.Reader) io.Reader {
				r, err := gzip.NewReader(b)
				if err != nil {
					t.Fatalf("could not create new gzip reader: %s", err)
				}
				return r
			},
		},
	}
	for _, d := range testData {
		req, err := http.NewRequest("GET", s.AdminURL()+statusPrefix+"metrics/local", nil)
		if err != nil {
			t.Fatalf("could not create request: %s", err)
		}
		if d.acceptEncoding != "" {
			req.Header.Set(httputil.AcceptEncodingHeader, d.acceptEncoding)
		}
		resp, err := client.Do(req)
		if err != nil {
			t.Fatalf("could not make request to %s: %s", req.URL, err)
		}
		defer resp.Body.Close()
		if ce := resp.Header.Get(httputil.ContentEncodingHeader); ce != d.acceptEncoding {
			t.Fatalf("unexpected content encoding: '%s' != '%s'", ce, d.acceptEncoding)
		}
		r := d.newReader(resp.Body)
		var data serverpb.JSONResponse
		if err := jsonpb.Unmarshal(r, &data); err != nil {
			t.Error(err)
		}
	}
}

// TestMultiRangeScanDeleteRange tests that commands which access multiple
// ranges are carried out properly.
func TestMultiRangeScanDeleteRange(t *testing.T) {
	defer leaktest.AfterTest(t)()
	s, _, db := serverutils.StartServer(t, base.TestServerArgs{})
	defer s.Stopper().Stop(context.TODO())
	ts := s.(*TestServer)
	tds := db.GetSender()

	if err := ts.node.storeCfg.DB.AdminSplit(context.TODO(), "m"); err != nil {
		t.Fatal(err)
	}
	writes := []roachpb.Key{roachpb.Key("a"), roachpb.Key("z")}
	get := &roachpb.GetRequest{
		Span: roachpb.Span{Key: writes[0]},
	}
	get.EndKey = writes[len(writes)-1]
	if _, err := client.SendWrapped(context.Background(), tds, get); err == nil {
		t.Errorf("able to call Get with a key range: %v", get)
	}
	var delTS hlc.Timestamp
	for i, k := range writes {
		put := roachpb.NewPut(k, roachpb.MakeValueFromBytes(k))
		if _, err := client.SendWrapped(context.Background(), tds, put); err != nil {
			t.Fatal(err)
		}
		scan := roachpb.NewScan(writes[0], writes[len(writes)-1].Next())
		reply, err := client.SendWrapped(context.Background(), tds, scan)
		if err != nil {
			t.Fatal(err)
		}
		sr := reply.(*roachpb.ScanResponse)
		if sr.Txn != nil {
			// This was the other way around at some point in the past.
			// Same below for Delete, etc.
			t.Errorf("expected no transaction in response header")
		}
		if rows := sr.Rows; len(rows) != i+1 {
			t.Fatalf("expected %d rows, but got %d", i+1, len(rows))
		}
	}

	del := &roachpb.DeleteRangeRequest{
		Span: roachpb.Span{
			Key:    writes[0],
			EndKey: roachpb.Key(writes[len(writes)-1]).Next(),
		},
		ReturnKeys: true,
	}
	reply, err := client.SendWrappedWith(context.Background(), tds, roachpb.Header{Timestamp: delTS}, del)
	if err != nil {
		t.Fatal(err)
	}
	dr := reply.(*roachpb.DeleteRangeResponse)
	if dr.Txn != nil {
		t.Errorf("expected no transaction in response header")
	}
	if !reflect.DeepEqual(dr.Keys, writes) {
		t.Errorf("expected %d keys to be deleted, but got %d instead", writes, dr.Keys)
	}

	scan := roachpb.NewScan(writes[0], writes[len(writes)-1].Next())
	txn := roachpb.NewTransaction("MyTxn", nil, 0, 0, s.Clock().Now(), 0)
	reply, err = client.SendWrappedWith(context.Background(), tds, roachpb.Header{Txn: txn}, scan)
	if err != nil {
		t.Fatal(err)
	}
	sr := reply.(*roachpb.ScanResponse)
	if txn := sr.Txn; txn == nil || txn.Name != "MyTxn" {
		t.Errorf("wanted Txn to persist, but it changed to %v", txn)
	}
	if rows := sr.Rows; len(rows) > 0 {
		t.Fatalf("scan after delete returned rows: %v", rows)
	}
}

// TestMultiRangeScanWithMaxResults tests that commands which access multiple
// ranges with MaxResults parameter are carried out properly.
func TestMultiRangeScanWithMaxResults(t *testing.T) {
	defer leaktest.AfterTest(t)()
	testCases := []struct {
		splitKeys []roachpb.Key
		keys      []roachpb.Key
	}{
		{[]roachpb.Key{roachpb.Key("m")},
			[]roachpb.Key{roachpb.Key("a"), roachpb.Key("z")}},
		{[]roachpb.Key{roachpb.Key("h"), roachpb.Key("q")},
			[]roachpb.Key{roachpb.Key("b"), roachpb.Key("f"), roachpb.Key("k"),
				roachpb.Key("r"), roachpb.Key("w"), roachpb.Key("y")}},
	}

	for i, tc := range testCases {
		s, _, db := serverutils.StartServer(t, base.TestServerArgs{})
		defer s.Stopper().Stop(context.TODO())
		ts := s.(*TestServer)
		tds := db.GetSender()

		for _, sk := range tc.splitKeys {
			if err := ts.node.storeCfg.DB.AdminSplit(context.TODO(), sk); err != nil {
				t.Fatal(err)
			}
		}

		for _, k := range tc.keys {
			put := roachpb.NewPut(k, roachpb.MakeValueFromBytes(k))
			if _, err := client.SendWrapped(context.Background(), tds, put); err != nil {
				t.Fatal(err)
			}
		}

		// Try every possible ScanRequest startKey.
		for start := 0; start < len(tc.keys); start++ {
			// Try every possible maxResults, from 1 to beyond the size of key array.
			for maxResults := 1; maxResults <= len(tc.keys)-start+1; maxResults++ {
				scan := roachpb.NewScan(tc.keys[start], tc.keys[len(tc.keys)-1].Next())
				reply, err := client.SendWrappedWith(
					context.Background(), tds, roachpb.Header{MaxSpanRequestKeys: int64(maxResults)}, scan,
				)
				if err != nil {
					t.Fatal(err)
				}
				rows := reply.(*roachpb.ScanResponse).Rows
				if start+maxResults <= len(tc.keys) && len(rows) != maxResults {
					t.Errorf("%d: start=%s: expected %d rows, but got %d", i, tc.keys[start], maxResults, len(rows))
				} else if start+maxResults == len(tc.keys)+1 && len(rows) != maxResults-1 {
					t.Errorf("%d: expected %d rows, but got %d", i, maxResults-1, len(rows))
				}
			}
		}
	}
}

func TestSystemConfigGossip(t *testing.T) {
	defer leaktest.AfterTest(t)()
	t.Skip("#12351")

	s, _, kvDB := serverutils.StartServer(t, base.TestServerArgs{})
	defer s.Stopper().Stop(context.TODO())
	ts := s.(*TestServer)
	ctx := context.TODO()

	key := sqlbase.MakeDescMetadataKey(keys.MaxReservedDescID)
	valAt := func(i int) *sqlbase.DatabaseDescriptor {
		return &sqlbase.DatabaseDescriptor{Name: "foo", ID: sqlbase.ID(i)}
	}

	// Register a callback for gossip updates.
	resultChan := ts.Gossip().RegisterSystemConfigChannel()

	// The span gets gossiped when it first shows up.
	select {
	case <-resultChan:

	case <-time.After(500 * time.Millisecond):
		t.Fatal("did not receive gossip message")
	}

	// Write a system key with the transaction marked as having a Gossip trigger.
	if err := kvDB.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
		if err := txn.SetSystemConfigTrigger(); err != nil {
			return err
		}
		return txn.Put(ctx, key, valAt(2))
	}); err != nil {
		t.Fatal(err)
	}

	// This has to be wrapped in a SucceedSoon because system migrations on the
	// testserver's startup can trigger system config updates without the key we
	// wrote.
	testutils.SucceedsSoon(t, func() error {
		// New system config received.
		var systemConfig config.SystemConfig
		select {
		case <-resultChan:
			systemConfig, _ = ts.gossip.GetSystemConfig()

		case <-time.After(500 * time.Millisecond):
			return errors.Errorf("did not receive gossip message")
		}

		// Now check the new config.
		var val *roachpb.Value
		for _, kv := range systemConfig.Values {
			if bytes.Equal(key, kv.Key) {
				val = &kv.Value
				break
			}
		}
		if val == nil {
			return errors.Errorf("key not found in gossiped info")
		}

		// Make sure the returned value is valAt(2).
		got := new(sqlbase.DatabaseDescriptor)
		if err := val.GetProto(got); err != nil {
			return err
		}
		if expected := valAt(2); !reflect.DeepEqual(got, expected) {
			return errors.Errorf("mismatch: expected %+v, got %+v", *expected, *got)
		}
		return nil
	})
}

func checkOfficialize(t *testing.T, network, oldAddrString, newAddrString, expAddrString string) {
	resolvedAddr := util.NewUnresolvedAddr(network, newAddrString)

	if unresolvedAddr, err := officialAddr(oldAddrString, resolvedAddr); err != nil {
		t.Fatal(err)
	} else if retAddrString := unresolvedAddr.String(); retAddrString != expAddrString {
		t.Errorf("officialAddr(%s, %s) was %s; expected %s", oldAddrString, newAddrString, retAddrString, expAddrString)
	}
}

func TestOfficializeAddr(t *testing.T) {
	defer leaktest.AfterTest(t)()

	hostname, err := os.Hostname()
	if err != nil {
		t.Fatal(err)
	}

	for _, network := range []string{"tcp", "tcp4", "tcp6"} {
		checkOfficialize(t, network, "hellow.world:0", "127.0.0.1:1234", "hellow.world:1234")
		checkOfficialize(t, network, "hellow.world:1234", "127.0.0.1:2345", "hellow.world:1234")
		checkOfficialize(t, network, ":1234", "127.0.0.1:2345", net.JoinHostPort(hostname, "1234"))
		checkOfficialize(t, network, ":0", "127.0.0.1:2345", net.JoinHostPort(hostname, "2345"))
	}
}

func TestClusterStores(t *testing.T) {
	defer leaktest.AfterTest(t)()
	tc := serverutils.StartTestCluster(t, 2, base.TestClusterArgs{})
	defer tc.Stopper().Stop(context.TODO())

	testutils.SucceedsSoon(t, func() error {
		stores := tc.Server(0).(*TestServer).ClusterStores()
		if len(stores) != 2 {
			return errors.Errorf("expected 2 stores, got %v", stores)
		}
		n1 := tc.Server(0).NodeID()
		n2 := tc.Server(1).NodeID()
		s1 := stores[0].NodeID
		s2 := stores[1].NodeID
		if !(n1 == s1 && n2 == s2) && !(n1 == s2 && n2 == s1) {
			return errors.Errorf("expected stores for nodes %d, %d, got %v", n1, n2, stores)
		}
		return nil
	})
}

func TestListenURLFileCreation(t *testing.T) {
	defer leaktest.AfterTest(t)()

	file, err := ioutil.TempFile(os.TempDir(), t.Name())
	if err != nil {
		t.Fatal(err)
	}
	if err := file.Close(); err != nil {
		t.Fatal(err)
	}

	s, err := serverutils.StartServerRaw(base.TestServerArgs{
		ListeningURLFile: file.Name(),
	})
	if err != nil {
		t.Fatal(err)
	}
	defer s.Stopper().Stop(context.TODO())
	defer func() {
		if err := os.Remove(file.Name()); err != nil {
			t.Error(err)
		}
	}()

	data, err := ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatal(err)
	}

	u, err := url.Parse(string(data))
	if err != nil {
		t.Fatal(err)
	}

	if s.ServingAddr() != u.Host {
		t.Fatalf("expected URL %s to match host %s", u, s.ServingAddr())
	}
}


text:
<?php

/**
 * @file
 * Contains \Drupal\field_ui_test\Entity\FieldUITestNoBundle.
 */

namespace Drupal\field_ui_test\Entity;

use Drupal\Core\Entity\Entity;
use Drupal\Core\Entity\Annotation\EntityType;
use Drupal\Core\Annotation\Translation;

/**
 * Defines the test Field UI class.
 *
 * @EntityType(
 *   id = "field_ui_test_no_bundle",
 *   label = @Translation("Test Field UI entity, no bundle"),
 *   module = "field_ui_test",
 *   controllers = {
 *     "storage" = "Drupal\Core\Entity\DatabaseStorageController"
 *   },
 *   fieldable = TRUE,
 *   route_base_path = "field-ui-test-no-bundle/manage"
 * )
 */
class FieldUITestNoBundle extends Entity {

  /**
   * The entity ID.
   *
   * @var int
   */
  public $id;

}