text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: install_lang.php 32641 2013-02-27 08:39:58Z monkey $
 */

if(!defined('IN_COMSENZ')) {
	exit('Access Denied');
}

define('UC_VERNAME', 'English ver.');
$lang = array(
	'SC_GBK' => 'Simplified Chinese',
	'TC_BIG5' => 'Traditional Chinese',
	'SC_UTF8' => 'English UTF8 version by small six website',
	'TC_UTF8' => 'Traditional Chinese UTF8 version',
	'EN_ISO' => 'ENGLISH ISO8859',
	'EN_UTF8' => 'ENGLIST UTF-8',

	'title_install' => SOFT_NAME.' Setup Wizard',
	'agreement_yes' => 'I agree',
	'agreement_no' => 'I do not agree',
	'notset' => 'Not limit',

	'message_title' => 'Prompt message',
	'error_message' => 'Error message',
	'message_return' => 'Return',
	'return' => 'Return',
	'install_wizard' => 'Setup Wizard',
	'config_nonexistence' => 'Config file does not exist',
	'nodir' => 'Directory does not exist',
	'redirect' => 'The browser will automatically jump page, Without human intervention.
Unless your browser does not support frames, Click here',
	'auto_redirect' => 'The browser will automatically jump page, Without human intervention',
	'database_errno_2003' => 'Can not connect to the database, check the database whether to start, the database server address is correct ',
	'database_errno_1044' => 'Can not create a new database, check the name of the database fill in correctly',
	'database_errno_1045' => 'Can not connect to the database, check the database user name or password is correct',
	'database_errno_1064' => 'SQL Syntax error',

	'dbpriv_createtable' => 'Not CREATE TABLE permission, Installation can not continue',
	'dbpriv_insert' => 'Not INSERT permission,Installation can not continue',
	'dbpriv_select' => 'Not SELECT permission,Installation can not continue',
	'dbpriv_update' => 'Not UPDATE permission,Installation can not continue',
	'dbpriv_delete' => 'Not DELETE permission,Installation can not continue',
	'dbpriv_droptable' => 'Not DROP TABLE permission,Can not be installed',

	'db_not_null' => 'Database already installed UCenter to continue the installation will clear the original data.',
	'db_drop_table_confirm' => 'Continue the installation will clear all the original data, you sure you want to continue?',

	'writeable' => 'Can write',
	'unwriteable' => 'Can not write',
	'old_step' => 'Previous',
	'new_step' => 'Next',

	'database_errno_2003' => 'Can not connect to the database, check the database whether to start, the database server address is correct ',
	'database_errno_1044' => 'Can not create a new database, check the name of the database fill in correctly',
	'database_errno_1045' => 'Can not connect to the database, check the database user name or password is correct',
	'database_connect_error' => 'Database connection error',

	'step_title_1' => 'Check install environment',
	'step_title_2' => 'Setting environment',
	'step_title_3' => 'Create a database',
	'step_title_4' => 'Install',
	'step_env_check_title' => 'Start install',
	'step_env_check_desc' => 'Environment and the file directory permissions check',
	'step_db_init_title' => 'Install the database',
	'step_db_init_desc' => 'Is running the database installation',

	'step1_file' => 'Directory file',
	'step1_need_status' => 'Required state',
	'step1_status' => 'Current status of the',
	'not_continue' => 'Please red cross partial amendments and try again',

	'tips_dbinfo' => 'Fill in the database info',
	'tips_dbinfo_comment' => '',
	'tips_admininfo' => 'Fill in the Administrator Info',
	'step_ext_info_title' => 'Installation was successful.',
	'step_ext_info_comment' => 'Click to enter login',

	'ext_info_succ' => 'Installation was successful.',
	'install_submit' => 'Submit',
	'install_locked' => 'Install the lock has been installed, if you sure you want to reinstall, please go to delete the server
 '.str_replace(ROOT_PATH, '', $lockfile),
	'error_quit_msg' => 'You must solve the above problem, the installation can continue',

	'step_app_reg_title' => 'Setting environment',
	'step_app_reg_desc' => 'The detection server environment and set UCenter',
	'tips_ucenter' => 'Please fill UCenter',
	'tips_ucenter_comment' => 'UCenter is Comsenz Core services program of the company\'s products, Discuz! Board The installation and operation rely on this program. If you have already installed UCenter, Please fill in the following information. Otherwise, go to Comsenz Products Download and install, Before continuing.',

	'advice_mysql_connect' => 'Please check the mysql module is loaded correctly',
	'advice_gethostbyname' => 'Whether PHP configuration gethostbyname function is disabled. Please contact your hosting provider to determine open this',
	'advice_file_get_contents' => 'This function requires the php.ini allow_url_fopen option is turned on. Please contact your hosting provider to determine open this',
	'advice_xml_parser_create' => 'This function requires PHP support XML. Please contact your hosting provider to determine open this',
	'advice_fsockopen' => 'This function requires the php.ini allow_url_fopen option is turned on. Please contact your hosting provider to determine open this',
	'advice_pfsockopen' => 'This function requires the php.ini allow_url_fopen option is turned on. Please contact your hosting provider to determine open this',
	'advice_stream_socket_client' => 'Whether PHP configuration banned the stream_socket_client function',
	'advice_curl_init' => 'Whether PHP configuration banned curl_init function',

	'ucurl' => 'UCenter URL',
	'ucpw' => 'UCenter Founder password',
	'ucip' => 'UCenter IP addresses',
	'ucenter_ucip_invalid' => 'Format error, please fill out the correct IP address',
	'ucip_comment' => 'You can not fill the vast majority of cases',

	'tips_siteinfo' => 'Please fill in the site information',
	'sitename' => 'Site Name',
	'siteurl' => 'Site URL',

	'forceinstall' => 'Mandatory install',
	'dbinfo_forceinstall_invalid' => 'Current database which already contains the same the table prefix data sheet, you can modify the table name prefix to avoid deleting the old data, or select the mandatory installation. Force the installation will delete the old data, and can not be restored',

	'click_to_back' => 'Click to return to the previous step',
	'adminemail' => 'System Email',
	'adminemail_comment' => 'Used to send error reports',
	'dbhost_comment' => 'A database server address, for ships localhost',
	'tablepre_comment' => 'The same database running multiple forums, please change the prefix',
	'forceinstall_check_label' => 'I want to delete the data, mandatory install !!!',

	'uc_url_empty' => 'You have not filled UCenter URL, Please return to fill',
	'uc_url_invalid' => 'URL Format error',
	'uc_url_unreachable' => 'UCenter URL The address may fill in error, please check',
	'uc_ip_invalid' => 'Unable to resolve the domain name, Please fill in the site IP',
	'uc_admin_invalid' => 'UCenter founder password error please re-fill',
	'uc_data_invalid' => 'Communication fails check the URL address is correct UCenter ',
	'uc_dbcharset_incorrect' => 'UCenter Database character set character set consistent with the current app',
	'uc_api_add_app_error' => 'Add to UCenter app error',
	'uc_dns_error' => 'UCenter DNS Parse error please return to fill out the IP address UCenter',

	'ucenter_ucurl_invalid' => 'UCenter the URL is empty or wrong format, please check',
	'ucenter_ucpw_invalid' => 'UCenter founder of the password is blank or formatting errors, please check',
	'siteinfo_siteurl_invalid' => 'Site URL is empty or format error, please check',
	'siteinfo_sitename_invalid' => 'Site name is blank or format error, please check',
	'dbinfo_dbhost_invalid' => 'Database server is empty or format error, please check',
	'dbinfo_dbname_invalid' => 'Database name is empty or format error, please check',
	'dbinfo_dbuser_invalid' => 'Database user name is blank or format error, please check',
	'dbinfo_dbpw_invalid' => 'Database password is blank or format error, please check',
	'dbinfo_adminemail_invalid' => 'System, the mailbox is empty or format error, please check',
	'dbinfo_tablepre_invalid' => 'Table prefix is empty or format error, please check',
	'admininfo_username_invalid' => 'Administrator user name is blank or format error, please check',
	'admininfo_email_invalid' => 'Administrator Email blank or format error, please check',
	'admininfo_password_invalid' => 'Administrator password is blank, please fill out the',
	'admininfo_password2_invalid' => 'The two passwords do not match, please check',

	'install_dzfull' => '
<input type="radio"'.(getgpc('install_ucenter') != 'no' ? ' checked="checked"' : '').' name="install_ucenter" value="yes" onclick="if(this.checked)$(\'form_items_2\').style.display=\'none\';" /> A new installation Discuz! X (Contain UCenter Server)',
	'install_dzonly' => '
<input type="radio"'.(getgpc('install_ucenter') == 'no' ? ' checked="checked"' : '').' name="install_ucenter" value="no" onclick="if(this.checked)$(\'form_items_2\').style.display=\'\';" /> Install only Discuz! X (Has been installed manually specify UCenter Server)',

	'username' => 'Admin account',
	'email' => 'Admin Email',
	'password' => 'Admin PW',
	'password_comment' => 'The administrator PW can not be empty',
	'password2' => 'Repeat PW',

	'admininfo_invalid' => 'Admini information is not complete, please check administrator account & password & email',
	'dbname_invalid' => 'Database name is empty, please fill out the database name',
	'tablepre_invalid' => 'Table prefix is empty or format error, please check',
	'admin_username_invalid' => 'Data illegal user name user name length should not exceed 15 letters long and can not contain special characters, usually Chinese, letters or numbers',
	'admin_password_invalid' => 'Password and the above inconsistency please re-enter',
	'admin_email_invalid' => 'Email Wrong address the e-mail address is being used or the format is invalid please replace the other address',
	'admin_invalid' => 'Your information manager information is not completed please carefully fill out each item',
	'admin_exist_password_error' => 'The user already exists if you want to set this user forum administrator the user's password is entered correctly or replace the board admin\'s name',

	'tagtemplates_subject' => 'Title',
	'tagtemplates_uid' => 'User ID',
	'tagtemplates_username' => 'Poster',
	'tagtemplates_dateline' => 'Date',
	'tagtemplates_url' => 'Thread URL',

	'uc_version_incorrect' => 'Your UCenter server version is too low please upgrade UCenter service ended to the latest version and upgrade, download address: http://www.comsenz.com/.',
	'config_unwriteable' => 'Install can not write to the config file, set the config.inc.php is writable state program properties(777)',

	'install_in_processed' => 'Being installed...',
	'install_succeed' => 'Install was successful, click to enter',
	'install_cloud' => 'Installation successful, welcome to the opening Discuz! The cloud platform
 Discuz! The cloud platform committed to helping owners to increase website traffic, and enhance the ability of website operators to increase website revenue.
 Discuz! cloud platform is provided free of charge QQ Internet, Tencent aspect search, roaming applications, the SOSO expression services. Discuz! Cloud platform will continue to provide more quality services to the project.
 opened Discuz! platform, make sure that your website (Discuz!, UCHome, or SupeSite) has been upgraded to Discuz! X3.',
	'to_install_cloud' => 'Opened to the background',
	'to_index' => 'Temporarily not opened',

	'init_credits_karma' => 'Prestige',
	'init_credits_money' => 'Money',

	'init_postno0' => 'Landlord',
	'init_postno1' => 'Sofa',
	'init_postno2' => 'Bench',
	'init_postno3' => 'Floor',

	'init_support' => 'Support',
	'init_opposition' => 'Opposition',

	'init_group_0' => 'Member',
	'init_group_1' => 'Administrator',
	'init_group_2' => 'Super Moderator',
	'init_group_3' => 'Moderator',
	'init_group_4' => 'Ban Post',
	'init_group_5' => 'Ban Visit',
	'init_group_6' => 'Ban IP',
	'init_group_7' => 'Tourist',
	'init_group_8' => 'Awaiting verification',
	'init_group_9' => 'Beggar',
	'init_group_10' => 'Newbie',
	'init_group_11' => 'Registered Member',
	'init_group_12' => 'Intermediate Member',
	'init_group_13' => 'Senior Member',
	'init_group_14' => 'Gold Member',
	'init_group_15' => 'Forum veteran',

	'init_rank_1' => '新生入学',
	'init_rank_2' => '小试牛刀',
	'init_rank_3' => '实习记者',
	'init_rank_4' => '自由撰稿人',
	'init_rank_5' => '特聘作家',

	'init_cron_1' => 'Empty Today\'s Posts',
	'init_cron_2' => 'Empty month Online',
	'init_cron_3' => 'daily data cleansing',
	'init_cron_4' => 'birthday Statistics and mail blessing',
	'init_cron_5' => 'Topic Reply Notification',
	'init_cron_6' => 'publish daily clean-up',
	'init_cron_7' => 'limited operation clean-up',
	'init_cron_8' => 'Forum to promote the clean-up',
	'init_cron_9' => 'Topic of the month clean-up',
	'init_cron_10' => 'daily X-Space update user',
	'init_cron_11' => 'Update weekly theme',

	'init_bbcode_1' => 'The contents of the horizontal scroll, this effect is similar to HTML marquee tag Note: This effect is only valid under the Internet Explorer browser。',
	'init_bbcode_2' => 'Embedded Flash animation',
	'init_bbcode_3' => 'QQ online status click this icon and his (her) chat',
	'init_bbcode_4' => 'Superscript',
	'init_bbcode_5' => 'Subscript',
	'init_bbcode_6' => 'Embedded Windows media audio',
	'init_bbcode_7' => 'Embedded Windows media audio or video',

	'init_qihoo_searchboxtxt' =>'Enter keywords, Quick Search this Forum',
	'init_threadsticky' =>'Sticky Top, Top category, edition Top',

	'init_default_style' => 'Default style',
	'init_default_forum' => 'Default Forum',
	'init_default_template' => 'Department of the default template',
	'init_default_template_copyright' => 'Beijing Sing-ups Technology Co. Ltd.',

	'init_dataformat' => 'Y-n-j',
	'init_modreasons' => 'Ad/SPAM\r\nMalicious irrigation\r\nCONTENT\r\nIrrelevant\r\nDuplicate post\r\n\r\nI agree\r\nFine article\r\nOriginal content',
	'init_userreasons' => 'Is to force!\r\nHorses are clouds of God\r\nLike this one!\r\nCottage\r\nCalm',
	'init_link' => 'Discuz! Official forum',
	'init_link_note' => 'Provide the latest Discuz! Product news, software downloads and technical exchanges',

	'init_promotion_task' => 'Web site promotion tasks',
	'init_gift_task' => 'Red envelope type of task',
	'init_avatar_task' => 'Picture type of task',

	'license' => '

English version of the license agreement for English users

All rights reserved (c) 2001-2013, Beijing comsenz-ups Technology Co. Ltd. All rights reserved.

Thank you for choosing Comsenz. I hope our efforts can provide you with a fast and efficient, powerful site solutions and strong community forum solution. The Comsenz URL for http://www.comsenz.com,Official forum site at http://www.discuz.net。

Notice to users: This Agreement is a legal agreement between you and the Comsenz Sing company provides a variety of software products and services you use. Whether you are an individual or organization, profit or not, use (including for the purpose of study and research), are required to carefully read this Agreement, including the exclusion or restriction of Comsenz responsibility Disclaimer and limit your rights. Please review and accept or do not accept the terms of service. If you do not agree to the terms of service and / or Comsenz it at any time to modify, you should not use or take the initiative to cancel the Comsenz Sing products. Otherwise, any of your related services in Comsenz registration, login, download, view and use behavior will be deemed fully accept all of the Terms of Service, including the acceptance of any modifications the Comsenz the Terms of Service at any time made .

The terms of service in the event of a change, Sing will be published on the website modifications. Once the revised Terms of Service on stage after the website management announced that an effective substitute for the original terms of service. You can always visit the Kang Shengguan party Forum to see the latest version of the Terms of Service. If you choose to accept the Terms, you are agreeing to be bound by the agreement to the conditions. If you do not agree to the Terms of Service, you can not get the right to use the Service. Or if you are in violation of the provisions of, the Comsenz Company reserves the right to suspend or terminate your eligibility to use the Comsenz and retain the right to pursue legal responsibility.

Understand, agree to and comply with all the terms of this Agreement prior to the commencement Comsenz. You may also signed another written agreement directly with the Comsenz to supplement or replace the whole or any part of this Agreement.

Comsenz with all intellectual property rights in the software. The software for the license agreement, not sold. Comsenz only allows you to comply with the provisions of this Agreement, copy, download, install, use or otherwise benefit from the functionality of the software or intellectual property rights.

I. The right to License Agreement

On the basis of full compliance with this License Agreement, the software used in non-commercial use, without having to pay a software copyright license fees.

You can modify the constraints and limits stipulated in the agreement the Comsenz source code (if provided) or interface style to suit your site requirements.

You use this software to build websites in which all members of the ownership of information, articles and related information, and independently undertake the audit of the site\'s content and use this software to build a duty of care to ensure that it does not infringe the legitimate rights and interests of any person, independently take responsibility for thefull responsibility for the the Comsenz software and services brought caused the Comsenz or loss of customers, you should be full compensation for.

If you need the Comsenz software or service user commercial use must be obtained separately written permission of Comsenz, you get a commercial license, you can be the software used for commercial purposes, is determined based on the type of license purchased technologyperiod of support, technical support methods and technical support content, from the moment of purchase, within a period of technical support is owned by the manner specified within the specified range of technical support services. Commercial users the power to reflect and comment on relevant comments will be a primary consideration, but not necessarily be adopted by the promise or guarantee.

Download for your website from Comsenz Application Center application, but should the application developer / owner to pay the appropriate fees.

II. Restrictions and limitations stipulated in the agreement

Comsenz without written before the commercial license, the Software may not be used for commercial purposes (including, but not limited to, corporate websites, business websites, for commercial purpose or profit website). Buy commercial license, please visit http://www.discuz.com refer to the instructions, you can also call 8610-51282255 for more information.

May not rent, sell, mortgage or sublicense the Software or associated with the commercial license.

In any case, regardless of the purpose, whether after modify or landscaping, changes to what extent, as long as the use of the whole or any part of the Comsenz, without the written permission of the page footer at the Comsenz name and Comsenz affiliated website (http://www.comsenz.com, or http://www.discuz.net) the link must be retained, but can not erase or modify.

Comsenz the whole or any part of the basis for the development of any derivative version, modified versions or third-party version is used to redistribute is prohibited.

You download an application from the Application Center, without the written permission of application developers / owners, not to reverse-engineer, reverse assemble, reverse compile, are not allowed to copy, modify, links, reproduced, assembly, publish, publishing, development relating to derivative products, works.

If you fail to comply with the terms of this Agreement, your license will be terminated, the license rights will be recovered, and you should bear the corresponding legal responsibility.

III. Limited Warranty and Disclaimer

The software and the documentation that came with as does not provide any explicit or implied, in the form of compensation or guarantees.

User voluntarily use the software, you must understand the risk of using the software, not buy, we do not promise to provide any form of technical support, guarantee and is not responsible for any use of this software problemsresponsibility.

Comsenz does not use this software to build websites or forum articles or liable for the information, the full responsibility borne by you.

The Comsenz can not be fully uploaded to the application-centric applications monitored by a third party, there is no guarantee the legality of the application, security, integrity, authenticity or quality; when you download an application from the Application Center, agreed to make their own judgmentand bear all risks without relying on Comsenz. But in any case, Comsenz shall have the right to stop the application center services and take appropriate action, including but not limited to uninstall related applications, suspension of all or part of the service, keep the relevant records, to the relevant authorities report. Whereby you and a third party may result in the loss of Comsenz is not liable for any direct, indirect or consequential responsibility.

Hong Shing Comsenz software and services in a timely manner, security, accuracy is not guaranteed, due to force majeure, Comsenz factors beyond its control (including hacker attacks, stopping power, etc.) caused by software use and servicesuspension or termination, your losses, you agree to the waiver of all rights Sing corporate responsibility. 6. Comsenz drew particular attention to, the Comsenz companies in order to protect the company\'s business development and adjustment autonomy Sing The company has at any time with or without prior notice to modify the service, suspend or terminate some or all of the software and services the right to modify will be announced on the the Comsenz company website page, including without limitation this notice. The Hong Shing exercise to modify or discontinue, terminate the rights of some or all of the software and services of losses caused to the Comsenz do not need to be responsible to you or any third party.

 For the the Comsenz end-user license agreement, the details of the commercial license and technical services, provided exclusively by the Comsenz. The Sing The company has the right to modify the license agreement and lists of services, the new authorized user of the date of entry into force of revised agreement or a price list from the change without prior notice.

Once you start the installation Comsenz, shall be deemed to fully understand and accept this agreement to the terms of, and in the enjoyment of the rights conferred by these provisions, subject to the restrictions and limitations. Agreement beyond the permitted behavior, will be in direct violation of the licensing agreement and an infringement, we have the right to terminate the license at any time, be ordered to stop the damage, and reserves the power to be held responsible.

Interpretation of the terms of the license agreement, effectiveness and dispute resolution, applies to the laws of the mainland of the People\'s Republic of China.

If any dispute or controversy between you and Comsenz, first of all should be resolved through friendly consultations, the negotiation fails, you hereby fully agree with the dispute or submit the dispute to the jurisdiction of the Comsenz located in Haidian District People\'s Court. The Sing The company has the explanation and the right to modify the content of the above provisions.

(After the body)

Comsenz

',

	'uc_installed' => 'You have installed UCenter, if you need to reinstall, delete data/install.lock file',
	'i_agree' => 'I have read and agree to the terms of all content',
	'supportted' => 'supportted',
	'unsupportted' => 'Does not support',
	'max_size' => 'Support/maximum size',
	'project' => 'Project',
	'ucenter_required' => 'Discuz! Desired configuration',
	'ucenter_best' => 'Discuz! Optimal',
	'curr_server' => 'Current server',
	'env_check' => 'milieu Check',
	'os' => 'Operating system',
	'php' => 'PHP Version',
	'attachmentupload' => 'Attach upload',
	'unlimit' => 'Unlimited',
	'version' => 'Version',
	'gdversion' => 'GD Library',
	'allow' => 'Allow ',
	'unix' => 'Unix',
	'diskspace' => 'Disk Space',
	'priv_check' => 'Directories, check file permissions',
	'func_depend' => 'Dependency checking function',
	'func_name' => 'Function name',
	'check_result' => 'Test results',
	'suggestion' => 'Proposal',
	'advice_mysql' => 'Please check the mysql module is loaded correctly',
	'advice_fopen' => 'This function requires the php.ini allow_url_fopen option is turned on. Please contact your hosting provider to determine open this',
	'advice_file_get_contents' => 'This function requires the php.ini allow_url_fopen option is turned on. Please contact your hosting provider to determine open this',
	'advice_xml' => 'This function requires PHP support XML. Please contact your hosting provider to determine open this',
	'none' => 'None',

	'dbhost' => 'Database server',
	'dbuser' => 'Database user name',
	'dbpw' => 'Database Pw',
	'dbname' => 'Database name',
	'tablepre' => 'Database Prefix',

	'ucfounderpw' => 'Founder password',
	'ucfounderpw2' => 'Repeat the founder password',

	'init_log' => 'Initialization record',
	'clear_dir' => 'Empty catalog',
	'select_db' => 'Select the database',
	'create_table' => 'Establish a data table',
	'succeed' => 'Success ',

	'install_data' => 'Data is being installed',
	'install_test_data' => 'Additional data are being installed',

	'method_undefined' => 'Undefined method',
	'database_nonexistence' => 'Database operations object does not exist',
	'skip_current' => 'Skip this step',
	'topic' => 'Topics',

);

$msglang = array(
	'config_nonexistence' => 'Your config.inc.php does not exist can not continue installation use FTP upload the file and try again.',
);

?>


text:
package org.apache.drill.exec.store.sys;

/**
 * Interfaces to define EStore, which is keep track of status/information for running queries. The information
 * would be gone, if the query is completed, or the foreman drillbit is not responding.
 * @param <V>
 */
public interface EStore <V> extends PStore<V> {
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace dvizh\shop;

use yii\base\BootstrapInterface;
use yii;

class Bootstrap implements BootstrapInterface
{
    public function bootstrap($app)
    {
        if(!$app->has('shop')) {
            $app->set('shop', ['class' => 'dvizh\shop\Shop']);
        }
    }
}


text:
from flask import Flask

from flask_restful import Api
from mocks.resources import MockResource, MockRunnerResource

app = Flask(__name__)
api = Api(app)

api.add_resource(MockResource, '/mocks/')
api.add_resource(MockRunnerResource, '/mocks/run/<string:mock_id>', endpoint='put')

if __name__ == '__main__':
    app.run()


text:
package com.wincom.actor.editor.tutogef.command;

import org.eclipse.draw2d.geometry.Rectangle;

import com.wincom.actor.editor.tutogef.model.Service;

public class ServiceChangeLayoutCommand extends AbstractLayoutCommand {
	private Service model;
	private Rectangle layout;
	private Rectangle oldLayout;

	@Override
	public void execute() {
		model.setLayout(layout);
	}

	@Override
	public void setConstraint(Rectangle rect) {
		this.layout = rect;
	}

	@Override
	public void setModel(Object model) {
		this.model = (Service) model;
		this.oldLayout = ((Service) model).getLayout();
	}

	@Override
	public void undo() {
		this.model.setLayout(this.oldLayout);
	}
}


text:
layout: article
title: "Referência rápida"
description: "Uma visão geral rápida das propriedades do elemento de vídeo."
introduction: "Uma visão geral rápida das propriedades do elemento de vídeo."
article:
  written_on: 2014-04-16
  updated_on: 2014-04-29
  order: 5
collection: videos
authors:
  - samdutton
key-takeaways:
  add-a-video:
    - Use o elemento para carregar, decodificar e reproduzir o vídeo em seu site.
    - Crie vídeos em vários formatos para abranger uma variedade de plataformas de dispositivos móveis.
    - Dimensione os vídeos corretamente. Certifique-se de que eles não ultrapassam o tamanho da tela.
    - A acessibilidade é importante. Adicione o elemento de faixa como um derivado do elemento de vídeo.
remember:
  media-fragments:
    - A Media Fragments API é compatível com a maioria das plataformas, exceto o iOS.
    - Certifique-se de que o recurso Range Requests é compatível com seu servidor. Por padrão, o recurso Range Requests é ativado na maioria dos servidores, mas alguns serviços de hospedagem podem tê-lo desativado.
  dont-overflow:
    - Não force a dimensão de um elemento que pode resultar em uma proporção diferente da proporção do vídeo original. O resultado visual de uma dimensão achatada ou esticada não é bom.
  accessibility-matters:
    - O elemento de faixa é compatível com o Google Chrome para Android, Safari no iOS e todos os navegadores para computador, exceto o Firefox (consulte caniuse.com/track). Também há vários códigos polyfill disponíveis. Recomendamos Playr ou Captionator.
  construct-video-streams:
    - No Android, MSE é compatível com os navegadores Google Chrome e Opera. Em computadores, MSE é compatível com o Internet Explorer 11 e o Google Chrome. A compatibilidade com o Firefox está prevista para versões futuras.
---

{% wrap content%}

{% include modules/toc.liquid %}

## Atributos de elementos de vídeo

Para ver uma lista completa de atributos de elementos de vídeo e suas definições, veja [the video element spec](//www.w3.org/TR/html5/embedded-content-0.html#the-video-element).

      Atributo
      Disponibilidade
      Descrição

      src
      Todos os navegadores
      Endereço (URL) do vídeo.

      poster
      Todos os navegadores
      Endereço (URL) de um arquivo de imagem que o navegador pode exibir assim que o elemento de vídeo for exibido, sem precisar fazer o download do conteúdo do vídeo.

      preload
      Todos os navegadores de dispositivos móveis ignoram o atributo `preload`.
      Informa o navegador de que é útil pré-carregar os metadados (ou vídeos) antes de sua reprodução. As opções são: none (nenhum), metadata (metadados) ou auto (automático) (consulte a seção `Pré-carregamento` para mais detalhes).

      autoplay
      Não é compatível com o iPhone nem com o Android. É compatível com todos os navegadores de computadores, iPad, Firefox e Opera para Android.
      Inicia o download e a reprodução assim que possível (consulte a seção `Reprodução automática`).

      loop
      Todos os navegadores
      Deixa o vídeo em loop.

      controls
      Todos os navegadores
      Exibe os controles padrão do vídeo (reproduzir, pausar etc.)

### Reprodução automática

Em computadores, `Reprodução automática` informa ao navegador para iniciar imediatamente o download e, assim que possível, iniciar a reprodução do vídeo. No iOS e Google Chrome para Android, a opção `Reprodução automática` não funciona. Os usuários precisam tocar na tela para reproduzir o vídeo.

Até mesmo em plataforma em que a reprodução automática é possível, é preciso avaliar se é útil ativá-la.

* O uso de dados pode ser caro.
* Iniciar o download e a reprodução de uma mídia sem solicitar o consentimento do usuário pode comprometer inesperadamente a largura de banda e o uso da CPU, o que atrasaria a renderização da página.
* Os usuários podem estar em um contexto em que a reprodução de vídeo ou de áudio seria considerada inadequada.

O comportamento da Reprodução automática pode ser configurado no Android WebView por meio da [WebSettings API](//developer.android.com/reference/android/webkit/WebSettings.html#setMediaPlaybackRequiresUserGesture(boolean)).
O padrão é verdadeiro, mas um aplicativo da WebView pode oferecer a opção de desabilitá-lo.

### Pré-carregar

O atributo `preload` informa ao navegador quanto de informação ou conteúdo deve ser pré-carregado.

      Valor
      Descrição

      none
      O usuário pode nem assistir ao vídeo. Não realiza o pré-carregamento.

      metadata
      Os metadados (duração, dimensões e faixas de texto) devem ser pré-carregados, mas com vídeo pequeno.

      auto
      Considera-se desejável o download imediato de todo o vídeo.

O atributo "preload" tem efeitos diferentes dependendo da plataforma.
Por exemplo, o Google Chrome armazena em buffer 25 segundos do vídeo em um computador e nada no iOS nem no Android. Isso significa que em dispositivos móveis podem ocorrer atrasos de inicialização da reprodução que não ocorrem em computadores. Consulte [a página de teste de Steve Souders](//stevesouders.com/tests/mediaevents.php) para ver detalhes completos.

## JavaScript

[O artigo "HTML5 Rocks Video"](//www.html5rocks.com/en/tutorials/video/basics/#toc-javascript) fez um ótimo trabalho em resumir as propriedades, os métodos e os eventos de Javascript que podem ser usados para controlar a reprodução de vídeos. Incluímos o conteúdo aqui e o atualizamos com questões específicas a dispositivos móveis em partes relevantes.

### Propriedades

    Propriedade
      Descrição

      currentTime
      Ver ou definir a posição de reprodução em segundos.

      volume
      Ver ou definir o nível do volume atual do vídeo.

      muted
      Ver ou definir o áudio como mudo.

      playbackRate
      Ver ou definir a taxa de reprodução. A velocidade de reprodução normalmente é um.

      buffered
      Informações sobre quanto do vídeo foi armazenado em buffer e está pronto para reprodução (veja a demonstração).

      currentSrc
      O endereço do vídeo em reprodução.

      videoWidth
      Largura do vídeo em pixels (pode ser diferente da largura do elemento de vídeo).

      videoHeight
      Altura do vídeo em pixels (pode ser diferente da altura do elemento de vídeo).

Tanto playbackRate ({% link_sample _code/scripted.html %}ver demonstração{% endlink_sample %}) como o volume não são compatíveis com dispositivos móveis.

### Métodos

    Método
    Descrição

      load()
      Carrega ou recarrega uma fonte de vídeo sem iniciar a reprodução. Por exemplo, quando o src do vídeo é alterado usando JavaScript.

      play()
      Reproduz um vídeo a partir do seu local atual.

      pause()
      Pausa o vídeo em seu local atual.

      canPlayType('format')
      Saiba os formatos compatíveis (confira `Verificar os formatos compatíveis`).

Em dispositivos móveis (exceto o Opera para Android), os métodos `play()` e `pause()` não funcionam, a menos que
sejam chamados em resposta a uma ação do usuário, como clicar em um botão. Veja a {% link_sample _code/scripted.html %}demonstração{% endlink_sample %}. Da mesma forma, a reprodução não pode ser iniciada para conteúdos como vídeos incorporados do YouTube.

### Eventos

Esses são os únicos subconjuntos de eventos de mídia que podem ser acionados. Consulte a página [eventos de mídia](//developer.mozilla.org/docs/Web/Guide/Events/Media_events) no Mozilla Developer Network para ver uma listagem completa.

    Evento
      Descrição

      canplaythrough
      Acionado quando há dados suficientes disponíveis a ponto de o navegador analisar que a reprodução do vídeo pode ser feita sem nenhuma interrupção.

      ended
      Acionado quando a reprodução do vídeo terminou.

      error
      Acionado em caso de erros.

      playing
      Acionado quando a reprodução do vídeo é iniciada pela primeira vez, após ter sido pausada ou quando está reiniciando.

      progress
      Acionado periodicamente para indicar o progresso do download.

      waiting
      Acionado quando uma ação está atrasada, pois está aguardando o término de outra ação.

      loadedmetadata
      Acionado quando o navegador termina de carregar os metadados do vídeo: duração, dimensões e faixas de texto.

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';

import { dbDirectors } from '/db/dbDirectors';
import { dbViolationCases } from '/db/dbViolationCases';
import { dbLog } from '/db/dbLog';
import { debug } from '/server/imports/utils/debug';
import { guardUser } from '/common/imports/guards';
import { notifyUsersForFscLog } from './helpers';

Meteor.methods({
  confiscateAllUserStocks({ userId, reason, violationCaseId }) {
    check(this.userId, String);
    check(userId, String);
    check(reason, String);
    check(violationCaseId, Match.Optional(String));

    confiscateAllUserStocks(Meteor.user(), { userId, reason, violationCaseId });

    return true;
  }
});
function confiscateAllUserStocks(currentUser, { userId, reason, violationCaseId }) {
  debug.log('confiscateAllUserStocks', { user: currentUser, userId, reason, violationCaseId });

  guardUser(currentUser).checkHasRole('fscMember');

  Meteor.users.findByIdOrThrow(userId, { fields: { _id: 1 } });

  if (violationCaseId) {
    dbViolationCases.findByIdOrThrow(violationCaseId, { fields: { _id: 1 } });
  }

  const cursor = dbDirectors.find({ userId });
  if (cursor.count() < 1) {
    return;
  }

  const directorsBulk = dbDirectors.rawCollection().initializeUnorderedBulkOp();
  const logBulk = dbLog.rawCollection().initializeUnorderedBulkOp();
  const createdAt = new Date();
  cursor.forEach((directorData) => {
    const { companyId, stocks } = directorData;

    logBulk.insert({
      logType: '沒收股份',
      userId: [currentUser._id, userId],
      companyId,
      data: { reason, stocks, violationCaseId },
      createdAt
    });

    if (dbDirectors.find({ companyId, userId: '!FSC' }).count() > 0) {
      directorsBulk
        .find({ companyId, userId: '!FSC' })
        .updateOne({ $inc: { stocks } });
    }
    else {
      directorsBulk.insert({
        companyId,
        userId: '!FSC',
        stocks,
        createdAt
      });
    }
  });
  logBulk.execute();
  directorsBulk.execute();
  dbDirectors.remove({ userId });
  notifyUsersForFscLog(userId);
}


text:
/**
 * Check a value against legacy plain object pattern.
 * This pattern is recursive, it populates buildCheckError.path with
 * current key of current object value against current pattern
 * @param  {*}      value   Value to check
 * @param  {Object} pattern Object to check value against
 * @memberof Patterns
 * @throws {Error}  Value was not conform to pattern
 * @returns {undefined}
 */
Patterns.checkLegacyObject = function checkLegacyObject(value, pattern) {
  if (!_.isObject(value)) {
    throw buildCheckError(value, pattern);
  }

  const
    patternKeys = _.keys(pattern),
    valueKeys = _.keys(value),
    excessKeys = _.difference(valueKeys, patternKeys),
    missingKeys = _.difference(patternKeys, valueKeys);

  if (excessKeys.length > 0 || missingKeys.length > 0) {
    const
      eK = excessKeys,
      mK = missingKeys,

      message = `(${eK.length > 0 ? `excess: ${eK.join(', ')}` : ''}`
        + `${eK.length > 0 && mK.length > 0 ? '; ' : ''}`
        + `${mK.length > 0 ? `missing: ${mK.join(', ')}` : ''})`;

    throw buildCheckError(value, pattern, message);
  }

  for (let key in value) {
    if (value.hasOwnProperty(key)) {
      buildCheckError.path.push({
        direction: `key ${key}`,
        of: value,
        against: pattern
      });
      K.check(value[key], pattern[key]);
    }
  }
};


text:
layout: page-fullwidth
title:  "Our First Valentines together"
subheadline:  "Chapter 9"
teaser: "How I traveled cities just to surprise and see you again."
categories:
    - story
header:
   image_fullwidth: header_unsplash_leaf.jpg
---

<s>RESERVED</s>


text:
package org.jkiss.dbeaver.ui.dialogs.connection;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.connection.DBPClientHome;
import org.jkiss.dbeaver.model.connection.DBPClientManager;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.registry.driver.DriverDescriptor;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * ClientHomesPanel
 */
public class ClientHomesPanel extends Composite
{
    private static final Log log = Log.getLog(ClientHomesPanel.class);

    private static String lastHomeDirectory;

    private Table homesTable;
    private Text idText;
    private Text pathText;
    private Text nameText;
    private Text productNameText;
    private Text productVersionText;
    private Button removeButton;
    private Font fontBold;
    private Font fontItalic;

    private DBPDriver driver;

    static class HomeInfo {
        DBPClientHome home;
        boolean isProvided;
        boolean isDefault;

        HomeInfo(DBPClientHome home)
        {
            this.home = home;
        }
    }

    public ClientHomesPanel(
        Composite parent,
        int style)
    {
        super(parent, style);

        fontBold = UIUtils.makeBoldFont(parent.getFont());
        fontItalic = UIUtils.modifyFont(parent.getFont(), SWT.ITALIC);
        addDisposeListener(new DisposeListener()
        {
            @Override
            public void widgetDisposed(DisposeEvent e)
            {
                UIUtils.dispose(fontBold);
                UIUtils.dispose(fontItalic);
            }
        });

        GridLayout layout = new GridLayout(2, false);
        setLayout(layout);

        Composite listGroup = UIUtils.createPlaceholder(this, 1, 5);
        listGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
        ((GridData)(listGroup.getLayoutData())).minimumWidth = 200;
        homesTable = new Table(listGroup, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
        homesTable.setLayoutData(new GridData(GridData.FILL_BOTH));
        homesTable.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent e)
            {
                TableItem[] selection = homesTable.getSelection();
                if (ArrayUtils.isEmpty(selection)) {
                    selectHome(null);
                } else {
                    selectHome((HomeInfo)selection[0].getData());
                }
            }
        });
        Composite buttonsGroup = UIUtils.createPlaceholder(listGroup, 2, 5);
        buttonsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_END));
        Button addButton = new Button(buttonsGroup, SWT.PUSH);
        addButton.setText(CoreMessages.controls_client_homes_panel_button_add_home);
        addButton.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent e)
            {
                addClientHome();
            }
        });
        removeButton = new Button(buttonsGroup, SWT.PUSH);
        removeButton.setText(CoreMessages.controls_client_homes_panel_button_remove_home);
        removeButton.setEnabled(false);
        removeButton.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent e)
            {
                TableItem[] selection = homesTable.getSelection();
                if (!ArrayUtils.isEmpty(selection)) {
                    removeClientHome();
                }
            }
        });

        Group infoGroup = UIUtils.createControlGroup(this, CoreMessages.controls_client_homes_panel_group_information, 2, GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL, 0);
        ((GridData)(infoGroup.getLayoutData())).minimumWidth = 300;
        idText = UIUtils.createLabelText(infoGroup, CoreMessages.controls_client_homes_panel_label_id, null, SWT.BORDER | SWT.READ_ONLY);
        pathText = UIUtils.createLabelText(infoGroup, CoreMessages.controls_client_homes_panel_label_path, null, SWT.BORDER | SWT.READ_ONLY);
        nameText = UIUtils.createLabelText(infoGroup, CoreMessages.controls_client_homes_panel_label_name, null, SWT.BORDER | SWT.READ_ONLY);
        productNameText = UIUtils.createLabelText(infoGroup, CoreMessages.controls_client_homes_panel_label_product_name, null, SWT.BORDER | SWT.READ_ONLY);
        productVersionText = UIUtils.createLabelText(infoGroup, CoreMessages.controls_client_homes_panel_label_product_version, null, SWT.BORDER | SWT.READ_ONLY);
    }

    private void removeClientHome()
    {
        int selIndex = homesTable.getSelectionIndex();
        HomeInfo info = (HomeInfo) homesTable.getItem(selIndex).getData();
        if (!info.isProvided) {
            if (UIUtils.confirmAction(
                getShell(),
                CoreMessages.controls_client_homes_panel_confirm_remove_home_title,
                NLS.bind(CoreMessages.controls_client_homes_panel_confirm_remove_home_text, info.home.getHomeId())))
            {
                homesTable.remove(selIndex);
                selectHome(null);
            }
        }
    }

    private void addClientHome()
    {
        DirectoryDialog directoryDialog = new DirectoryDialog(getShell());
        if (lastHomeDirectory != null) {
            directoryDialog.setFilterPath(lastHomeDirectory);
        }
        String homeId = directoryDialog.open();
        if (homeId == null) {
            return;
        }
        lastHomeDirectory = homeId;
        DBPClientManager clientManager = driver.getClientManager();
        if (clientManager != null) {
            createHomeItem(clientManager, homeId, false);
        }
    }

    private void selectHome(HomeInfo home)
    {
        removeButton.setEnabled(home != null && !home.isProvided);
        idText.setText(home == null ? "" : CommonUtils.notEmpty(home.home.getHomeId())); //$NON-NLS-1$
        pathText.setText(home == null ? "" : home.home.getHomePath().getAbsolutePath()); //$NON-NLS-1$
        nameText.setText(home == null ? "" : CommonUtils.notEmpty(home.home.getDisplayName())); //$NON-NLS-1$
        try {
            productNameText.setText(home == null ? "" : CommonUtils.notEmpty(home.home.getProductName())); //$NON-NLS-1$
        } catch (DBException e) {
            log.warn(e);
        }
        try {
            productVersionText.setText(home == null ? "" : CommonUtils.notEmpty(home.home.getProductVersion())); //$NON-NLS-1$
        } catch (DBException e) {
            log.warn(e);
        }
    }

    public Collection<String> getHomeIds()
    {
        java.util.List<String> homes = new ArrayList<>();
        for (TableItem item : homesTable.getItems()) {
            homes.add(((HomeInfo)item.getData()).home.getHomeId());
        }
        return homes;
    }

    public void loadHomes(DBPDriver driver)
    {
        homesTable.removeAll();
        selectHome(null);

        this.driver = driver;
        DBPClientManager clientManager = this.driver.getClientManager();
        if (clientManager == null) {
            log.error("Client manager is not supported by driver '" + driver.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
            return;
        }
        Set<String> providedHomes = new LinkedHashSet<>(
            clientManager.findClientHomeIds());
        Set<String> allHomes = new LinkedHashSet<>(providedHomes);
        allHomes.addAll(driver.getClientHomeIds());

        for (String homeId : allHomes) {
            TableItem item = createHomeItem(clientManager, homeId, providedHomes.contains(homeId));
            if (item != null) {
                HomeInfo homeInfo = (HomeInfo) item.getData();
                if (homeInfo.isDefault) {
                    homesTable.setSelection(homesTable.indexOf(item));
                    selectHome(homeInfo);
                }
            }
        }
    }

    private TableItem createHomeItem(DBPClientManager clientManager, String homeId, boolean provided)
    {
        DBPClientHome home;
        try {
            home = clientManager.getClientHome(homeId);
            if (home == null) {
                log.warn("Home '" + homeId + "' is not supported"); //$NON-NLS-1$ //$NON-NLS-2$
                return null;
            }
        } catch (Exception e) {
            log.error(e);
            return null;
        }
        HomeInfo homeInfo = new HomeInfo(home);
        homeInfo.isProvided = provided;
        homeInfo.isDefault = home.getHomeId().equals(clientManager.getDefaultClientHomeId());
        TableItem homeItem = new TableItem(homesTable, SWT.NONE);
        homeItem.setText(home.getDisplayName());
        homeItem.setImage(DBeaverIcons.getImage(UIIcon.HOME));
        homeItem.setData(homeInfo);
        if (!homeInfo.isProvided) {
            homeItem.setFont(fontItalic);
        } else {
            if (homeInfo.isDefault) {
                homeItem.setFont(fontBold);
            }
        }
        return homeItem;
    }

    private String getSelectedHome()
    {
        TableItem[] selection = homesTable.getSelection();
        if (ArrayUtils.isEmpty(selection)) {
            return null;
        } else {
            return ((HomeInfo)selection[0].getData()).home.getHomeId();
        }
    }

    private static class ChooserDialog extends org.eclipse.jface.dialogs.Dialog {
        private DBPDriver driver;
        private ClientHomesPanel panel;
        private String selectedHome;

        protected ChooserDialog(Shell parentShell, DBPDriver driver)
        {
            super(parentShell);
            this.driver = driver;
        }

        @Override
        protected Control createDialogArea(Composite parent)
        {
            getShell().setText(CoreMessages.controls_client_homes_panel_dialog_title);

            panel = new ClientHomesPanel(parent, SWT.NONE);
            GridData gd = new GridData(GridData.FILL_BOTH);
            //gd.widthHint = 500;
            panel.setLayoutData(gd);
            panel.loadHomes(driver);

            return parent;
        }

        @Override
        protected boolean isResizable()
        {
            return true;
        }

        @Override
        protected void buttonPressed(int buttonId)
        {
            if (IDialogConstants.OK_ID == buttonId) {
                selectedHome = panel.getSelectedHome();
                if (driver instanceof DriverDescriptor) {
                    ((DriverDescriptor) driver).setClientHomeIds(panel.getHomeIds());
                    ((DriverDescriptor) driver).getProviderDescriptor().getRegistry().saveDrivers();
                }
            }
            super.buttonPressed(buttonId);
        }
    }

    public static String chooseClientHome(Shell parent, DBPDriver driver)
    {
        ChooserDialog dialog = new ChooserDialog(parent, driver);
        if (dialog.open() == IDialogConstants.OK_ID) {
            return dialog.selectedHome;
        } else {
            return null;
        }
    }

}


text:
package util;

import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;

import org.apache.uima.fit.util.FSCollectionFactory;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;

import com.google.common.collect.Range;

import edu.cmu.lti.oaqa.type.answer.Answer;
import edu.cmu.lti.oaqa.type.input.Question;
import edu.cmu.lti.oaqa.type.nlp.Token;
import edu.cmu.lti.oaqa.type.retrieval.AbstractQuery;
import edu.cmu.lti.oaqa.type.retrieval.ConceptSearchResult;
import edu.cmu.lti.oaqa.type.retrieval.Document;
import edu.cmu.lti.oaqa.type.retrieval.Passage;
import edu.cmu.lti.oaqa.type.retrieval.QueryConcept;
import edu.cmu.lti.oaqa.type.retrieval.SearchResult;
import edu.cmu.lti.oaqa.type.retrieval.TripleSearchResult;

public class TypeUtil {

  public static Question getQuestion(JCas jcas) {
    return JCasUtil.selectSingle(jcas, Question.class);
  }

  public static List<Token> getOrderedTokens(JCas jcas) {
    return JCasUtil.select(jcas, Token.class).stream()
            .sorted(Comparator.comparing(Token::getBegin)).collect(toList());
  }

  public static Collection<AbstractQuery> getAbstractQueries(JCas jcas) {
    return JCasUtil.select(jcas, AbstractQuery.class);
  }

  public static AbstractQuery getAbstractQueriesCombined(JCas jcas) {
    List<QueryConcept> conceptsCombined = getAbstractQueries(jcas).stream()
            .flatMap(a -> FSCollectionFactory.create(a.getConcepts(), QueryConcept.class).stream())
            .collect(toList());
    return TypeFactory.createAbstractQuery(jcas, conceptsCombined);
  }

  public static final Comparator<SearchResult> SEARCH_RESULT_SCORE_COMPARATOR = Comparator
          .comparing(SearchResult::getScore).reversed();

  public static <T extends SearchResult> List<T> rankedSearchResultsByScore(Collection<T> results,
          int hitSize) {
    List<T> sorted = results.stream().sorted(SEARCH_RESULT_SCORE_COMPARATOR).limit(hitSize)
            .collect(toList());
    IntStream.range(0, sorted.size()).forEach(rank -> sorted.get(rank).setRank(rank));
    return sorted;
  }

  public static final Comparator<SearchResult> SEARCH_RESULT_RANK_COMPARATOR = Comparator
          .comparing(SearchResult::getRank);

  private static <T extends SearchResult> Collection<T> rankedSearchResultsByRank(
          Collection<T> results) {
    return results.stream().sorted(SEARCH_RESULT_RANK_COMPARATOR)
            .collect(toCollection(ArrayList::new));
  }

  public static Collection<ConceptSearchResult> getRankedConceptSearchResults(JCas jcas) {
    return rankedSearchResultsByRank(JCasUtil.select(jcas, ConceptSearchResult.class));
  }

  public static Collection<TripleSearchResult> getRankedTripleSearchResults(JCas jcas) {
    return rankedSearchResultsByRank(JCasUtil.select(jcas, TripleSearchResult.class));
  }

  public static Collection<Document> getRankedDocuments(JCas jcas) {
    return rankedSearchResultsByRank(JCasUtil.select(jcas, Document.class));
  }

  public static Collection<Passage> getRankedPassages(JCas jcas) {
    return rankedSearchResultsByRank(JCasUtil.select(jcas, Passage.class));
  }

  public static Collection<Answer> getAnswers(JCas jcas) {
    return JCasUtil.select(jcas, Answer.class);
  }

  public static Range<Integer> spanRange(Annotation annotation) {
    return Range.closedOpen(annotation.getBegin(), annotation.getEnd());
  }

  public static Range<Integer> spanRangeInSection(Passage passage) {
    return Range.closedOpen(passage.getOffsetInBeginSection(), passage.getOffsetInEndSection());
  }

}


text:
package io.bot.email.model;

public class BotContext {
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wq.android.lightannotation">

    <application android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
>

    </application>

</manifest>


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Survey;

/**
 * SurveySearch represents the model behind the search form about `app\models\Survey`.
 */
class SurveySearch extends Survey
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'global_score', 'guest_country_id'], 'integer'],
            [['checkout_date', 'apartment', 'source_title', 'guest_name', 'guest_email', 'guest_address', 'touroperator_name', 'best_employee_name', 'best_employee_group_name', 'good_things', 'bad_things', 'met_expectation_title', 'evolution_title', 'suggestions'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Survey::find()->with(['source.translations', 'guestCountry.translations']);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort'=> ['defaultOrder' => ['id' => SORT_DESC]]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'global_score' => $this->global_score,
            'guest_country_id' => $this->guest_country_id,
        ]);

        $co_from = $co_to = null;
        if ($this->checkout_date) list($co_from, $co_to) = $this->fillInterval($this->checkout_date);

        $query->andFilterWhere(['like', 'apartment', $this->apartment])
            ->andFilterWhere(['between', 'checkout_date', $co_from, $co_to])
            ->andFilterWhere(['like', 'source_title', $this->source_title])
            ->andFilterWhere(['like', 'guest_name', $this->guest_name])
            ->andFilterWhere(['like', 'guest_email', $this->guest_email])
            ->andFilterWhere(['like', 'guest_address', $this->guest_address])
            ->andFilterWhere(['like', 'touroperator_name', $this->touroperator_name])
            ->andFilterWhere(['like', 'best_employee_name', $this->best_employee_name])
            ->andFilterWhere(['like', 'best_employee_group_name', $this->best_employee_group_name])
            ->andFilterWhere(['like', 'good_things', $this->good_things])
            ->andFilterWhere(['like', 'bad_things', $this->bad_things])
            ->andFilterWhere(['like', 'met_expectation_title', $this->met_expectation_title])
            ->andFilterWhere(['like', 'evolution_title', $this->evolution_title])
            ->andFilterWhere(['like', 'suggestions', $this->suggestions]);

        return $dataProvider;
    }

    protected function fillInterval($adate) {
        $co_from = $adate . substr('0000-00-00', strlen($adate));
        $co_year = intval(substr($co_from, 0, 4));
        if (!$co_year) $co_year = 1970;
        $co_month = intval(substr($co_from, 5, 2));
        if (!$co_month) $co_month = 1;
        $co_day = intval(substr($co_from, 8, 2));
        if (!$co_day) $co_day = 1;
        $co_from = date('Y-m-d', mktime(0, 0, 0, $co_month, $co_day, $co_year));

        $co_to = $adate . substr('9999-99-99', strlen($adate));
        $co_year = intval(substr($co_to, 0, 4));
        if (!$co_year || $co_year > 2037) $co_year = 2037;
        $co_month = intval(substr($co_to, 5, 2));
        if (!$co_month || $co_month > 12) $co_month = 12;
        $co_day = intval(substr($co_to, 8, 2));
        $max_day = date('t', mktime(0, 0, 0, $co_month, 1, $co_year));
        if (!$co_day || $co_day > $max_day) $co_day = $max_day;
        $co_to = date('Y-m-d', mktime(0, 0, 0, $co_month, $co_day, $co_year));

        return [$co_from, $co_to];
    }
}


text:
package product_rate_plans

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/authclub/billforward/models"
)

// GetAllRatePlansReader is a Reader for the GetAllRatePlans structure.
type GetAllRatePlansReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *GetAllRatePlansReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewGetAllRatePlansOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	default:
		result := NewGetAllRatePlansDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		if response.Code()/100 == 2 {
			return result, nil
		}
		return nil, result
	}
}

// NewGetAllRatePlansOK creates a GetAllRatePlansOK with default headers values
func NewGetAllRatePlansOK() *GetAllRatePlansOK {
	return &GetAllRatePlansOK{}
}

/*GetAllRatePlansOK handles this case with default header values.

success
*/
type GetAllRatePlansOK struct {
	Payload *models.ProductRatePlanPagedMetadata
}

func (o *GetAllRatePlansOK) Error() string {
	return fmt.Sprintf("[GET /product-rate-plans][%d] getAllRatePlansOK  %+v", 200, o.Payload)
}

func (o *GetAllRatePlansOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.ProductRatePlanPagedMetadata)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewGetAllRatePlansDefault creates a GetAllRatePlansDefault with default headers values
func NewGetAllRatePlansDefault(code int) *GetAllRatePlansDefault {
	return &GetAllRatePlansDefault{
		_statusCode: code,
	}
}

/*GetAllRatePlansDefault handles this case with default header values.

error
*/
type GetAllRatePlansDefault struct {
	_statusCode int

	Payload *models.BFError
}

// Code gets the status code for the get all rate plans default response
func (o *GetAllRatePlansDefault) Code() int {
	return o._statusCode
}

func (o *GetAllRatePlansDefault) Error() string {
	return fmt.Sprintf("[GET /product-rate-plans][%d] getAllRatePlans default  %+v", o._statusCode, o.Payload)
}

func (o *GetAllRatePlansDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.BFError)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
using System.Linq;
using Entitas.CodeGenerator;

namespace Entitas.CodeGenerator {
    public class PoolsGenerator : IPoolCodeGenerator {

        const string FILE_NAME = "Pools";
        const string CLASS_TEMPLATE = @"using Entitas;

public static class Pools {{{0}{1}
}}";

        const string ALL_POOLS_GETTER = @"

    static Pool[] _allPools;

    public static Pool[] allPools {{
        get {{
            if (_allPools == null) {{
                _allPools = new [] {{ {0} }};
            }}

            return _allPools;
        }}
    }}";

        const string GETTER = @"

    static Pool _{0};

    public static Pool {0} {{
        get {{
            if (_{0} == null) {{
                _{0} = new Pool({1}" + CodeGenerator.DEFAULT_INDICES_LOOKUP_TAG + @".TotalComponents);
                #if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR)
                var poolObserver = new Entitas.Unity.VisualDebugging.PoolObserver(_{0}, {1}" + CodeGenerator.DEFAULT_INDICES_LOOKUP_TAG + @".componentNames, {1}" + CodeGenerator.DEFAULT_INDICES_LOOKUP_TAG + @".componentTypes, ""{2}Pool"");
                UnityEngine.Object.DontDestroyOnLoad(poolObserver.entitiesContainer);
                #endif
            }}

            return _{0};
        }}
    }}";

        public CodeGenFile[] Generate(string[] poolNames) {
            const string DEFAULT_POOL_NAME = "pool";

            var allPools = poolNames == null || poolNames.Length == 0
                ? string.Format(ALL_POOLS_GETTER, DEFAULT_POOL_NAME)
                : string.Format(ALL_POOLS_GETTER, string.Join(", ", poolNames.Select(poolName => poolName.LowercaseFirst()).ToArray()));

            var getters = poolNames == null || poolNames.Length == 0
                ? string.Format(GETTER, DEFAULT_POOL_NAME, string.Empty, string.Empty)
                : poolNames.Aggregate(string.Empty, (acc, poolName) =>
                    acc + string.Format(GETTER, poolName.LowercaseFirst(), poolName, poolName + " "));

            return new [] { new CodeGenFile {
                    fileName = FILE_NAME,
                    fileContent = string.Format(CLASS_TEMPLATE, allPools, getters).ToUnixLineEndings()
                }
            };
        }
    }
}


text:
import * as IStyle from './IStyle';

type eventFunc = (ev: any, chart: any) => void;

export interface ITooltip {
  offsetX?: number;
  offsetY?: number;
  items?: object[];
  show?: boolean;
  triggerOn?: string | string[];
  triggerOff?: string | string[];
  showTitle?: boolean;
  showCrosshairs?: boolean;
  crosshairsStyle?: IStyle.ILineStyle;
  showTooltipMarker?: boolean;
  background?: any;
  titleStyle?: IStyle.ITextStyle;
  nameStyle?: IStyle.ITextStyle;
  valueStyle?: IStyle.ITextStyle;
  showItemMarker?: boolean;
  itemMarkerStyle?: any;
  custom?: boolean;
  onShow?: eventFunc;
  onHide?: eventFunc;
  onChange?: eventFunc;
}

type ITooltipConfig = boolean | ITooltip;

export default ITooltipConfig;


text:
namespace easynet{

class EventLoop;
class Channel;

class Epoller
{
public:
	using ChannelArray = std::vector<Channel*>;

	Epoller(EventLoop *loop);
	~Epoller() { close(); }

	Epoller(const Epoller &rhs) = delete;
	Epoller& operator=(const Epoller &rhs) = delete;

	void poll(int timeoutMillis, ChannelArray *channels, ChannelArray *listenChannels);
	void updateChannel(Channel *channel);

private:
	void getActiveChannels(int numEvents, ChannelArray *channels, ChannelArray *listenChannels);
	int  update(int oper, Channel *channel);
	void close() { ::close(epollFd_); }

	std::string getEventsName(int events);
	std::string getEpollCtlOperName(int oper);

	EventLoop *loop_;  // the EventLoop of the epoller belongs to
	int epollFd_;

	std::vector<epoll_event> events_;  // buffers for epoller to return triggered events
};

}
#endif


text:
package org.apache.hadoop.hdfs.server.federation.store;

import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMENODES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.NAMESERVICES;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.ROUTERS;
import static org.apache.hadoop.hdfs.server.federation.FederationTestUtils.verifyException;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.clearRecords;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.createMockRegistrationForNamenode;
import static org.apache.hadoop.hdfs.server.federation.store.FederationStateStoreTestUtils.synchronizeRecords;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamenodeServiceState;
import org.apache.hadoop.hdfs.server.federation.router.RBFConfigKeys;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.GetNamenodeRegistrationsResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatRequest;
import org.apache.hadoop.hdfs.server.federation.store.protocol.NamenodeHeartbeatResponse;
import org.apache.hadoop.hdfs.server.federation.store.protocol.UpdateNamenodeRegistrationRequest;
import org.apache.hadoop.hdfs.server.federation.store.records.MembershipState;
import org.apache.hadoop.util.Time;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Test the basic {@link MembershipStore} membership functionality.
 */
public class TestStateStoreMembershipState extends TestStateStoreBase {

  private static MembershipStore membershipStore;

  @BeforeClass
  public static void create() {
    // Reduce expirations to 5 seconds
    getConf().setLong(
        RBFConfigKeys.FEDERATION_STORE_MEMBERSHIP_EXPIRATION_MS,
        TimeUnit.SECONDS.toMillis(5));
  }

  @Before
  public void setup() throws IOException, InterruptedException {

    membershipStore =
        getStateStore().getRegisteredRecordStore(MembershipStore.class);

    // Clear NN registrations
    assertTrue(clearRecords(getStateStore(), MembershipState.class));
  }

  @Test
  public void testNamenodeStateOverride() throws Exception {
    // Populate the state store
    // 1) ns0:nn0 - Standby
    String ns = "ns0";
    String nn = "nn0";
    MembershipState report = createRegistration(
        ns, nn, ROUTERS[1], FederationNamenodeServiceState.STANDBY);
    assertTrue(namenodeHeartbeat(report));

    // Load data into cache and calculate quorum
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    MembershipState existingState = getNamenodeRegistration(ns, nn);
    assertEquals(
        FederationNamenodeServiceState.STANDBY, existingState.getState());

    // Override cache
    UpdateNamenodeRegistrationRequest request =
        UpdateNamenodeRegistrationRequest.newInstance(
            ns, nn, FederationNamenodeServiceState.ACTIVE);
    assertTrue(membershipStore.updateNamenodeRegistration(request).getResult());

    MembershipState newState = getNamenodeRegistration(ns, nn);
    assertEquals(FederationNamenodeServiceState.ACTIVE, newState.getState());
  }

  @Test
  public void testStateStoreDisconnected() throws Exception {

    // Close the data store driver
    getStateStore().closeDriver();
    assertFalse(getStateStore().isDriverReady());

    NamenodeHeartbeatRequest hbRequest = NamenodeHeartbeatRequest.newInstance();
    hbRequest.setNamenodeMembership(
        createMockRegistrationForNamenode(
            "test", "test", FederationNamenodeServiceState.UNAVAILABLE));
    verifyException(membershipStore, "namenodeHeartbeat",
        StateStoreUnavailableException.class,
        new Class[] {NamenodeHeartbeatRequest.class},
        new Object[] {hbRequest });

    // Information from cache, no exception should be triggered for these
    // TODO - should cached info expire at some point?
    GetNamenodeRegistrationsRequest getRequest =
        GetNamenodeRegistrationsRequest.newInstance();
    verifyException(membershipStore,
        "getNamenodeRegistrations", null,
        new Class[] {GetNamenodeRegistrationsRequest.class},
        new Object[] {getRequest});

    verifyException(membershipStore,
        "getExpiredNamenodeRegistrations", null,
        new Class[] {GetNamenodeRegistrationsRequest.class},
        new Object[] {getRequest});

    UpdateNamenodeRegistrationRequest overrideRequest =
        UpdateNamenodeRegistrationRequest.newInstance();
    verifyException(membershipStore,
        "updateNamenodeRegistration", null,
        new Class[] {UpdateNamenodeRegistrationRequest.class},
        new Object[] {overrideRequest});
  }

  private void registerAndLoadRegistrations(
      List<MembershipState> registrationList) throws IOException {
    // Populate
    assertTrue(synchronizeRecords(
        getStateStore(), registrationList, MembershipState.class));

    // Load into cache
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));
  }

  private MembershipState createRegistration(String ns, String nn,
      String router, FederationNamenodeServiceState state) throws IOException {
    MembershipState record = MembershipState.newInstance(
        router, ns,
        nn, "testcluster", "testblock-" + ns, "testrpc-"+ ns + nn,
        "testservice-"+ ns + nn, "testlifeline-"+ ns + nn,
        "testweb-" + ns + nn, state, false);
    return record;
  }

  @Test
  public void testRegistrationMajorityQuorum()
      throws InterruptedException, IOException {

    // Populate the state store with a set of non-matching elements
    // 1) ns0:nn0 - Standby (newest)
    // 2) ns0:nn0 - Active (oldest)
    // 3) ns0:nn0 - Active (2nd oldest)
    // 4) ns0:nn0 - Active (3nd oldest element, newest active element)
    // Verify the selected entry is the newest majority opinion (4)
    String ns = "ns0";
    String nn = "nn0";

    // Active - oldest
    MembershipState report = createRegistration(
        ns, nn, ROUTERS[1], FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report));
    Thread.sleep(1000);

    // Active - 2nd oldest
    report = createRegistration(
        ns, nn, ROUTERS[2], FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report));
    Thread.sleep(1000);

    // Active - 3rd oldest, newest active element
    report = createRegistration(
        ns, nn, ROUTERS[3], FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report));

    // standby - newest overall
    report = createRegistration(
        ns, nn, ROUTERS[0], FederationNamenodeServiceState.STANDBY);
    assertTrue(namenodeHeartbeat(report));

    // Load and calculate quorum
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    // Verify quorum entry
    MembershipState quorumEntry = getNamenodeRegistration(
        report.getNameserviceId(), report.getNamenodeId());
    assertNotNull(quorumEntry);
    assertEquals(quorumEntry.getRouterId(), ROUTERS[3]);
  }

  @Test
  public void testRegistrationQuorumExcludesExpired()
      throws InterruptedException, IOException {

    // Populate the state store with some expired entries and verify the expired
    // entries are ignored.
    // 1) ns0:nn0 - Active
    // 2) ns0:nn0 - Expired
    // 3) ns0:nn0 - Expired
    // 4) ns0:nn0 - Expired
    // Verify the selected entry is the active entry
    List<MembershipState> registrationList = new ArrayList<>();
    String ns = "ns0";
    String nn = "nn0";
    String rpcAddress = "testrpcaddress";
    String serviceAddress = "testserviceaddress";
    String lifelineAddress = "testlifelineaddress";
    String blockPoolId = "testblockpool";
    String clusterId = "testcluster";
    String webAddress = "testwebaddress";
    boolean safemode = false;

    // Active
    MembershipState record = MembershipState.newInstance(
        ROUTERS[0], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.ACTIVE, safemode);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[1], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[2], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[3], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    registrationList.add(record);
    registerAndLoadRegistrations(registrationList);

    // Verify quorum entry chooses active membership
    MembershipState quorumEntry = getNamenodeRegistration(
        record.getNameserviceId(), record.getNamenodeId());
    assertNotNull(quorumEntry);
    assertEquals(ROUTERS[0], quorumEntry.getRouterId());
  }

  @Test
  public void testRegistrationQuorumAllExpired() throws IOException {

    // 1) ns0:nn0 - Expired (oldest)
    // 2) ns0:nn0 - Expired
    // 3) ns0:nn0 - Expired
    // 4) ns0:nn0 - Expired
    // Verify no entry is either selected or cached
    List<MembershipState> registrationList = new ArrayList<>();
    String ns = NAMESERVICES[0];
    String nn = NAMENODES[0];
    String rpcAddress = "testrpcaddress";
    String serviceAddress = "testserviceaddress";
    String lifelineAddress = "testlifelineaddress";
    String blockPoolId = "testblockpool";
    String clusterId = "testcluster";
    String webAddress = "testwebaddress";
    boolean safemode = false;
    long startingTime = Time.now();

    // Expired
    MembershipState record = MembershipState.newInstance(
        ROUTERS[0], ns, nn, clusterId, blockPoolId,
        rpcAddress, webAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    record.setDateModified(startingTime - 10000);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[1], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    record.setDateModified(startingTime);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[2], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    record.setDateModified(startingTime);
    registrationList.add(record);

    // Expired
    record = MembershipState.newInstance(
        ROUTERS[3], ns, nn, clusterId, blockPoolId,
        rpcAddress, serviceAddress, lifelineAddress, webAddress,
        FederationNamenodeServiceState.EXPIRED, safemode);
    record.setDateModified(startingTime);
    registrationList.add(record);

    registerAndLoadRegistrations(registrationList);

    // Verify no entry is found for this nameservice
    assertNull(getNamenodeRegistration(
        record.getNameserviceId(), record.getNamenodeId()));
  }

  @Test
  public void testRegistrationNoQuorum()
      throws InterruptedException, IOException {

    // Populate the state store with a set of non-matching elements
    // 1) ns0:nn0 - Standby (newest)
    // 2) ns0:nn0 - Standby (oldest)
    // 3) ns0:nn0 - Active (2nd oldest)
    // 4) ns0:nn0 - Active (3nd oldest element, newest active element)
    // Verify the selected entry is the newest entry (1)
    MembershipState report1 = createRegistration(
        NAMESERVICES[0], NAMENODES[0], ROUTERS[1],
        FederationNamenodeServiceState.STANDBY);
    assertTrue(namenodeHeartbeat(report1));
    Thread.sleep(100);
    MembershipState report2 = createRegistration(
        NAMESERVICES[0], NAMENODES[0], ROUTERS[2],
        FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report2));
    Thread.sleep(100);
    MembershipState report3 = createRegistration(
        NAMESERVICES[0], NAMENODES[0], ROUTERS[3],
        FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report3));
    Thread.sleep(100);
    MembershipState report4 = createRegistration(
        NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
        FederationNamenodeServiceState.STANDBY);
    assertTrue(namenodeHeartbeat(report4));

    // Load and calculate quorum
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    // Verify quorum entry uses the newest data, even though it is standby
    MembershipState quorumEntry = getNamenodeRegistration(
        report1.getNameserviceId(), report1.getNamenodeId());
    assertNotNull(quorumEntry);
    assertEquals(ROUTERS[0], quorumEntry.getRouterId());
    assertEquals(
        FederationNamenodeServiceState.STANDBY, quorumEntry.getState());
  }

  @Test
  public void testRegistrationExpired()
      throws InterruptedException, IOException {

    // Populate the state store with a single NN element
    // 1) ns0:nn0 - Active
    // Wait for the entry to expire without heartbeating
    // Verify the NN entry is populated as EXPIRED internally in the state store

    MembershipState report = createRegistration(
        NAMESERVICES[0], NAMENODES[0], ROUTERS[0],
        FederationNamenodeServiceState.ACTIVE);
    assertTrue(namenodeHeartbeat(report));

    // Load cache
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    // Verify quorum and entry
    MembershipState quorumEntry = getNamenodeRegistration(
        report.getNameserviceId(), report.getNamenodeId());
    assertNotNull(quorumEntry);
    assertEquals(ROUTERS[0], quorumEntry.getRouterId());
    assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());

    // Wait past expiration (set in conf to 5 seconds)
    Thread.sleep(6000);
    // Reload cache
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    // Verify entry is now expired and is no longer in the cache
    quorumEntry = getNamenodeRegistration(NAMESERVICES[0], NAMENODES[0]);
    assertNull(quorumEntry);

    // Verify entry is now expired and can't be used by RPC service
    quorumEntry = getNamenodeRegistration(
        report.getNameserviceId(), report.getNamenodeId());
    assertNull(quorumEntry);

    // Heartbeat again, updates dateModified
    assertTrue(namenodeHeartbeat(report));
    // Reload cache
    assertTrue(getStateStore().loadCache(MembershipStore.class, true));

    // Verify updated entry marked as active and is accessible to RPC server
    quorumEntry = getNamenodeRegistration(
        report.getNameserviceId(), report.getNamenodeId());
    assertNotNull(quorumEntry);
    assertEquals(ROUTERS[0], quorumEntry.getRouterId());
    assertEquals(FederationNamenodeServiceState.ACTIVE, quorumEntry.getState());
  }

  /**
   * Get a single namenode membership record from the store.
   *
   * @param nsId The HDFS nameservice ID to search for
   * @param nnId The HDFS namenode ID to search for
   * @return The single NamenodeMembershipRecord that matches the query or null
   *         if not found.
   * @throws IOException if the query could not be executed.
   */
  private MembershipState getNamenodeRegistration(
      final String nsId, final String nnId) throws IOException {

    MembershipState partial = MembershipState.newInstance();
    partial.setNameserviceId(nsId);
    partial.setNamenodeId(nnId);
    GetNamenodeRegistrationsRequest request =
        GetNamenodeRegistrationsRequest.newInstance(partial);
    GetNamenodeRegistrationsResponse response =
        membershipStore.getNamenodeRegistrations(request);

    List<MembershipState> results = response.getNamenodeMemberships();
    if (results != null && results.size() == 1) {
      MembershipState record = results.get(0);
      return record;
    }
    return null;
  }

  /**
   * Register a namenode heartbeat with the state store.
   *
   * @param store FederationMembershipStateStore instance to retrieve the
   *          membership data records.
   * @param namenode A fully populated namenode membership record to be
   *          committed to the data store.
   * @return True if successful, false otherwise.
   * @throws IOException if the state store query could not be performed.
   */
  private boolean namenodeHeartbeat(MembershipState namenode)
      throws IOException {

    NamenodeHeartbeatRequest request =
        NamenodeHeartbeatRequest.newInstance(namenode);
    NamenodeHeartbeatResponse response =
        membershipStore.namenodeHeartbeat(request);
    return response.getResult();
  }
}


text:
<%= header %>
<!--
	Tests setting `BOOMR_page_ready` then calling `page_ready()`
-->
<%= boomerangScript %>
<script>
BOOMR_test.init({
	autorun: false,
	testAfterOnBeacon: 1
});

window.onload = function() {
	window.BOOMR_page_ready = window.pageReadyTs = +(new Date()) - 1000;
	BOOMR.page_ready();
};
</script>
<script src="06-page-ready-timestamp-global.js" type="text/javascript"></script>
<!-- delay the page load event -->
<img src="/delay?delay=2000&file=/assets/img.jpg" />
<%= footer %>


text:
#ifndef MSGRAPHSERVICEREMINDER_H
#define MSGRAPHSERVICEREMINDER_H

#import <Foundation/Foundation.h>
#import "core/MSOrcChangesTrackingArray.h"

@class MSGraphServiceDateTimeTimeZone;
@class MSGraphServiceLocation;
#import "core/MSOrcBaseEntity.h"
#import "api/MSOrcInteroperableWithDictionary.h"

/** Interface MSGraphServiceReminder
 *
 */
__deprecated_msg("This SDK is deprecated. Please review the README for further information (https://github.com/OfficeDev/Microsoft-Graph-SDK-iOS).")
@interface MSGraphServiceReminder : MSOrcBaseEntity <MSOrcInteroperableWithDictionary>

/** Property eventId
 *
 */
@property (nonatomic,  copy, setter=setEventId:, getter=eventId) NSString * eventId;

/** Property eventStartTime
 *
 */
@property (nonatomic,  copy, setter=setEventStartTime:, getter=eventStartTime) MSGraphServiceDateTimeTimeZone * eventStartTime;

/** Property eventEndTime
 *
 */
@property (nonatomic,  copy, setter=setEventEndTime:, getter=eventEndTime) MSGraphServiceDateTimeTimeZone * eventEndTime;

/** Property changeKey
 *
 */
@property (nonatomic,  copy, setter=setChangeKey:, getter=changeKey) NSString * changeKey;

/** Property eventSubject
 *
 */
@property (nonatomic,  copy, setter=setEventSubject:, getter=eventSubject) NSString * eventSubject;

/** Property eventLocation
 *
 */
@property (nonatomic,  copy, setter=setEventLocation:, getter=eventLocation) MSGraphServiceLocation * eventLocation;

/** Property eventWebLink
 *
 */
@property (nonatomic,  copy, setter=setEventWebLink:, getter=eventWebLink) NSString * eventWebLink;

/** Property reminderFireTime
 *
 */
@property (nonatomic,  copy, setter=setReminderFireTime:, getter=reminderFireTime) MSGraphServiceDateTimeTimeZone * reminderFireTime;

+ (NSDictionary *) $$$_$$$propertiesNamesMappings;

@end

#endif


text:
package com.addhen.android.raiburari.presentation.view.ui.listener;

/**
 * ObservableScrollView Listener
 *
 * @author Henry Addo
 */
public interface ObservableScrollViewListener {

  /**
   * Called when the scroll change events occurred.
   * This won't be called just after the view is laid out, so if you'd like to
   * initialize the position of your views with this method, you should call this manually
   * or invoke scroll as appropriate.
   *
   * @param scrollY scroll position in Y axis
   * @param firstScroll true when this is called for the first time in the consecutive motion
   * events
   * @param dragging true when the view is dragged and false when the view is scrolled in the
   * inertia
   */
  void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging);

  /**
   * Called when the down motion event occurred.
   */
  void onDownMotionEvent();

  /**
   * Called when the dragging ended or canceled.
   *
   * @param observableScrollState state to indicate the scroll direction
   */
  void onUpOrCancelMotionEvent(ObservableScrollState observableScrollState);
}


text:
@class DVTSourceControlRemoteRepository, DVTSourceControlWorkingCopy, DVTSourceControlWorkspaceBlueprint, IDESourceControlWorkingTree, NSAttributedString, NSMenuItem, NSString;

@interface IDESourceControlWorkingCopyMenuObject : NSObject
{
    DVTSourceControlWorkingCopy *_workingCopy;
    DVTSourceControlRemoteRepository *_remoteRepository;
    DVTSourceControlWorkspaceBlueprint *_blueprint;
    IDESourceControlWorkingTree *_workingTree;
    NSMenuItem *_menuItem;
    NSString *_workingCopyName;
    NSString *_currentBranchName;
    NSAttributedString *_menuItemAttributedTitle;
}

+ (id)titleForWorkingCopyName:(id)arg1 branchName:(id)arg2 dimmingIcons:(BOOL)arg3 warningIcon:(BOOL)arg4 includeIconInTitles:(BOOL)arg5;
+ (id)titleForWorkingCopyName:(id)arg1 branchName:(id)arg2 dimmingIcons:(BOOL)arg3 includeIconInTitles:(BOOL)arg4;
+ (id)_iconAsAttributedStringForImage:(id)arg1;
+ (id)_warningImage;
+ (id)_branchImage;
+ (id)_workingCopyConfigurationImage;
+ (id)_workingCopyImage;
@property(readonly) IDESourceControlWorkingTree *workingTree; // @synthesize workingTree=_workingTree;
@property(readonly) DVTSourceControlWorkspaceBlueprint *blueprint; // @synthesize blueprint=_blueprint;
@property(readonly) DVTSourceControlRemoteRepository *remoteRepository; // @synthesize remoteRepository=_remoteRepository;
@property(readonly) DVTSourceControlWorkingCopy *workingCopy; // @synthesize workingCopy=_workingCopy;
- (void).cxx_destruct;
- (void)dealloc;
- (void)menuDidClose;
- (void)teardown;
@property(readonly) NSMenuItem *menuItem;
- (void)loadMenuItem;
- (id)initWithWorkingTree:(id)arg1;
- (id)initWithMissingRepository:(id)arg1 fromBlueprint:(id)arg2;
- (id)initWithWorkingCopy:(id)arg1;

@end


text:
package org.jboss.netty.handler.traffic;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import org.jboss.netty.util.ObjectSizeEstimator;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;

/**
 * This implementation of the {@link AbstractTrafficShapingHandler} is for global
 * traffic shaping, that is to say a global limitation of the bandwidth, whatever
 * the number of opened channels.

 *
 * The general use should be as follow:

 *

 *
Create your unique GlobalTrafficShapingHandler like:

 * <tt>GlobalTrafficShapingHandler myHandler = new GlobalTrafficShapingHandler(timer);</tt>

 * timer could be created using <tt>HashedWheelTimer</tt>

 * <tt>pipeline.addLast("GLOBAL_TRAFFIC_SHAPING", myHandler);</tt>

 *
 * Note that this handler has a Pipeline Coverage of "all" which means only one such handler must be created
 * and shared among all channels as the counter must be shared among all channels.

 *
 * Other arguments can be passed like write or read limitation (in bytes/s where 0 means no limitation)
 * or the check interval (in millisecond) that represents the delay between two computations of the
 * bandwidth and so the call back of the doAccounting method (0 means no accounting at all).

 *
 * A value of 0 means no accounting for checkInterval. If you need traffic shaping but no such accounting,
 * it is recommended to set a positive value, even if it is high since the precision of the
 * Traffic Shaping depends on the period where the traffic is computed. The highest the interval,
 * the less precise the traffic shaping will be. It is suggested as higher value something close
 * to 5 or 10 minutes.

 *
 * maxTimeToWait, by default set to 15s, allows to specify an upper bound of time shaping.

 *

 *
Add it in your pipeline, before a recommended {@link ExecutionHandler} (like
 * {@link OrderedMemoryAwareThreadPoolExecutor} or {@link MemoryAwareThreadPoolExecutor}).

 * <tt>pipeline.addLast("GLOBAL_TRAFFIC_SHAPING", myHandler);</tt>

 *

 *
When you shutdown your application, release all the external resources
 * by calling:

 * <tt>myHandler.releaseExternalResources();</tt>

 *

 *

 */
@Sharable
public class GlobalTrafficShapingHandler extends AbstractTrafficShapingHandler {
    private Map<Integer, List<ToSend>> messagesQueues = new HashMap<Integer, List<ToSend>>();

    /**
     * Create the global TrafficCounter
     */
    void createGlobalTrafficCounter() {
        TrafficCounter tc;
        if (timer != null) {
            tc = new TrafficCounter(this, timer, "GlobalTC",
                    checkInterval);
            setTrafficCounter(tc);
            tc.start();
        }
    }

    public GlobalTrafficShapingHandler(Timer timer, long writeLimit,
            long readLimit, long checkInterval) {
        super(timer, writeLimit, readLimit, checkInterval);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(Timer timer, long writeLimit,
            long readLimit, long checkInterval, long maxTime) {
        super(timer, writeLimit, readLimit, checkInterval, maxTime);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(Timer timer, long writeLimit,
            long readLimit) {
        super(timer, writeLimit, readLimit);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(Timer timer, long checkInterval) {
        super(timer, checkInterval);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(Timer timer) {
        super(timer);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator,
            Timer timer, long writeLimit, long readLimit,
            long checkInterval) {
        super(objectSizeEstimator, timer, writeLimit, readLimit,
                checkInterval);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator,
            Timer timer, long writeLimit, long readLimit,
            long checkInterval, long maxTime) {
        super(objectSizeEstimator, timer, writeLimit, readLimit,
                checkInterval, maxTime);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator,
            Timer timer, long writeLimit, long readLimit) {
        super(objectSizeEstimator, timer, writeLimit, readLimit);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator,
            Timer timer, long checkInterval) {
        super(objectSizeEstimator, timer, checkInterval);
        createGlobalTrafficCounter();
    }

    public GlobalTrafficShapingHandler(ObjectSizeEstimator objectSizeEstimator,
            Timer timer) {
        super(objectSizeEstimator, timer);
        createGlobalTrafficCounter();
    }

    private static final class ToSend {
        final long date;
        final MessageEvent toSend;

        private ToSend(final long delay, final MessageEvent toSend) {
            this.date = System.currentTimeMillis() + delay;
            this.toSend = toSend;
        }
    }

    @Override
    protected synchronized void submitWrite(final ChannelHandlerContext ctx, final MessageEvent evt, final long delay)
            throws Exception {
        Integer key = ctx.getChannel().getId();
        List<ToSend> messagesQueue = messagesQueues.get(key);
        if (delay == 0 && (messagesQueue == null || messagesQueue.isEmpty())) {
            internalSubmitWrite(ctx, evt);
            return;
        }
        if (timer == null) {
            // Sleep since no executor
            Thread.sleep(delay);
            internalSubmitWrite(ctx, evt);
            return;
        }
        if (messagesQueue == null) {
            messagesQueue = new LinkedList<ToSend>();
            messagesQueues.put(key, messagesQueue);
        }
        final ToSend newToSend = new ToSend(delay, evt);
        messagesQueue.add(newToSend);
        final List<ToSend> mqfinal = messagesQueue;
        timer.newTimeout(new TimerTask() {
            public void run(Timeout timeout) throws Exception {
                sendAllValid(ctx, mqfinal);
            }
        }, delay + 1, TimeUnit.MILLISECONDS);
    }

    private synchronized void sendAllValid(ChannelHandlerContext ctx, final List<ToSend> messagesQueue)
            throws Exception {
        while (!messagesQueue.isEmpty()) {
            ToSend newToSend = messagesQueue.remove(0);
            if (newToSend.date <= System.currentTimeMillis()) {
                internalSubmitWrite(ctx, newToSend.toSend);
            } else {
                messagesQueue.add(0, newToSend);
                break;
            }
        }
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception {
        Integer key = ctx.getChannel().getId();
        List<ToSend> messagesQueue = new LinkedList<ToSend>();
        messagesQueues.put(key, messagesQueue);
        super.channelConnected(ctx, e);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception {
        Integer key = ctx.getChannel().hashCode();
        List<ToSend> mq = messagesQueues.remove(key);
        if (mq != null) {
            mq.clear();
        }
        super.channelClosed(ctx, e);
    }
}


text:
import ARSON from "arson";
import { memoize } from "lodash";

export default highlight;

const startWorker = memoize(url => {
  const { Worker } = global;
  return new Worker(url);
});

function highlight(options) {
  return new Promise((resolve, reject) => {
    const worker = startWorker(options.worker);

    const onWorkerMessage = e => {
      const data = ARSON.parse(e.data);

      if (data.id !== options.id) {
        return;
      }

      if (data.payload.type === "error") {
        return reject(data.payload.error);
      }

      resolve(data);
      worker.removeEventListener("message", onWorkerMessage);
    };

    worker.addEventListener("message", onWorkerMessage);
    worker.postMessage(ARSON.stringify(options));
  });
}