repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Gr33nOpo55um/EnOcean | src/ch/bfh/gr33nopo55um/enocean/helper/ReadConfig.java | 1385 | package ch.bfh.gr33nopo55um.enocean.helper;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.Properties;
/**
* @author silas
* @class Class for reading the config file
*/
public class ReadConfig {
private InputStream inputStream;
public String readPropertyValue(String value) throws IOException {
String result = null;
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
Date time = new Date(System.currentTimeMillis());
/**
* @brief get the property value and print it out
*/
result = prop.getProperty(value);
/**
* @brief throws error if no prop file is available
*/
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
assert inputStream != null;
inputStream.close();
}
return result;
}
}
| apache-2.0 |
basiljose1/byjcrm | test/templates_c/vlayout/b8db083918b3114ff17815f91bb3f975eaaa86fa.file.HistoryContents.tpl.php | 15806 | <?php /* Smarty version Smarty-3.1.7, created on 2016-09-06 12:49:40
compiled from "/home/bj/www/vtigercrma/includes/runtime/../../layouts/vlayout/modules/Vtiger/dashboards/HistoryContents.tpl" */ ?>
<?php /*%%SmartyHeaderCode:167699122357cebb64d5ad30-23480925%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'b8db083918b3114ff17815f91bb3f975eaaa86fa' =>
array (
0 => '/home/bj/www/vtigercrma/includes/runtime/../../layouts/vlayout/modules/Vtiger/dashboards/HistoryContents.tpl',
1 => 1468488064,
2 => 'file',
),
),
'nocache_hash' => '167699122357cebb64d5ad30-23480925',
'function' =>
array (
),
'variables' =>
array (
'HISTORIES' => 0,
'index' => 0,
'HISTORY' => 0,
'MODELNAME' => 0,
'MOD_NAME' => 0,
'SINGLE_MODULE_NAME' => 0,
'RELATION' => 0,
'PROCEED' => 0,
'TRANSLATED_MODULE_NAME' => 0,
'PARENT' => 0,
'USER' => 0,
'DETAILVIEW_URL' => 0,
'FIELDS' => 0,
'INDEX' => 0,
'FIELD' => 0,
'MODULE_NAME' => 0,
'LINKED_RECORD_DETAIL_URL' => 0,
'PARENT_DETAIL_URL' => 0,
'NEXTPAGE' => 0,
'PAGE' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.7',
'unifunc' => 'content_57cebb64ed5b8',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_57cebb64ed5b8')) {function content_57cebb64ed5b8($_smarty_tpl) {?>
<div style='padding:5px;'>
<?php if ($_smarty_tpl->tpl_vars['HISTORIES']->value!=false){?>
<?php $_smarty_tpl->tpl_vars['HISTORY'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['HISTORY']->_loop = false;
$_smarty_tpl->tpl_vars[$_smarty_tpl->tpl_vars['index']->value] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['HISTORIES']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['HISTORY']->key => $_smarty_tpl->tpl_vars['HISTORY']->value){
$_smarty_tpl->tpl_vars['HISTORY']->_loop = true;
$_smarty_tpl->tpl_vars[$_smarty_tpl->tpl_vars['index']->value]->value = $_smarty_tpl->tpl_vars['HISTORY']->key;
?>
<?php $_smarty_tpl->tpl_vars['MODELNAME'] = new Smarty_variable(get_class($_smarty_tpl->tpl_vars['HISTORY']->value), null, 0);?>
<?php if ($_smarty_tpl->tpl_vars['MODELNAME']->value=='ModTracker_Record_Model'){?>
<?php $_smarty_tpl->tpl_vars['USER'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getModifiedBy(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['TIME'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getActivityTime(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['PARENT'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getParent(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['MOD_NAME'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getParent()->getModule()->getName(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['SINGLE_MODULE_NAME'] = new Smarty_variable(('SINGLE_').($_smarty_tpl->tpl_vars['MOD_NAME']->value), null, 0);?>
<?php $_smarty_tpl->tpl_vars['TRANSLATED_MODULE_NAME'] = new Smarty_variable(vtranslate($_smarty_tpl->tpl_vars['SINGLE_MODULE_NAME']->value,$_smarty_tpl->tpl_vars['MOD_NAME']->value), null, 0);?>
<?php $_smarty_tpl->tpl_vars['PROCEED'] = new Smarty_variable(true, null, 0);?>
<?php if (($_smarty_tpl->tpl_vars['HISTORY']->value->isRelationLink())||($_smarty_tpl->tpl_vars['HISTORY']->value->isRelationUnLink())){?>
<?php $_smarty_tpl->tpl_vars['RELATION'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getRelationInstance(), null, 0);?>
<?php if (!($_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord())){?>
<?php $_smarty_tpl->tpl_vars['PROCEED'] = new Smarty_variable(false, null, 0);?>
<?php }?>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['PROCEED']->value){?>
<div class="row-fluid">
<div class='span1'>
<img width='24px' src="<?php echo vimage_path(($_smarty_tpl->tpl_vars['MOD_NAME']->value).('.png'));?>
" alt="<?php echo $_smarty_tpl->tpl_vars['TRANSLATED_MODULE_NAME']->value;?>
" title="<?php echo $_smarty_tpl->tpl_vars['TRANSLATED_MODULE_NAME']->value;?>
" />
</div>
<div class="span11">
<p class="pull-right muted" style="padding-right:5px;"><small title="<?php echo Vtiger_Util_Helper::formatDateTimeIntoDayString(($_smarty_tpl->tpl_vars['TIME']->value));?>
"><?php echo Vtiger_Util_Helper::formatDateDiffInStrings(($_smarty_tpl->tpl_vars['TIME']->value));?>
</small></p>
<?php $_smarty_tpl->tpl_vars['DETAILVIEW_URL'] = new Smarty_variable($_smarty_tpl->tpl_vars['PARENT']->value->getDetailViewUrl(), null, 0);?>
<?php if ($_smarty_tpl->tpl_vars['HISTORY']->value->isUpdate()){?>
<?php $_smarty_tpl->tpl_vars['FIELDS'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getFieldInstances(), null, 0);?>
<div class="">
<div><b><?php echo $_smarty_tpl->tpl_vars['USER']->value->getName();?>
</b> <?php echo vtranslate('LBL_UPDATED');?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,'javascript:')===0){?>
onclick='<?php echo substr($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,strlen("javascript:"));?>
' <?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value;?>
"' <?php }?>>
<?php echo $_smarty_tpl->tpl_vars['PARENT']->value->getName();?>
</a>
</div>
<?php $_smarty_tpl->tpl_vars['FIELD'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['FIELD']->_loop = false;
$_smarty_tpl->tpl_vars['INDEX'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['FIELDS']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['FIELD']->key => $_smarty_tpl->tpl_vars['FIELD']->value){
$_smarty_tpl->tpl_vars['FIELD']->_loop = true;
$_smarty_tpl->tpl_vars['INDEX']->value = $_smarty_tpl->tpl_vars['FIELD']->key;
?>
<?php if ($_smarty_tpl->tpl_vars['INDEX']->value<2){?>
<?php if ($_smarty_tpl->tpl_vars['FIELD']->value&&$_smarty_tpl->tpl_vars['FIELD']->value->getFieldInstance()&&$_smarty_tpl->tpl_vars['FIELD']->value->getFieldInstance()->isViewableInDetailView()){?>
<div class='font-x-small'>
<i><?php echo vtranslate($_smarty_tpl->tpl_vars['FIELD']->value->getName(),$_smarty_tpl->tpl_vars['FIELD']->value->getModuleName());?>
</i>
<?php if ($_smarty_tpl->tpl_vars['FIELD']->value->get('prevalue')!=''&&$_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')!=''&&!($_smarty_tpl->tpl_vars['FIELD']->value->getFieldInstance()->getFieldDataType()=='reference'&&($_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')=='0'||$_smarty_tpl->tpl_vars['FIELD']->value->get('prevalue')=='0'))){?>
<?php echo vtranslate('LBL_FROM');?>
<b><?php echo Vtiger_Util_Helper::toVtiger6SafeHTML($_smarty_tpl->tpl_vars['FIELD']->value->getDisplayValue(decode_html($_smarty_tpl->tpl_vars['FIELD']->value->get('prevalue'))));?>
</b>
<?php }elseif($_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')==''||($_smarty_tpl->tpl_vars['FIELD']->value->getFieldInstance()->getFieldDataType()=='reference'&&$_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')=='0')){?>
<b> <?php echo vtranslate('LBL_DELETED');?>
</b> ( <del><?php echo Vtiger_Util_Helper::toVtiger6SafeHTML($_smarty_tpl->tpl_vars['FIELD']->value->getDisplayValue(decode_html($_smarty_tpl->tpl_vars['FIELD']->value->get('prevalue'))));?>
</del> )
<?php }else{ ?>
<?php echo vtranslate('LBL_CHANGED');?>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')!=''&&!($_smarty_tpl->tpl_vars['FIELD']->value->getFieldInstance()->getFieldDataType()=='reference'&&$_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue')=='0')){?>
<?php echo vtranslate('LBL_TO');?>
<b><?php echo Vtiger_Util_Helper::toVtiger6SafeHTML($_smarty_tpl->tpl_vars['FIELD']->value->getDisplayValue(decode_html($_smarty_tpl->tpl_vars['FIELD']->value->get('postvalue'))));?>
</b>
<?php }?>
</div>
<?php }?>
<?php }else{ ?>
<a href="<?php echo $_smarty_tpl->tpl_vars['PARENT']->value->getUpdatesUrl();?>
"><?php echo vtranslate('LBL_MORE');?>
</a>
<?php break 1?>
<?php }?>
<?php } ?>
</div>
<?php }elseif($_smarty_tpl->tpl_vars['HISTORY']->value->isCreate()){?>
<div class='' style='margin-top:5px'>
<b><?php echo $_smarty_tpl->tpl_vars['USER']->value->getName();?>
</b> <?php echo vtranslate('LBL_ADDED');?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,'javascript:')===0){?>
onclick='<?php echo substr($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,strlen("javascript:"));?>
' <?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value;?>
"' <?php }?>>
<?php echo $_smarty_tpl->tpl_vars['PARENT']->value->getName();?>
</a>
</div>
<?php }elseif(($_smarty_tpl->tpl_vars['HISTORY']->value->isRelationLink()||$_smarty_tpl->tpl_vars['HISTORY']->value->isRelationUnLink())){?>
<?php $_smarty_tpl->tpl_vars['RELATION'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getRelationInstance(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL'] = new Smarty_variable($_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getDetailViewUrl(), null, 0);?>
<?php $_smarty_tpl->tpl_vars['PARENT_DETAIL_URL'] = new Smarty_variable($_smarty_tpl->tpl_vars['RELATION']->value->getParent()->getParent()->getDetailViewUrl(), null, 0);?>
<div class='' style='margin-top:5px'>
<b><?php echo $_smarty_tpl->tpl_vars['USER']->value->getName();?>
</b>
<?php if ($_smarty_tpl->tpl_vars['HISTORY']->value->isRelationLink()){?>
<?php echo vtranslate('LBL_ADDED',$_smarty_tpl->tpl_vars['MODULE_NAME']->value);?>
<?php }else{ ?>
<?php echo vtranslate('LBL_REMOVED',$_smarty_tpl->tpl_vars['MODULE_NAME']->value);?>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getModuleName()=='Calendar'){?>
<?php if (isPermitted('Calendar','DetailView',$_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getId())=='yes'){?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value,'javascript:')===0){?> onclick='<?php echo substr($_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value,strlen("javascript:"));?>
'
<?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value;?>
"' <?php }?>><?php echo $_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getName();?>
</a>
<?php }else{ ?>
<?php echo vtranslate($_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getModuleName(),$_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getModuleName());?>
<?php }?>
<?php }else{ ?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value,'javascript:')===0){?> onclick='<?php echo substr($_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value,strlen("javascript:"));?>
'
<?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['LINKED_RECORD_DETAIL_URL']->value;?>
"' <?php }?>><?php echo $_smarty_tpl->tpl_vars['RELATION']->value->getLinkedRecord()->getName();?>
</a>
<?php }?><?php echo vtranslate('LBL_FOR');?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['PARENT_DETAIL_URL']->value,'javascript:')===0){?>
onclick='<?php echo substr($_smarty_tpl->tpl_vars['PARENT_DETAIL_URL']->value,strlen("javascript:"));?>
' <?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['PARENT_DETAIL_URL']->value;?>
"' <?php }?>>
<?php echo $_smarty_tpl->tpl_vars['RELATION']->value->getParent()->getParent()->getName();?>
</a>
</div>
<?php }elseif($_smarty_tpl->tpl_vars['HISTORY']->value->isRestore()){?>
<div class='' style='margin-top:5px'>
<b><?php echo $_smarty_tpl->tpl_vars['USER']->value->getName();?>
</b> <?php echo vtranslate('LBL_RESTORED');?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,'javascript:')===0){?>
onclick='<?php echo substr($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,strlen("javascript:"));?>
' <?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value;?>
"' <?php }?>>
<?php echo $_smarty_tpl->tpl_vars['PARENT']->value->getName();?>
</a>
</div>
<?php }elseif($_smarty_tpl->tpl_vars['HISTORY']->value->isDelete()){?>
<div class='' style='margin-top:5px'>
<b><?php echo $_smarty_tpl->tpl_vars['USER']->value->getName();?>
</b> <?php echo vtranslate('LBL_DELETED');?>
<a class="cursorPointer" <?php if (stripos($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,'javascript:')===0){?>
onclick='<?php echo substr($_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value,strlen("javascript:"));?>
' <?php }else{ ?> onclick='window.location.href="<?php echo $_smarty_tpl->tpl_vars['DETAILVIEW_URL']->value;?>
"' <?php }?>>
<?php echo $_smarty_tpl->tpl_vars['PARENT']->value->getName();?>
</a>
</div>
<?php }?>
</div>
</div>
<?php }?>
<?php }elseif($_smarty_tpl->tpl_vars['MODELNAME']->value=='ModComments_Record_Model'){?>
<div class="row-fluid">
<div class="span1">
<image width='24px' src="<?php echo vimage_path('Comments.png');?>
"/>
</div>
<div class="span11">
<?php $_smarty_tpl->tpl_vars['COMMENT_TIME'] = new Smarty_variable($_smarty_tpl->tpl_vars['HISTORY']->value->getCommentedTime(), null, 0);?>
<p class="pull-right muted" style="padding-right:5px;"><small title="<?php echo Vtiger_Util_Helper::formatDateTimeIntoDayString(($_smarty_tpl->tpl_vars['COMMENT_TIME']->value));?>
"><?php echo Vtiger_Util_Helper::formatDateDiffInStrings(($_smarty_tpl->tpl_vars['COMMENT_TIME']->value));?>
</small></p>
<div>
<b><?php echo $_smarty_tpl->tpl_vars['HISTORY']->value->getCommentedByModel()->getName();?>
</b> <?php echo vtranslate('LBL_COMMENTED');?>
<?php echo vtranslate('LBL_ON');?>
<a class="textOverflowEllipsis" href="<?php echo $_smarty_tpl->tpl_vars['HISTORY']->value->getParentRecordModel()->getDetailViewUrl();?>
"><?php echo $_smarty_tpl->tpl_vars['HISTORY']->value->getParentRecordModel()->getName();?>
</a>
</div>
<div class='font-x-small'><i>"<?php echo nl2br($_smarty_tpl->tpl_vars['HISTORY']->value->get('commentcontent'));?>
"</i></div>
</div>
</div>
<?php }?>
<?php } ?>
<?php if ($_smarty_tpl->tpl_vars['NEXTPAGE']->value){?>
<div class="row-fluid">
<div class="span12">
<a href="javascript:;" class="load-more" data-page="<?php echo $_smarty_tpl->tpl_vars['PAGE']->value;?>
" data-nextpage="<?php echo $_smarty_tpl->tpl_vars['NEXTPAGE']->value;?>
"><?php echo vtranslate('LBL_MORE');?>
...</a>
</div>
</div>
<?php }?>
<?php }else{ ?>
<span class="noDataMsg">
<?php echo vtranslate('LBL_NO_UPDATES_OR_COMMENTS',$_smarty_tpl->tpl_vars['MODULE_NAME']->value);?>
</span>
<?php }?>
</div>
<?php }} ?> | apache-2.0 |
learning-layers/LTB-API | module/ltbapi/src/ltbapi/V2/Rpc/Auth/OIDC.php | 5464 | <?php
namespace ltbapi\V2\Rpc\Auth;
class OIDC {
private $message = '';
public function __construct($open_id_config){
/*
* The settings are copied from the local settings. The redirect uri
* will be accessed from the AuthController but should be here for completeness.
*/
$this->redirect_uri = $open_id_config['RedirectUri'];
$this->client_id = $open_id_config['ClientID'];
$this->client_secret = $open_id_config['ClientSecret'];
$this->provider = $open_id_config['Provider'];
$this->OidcEndpointToken = $open_id_config['OidcEndpointToken'];
$this->OidcEndpointUserinfo = $open_id_config['OidcEndpointUserinfo'];
$this->web_agent_uri = $open_id_config['WebAgent'];
$this->app_agent_uri = $open_id_config['AppAgent'];
}
public function getMessage(){
return $this->message;
}
private function addMessage($m){
$this->message .= $m;
}
public function connectOIDC($token_endpoint_key, $auth_mode, $data='', $token='', $verbose=false){
//$info_endpoint = $this->provider."/.well-known/openid-configuration";
$token_endpoint = $this->$token_endpoint_key;
if ($auth_mode == 'BASIC'){
$data['client_id'] = $this->client_id;
$data['client_secret'] = $this->client_secret;
}
$postdata = '';
if ($data){
foreach ($data as $k => $v){
$postdata .= $k."=".$v."&";
}
$postdata = rtrim($postdata, "&");
}
try {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $token_endpoint);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
if ($auth_mode == 'BASIC'){
curl_setopt($ch, CURLOPT_HEADER, FALSE);
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $token));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//For local installations the CA certificate cannot be verified, so we have to
//tell curl not to check
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, !_DEVELOP_ENV);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
if ($verbose){
curl_setopt($ch, CURLOPT_VERBOSE, $verbose);
$verbosebuffer = fopen('php://temp', 'rw+');
curl_setopt($ch, CURLOPT_STDERR, $verbosebuffer);
}
$response = curl_exec($ch);
$info = curl_getinfo($ch);
if ($response === FALSE) {
$this->addMessage(sprintf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch))));
$result = FALSE;
} else {
$response = $this->curl_exec_utf8($response, $ch);
$result = json_decode($response, true);
}
curl_close($ch);
} catch (\Exception $ex) {
$this->addMessage('Could not connect well to OpenID server or got invalid data back. '.
(_DEBUG ? $ex->getMessage() : ''));
$result = FALSE;
}
$debug_msg = ' In connectOIDC got back:['. print_r($result,1).
"\n\n Curl info ".print_r($info, 1).']';
if($verbose){
rewind($verbosebuffer);
$verboseLog = stream_get_contents($verbosebuffer);
$debug_msg .= ' Debug info '.print_r($verboseLog, 1);
}
if (_DEBUG){
$this->addMessage($debug_msg);
}
return $result;
}
private function curl_exec_utf8($data, $ch) {
unset($charset);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
/* 1: HTTP Content-Type: header */
preg_match( '@([\w/+]+)(;\s*charset=(\S+))?@i', $content_type, $matches );
if ( isset( $matches[3] ) )
$charset = $matches[3];
/* 2: <meta> element in the page */
if (!isset($charset)) {
preg_match( '@<meta\s+http-equiv="Content-Type"\s+content="([\w/]+)(;\s*charset=([^\s"]+))?@i', $data, $matches );
if ( isset( $matches[3] ) )
$charset = $matches[3];
}
/* 3: <xml> element in the page */
if (!isset($charset)) {
preg_match( '@<\?xml.+encoding="([^\s"]+)@si', $data, $matches );
if ( isset( $matches[1] ) )
$charset = $matches[1];
}
/* 4: PHP's heuristic detection */
if (!isset($charset)) {
$encoding = mb_detect_encoding($data);
if ($encoding)
$charset = $encoding;
}
/* 5: Default for HTML */
if (!isset($charset)) {
if (strstr($content_type, "text/html") === 0)
$charset = "ISO 8859-1";
}
/* Convert it if it is anything but UTF-8 */
/* You can change "UTF-8" to "UTF-8//IGNORE" to
ignore conversion errors and still output something reasonable */
if (isset($charset) && strtoupper($charset) != "UTF-8")
$data = iconv($charset, 'UTF-8', $data);
return $data;
}
}
| apache-2.0 |
Rmelev/rshmelev | chapter_007/src/main/java/ru/job4j/threads/MultiThreadProblems.java | 1375 | package ru.job4j.threads;
/**
* class to show problems with multi thread.
*/
public class MultiThreadProblems implements Runnable {
/**
* thread.
*/
private Thread thread;
/**
* counter in loop.
*/
private static int i = 0;
/**
* Constructor.
*/
MultiThreadProblems() {
thread = new Thread(this);
thread.start();
}
/**
* overrided run().
*/
@Override
public void run() {
while (i < 10) {
i++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Прохожу цикл в " + i + "раз");
}
}
/**
* main().
* @param args - args.
*/
public static void main(String[] args) {
new MultiThreadProblems();
new MultiThreadProblems() {
@Override
public void run() {
while (i < 10) {
i++;
try {
Thread.sleep(3743);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Прохожу цикл в " + i + "раз");
}
}
};
}
}
| apache-2.0 |
tbartolucci/hackerrank | src/com/hackerrank/introduction/Loops.java | 637 | package com.hackerrank.introduction;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Loops {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for ( int testcase = 0; testcase < t; testcase++ ) {
int a=sc.nextInt();
int b=sc.nextInt();
int n=sc.nextInt();
int answer = a;
for ( int counter = 0; counter < n; counter++ ) {
answer = answer + ((int) ( Math.pow(2, counter) * b));
System.out.printf("%d ", answer);
}
System.out.printf("%n");
}
}
}
| apache-2.0 |
levivic/origin | pkg/deploy/api/test/ok.go | 4731 | package test
import (
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/resource"
deployapi "github.com/openshift/origin/pkg/deploy/api"
imageapi "github.com/openshift/origin/pkg/image/api"
)
func OkDeploymentConfigSpec() deployapi.DeploymentConfigSpec {
return deployapi.DeploymentConfigSpec{
Replicas: 1,
Selector: OkSelector(),
Strategy: OkStrategy(),
Template: OkPodTemplate(),
Triggers: []deployapi.DeploymentTriggerPolicy{
OkImageChangeTrigger(),
},
}
}
func OkDeploymentConfigStatus(version int) deployapi.DeploymentConfigStatus {
return deployapi.DeploymentConfigStatus{
LatestVersion: version,
}
}
func OkImageChangeDetails() *deployapi.DeploymentDetails {
return &deployapi.DeploymentDetails{
Causes: []*deployapi.DeploymentCause{{
Type: deployapi.DeploymentTriggerOnImageChange,
ImageTrigger: &deployapi.DeploymentCauseImageTrigger{
From: kapi.ObjectReference{
Name: imageapi.JoinImageStreamTag("test", "tag"),
Kind: "ImageStreamTag",
}}}}}
}
func OkConfigChangeDetails() *deployapi.DeploymentDetails {
return &deployapi.DeploymentDetails{
Causes: []*deployapi.DeploymentCause{{
Type: deployapi.DeploymentTriggerOnConfigChange,
}}}
}
func OkStrategy() deployapi.DeploymentStrategy {
return deployapi.DeploymentStrategy{
Type: deployapi.DeploymentStrategyTypeRecreate,
Resources: kapi.ResourceRequirements{
Limits: kapi.ResourceList{
kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"),
kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"),
},
},
RecreateParams: &deployapi.RecreateDeploymentStrategyParams{
TimeoutSeconds: mkintp(20),
},
}
}
func OkCustomStrategy() deployapi.DeploymentStrategy {
return deployapi.DeploymentStrategy{
Type: deployapi.DeploymentStrategyTypeCustom,
CustomParams: OkCustomParams(),
Resources: kapi.ResourceRequirements{
Limits: kapi.ResourceList{
kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"),
kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"),
},
},
}
}
func OkCustomParams() *deployapi.CustomDeploymentStrategyParams {
return &deployapi.CustomDeploymentStrategyParams{
Image: "openshift/origin-deployer",
Environment: []kapi.EnvVar{
{
Name: "ENV1",
Value: "VAL1",
},
},
Command: []string{"/bin/echo", "hello", "world"},
}
}
func mkintp(i int) *int64 {
v := int64(i)
return &v
}
func OkRollingStrategy() deployapi.DeploymentStrategy {
return deployapi.DeploymentStrategy{
Type: deployapi.DeploymentStrategyTypeRolling,
RollingParams: &deployapi.RollingDeploymentStrategyParams{
UpdatePeriodSeconds: mkintp(1),
IntervalSeconds: mkintp(1),
TimeoutSeconds: mkintp(20),
},
Resources: kapi.ResourceRequirements{
Limits: kapi.ResourceList{
kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"),
kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"),
},
},
}
}
func OkSelector() map[string]string {
return map[string]string{"a": "b"}
}
func OkPodTemplate() *kapi.PodTemplateSpec {
return &kapi.PodTemplateSpec{
Spec: kapi.PodSpec{
Containers: []kapi.Container{
{
Name: "container1",
Image: "registry:8080/repo1:ref1",
Env: []kapi.EnvVar{
{
Name: "ENV1",
Value: "VAL1",
},
},
ImagePullPolicy: kapi.PullIfNotPresent,
},
{
Name: "container2",
Image: "registry:8080/repo1:ref2",
ImagePullPolicy: kapi.PullIfNotPresent,
},
},
RestartPolicy: kapi.RestartPolicyAlways,
DNSPolicy: kapi.DNSClusterFirst,
},
ObjectMeta: kapi.ObjectMeta{
Labels: OkSelector(),
},
}
}
func OkConfigChangeTrigger() deployapi.DeploymentTriggerPolicy {
return deployapi.DeploymentTriggerPolicy{
Type: deployapi.DeploymentTriggerOnConfigChange,
}
}
func OkImageChangeTrigger() deployapi.DeploymentTriggerPolicy {
return deployapi.DeploymentTriggerPolicy{
Type: deployapi.DeploymentTriggerOnImageChange,
ImageChangeParams: &deployapi.DeploymentTriggerImageChangeParams{
Automatic: true,
ContainerNames: []string{
"container1",
},
From: kapi.ObjectReference{
Kind: "ImageStreamTag",
Name: imageapi.JoinImageStreamTag("test-image-stream", imageapi.DefaultImageTag),
},
},
}
}
func OkDeploymentConfig(version int) *deployapi.DeploymentConfig {
return &deployapi.DeploymentConfig{
ObjectMeta: kapi.ObjectMeta{
Name: "config",
},
Spec: OkDeploymentConfigSpec(),
Status: OkDeploymentConfigStatus(version),
}
}
func TestDeploymentConfig(config *deployapi.DeploymentConfig) *deployapi.DeploymentConfig {
config.Spec.Test = true
return config
}
| apache-2.0 |
renatocastorela/myrepo | web/src/main/java/org/oiga/web/social/signin/SignInUtils.java | 416 | package org.oiga.web.social.signin;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
public class SignInUtils {
public static void signin(String userId) {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, null));
}
}
| apache-2.0 |
FangStarNet/symphonyx | src/main/java/org/b3log/symphony/repository/OptionRepository.java | 1150 | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.com & fangstar.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.repository;
import org.b3log.latke.repository.AbstractRepository;
import org.b3log.latke.repository.annotation.Repository;
import org.b3log.symphony.model.Option;
/**
* Option repository.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.0, Oct 16, 2012
* @since 0.2.0
*/
@Repository
public class OptionRepository extends AbstractRepository {
/**
* Public constructor.
*/
public OptionRepository() {
super(Option.OPTION);
}
}
| apache-2.0 |
tomwalder/php-appengine-pull-queue | src/AEQ/Pull/Queue.php | 9383 | <?php namespace AEQ\Pull;
/**
* Copyright 2016 Tom Walder
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use google\appengine\runtime\ApiProxy;
use google\appengine\runtime\ApplicationError;
use google\appengine\TaskQueueBulkAddRequest;
use google\appengine\TaskQueueBulkAddResponse;
use google\appengine\TaskQueueDeleteRequest;
use google\appengine\TaskQueueDeleteResponse;
use google\appengine\TaskQueueQueryAndOwnTasksRequest;
use google\appengine\TaskQueueQueryAndOwnTasksResponse;
use google\appengine\TaskQueueQueryTasksRequest;
use google\appengine\TaskQueueQueryTasksResponse;
use google\appengine\TaskQueueServiceError\ErrorCode;
use google\appengine\TaskQueueFetchQueueStatsRequest;
use google\appengine\TaskQueueFetchQueueStatsResponse;
use google\appengine\TaskQueueFetchQueueStatsResponse\QueueStats;
class Queue
{
const MAX_LIST_ROWS = 100;
/**
* Name of the queue
*
* @var string
*/
protected $str_name;
/**
* Set the queue name
*
* @param string $str_name
*/
public function __construct($str_name)
{
$this->str_name = $str_name;
}
/**
* Get the Queue name
*
* @return string
*/
public function getName()
{
return $this->str_name;
}
/**
* Add a single task
*
* @param Task $obj_task
*
* @return string[]|array
*/
public function addTask(Task $obj_task)
{
return $this->addTasks([$obj_task]);
}
/**
* Add many tasks
*
* @param Task[] $arr_tasks
*
* @return string[]|array Added task names
*/
public function addTasks(array $arr_tasks)
{
// Set up request and response objects
$obj_request = new TaskQueueBulkAddRequest();
$obj_response = new TaskQueueBulkAddResponse();
// Add the tasks
$int_now = time();
$int_now_usec = $int_now * 1e6;
foreach ($arr_tasks as $obj_task) {
$obj_add_request = $obj_request->addAddRequest();
$obj_add_request
->setQueueName($this->str_name)
->setMode(\google\appengine\TaskQueueMode\Mode::PULL)
->setEtaUsec(null === $obj_task->getEta() ? $int_now_usec : $obj_task->getEta() * 1e6)
->setTaskName($obj_task->getName())
->setBody($obj_task->getPayload());
}
// Make the request
$this->makeCall('BulkAdd', $obj_request, $obj_response);
// Extract task names
$arr_task_names = [];
$arr_results = $obj_response->getTaskResultList();
foreach ($arr_results as $index => $task_result) {
if ($task_result->hasChosenTaskName()) {
$arr_task_names[$index] = $task_result->getChosenTaskName();
}
if ($task_result->getResult() != ErrorCode::OK) {
throw new \RuntimeException($this->translateResultCode($task_result->getResult()));
}
}
return $arr_task_names;
}
/**
* Lease one or more tasks
*
* @param int $int_tasks
* @param int $int_lease_duration
*
* @return Task[]|array
*/
public function leaseTasks($int_tasks = 1, $int_lease_duration = 30)
{
// Set up the request, response pair
$obj_request = new TaskQueueQueryAndOwnTasksRequest();
$obj_response = new TaskQueueQueryAndOwnTasksResponse();
// Configure the request
$obj_request
->setQueueName($this->str_name)
->setMaxTasks($int_tasks)
->setLeaseSeconds($int_lease_duration);
// Make the call
$this->makeCall('QueryAndOwnTasks', $obj_request, $obj_response);
// Process the response into Tasks
$arr_tasks = [];
foreach ($obj_response->getTaskList() as $obj_source_task) {
/** @var \google\appengine\TaskQueueQueryTasksResponse\Task $obj_source_task */
$obj_task = new Task();
$obj_task->setName($obj_source_task->getTaskName());
$obj_task->setPayload($obj_source_task->getBody());
$obj_task->setTimesLeased($obj_source_task->getRetryCount());
$obj_task->setEta($obj_source_task->getEtaUsec() / 1e6);
$arr_tasks[] = $obj_task;
}
return $arr_tasks;
}
/**
* Delete a task
*
* @param Task $obj_task
*
* @return array
*/
public function deleteTask(Task $obj_task)
{
return $this->deleteTasks([$obj_task]);
}
/**
* Delete an array of one or more tasks
*
* @param array $arr_tasks
*
* @return array
*/
public function deleteTasks(array $arr_tasks)
{
$obj_request = new TaskQueueDeleteRequest();
$obj_response = new TaskQueueDeleteResponse();
$obj_request->setQueueName($this->str_name);
foreach ($arr_tasks as $obj_task) {
$obj_request->addTaskName($obj_task->getName());
}
$this->makeCall('Delete', $obj_request, $obj_response);
foreach ($obj_response->getResultList() as $int_idx => $int_code) {
if ($int_code != ErrorCode::OK) {
throw new \RuntimeException($this->translateResultCode($int_code));
}
}
return $obj_response->getResultSize();
}
/**
* List first 100 tasks from the queue
*
* @return array
*/
public function listTasks()
{
$arr_tasks = [];
$obj_request = new TaskQueueQueryTasksRequest();
$obj_response = new TaskQueueQueryTasksResponse();
$obj_request->setQueueName($this->str_name);
$obj_request->setMaxRows(self::MAX_LIST_ROWS);
$this->makeCall('QueryTasks', $obj_request, $obj_response);
if ($obj_response->getTaskSize() > 0) {
foreach ($obj_response->getTaskList() as $obj_source_task) {
/** @var \google\appengine\TaskQueueQueryTasksResponse\Task $obj_source_task */
$arr_tasks[] = (new Task())
->setName($obj_source_task->getTaskName())
->setPayload($obj_source_task->getBody())
->setEta($obj_source_task->getEtaUsec() / 1e6);
}
}
return $arr_tasks;
}
/**
* Get stats from the queue, like the approximate number of non-completed tasks or the number of tasks executed in the last minute.
*
* @return QueueStats
*/
public function getStats()
{
$request = new TaskQueueFetchQueueStatsRequest();
$response = new TaskQueueFetchQueueStatsResponse();
$request->addQueueName($this->str_name);
$this->makeCall('FetchQueueStats', $request, $response);
return $response->getQueueStats(0);
}
/**
* Make a service call
*
* @param $str_call
* @param $obj_request
* @param $obj_response
*/
private function makeCall($str_call, $obj_request, $obj_response)
{
try {
ApiProxy::makeSyncCall('taskqueue', $str_call, $obj_request, $obj_response);
} catch (ApplicationError $obj_ex) {
throw new \RuntimeException(
"Failed to execute call [{$str_call}] with: {$obj_ex->getApplicationError()} (" . $this->translateResultCode($obj_ex->getApplicationError()) . ")"
);
}
}
/**
* Translate a return code
*
* @param $int_code
*
* @return string
*/
protected function translateResultCode($int_code)
{
$arr_codes = [
0 => 'OK',
1 => 'UNKNOWN_QUEUE',
2 => 'TRANSIENT_ERROR',
3 => 'INTERNAL_ERROR',
4 => 'TASK_TOO_LARGE',
5 => 'INVALID_TASK_NAME',
6 => 'INVALID_QUEUE_NAME',
7 => 'INVALID_URL',
8 => 'INVALID_QUEUE_RATE',
9 => 'PERMISSION_DENIED',
10 => 'TASK_ALREADY_EXISTS',
11 => 'TOMBSTONED_TASK',
12 => 'INVALID_ETA',
13 => 'INVALID_REQUEST',
14 => 'UNKNOWN_TASK',
15 => 'TOMBSTONED_QUEUE',
16 => 'DUPLICATE_TASK_NAME',
17 => 'SKIPPED',
18 => 'TOO_MANY_TASKS',
19 => 'INVALID_PAYLOAD',
20 => 'INVALID_RETRY_PARAMETERS',
21 => 'INVALID_QUEUE_MODE',
22 => 'ACL_LOOKUP_ERROR',
23 => 'TRANSACTIONAL_REQUEST_TOO_LARGE',
24 => 'INCORRECT_CREATOR_NAME',
25 => 'TASK_LEASE_EXPIRED',
26 => 'QUEUE_PAUSED',
27 => 'INVALID_TAG',
1000 => 'DATASTORE_ERROR'
];
return (isset($arr_codes[$int_code]) ? $arr_codes[$int_code] : 'UNKNOWN');
}
} | apache-2.0 |
desruisseaux/sis | core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/DefaultRelativeInternalPositionalAccuracy.java | 4482 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.metadata.iso.quality;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlRootElement;
import org.opengis.metadata.quality.RelativeInternalPositionalAccuracy;
/**
* Closeness of the relative positions of features in the scope to their respective
* relative positions accepted as or being true.
*
* <p><b>Limitations:</b></p>
* <ul>
* <li>Instances of this class are not synchronized for multi-threading.
* Synchronization, if needed, is caller's responsibility.</li>
* <li>Serialized objects of this class are not guaranteed to be compatible with future Apache SIS releases.
* Serialization support is appropriate for short term storage or RMI between applications running the
* same version of Apache SIS. For long term storage, use {@link org.apache.sis.xml.XML} instead.</li>
* </ul>
*
* @author Martin Desruisseaux (IRD, Geomatys)
* @author Touraïvane (IRD)
* @since 0.3
* @version 0.3
* @module
*/
@XmlType(name = "DQ_RelativeInternalPositionalAccuracy_Type")
@XmlRootElement(name = "DQ_RelativeInternalPositionalAccuracy")
public class DefaultRelativeInternalPositionalAccuracy extends AbstractPositionalAccuracy
implements RelativeInternalPositionalAccuracy
{
/**
* Serial number for inter-operability with different versions.
*/
private static final long serialVersionUID = 8385667875833802576L;
/**
* Constructs an initially empty relative internal positional accuracy.
*/
public DefaultRelativeInternalPositionalAccuracy() {
}
/**
* Constructs a new instance initialized with the values from the specified metadata object.
* This is a <cite>shallow</cite> copy constructor, since the other metadata contained in the
* given object are not recursively copied.
*
* @param object The metadata to copy values from, or {@code null} if none.
*
* @see #castOrCopy(RelativeInternalPositionalAccuracy)
*/
public DefaultRelativeInternalPositionalAccuracy(final RelativeInternalPositionalAccuracy object) {
super(object);
}
/**
* Returns a SIS metadata implementation with the values of the given arbitrary implementation.
* This method performs the first applicable action in the following choices:
*
* <ul>
* <li>If the given object is {@code null}, then this method returns {@code null}.</li>
* <li>Otherwise if the given object is already an instance of
* {@code DefaultRelativeInternalPositionalAccuracy}, then it is returned unchanged.</li>
* <li>Otherwise a new {@code DefaultRelativeInternalPositionalAccuracy} instance is created using the
* {@linkplain #DefaultRelativeInternalPositionalAccuracy(RelativeInternalPositionalAccuracy) copy constructor}
* and returned. Note that this is a <cite>shallow</cite> copy operation, since the other
* metadata contained in the given object are not recursively copied.</li>
* </ul>
*
* @param object The object to get as a SIS implementation, or {@code null} if none.
* @return A SIS implementation containing the values of the given object (may be the
* given object itself), or {@code null} if the argument was null.
*/
public static DefaultRelativeInternalPositionalAccuracy castOrCopy(final RelativeInternalPositionalAccuracy object) {
if (object == null || object instanceof DefaultRelativeInternalPositionalAccuracy) {
return (DefaultRelativeInternalPositionalAccuracy) object;
}
return new DefaultRelativeInternalPositionalAccuracy(object);
}
}
| apache-2.0 |
findmypast-oss/jackal | client/run.js | 392 | 'use strict'
const request = require('request')
const handleResponse = require('./handle-response')
const url = require('./jackal-url')
module.exports = (jackalUrl, providerName, options, done) => {
const query = options.providerUrl ? `?testUrl=${options.providerUrl}` : ''
const jacky = url(jackalUrl, `/api/contracts/${providerName}${query}`)
request(jacky, handleResponse(done))
}
| apache-2.0 |
ysc/rank | src/main/java/org/seo/rank/list/impl/DefaultParser.java | 11512 | /**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.seo.rank.list.impl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.seo.rank.list.Parser;
import org.seo.rank.list.UrlTools;
import org.seo.rank.model.Article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author 杨尚川
*/
public class DefaultParser implements Parser{
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultParser.class);
private static final String ACCEPT = "text/html, */*; q=0.01";
private static final String ENCODING = "gzip, deflate";
private static final String LANGUAGE = "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3";
private static final String CONNECTION = "keep-alive";
private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Firefox/31.0";
@Override
public List<Article> parse(String url, String nextPageCssQuery, String nextPageText, String titleCssQuery) {
List<Article> articles = new ArrayList<>();
try{
Document document = Jsoup.connect(url)
.header("Accept", ACCEPT)
.header("Accept-Encoding", ENCODING)
.header("Accept-Language", LANGUAGE)
.header("Connection", CONNECTION)
.header("User-Agent", USER_AGENT)
.get();
Elements elements = document.select(titleCssQuery);
for(Element element : elements){
String title = element.text();
String href = element.attr("href");
if(!StringUtils.isBlank(title) && !StringUtils.isBlank(href)){
href = UrlTools.normalizeUrl(url, href);
Article article = new Article();
article.setTitle(title);
article.setUrl(href);
articles.add(article);
}else{
LOGGER.info("解析列表页出错:"+url+" title:"+title+", href:"+href);
}
}
//获取下一页链接地址
String nextPageUrl = getNextPageUrl(document, nextPageCssQuery, nextPageText);
LOGGER.debug("下一页链接:"+nextPageUrl);
if(nextPageUrl != null){
nextPageUrl = UrlTools.normalizeUrl(url, nextPageUrl);
LOGGER.debug("规范化后的下一页链接:"+nextPageUrl);
//解析下一页
List<Article> result = parse(nextPageUrl, nextPageCssQuery, nextPageText, titleCssQuery);
articles.addAll(result);
}else{
LOGGER.info("列表页解析完毕,最后一页:"+url);
}
}catch(Exception e){
LOGGER.error("解析列表页出错:"+url, e);
}
return articles;
}
/**
* 获取下一页链接地址
* @param document 本页文档对象
* @param nextPageCssQuery 获取下一页的CSS路径
* @param nextPageText 下一页CSS路径对应的元素的文本值
* @return 下一页链接地址
*/
private String getNextPageUrl(Document document, String nextPageCssQuery, String nextPageText){
Elements elements = document.select(nextPageCssQuery);
for(Element element : elements){
String text = element.text();
LOGGER.debug(text);
if(text != null && nextPageText.trim().equals(text.trim())){
String href = element.attr("href");
return href;
}
}
return null;
}
public static List<Article> run(String url, String nextPageCssQuery, String nextPageText, String titleCssQuery){
Parser parser = new DefaultParser();
long start = System.currentTimeMillis();
List<Article> articles = parser.parse(url, nextPageCssQuery, nextPageText, titleCssQuery);
long cost = System.currentTimeMillis() - start;
int i=1;
for(Article article : articles){
LOGGER.info((i++) + "、" + article.getTitle() + " : " + article.getUrl());
}
LOGGER.info("采集文章 " + articles.size() + " 篇耗时:" + cost / 1000.0 + " 秒");
return articles;
}
public static List<Article> iteyeBlog(){
String url = "http://yangshangchuan.iteye.com/";
String nextPageCssQuery = "html body div#page div#content.clearfix div#main div.pagination a.next_page";
String nextPageText = "下一页 »";
String titleCssQuery = "html body div#page div#content.clearfix div#main div.blog_main div.blog_title h3 a";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> iteyeNews(){
String url = "http://www.iteye.com/news";
String nextPageCssQuery = "html body div#page div#content.clearfix div#main div#index_main div.pagination a.next_page";
String nextPageText = "下一页 »";
//h3 > a表示h3后直接跟着a,这样 h3 span.category a 就不会被选择
String titleCssQuery = "html body div#page div#content.clearfix div#main div#index_main div.news.clearfix div.content h3 > a";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> iteyeMagazines(){
String url = "http://www.iteye.com/magazines";
String nextPageCssQuery = "html body div#page div#content.clearfix div#main div#index_main div.pagination a.next_page";
String nextPageText = "下一页 »";
String titleCssQuery = "html body div#page div#content.clearfix div#main div#index_main div.news.clearfix div.content h3 a";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> csdnBlog(){
String url = "http://blog.csdn.net/iispring";
String nextPageCssQuery = "html body div#container div#body div#main div.main div#papelist.pagelist a";
String titleCssQuery = "html body div#container div#body div#main div.main div#article_list.list div.list_item.article_item div.article_title h1 span.link_title a";
String nextPageText = "下一页";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> oschinaNews(){
String url = "http://www.oschina.net/news";
String nextPageCssQuery = "html body div#OSC_Screen div#OSC_Content.CenterDiv div#NewsChannel.Channel div#NewsList.ListPanel div#RecentNewsList.panel ul.pager li.page.next a";
String titleCssQuery = "html body div#OSC_Screen div#OSC_Content.CenterDiv div#NewsChannel.Channel div#NewsList.ListPanel div#RecentNewsList.panel ul.List li h2 a";
String nextPageText = ">";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> oschinaBlog(){
String url = "http://my.oschina.net/apdplat/blog";
String nextPageCssQuery = "html body div#OSC_Screen div#OSC_Content div.blog-user div.container div.flex-item div#search_list.flex-item-9.flex-item-md-9.content div#list.list.blog-list div.pages.sm-hide ul li a";
String titleCssQuery = "html body div#OSC_Screen div#OSC_Content div.blog-user div.container div.flex-item div#search_list.flex-item-9.flex-item-md-9.content div#list.list.blog-list div.list-item div.layout div.layout-column div.title a";
String nextPageText = "下一页";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
public static List<Article> baidu(String query){
//对查询词进行编码
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("url构造失败", e);
return Collections.emptyList();
}
if(StringUtils.isBlank(query)){
return Collections.emptyList();
}
String url = "http://www.baidu.com/s?wd=" + query;
String nextPageCssQuery = "html body div div div p#page a.n";
String titleCssQuery = "html body div div div div div h3.t a";
String nextPageText = "下一页>";
return run(url, nextPageCssQuery, nextPageText, titleCssQuery);
}
/**
* 比较我的OSCHINA博客和ITEYE博客的异同
*/
public static void blogCompare(){
List<Article> ob = oschinaBlog();
List<Article> ib = iteyeBlog();
Map<String, String> om = new HashMap<>();
Map<String, String> im = new HashMap<>();
ob.stream().forEach(b->om.put(b.getTitle(), b.getUrl()));
ib.stream().forEach(b->im.put(b.getTitle(), b.getUrl()));
List<String> iteyeBlog = ib.stream().map(b -> b.getTitle().replace("[置顶]", "").trim()).sorted().collect(Collectors.toList());
List<String> oschinaBlog = ob.stream().map(b -> b.getTitle()).sorted().collect(Collectors.toList());
List<String> commons = oschinaBlog.stream().filter(b -> iteyeBlog.contains(b)).collect(Collectors.toList());
LOGGER.info("<h4>oschina和iteye都有("+commons.size()+"):</h4>");
AtomicInteger j = new AtomicInteger();
commons.forEach(item -> LOGGER.info(j.incrementAndGet()+"、"+item+" <a target=\"_blank\" href=\""+om.get(item)+"\">oschina</a> <a target=\"_blank\" href=\""+im.get(item)+"\">iteye</a><br/>"));
List<String> oschina = oschinaBlog.stream().filter(i -> !iteyeBlog.contains(i)).collect(Collectors.toList());
LOGGER.info("<h4>oschina独有("+oschina.size()+"):</h4>");
AtomicInteger l = new AtomicInteger();
oschina.forEach(item -> LOGGER.info(l.incrementAndGet()+"、<a target=\"_blank\" href=\""+om.get(item)+"\">"+item+"</a><br/>"));
List<String> iteye = iteyeBlog.stream().filter(i -> !oschinaBlog.contains(i)).collect(Collectors.toList());
LOGGER.info("<h4>iteye独有("+iteye.size()+"):</h4>");
AtomicInteger k = new AtomicInteger();
iteye.forEach(item -> LOGGER.info(k.incrementAndGet()+"、<a target=\"_blank\" href=\""+im.get(item)+"\">"+item+"</a><br/>"));
}
public static void main(String[] args){
//iteyeBlog();
//iteyeNews();
//iteyeMagazines();
//csdnBlog();
//oschinaNews();
//oschinaBlog();
//baidu("Java应用级产品开发平台APDPlat作者杨尚川专访");
blogCompare();
}
}
| apache-2.0 |
guoxiaoxing/material-design-music-player | cloud/src/main/java/com/guoxiaoxing/cloud/music/receiver/LaunchNowPlayingReceiver.java | 920 | package com.guoxiaoxing.cloud.music.receiver;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import com.guoxiaoxing.cloud.music.ui.activity.PlayingActivity;
public class LaunchNowPlayingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// if (MusicPlayer.isPlaying()) {
Intent activityIntent = new Intent(context.getApplicationContext(), PlayingActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(activityIntent);
Intent intent1 = new Intent();
intent1.setComponent(new ComponentName("com.guoxiaoxing.cloud.music", "PlayingActivity.class"));
context.sendBroadcast(intent1);
// }
}
}
| apache-2.0 |
rickerc/neutron_audit | neutron/extensions/securitygroup.py | 12372 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from abc import ABCMeta
from abc import abstractmethod
import netaddr
from oslo.config import cfg
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import base
from neutron.common import constants as const
from neutron.common import exceptions as qexception
from neutron import manager
from neutron.openstack.common import uuidutils
from neutron import quota
# Security group Exceptions
class SecurityGroupInvalidPortRange(qexception.InvalidInput):
message = _("For TCP/UDP protocols, port_range_min must be "
"<= port_range_max")
class SecurityGroupInvalidPortValue(qexception.InvalidInput):
message = _("Invalid value for port %(port)s")
class SecurityGroupInvalidIcmpValue(qexception.InvalidInput):
message = _("Invalid value for ICMP %(field)s (%(attr)s) "
"%(value)s. It must be 0 to 255.")
class SecurityGroupInUse(qexception.InUse):
message = _("Security Group %(id)s in use.")
class SecurityGroupCannotRemoveDefault(qexception.InUse):
message = _("Removing default security group not allowed.")
class SecurityGroupCannotUpdateDefault(qexception.InUse):
message = _("Updating default security group not allowed.")
class SecurityGroupDefaultAlreadyExists(qexception.InUse):
message = _("Default security group already exists.")
class SecurityGroupRuleInvalidProtocol(qexception.InvalidInput):
message = _("Security group rule protocol %(protocol)s not supported. "
"Only protocol values %(values)s and their integer "
"representation (0 to 255) are supported.")
class SecurityGroupRulesNotSingleTenant(qexception.InvalidInput):
message = _("Multiple tenant_ids in bulk security group rule create"
" not allowed")
class SecurityGroupRemoteGroupAndRemoteIpPrefix(qexception.InvalidInput):
message = _("Only remote_ip_prefix or remote_group_id may "
"be provided.")
class SecurityGroupProtocolRequiredWithPorts(qexception.InvalidInput):
message = _("Must also specifiy protocol if port range is given.")
class SecurityGroupNotSingleGroupRules(qexception.InvalidInput):
message = _("Only allowed to update rules for "
"one security profile at a time")
class SecurityGroupNotFound(qexception.NotFound):
message = _("Security group %(id)s does not exist")
class SecurityGroupRuleNotFound(qexception.NotFound):
message = _("Security group rule %(id)s does not exist")
class DuplicateSecurityGroupRuleInPost(qexception.InUse):
message = _("Duplicate Security Group Rule in POST.")
class SecurityGroupRuleExists(qexception.InUse):
message = _("Security group rule already exists. Group id is %(id)s.")
class SecurityGroupRuleParameterConflict(qexception.InvalidInput):
message = _("Conflicting value ethertype %(ethertype)s for CIDR %(cidr)s")
def convert_protocol(value):
if value is None:
return
try:
val = int(value)
if val >= 0 and val <= 255:
return val
raise SecurityGroupRuleInvalidProtocol(
protocol=value, values=sg_supported_protocols)
except (ValueError, TypeError):
if value.lower() in sg_supported_protocols:
return value.lower()
raise SecurityGroupRuleInvalidProtocol(
protocol=value, values=sg_supported_protocols)
except AttributeError:
raise SecurityGroupRuleInvalidProtocol(
protocol=value, values=sg_supported_protocols)
def convert_ethertype_to_case_insensitive(value):
if isinstance(value, basestring):
for ethertype in sg_supported_ethertypes:
if ethertype.lower() == value.lower():
return ethertype
def convert_validate_port_value(port):
if port is None:
return port
try:
val = int(port)
except (ValueError, TypeError):
raise SecurityGroupInvalidPortValue(port=port)
if val >= 0 and val <= 65535:
return val
else:
raise SecurityGroupInvalidPortValue(port=port)
def convert_to_uuid_list_or_none(value_list):
if value_list is None:
return
for sg_id in value_list:
if not uuidutils.is_uuid_like(sg_id):
msg = _("'%s' is not an integer or uuid") % sg_id
raise qexception.InvalidInput(error_message=msg)
return value_list
def convert_ip_prefix_to_cidr(ip_prefix):
if not ip_prefix:
return
try:
cidr = netaddr.IPNetwork(ip_prefix)
return str(cidr)
except (ValueError, TypeError, netaddr.AddrFormatError):
raise qexception.InvalidCIDR(input=ip_prefix)
def _validate_name_not_default(data, valid_values=None):
if data == "default":
raise SecurityGroupDefaultAlreadyExists()
attr.validators['type:name_not_default'] = _validate_name_not_default
sg_supported_protocols = [None, const.PROTO_NAME_TCP,
const.PROTO_NAME_UDP, const.PROTO_NAME_ICMP]
sg_supported_ethertypes = ['IPv4', 'IPv6']
# Attribute Map
RESOURCE_ATTRIBUTE_MAP = {
'security_groups': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True,
'primary_key': True},
'name': {'allow_post': True, 'allow_put': True,
'is_visible': True, 'default': '',
'validate': {'type:name_not_default': None}},
'description': {'allow_post': True, 'allow_put': True,
'is_visible': True, 'default': ''},
'tenant_id': {'allow_post': True, 'allow_put': False,
'required_by_policy': True,
'is_visible': True},
'security_group_rules': {'allow_post': False, 'allow_put': False,
'is_visible': True},
},
'security_group_rules': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True,
'primary_key': True},
'security_group_id': {'allow_post': True, 'allow_put': False,
'is_visible': True, 'required_by_policy': True},
'remote_group_id': {'allow_post': True, 'allow_put': False,
'default': None, 'is_visible': True},
'direction': {'allow_post': True, 'allow_put': True,
'is_visible': True,
'validate': {'type:values': ['ingress', 'egress']}},
'protocol': {'allow_post': True, 'allow_put': False,
'is_visible': True, 'default': None,
'convert_to': convert_protocol},
'port_range_min': {'allow_post': True, 'allow_put': False,
'convert_to': convert_validate_port_value,
'default': None, 'is_visible': True},
'port_range_max': {'allow_post': True, 'allow_put': False,
'convert_to': convert_validate_port_value,
'default': None, 'is_visible': True},
'ethertype': {'allow_post': True, 'allow_put': False,
'is_visible': True, 'default': 'IPv4',
'convert_to': convert_ethertype_to_case_insensitive,
'validate': {'type:values': sg_supported_ethertypes}},
'remote_ip_prefix': {'allow_post': True, 'allow_put': False,
'default': None, 'is_visible': True,
'convert_to': convert_ip_prefix_to_cidr},
'tenant_id': {'allow_post': True, 'allow_put': False,
'required_by_policy': True,
'is_visible': True},
}
}
SECURITYGROUPS = 'security_groups'
EXTENDED_ATTRIBUTES_2_0 = {
'ports': {SECURITYGROUPS: {'allow_post': True,
'allow_put': True,
'is_visible': True,
'convert_to': convert_to_uuid_list_or_none,
'default': attr.ATTR_NOT_SPECIFIED}}}
security_group_quota_opts = [
cfg.IntOpt('quota_security_group',
default=10,
help=_('Number of security groups allowed per tenant,'
'-1 for unlimited')),
cfg.IntOpt('quota_security_group_rule',
default=100,
help=_('Number of security rules allowed per tenant, '
'-1 for unlimited')),
]
cfg.CONF.register_opts(security_group_quota_opts, 'QUOTAS')
class Securitygroup(extensions.ExtensionDescriptor):
"""Security group extension."""
@classmethod
def get_name(cls):
return "security-group"
@classmethod
def get_alias(cls):
return "security-group"
@classmethod
def get_description(cls):
return "The security groups extension."
@classmethod
def get_namespace(cls):
# todo
return "http://docs.openstack.org/ext/securitygroups/api/v2.0"
@classmethod
def get_updated(cls):
return "2012-10-05T10:00:00-00:00"
@classmethod
def get_resources(cls):
"""Returns Ext Resources."""
my_plurals = [(key, key[:-1]) for key in RESOURCE_ATTRIBUTE_MAP.keys()]
attr.PLURALS.update(dict(my_plurals))
exts = []
plugin = manager.NeutronManager.get_plugin()
for resource_name in ['security_group', 'security_group_rule']:
collection_name = resource_name.replace('_', '-') + "s"
params = RESOURCE_ATTRIBUTE_MAP.get(resource_name + "s", dict())
quota.QUOTAS.register_resource_by_name(resource_name)
controller = base.create_resource(collection_name,
resource_name,
plugin, params, allow_bulk=True,
allow_pagination=True,
allow_sorting=True)
ex = extensions.ResourceExtension(collection_name,
controller,
attr_map=params)
exts.append(ex)
return exts
def get_extended_resources(self, version):
if version == "2.0":
return dict(EXTENDED_ATTRIBUTES_2_0.items() +
RESOURCE_ATTRIBUTE_MAP.items())
else:
return {}
class SecurityGroupPluginBase(object):
__metaclass__ = ABCMeta
@abstractmethod
def create_security_group(self, context, security_group):
pass
@abstractmethod
def update_security_group(self, context, id, security_group):
pass
@abstractmethod
def delete_security_group(self, context, id):
pass
@abstractmethod
def get_security_groups(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
pass
@abstractmethod
def get_security_group(self, context, id, fields=None):
pass
@abstractmethod
def create_security_group_rule(self, context, security_group_rule):
pass
@abstractmethod
def delete_security_group_rule(self, context, id):
pass
@abstractmethod
def get_security_group_rules(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
pass
@abstractmethod
def get_security_group_rule(self, context, id, fields=None):
pass
| apache-2.0 |
agileowl/tapestry-5 | tapestry-func/src/main/java/org/apache/tapestry5/func/LazyZipValue.java | 1004 | // Copyright 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.func;
public class LazyZipValue<A, B> implements LazyValue<Tuple<A, B>>
{
private final Flow<A> aFlow;
private final Flow<B> bFlow;
public LazyZipValue(Flow<A> aFlow, Flow<B> bFlow)
{
this.aFlow = aFlow;
this.bFlow = bFlow;
}
public Tuple<A, B> get()
{
return new Tuple<A, B>(aFlow.first(), bFlow.first());
}
}
| apache-2.0 |
wealthfront/kawala | kawala-testing/src/test/java/com/kaching/platform/testing/CyclicDependencyTestRunnerTest.java | 3542 | /**
* Copyright 2015 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import com.kaching.platform.testing.CyclicDependencyTestRunner.Packages;
import com.kaching.platform.testing.CyclicDependencyTestRunner.PackagesBuilder.Result;
public class CyclicDependencyTestRunnerTest {
@Packages(
binDirectories = "target/test-classes",
forPackages = "com.kaching.platform.testing.testexamples.a")
private static class SinglePackage {}
@Test
public void testSinglePackage_NoCycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(SinglePackage.class);
Result result = runner.getTestResults(SinglePackage.class.getAnnotation(Packages.class));
assertTrue(result.numClasses > 0);
assertTrue(result.getUniqueCycles().isEmpty());
}
@Packages(
binDirectories = "target/test-classes",
forPackages = {"com.kaching.platform.testing.testexamples.a",
"com.kaching.platform.testing.testexamples.b"})
private static class TwoPackages {}
@Test
public void testTwoPackages_NoCycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(TwoPackages.class);
Result result = runner.getTestResults(TwoPackages.class.getAnnotation(Packages.class));
assertTrue(result.numClasses > 0);
assertTrue(result.getUniqueCycles().isEmpty());
}
@Packages(
binDirectories = "target/test-classes",
forPackages = {"com.kaching.platform.testing.testexamples.a",
"com.kaching.platform.testing.testexamples.b",
"com.kaching.platform.testing.testexamples.c"})
private static class ThreePackages {}
@Test
public void testThreePackages_Cycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(ThreePackages.class);
Result result = runner.getTestResults(ThreePackages.class.getAnnotation(Packages.class));
assertTrue(result.numClasses > 0);
assertEquals(1, result.getUniqueCycles().size());
}
@Packages(
binDirectories = "target/test-classes",
minClasses = 1,
forPackages = "com.kaching.platform.testing.testexamples")
private static class BasePackage {}
@Test
public void testBasePackage_Cycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(BasePackage.class);
Result result = runner.getTestResults(BasePackage.class.getAnnotation(Packages.class));
assertTrue(result.numClasses > 0);
assertEquals(1, result.getUniqueCycles().size());
assertEquals("Strongly connected components: {\n" +
"[com.kaching.platform.testing.testexamples.a,\n"
+ " com.kaching.platform.testing.testexamples.b,\n"
+ " com.kaching.platform.testing.testexamples.c]\n"
+ "}", result.toString());
}
}
| apache-2.0 |
First-Peoples-Cultural-Council/fv-web-ui | modules/common/firstvoices-publisher/src/main/java/ca/firstvoices/publisher/operations/CheckUnpublishedChanges.java | 1939 | /*
*
* *
* * Copyright 2020 First People's Cultural Council
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* * /
*
*/
package ca.firstvoices.publisher.operations;
import ca.firstvoices.publisher.services.UnpublishedChangesService;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.runtime.api.Framework;
/**
*
*/
@Operation(id = CheckUnpublishedChanges.ID, category = Constants.CAT_DOCUMENT, label =
"FVCheckUnpublishedChanges", description =
"This operation is used to check if a document has unpublished changes. "
+ "It returns true if unpublished changes exist and false otherwise.")
public class CheckUnpublishedChanges {
public static final String ID = "Document.CheckUnpublishedChanges";
protected UnpublishedChangesService service = Framework
.getService(UnpublishedChangesService.class);
CoreSession session;
@OperationMethod
public boolean run(DocumentModel input) {
session = input.getCoreSession();
// Call the checkUnpublishedChanges service which
// returns true if a document has unpublished changes and false otherwise.
return service.checkUnpublishedChanges(session, input);
}
}
| apache-2.0 |
mattnworb/helios | helios-services/src/main/java/com/spotify/helios/master/MasterService.java | 19145 | /*-
* -\-\-
* Helios Services
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.helios.master;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.spotify.helios.servicescommon.ServiceRegistrars.createServiceRegistrar;
import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.digest;
import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.heliosAclProvider;
import ch.qos.logback.access.jetty.RequestLogImpl;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.AbstractIdleService;
import com.spotify.helios.common.HeliosRuntimeException;
import com.spotify.helios.common.descriptors.TaskStatusEvent;
import com.spotify.helios.master.http.VersionResponseFilter;
import com.spotify.helios.master.metrics.HealthCheckGauge;
import com.spotify.helios.master.metrics.ReportingResourceMethodDispatchAdapter;
import com.spotify.helios.master.reaper.DeadAgentReaper;
import com.spotify.helios.master.reaper.ExpiredJobReaper;
import com.spotify.helios.master.reaper.JobHistoryReaper;
import com.spotify.helios.master.reaper.OldJobReaper;
import com.spotify.helios.master.resources.DeploymentGroupResource;
import com.spotify.helios.master.resources.HistoryResource;
import com.spotify.helios.master.resources.HostsResource;
import com.spotify.helios.master.resources.JobsResource;
import com.spotify.helios.master.resources.MastersResource;
import com.spotify.helios.master.resources.VersionResource;
import com.spotify.helios.rollingupdate.RollingUpdateService;
import com.spotify.helios.serviceregistration.ServiceRegistrar;
import com.spotify.helios.serviceregistration.ServiceRegistration;
import com.spotify.helios.servicescommon.EventSender;
import com.spotify.helios.servicescommon.EventSenderFactory;
import com.spotify.helios.servicescommon.FastForwardConfig;
import com.spotify.helios.servicescommon.ManagedStatsdReporter;
import com.spotify.helios.servicescommon.ReactorFactory;
import com.spotify.helios.servicescommon.ServiceUtil;
import com.spotify.helios.servicescommon.ZooKeeperRegistrarService;
import com.spotify.helios.servicescommon.coordination.CuratorClientFactory;
import com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClientProvider;
import com.spotify.helios.servicescommon.coordination.ZooKeeperHealthChecker;
import com.spotify.helios.servicescommon.coordination.ZooKeeperModelReporter;
import com.spotify.helios.servicescommon.statistics.FastForwardReporter;
import com.spotify.helios.servicescommon.statistics.Metrics;
import com.spotify.helios.servicescommon.statistics.MetricsImpl;
import com.spotify.helios.servicescommon.statistics.NoopMetrics;
import io.dropwizard.configuration.ConfigurationException;
import io.dropwizard.jetty.GzipFilterFactory;
import io.dropwizard.jetty.RequestLogFactory;
import io.dropwizard.logging.AppenderFactory;
import io.dropwizard.server.DefaultServerFactory;
import io.dropwizard.setup.Environment;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.AuthInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.ACL;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Helios master service.
*/
public class MasterService extends AbstractIdleService {
private static final Logger log = LoggerFactory.getLogger(MasterService.class);
private static final String LOGBACK_ACCESS_CONFIG = "logback-access.xml";
private static final String LOGBACK_ACCESS_RESOURCE = "/" + LOGBACK_ACCESS_CONFIG;
private final Server server;
private final MasterConfig config;
private final ServiceRegistrar registrar;
private final ZooKeeperClient zooKeeperClient;
private final ExpiredJobReaper expiredJobReaper;
private final CuratorClientFactory curatorClientFactory;
private final RollingUpdateService rollingUpdateService;
private final Optional<DeadAgentReaper> agentReaper;
private final Optional<OldJobReaper> oldJobReaper;
private final Optional<JobHistoryReaper> jobHistoryReaper;
private ZooKeeperRegistrarService zkRegistrar;
/**
* Create a new service instance. Initializes the control interface and the worker.
*
* @param config The service configuration.
* @param environment The DropWizard environment.
* @param curatorClientFactory The zookeeper curator factory.
*
* @throws ConfigurationException If there is a problem with the DropWizard configuration.
* @throws IOException IOException
* @throws InterruptedException InterruptedException
*/
public MasterService(final MasterConfig config,
final Environment environment,
final CuratorClientFactory curatorClientFactory)
throws ConfigurationException, IOException, InterruptedException {
this.config = config;
this.curatorClientFactory = curatorClientFactory;
// Configure metrics
final MetricRegistry metricsRegistry = environment.metrics();
metricsRegistry.registerAll(new GarbageCollectorMetricSet());
metricsRegistry.registerAll(new MemoryUsageGaugeSet());
log.info("Starting metrics");
final Metrics metrics;
if (config.isInhibitMetrics()) {
metrics = new NoopMetrics();
} else {
metrics = new MetricsImpl(metricsRegistry, MetricsImpl.Type.MASTER);
metrics.start();
if (!Strings.isNullOrEmpty(config.getStatsdHostPort())) {
environment.lifecycle().manage(new ManagedStatsdReporter(config.getStatsdHostPort(),
metricsRegistry));
}
final FastForwardConfig ffwdConfig = config.getFfwdConfig();
if (ffwdConfig != null) {
environment.lifecycle().manage(FastForwardReporter.create(
metricsRegistry,
ffwdConfig.getAddress(),
ffwdConfig.getMetricKey(),
ffwdConfig.getReportingIntervalSeconds())
);
}
}
// Set up the master model
this.zooKeeperClient = setupZookeeperClient(config);
final ZooKeeperModelReporter modelReporter =
new ZooKeeperModelReporter(metrics.getZooKeeperMetrics());
final ZooKeeperClientProvider zkClientProvider = new ZooKeeperClientProvider(
zooKeeperClient, modelReporter);
// Create state directory, if necessary
final Path stateDirectory = config.getStateDirectory().toAbsolutePath().normalize();
if (!Files.exists(stateDirectory)) {
try {
Files.createDirectories(stateDirectory);
} catch (IOException e) {
log.error("Failed to create state directory: {}", stateDirectory, e);
throw new RuntimeException(e);
}
}
final String deploymentGroupEventTopic = TaskStatusEvent.TASK_STATUS_EVENT_TOPIC;
final List<EventSender> eventSenders =
EventSenderFactory.build(environment, config, metricsRegistry, deploymentGroupEventTopic);
final ZooKeeperMasterModel model =
new ZooKeeperMasterModel(zkClientProvider, config.getName(), eventSenders,
deploymentGroupEventTopic);
final ZooKeeperHealthChecker zooKeeperHealthChecker =
new ZooKeeperHealthChecker(zooKeeperClient);
environment.healthChecks().register("zookeeper", zooKeeperHealthChecker);
// Report health checks as a gauge metric
environment.healthChecks().getNames().forEach(
name -> environment.metrics().register(
"helios." + name + ".ok", new HealthCheckGauge(environment.healthChecks(), name)));
// Set up service registrar
this.registrar = createServiceRegistrar(config.getServiceRegistrarPlugin(),
config.getServiceRegistryAddress(),
config.getDomain());
// Set up reaping of expired jobs
this.expiredJobReaper = ExpiredJobReaper.newBuilder()
.setMasterModel(model)
.build();
// Set up rolling update service
final ReactorFactory reactorFactory = new ReactorFactory();
this.rollingUpdateService = new RollingUpdateService(model, reactorFactory);
// Set up agent reaper (de-registering hosts that have been DOWN for more than X hours)
if (config.getAgentReapingTimeout() > 0) {
this.agentReaper = Optional.of(new DeadAgentReaper(model, config.getAgentReapingTimeout()));
} else {
log.info("Reaping of dead agents disabled");
this.agentReaper = Optional.empty();
}
// Set up old job reaper (removes jobs not deployed anywhere and created more than X days ago)
if (config.getJobRetention() > 0) {
this.oldJobReaper = Optional.of(new OldJobReaper(model, config.getJobRetention()));
} else {
log.info("Reaping of old jobs disabled");
this.oldJobReaper = Optional.empty();
}
// Set up job history reaper (removes histories whose corresponding job doesn't exist)
if (config.isJobHistoryReapingEnabled()) {
this.jobHistoryReaper = Optional.of(
new JobHistoryReaper(model, zkClientProvider.get("jobHistoryReaper")));
} else {
log.info("Reaping of orphaned jobs disabled");
this.jobHistoryReaper = Optional.empty();
}
// Set up http server
environment.servlets()
.addFilter("VersionResponseFilter", new VersionResponseFilter(metrics.getMasterMetrics()))
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
environment.jersey().register(
new ReportingResourceMethodDispatchAdapter(metrics.getMasterMetrics()));
environment.jersey().register(new JobsResource(
model, metrics.getMasterMetrics(), config.getWhitelistedCapabilities()));
environment.jersey().register(new HistoryResource(model, metrics.getMasterMetrics()));
environment.jersey().register(new HostsResource(model));
environment.jersey().register(new MastersResource(model));
environment.jersey().register(new VersionResource());
environment.jersey().register(new UserProvider());
environment.jersey().register(new DeploymentGroupResource(model));
final DefaultServerFactory serverFactory = ServiceUtil.createServerFactory(
config.getHttpEndpoint(), config.getAdminEndpoint(), false);
final RequestLogFactory requestLog = new RequestLogFactory();
requestLog.setAppenders(ImmutableList.<AppenderFactory>of());
serverFactory.setRequestLogFactory(requestLog);
// Enable CORS headers
final FilterRegistration.Dynamic cors = environment.servlets()
.addFilter("CORS", CrossOriginFilter.class);
// Configure CORS parameters
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
// Add URL mapping
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
// Enable gzip compression for POST and GET requests. Default is GET only.
final GzipFilterFactory gzip = new GzipFilterFactory();
gzip.setIncludedMethods(ImmutableSet.of("GET", "POST"));
serverFactory.setGzipFilterFactory(gzip);
this.server = serverFactory.build(environment);
setUpRequestLogging(stateDirectory);
}
private void setUpRequestLogging(final Path stateDirectory) {
// Set up request logging
final Handler originalHandler = server.getHandler();
final HandlerCollection handlerCollection;
if (originalHandler instanceof HandlerCollection) {
handlerCollection = (HandlerCollection) originalHandler;
} else {
handlerCollection = new HandlerCollection();
handlerCollection.addHandler(originalHandler);
}
final RequestLogHandler requestLogHandler = new RequestLogHandler();
final RequestLogImpl requestLog = new RequestLogImpl();
requestLog.setQuiet(true);
if (stateDirectory.resolve(LOGBACK_ACCESS_CONFIG).toFile().exists()) {
requestLog.setFileName(stateDirectory.resolve(LOGBACK_ACCESS_CONFIG).toString());
} else if (this.getClass().getResource(LOGBACK_ACCESS_RESOURCE) != null) {
requestLog.setResource(LOGBACK_ACCESS_RESOURCE);
}
requestLogHandler.setRequestLog(requestLog);
handlerCollection.addHandler(requestLogHandler);
server.setHandler(handlerCollection);
}
@Override
protected void startUp() throws Exception {
logBanner();
if (!config.getNoZooKeeperMasterRegistration()) {
zkRegistrar.startAsync().awaitRunning();
}
expiredJobReaper.startAsync().awaitRunning();
rollingUpdateService.startAsync().awaitRunning();
agentReaper.ifPresent(reaper -> reaper.startAsync().awaitRunning());
oldJobReaper.ifPresent(reaper -> reaper.startAsync().awaitRunning());
jobHistoryReaper.ifPresent(reaper -> reaper.startAsync().awaitRunning());
try {
server.start();
} catch (Exception e) {
log.error("Unable to start server, shutting down", e);
server.stop();
}
final ServiceRegistration serviceRegistration = ServiceRegistration.newBuilder()
.endpoint("helios", "http", config.getHttpEndpoint().getPort(),
config.getDomain(), config.getName())
.build();
registrar.register(serviceRegistration);
}
@Override
protected void shutDown() throws Exception {
server.stop();
server.join();
registrar.close();
agentReaper.ifPresent(reaper -> reaper.stopAsync().awaitTerminated());
oldJobReaper.ifPresent(reaper -> reaper.stopAsync().awaitTerminated());
jobHistoryReaper.ifPresent(reaper -> reaper.stopAsync().awaitTerminated());
rollingUpdateService.stopAsync().awaitTerminated();
expiredJobReaper.stopAsync().awaitTerminated();
zkRegistrar.stopAsync().awaitTerminated();
zooKeeperClient.close();
}
private void logBanner() {
try {
final String banner = Resources.toString(Resources.getResource("master-banner.txt"), UTF_8);
log.info("\n{}", banner);
} catch (IllegalArgumentException | IOException ignored) {
// ignored
}
}
/**
* Create a Zookeeper client and create the control and state nodes if needed.
*
* @param config The service configuration.
*
* @return A zookeeper client.
*/
private ZooKeeperClient setupZookeeperClient(final MasterConfig config) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
final String masterUser = config.getZookeeperAclMasterUser();
final String masterPassword = config.getZooKeeperAclMasterPassword();
final String agentUser = config.getZookeeperAclAgentUser();
final String agentDigest = config.getZooKeeperAclAgentDigest();
if (!isNullOrEmpty(masterPassword)) {
if (isNullOrEmpty(masterUser)) {
throw new HeliosRuntimeException(
"Master username must be set if a password is set");
}
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", masterUser, masterPassword).getBytes()));
}
if (config.isZooKeeperEnableAcls()) {
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or password not set");
}
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, digest(masterUser, masterPassword),
agentUser, agentDigest);
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = curatorClientFactory.newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
aclProvider,
authorization);
final ZooKeeperClient client =
new DefaultZooKeeperClient(curator, config.getZooKeeperClusterId());
client.start();
zkRegistrar = ZooKeeperRegistrarService.newBuilder()
.setZooKeeperClient(client)
.setZooKeeperRegistrar(new MasterZooKeeperRegistrar(config.getName()))
.build();
// TODO: This is perhaps not the correct place to do this - but at present it's the only
// place where we have access to the ACL provider.
if (aclProvider != null) {
// Set ACLs on the ZK root, if they aren't already set correctly.
// This is handy since it avoids having to manually do this operation when setting up
// a new ZK cluster.
// Note that this is slightly racey -- if two masters start at the same time both might
// attempt to update the ACLs but only one will succeed. That said, it's unlikely and the
// effects are limited to a spurious log line.
try {
final List<ACL> curAcls = client.getAcl("/");
final List<ACL> wantedAcls = aclProvider.getAclForPath("/");
if (!Sets.newHashSet(curAcls).equals(Sets.newHashSet(wantedAcls))) {
log.info(
"Current ACL's on the zookeeper root node differ from desired, updating: {} -> {}",
curAcls, wantedAcls);
client.getCuratorFramework().setACL().withACL(wantedAcls).forPath("/");
}
} catch (Exception e) {
log.error("Failed to get/set ACLs on the zookeeper root node", e);
}
}
return client;
}
}
| apache-2.0 |
tolo/JServer | src/java/com/teletalk/jserver/net/sns/client/SnsServerAdministrationClient.java | 2884 | /*
* Copyright 2007 the project originators.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.teletalk.jserver.net.sns.client;
import com.teletalk.jserver.net.sns.server.SnsServer;
import com.teletalk.jserver.tcp.messaging.Destination;
import com.teletalk.jserver.tcp.messaging.MessageHeader;
import com.teletalk.jserver.tcp.messaging.MessagingManager;
import com.teletalk.jserver.tcp.messaging.admin.ServerAdministrationClient;
import com.teletalk.jserver.tcp.messaging.rpc.MessagingRpcInterface;
/**
* Client implementation of RPC based messaging remote administration of JServer via an SNS.
*
* @author Tobias Löfstrand
*
* @since 2.1.4 (20060511)
*/
public class SnsServerAdministrationClient extends ServerAdministrationClient
{
/**
* Creates an SnsServerAdministrationClient.
*/
public SnsServerAdministrationClient(MessagingManager messagingManager, Destination remoteServer, SnsServer currentSns)
{
super(messagingManager, remoteServer);
this.initMessagingRpcInterface(currentSns);
}
/**
* Creates an SnsServerAdministrationClient.
*/
public SnsServerAdministrationClient(MessagingRpcInterface messagingRpcInterface, String rpcHandlerName, SnsServer currentSns)
{
super(messagingRpcInterface, rpcHandlerName);
this.initMessagingRpcInterface(currentSns);
}
/**
* Creates an SnsServerAdministrationClient.
*/
public SnsServerAdministrationClient(MessagingRpcInterface messagingRpcInterface, SnsServer currentSns)
{
super(messagingRpcInterface);
this.initMessagingRpcInterface(currentSns);
}
private void initMessagingRpcInterface(final SnsServer currentSns)
{
int snsServerInterfaceVersion = 1;
try{
snsServerInterfaceVersion = currentSns.getInterfaceVersion();
}catch(Exception e){}
if( snsServerInterfaceVersion < 2 )
{
MessageHeader prototypeHeader = super.getMessagingRpcInterface().getMessageDispatcher().getPrototypeMessageHeader();
if( prototypeHeader == null ) prototypeHeader = new MessageHeader();
prototypeHeader.setHeaderType(MessageHeader.RPC_HEADER);
this.messagingRpcInterface.getMessageDispatcher().setPrototypeMessageHeader(prototypeHeader);
}
}
}
| apache-2.0 |
Mozu/mozu-python-sdk | mozurestsdk/commerce/customer/accounts/customernote.py | 5978 |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozurestsdk.apicontext import ApiContext;
class CustomerNote(object):
def __init__(self, apiContext: ApiContext = None, mozuClient = None):
self.client = mozuClient or default_client();
if (apiContext is not None):
self.client.withApiContext(apiContext);
else:
self.client.withApiContext(ApiContext());
def getAccountNote(self,accountId, noteId, responseFields = None):
""" Retrieves the contents of a particular note attached to a specified customer account.
Args:
| accountId (int) - Unique identifier of the customer account.
| noteId (int) - Unique identifier of a particular note to retrieve.
| responseFields (string) - Use this field to include those fields which are not included by default.
Returns:
| CustomerNote
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/customer/accounts/{accountId}/notes/{noteId}?responseFields={responseFields}", "GET", UrlLocation.TenantPod, False);
url.formatUrl("accountId", accountId);
url.formatUrl("noteId", noteId);
url.formatUrl("responseFields", responseFields);
self.client.withResourceUrl(url).execute();
return self.client.result();
def getAccountNotes(self,accountId, startIndex = None, pageSize = None, sortBy = None, filter = None, responseFields = None):
""" Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options.
Args:
| accountId (int) - Unique identifier of the customer account.
| startIndex (int) - When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
| pageSize (int) - The number of results to display on each page when creating paged results from a query. The maximum value is 200.
| sortBy (string) - The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
| filter (string) - A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
| responseFields (string) - Use this field to include those fields which are not included by default.
Returns:
| CustomerNoteCollection
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/customer/accounts/{accountId}/notes?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}", "GET", UrlLocation.TenantPod, False);
url.formatUrl("accountId", accountId);
url.formatUrl("filter", filter);
url.formatUrl("pageSize", pageSize);
url.formatUrl("responseFields", responseFields);
url.formatUrl("sortBy", sortBy);
url.formatUrl("startIndex", startIndex);
self.client.withResourceUrl(url).execute();
return self.client.result();
def addAccountNote(self,note, accountId, responseFields = None):
""" Adds a new note to the specified customer account.
Args:
| note(note) - Properties of a note configured for a customer account.
| accountId (int) - Unique identifier of the customer account.
| responseFields (string) - Use this field to include those fields which are not included by default.
Returns:
| CustomerNote
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/customer/accounts/{accountId}/notes?responseFields={responseFields}", "POST", UrlLocation.TenantPod, False);
url.formatUrl("accountId", accountId);
url.formatUrl("responseFields", responseFields);
self.client.withResourceUrl(url).withBody(note).execute();
return self.client.result();
def updateAccountNote(self,note, accountId, noteId, responseFields = None):
""" Modifies an existing note for a customer account.
Args:
| note(note) - Properties of a note configured for a customer account.
| accountId (int) - Unique identifier of the customer account.
| noteId (int) - Unique identifier of a particular note to retrieve.
| responseFields (string) - Use this field to include those fields which are not included by default.
Returns:
| CustomerNote
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/customer/accounts/{accountId}/notes/{noteId}?responseFields={responseFields}", "PUT", UrlLocation.TenantPod, False);
url.formatUrl("accountId", accountId);
url.formatUrl("noteId", noteId);
url.formatUrl("responseFields", responseFields);
self.client.withResourceUrl(url).withBody(note).execute();
return self.client.result();
def deleteAccountNote(self,accountId, noteId):
""" Removes a note from the specified customer account.
Args:
| accountId (int) - Unique identifier of the customer account.
| noteId (int) - Unique identifier of a particular note to retrieve.
Raises:
| ApiException
"""
url = MozuUrl("/api/commerce/customer/accounts/{accountId}/notes/{noteId}", "DELETE", UrlLocation.TenantPod, False);
url.formatUrl("accountId", accountId);
url.formatUrl("noteId", noteId);
self.client.withResourceUrl(url).execute();
| apache-2.0 |
SergeyZubkov/Angular-ES6-Webpack-SCSS | client/app/filters/rateFilter.js | 118 | function rateFilter() {
return function(input) {
return `${input} руб./час`
}
}
export default rateFilter;
| apache-2.0 |
ouhi2008/NuGetGalleryWithLDAP | Website/Commands/ModifyCuratedPackageCommand.cs | 1228 | using System;
using System.Linq;
namespace NuGetGallery
{
public interface IModifyCuratedPackageCommand
{
void Execute(
int curatedFeedKey,
int curatedPackageKey,
bool included);
}
public class ModifyCuratedPackageCommand : AppCommand, IModifyCuratedPackageCommand
{
public ModifyCuratedPackageCommand(IEntitiesContext entities)
: base(entities)
{
}
public void Execute(
int curatedFeedKey,
int curatedPackageKey,
bool included)
{
var curatedFeed = GetService<ICuratedFeedByKeyQuery>().Execute(curatedFeedKey, includePackages: true);
if (curatedFeed == null)
{
throw new InvalidOperationException("The curated feed does not exist.");
}
var curatedPackage = curatedFeed.Packages.SingleOrDefault(cp => cp.Key == curatedPackageKey);
if (curatedPackage == null)
{
throw new InvalidOperationException("The curated package does not exist.");
}
curatedPackage.Included = included;
Entities.SaveChanges();
}
}
} | apache-2.0 |
weld/core | tests-arquillian/src/test/java/org/jboss/weld/tests/interceptors/aroundConstruct/basic/BravoParameterProducer.java | 1100 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.interceptors.aroundConstruct.basic;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.Produces;
@Dependent
public class BravoParameterProducer {
@Produces
public BravoParameter produceParameter1() {
return new BravoParameter("parameter1");
}
}
| apache-2.0 |
ice91/CloudBrush | src/Brush/Graph2Fasta.java | 4079 | /*
The file is derived from Contrail Project which is developed by Michael Schatz,
Jeremy Chambers, Avijit Gupta, Rushil Gupta, David Kelley, Jeremy Lewi,
Deepak Nettem, Dan Sommer, Mihai Pop, Schatz Lab and Cold Spring Harbor Laboratory,
and is released under Apache License 2.0 at:
http://sourceforge.net/apps/mediawiki/contrail-bio/
*/
package Brush;
import java.io.IOException;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
public class Graph2Fasta extends Configured implements Tool
{
private static final Logger sLogger = Logger.getLogger(Graph2Fasta.class);
// Graph2FastaMapper
///////////////////////////////////////////////////////////////////////////
private static class Graph2FastaMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, Text>
{
public void map(LongWritable lineid, Text nodetxt,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException
{
Node node = new Node();
node.fromNodeMsg(nodetxt.toString());
reporter.incrCounter("Brush", "nodes", 1);
String str = node.str();
output.collect(new Text(">" + node.getNodeId()), new Text("len=" + str.length() + "\tcov=" + node.cov()));
int LINE_LEN = 60;
for (int i = 0; i < str.length(); i+=LINE_LEN)
{
int end = i + LINE_LEN;
if (end > str.length()) { end = str.length();}
String line = str.substring(i, end);
output.collect(new Text(line), null);
}
}
}
// Run Tool
///////////////////////////////////////////////////////////////////////////
public RunningJob run(String inputPath, String outputPath) throws Exception
{
sLogger.info("Tool name: Graph2Fasta");
sLogger.info(" - input: " + inputPath);
sLogger.info(" - output: " + outputPath);
JobConf conf = new JobConf(Graph2Fasta.class);
conf.setJobName("Graph2Fasta " + inputPath);
FileInputFormat.addInputPath(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path(outputPath));
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
conf.setMapOutputKeyClass(Text.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(Graph2FastaMapper.class);
BrushConfig.initializeConfiguration(conf);
conf.setNumReduceTasks(0);
//delete the output directory if it exists already
FileSystem.get(conf).delete(new Path(outputPath), true);
return JobClient.runJob(conf);
}
// Parse Arguments and run
///////////////////////////////////////////////////////////////////////////
public int run(String[] args) throws Exception
{
String inputPath = "";
String outputPath = "";
run(inputPath, outputPath);
return 0;
}
// Main
///////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws Exception
{
int res = ToolRunner.run(new Configuration(), new Graph2Fasta(), args);
System.exit(res);
}
}
| apache-2.0 |
kingargyle/turmeric-bot | tests/camel-itest-karaf/src/test/java/org/apache/camel/itest/karaf/CamelQuickFixTest.java | 1467 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.itest.karaf;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
@RunWith(JUnit4TestRunner.class)
@Ignore("Requires Karaf 2.2 which has slf4j logger improved")
public class CamelQuickFixTest extends AbstractFeatureTest {
public static final String COMPONENT = "quickfix";
@Test
public void test() throws Exception {
testComponent(COMPONENT);
}
@Configuration
public static Option[] configure() {
return configure(COMPONENT);
}
} | apache-2.0 |
azzlack/Sentinel.OAuth | src/Sentinel.Tests/Unit/SHA2CryptoProviderTests.cs | 6073 | namespace Sentinel.Tests.Unit
{
using Newtonsoft.Json;
using NUnit.Framework;
using Sentinel.OAuth.Core.Constants.Identity;
using Sentinel.OAuth.Core.Interfaces.Providers;
using Sentinel.OAuth.Implementation.Providers;
using Sentinel.OAuth.Models.Identity;
using System;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using HashAlgorithm = Sentinel.OAuth.Core.Constants.HashAlgorithm;
[TestFixture]
[Category("Unit")]
public class SHA2CryptoProviderTests
{
private ICryptoProvider provider;
[SetUp]
public void SetUp()
{
this.provider = new SHA2CryptoProvider(OAuth.Core.Constants.HashAlgorithm.SHA256);
}
[TestCase(256)]
[TestCase(384)]
[TestCase(512)]
public void Create_WhenGivenValidLength_ReturnsValidHash(int size)
{
var p = new SHA2CryptoProvider((HashAlgorithm)Enum.Parse(typeof(HashAlgorithm), size.ToString()));
var hash = p.CreateHash(size);
var raw = Convert.FromBase64String(hash);
Console.WriteLine($"Hash: {hash}");
Console.WriteLine($"Hash Size: {size / 8} bits");
Console.WriteLine($"Raw Size: {raw.Length} bits");
Assert.AreEqual(size / 8, raw.Length);
}
[TestCase("aabbccddee")]
public void Create_WhenGivenValidString_ReturnsHash(string text)
{
var hash = this.provider.CreateHash(text);
Console.WriteLine("Hash: {0}", hash);
Assert.IsNotNullOrEmpty(hash);
}
[Test]
public void Create_WhenGeneratingString_ReturnsValidHash()
{
string text;
var hash = this.provider.CreateHash(out text, 8);
Console.WriteLine("Hash: {0}", hash);
Assert.IsNotNullOrEmpty(hash);
var valid = this.provider.ValidateHash(text, hash);
Assert.IsTrue(valid);
}
[TestCase(8)]
[TestCase(48)]
[TestCase(64)]
[TestCase(128)]
public void Create_WhenGeneratingStringWithSpecificLength_ReturnsValidHash(int size)
{
string text;
var hash = this.provider.CreateHash(out text, size);
Console.WriteLine("Hash: {0}", hash);
var textSize = Encoding.UTF8.GetBytes(text);
Console.WriteLine("Text: {0}", text);
Console.WriteLine("Text Size: {0} bits", textSize.Length * 8);
Assert.AreEqual(size, textSize.Length * 8);
Assert.IsNotNullOrEmpty(hash);
var valid = this.provider.ValidateHash(text, hash);
Assert.IsTrue(valid);
}
[TestCase(64, "aabbccddee")]
[TestCase(48, "123")]
[TestCase(128, "aabbccddee")]
public void Create_WhenGivenValidString_ReturnsHash(int saltByteSize, string text)
{
var p = new SHA2CryptoProvider(Sentinel.OAuth.Core.Constants.HashAlgorithm.SHA256, saltByteSize);
var hash = p.CreateHash(text);
Console.WriteLine("Hash: {0}", hash);
Assert.IsNotNullOrEmpty(hash);
}
[TestCase("aabbccddee")]
[TestCase("bfdsghbjflbnfkdkhgureinbfdlg")]
public void Validate_WhenGivenValidTextAndHashCombination_ReturnsTrue(string text)
{
var hash = this.provider.CreateHash(text);
var valid = this.provider.ValidateHash(text, hash);
Assert.IsTrue(valid);
}
[TestCase("aabbccddee", "JsSAQQiINCmefez0E1vt9VLEwd6kMPD/M3/qwDOpuIw2WupF77UkJIYwzabp2G0CVhYPgDs+craqGzYX9anabcTePNfni5gJ79it0LnjiIng9A5guQ4wEwn+OCPgWZI+a7n7Uy2rNLd+0wTkYX/JX+dU+rgh0xhefIs1Gq5Vxuc=")]
[TestCase("aabbccddee", "bdsbgdsnkjlnkls")]
public void Validate_WhenGivenIncorrectTextAndHashCombination_ReturnsFalse(string text, string correctHash)
{
var valid = this.provider.ValidateHash(text, correctHash);
Assert.IsFalse(valid);
}
[TestCase(64)]
[TestCase(24)]
public void Validate_WhenGivenAutoGeneratedString_ReturnsValid(int saltByteSize)
{
var p = new SHA2CryptoProvider(Sentinel.OAuth.Core.Constants.HashAlgorithm.SHA512, saltByteSize);
var csprng = new RNGCryptoServiceProvider();
var arr = new byte[64];
csprng.GetBytes(arr);
var text = Encoding.UTF8.GetString(arr);
Console.WriteLine("Text: {0}", text);
var hash = p.CreateHash(text);
Console.WriteLine("Hash: {0}", hash);
var valid = p.ValidateHash(text, hash);
Assert.IsTrue(valid);
}
[TestCase("Lorem ipsum", "myspecialkey")]
[TestCase("b dnsnfgrsnfgnfghnfgnfg", "some otherky")]
public void Encrypt_WhenGivenString_ReturnsEncryptedString(string text, string key)
{
var r = this.provider.Encrypt(text, key);
Console.WriteLine("Original: {0}", text);
Console.WriteLine("Encrypted: {0}", r);
Assert.IsNotNullOrEmpty(r);
}
[TestCase("v s bvzølnbdskøcmbøsdmvdøsbvjkdsb mvbdsvndjkls")]
[TestCase("myspecialkey")]
public void Decrypt_WhenGivenEncryptedString_ReturnsDecryptedString(string key)
{
var c1 = new SentinelPrincipal(new SentinelIdentity(AuthenticationType.OAuth, new SentinelClaim(ClaimTypes.Name, "azzlack")));
var s = JsonConvert.SerializeObject(c1);
var e = this.provider.Encrypt(s, key);
Console.WriteLine("Original: {0}", s);
Console.WriteLine();
Console.WriteLine("Encrypted: {0}", e);
Console.WriteLine();
var d = this.provider.Decrypt(e, key);
Console.WriteLine("Decrypted: {0}", d);
var c2 = JsonConvert.DeserializeObject<SentinelPrincipal>(d);
Assert.AreEqual(c1.Identity.Name, c2.Identity.Name);
}
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/handlers/RequestHandler2Adaptor.java | 2443 | /*
* Copyright 2010-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.handlers;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.util.AWSRequestMetrics;
import com.amazonaws.util.TimingInfo;
/**
* Internal class used to adapt a request handler that implements the
* deprecated {@link RequestHandler} interface to the deprecating
* {@link RequestHandler2} interface.
*/
final class RequestHandler2Adaptor extends RequestHandler2 {
@SuppressWarnings("deprecation")
private final RequestHandler old;
RequestHandler2Adaptor(@SuppressWarnings("deprecation") RequestHandler old) {
if (old == null)
throw new IllegalArgumentException();
this.old = old;
}
@SuppressWarnings("deprecation")
@Override public void beforeRequest(Request<?> request) {
old.beforeRequest(request);
}
@SuppressWarnings("deprecation")
@Override
public void afterResponse(Request<?> request, Response<?> response) {
AWSRequestMetrics awsRequestMetrics = request == null ? null : request
.getAWSRequestMetrics();
Object awsResponse = response == null ? null : response
.getAwsResponse();
TimingInfo timingInfo = awsRequestMetrics == null ? null
: awsRequestMetrics.getTimingInfo();
old.afterResponse(request, awsResponse, timingInfo);
}
@SuppressWarnings("deprecation")
@Override public void afterError(Request<?> request, Response<?> response,
Exception e) {
old.afterError(request, e);
}
@Override public int hashCode() {
return old.hashCode();
}
@Override public boolean equals(Object o) {
if (!(o instanceof RequestHandler2Adaptor))
return false;
RequestHandler2Adaptor that = (RequestHandler2Adaptor)o;
return this.old.equals(that.old);
}
}
| apache-2.0 |
squaremo/libnetwork | drivers/remote/driver.go | 6836 | package remote
import (
"fmt"
"net"
log "github.com/Sirupsen/logrus"
"github.com/docker/docker/pkg/plugins"
"github.com/docker/libnetwork/driverapi"
"github.com/docker/libnetwork/types"
)
type driver struct {
endpoint *plugins.Client
networkType string
}
func newDriver(name string, client *plugins.Client) driverapi.Driver {
return &driver{networkType: name, endpoint: client}
}
// Init makes sure a remote driver is registered when a network driver
// plugin is activated.
func Init(dc driverapi.DriverCallback) error {
plugins.Handle(driverapi.NetworkPluginEndpointType, func(name string, client *plugins.Client) {
if err := dc.RegisterDriver(name, newDriver(name, client)); err != nil {
log.Errorf("error registering driver for %s due to %v", name, err)
}
})
return nil
}
// Config is not implemented for remote drivers, since it is assumed
// to be supplied to the remote process out-of-band (e.g., as command
// line arguments).
func (d *driver) Config(option map[string]interface{}) error {
return &driverapi.ErrNotImplemented{}
}
func (d *driver) call(methodName string, arg interface{}, retVal maybeError) error {
method := driverapi.NetworkPluginEndpointType + "." + methodName
err := d.endpoint.Call(method, arg, retVal)
if err != nil {
return err
}
if e := retVal.getError(); e != "" {
return fmt.Errorf("remote: %s", e)
}
return nil
}
func (d *driver) CreateNetwork(id types.UUID, options map[string]interface{}) error {
create := &createNetworkRequest{
NetworkID: string(id),
Options: options,
}
return d.call("CreateNetwork", create, &createNetworkResponse{})
}
func (d *driver) DeleteNetwork(nid types.UUID) error {
delete := &deleteNetworkRequest{NetworkID: string(nid)}
return d.call("DeleteNetwork", delete, &deleteNetworkResponse{})
}
func (d *driver) CreateEndpoint(nid, eid types.UUID, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
if epInfo == nil {
return fmt.Errorf("must not be called with nil EndpointInfo")
}
reqIfaces := make([]*endpointInterface, len(epInfo.Interfaces()))
for i, iface := range epInfo.Interfaces() {
addr4 := iface.Address()
addr6 := iface.AddressIPv6()
reqIfaces[i] = &endpointInterface{
ID: iface.ID(),
Address: addr4.String(),
AddressIPv6: addr6.String(),
MacAddress: iface.MacAddress().String(),
}
}
create := &createEndpointRequest{
NetworkID: string(nid),
EndpointID: string(eid),
Interfaces: reqIfaces,
Options: epOptions,
}
var res createEndpointResponse
if err := d.call("CreateEndpoint", create, &res); err != nil {
return err
}
ifaces, err := res.parseInterfaces()
if err != nil {
return err
}
if len(reqIfaces) > 0 && len(ifaces) > 0 {
// We're not supposed to add interfaces if there already are
// some. Attempt to roll back
return errorWithRollback("driver attempted to add more interfaces", d.DeleteEndpoint(nid, eid))
}
for _, iface := range ifaces {
var addr4, addr6 net.IPNet
if iface.Address != nil {
addr4 = *(iface.Address)
}
if iface.AddressIPv6 != nil {
addr6 = *(iface.AddressIPv6)
}
if err := epInfo.AddInterface(iface.ID, iface.MacAddress, addr4, addr6); err != nil {
return errorWithRollback(fmt.Sprintf("failed to AddInterface %v: %s", iface, err), d.DeleteEndpoint(nid, eid))
}
}
return nil
}
func errorWithRollback(msg string, err error) error {
rollback := "rolled back"
if err != nil {
rollback = "failed to roll back: " + err.Error()
}
return fmt.Errorf("%s; %s", msg, rollback)
}
func (d *driver) DeleteEndpoint(nid, eid types.UUID) error {
delete := &deleteEndpointRequest{
NetworkID: string(nid),
EndpointID: string(eid),
}
return d.call("DeleteEndpoint", delete, &deleteEndpointResponse{})
}
func (d *driver) EndpointOperInfo(nid, eid types.UUID) (map[string]interface{}, error) {
info := &endpointInfoRequest{
NetworkID: string(nid),
EndpointID: string(eid),
}
var res endpointInfoResponse
if err := d.call("EndpointOperInfo", info, &res); err != nil {
return nil, err
}
return res.Value, nil
}
// Join method is invoked when a Sandbox is attached to an endpoint.
func (d *driver) Join(nid, eid types.UUID, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
join := &joinRequest{
NetworkID: string(nid),
EndpointID: string(eid),
SandboxKey: sboxKey,
Options: options,
}
var (
res joinResponse
err error
)
if err = d.call("Join", join, &res); err != nil {
return err
}
// Expect each interface ID given by CreateEndpoint to have an
// entry at that index in the names supplied here. In other words,
// if you supply 0..n interfaces with IDs 0..n above, you should
// supply the names in the same order.
ifaceNames := res.InterfaceNames
for _, iface := range jinfo.InterfaceNames() {
i := iface.ID()
if i >= len(ifaceNames) || i < 0 {
return fmt.Errorf("no correlating interface %d in supplied interface names", i)
}
supplied := ifaceNames[i]
if err := iface.SetNames(supplied.SrcName, supplied.DstPrefix); err != nil {
return errorWithRollback(fmt.Sprintf("failed to set interface name: %s", err), d.Leave(nid, eid))
}
}
var addr net.IP
if res.Gateway != "" {
if addr = net.ParseIP(res.Gateway); addr == nil {
return fmt.Errorf(`unable to parse Gateway "%s"`, res.Gateway)
}
if jinfo.SetGateway(addr) != nil {
return errorWithRollback(fmt.Sprintf("failed to set gateway: %v", addr), d.Leave(nid, eid))
}
}
if res.GatewayIPv6 != "" {
if addr = net.ParseIP(res.GatewayIPv6); addr == nil {
return fmt.Errorf(`unable to parse GatewayIPv6 "%s"`, res.GatewayIPv6)
}
if jinfo.SetGatewayIPv6(addr) != nil {
return errorWithRollback(fmt.Sprintf("failed to set gateway IPv6: %v", addr), d.Leave(nid, eid))
}
}
if len(res.StaticRoutes) > 0 {
routes, err := res.parseStaticRoutes()
if err != nil {
return err
}
for _, route := range routes {
if jinfo.AddStaticRoute(route.Destination, route.RouteType, route.NextHop, route.InterfaceID) != nil {
return errorWithRollback(fmt.Sprintf("failed to set static route: %v", route), d.Leave(nid, eid))
}
}
}
if jinfo.SetHostsPath(res.HostsPath) != nil {
return errorWithRollback(fmt.Sprintf("failed to set hosts path: %s", res.HostsPath), d.Leave(nid, eid))
}
if jinfo.SetResolvConfPath(res.ResolvConfPath) != nil {
return errorWithRollback(fmt.Sprintf("failed to set resolv.conf path: %s", res.ResolvConfPath), d.Leave(nid, eid))
}
return nil
}
// Leave method is invoked when a Sandbox detaches from an endpoint.
func (d *driver) Leave(nid, eid types.UUID) error {
leave := &leaveRequest{
NetworkID: string(nid),
EndpointID: string(eid),
}
return d.call("Leave", leave, &leaveResponse{})
}
func (d *driver) Type() string {
return d.networkType
}
| apache-2.0 |
webdriverextensions/webdriverextensions | src/main/java/com/github/webdriverextensions/internal/ReflectionUtils.java | 4083 | package com.github.webdriverextensions.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.lang.reflect.TypeVariable;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.pagefactory.ElementLocator;
public class ReflectionUtils {
private ReflectionUtils() {}
public static ElementLocator getLocator(WebElement webElement) {
try {
Field locatorField = webElement.getClass().getDeclaredField("locator");
locatorField.setAccessible(true);
ElementLocator locator = (ElementLocator) locatorField.get(locatorField);
locatorField.setAccessible(false);
return locator;
} catch (IllegalAccessException|NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public static Class getType(Field field, ParameterizedType genericTypeArguments) {
Type genericType = field.getGenericType();
if (genericType instanceof TypeVariable) {
TypeVariable genericTypeVariable = (TypeVariable) genericType;
TypeVariable<?>[] classGenericTypeParameters = ((TypeVariable) genericType).getGenericDeclaration().getTypeParameters();
for (int i = 0; i < classGenericTypeParameters.length; i++) {
if (classGenericTypeParameters[i].getName().equals(genericTypeVariable.getName())) {
return (Class) genericTypeArguments.getActualTypeArguments()[i];
}
}
throw new WebDriverExtensionException("Could not find genericTypeVariableName = " + genericTypeVariable.getName() + " in class");
} else {
return field.getType();
}
}
public static Class getListType(Field field, ParameterizedType genericTypeArguments) {
Type genericType = field.getGenericType();
Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
if (listType instanceof TypeVariable) {
String genericTypeVariableName = ((TypeVariable) listType).getName();
TypeVariable<?>[] classGenericTypeParameters = ((TypeVariable) listType).getGenericDeclaration().getTypeParameters();
for (int i = 0; i < classGenericTypeParameters.length; i++) {
if (classGenericTypeParameters[i].getName().equals(genericTypeVariableName)) {
return (Class) genericTypeArguments.getActualTypeArguments()[i];
}
}
throw new WebDriverExtensionException("Could not find genericTypeVariableName = " + genericTypeVariableName + " in class");
} if (listType instanceof ParameterizedType) {
return (Class) ((ParameterizedType) listType).getRawType();
} else {
return (Class) listType;
}
}
public static Field[] getAnnotatedDeclaredFields(Class clazz,
Class<? extends Annotation> annotationClass) {
Field[] allFields = getDeclaredFields(clazz);
List<Field> annotatedFields = new LinkedList<>();
for (Field field : allFields) {
if (field.isAnnotationPresent(annotationClass)) {
annotatedFields.add(field);
}
}
return annotatedFields.toArray(new Field[annotatedFields.size()]);
}
public static Field[] getDeclaredFields(Class clazz) {
List<Field> fields = new LinkedList<>();
Field[] declaredFields = clazz.getDeclaredFields();
Collections.addAll(fields, declaredFields);
Class superClass = clazz.getSuperclass();
if (superClass != null) {
Field[] declaredFieldsOfSuper = getDeclaredFields(superClass);
if (declaredFieldsOfSuper.length > 0) {
Collections.addAll(fields, declaredFieldsOfSuper);
}
}
return fields.toArray(new Field[fields.size()]);
}
}
| apache-2.0 |
Pkcs11Interop/Pkcs11Interop | src/Pkcs11Interop/HighLevelAPI81/MechanismParams/CkSsl3KeyMatParams.cs | 6919 | /*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI.MechanismParams;
using Net.Pkcs11Interop.LowLevelAPI81.MechanismParams;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.HighLevelAPI81.MechanismParams
{
/// <summary>
/// Parameters for the CKM_SSL3_KEY_AND_MAC_DERIVE mechanism
/// </summary>
public class CkSsl3KeyMatParams : ICkSsl3KeyMatParams
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Low level mechanism parameters
/// </summary>
private CK_SSL3_KEY_MAT_PARAMS _lowLevelStruct = new CK_SSL3_KEY_MAT_PARAMS();
/// <summary>
/// Flag indicating whether object with returned key material has left this instance
/// </summary>
private bool _returnedKeyMaterialLeftInstance = false;
/// <summary>
/// Resulting key handles and initialization vectors after performing a DeriveKey method
/// </summary>
private CkSsl3KeyMatOut _returnedKeyMaterial = null;
/// <summary>
/// Resulting key handles and initialization vectors after performing a DeriveKey method
/// </summary>
public ICkSsl3KeyMatOut ReturnedKeyMaterial
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
// Abrakadabra :)
UnmanagedMemory.Read(_lowLevelStruct.ReturnedKeyMaterial, _returnedKeyMaterial._lowLevelStruct);
// Since now it is the caller's responsibility to dispose returned key material
_returnedKeyMaterialLeftInstance = true;
return _returnedKeyMaterial;
}
}
/// <summary>
/// Client's and server's random data information
/// </summary>
private ICkSsl3RandomData _randomInfo = null;
/// <summary>
/// Initializes a new instance of the CkSsl3KeyMatParams class.
/// </summary>
/// <param name='macSizeInBits'>The length (in bits) of the MACing keys agreed upon during the protocol handshake phase</param>
/// <param name='keySizeInBits'>The length (in bits) of the secret keys agreed upon during the protocol handshake phase</param>
/// <param name='ivSizeInBits'>The length (in bits) of the IV agreed upon during the protocol handshake phase or if no IV is required, the length should be set to 0</param>
/// <param name='isExport'>Flag indicating whether the keys have to be derived for an export version of the protocol</param>
/// <param name='randomInfo'>Client's and server's random data information</param>
public CkSsl3KeyMatParams(NativeULong macSizeInBits, NativeULong keySizeInBits, NativeULong ivSizeInBits, bool isExport, ICkSsl3RandomData randomInfo)
{
if (randomInfo == null)
throw new ArgumentNullException("randomInfo");
// Keep reference to randomInfo so GC will not free it while this object exists
_randomInfo = randomInfo;
if (ivSizeInBits % 8 != 0)
throw new ArgumentException("Value has to be a multiple of 8", "ivSizeInBits");
// GC will not free ReturnedKeyMaterial while this object exists
_returnedKeyMaterial = new CkSsl3KeyMatOut(ivSizeInBits / 8);
_lowLevelStruct.MacSizeInBits = macSizeInBits;
_lowLevelStruct.KeySizeInBits = keySizeInBits;
_lowLevelStruct.IVSizeInBits = ivSizeInBits;
_lowLevelStruct.IsExport = isExport;
_lowLevelStruct.RandomInfo = (CK_SSL3_RANDOM_DATA)_randomInfo.ToMarshalableStructure();
// Abrakadabra :)
_lowLevelStruct.ReturnedKeyMaterial = UnmanagedMemory.Allocate(UnmanagedMemory.SizeOf(typeof(CK_SSL3_KEY_MAT_OUT)));
UnmanagedMemory.Write(_lowLevelStruct.ReturnedKeyMaterial, _returnedKeyMaterial._lowLevelStruct);
}
#region IMechanismParams
/// <summary>
/// Returns managed object that can be marshaled to an unmanaged block of memory
/// </summary>
/// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
public object ToMarshalableStructure()
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
return _lowLevelStruct;
}
#endregion
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
if (_returnedKeyMaterialLeftInstance == false)
{
if (_returnedKeyMaterial != null)
{
_returnedKeyMaterial.Dispose();
_returnedKeyMaterial = null;
}
}
}
// Dispose unmanaged objects
UnmanagedMemory.Free(ref _lowLevelStruct.ReturnedKeyMaterial);
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkSsl3KeyMatParams()
{
Dispose(false);
}
#endregion
}
}
| apache-2.0 |
aosp-mirror/platform_frameworks_support | compat/src/main/java/androidx/core/hardware/fingerprint/FingerprintManagerCompat.java | 11089 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package androidx.core.hardware.fingerprint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;
import androidx.core.os.CancellationSignal;
import java.security.Signature;
import javax.crypto.Cipher;
import javax.crypto.Mac;
/**
* A class that coordinates access to the fingerprint hardware.
* <p>
* On platforms before {@link android.os.Build.VERSION_CODES#M}, this class behaves as there would
* be no fingerprint hardware available.
*/
public final class FingerprintManagerCompat {
private final Context mContext;
/** Get a {@link FingerprintManagerCompat} instance for a provided context. */
@NonNull
public static FingerprintManagerCompat from(@NonNull Context context) {
return new FingerprintManagerCompat(context);
}
private FingerprintManagerCompat(Context context) {
mContext = context;
}
/**
* Determine if there is at least one fingerprint enrolled.
*
* @return true if at least one fingerprint is enrolled, false otherwise
*/
@RequiresPermission(android.Manifest.permission.USE_FINGERPRINT)
public boolean hasEnrolledFingerprints() {
if (Build.VERSION.SDK_INT >= 23) {
final FingerprintManager fp = getFingerprintManagerOrNull(mContext);
return (fp != null) && fp.hasEnrolledFingerprints();
} else {
return false;
}
}
/**
* Determine if fingerprint hardware is present and functional.
*
* @return true if hardware is present and functional, false otherwise.
*/
@RequiresPermission(android.Manifest.permission.USE_FINGERPRINT)
public boolean isHardwareDetected() {
if (Build.VERSION.SDK_INT >= 23) {
final FingerprintManager fp = getFingerprintManagerOrNull(mContext);
return (fp != null) && fp.isHardwareDetected();
} else {
return false;
}
}
/**
* Request authentication of a crypto object. This call warms up the fingerprint hardware
* and starts scanning for a fingerprint. It terminates when
* {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)} or
* {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} is called, at
* which point the object is no longer valid. The operation can be canceled by using the
* provided cancel object.
*
* @param crypto object associated with the call or null if none required.
* @param flags optional flags; should be 0
* @param cancel an object that can be used to cancel authentication
* @param callback an object to receive authentication events
* @param handler an optional handler for events
*/
@RequiresPermission(android.Manifest.permission.USE_FINGERPRINT)
public void authenticate(@Nullable CryptoObject crypto, int flags,
@Nullable CancellationSignal cancel, @NonNull AuthenticationCallback callback,
@Nullable Handler handler) {
if (Build.VERSION.SDK_INT >= 23) {
final FingerprintManager fp = getFingerprintManagerOrNull(mContext);
if (fp != null) {
android.os.CancellationSignal cancellationSignal = cancel != null
? (android.os.CancellationSignal) cancel.getCancellationSignalObject()
: null;
fp.authenticate(
wrapCryptoObject(crypto),
cancellationSignal,
flags,
wrapCallback(callback),
handler);
}
}
}
@Nullable
@RequiresApi(23)
private static FingerprintManager getFingerprintManagerOrNull(@NonNull Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
return context.getSystemService(FingerprintManager.class);
} else {
return null;
}
}
@RequiresApi(23)
private static FingerprintManager.CryptoObject wrapCryptoObject(CryptoObject cryptoObject) {
if (cryptoObject == null) {
return null;
} else if (cryptoObject.getCipher() != null) {
return new FingerprintManager.CryptoObject(cryptoObject.getCipher());
} else if (cryptoObject.getSignature() != null) {
return new FingerprintManager.CryptoObject(cryptoObject.getSignature());
} else if (cryptoObject.getMac() != null) {
return new FingerprintManager.CryptoObject(cryptoObject.getMac());
} else {
return null;
}
}
@RequiresApi(23)
static CryptoObject unwrapCryptoObject(FingerprintManager.CryptoObject cryptoObject) {
if (cryptoObject == null) {
return null;
} else if (cryptoObject.getCipher() != null) {
return new CryptoObject(cryptoObject.getCipher());
} else if (cryptoObject.getSignature() != null) {
return new CryptoObject(cryptoObject.getSignature());
} else if (cryptoObject.getMac() != null) {
return new CryptoObject(cryptoObject.getMac());
} else {
return null;
}
}
@RequiresApi(23)
private static FingerprintManager.AuthenticationCallback wrapCallback(
final AuthenticationCallback callback) {
return new FingerprintManager.AuthenticationCallback() {
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
callback.onAuthenticationError(errMsgId, errString);
}
@Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
callback.onAuthenticationHelp(helpMsgId, helpString);
}
@Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
callback.onAuthenticationSucceeded(new AuthenticationResult(
unwrapCryptoObject(result.getCryptoObject())));
}
@Override
public void onAuthenticationFailed() {
callback.onAuthenticationFailed();
}
};
}
/**
* A wrapper class for the crypto objects supported by FingerprintManager. Currently the
* framework supports {@link Signature} and {@link Cipher} objects.
*/
public static class CryptoObject {
private final Signature mSignature;
private final Cipher mCipher;
private final Mac mMac;
public CryptoObject(@NonNull Signature signature) {
mSignature = signature;
mCipher = null;
mMac = null;
}
public CryptoObject(@NonNull Cipher cipher) {
mCipher = cipher;
mSignature = null;
mMac = null;
}
public CryptoObject(@NonNull Mac mac) {
mMac = mac;
mCipher = null;
mSignature = null;
}
/**
* Get {@link Signature} object.
* @return {@link Signature} object or null if this doesn't contain one.
*/
@Nullable
public Signature getSignature() { return mSignature; }
/**
* Get {@link Cipher} object.
* @return {@link Cipher} object or null if this doesn't contain one.
*/
@Nullable
public Cipher getCipher() { return mCipher; }
/**
* Get {@link Mac} object.
* @return {@link Mac} object or null if this doesn't contain one.
*/
@Nullable
public Mac getMac() { return mMac; }
}
/**
* Container for callback data from {@link FingerprintManagerCompat#authenticate(CryptoObject,
* int, CancellationSignal, AuthenticationCallback, Handler)}.
*/
public static final class AuthenticationResult {
private final CryptoObject mCryptoObject;
public AuthenticationResult(CryptoObject crypto) {
mCryptoObject = crypto;
}
/**
* Obtain the crypto object associated with this transaction
* @return crypto object provided to {@link FingerprintManagerCompat#authenticate(
* CryptoObject, int, CancellationSignal, AuthenticationCallback, Handler)}.
*/
public CryptoObject getCryptoObject() { return mCryptoObject; }
}
/**
* Callback structure provided to {@link FingerprintManagerCompat#authenticate(CryptoObject,
* int, CancellationSignal, AuthenticationCallback, Handler)}. Users of {@link
* FingerprintManagerCompat#authenticate(CryptoObject, int, CancellationSignal,
* AuthenticationCallback, Handler) } must provide an implementation of this for listening to
* fingerprint events.
*/
public static abstract class AuthenticationCallback {
/**
* Called when an unrecoverable error has been encountered and the operation is complete.
* No further callbacks will be made on this object.
* @param errMsgId An integer identifying the error message
* @param errString A human-readable error string that can be shown in UI
*/
public void onAuthenticationError(int errMsgId, CharSequence errString) { }
/**
* Called when a recoverable error has been encountered during authentication. The help
* string is provided to give the user guidance for what went wrong, such as
* "Sensor dirty, please clean it."
* @param helpMsgId An integer identifying the error message
* @param helpString A human-readable string that can be shown in UI
*/
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { }
/**
* Called when a fingerprint is recognized.
* @param result An object containing authentication-related data
*/
public void onAuthenticationSucceeded(AuthenticationResult result) { }
/**
* Called when a fingerprint is valid but not recognized.
*/
public void onAuthenticationFailed() { }
}
}
| apache-2.0 |
AutorestCI/azure-sdk-for-node | lib/services/webSiteManagement2/lib/models/hybridConnectionCollection.js | 1617 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Collection of hostname bindings.
*/
class HybridConnectionCollection extends Array {
/**
* Create a HybridConnectionCollection.
* @member {string} [nextLink] Link to next page of resources.
*/
constructor() {
super();
}
/**
* Defines the metadata of HybridConnectionCollection
*
* @returns {object} metadata of HybridConnectionCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'HybridConnectionCollection',
type: {
name: 'Composite',
className: 'HybridConnectionCollection',
modelProperties: {
value: {
required: true,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'HybridConnectionElementType',
type: {
name: 'Composite',
className: 'HybridConnection'
}
}
}
},
nextLink: {
required: false,
serializedName: 'nextLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = HybridConnectionCollection;
| apache-2.0 |
lucca65/rails_semantic_base | spec/requests/messages_spec.rb | 239 | require 'rails_helper'
RSpec.describe "Messages", :type => :request do
describe "GET /messages" do
it "works! (now write some real specs)" do
get messages_path
expect(response).to have_http_status(200)
end
end
end
| apache-2.0 |
Yoyorony/FuncraftAlerts | java/yoyorony/me/funcraftv2alerts/ForumActivityItemsThird.java | 8874 | package yoyorony.me.funcraftv2alerts;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ForumActivityItemsThird extends AppCompatActivity {
public static ListView listviexRSS = null;
public static SwipeRefreshLayout swiper = null;
public static ArrayList<String> Title = new ArrayList<>();
public static ArrayList<String> Subtitle = new ArrayList<>();
public static ArrayList<String> Dates = new ArrayList<>();
public static ArrayList<String> Links = new ArrayList<>();
public static CustomBaseAdapterItems adapter;
public static AlertDialog waitDialog;
public static AlertDialog timeoutDialog;
public static AlertDialog errorDialog;
public static AlertDialog connexionerrorDialog;
public static boolean timeout;
public static boolean error;
public static boolean connexionerror;
private AdapterView.OnItemClickListener ListViewListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent browserintent = new Intent(Intent.ACTION_VIEW, Uri.parse(Links.get(position)));
browserintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(browserintent);
}
};
private SwipeRefreshLayout.OnRefreshListener SwiperListener = new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new DownloadItems().execute();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_apercuforum);
super.onCreate(savedInstanceState);
this.setTitle(getActTitle());
buildDialogs();
waitDialog.show();
listviexRSS = (ListView) findViewById(R.id.listViewRSS);
swiper = (SwipeRefreshLayout) findViewById(R.id.swipeRSS);
swiper.setOnRefreshListener(SwiperListener);
adapter = new CustomBaseAdapterItems(this, new ArrayList<StringsForAdapterItems>());
listviexRSS.setAdapter(adapter);
listviexRSS.setOnItemClickListener(ListViewListener);
new DownloadItems().execute();
}
private class DownloadItems extends AsyncTask<Void, Void, ArrayList<StringsForAdapterItems>> {
@Override
protected ArrayList<StringsForAdapterItems> doInBackground(Void... v) {
return getStringsAdapter();
}
protected void onPreExecute(){
timeout = false; error = false; connexionerror = false;
Title = new ArrayList<>();
Subtitle = new ArrayList<>();
Dates = new ArrayList<>();
Links = new ArrayList<>();
}
protected void onPostExecute(ArrayList<StringsForAdapterItems> forumList){
if(timeout){
waitDialog.dismiss();
timeoutDialog.show();
}else if(error){
waitDialog.dismiss();
errorDialog.show();
}else if(connexionerror){
waitDialog.dismiss();
connexionerrorDialog.show();
}else{
adapter.getStringArray().clear();
adapter.getStringArray().addAll(forumList);
adapter.notifyDataSetChanged();
waitDialog.dismiss();
}
swiper.setRefreshing(false);
}
}
private void buildDialogs(){
final ProgressDialog.Builder waitDialogBuilder = new ProgressDialog.Builder(this);
View view = this.getLayoutInflater().inflate(R.layout.waitdialogue, null);
((TextView) view.findViewById(R.id.waitDialogTitle)).setText(R.string.waitTitle);
((TextView) view.findViewById(R.id.waitDialogMessage)).setText(R.string.waitMessage);
waitDialogBuilder.setCancelable(false);
waitDialogBuilder.setView(view);
waitDialog = waitDialogBuilder.create();
final ProgressDialog.Builder timeoutDialogBuilder = new ProgressDialog.Builder(this);
view = this.getLayoutInflater().inflate(R.layout.alertdialogue, null);
((TextView) view.findViewById(R.id.alertDialogTitle)).setText(R.string.timeouttitle);
((TextView) view.findViewById(R.id.alertDialogMessage)).setText(R.string.timeoutmessage);
timeoutDialogBuilder.setCancelable(true);
timeoutDialogBuilder.setView(view);
timeoutDialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
timeoutDialog = timeoutDialogBuilder.create();
final ProgressDialog.Builder errorDialogBuilder = new ProgressDialog.Builder(this);
view = this.getLayoutInflater().inflate(R.layout.alertdialogue, null);
((TextView) view.findViewById(R.id.alertDialogTitle)).setText(R.string.connexionfailtitle);
((TextView) view.findViewById(R.id.alertDialogMessage)).setText(R.string.connexionfailmessage);
errorDialogBuilder.setCancelable(true);
errorDialogBuilder.setView(view);
errorDialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
errorDialog = errorDialogBuilder.create();
final ProgressDialog.Builder connexionerrorDialogBuilder = new ProgressDialog.Builder(this);
view = this.getLayoutInflater().inflate(R.layout.alertdialogue, null);
((TextView) view.findViewById(R.id.alertDialogTitle)).setText(R.string.noconnexiontitle);
((TextView) view.findViewById(R.id.alertDialogMessage)).setText(R.string.noconnexionmessage);
connexionerrorDialogBuilder.setCancelable(true);
connexionerrorDialogBuilder.setView(view);
connexionerrorDialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
connexionerrorDialog = connexionerrorDialogBuilder.create();
}
private String getActTitle(){
return "Forum - " + getResources().getStringArray(R.array.Forums110Title)[ForumActivityItemsSecond.selection];
}
private ArrayList<StringsForAdapterItems> getStringsAdapter() {
ArrayList<StringsForAdapterItems> Strings = new ArrayList<>();
StringsForAdapterItems s;
if(ForumActivity.selection == 1 && ForumActivitySubmenu.selection == 2){
switch (ForumActivityItems.selection){
case 0:
switch (ForumActivityItemsSecond.selection){
case 0:
Connexion.getItemsFeed("https://community.funcraft.net/forums/ameliorations-acceptees.16/index.rss", 2);
break;
case 1:
Connexion.getItemsFeed("https://community.funcraft.net/forums/ameliorations-refusees.17/index.rss", 2);
break;
}
break;
case 1:
switch (ForumActivityItemsSecond.selection){
case 0:
Connexion.getItemsFeed("https://community.funcraft.net/forums/propositions-acceptees.18/index.rss", 2);
break;
case 1:
Connexion.getItemsFeed("https://community.funcraft.net/forums/propositions-refusees.19/index.rss", 2);
break;
}
break;
}
}
for (int i = 0; i < Title.size(); i++) {
s = new StringsForAdapterItems();
s.setTitle(Title.get(i));
s.setSubtitle(Subtitle.get(i));
s.setDates(Dates.get(i));
Strings.add(s);
}
return Strings;
}
} | apache-2.0 |
nezihyigitbasi/presto | presto-hive/src/main/java/com/facebook/presto/hive/HiveClientConfig.java | 42318 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.hive;
import com.facebook.presto.hive.s3.S3FileSystemType;
import com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.net.HostAndPort;
import io.airlift.configuration.Config;
import io.airlift.configuration.ConfigDescription;
import io.airlift.configuration.DefunctConfig;
import io.airlift.configuration.LegacyConfig;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import io.airlift.units.MaxDataSize;
import io.airlift.units.MinDataSize;
import io.airlift.units.MinDuration;
import org.joda.time.DateTimeZone;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static com.facebook.presto.hive.HiveStorageFormat.ORC;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.concurrent.TimeUnit.MINUTES;
@DefunctConfig({
"hive.file-system-cache-ttl",
"hive.max-global-split-iterator-threads",
"hive.max-sort-files-per-bucket",
"hive.bucket-writing",
"hive.optimized-reader.enabled"})
public class HiveClientConfig
{
private String timeZone = TimeZone.getDefault().getID();
private DataSize maxSplitSize = new DataSize(64, MEGABYTE);
private int maxPartitionsPerScan = 100_000;
private int maxOutstandingSplits = 1_000;
private DataSize maxOutstandingSplitsSize = new DataSize(256, MEGABYTE);
private int maxSplitIteratorThreads = 1_000;
private int minPartitionBatchSize = 10;
private int maxPartitionBatchSize = 100;
private int maxInitialSplits = 200;
private int splitLoaderConcurrency = 4;
private DataSize maxInitialSplitSize;
private int domainCompactionThreshold = 100;
private DataSize writerSortBufferSize = new DataSize(64, MEGABYTE);
private boolean forceLocalScheduling;
private boolean recursiveDirWalkerEnabled;
private int maxConcurrentFileRenames = 20;
private int maxConcurrentZeroRowFileCreations = 20;
private boolean allowCorruptWritesForTesting;
private Duration metastoreCacheTtl = new Duration(0, TimeUnit.SECONDS);
private Duration metastoreRefreshInterval = new Duration(0, TimeUnit.SECONDS);
private long metastoreCacheMaximumSize = 10000;
private long perTransactionMetastoreCacheMaximumSize = 1000;
private int maxMetastoreRefreshThreads = 100;
private HostAndPort metastoreSocksProxy;
private Duration metastoreTimeout = new Duration(10, TimeUnit.SECONDS);
private Duration ipcPingInterval = new Duration(10, TimeUnit.SECONDS);
private Duration dfsTimeout = new Duration(60, TimeUnit.SECONDS);
private Duration dfsConnectTimeout = new Duration(500, TimeUnit.MILLISECONDS);
private int dfsConnectMaxRetries = 5;
private boolean verifyChecksum = true;
private String domainSocketPath;
private S3FileSystemType s3FileSystemType = S3FileSystemType.PRESTO;
private HiveStorageFormat hiveStorageFormat = ORC;
private HiveCompressionCodec compressionCodec = HiveCompressionCodec.GZIP;
private boolean respectTableFormat = true;
private boolean immutablePartitions;
private int maxPartitionsPerWriter = 100;
private int maxOpenSortFiles = 50;
private int writeValidationThreads = 16;
private List<String> resourceConfigFiles = ImmutableList.of();
private DataSize textMaxLineLength = new DataSize(100, MEGABYTE);
private boolean useParquetColumnNames;
private boolean failOnCorruptedParquetStatistics = true;
private DataSize parquetMaxReadBlockSize = new DataSize(16, MEGABYTE);
private boolean assumeCanonicalPartitionKeys;
private boolean useOrcColumnNames;
private boolean orcBloomFiltersEnabled;
private double orcDefaultBloomFilterFpp = 0.05;
private DataSize orcMaxMergeDistance = new DataSize(1, MEGABYTE);
private DataSize orcMaxBufferSize = new DataSize(8, MEGABYTE);
private DataSize orcTinyStripeThreshold = new DataSize(8, MEGABYTE);
private DataSize orcStreamBufferSize = new DataSize(8, MEGABYTE);
private DataSize orcMaxReadBlockSize = new DataSize(16, MEGABYTE);
private boolean orcLazyReadSmallRanges = true;
private boolean orcOptimizedWriterEnabled = true;
private double orcWriterValidationPercentage;
private OrcWriteValidationMode orcWriterValidationMode = OrcWriteValidationMode.BOTH;
private boolean rcfileOptimizedWriterEnabled = true;
private boolean rcfileWriterValidate;
private HiveMetastoreAuthenticationType hiveMetastoreAuthenticationType = HiveMetastoreAuthenticationType.NONE;
private HdfsAuthenticationType hdfsAuthenticationType = HdfsAuthenticationType.NONE;
private boolean hdfsImpersonationEnabled;
private boolean hdfsWireEncryptionEnabled;
private boolean skipDeletionForAlter;
private boolean skipTargetCleanupOnRollback;
private boolean bucketExecutionEnabled = true;
private boolean sortedWritingEnabled = true;
private boolean ignoreTableBucketing;
private int maxBucketsForGroupedExecution = 1_000_000;
// TODO: Clean up this gatekeeper config and related code/session property once the roll out is done.
private boolean sortedWriteToTempPathEnabled;
private int sortedWriteTempPathSubdirectoryCount = 10;
private int fileSystemMaxCacheSize = 1000;
private boolean optimizeMismatchedBucketCount;
private boolean writesToNonManagedTablesEnabled;
private boolean createsOfNonManagedTablesEnabled = true;
private boolean tableStatisticsEnabled = true;
private int partitionStatisticsSampleSize = 100;
private boolean ignoreCorruptedStatistics;
private boolean collectColumnStatisticsOnWrite;
private String recordingPath;
private boolean replay;
private Duration recordingDuration = new Duration(0, MINUTES);
private boolean s3SelectPushdownEnabled;
private int s3SelectPushdownMaxConnections = 500;
private boolean isTemporaryStagingDirectoryEnabled = true;
private String temporaryStagingDirectoryPath = "/tmp/presto-${USER}";
private String temporaryTableSchema = "default";
private HiveStorageFormat temporaryTableStorageFormat = ORC;
private HiveCompressionCodec temporaryTableCompressionCodec = HiveCompressionCodec.SNAPPY;
private boolean pushdownFilterEnabled;
public int getMaxInitialSplits()
{
return maxInitialSplits;
}
@Config("hive.max-initial-splits")
public HiveClientConfig setMaxInitialSplits(int maxInitialSplits)
{
this.maxInitialSplits = maxInitialSplits;
return this;
}
public DataSize getMaxInitialSplitSize()
{
if (maxInitialSplitSize == null) {
return new DataSize(maxSplitSize.getValue() / 2, maxSplitSize.getUnit());
}
return maxInitialSplitSize;
}
@Config("hive.max-initial-split-size")
public HiveClientConfig setMaxInitialSplitSize(DataSize maxInitialSplitSize)
{
this.maxInitialSplitSize = maxInitialSplitSize;
return this;
}
@Min(1)
public int getSplitLoaderConcurrency()
{
return splitLoaderConcurrency;
}
@Config("hive.split-loader-concurrency")
public HiveClientConfig setSplitLoaderConcurrency(int splitLoaderConcurrency)
{
this.splitLoaderConcurrency = splitLoaderConcurrency;
return this;
}
@Min(1)
public int getDomainCompactionThreshold()
{
return domainCompactionThreshold;
}
@Config("hive.domain-compaction-threshold")
@ConfigDescription("Maximum ranges to allow in a tuple domain without compacting it")
public HiveClientConfig setDomainCompactionThreshold(int domainCompactionThreshold)
{
this.domainCompactionThreshold = domainCompactionThreshold;
return this;
}
@MinDataSize("1MB")
@MaxDataSize("1GB")
public DataSize getWriterSortBufferSize()
{
return writerSortBufferSize;
}
@Config("hive.writer-sort-buffer-size")
public HiveClientConfig setWriterSortBufferSize(DataSize writerSortBufferSize)
{
this.writerSortBufferSize = writerSortBufferSize;
return this;
}
public boolean isForceLocalScheduling()
{
return forceLocalScheduling;
}
@Config("hive.force-local-scheduling")
public HiveClientConfig setForceLocalScheduling(boolean forceLocalScheduling)
{
this.forceLocalScheduling = forceLocalScheduling;
return this;
}
@Min(1)
public int getMaxConcurrentFileRenames()
{
return maxConcurrentFileRenames;
}
@Config("hive.max-concurrent-file-renames")
public HiveClientConfig setMaxConcurrentFileRenames(int maxConcurrentFileRenames)
{
this.maxConcurrentFileRenames = maxConcurrentFileRenames;
return this;
}
@Min(1)
public int getMaxConcurrentZeroRowFileCreations()
{
return maxConcurrentZeroRowFileCreations;
}
@Config("hive.max-concurrent-zero-row-file-creations")
public HiveClientConfig setMaxConcurrentZeroRowFileCreations(int maxConcurrentZeroRowFileCreations)
{
this.maxConcurrentZeroRowFileCreations = maxConcurrentZeroRowFileCreations;
return this;
}
public boolean getRecursiveDirWalkerEnabled()
{
return recursiveDirWalkerEnabled;
}
@Config("hive.recursive-directories")
public HiveClientConfig setRecursiveDirWalkerEnabled(boolean recursiveDirWalkerEnabled)
{
this.recursiveDirWalkerEnabled = recursiveDirWalkerEnabled;
return this;
}
public DateTimeZone getDateTimeZone()
{
return DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone));
}
@NotNull
public String getTimeZone()
{
return timeZone;
}
@Config("hive.time-zone")
public HiveClientConfig setTimeZone(String id)
{
this.timeZone = (id != null) ? id : TimeZone.getDefault().getID();
return this;
}
@NotNull
public DataSize getMaxSplitSize()
{
return maxSplitSize;
}
@Config("hive.max-split-size")
public HiveClientConfig setMaxSplitSize(DataSize maxSplitSize)
{
this.maxSplitSize = maxSplitSize;
return this;
}
@Min(1)
public int getMaxPartitionsPerScan()
{
return maxPartitionsPerScan;
}
@Config("hive.max-partitions-per-scan")
@ConfigDescription("Maximum allowed partitions for a single table scan")
public HiveClientConfig setMaxPartitionsPerScan(int maxPartitionsPerScan)
{
this.maxPartitionsPerScan = maxPartitionsPerScan;
return this;
}
@Min(1)
public int getMaxOutstandingSplits()
{
return maxOutstandingSplits;
}
@Config("hive.max-outstanding-splits")
@ConfigDescription("Target number of buffered splits for each table scan in a query, before the scheduler tries to pause itself")
public HiveClientConfig setMaxOutstandingSplits(int maxOutstandingSplits)
{
this.maxOutstandingSplits = maxOutstandingSplits;
return this;
}
@MinDataSize("1MB")
public DataSize getMaxOutstandingSplitsSize()
{
return maxOutstandingSplitsSize;
}
@Config("hive.max-outstanding-splits-size")
@ConfigDescription("Maximum amount of memory allowed for split buffering for each table scan in a query, before the query is failed")
public HiveClientConfig setMaxOutstandingSplitsSize(DataSize maxOutstandingSplits)
{
this.maxOutstandingSplitsSize = maxOutstandingSplits;
return this;
}
@Min(1)
public int getMaxSplitIteratorThreads()
{
return maxSplitIteratorThreads;
}
@Config("hive.max-split-iterator-threads")
public HiveClientConfig setMaxSplitIteratorThreads(int maxSplitIteratorThreads)
{
this.maxSplitIteratorThreads = maxSplitIteratorThreads;
return this;
}
@Deprecated
public boolean getAllowCorruptWritesForTesting()
{
return allowCorruptWritesForTesting;
}
@Deprecated
@Config("hive.allow-corrupt-writes-for-testing")
@ConfigDescription("Allow Hive connector to write data even when data will likely be corrupt")
public HiveClientConfig setAllowCorruptWritesForTesting(boolean allowCorruptWritesForTesting)
{
this.allowCorruptWritesForTesting = allowCorruptWritesForTesting;
return this;
}
@NotNull
public Duration getMetastoreCacheTtl()
{
return metastoreCacheTtl;
}
@MinDuration("0ms")
@Config("hive.metastore-cache-ttl")
public HiveClientConfig setMetastoreCacheTtl(Duration metastoreCacheTtl)
{
this.metastoreCacheTtl = metastoreCacheTtl;
return this;
}
@NotNull
public Duration getMetastoreRefreshInterval()
{
return metastoreRefreshInterval;
}
@MinDuration("1ms")
@Config("hive.metastore-refresh-interval")
public HiveClientConfig setMetastoreRefreshInterval(Duration metastoreRefreshInterval)
{
this.metastoreRefreshInterval = metastoreRefreshInterval;
return this;
}
public long getMetastoreCacheMaximumSize()
{
return metastoreCacheMaximumSize;
}
@Min(1)
@Config("hive.metastore-cache-maximum-size")
public HiveClientConfig setMetastoreCacheMaximumSize(long metastoreCacheMaximumSize)
{
this.metastoreCacheMaximumSize = metastoreCacheMaximumSize;
return this;
}
public long getPerTransactionMetastoreCacheMaximumSize()
{
return perTransactionMetastoreCacheMaximumSize;
}
@Min(1)
@Config("hive.per-transaction-metastore-cache-maximum-size")
public HiveClientConfig setPerTransactionMetastoreCacheMaximumSize(long perTransactionMetastoreCacheMaximumSize)
{
this.perTransactionMetastoreCacheMaximumSize = perTransactionMetastoreCacheMaximumSize;
return this;
}
@Min(1)
public int getMaxMetastoreRefreshThreads()
{
return maxMetastoreRefreshThreads;
}
@Config("hive.metastore-refresh-max-threads")
public HiveClientConfig setMaxMetastoreRefreshThreads(int maxMetastoreRefreshThreads)
{
this.maxMetastoreRefreshThreads = maxMetastoreRefreshThreads;
return this;
}
public HostAndPort getMetastoreSocksProxy()
{
return metastoreSocksProxy;
}
@Config("hive.metastore.thrift.client.socks-proxy")
public HiveClientConfig setMetastoreSocksProxy(HostAndPort metastoreSocksProxy)
{
this.metastoreSocksProxy = metastoreSocksProxy;
return this;
}
@NotNull
public Duration getMetastoreTimeout()
{
return metastoreTimeout;
}
@Config("hive.metastore-timeout")
public HiveClientConfig setMetastoreTimeout(Duration metastoreTimeout)
{
this.metastoreTimeout = metastoreTimeout;
return this;
}
@Min(1)
public int getMinPartitionBatchSize()
{
return minPartitionBatchSize;
}
@Config("hive.metastore.partition-batch-size.min")
public HiveClientConfig setMinPartitionBatchSize(int minPartitionBatchSize)
{
this.minPartitionBatchSize = minPartitionBatchSize;
return this;
}
@Min(1)
public int getMaxPartitionBatchSize()
{
return maxPartitionBatchSize;
}
@Config("hive.metastore.partition-batch-size.max")
public HiveClientConfig setMaxPartitionBatchSize(int maxPartitionBatchSize)
{
this.maxPartitionBatchSize = maxPartitionBatchSize;
return this;
}
@NotNull
public List<String> getResourceConfigFiles()
{
return resourceConfigFiles;
}
@Config("hive.config.resources")
public HiveClientConfig setResourceConfigFiles(String files)
{
this.resourceConfigFiles = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(files);
return this;
}
public HiveClientConfig setResourceConfigFiles(List<String> files)
{
this.resourceConfigFiles = ImmutableList.copyOf(files);
return this;
}
@NotNull
@MinDuration("1ms")
public Duration getIpcPingInterval()
{
return ipcPingInterval;
}
@Config("hive.dfs.ipc-ping-interval")
public HiveClientConfig setIpcPingInterval(Duration pingInterval)
{
this.ipcPingInterval = pingInterval;
return this;
}
@NotNull
@MinDuration("1ms")
public Duration getDfsTimeout()
{
return dfsTimeout;
}
@Config("hive.dfs-timeout")
public HiveClientConfig setDfsTimeout(Duration dfsTimeout)
{
this.dfsTimeout = dfsTimeout;
return this;
}
@MinDuration("1ms")
@NotNull
public Duration getDfsConnectTimeout()
{
return dfsConnectTimeout;
}
@Config("hive.dfs.connect.timeout")
public HiveClientConfig setDfsConnectTimeout(Duration dfsConnectTimeout)
{
this.dfsConnectTimeout = dfsConnectTimeout;
return this;
}
@Min(0)
public int getDfsConnectMaxRetries()
{
return dfsConnectMaxRetries;
}
@Config("hive.dfs.connect.max-retries")
public HiveClientConfig setDfsConnectMaxRetries(int dfsConnectMaxRetries)
{
this.dfsConnectMaxRetries = dfsConnectMaxRetries;
return this;
}
public HiveStorageFormat getHiveStorageFormat()
{
return hiveStorageFormat;
}
@Config("hive.storage-format")
public HiveClientConfig setHiveStorageFormat(HiveStorageFormat hiveStorageFormat)
{
this.hiveStorageFormat = hiveStorageFormat;
return this;
}
public HiveCompressionCodec getCompressionCodec()
{
return compressionCodec;
}
@Config("hive.compression-codec")
public HiveClientConfig setCompressionCodec(HiveCompressionCodec compressionCodec)
{
this.compressionCodec = compressionCodec;
return this;
}
public boolean isRespectTableFormat()
{
return respectTableFormat;
}
@Config("hive.respect-table-format")
@ConfigDescription("Should new partitions be written using the existing table format or the default Presto format")
public HiveClientConfig setRespectTableFormat(boolean respectTableFormat)
{
this.respectTableFormat = respectTableFormat;
return this;
}
public boolean isImmutablePartitions()
{
return immutablePartitions;
}
@Config("hive.immutable-partitions")
@ConfigDescription("Can new data be inserted into existing partitions or existing unpartitioned tables")
public HiveClientConfig setImmutablePartitions(boolean immutablePartitions)
{
this.immutablePartitions = immutablePartitions;
return this;
}
@Min(1)
public int getMaxPartitionsPerWriter()
{
return maxPartitionsPerWriter;
}
@Config("hive.max-partitions-per-writers")
@ConfigDescription("Maximum number of partitions per writer")
public HiveClientConfig setMaxPartitionsPerWriter(int maxPartitionsPerWriter)
{
this.maxPartitionsPerWriter = maxPartitionsPerWriter;
return this;
}
@Min(2)
@Max(1000)
public int getMaxOpenSortFiles()
{
return maxOpenSortFiles;
}
@Config("hive.max-open-sort-files")
@ConfigDescription("Maximum number of writer temporary files to read in one pass")
public HiveClientConfig setMaxOpenSortFiles(int maxOpenSortFiles)
{
this.maxOpenSortFiles = maxOpenSortFiles;
return this;
}
public int getWriteValidationThreads()
{
return writeValidationThreads;
}
@Config("hive.write-validation-threads")
@ConfigDescription("Number of threads used for verifying data after a write")
public HiveClientConfig setWriteValidationThreads(int writeValidationThreads)
{
this.writeValidationThreads = writeValidationThreads;
return this;
}
public String getDomainSocketPath()
{
return domainSocketPath;
}
@Config("hive.dfs.domain-socket-path")
@LegacyConfig("dfs.domain-socket-path")
public HiveClientConfig setDomainSocketPath(String domainSocketPath)
{
this.domainSocketPath = domainSocketPath;
return this;
}
@NotNull
public S3FileSystemType getS3FileSystemType()
{
return s3FileSystemType;
}
@Config("hive.s3-file-system-type")
public HiveClientConfig setS3FileSystemType(S3FileSystemType s3FileSystemType)
{
this.s3FileSystemType = s3FileSystemType;
return this;
}
public boolean isVerifyChecksum()
{
return verifyChecksum;
}
@Config("hive.dfs.verify-checksum")
public HiveClientConfig setVerifyChecksum(boolean verifyChecksum)
{
this.verifyChecksum = verifyChecksum;
return this;
}
public boolean isUseOrcColumnNames()
{
return useOrcColumnNames;
}
@Config("hive.orc.use-column-names")
@ConfigDescription("Access ORC columns using names from the file")
public HiveClientConfig setUseOrcColumnNames(boolean useOrcColumnNames)
{
this.useOrcColumnNames = useOrcColumnNames;
return this;
}
@NotNull
public DataSize getOrcMaxMergeDistance()
{
return orcMaxMergeDistance;
}
@Config("hive.orc.max-merge-distance")
public HiveClientConfig setOrcMaxMergeDistance(DataSize orcMaxMergeDistance)
{
this.orcMaxMergeDistance = orcMaxMergeDistance;
return this;
}
@NotNull
public DataSize getOrcMaxBufferSize()
{
return orcMaxBufferSize;
}
@Config("hive.orc.max-buffer-size")
public HiveClientConfig setOrcMaxBufferSize(DataSize orcMaxBufferSize)
{
this.orcMaxBufferSize = orcMaxBufferSize;
return this;
}
@NotNull
public DataSize getOrcStreamBufferSize()
{
return orcStreamBufferSize;
}
@Config("hive.orc.stream-buffer-size")
public HiveClientConfig setOrcStreamBufferSize(DataSize orcStreamBufferSize)
{
this.orcStreamBufferSize = orcStreamBufferSize;
return this;
}
@NotNull
public DataSize getOrcTinyStripeThreshold()
{
return orcTinyStripeThreshold;
}
@Config("hive.orc.tiny-stripe-threshold")
public HiveClientConfig setOrcTinyStripeThreshold(DataSize orcTinyStripeThreshold)
{
this.orcTinyStripeThreshold = orcTinyStripeThreshold;
return this;
}
@NotNull
public DataSize getOrcMaxReadBlockSize()
{
return orcMaxReadBlockSize;
}
@Config("hive.orc.max-read-block-size")
public HiveClientConfig setOrcMaxReadBlockSize(DataSize orcMaxReadBlockSize)
{
this.orcMaxReadBlockSize = orcMaxReadBlockSize;
return this;
}
@Deprecated
public boolean isOrcLazyReadSmallRanges()
{
return orcLazyReadSmallRanges;
}
// TODO remove config option once efficacy is proven
@Deprecated
@Config("hive.orc.lazy-read-small-ranges")
@ConfigDescription("ORC read small disk ranges lazily")
public HiveClientConfig setOrcLazyReadSmallRanges(boolean orcLazyReadSmallRanges)
{
this.orcLazyReadSmallRanges = orcLazyReadSmallRanges;
return this;
}
public boolean isOrcBloomFiltersEnabled()
{
return orcBloomFiltersEnabled;
}
@Config("hive.orc.bloom-filters.enabled")
public HiveClientConfig setOrcBloomFiltersEnabled(boolean orcBloomFiltersEnabled)
{
this.orcBloomFiltersEnabled = orcBloomFiltersEnabled;
return this;
}
public double getOrcDefaultBloomFilterFpp()
{
return orcDefaultBloomFilterFpp;
}
@Config("hive.orc.default-bloom-filter-fpp")
@ConfigDescription("ORC Bloom filter false positive probability")
public HiveClientConfig setOrcDefaultBloomFilterFpp(double orcDefaultBloomFilterFpp)
{
this.orcDefaultBloomFilterFpp = orcDefaultBloomFilterFpp;
return this;
}
@Deprecated
public boolean isOrcOptimizedWriterEnabled()
{
return orcOptimizedWriterEnabled;
}
@Deprecated
@Config("hive.orc.optimized-writer.enabled")
public HiveClientConfig setOrcOptimizedWriterEnabled(boolean orcOptimizedWriterEnabled)
{
this.orcOptimizedWriterEnabled = orcOptimizedWriterEnabled;
return this;
}
@DecimalMin("0.0")
@DecimalMax("100.0")
public double getOrcWriterValidationPercentage()
{
return orcWriterValidationPercentage;
}
@Config("hive.orc.writer.validation-percentage")
@ConfigDescription("Percentage of ORC files to validate after write by re-reading the whole file")
public HiveClientConfig setOrcWriterValidationPercentage(double orcWriterValidationPercentage)
{
this.orcWriterValidationPercentage = orcWriterValidationPercentage;
return this;
}
@NotNull
public OrcWriteValidationMode getOrcWriterValidationMode()
{
return orcWriterValidationMode;
}
@Config("hive.orc.writer.validation-mode")
@ConfigDescription("Level of detail in ORC validation. Lower levels require more memory.")
public HiveClientConfig setOrcWriterValidationMode(OrcWriteValidationMode orcWriterValidationMode)
{
this.orcWriterValidationMode = orcWriterValidationMode;
return this;
}
@Deprecated
public boolean isRcfileOptimizedWriterEnabled()
{
return rcfileOptimizedWriterEnabled;
}
@Deprecated
@Config("hive.rcfile-optimized-writer.enabled")
public HiveClientConfig setRcfileOptimizedWriterEnabled(boolean rcfileOptimizedWriterEnabled)
{
this.rcfileOptimizedWriterEnabled = rcfileOptimizedWriterEnabled;
return this;
}
public boolean isRcfileWriterValidate()
{
return rcfileWriterValidate;
}
@Config("hive.rcfile.writer.validate")
@ConfigDescription("Validate RCFile after write by re-reading the whole file")
public HiveClientConfig setRcfileWriterValidate(boolean rcfileWriterValidate)
{
this.rcfileWriterValidate = rcfileWriterValidate;
return this;
}
public boolean isAssumeCanonicalPartitionKeys()
{
return assumeCanonicalPartitionKeys;
}
@Config("hive.assume-canonical-partition-keys")
public HiveClientConfig setAssumeCanonicalPartitionKeys(boolean assumeCanonicalPartitionKeys)
{
this.assumeCanonicalPartitionKeys = assumeCanonicalPartitionKeys;
return this;
}
@MinDataSize("1B")
@MaxDataSize("1GB")
@NotNull
public DataSize getTextMaxLineLength()
{
return textMaxLineLength;
}
@Config("hive.text.max-line-length")
@ConfigDescription("Maximum line length for text files")
public HiveClientConfig setTextMaxLineLength(DataSize textMaxLineLength)
{
this.textMaxLineLength = textMaxLineLength;
return this;
}
public boolean isUseParquetColumnNames()
{
return useParquetColumnNames;
}
@Config("hive.parquet.use-column-names")
@ConfigDescription("Access Parquet columns using names from the file")
public HiveClientConfig setUseParquetColumnNames(boolean useParquetColumnNames)
{
this.useParquetColumnNames = useParquetColumnNames;
return this;
}
public boolean isFailOnCorruptedParquetStatistics()
{
return failOnCorruptedParquetStatistics;
}
@Config("hive.parquet.fail-on-corrupted-statistics")
@ConfigDescription("Fail when scanning Parquet files with corrupted statistics")
public HiveClientConfig setFailOnCorruptedParquetStatistics(boolean failOnCorruptedParquetStatistics)
{
this.failOnCorruptedParquetStatistics = failOnCorruptedParquetStatistics;
return this;
}
@NotNull
public DataSize getParquetMaxReadBlockSize()
{
return parquetMaxReadBlockSize;
}
@Config("hive.parquet.max-read-block-size")
public HiveClientConfig setParquetMaxReadBlockSize(DataSize parquetMaxReadBlockSize)
{
this.parquetMaxReadBlockSize = parquetMaxReadBlockSize;
return this;
}
@Deprecated
public boolean isOptimizeMismatchedBucketCount()
{
return optimizeMismatchedBucketCount;
}
@Deprecated
@Config("hive.optimize-mismatched-bucket-count")
public HiveClientConfig setOptimizeMismatchedBucketCount(boolean optimizeMismatchedBucketCount)
{
this.optimizeMismatchedBucketCount = optimizeMismatchedBucketCount;
return this;
}
public enum HiveMetastoreAuthenticationType
{
NONE,
KERBEROS
}
@NotNull
public HiveMetastoreAuthenticationType getHiveMetastoreAuthenticationType()
{
return hiveMetastoreAuthenticationType;
}
@Config("hive.metastore.authentication.type")
@ConfigDescription("Hive Metastore authentication type")
public HiveClientConfig setHiveMetastoreAuthenticationType(HiveMetastoreAuthenticationType hiveMetastoreAuthenticationType)
{
this.hiveMetastoreAuthenticationType = hiveMetastoreAuthenticationType;
return this;
}
public enum HdfsAuthenticationType
{
NONE,
KERBEROS,
}
@NotNull
public HdfsAuthenticationType getHdfsAuthenticationType()
{
return hdfsAuthenticationType;
}
@Config("hive.hdfs.authentication.type")
@ConfigDescription("HDFS authentication type")
public HiveClientConfig setHdfsAuthenticationType(HdfsAuthenticationType hdfsAuthenticationType)
{
this.hdfsAuthenticationType = hdfsAuthenticationType;
return this;
}
public boolean isHdfsImpersonationEnabled()
{
return hdfsImpersonationEnabled;
}
@Config("hive.hdfs.impersonation.enabled")
@ConfigDescription("Should Presto user be impersonated when communicating with HDFS")
public HiveClientConfig setHdfsImpersonationEnabled(boolean hdfsImpersonationEnabled)
{
this.hdfsImpersonationEnabled = hdfsImpersonationEnabled;
return this;
}
public boolean isHdfsWireEncryptionEnabled()
{
return hdfsWireEncryptionEnabled;
}
@Config("hive.hdfs.wire-encryption.enabled")
@ConfigDescription("Should be turned on when HDFS wire encryption is enabled")
public HiveClientConfig setHdfsWireEncryptionEnabled(boolean hdfsWireEncryptionEnabled)
{
this.hdfsWireEncryptionEnabled = hdfsWireEncryptionEnabled;
return this;
}
public boolean isSkipDeletionForAlter()
{
return skipDeletionForAlter;
}
@Config("hive.skip-deletion-for-alter")
@ConfigDescription("Skip deletion of old partition data when a partition is deleted and then inserted in the same transaction")
public HiveClientConfig setSkipDeletionForAlter(boolean skipDeletionForAlter)
{
this.skipDeletionForAlter = skipDeletionForAlter;
return this;
}
public boolean isSkipTargetCleanupOnRollback()
{
return skipTargetCleanupOnRollback;
}
@Config("hive.skip-target-cleanup-on-rollback")
@ConfigDescription("Skip deletion of target directories when a metastore operation fails and the write mode is DIRECT_TO_TARGET_NEW_DIRECTORY")
public HiveClientConfig setSkipTargetCleanupOnRollback(boolean skipTargetCleanupOnRollback)
{
this.skipTargetCleanupOnRollback = skipTargetCleanupOnRollback;
return this;
}
public boolean isBucketExecutionEnabled()
{
return bucketExecutionEnabled;
}
@Config("hive.bucket-execution")
@ConfigDescription("Enable bucket-aware execution: only use a single worker per bucket")
public HiveClientConfig setBucketExecutionEnabled(boolean bucketExecutionEnabled)
{
this.bucketExecutionEnabled = bucketExecutionEnabled;
return this;
}
public boolean isSortedWritingEnabled()
{
return sortedWritingEnabled;
}
@Config("hive.sorted-writing")
@ConfigDescription("Enable writing to bucketed sorted tables")
public HiveClientConfig setSortedWritingEnabled(boolean sortedWritingEnabled)
{
this.sortedWritingEnabled = sortedWritingEnabled;
return this;
}
@Config("hive.ignore-table-bucketing")
@ConfigDescription("Ignore table bucketing to allow reading from unbucketed partitions")
public HiveClientConfig setIgnoreTableBucketing(boolean ignoreTableBucketing)
{
this.ignoreTableBucketing = ignoreTableBucketing;
return this;
}
public boolean isIgnoreTableBucketing()
{
return ignoreTableBucketing;
}
@Config("hive.max-buckets-for-grouped-execution")
@ConfigDescription("Maximum number of buckets to run with grouped execution")
public HiveClientConfig setMaxBucketsForGroupedExecution(int maxBucketsForGroupedExecution)
{
this.maxBucketsForGroupedExecution = maxBucketsForGroupedExecution;
return this;
}
public int getMaxBucketsForGroupedExecution()
{
return maxBucketsForGroupedExecution;
}
@Config("hive.sorted-write-to-temp-path-enabled")
@ConfigDescription("Enable writing temp files to temp path when writing to bucketed sorted tables")
public HiveClientConfig setSortedWriteToTempPathEnabled(boolean sortedWriteToTempPathEnabled)
{
this.sortedWriteToTempPathEnabled = sortedWriteToTempPathEnabled;
return this;
}
public boolean isSortedWriteToTempPathEnabled()
{
return sortedWriteToTempPathEnabled;
}
@Config("hive.sorted-write-temp-path-subdirectory-count")
@ConfigDescription("Number of directories per partition for temp files generated by writing sorted table")
public HiveClientConfig setSortedWriteTempPathSubdirectoryCount(int sortedWriteTempPathSubdirectoryCount)
{
this.sortedWriteTempPathSubdirectoryCount = sortedWriteTempPathSubdirectoryCount;
return this;
}
public int getSortedWriteTempPathSubdirectoryCount()
{
return sortedWriteTempPathSubdirectoryCount;
}
public int getFileSystemMaxCacheSize()
{
return fileSystemMaxCacheSize;
}
@Config("hive.fs.cache.max-size")
@ConfigDescription("Hadoop FileSystem cache size")
public HiveClientConfig setFileSystemMaxCacheSize(int fileSystemMaxCacheSize)
{
this.fileSystemMaxCacheSize = fileSystemMaxCacheSize;
return this;
}
public boolean getWritesToNonManagedTablesEnabled()
{
return writesToNonManagedTablesEnabled;
}
@Config("hive.non-managed-table-writes-enabled")
@ConfigDescription("Enable writes to non-managed (external) tables")
public HiveClientConfig setWritesToNonManagedTablesEnabled(boolean writesToNonManagedTablesEnabled)
{
this.writesToNonManagedTablesEnabled = writesToNonManagedTablesEnabled;
return this;
}
public boolean getCreatesOfNonManagedTablesEnabled()
{
return createsOfNonManagedTablesEnabled;
}
@Config("hive.non-managed-table-creates-enabled")
@ConfigDescription("Enable non-managed (external) table creates")
public HiveClientConfig setCreatesOfNonManagedTablesEnabled(boolean createsOfNonManagedTablesEnabled)
{
this.createsOfNonManagedTablesEnabled = createsOfNonManagedTablesEnabled;
return this;
}
public boolean isTableStatisticsEnabled()
{
return tableStatisticsEnabled;
}
@Config("hive.table-statistics-enabled")
@ConfigDescription("Enable use of table statistics")
public HiveClientConfig setTableStatisticsEnabled(boolean tableStatisticsEnabled)
{
this.tableStatisticsEnabled = tableStatisticsEnabled;
return this;
}
@Min(1)
public int getPartitionStatisticsSampleSize()
{
return partitionStatisticsSampleSize;
}
@Config("hive.partition-statistics-sample-size")
@ConfigDescription("Maximum sample size of the partitions column statistics")
public HiveClientConfig setPartitionStatisticsSampleSize(int partitionStatisticsSampleSize)
{
this.partitionStatisticsSampleSize = partitionStatisticsSampleSize;
return this;
}
public boolean isIgnoreCorruptedStatistics()
{
return ignoreCorruptedStatistics;
}
@Config("hive.ignore-corrupted-statistics")
@ConfigDescription("Ignore corrupted statistics rather than failing")
public HiveClientConfig setIgnoreCorruptedStatistics(boolean ignoreCorruptedStatistics)
{
this.ignoreCorruptedStatistics = ignoreCorruptedStatistics;
return this;
}
public boolean isCollectColumnStatisticsOnWrite()
{
return collectColumnStatisticsOnWrite;
}
@Config("hive.collect-column-statistics-on-write")
@ConfigDescription("Enables automatic column level statistics collection on write")
public HiveClientConfig setCollectColumnStatisticsOnWrite(boolean collectColumnStatisticsOnWrite)
{
this.collectColumnStatisticsOnWrite = collectColumnStatisticsOnWrite;
return this;
}
public String getRecordingPath()
{
return recordingPath;
}
@Config("hive.metastore-recording-path")
public HiveClientConfig setRecordingPath(String recordingPath)
{
this.recordingPath = recordingPath;
return this;
}
public boolean isReplay()
{
return replay;
}
@Config("hive.replay-metastore-recording")
public HiveClientConfig setReplay(boolean replay)
{
this.replay = replay;
return this;
}
@NotNull
public Duration getRecordingDuration()
{
return recordingDuration;
}
@Config("hive.metastore-recoding-duration")
public HiveClientConfig setRecordingDuration(Duration recordingDuration)
{
this.recordingDuration = recordingDuration;
return this;
}
public boolean isS3SelectPushdownEnabled()
{
return s3SelectPushdownEnabled;
}
@Config("hive.s3select-pushdown.enabled")
@ConfigDescription("Enable query pushdown to AWS S3 Select service")
public HiveClientConfig setS3SelectPushdownEnabled(boolean s3SelectPushdownEnabled)
{
this.s3SelectPushdownEnabled = s3SelectPushdownEnabled;
return this;
}
@Min(1)
public int getS3SelectPushdownMaxConnections()
{
return s3SelectPushdownMaxConnections;
}
@Config("hive.s3select-pushdown.max-connections")
public HiveClientConfig setS3SelectPushdownMaxConnections(int s3SelectPushdownMaxConnections)
{
this.s3SelectPushdownMaxConnections = s3SelectPushdownMaxConnections;
return this;
}
public boolean isTemporaryStagingDirectoryEnabled()
{
return isTemporaryStagingDirectoryEnabled;
}
@Config("hive.temporary-staging-directory-enabled")
@ConfigDescription("Should use (if possible) temporary staging directory for write operations")
public HiveClientConfig setTemporaryStagingDirectoryEnabled(boolean temporaryStagingDirectoryEnabled)
{
this.isTemporaryStagingDirectoryEnabled = temporaryStagingDirectoryEnabled;
return this;
}
@NotNull
public String getTemporaryStagingDirectoryPath()
{
return temporaryStagingDirectoryPath;
}
@Config("hive.temporary-staging-directory-path")
@ConfigDescription("Location of temporary staging directory for write operations. Use ${USER} placeholder to use different location for each user.")
public HiveClientConfig setTemporaryStagingDirectoryPath(String temporaryStagingDirectoryPath)
{
this.temporaryStagingDirectoryPath = temporaryStagingDirectoryPath;
return this;
}
@NotNull
public String getTemporaryTableSchema()
{
return temporaryTableSchema;
}
@Config("hive.temporary-table-schema")
public HiveClientConfig setTemporaryTableSchema(String temporaryTableSchema)
{
this.temporaryTableSchema = temporaryTableSchema;
return this;
}
@NotNull
public HiveStorageFormat getTemporaryTableStorageFormat()
{
return temporaryTableStorageFormat;
}
@Config("hive.temporary-table-storage-format")
public HiveClientConfig setTemporaryTableStorageFormat(HiveStorageFormat temporaryTableStorageFormat)
{
this.temporaryTableStorageFormat = temporaryTableStorageFormat;
return this;
}
@NotNull
public HiveCompressionCodec getTemporaryTableCompressionCodec()
{
return temporaryTableCompressionCodec;
}
@Config("hive.temporary-table-compression-codec")
public HiveClientConfig setTemporaryTableCompressionCodec(HiveCompressionCodec temporaryTableCompressionCodec)
{
this.temporaryTableCompressionCodec = temporaryTableCompressionCodec;
return this;
}
public boolean isPushdownFilterEnabled()
{
return pushdownFilterEnabled;
}
@Config("hive.pushdown-filter-enabled")
@ConfigDescription("Experimental: enable complex filter pushdown")
public HiveClientConfig setPushdownFilterEnabled(boolean pushdownFilterEnabled)
{
this.pushdownFilterEnabled = pushdownFilterEnabled;
return this;
}
}
| apache-2.0 |
PaulWay/insights-core | insights/parsers/multipath_conf.py | 4720 | """
MultipathConf - file ``/etc/multipath.conf``
============================================
The main class is the MultipathConf class, which reads the multipath daemon's
``/etc/multipath.conf`` configuration file. This is in a pseudo-JSON format.
The ``multipath`` parser function is deprecated and should not be used.
"""
from insights.contrib import pyparsing as p
from insights import parser, Parser, LegacyItemAccess
@parser("multipath.conf")
class MultipathConf(Parser, LegacyItemAccess):
"""
Return a dict where the keys are the name of sections in multipath
configuraion file. If there are subsections, the value is a list of
dictionaries with parameters as key and value. Otherwise the value is
just a single dictionary.
Configuration File Example::
defaults {
path_selector "round-robin 0"
user_friendly_names yes
}
multipaths {
multipath {
alias yellow
path_grouping_policy multibus
}
multipath {
wwid 1DEC_____321816758474
alias red
}
}
devices {
device {
path_selector "round-robin 0"
no_path_retry queue
}
device {
vendor 1DEC_____321816758474
path_grouping_policy red
}
}
blacklist {
wwid 26353900f02796769
devnode "^hd[a-z]"
}
Parse Result::
data = {
"blacklist": {
"devnode": "^hd[a-z]",
"wwid": "26353900f02796769"
},
"devices": [
{
"path_selector": "round-robin 0",
"no_path_retry": "queue"
},
{
"path_grouping_policy": "red",
"vendor": "1DEC_____321816758474"
}
],
"defaults": {
"path_selector": "round-robin 0",
"user_friendly_names": "yes"
},
"multipaths": [
{
"alias": "yellow",
"path_grouping_policy": "multibus"
},
{
"alias": "red",
"wwid": "1DEC_____321816758474"
}
]
}
Examples:
>>> conf = shared[MultipathConf]
>>> conf.data['blacklist']['devnode'] # Access via data property
'^hd[a-z]'
>>> conf['defaults']['user_friendly_names'] # Pseudo-dict access
'yes'
>>> len(conf['multipaths'])
2
>>> conf['multipaths'][0]['alias']
'yellow'
"""
@classmethod
def _create_parser(cls):
"""
Need to check the specific symbol "/" in attr_value part as well.
I checked some multipath configuraion files from the sosreport and got
although there are some more specific symbols like "-%", it is enclosed
in double quotes and will be accepted. Furthermore, I also checked the
source code of "device-mapper-multipath" and got if the attr_value in
"multipath.conf" include a "whitespace", it must be enclosed in double
quotation marks. So, we could just add one more specific symbol "/" to
check.
----------------------------------------------------------
udev_dir /dev
getuid_callout "/sbin/scsi_id -g -u -s /block/%n"
----------------------------------------------------------
"""
section_name = p.Word(p.alphas + "_")
attr_name = attr_value = p.Word(p.alphanums + "_/")
LBRACE, RBRACE = map(p.Suppress, "{}")
attr = p.Group(attr_name + (attr_value | p.quotedString.setParseAction(p.removeQuotes)))
attr_list = p.Dict(p.ZeroOrMore(attr))
simple_section = p.Group(section_name + LBRACE + attr_list + RBRACE)
complex_section = p.Group(section_name + LBRACE + p.OneOrMore(simple_section) + RBRACE)
simple_or_complex = p.Dict(simple_section | complex_section)
my_conf = p.Group(p.ZeroOrMore(simple_or_complex))
my_conf.ignore("#" + p.restOfLine)
return my_conf
def parse_content(self, content):
self.data = MultipathConf._create_parser().parseString("\n".join(content))[0].asDict()
@parser("multipath.conf")
def multipath(context):
# This mapper is deprecated and will be removed in the future. Do not use.
return MultipathConf(context).data
| apache-2.0 |
flier/zipkin-cpp | include/zipkin.hpp | 250 | #pragma once
#include "Config.h"
#include "Version.h"
#include "Span.h"
#include "Tracer.h"
#include "Propagation.h"
#include "Collector.h"
#include "KafkaCollector.h"
#ifdef WITH_CURL
#include "HttpCollector.h"
#endif
#include "ScribeCollector.h" | apache-2.0 |
wolvesled/JavaBeginnerStudy | DynShapes.java | 3184 | // Use dynamic method dispatch.
// A class for two-dimensional objects.
class TwoDShape {
private double width; // these are
private double height; // now private
private String name;
// A default constructor.
TwoDShape() {
width = height = 0.0;
name = "null";
}
// Parameterized constructor.
TwoDShape(double w, double h, String n) {
width = w;
height = h;
name = n;
}
// Construct object with equal width and height.
TwoDShape(double x, String n) {
width = height = x;
name = n;
}
// Construct an object from an object.
TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
// Accessor methods for width and height.
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
void setHeight(double h) { height = h; }
String getName() { return name; }
void showDim() {
System.out.println("Width and height are " + width + " and " + height);
}
double area() {
System.out.println("area() must be overriden");
return 0.0;
}
}
// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
private String style;
// A default constructor.
Triangle() {
super();
style = "null";
}
//Constructor
Triangle(String s, double w, double h) {
super(w, h, "triangle"); // call superclass constructor
style = s;
}
// Construct an isoceles triangle.
Triangle(double x) {
super(x, "triangle"); // call superclass constructor
style = "isosceles";
}
// Construct an object from an object.
Triangle(Triangle ob) {
super(ob); // pass object to TwoDShape constructor
style = ob.style;
}
// Override area() for Triangle.
double area () {
return getWidth() * getHeight() / 2;
}
void showStyle() {
System.out.println("Triangle is " + style);
}
}
// A subclass of TwoDShape for rectangles.
class Rectangle extends TwoDShape {
// A default constructor.
Rectangle() {
super();
}
// Constructor for Rectangle.
Rectangle(double w, double h) {
super(w, h, "rectangle"); // call superclass constructor
}
// Construct a square.
Rectangle(double x) {
super(x, "rectangle"); // call superclass constructor
}
// Construct an object from an object.
Rectangle(Rectangle ob) {
super(ob); // pass object to TwoDShape constructor
}
boolean isSquare() {
if(getWidth() == getHeight()) return true;
return false;
}
// Override area() for Rectangle.
double area() {
return getWidth() * getHeight();
}
}
class DynShapes {
public static void main(String args[]) {
TwoDShape shapes[] = new TwoDShape[5];
shapes[0] = new Triangle("right", 8.0, 12.0);
shapes[1] = new Rectangle(10);
shapes[2] = new Rectangle(10, 4);
shapes[3] = new Triangle(7.0);
shapes[4] = new TwoDShape(10, 20, "generic");
for(int i=0; i < shapes.length; i++) {
System.out.println("object is " + shapes[i].getName());
System.out.println("Area is " + shapes[i].area());
System.out.println();
}
}
}
| apache-2.0 |
davidtsadler/ebay-sdk-php | src/Trading/Enums/BalanceCodeType.php | 340 | <?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Trading\Enums;
class BalanceCodeType
{
const C_CUSTOM_CODE = 'CustomCode';
const C_OTHER = 'Other';
}
| apache-2.0 |
pyrochlore/cycles | src/blender/addon/properties.py | 37894 | #
# Copyright 2011-2013 Blender Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
#
# <pep8 compliant>
import bpy
from bpy.props import (BoolProperty,
EnumProperty,
FloatProperty,
IntProperty,
PointerProperty)
# enums
import _cycles
enum_devices = (
('CPU', "CPU", "Use CPU for rendering"),
('GPU', "GPU Compute", "Use GPU compute device for rendering, configured in user preferences"),
)
if _cycles.with_network:
enum_devices += (('NETWORK', "Networked Device", "Use networked device for rendering"),)
enum_feature_set = (
('SUPPORTED', "Supported", "Only use finished and supported features"),
('EXPERIMENTAL', "Experimental", "Use experimental and incomplete features that might be broken or change in the future", 'ERROR', 1),
)
enum_displacement_methods = (
('BUMP', "Bump", "Bump mapping to simulate the appearance of displacement"),
('TRUE', "True", "Use true displacement only, requires fine subdivision"),
('BOTH', "Both", "Combination of displacement and bump mapping"),
)
enum_bvh_types = (
('DYNAMIC_BVH', "Dynamic BVH", "Objects can be individually updated, at the cost of slower render time"),
('STATIC_BVH', "Static BVH", "Any object modification requires a complete BVH rebuild, but renders faster"),
)
enum_filter_types = (
('BOX', "Box", "Box filter"),
('GAUSSIAN', "Gaussian", "Gaussian filter"),
)
enum_aperture_types = (
('RADIUS', "Radius", "Directly change the size of the aperture"),
('FSTOP', "F/stop", "Change the size of the aperture by f/stops"),
)
enum_panorama_types = (
('EQUIRECTANGULAR', "Equirectangular", "Render the scene with a spherical camera, also known as Lat Long panorama"),
('FISHEYE_EQUIDISTANT', "Fisheye Equidistant", "Ideal for fulldomes, ignore the sensor dimensions"),
('FISHEYE_EQUISOLID', "Fisheye Equisolid",
"Similar to most fisheye modern lens, takes sensor dimensions into consideration"),
)
enum_curve_primitives = (
('TRIANGLES', "Triangles", "Create triangle geometry around strands"),
('LINE_SEGMENTS', "Line Segments", "Use line segment primitives"),
('CURVE_SEGMENTS', "Curve Segments", "Use segmented cardinal curve primitives"),
)
enum_triangle_curves = (
('CAMERA_TRIANGLES', "Planes", "Create individual triangles forming planes that face camera"),
('TESSELLATED_TRIANGLES', "Tessellated", "Create mesh surrounding each strand"),
)
enum_curve_shape = (
('RIBBONS', "Ribbons", "Ignore thickness of each strand"),
('THICK', "Thick", "Use thickness of strand when rendering"),
)
enum_tile_order = (
('CENTER', "Center", "Render from center to the edges"),
('RIGHT_TO_LEFT', "Right to Left", "Render from right to left"),
('LEFT_TO_RIGHT', "Left to Right", "Render from left to right"),
('TOP_TO_BOTTOM', "Top to Bottom", "Render from top to bottom"),
('BOTTOM_TO_TOP', "Bottom to Top", "Render from bottom to top"),
)
enum_use_layer_samples = (
('USE', "Use", "Per render layer number of samples override scene samples"),
('BOUNDED', "Bounded", "Bound per render layer number of samples by global samples"),
('IGNORE', "Ignore", "Ignore per render layer number of samples"),
)
enum_sampling_pattern = (
('SOBOL', "Sobol", "Use Sobol random sampling pattern"),
('CORRELATED_MUTI_JITTER', "Correlated Multi-Jitter", "Use Correlated Multi-Jitter random sampling pattern"),
)
enum_integrator = (
('BRANCHED_PATH', "Branched Path Tracing", "Path tracing integrator that branches on the first bounce, giving more control over the number of light and material samples"),
('PATH', "Path Tracing", "Pure path tracing integrator"),
)
enum_volume_sampling = (
('DISTANCE', "Distance", "Use distance sampling, best for dense volumes with lights far away"),
('EQUIANGULAR', "Equiangular", "Use equiangular sampling, best for volumes with low density with light inside or near the volume"),
('MULTIPLE_IMPORTANCE', "Multiple Importance", "Combine distance and equi-angular sampling for volumes where neither method is ideal"),
)
enum_volume_interpolation = (
('LINEAR', "Linear", "Good smoothness and speed"),
('CUBIC', 'Cubic', 'Smoothed high quality interpolation, but slower')
)
class CyclesRenderSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Scene.cycles = PointerProperty(
name="Cycles Render Settings",
description="Cycles render settings",
type=cls,
)
cls.device = EnumProperty(
name="Device",
description="Device to use for rendering",
items=enum_devices,
default='CPU',
)
cls.feature_set = EnumProperty(
name="Feature Set",
description="Feature set to use for rendering",
items=enum_feature_set,
default='SUPPORTED',
)
cls.shading_system = BoolProperty(
name="Open Shading Language",
description="Use Open Shading Language (CPU rendering only)",
)
cls.progressive = EnumProperty(
name="Integrator",
description="Method to sample lights and materials",
items=enum_integrator,
default='PATH',
)
cls.use_square_samples = BoolProperty(
name="Square Samples",
description="Square sampling values for easier artist control",
default=False,
)
cls.samples = IntProperty(
name="Samples",
description="Number of samples to render for each pixel",
min=1, max=2147483647,
default=10,
)
cls.preview_samples = IntProperty(
name="Preview Samples",
description="Number of samples to render in the viewport, unlimited if 0",
min=0, max=2147483647,
default=10,
)
cls.preview_pause = BoolProperty(
name="Pause Preview",
description="Pause all viewport preview renders",
default=False,
)
cls.preview_active_layer = BoolProperty(
name="Preview Active Layer",
description="Preview active render layer in viewport",
default=False,
)
cls.aa_samples = IntProperty(
name="AA Samples",
description="Number of antialiasing samples to render for each pixel",
min=1, max=10000,
default=4,
)
cls.preview_aa_samples = IntProperty(
name="AA Samples",
description="Number of antialiasing samples to render in the viewport, unlimited if 0",
min=0, max=10000,
default=4,
)
cls.diffuse_samples = IntProperty(
name="Diffuse Samples",
description="Number of diffuse bounce samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.glossy_samples = IntProperty(
name="Glossy Samples",
description="Number of glossy bounce samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.transmission_samples = IntProperty(
name="Transmission Samples",
description="Number of transmission bounce samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.ao_samples = IntProperty(
name="Ambient Occlusion Samples",
description="Number of ambient occlusion samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.mesh_light_samples = IntProperty(
name="Mesh Light Samples",
description="Number of mesh emission light samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.subsurface_samples = IntProperty(
name="Subsurface Samples",
description="Number of subsurface scattering samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.volume_samples = IntProperty(
name="Volume Samples",
description="Number of volume scattering samples to render for each AA sample",
min=1, max=10000,
default=0,
)
cls.sampling_pattern = EnumProperty(
name="Sampling Pattern",
description="Random sampling pattern used by the integrator",
items=enum_sampling_pattern,
default='SOBOL',
)
cls.use_layer_samples = EnumProperty(
name="Layer Samples",
description="How to use per render layer sample settings",
items=enum_use_layer_samples,
default='USE',
)
cls.sample_all_lights_direct = BoolProperty(
name="Sample All Direct Lights",
description="Sample all lights (for direct samples), rather than randomly picking one",
default=True,
)
cls.sample_all_lights_indirect = BoolProperty(
name="Sample All Indirect Lights",
description="Sample all lights (for indirect samples), rather than randomly picking one",
default=True,
)
cls.caustics_reflective = BoolProperty(
name="Reflective Caustics",
description="Use reflective caustics, resulting in a brighter image (more noise but added realism)",
default=True,
)
cls.caustics_refractive = BoolProperty(
name="Refractive Caustics",
description="Use refractive caustics, resulting in a brighter image (more noise but added realism)",
default=True,
)
cls.blur_glossy = FloatProperty(
name="Filter Glossy",
description="Adaptively blur glossy shaders after blurry bounces, "
"to reduce noise at the cost of accuracy",
min=0.0, max=10.0,
default=0.0,
)
cls.min_bounces = IntProperty(
name="Min Bounces",
description="Minimum number of bounces, setting this lower "
"than the maximum enables probabilistic path "
"termination (faster but noisier)",
min=0, max=1024,
default=3,
)
cls.max_bounces = IntProperty(
name="Max Bounces",
description="Total maximum number of bounces",
min=0, max=1024,
default=12,
)
cls.diffuse_bounces = IntProperty(
name="Diffuse Bounces",
description="Maximum number of diffuse reflection bounces, bounded by total maximum",
min=0, max=1024,
default=4,
)
cls.glossy_bounces = IntProperty(
name="Glossy Bounces",
description="Maximum number of glossy reflection bounces, bounded by total maximum",
min=0, max=1024,
default=4,
)
cls.transmission_bounces = IntProperty(
name="Transmission Bounces",
description="Maximum number of transmission bounces, bounded by total maximum",
min=0, max=1024,
default=12,
)
cls.volume_bounces = IntProperty(
name="Volume Bounces",
description="Maximum number of volumetric scattering events",
min=0, max=1024,
default=0,
)
cls.transparent_min_bounces = IntProperty(
name="Transparent Min Bounces",
description="Minimum number of transparent bounces, setting "
"this lower than the maximum enables "
"probabilistic path termination (faster but "
"noisier)",
min=0, max=1024,
default=8,
)
cls.transparent_max_bounces = IntProperty(
name="Transparent Max Bounces",
description="Maximum number of transparent bounces",
min=0, max=1024,
default=8,
)
cls.use_transparent_shadows = BoolProperty(
name="Transparent Shadows",
description="Use transparency of surfaces for rendering shadows",
default=True,
)
cls.volume_step_size = FloatProperty(
name="Step Size",
description="Distance between volume shader samples when rendering the volume "
"(lower values give more accurate and detailed results, but also increased render time)",
default=0.1,
min=0.0000001, max=100000.0, soft_min=0.01, soft_max=1.0
)
cls.volume_max_steps = IntProperty(
name="Max Steps",
description="Maximum number of steps through the volume before giving up, "
"to avoid extremely long render times with big objects or small step sizes",
default=1024,
min=2, max=65536
)
cls.film_exposure = FloatProperty(
name="Exposure",
description="Image brightness scale",
min=0.0, max=10.0,
default=1.0,
)
cls.film_transparent = BoolProperty(
name="Transparent",
description="World background is transparent with premultiplied alpha",
default=False,
)
cls.filter_type = EnumProperty(
name="Filter Type",
description="Pixel filter type",
items=enum_filter_types,
default='GAUSSIAN',
)
cls.filter_width = FloatProperty(
name="Filter Width",
description="Pixel filter width",
min=0.01, max=10.0,
default=1.5,
)
cls.seed = IntProperty(
name="Seed",
description="Seed value for integrator to get different noise patterns",
min=0, max=2147483647,
default=0,
)
cls.sample_clamp_direct = FloatProperty(
name="Clamp Direct",
description="If non-zero, the maximum value for a direct sample, "
"higher values will be scaled down to avoid too "
"much noise and slow convergence at the cost of accuracy",
min=0.0, max=1e8,
default=0.0,
)
cls.sample_clamp_indirect = FloatProperty(
name="Clamp Indirect",
description="If non-zero, the maximum value for an indirect sample, "
"higher values will be scaled down to avoid too "
"much noise and slow convergence at the cost of accuracy",
min=0.0, max=1e8,
default=0.0,
)
cls.debug_tile_size = IntProperty(
name="Tile Size",
description="",
min=1, max=4096,
default=1024,
)
cls.preview_start_resolution = IntProperty(
name="Start Resolution",
description="Resolution to start rendering preview at, "
"progressively increasing it to the full viewport size",
min=8, max=16384,
default=64,
)
cls.debug_reset_timeout = FloatProperty(
name="Reset timeout",
description="",
min=0.01, max=10.0,
default=0.1,
)
cls.debug_cancel_timeout = FloatProperty(
name="Cancel timeout",
description="",
min=0.01, max=10.0,
default=0.1,
)
cls.debug_text_timeout = FloatProperty(
name="Text timeout",
description="",
min=0.01, max=10.0,
default=1.0,
)
cls.debug_bvh_type = EnumProperty(
name="Viewport BVH Type",
description="Choose between faster updates, or faster render",
items=enum_bvh_types,
default='DYNAMIC_BVH',
)
cls.debug_use_spatial_splits = BoolProperty(
name="Use Spatial Splits",
description="Use BVH spatial splits: longer builder time, faster render",
default=False,
)
cls.use_cache = BoolProperty(
name="Cache BVH",
description="Cache last built BVH to disk for faster re-render if no geometry changed",
default=False,
)
cls.tile_order = EnumProperty(
name="Tile Order",
description="Tile order for rendering",
items=enum_tile_order,
default='CENTER',
options=set(), # Not animatable!
)
cls.use_progressive_refine = BoolProperty(
name="Progressive Refine",
description="Instead of rendering each tile until it is finished, "
"refine the whole image progressively "
"(this renders somewhat slower, "
"but time can be saved by manually stopping the render when the noise is low enough)",
default=False,
)
cls.bake_type = EnumProperty(
name="Bake Type",
default='COMBINED',
description="Type of pass to bake",
items = (
('COMBINED', "Combined", ""),
('AO', "Ambient Occlusion", ""),
('SHADOW', "Shadow", ""),
('NORMAL', "Normal", ""),
('UV', "UV", ""),
('EMIT', "Emit", ""),
('ENVIRONMENT', "Environment", ""),
('DIFFUSE_DIRECT', "Diffuse Direct", ""),
('DIFFUSE_INDIRECT', "Diffuse Indirect", ""),
('DIFFUSE_COLOR', "Diffuse Color", ""),
('GLOSSY_DIRECT', "Glossy Direct", ""),
('GLOSSY_INDIRECT', "Glossy Indirect", ""),
('GLOSSY_COLOR', "Glossy Color", ""),
('TRANSMISSION_DIRECT', "Transmission Direct", ""),
('TRANSMISSION_INDIRECT', "Transmission Indirect", ""),
('TRANSMISSION_COLOR', "Transmission Color", ""),
('SUBSURFACE_DIRECT', "Subsurface Direct", ""),
('SUBSURFACE_INDIRECT', "Subsurface Indirect", ""),
('SUBSURFACE_COLOR', "Subsurface Color", ""),
),
)
@classmethod
def unregister(cls):
del bpy.types.Scene.cycles
class CyclesCameraSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
import math
bpy.types.Camera.cycles = PointerProperty(
name="Cycles Camera Settings",
description="Cycles camera settings",
type=cls,
)
cls.aperture_type = EnumProperty(
name="Aperture Type",
description="Use F/stop number or aperture radius",
items=enum_aperture_types,
default='RADIUS',
)
cls.aperture_fstop = FloatProperty(
name="Aperture F/stop",
description="F/stop ratio (lower numbers give more defocus, higher numbers give a sharper image)",
min=0.0, soft_min=0.1, soft_max=64.0,
default=5.6,
step=10,
precision=1,
)
cls.aperture_size = FloatProperty(
name="Aperture Size",
description="Radius of the aperture for depth of field (higher values give more defocus)",
min=0.0, soft_max=10.0,
default=0.0,
step=1,
precision=4,
subtype='DISTANCE',
)
cls.aperture_blades = IntProperty(
name="Aperture Blades",
description="Number of blades in aperture for polygonal bokeh (at least 3)",
min=0, max=100,
default=0,
)
cls.aperture_rotation = FloatProperty(
name="Aperture Rotation",
description="Rotation of blades in aperture",
soft_min=-math.pi, soft_max=math.pi,
subtype='ANGLE',
default=0,
)
cls.aperture_ratio = FloatProperty(
name="Aperture Ratio",
description="Distortion to simulate anamorphic lens bokeh",
min=0.01, soft_min=1.0, soft_max=2.0,
default=1.0,
precision=4,
)
cls.panorama_type = EnumProperty(
name="Panorama Type",
description="Distortion to use for the calculation",
items=enum_panorama_types,
default='FISHEYE_EQUISOLID',
)
cls.fisheye_fov = FloatProperty(
name="Field of View",
description="Field of view for the fisheye lens",
min=0.1745, soft_max=2.0 * math.pi, max=10.0 * math.pi,
subtype='ANGLE',
default=math.pi,
)
cls.fisheye_lens = FloatProperty(
name="Fisheye Lens",
description="Lens focal length (mm)",
min=0.01, soft_max=15.0, max=100.0,
default=10.5,
)
@classmethod
def unregister(cls):
del bpy.types.Camera.cycles
class CyclesMaterialSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Material.cycles = PointerProperty(
name="Cycles Material Settings",
description="Cycles material settings",
type=cls,
)
cls.sample_as_light = BoolProperty(
name="Multiple Importance Sample",
description="Use multiple importance sampling for this material, "
"disabling may reduce overall noise for large "
"objects that emit little light compared to other light sources",
default=True,
)
cls.use_transparent_shadow = BoolProperty(
name="Transparent Shadows",
description="Use transparent shadows for this material if it contains a Transparent BSDF, "
"disabling will render faster but not give accurate shadows",
default=True,
)
cls.homogeneous_volume = BoolProperty(
name="Homogeneous Volume",
description="When using volume rendering, assume volume has the same density everywhere "
"(not using any textures), for faster rendering",
default=False,
)
cls.volume_sampling = EnumProperty(
name="Volume Sampling",
description="Sampling method to use for volumes",
items=enum_volume_sampling,
default='DISTANCE',
)
cls.volume_interpolation = EnumProperty(
name="Volume Interpolation",
description="Interpolation method to use for volumes",
items=enum_volume_interpolation,
default='LINEAR',
)
@classmethod
def unregister(cls):
del bpy.types.Material.cycles
class CyclesLampSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Lamp.cycles = PointerProperty(
name="Cycles Lamp Settings",
description="Cycles lamp settings",
type=cls,
)
cls.cast_shadow = BoolProperty(
name="Cast Shadow",
description="Lamp casts shadows",
default=True,
)
cls.samples = IntProperty(
name="Samples",
description="Number of light samples to render for each AA sample",
min=1, max=10000,
default=1,
)
cls.max_bounces = IntProperty(
name="Max Bounces",
description="Maximum number of bounces the light will contribute to the render",
min=0, max=1024,
default=1024,
)
cls.use_multiple_importance_sampling = BoolProperty(
name="Multiple Importance Sample",
description="Use multiple importance sampling for the lamp, "
"reduces noise for area lamps and sharp glossy materials",
default=False,
)
@classmethod
def unregister(cls):
del bpy.types.Lamp.cycles
class CyclesWorldSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.World.cycles = PointerProperty(
name="Cycles World Settings",
description="Cycles world settings",
type=cls,
)
cls.sample_as_light = BoolProperty(
name="Multiple Importance Sample",
description="Use multiple importance sampling for the environment, "
"enabling for non-solid colors is recommended",
default=False,
)
cls.sample_map_resolution = IntProperty(
name="Map Resolution",
description="Importance map size is resolution x resolution; "
"higher values potentially produce less noise, at the cost of memory and speed",
min=4, max=8096,
default=256,
)
cls.samples = IntProperty(
name="Samples",
description="Number of light samples to render for each AA sample",
min=1, max=10000,
default=4,
)
cls.homogeneous_volume = BoolProperty(
name="Homogeneous Volume",
description="When using volume rendering, assume volume has the same density everywhere"
"(not using any textures), for faster rendering",
default=False,
)
cls.volume_sampling = EnumProperty(
name="Volume Sampling",
description="Sampling method to use for volumes",
items=enum_volume_sampling,
default='EQUIANGULAR',
)
cls.volume_interpolation = EnumProperty(
name="Volume Interpolation",
description="Interpolation method to use for volumes",
items=enum_volume_interpolation,
default='LINEAR',
)
@classmethod
def unregister(cls):
del bpy.types.World.cycles
class CyclesVisibilitySettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Object.cycles_visibility = PointerProperty(
name="Cycles Visibility Settings",
description="Cycles visibility settings",
type=cls,
)
bpy.types.World.cycles_visibility = PointerProperty(
name="Cycles Visibility Settings",
description="Cycles visibility settings",
type=cls,
)
cls.camera = BoolProperty(
name="Camera",
description="Object visibility for camera rays",
default=True,
)
cls.diffuse = BoolProperty(
name="Diffuse",
description="Object visibility for diffuse reflection rays",
default=True,
)
cls.glossy = BoolProperty(
name="Glossy",
description="Object visibility for glossy reflection rays",
default=True,
)
cls.transmission = BoolProperty(
name="Transmission",
description="Object visibility for transmission rays",
default=True,
)
cls.shadow = BoolProperty(
name="Shadow",
description="Object visibility for shadow rays",
default=True,
)
cls.scatter = BoolProperty(
name="Volume Scatter",
description="Object visibility for volume scatter rays",
default=True,
)
@classmethod
def unregister(cls):
del bpy.types.Object.cycles_visibility
del bpy.types.World.cycles_visibility
class CyclesMeshSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Mesh.cycles = PointerProperty(
name="Cycles Mesh Settings",
description="Cycles mesh settings",
type=cls,
)
bpy.types.Curve.cycles = PointerProperty(
name="Cycles Mesh Settings",
description="Cycles mesh settings",
type=cls,
)
bpy.types.MetaBall.cycles = PointerProperty(
name="Cycles Mesh Settings",
description="Cycles mesh settings",
type=cls,
)
cls.displacement_method = EnumProperty(
name="Displacement Method",
description="Method to use for the displacement",
items=enum_displacement_methods,
default='BUMP',
)
cls.use_subdivision = BoolProperty(
name="Use Subdivision",
description="Subdivide mesh for rendering",
default=False,
)
cls.dicing_rate = FloatProperty(
name="Dicing Rate",
description="",
min=0.001, max=1000.0,
default=1.0,
)
@classmethod
def unregister(cls):
del bpy.types.Mesh.cycles
del bpy.types.Curve.cycles
del bpy.types.MetaBall.cycles
class CyclesObjectBlurSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Object.cycles = PointerProperty(
name="Cycles Object Settings",
description="Cycles object settings",
type=cls,
)
cls.use_motion_blur = BoolProperty(
name="Use Motion Blur",
description="Use motion blur for this object",
default=True,
)
cls.use_deform_motion = BoolProperty(
name="Use Deformation Motion",
description="Use deformation motion blur for this object",
default=True,
)
cls.motion_steps = IntProperty(
name="Motion Steps",
description="Control accuracy of deformation motion blur, more steps gives more memory usage (actual number of steps is 2^(steps - 1))",
min=1, soft_max=8,
default=1,
)
@classmethod
def unregister(cls):
del bpy.types.Object.cycles
class CyclesCurveRenderSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.Scene.cycles_curves = PointerProperty(
name="Cycles Hair Rendering Settings",
description="Cycles hair rendering settings",
type=cls,
)
cls.primitive = EnumProperty(
name="Primitive",
description="Type of primitive used for hair rendering",
items=enum_curve_primitives,
default='LINE_SEGMENTS',
)
cls.shape = EnumProperty(
name="Shape",
description="Form of hair",
items=enum_curve_shape,
default='THICK',
)
cls.cull_backfacing = BoolProperty(
name="Cull back-faces",
description="Do not test the back-face of each strand",
default=True,
)
cls.use_curves = BoolProperty(
name="Use Cycles Hair Rendering",
description="Activate Cycles hair rendering for particle system",
default=True,
)
cls.resolution = IntProperty(
name="Resolution",
description="Resolution of generated mesh",
min=3, max=64,
default=3,
)
cls.minimum_width = FloatProperty(
name="Minimal width",
description="Minimal pixel width for strands (0 - deactivated)",
min=0.0, max=100.0,
default=0.0,
)
cls.maximum_width = FloatProperty(
name="Maximal width",
description="Maximum extension that strand radius can be increased by",
min=0.0, max=100.0,
default=0.1,
)
cls.subdivisions = IntProperty(
name="Subdivisions",
description="Number of subdivisions used in Cardinal curve intersection (power of 2)",
min=0, max=24,
default=4,
)
@classmethod
def unregister(cls):
del bpy.types.Scene.cycles_curves
class CyclesCurveSettings(bpy.types.PropertyGroup):
@classmethod
def register(cls):
bpy.types.ParticleSettings.cycles = PointerProperty(
name="Cycles Hair Settings",
description="Cycles hair settings",
type=cls,
)
cls.radius_scale = FloatProperty(
name="Radius Scaling",
description="Multiplier of width properties",
min=0.0, max=1000.0,
default=0.01,
)
cls.root_width = FloatProperty(
name="Root Size",
description="Strand's width at root",
min=0.0, max=1000.0,
default=1.0,
)
cls.tip_width = FloatProperty(
name="Tip Multiplier",
description="Strand's width at tip",
min=0.0, max=1000.0,
default=0.0,
)
cls.shape = FloatProperty(
name="Strand Shape",
description="Strand shape parameter",
min=-1.0, max=1.0,
default=0.0,
)
cls.use_closetip = BoolProperty(
name="Close tip",
description="Set tip radius to zero",
default=True,
)
@classmethod
def unregister(cls):
del bpy.types.ParticleSettings.cycles
def register():
bpy.utils.register_class(CyclesRenderSettings)
bpy.utils.register_class(CyclesCameraSettings)
bpy.utils.register_class(CyclesMaterialSettings)
bpy.utils.register_class(CyclesLampSettings)
bpy.utils.register_class(CyclesWorldSettings)
bpy.utils.register_class(CyclesVisibilitySettings)
bpy.utils.register_class(CyclesMeshSettings)
bpy.utils.register_class(CyclesCurveRenderSettings)
bpy.utils.register_class(CyclesCurveSettings)
def unregister():
bpy.utils.unregister_class(CyclesRenderSettings)
bpy.utils.unregister_class(CyclesCameraSettings)
bpy.utils.unregister_class(CyclesMaterialSettings)
bpy.utils.unregister_class(CyclesLampSettings)
bpy.utils.unregister_class(CyclesWorldSettings)
bpy.utils.unregister_class(CyclesMeshSettings)
bpy.utils.unregister_class(CyclesVisibilitySettings)
bpy.utils.unregister_class(CyclesCurveRenderSettings)
bpy.utils.unregister_class(CyclesCurveSettings)
| apache-2.0 |
murgatroid99/grpc | test/core/surface/server_test.cc | 6453 | /*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/iomgr/resolve_address.h"
#include "src/core/lib/security/credentials/fake/fake_credentials.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
void test_register_method_fail(void) {
grpc_server* server = grpc_server_create(nullptr, nullptr);
void* method;
void* method_old;
method = grpc_server_register_method(server, nullptr, nullptr,
GRPC_SRM_PAYLOAD_NONE, 0);
GPR_ASSERT(method == nullptr);
method_old =
grpc_server_register_method(server, "m", "h", GRPC_SRM_PAYLOAD_NONE, 0);
GPR_ASSERT(method_old != nullptr);
method = grpc_server_register_method(
server, "m", "h", GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER, 0);
GPR_ASSERT(method == nullptr);
method_old =
grpc_server_register_method(server, "m2", "h2", GRPC_SRM_PAYLOAD_NONE,
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST);
GPR_ASSERT(method_old != nullptr);
method =
grpc_server_register_method(server, "m2", "h2", GRPC_SRM_PAYLOAD_NONE, 0);
GPR_ASSERT(method == nullptr);
method = grpc_server_register_method(
server, "m2", "h2", GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER,
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST);
GPR_ASSERT(method == nullptr);
grpc_server_destroy(server);
}
void test_request_call_on_no_server_cq(void) {
grpc_completion_queue* cc = grpc_completion_queue_create_for_next(nullptr);
grpc_server* server = grpc_server_create(nullptr, nullptr);
GPR_ASSERT(GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE ==
grpc_server_request_call(server, nullptr, nullptr, nullptr, cc, cc,
nullptr));
GPR_ASSERT(GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE ==
grpc_server_request_registered_call(server, nullptr, nullptr,
nullptr, nullptr, nullptr, cc,
cc, nullptr));
grpc_completion_queue_destroy(cc);
grpc_server_destroy(server);
}
void test_bind_server_twice(void) {
grpc_arg a;
a.type = GRPC_ARG_INTEGER;
a.key = const_cast<char*>(GRPC_ARG_ALLOW_REUSEPORT);
a.value.integer = 0;
grpc_channel_args args = {1, &a};
char* addr;
grpc_server* server1 = grpc_server_create(&args, nullptr);
grpc_server* server2 = grpc_server_create(&args, nullptr);
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
int port = grpc_pick_unused_port_or_die();
gpr_asprintf(&addr, "[::]:%d", port);
grpc_server_register_completion_queue(server1, cq, nullptr);
grpc_server_register_completion_queue(server2, cq, nullptr);
GPR_ASSERT(0 == grpc_server_add_secure_http2_port(server2, addr, nullptr));
GPR_ASSERT(port == grpc_server_add_insecure_http2_port(server1, addr));
GPR_ASSERT(0 == grpc_server_add_insecure_http2_port(server2, addr));
grpc_server_credentials* fake_creds =
grpc_fake_transport_security_server_credentials_create();
GPR_ASSERT(0 == grpc_server_add_secure_http2_port(server2, addr, fake_creds));
grpc_server_credentials_release(fake_creds);
grpc_server_shutdown_and_notify(server1, cq, nullptr);
grpc_server_shutdown_and_notify(server2, cq, nullptr);
grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr);
grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr);
grpc_server_destroy(server1);
grpc_server_destroy(server2);
grpc_completion_queue_destroy(cq);
gpr_free(addr);
}
void test_bind_server_to_addr(const char* host, bool secure) {
int port = grpc_pick_unused_port_or_die();
char* addr;
gpr_join_host_port(&addr, host, port);
gpr_log(GPR_INFO, "Test bind to %s", addr);
grpc_server* server = grpc_server_create(nullptr, nullptr);
if (secure) {
grpc_server_credentials* fake_creds =
grpc_fake_transport_security_server_credentials_create();
GPR_ASSERT(grpc_server_add_secure_http2_port(server, addr, fake_creds));
grpc_server_credentials_release(fake_creds);
} else {
GPR_ASSERT(grpc_server_add_insecure_http2_port(server, addr));
}
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
grpc_server_register_completion_queue(server, cq, nullptr);
grpc_server_start(server);
grpc_server_shutdown_and_notify(server, cq, nullptr);
grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr);
grpc_server_destroy(server);
grpc_completion_queue_destroy(cq);
gpr_free(addr);
}
static int external_dns_works(const char* host) {
grpc_resolved_addresses* res = nullptr;
grpc_error* error = grpc_blocking_resolve_address(host, "80", &res);
GRPC_ERROR_UNREF(error);
if (res != nullptr) {
grpc_resolved_addresses_destroy(res);
return 1;
}
return 0;
}
static void test_bind_server_to_addrs(const char** addrs, size_t n) {
for (size_t i = 0; i < n; i++) {
test_bind_server_to_addr(addrs[i], false);
test_bind_server_to_addr(addrs[i], true);
}
}
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
grpc_init();
test_register_method_fail();
test_request_call_on_no_server_cq();
test_bind_server_twice();
static const char* addrs[] = {
"::1", "127.0.0.1", "::ffff:127.0.0.1", "localhost", "0.0.0.0", "::",
};
test_bind_server_to_addrs(addrs, GPR_ARRAY_SIZE(addrs));
if (external_dns_works("loopback46.unittest.grpc.io")) {
static const char* dns_addrs[] = {
"loopback46.unittest.grpc.io",
"loopback4.unittest.grpc.io",
};
test_bind_server_to_addrs(dns_addrs, GPR_ARRAY_SIZE(dns_addrs));
}
grpc_shutdown();
return 0;
}
| apache-2.0 |
eggman89/TagGenerationAndMusicReco | src/main/scala-2.10/eggman89/hashmap.scala | 456 | package eggman89
/**
* Created by sneha on 12/7/2015.
*/
class hashmap extends java.io.Serializable
{
var obj:Map[String,Int] = Map()
var id = 0
def add(value:String): Int ={
if (obj.contains(value) == true)
{
obj(value)
}
else
{
id = id + 1
obj = obj +(value->id)
id
}
}
def findval(value : Int) : String = {
val default = ("-1",0)
obj.find(_._2==value).getOrElse(default)._1
}
}
| apache-2.0 |
biddyweb/gateway | transport/bio/src/main/java/org/kaazing/gateway/transport/bio/MulticastAcceptorImpl.java | 12393 | /**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kaazing.gateway.transport.bio;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.service.TransportMetadata;
import org.apache.mina.core.session.ExpiringSessionRecycler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionRecycler;
import org.apache.mina.transport.socket.DatagramSessionConfigEx;
import org.apache.mina.transport.socket.DefaultDatagramSessionConfigEx;
import org.apache.mina.util.ExceptionMonitor;
import org.kaazing.mina.core.buffer.IoBufferAllocatorEx;
import org.kaazing.mina.core.buffer.IoBufferEx;
import org.kaazing.mina.core.future.BindFuture;
import org.kaazing.mina.core.future.DefaultBindFuture;
import org.kaazing.mina.core.future.DefaultUnbindFuture;
import org.kaazing.mina.core.future.UnbindFuture;
import org.kaazing.mina.core.service.AbstractIoAcceptorEx;
import org.kaazing.mina.core.service.IoProcessorEx;
import org.kaazing.mina.core.session.IoSessionConfigEx;
import org.kaazing.mina.core.session.IoSessionEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MulticastAcceptorImpl extends AbstractIoAcceptorEx {
private static final IoSessionRecycler DEFAULT_RECYCLER = new ExpiringSessionRecycler();
private final Logger logger = LoggerFactory.getLogger("transport.mcp");
private final ConcurrentMap<SocketAddress, Handle> boundHandles;
private final MulticastProcessor processor;
private IoSessionRecycler sessionRecycler = DEFAULT_RECYCLER;
public MulticastAcceptorImpl() {
this(new DefaultDatagramSessionConfigEx(), null);
}
public MulticastAcceptorImpl(IoSessionConfigEx sessionConfig) {
this(sessionConfig, null);
}
public MulticastAcceptorImpl(IoSessionConfigEx sessionConfig, Executor executor) {
super(sessionConfig, executor);
boundHandles = new ConcurrentHashMap<>();
processor = new MulticastProcessor();
}
@Override
public DatagramSessionConfigEx getSessionConfig() {
return (DatagramSessionConfigEx) super.getSessionConfig();
}
@Override
protected BindFuture bindAsyncInternal(SocketAddress localAddress) {
List<? extends SocketAddress> localAddresses = Collections.singletonList(localAddress);
try {
bindInternal(localAddresses);
return DefaultBindFuture.succeededFuture();
} catch (Exception e) {
DefaultBindFuture bindFuture = new DefaultBindFuture();
bindFuture.setException(e);
return bindFuture;
}
}
@Override
protected UnbindFuture unbindAsyncInternal(SocketAddress localAddress) {
List<? extends SocketAddress> localAddresses = Collections.singletonList(localAddress);
try {
unbind0(localAddresses);
return DefaultUnbindFuture.succeededFuture();
} catch (Exception e) {
DefaultUnbindFuture unbindFuture = new DefaultUnbindFuture();
unbindFuture.setException(e);
return unbindFuture;
}
}
@Override
protected Set<SocketAddress> bindInternal(
List<? extends SocketAddress> localAddresses) throws Exception {
Set<SocketAddress> boundAddresses = new HashSet<>();
List<SocketAddress> failedAddresses = new LinkedList<>();
for (SocketAddress localAddress : localAddresses) {
MulticastAddress multicastAddress = (MulticastAddress)localAddress;
Handle handle = new Handle(multicastAddress);
Handle oldHandle = boundHandles.putIfAbsent(localAddress, handle);
if (oldHandle != null) {
failedAddresses.add(localAddress);
}
else {
try {
handle.bind();
logger.debug("Bound to resource: " + localAddress);
}
catch (IOException e) {
String error = "Unable to bind to resource: " + localAddress + " cause: " + e.getMessage();
logger.error(error);
throw new RuntimeException(error);
}
boundAddresses.add(multicastAddress);
}
}
if (!failedAddresses.isEmpty()) {
throw new RuntimeException("Addresses already bound to different handlers: " + failedAddresses);
}
return boundAddresses;
}
@Override
protected void unbind0(List<? extends SocketAddress> localAddresses)
throws Exception {
for (SocketAddress localAddress : localAddresses) {
Handle handle = boundHandles.get(localAddress);
if (handle != null) {
try {
handle.unbind();
logger.debug("Unbound from resource: " + localAddress);
}
catch (IOException e) {
String error = "Unable to unbind from resource: " + localAddress + " cause: " + e.getMessage();
logger.error(error);
throw new RuntimeException(error);
}
}
}
}
// TODO: change to return void for 2.0.0-RCx upgrade
@Override
protected IoFuture dispose0() throws Exception {
// close all recycled sessions that have not yet timed out
// this triggers the sessionClosed event for the filter chain
Set<IoSession> managedSessions = new HashSet<>(getManagedSessions().values());
for (IoSession managedSession : managedSessions) {
managedSession.close(true);
}
// unbind handles that may not yet have an associated session
for (Handle handle : boundHandles.values()) {
try {
handle.unbind();
}
catch (IOException e) {
e.printStackTrace();
}
}
// TODO: remove return for 2.0.0-RCx upgrade
return null;
}
@Override
public TransportMetadata getTransportMetadata() {
return MulticastSession.TRANSPORT_METADATA;
}
@Override
public final IoSessionEx newSession(SocketAddress remoteAddress, SocketAddress localAddress) {
if (isDisposing()) {
throw new IllegalStateException("Already disposed.");
}
if (remoteAddress == null) {
throw new NullPointerException("remoteAddress");
}
synchronized (bindLock) {
if (!isActive()) {
throw new IllegalStateException(
"Can't create a session from a unbound service.");
}
try {
return newSessionWithoutLock(remoteAddress, localAddress);
} catch (RuntimeException | Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to create a session.", e);
}
}
}
private IoSessionEx newSessionWithoutLock(
SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
Handle handle = boundHandles.get(localAddress);
if (handle == null) {
throw new IllegalArgumentException("Unknown local address: " + localAddress);
}
IoSessionEx session;
IoSessionRecycler sessionRecycler = getSessionRecycler();
synchronized (sessionRecycler) {
session = (IoSessionEx) sessionRecycler.recycle(localAddress, remoteAddress);
if (session != null && !session.isClosing()) {
return session;
}
// If a new session needs to be created.
MulticastSession newSession = new MulticastSession(this, processor, handle.socket, handle.localAddress, remoteAddress);
sessionRecycler.put(newSession);
session = newSession;
}
initSession(session, null, null);
try {
this.getFilterChainBuilder().buildFilterChain(session.getFilterChain());
getListeners().fireSessionCreated(session);
}
catch (Throwable t) {
ExceptionMonitor.getInstance().exceptionCaught(t);
}
return session;
}
public IoSessionRecycler getSessionRecycler() {
return sessionRecycler;
}
private class Handle implements Runnable {
private final MulticastSocket socket;
private final SocketAddress localAddress;
private final InetSocketAddress groupAddress;
private final NetworkInterface device;
public Handle(MulticastAddress localAddress) throws IOException {
this.localAddress = localAddress;
this.socket = new MulticastSocket(new InetSocketAddress(localAddress.getGroupAddress(), localAddress.getBindPort()));
this.groupAddress = new InetSocketAddress(localAddress.getGroupAddress(), 0);
this.device = localAddress.getDevice();
}
@Override
public void run() {
while (socket.isBound()) {
try {
// blocking read or exception on close
byte[] buf = new byte[socket.getReceiveBufferSize()];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// recycle session if necessary
SocketAddress remoteAddress = packet.getSocketAddress();
IoSessionEx session = newSession(remoteAddress, localAddress);
// verify session can receive messages
if (!session.isReadSuspended()) {
// prepare message
byte[] data = packet.getData();
int offset = packet.getOffset();
int length = packet.getLength();
IoBufferAllocatorEx<?> allocator = session.getBufferAllocator();
IoBufferEx message = allocator.wrap(ByteBuffer.wrap(data, offset, length));
// deliver message
session.getFilterChain().fireMessageReceived(message);
}
}
catch (IOException e) {
if (socket.isClosed()) {
// socket closed, so close sessions for this local address
Set<IoSession> managedSessions = new HashSet<>(getManagedSessions().values());
for (IoSession managedSession : managedSessions) {
if (localAddress.equals(managedSession.getLocalAddress())) {
managedSession.close(true);
}
}
Handle h = boundHandles.remove(localAddress);
if (h != this) {
throw new IllegalStateException("Duplicate local address binding");
}
}
break;
}
}
}
public void bind() throws IOException {
socket.joinGroup(groupAddress, device);
executeWorker(this);
}
public void unbind() throws IOException {
if (!socket.isClosed()) {
socket.leaveGroup(groupAddress, device);
socket.close();
}
}
}
private class MulticastProcessor implements IoProcessorEx<MulticastSession> {
@Override
public void dispose() {
}
@Override
public boolean isDisposed() {
return false;
}
@Override
public boolean isDisposing() {
return false;
}
@Override
public void add(MulticastSession session) {
}
@Override
public void flush(MulticastSession session) {
// TODO: for multicast writes
}
@Override
public void remove(MulticastSession session) {
session.getSocket().close();
getSessionRecycler().remove(session);
getListeners().fireSessionDestroyed(session);
}
@Override
public void updateTrafficControl(MulticastSession session) {
}
}
}
| apache-2.0 |
assemblade/CAT | cat-client-model/src/main/java/com/assemblade/client/model/Property.java | 2187 | /*
* Copyright 2012 Mike Adamson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.assemblade.client.model;
import java.io.Serializable;
public class Property implements Identifiable,Serializable {
private static final long serialVersionUID = 8031343993035061521L;
private String url;
private Folder folder;
private String id;
private String name;
private String description;
private String value;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Property property = (Property) o;
if (id != null ? !id.equals(property.id) : property.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
| apache-2.0 |
SpruceHillio/urbanairship-java-api-wrapper | src/main/java/io/sprucehill/urbanairship/model/TagsRequest.java | 6557 | package io.sprucehill.urbanairship.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Setting tags on either channel IDs or namedUser IDs
*
* @author Michael Duergner <michael@sprucehill.io>
*/
public class TagsRequest extends Base {
@JsonProperty(value = "audience")
Audience audience;
@JsonProperty(value = "add")
Map<String,Set<String>> add;
@JsonProperty(value = "remove")
Map<String,Set<String>> remove;
@JsonProperty(value = "set")
Map<String,Set<String>> set;
protected TagsRequest() {}
/**
* Get the audience selector
*
* @return The Audience.
*/
public Audience getAudience() {
return audience;
}
/**
* Get a Builder for this object
*
* @return The Builder object
*/
public static Builder builder() {
return new Builder();
}
/**
* A Builder for the tags request DTO model object
*
*/
public static class Builder {
TagsRequest tagsRequest;
protected Builder () {
tagsRequest = new TagsRequest();
}
/**
* Set the Audience for the request
*
* @param audience The Audience
* @return The Builder instance
*/
public Builder withAudience(Audience audience) {
tagsRequest.audience = audience;
return this;
}
/**
* Add a tag to that tag group.
*
* Adding a tag will unset any maybe set set tags tag groups.
*
* @param tag The tag to add
* @param tagGroup The tag group to add the tag to
* @return The builder instance
*/
public Builder addTagToTagGroup(String tag, String tagGroup) {
if (null == tagsRequest.add) {
tagsRequest.add = new HashMap<>();
}
if (!tagsRequest.add.containsKey(tagGroup)) {
tagsRequest.add.put(tagGroup,new HashSet<>());
}
tagsRequest.add.get(tagGroup).add(tag);
tagsRequest.set = null;
return this;
}
/**
* Adds multiple tags to that tag group
*
* Adding tags will unset any maybe set set tags tag groups.
*
* @param tags The tags to add
* @param tagGroup The tag group to add the tags to
* @return The builder instance
*/
public Builder addTagsToTagGroup(Set<String> tags, String tagGroup) {
if (null == tagsRequest.add) {
tagsRequest.add = new HashMap<>();
}
if (!tagsRequest.add.containsKey(tagGroup)) {
tagsRequest.add.put(tagGroup,new HashSet<>());
}
tagsRequest.add.get(tagGroup).addAll(tags);
tagsRequest.set = null;
return this;
}
/**
* Remove a tag from that tag group
*
* Removing a tag will unset any maybe set set tags tag groups.
*
* @param tag The tag to remove
* @param tagGroup The tag group to remove the tag from
* @return The builder instance
*/
public Builder removeTagToTagGroup(String tag, String tagGroup) {
if (null == tagsRequest.remove) {
tagsRequest.remove = new HashMap<>();
}
if (!tagsRequest.remove.containsKey(tagGroup)) {
tagsRequest.remove.put(tagGroup,new HashSet<>());
}
tagsRequest.remove.get(tagGroup).add(tag);
tagsRequest.set = null;
return this;
}
/**
* Remove tags from that tag group
*
* Removing tags will unset any maybe set set tags tag groups.
*
* @param tags The tags to remove
* @param tagGroup The tag group to remove the tags from
* @return The builder instance
*/
public Builder removeTagsToTagGroup(Set<String> tags, String tagGroup) {
if (null == tagsRequest.remove) {
tagsRequest.remove = new HashMap<>();
}
if (!tagsRequest.remove.containsKey(tagGroup)) {
tagsRequest.remove.put(tagGroup,new HashSet<>());
}
tagsRequest.remove.get(tagGroup).addAll(tags);
tagsRequest.set = null;
return this;
}
/**
* Set the tags for that tag group to the submitted tag
*
* Setting a tag to a tag group will unset and maybe set add and remove tag group
*
* @param tag The tag to that the tag group to
* @param tagGroup The tag group to operate on
* @return The builder instance
*/
public Builder setTagToTagGroup(String tag, String tagGroup) {
if (null == tagsRequest.set) {
tagsRequest.set = new HashMap<>();
}
if (!tagsRequest.set.containsKey(tagGroup)) {
tagsRequest.set.put(tagGroup,new HashSet<>());
}
tagsRequest.set.get(tagGroup).add(tag);
tagsRequest.add = null;
tagsRequest.remove = null;
return this;
}
/**
* Se the tags for that tag group to the submitted tags
*
* Setting tags to a tag group will unset and maybe set add and remove tag group
*
* @param tags The tags to set the tag group to
* @param tagGroup The tag group to operate on
* @return The builder instance
*/
public Builder setTagsToTagGroup(Set<String> tags, String tagGroup) {
if (null == tagsRequest.set) {
tagsRequest.set = new HashMap<>();
}
if (!tagsRequest.set.containsKey(tagGroup)) {
tagsRequest.set.put(tagGroup,new HashSet<>());
}
tagsRequest.set.get(tagGroup).addAll(tags);
tagsRequest.add = null;
tagsRequest.remove = null;
return this;
}
/**
* Get the tags request DTO model object
*
* @return The tags request DTO model object
*/
public TagsRequest build() {
return tagsRequest;
}
}
}
| apache-2.0 |
smurawski/chef | spec/unit/provider/template/content_spec.rb | 6527 | #
# Author:: Lamont Granquist (<lamont@chef.io>)
# Copyright:: Copyright 2013-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "spec_helper"
describe Chef::Provider::Template::Content do
let(:enclosing_directory) {
canonicalize_path(Dir.mktmpdir)
}
let(:resource_path) {
canonicalize_path(File.expand_path(File.join(enclosing_directory, "openldap_stuff.conf")))
}
let(:new_resource) do
double("Chef::Resource::Template (new)",
:cookbook_name => "openldap",
:recipe_name => "default",
:source_line => "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
:source_line_file => "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb",
:source_line_number => "2",
:source => "openldap_stuff.conf.erb",
:name => "openldap_stuff.conf",
:path => resource_path,
:local => false,
:cookbook => nil,
:variables => {},
:inline_helper_blocks => {},
:inline_helper_modules => [],
:helper_modules => [])
end
let(:rendered_file_locations) {
[Dir.tmpdir + "/openldap_stuff.conf",
enclosing_directory + "/openldap_stuff.conf"]
}
let(:run_context) do
cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks"))
Chef::Cookbook::FileVendor.fetch_from_disk(cookbook_repo)
cl = Chef::CookbookLoader.new(cookbook_repo)
cl.load_cookbooks
cookbook_collection = Chef::CookbookCollection.new(cl)
node = Chef::Node.new
double("Chef::Resource::RunContext", :node => node, :cookbook_collection => cookbook_collection)
end
let(:content) do
current_resource = double("Chef::Resource::Template (current)")
Chef::Provider::Template::Content.new(new_resource, current_resource, run_context)
end
after do
rendered_file_locations.each do |file|
FileUtils.rm(file) if ::File.exist?(file)
end
end
it "finds the template file in the cookbook cache if it isn't local" do
expect(content.template_location).to eq(CHEF_SPEC_DATA + "/cookbooks/openldap/templates/default/openldap_stuff.conf.erb")
end
it "finds the template file locally if it is local" do
allow(new_resource).to receive(:local).and_return(true)
allow(new_resource).to receive(:source).and_return("/tmp/its_on_disk.erb")
expect(content.template_location).to eq("/tmp/its_on_disk.erb")
end
it "should use the cookbook name if defined in the template resource" do
allow(new_resource).to receive(:cookbook_name).and_return("apache2")
allow(new_resource).to receive(:cookbook).and_return("openldap")
allow(new_resource).to receive(:source).and_return("test.erb")
expect(content.template_location).to eq(CHEF_SPEC_DATA + "/cookbooks/openldap/templates/default/test.erb")
end
it "returns a tempfile in the tempdir when :file_staging_uses_destdir is not set" do
Chef::Config[:file_staging_uses_destdir] = false
expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be true
expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be false
end
it "returns a tempfile in the destdir when :file_staging_uses_destdir is set" do
Chef::Config[:file_staging_uses_destdir] = true
expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be true
end
context "when creating a tempfile in destdir fails" do
let(:enclosing_directory) {
canonicalize_path("/nonexisting/path")
}
it "returns a tempfile in the tempdir when :file_deployment_uses_destdir is set to :auto" do
Chef::Config[:file_staging_uses_destdir] = :auto
expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be true
expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be false
end
it "fails when :file_desployment_uses_destdir is set" do
Chef::Config[:file_staging_uses_destdir] = true
expect { content.tempfile }.to raise_error(Chef::Exceptions::FileContentStagingError)
end
it "returns a tempfile in the tempdir when :file_desployment_uses_destdir is not set" do
expect(content.tempfile.path.start_with?(Dir::tmpdir)).to be true
expect(canonicalize_path(content.tempfile.path).start_with?(enclosing_directory)).to be false
end
end
it "creates the template with the rendered content" do
run_context.node.normal[:slappiness] = "a warm gun"
expect(IO.read(content.tempfile.path)).to eq("slappiness is a warm gun")
end
describe "when using location helpers" do
let(:new_resource) do
double("Chef::Resource::Template (new)",
:cookbook_name => "openldap",
:recipe_name => "default",
:source_line => CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
:source_line_file => CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb",
:source_line_number => "2",
:source => "helpers.erb",
:name => "helpers.erb",
:path => CHEF_SPEC_DATA + "/cookbooks/openldap/templates/default/helpers.erb",
:local => false,
:cookbook => nil,
:variables => {},
:inline_helper_blocks => {},
:inline_helper_modules => [],
:helper_modules => [])
end
it "creates the template with the rendered content" do
expect(IO.read(content.tempfile.path)).to eql <<EOF
openldap
default
#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
2
helpers.erb
#{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
openldap
default
#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
2
helpers.erb
#{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
EOF
end
end
end
| apache-2.0 |
JLospinoso/juno | juno-core/src/main/java/net/lospi/juno/estimation/ml/PhaseOneResults.java | 231 | /*
* Copyright (c) 2014. Josh Lospinoso. All rights reserved
*/
package net.lospi.juno.estimation.ml;
public interface PhaseOneResults {
WeightMatrix getWeightMatrix();
boolean isSuccessful();
String getStatus();
}
| apache-2.0 |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/annotation/Propagation.java | 927 | /*
* Copyright (c) 2009-present, b3log.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.latke.repository.annotation;
/**
* Transaction propagation behaviors.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.0, Jul 8, 2013
*/
public enum Propagation {
/**
* Supports a current transaction, creates a new one if none exists.
*/
REQUIRED,
}
| apache-2.0 |
getcarina/interlock | plugins/stats/info.go | 430 | package stats
import (
"github.com/getcarina/interlock"
)
const (
pluginName = "stats"
pluginVersion = "0.1"
pluginDescription = "cluster stats to graphite"
pluginUrl = "https://github.com/getcarina/interlock/tree/master/plugins/stats"
)
var (
pluginInfo = &interlock.PluginInfo{
Name: pluginName,
Version: pluginVersion,
Description: pluginDescription,
Url: pluginUrl,
}
)
| apache-2.0 |
xushaomin/apple-auto | apple-auto-partner-platform/src/main/webapp/static/js/heart_beat.js | 8352 | /**
* All JS in here.
*/
$(function () {
new HeartBeat();
});
function HeartBeat() {
this.toggleMenuActive();
}
HeartBeat.prototype = {
toggleMenuActive: function () {
var href = location.pathname;
if (href.indexOf("instance/") != -1) {
$("#mainMenu li#instanceMenu").addClass("active");
} else if (href.indexOf("log/") != -1) {
$("#mainMenu li#logMenu").addClass("active");
} else if (href.indexOf("config/") != -1) {
$("#mainMenu li#configMenu").addClass("active");
} else if (href.indexOf("user/") != -1 || href.indexOf("system/") != -1) {
$("#mainMenu li#systemMenu").addClass("active");
} else if (href.indexOf("user_profile") != -1) {
$("#mainMenu li#userProfileMenu").addClass("active");
} else {
$("#mainMenu li:eq(0)").addClass("active");
}
},
initialAlert: function (eleId, fadeInTime, fadeOutTime) {
if ('' != eleId) {
fadeInTime = fadeInTime || 1000; //default fade in: 1000ms
fadeOutTime = fadeOutTime || 1000; //default fade out: 1000ms
var $alert = $("#" + eleId);
$alert.show().parent().parent().fadeIn(fadeInTime).slideUp(fadeOutTime);
}
}
};
/**
* displaytag paginated use it.
* Don't change it
*
* @param formId
* @param data
*/
function displaytagform(formId, data) {
var $form = $("#" + formId);
var action = $form.attr("action");
var params = action.indexOf('?') == -1 ? '?' : '&';
$.map(data, function (d) {
params += (d.f + "=" + d.v + "&");
});
var url = action + params;
var $targetDiv = $("div.displayTarget");
if ($targetDiv.length > 0) {
//if exist, load the content to the div
$targetDiv.load(url);
} else {
location.href = url;
}
}
/**
* instance_list.jsp
* @param alert
* @constructor
*/
function InstanceList(alert) {
HeartBeat.prototype.initialAlert(alert);
}
/**
* user_profile.jsp
* @param alert
* @constructor
*/
function UserProfile(alert) {
HeartBeat.prototype.initialAlert(alert);
}
/**
* system_setting.jsp
* @param alert
* @constructor
*/
function SystemSetting(alert) {
HeartBeat.prototype.initialAlert(alert);
this.executeCleanLog();
}
SystemSetting.prototype = {
executeCleanLog: function () {
$("a#executeCleanLog").click(function () {
$("#executeCleanLogForm").submit();
});
}
};
/**
* user_list.jsp
* @param alert
* @constructor
*/
function UserList(alert) {
HeartBeat.prototype.initialAlert(alert);
this.resetPass();
this.deleteUser();
}
UserList.prototype = {
resetPass: function () {
$("a.resetPass").click(function () {
var $this = $(this);
if (!confirm($this.attr("confirmText"))) {
return
}
var guid = $this.attr("guid");
$.post("reset_password/" + guid + ".hb", function (data) {
var $modal = $("#resetPassModal");
$modal.find("div.modal-body").html(data);
$modal.modal("show");
});
});
},
deleteUser: function () {
$("a.deleteUser").click(function () {
var $this = $(this);
if (!confirm($this.attr("confirmText"))) {
return
}
var guid = $this.attr("guid");
$.post("delete/" + guid + ".hb", function (data) {
if ('ok' === data) {
location.href = location.pathname + "?alert=deleteSuccess";
}
});
});
}
};
/**
* index.jsp
* @param alert
* @constructor
*/
function Index(alert) {
HeartBeat.prototype.initialAlert(alert);
this.submitSearch();
}
Index.prototype = {
submitSearch: function () {
$("select[name='maxResult']").change(function () {
$(this.form).submit();
});
$("input#enabled").change(function () {
var $this = $(this);
$this.next().val($this.is(":checked"));
$(this.form).submit();
});
}
};
/**
* instance_form.jsp
* @constructor
*/
function InstanceForm() {
this.addParam();
this.deleteParam();
this.checkRandom();
}
InstanceForm.prototype = {
checkRandom: function () {
$("form").on("click", "input.random", function () {
var $this = $(this);
if ($this.is(":checked")) {
$this.parent().prev().val("").attr("readonly", true);
} else {
$this.parent().prev().attr("readonly", false);
}
});
},
addParam: function () {
$("form").on("click", "a.addParam", function () {
var $this = $(this);
var $tr = $this.parent().parent();
var order = $tr.attr("order");
var newOrder = parseInt(order) + 1;
var $newTr = $tr.clone().attr("order", newOrder);
var $keyEle = $newTr.find("td input:first");
$keyEle.attr("id", "urlParameters" + newOrder + ".key").attr("name", "urlParameters[" + newOrder + "].key");
var $valueEle = $newTr.find("td .input-group input.value");
$valueEle.attr("id", "urlParameters" + newOrder + ".value").attr("name", "urlParameters[" + newOrder + "].value");
var $randomEle = $newTr.find("td input:checkbox");
$randomEle.attr("name", "urlParameters[" + newOrder + "].randomValue");
$newTr.find("td:last").find("a").removeClass("hidden");
$tr.after($newTr);
$this.addClass("hidden").next().addClass("hidden");
});
},
deleteParam: function () {
$("form").on("click", "a.deleteParam", function () {
var $tr = $(this).parent().parent();
var order = $tr.attr("order");
var $prevLastTd = $tr.prev().find("td:last");
$prevLastTd.find("a.addParam").removeClass("hidden");
if (order != "1") {
$prevLastTd.find("a.deleteParam").removeClass("hidden");
}
$tr.remove();
});
}
};
/**
* monitoring_instance.jsp
* @constructor
*/
function MonitoringInstance(guid) {
this.loadInstanceStatics(guid)
}
MonitoringInstance.prototype = {
loadInstanceStatics: function (guid) {
var self = this;
self._loadCurrInsStatics(guid);
setInterval(function () {
self._loadCurrInsStatics(guid);
}, 60000); //60 seconds
},
_loadCurrInsStatics: function (guid) {
var $staticsDiv = $("div#staticsDiv");
var $loading = $staticsDiv.prev().removeClass("hidden");
$staticsDiv.load("statistics/" + guid + ".hb", function () {
$loading.addClass("hidden");
});
}
};
/**
* search_result.jsp
* @constructor
*/
function SearchResult() {
this.toggleTab();
}
SearchResult.prototype = {
toggleTab: function () {
$(".nav-tabs li a").click(function () {
$("#searchType").val($(this).attr("sType"));
$("#filterForm").submit();
});
}
};
/**
* reminder_logs.jsp
* @constructor
*/
function ReminderLogs() {
this.showEmailContent();
this.showWeChatContent();
}
ReminderLogs.prototype = {
showEmailContent: function () {
$("a.showMailContent").click(function () {
$("div#modalContainer").html($(this).next().html());
$("h4#myModalLabel").html("提醒的邮件内容");
$("button#modalConfirmBtn").hide();
$("div#myModal").modal("show");
});
},
showWeChatContent: function () {
$("a.showWeChatContent").click(function () {
$("div#modalContainer").html($(this).next().html());
$("h4#myModalLabel").html("微信收到的提醒内容");
$("button#modalConfirmBtn").hide();
$("div#myModal").modal("show");
});
}
};
| apache-2.0 |
meego-netbook-ux/google-gadgets-meego | extensions/qt_system_framework/qt_system_framework.cc | 10459 | /*
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <vector>
#include <QtGui/QCursor>
#include <QtGui/QFileDialog>
#include <QtGui/QDesktopWidget>
#include <ggadget/common.h>
#include <ggadget/gadget_consts.h>
#include <ggadget/framework_interface.h>
#include <ggadget/registerable_interface.h>
#include <ggadget/scriptable_interface.h>
#include <ggadget/scriptable_framework.h>
#include <ggadget/scriptable_array.h>
#include <ggadget/string_utils.h>
#include <ggadget/gadget.h>
#include <ggadget/gadget.h>
#include <ggadget/permissions.h>
#include <ggadget/xdg/desktop_entry.h>
#include <ggadget/xdg/icon_theme.h>
#include <ggadget/xdg/utilities.h>
#define Initialize qt_system_framework_LTX_Initialize
#define Finalize qt_system_framework_LTX_Finalize
#define RegisterFrameworkExtension \
qt_system_framework_LTX_RegisterFrameworkExtension
namespace ggadget {
namespace framework {
// To avoid naming conflicts.
namespace qt_system_framework {
class QtSystemCursor : public CursorInterface {
public:
virtual void GetPosition(int *x, int *y) {
QPoint p = QCursor::pos();
if (x) *x = p.x();
if (y) *y = p.y();
}
};
class QtSystemScreen : public ScreenInterface {
public:
virtual void GetSize(int *width, int *height) {
QDesktopWidget w;
QRect r = w.screenGeometry();
if (width) *width = r.width();
if (height) *height = r.height();
}
};
static const Variant kBrowseForFilesDefaultArgs[] = {
Variant(), // filter
Variant(static_cast<const char *>(NULL)), // title
Variant(BROWSE_FILE_MODE_OPEN) // mode
};
static const Variant kBrowseForFileDefaultArgs[] = {
Variant(), // filter
Variant(static_cast<const char *>(NULL)), // title
Variant(BROWSE_FILE_MODE_OPEN), // mode
Variant(static_cast<const char *>(NULL)) // default_name
};
class QtSystemBrowseForFileHelper {
public:
QtSystemBrowseForFileHelper(ScriptableInterface *framework, Gadget *gadget)
: gadget_(gadget) {
framework->ConnectOnReferenceChange(
NewSlot(this, &QtSystemBrowseForFileHelper::OnFrameworkRefChange));
}
// Function to destroy the helper object when framework is destroyed.
void OnFrameworkRefChange(int ref, int change) {
GGL_UNUSED(ref);
if (change == 0) {
DLOG("Framework destroyed, delete QtSystemBrowseForFileHelper object.");
delete this;
}
}
std::string BrowseForFile(const char *filter, const char *title,
BrowseForFileMode mode, const char *default_name) {
std::string result;
std::vector<std::string> files;
if (BrowseForFilesImpl(filter, false, title, mode, default_name, &files) &&
files.size() > 0)
result = files[0];
return result;
}
ScriptableArray *BrowseForFiles(const char *filter, const char *title,
BrowseForFileMode mode) {
std::vector<std::string> files;
BrowseForFilesImpl(filter, true, title, mode, NULL, &files);
return ScriptableArray::Create(files.begin(), files.end());
}
bool BrowseForFilesImpl(const char *filter, bool multiple, const char *title,
BrowseForFileMode mode, const char *default_name,
std::vector<std::string> *result) {
GGL_UNUSED(title);
GGL_UNUSED(mode);
GGL_UNUSED(default_name);
ASSERT(result);
result->clear();
QStringList filters;
QFileDialog dialog;
// TODO: support title(including gadget name), gadget icon, mode, default_name.
if (multiple) dialog.setFileMode(QFileDialog::ExistingFiles);
if (filter && *filter) {
size_t len = strlen(filter);
char *copy = new char[len + 2];
memcpy(copy, filter, len + 1);
copy[len] = '|';
copy[len + 1] = '\0';
char *str = copy;
int i = 0;
int t = 0;
while (str[i] != '\0') {
if (str[i] == '|') {
t++;
if (t == 1) str[i] = '(';
if (t == 2) {
str[i] = ')';
char bak = str[i + 1];
str[i + 1] = '\0';
filters << QString::fromUtf8(str);
str[i + 1] = bak;
str = &str[i+1];
i = 0;
t = 0;
continue;
}
} else if (str[i] == ';' && t == 1) {
str[i] = ' ';
}
i++;
}
delete [] copy;
dialog.setFilters(filters);
}
if (dialog.exec()) {
QStringList fnames = dialog.selectedFiles();
for (int i = 0; i < fnames.size(); ++i)
result->push_back(fnames.at(i).toUtf8().data());
return true;
}
return false;
}
Gadget *gadget_;
};
// Gets the icon file of a DesktopEntry file.
static std::string GetDesktopEntryIcon(const char *file) {
ASSERT(file);
ggadget::xdg::DesktopEntry entry(file);
if (entry.IsValid()) {
return entry.GetIcon();
} else {
return "";
}
}
static std::string GetDirectorySpecialIcon(const std::string &file) {
GGL_UNUSED(file);
// TODO: check .directory file to show the right icon
return "";
}
std::string GetFileIcon(const char *file) {
static const int kDefaultIconSize = 128;
std::vector<std::string> icon_names;
std::string type = ggadget::xdg::GetFileMimeType(file);
std::string icon_name, icon_file;
DLOG("GetFileIcon:%s, %s", file, type.c_str());
if (type == ggadget::xdg::kDesktopEntryMimeType) {
icon_name = GetDesktopEntryIcon(file);
if (icon_name.length())
icon_names.push_back(icon_name);
} else if (type == ggadget::xdg::kDirectoryMimeType) {
icon_name = GetDirectorySpecialIcon(file);
if (icon_name.length())
icon_names.push_back(icon_name);
icon_names.push_back("folder");
} else {
icon_name = ggadget::xdg::GetMimeTypeXDGIcon(type.c_str());
if (icon_name.length())
icon_names.push_back(icon_name);
// Try icon name similar than: text-plain
icon_name = type;
for (size_t i = icon_name.find('/', 0); i != std::string::npos;
i = icon_name.find('/', i + 1))
icon_name[i] = '-';
icon_names.push_back(icon_name);
// Try generic name like text-x-generic.
icon_name = type.substr(0, type.find('/')) + "-x-generic";
icon_names.push_back(icon_name);
icon_names.push_back("gnome-mime-" + icon_name);
// Last resort
icon_names.push_back("unknown");
}
for (size_t i = 0; i < icon_names.size(); i++) {
if (icon_names[i][0] == '/') {
if (!access(icon_names[i].c_str(), R_OK))
return icon_names[i];
} else {
icon_file = ggadget::xdg::LookupIconInDefaultTheme(icon_names[i], kDefaultIconSize);
if (icon_file.length()) {
DLOG("Found Icon: %s", icon_file.c_str());
return icon_file;
}
}
}
return icon_file;
}
static QtSystemCursor g_cursor_;
static QtSystemScreen g_screen_;
static ScriptableCursor g_script_cursor_(&g_cursor_);
static ScriptableScreen g_script_screen_(&g_screen_);
} // namespace qt_system_framework
} // namespace framework
} // namespace ggadget
using namespace ggadget;
using namespace ggadget::framework;
using namespace ggadget::framework::qt_system_framework;
extern "C" {
bool Initialize() {
LOGI("Initialize qt_system_framework extension.");
return true;
}
void Finalize() {
LOGI("Finalize qt_system_framework extension.");
}
bool RegisterFrameworkExtension(ScriptableInterface *framework,
Gadget *gadget) {
LOGI("Register qt_system_framework extension.");
ASSERT(framework && gadget);
if (!framework)
return false;
RegisterableInterface *reg_framework = framework->GetRegisterable();
if (!reg_framework) {
LOG("Specified framework is not registerable.");
return false;
}
ScriptableInterface *system = NULL;
// Gets or adds system object.
ResultVariant prop = framework->GetProperty("system");
if (prop.v().type() != Variant::TYPE_SCRIPTABLE) {
// property "system" is not available or have wrong type, then add one
// with correct type.
// Using SharedScriptable here, so that it can be destroyed correctly
// when framework is destroyed.
system = new SharedScriptable<UINT64_C(0xdf78c12fc974489c)>();
reg_framework->RegisterVariantConstant("system", Variant(system));
} else {
system = VariantValue<ScriptableInterface *>()(prop.v());
}
if (!system) {
LOG("Failed to retrieve or add framework.system object.");
return false;
}
RegisterableInterface *reg_system = system->GetRegisterable();
if (!reg_system) {
LOG("framework.system object is not registerable.");
return false;
}
// Check permissions.
const Permissions *permissions = gadget->GetPermissions();
if (permissions->IsRequiredAndGranted(Permissions::FILE_READ)) {
QtSystemBrowseForFileHelper *helper =
new QtSystemBrowseForFileHelper(framework, gadget);
reg_framework->RegisterMethod("BrowseForFile",
NewSlotWithDefaultArgs(
NewSlot(helper, &QtSystemBrowseForFileHelper::BrowseForFile),
kBrowseForFileDefaultArgs));
reg_framework->RegisterMethod("BrowseForFiles",
NewSlotWithDefaultArgs(
NewSlot(helper, &QtSystemBrowseForFileHelper::BrowseForFiles),
kBrowseForFilesDefaultArgs));
reg_system->RegisterMethod("getFileIcon",
NewSlot(ggadget::framework::qt_system_framework::GetFileIcon));
} else {
DLOG("No permission to read file.");
}
if (permissions->IsRequiredAndGranted(Permissions::DEVICE_STATUS)) {
reg_system->RegisterVariantConstant("cursor",
Variant(&g_script_cursor_));
reg_system->RegisterVariantConstant("screen",
Variant(&g_script_screen_));
} else {
DLOG("No permission to access device status.");
}
return true;
}
}
| apache-2.0 |
sihrc/Personal-Code-Bin | project-euler/problem_289.cpp | 832 | /*
Eulerian Cycles
Problem 289
Let C(x,y) be a circle passing through the points (x, y), (x, y+1), (x+1, y) and (x+1, y+1).
For positive integers m and n, let E(m,n) be a configuration which consists of the m·n circles:
{ C(x,y): 0 ≤ x < m, 0 ≤ y < n, x and y are integers }
An Eulerian cycle on E(m,n) is a closed path that passes through each arc exactly once.
Many such paths are possible on E(m,n), but we are only interested in those which are not self-crossing:
A non-crossing path just touches itself at lattice points, but it never crosses itself.
The image below shows E(3,3) and an example of an Eulerian non-crossing path.
Let L(m,n) be the number of Eulerian non-crossing paths on E(m,n).
For example, L(1,2) = 2, L(2,2) = 37 and L(3,3) = 104290.
Find L(6,10) mod 1010.
*/ | apache-2.0 |
zengboming/JAVA | 第六组第六题/src/grade/book/Majors.java | 3358 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package grade.book;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author Cogallen
*/
@Entity
@Table(name = "majors", catalog = "gradeBook", schema = "")
@NamedQueries({
@NamedQuery(name = "Majors.findAll", query = "SELECT m FROM Majors m"),
@NamedQuery(name = "Majors.findByCode", query = "SELECT m FROM Majors m WHERE m.code = :code"),
@NamedQuery(name = "Majors.findByMajor", query = "SELECT m FROM Majors m WHERE m.major = :major"),
@NamedQuery(name = "Majors.findByShortName", query = "SELECT m FROM Majors m WHERE m.shortName = :shortName")})
public class Majors implements Serializable {
@Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "Code")
private Integer code;
@Column(name = "Major")
private String major;
@Column(name = "shortName")
private String shortName;
public Majors() {
}
public Majors(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
Integer oldCode = this.code;
this.code = code;
changeSupport.firePropertyChange("code", oldCode, code);
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
String oldMajor = this.major;
this.major = major;
changeSupport.firePropertyChange("major", oldMajor, major);
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
String oldShortName = this.shortName;
this.shortName = shortName;
changeSupport.firePropertyChange("shortName", oldShortName, shortName);
}
@Override
public int hashCode() {
int hash = 0;
hash += (code != null ? code.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Majors)) {
return false;
}
Majors other = (Majors) object;
if ((this.code == null && other.code != null) || (this.code != null && !this.code.equals(other.code))) {
return false;
}
return true;
}
@Override
public String toString() {
return "grade.book.Majors[ code=" + code + " ]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
| apache-2.0 |
little-cui/service-center | syncer/serf/serf_test.go | 4392 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package serf
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/apache/servicecomb-service-center/pkg/log"
"github.com/hashicorp/serf/serf"
"github.com/stretchr/testify/assert"
)
func TestSerfServer(t *testing.T) {
svr := defaultServer()
ctx, cancel := context.WithCancel(context.Background())
err := startServer(ctx, svr)
assert.Nil(t, err)
err = svr.UserEvent("test-event", []byte("test-data"))
assert.Nil(t, err)
_, err = svr.Join([]string{"127.0.0.1:35151"})
assert.Nil(t, err)
list := svr.MembersByTags(map[string]string{"test-key": "test-value"})
assert.Equal(t, 0, len(list))
self := svr.LocalMember()
assert.NotNil(t, self)
m := svr.Member("syncer-test")
assert.NotNil(t, m)
cancel()
svr.Stop()
}
func TestServerFailed(t *testing.T) {
svr := NewServer(
"",
WithNode("syncer-test"),
WithTags(map[string]string{"test-key": "test-value"}),
WithAddTag("added-key", "added-value"),
WithBindAddr("127.0.0.1"),
WithBindPort(35151),
WithAdvertiseAddr(""),
WithAdvertisePort(0),
WithEnableCompression(true),
WithSecretKey([]byte("123456")),
WithLogOutput(os.Stdout),
)
err := startServer(context.Background(), svr)
assert.NotNil(t, err)
svr.Stop()
}
func TestServerEventHandler(t *testing.T) {
svr := defaultServer()
err := startServer(context.Background(), svr)
if err != nil {
log.Error("", err)
}
svr.OnceEventHandler(NewEventHandler(MemberJoinFilter(), func(data ...[]byte) bool {
t.Log("Once event form member join triggered")
return true
}))
// wait for trigger
<-time.After(time.Second)
handler := NewEventHandler(MemberJoinFilter(), func(data ...[]byte) bool {
return false
})
svr.RemoveEventHandler(handler)
svr.AddEventHandler(handler)
svr.AddEventHandler(handler)
svr.RemoveEventHandler(handler)
svr.Stop()
}
func TestUserQuery(t *testing.T) {
svr := defaultServer()
err := startServer(context.Background(), svr)
if err != nil {
log.Error("", err)
}
err = svr.Query("test-query", []byte("test-data"), func(from string, data []byte) {},
WithFilterNodes("syncer-test"),
WithFilterTags(map[string]string{"test-key": "test-value"}),
WithRequestAck(false),
WithRelayFactor(0),
WithTimeout(time.Second),
)
assert.Nil(t, err)
svr.Stop()
}
func TestEventHandler(t *testing.T) {
filter := UserEventFilter("test-event")
ok := filter.Invoke(serf.UserEvent{Name: "test-event", Payload: []byte("test-data")}, func(data ...[]byte) bool {
return true
})
assert.True(t, ok)
ok = filter.Invoke(&serf.Query{Name: "test-event", Payload: []byte("test-data")}, func(data ...[]byte) bool {
return true
})
assert.False(t, ok)
t.Log(filter.String())
filter = QueryFilter("test-event")
ok = filter.Invoke(&serf.Query{Name: "test-event", Payload: []byte("test-data")}, func(data ...[]byte) bool {
return true
})
assert.True(t, ok)
ok = filter.Invoke(serf.UserEvent{Name: "test-event", Payload: []byte("test-data")}, func(data ...[]byte) bool {
return true
})
assert.False(t, ok)
t.Log(filter.String())
filter = MemberLeaveFilter()
filter = MemberFailedFilter()
filter = MemberUpdateFilter()
filter = MemberReapFilter()
}
func defaultServer() *Server {
return NewServer(
"",
WithNode("syncer-test"),
WithBindAddr("127.0.0.1"),
WithBindPort(35151),
)
}
func startServer(ctx context.Context, svr *Server) (err error) {
svr.Start(ctx)
select {
case <-svr.Ready():
case <-svr.Stopped():
err = errors.New("start serf server failed")
case <-time.After(time.Second * 3):
err = errors.New("start serf server timeout")
}
return
}
| apache-2.0 |
aQute-os/biz.aQute.openapi | biz.aQute.openapi.api/src/aQute/openapi/security/environment/api/package-info.java | 97 | @org.osgi.annotation.versioning.Version("1.0.0")
package aQute.openapi.security.environment.api;
| apache-2.0 |
StackableRegiments/analyticalmetlx | src/test/scala/com/metl/data/MeTLCommandSuite.scala | 1697 | package com.metl.data
import org.scalatest._
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
import org.scalatest.matchers.{ShouldMatchers, HavePropertyMatcher, HavePropertyMatchResult}
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.OptionValues._
import net.liftweb.util.Helpers._
import net.liftweb.common._
import scala.xml._
import com.metl.data._
import Privacy._
class MeTLCommandSuite extends FunSuite with GeneratorDrivenPropertyChecks with BeforeAndAfter with ShouldMatchers with MeTLDataGenerators with QueryXml with MeTLCommandMatchers {
var xmlSerializer: GenericXmlSerializer = _
before {
xmlSerializer = new GenericXmlSerializer(EmptyBackendAdaptor)
}
test("extract command from xml") {
val content = <message>
<command>
<author>eecrole</author>
<name>GO_TO_SLIDE</name>
<parameters>
<parameter>2234234</parameter>
</parameters>
</command>
</message>
val result = xmlSerializer.toMeTLData(content).asInstanceOf[MeTLCommand]
result should have (
server (ServerConfiguration.empty),
author ("eecrole"),
timestamp (-1L),
command ("GO_TO_SLIDE"),
commandParameters (List("2234234"))
)
}
test("serialize MeTLCommand to xml") {
forAll (genCommand) { (genComm: MeTLCommand) =>
implicit val xml = xmlSerializer.fromMeTLCommand(genComm)
genComm should have (
author (queryXml[String]("author")),
command (queryXml[String]("name")),
commandParameters (xmlSerializer.getListOfStringsByNameWithin(xml, "parameter", "parameters"))
)
}
}
}
| apache-2.0 |
romanchyla/pylucene-trunk | test/BaseTestRangeFilter.py | 3541 | # ====================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ====================================================================
from random import seed, randint
from unittest import TestCase
from lucene import *
class BaseTestRangeFilter(TestCase):
def __init__(self, *args):
super(BaseTestRangeFilter, self).__init__(*args)
#
# Collation interacts badly with hyphens -- collation produces
# different ordering than Unicode code-point ordering -- so two
# indexes are created: one which can't have negative random
# integers, for testing collated ranges, and the other which can
# have negative random integers, for all other tests.
#
self.MAX_INT = 0x7fffffff
class TestIndex(object):
def __init__(_self, minR, maxR, allowNegativeRandomInts):
_self.minR = minR
_self.maxR = maxR
_self.allowNegativeRandomInts = allowNegativeRandomInts
_self.index = RAMDirectory()
self.signedIndex = TestIndex(self.MAX_INT, ~self.MAX_INT, True)
self.unsignedIndex = TestIndex(self.MAX_INT, 0, False)
self.minId = 0
self.maxId = 10000
self.build(self.signedIndex)
self.build(self.unsignedIndex)
#
# a simple padding function that should work with any int
#
def pad(self, n):
if n < 0:
return "-%0.10d" % (self.MAX_INT + n + 1)
else:
return "0%0.10d" % n
def build(self, index):
writer = IndexWriter(index.index, SimpleAnalyzer(), True,
IndexWriter.MaxFieldLength.LIMITED)
seed(101)
for d in xrange(self.minId, self.maxId + 1):
doc = Document()
doc.add(Field("id", self.pad(d), Field.Store.YES,
Field.Index.NOT_ANALYZED));
if index.allowNegativeRandomInts:
r = randint(~self.MAX_INT, self.MAX_INT)
else:
r = randint(0, self.MAX_INT)
if index.maxR < r:
index.maxR = r
if r < index.minR:
index.minR = r
doc.add(Field("rand", self.pad(r), Field.Store.YES,
Field.Index.NOT_ANALYZED))
doc.add(Field("body", "body", Field.Store.YES,
Field.Index.NOT_ANALYZED));
writer.addDocument(doc)
writer.commit()
writer.close()
def testPad(self):
tests = [-9999999, -99560, -100, -3, -1, 0, 3, 9, 10, 1000, 999999999]
for i in xrange(0, len(tests) - 1):
a = tests[i]
b = tests[i + 1]
aa = self.pad(a)
bb = self.pad(b)
label = "%s:%s vs %s:%s" %(a, aa, b, bb)
self.assertEqual(len(aa), len(bb), "length of %s" %label)
self.assert_(aa < bb, "compare less than %s" %label)
| apache-2.0 |
sdl/dxa-content-management | Sdl.Web.Tridion.Templates.R2/Data/TargetGroups/Model/TargetGroupCondition.cs | 185 | namespace Sdl.Web.Tridion.Templates.R2.Data.TargetGroups.Model
{
public class TargetGroupCondition : Condition
{
public TargetGroup TargetGroup { get; set; }
}
}
| apache-2.0 |
mitre-cyber-academy/2013-web-400 | cookbooks/challenge/files/default/rails_messaging_app/config/environments/test.rb | 1537 | Railsmessagingapp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| apache-2.0 |
consulo/consulo-scala | src/org/jetbrains/plugins/scala/lang/psi/ScalaPsiImplementationHelper.scala | 2195 | package org.jetbrains.plugins.scala.lang.psi
import api.toplevel.typedef.{ScObject, ScClass, ScTrait}
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.{OrderEntry, ProjectRootManager, ProjectFileIndex}
import com.intellij.psi.{PsiClass, JavaPsiFacade, PsiFile}
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.openapi.module.Module
import impl.ScalaPsiManager
import java.util.List
import org.jetbrains.plugins.scala.extensions.toPsiClassExt
object ScalaPsiImplementationHelper {
def getOriginalClass(psiClass: PsiClass): PsiClass = {
val psiFile: PsiFile = psiClass.getContainingFile
val vFile: VirtualFile = psiFile.getVirtualFile
val project: Project = psiClass.getProject
val idx: ProjectFileIndex = ProjectRootManager.getInstance(project).getFileIndex
if (vFile == null || !idx.isInLibrarySource(vFile)) return psiClass
val orderEntries: List[OrderEntry] = idx.getOrderEntriesForFile(vFile)
val fqn: String = psiClass.qualifiedName
if (fqn == null) return psiClass
val classes: Array[PsiClass] = ScalaPsiManager.instance(project).getCachedClasses(new GlobalSearchScope((project)) {
def compare(file1: VirtualFile, file2: VirtualFile): Int = 0
def contains(file: VirtualFile): Boolean = {
val entries: List[OrderEntry] = idx.getOrderEntriesForFile(file)
var i: Int = 0
while (i < entries.size) {
{
val entry: OrderEntry = entries.get(i)
if (orderEntries.contains(entry)) return true
}
i += 1
}
false
}
def isSearchInModuleContent(aModule: Module): Boolean = false
def isSearchInLibraries: Boolean = true
}, fqn)
if (classes.length == 0) psiClass
else if (classes.length == 1) classes(0)
else {
psiClass match {
case _: ScTrait | _: ScClass =>
classes.find(td => td.isInstanceOf[ScTrait] || td.isInstanceOf[ScClass]).getOrElse(classes(0))
case _: ScObject =>
classes.find(td => td.isInstanceOf[ScObject]).getOrElse(classes(0))
case _ => classes(0)
}
}
}
} | apache-2.0 |
Esri/map-carousel-template | js/nls/cs/resources.js | 547 | define({
"app": {
"title": "Otočná nabídka mapy",
"errors": {
"noMaps": "Tato skupina neobsahuje žádné veřejné webové mapy, které by bylo možné zobrazit",
"noGroup": "Skupina nebyla nalezena",
"createGroup": "Nelze vytvořit skupinu",
"bitly": "Služba bitly slouží ke zkracování adresy URL pro usnadnění sdílení. Pro více informací o vytváření a používání klíče bitly si přečtěte soubor readme.",
"general": "Chyba"
},
"mapcount": "Mapa ${page} z ${total}"
}
}); | apache-2.0 |
pdrados/cas | .github/renovate.js | 296 | module.exports = {
branchPrefix: 'renovate/',
gitAuthor: 'Renovate Bot <bot@renovateapp.com>',
logLevel: 'warn',
onboarding: false,
platform: 'github',
includeForks: true,
repositories: [
'apereo/cas'
],
enabledManagers: ["gradle"],
"gradle": {
"enabled": true
}
};
| apache-2.0 |
annict/annict | db/migrate/20190317000000_update_for_irregular_episodes.rb | 298 | # frozen_string_literal: true
class UpdateForIrregularEpisodes < ActiveRecord::Migration[5.2]
def change
add_column :programs, :irregular, :boolean, default: false, null: false
add_column :program_details, :minimum_episode_generatable_number, :integer, default: 1, null: false
end
end
| apache-2.0 |
abdlquadri/MokiTouch-Android | MokiTouchAndroid/src/main/java/com/moki/touch/cache/DownloadThread.java | 4182 | package com.moki.touch.cache;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.moki.touch.models.ContentObject;
import com.moki.touch.util.UrlUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Copyright (C) 2014 Moki Mobility Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may only use this file in compliance with the license
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class DownloadThread {
private ContentObject mContentObject;
private Downloader mDownloader;
private String filepath;
public DownloadThread(ContentObject contentObject, Downloader downloader, String filePath) {
mContentObject = contentObject;
mDownloader = downloader;
this.filepath = filePath;
downloadContent();
}
public void downloadContent() {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
loadRemoteData(UrlUtil.addHttp(mContentObject.getUrl()), mContentObject.getContentFileName());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mDownloader.downloadComplete(mContentObject);
}
};
task.execute();
}
public File getExternalDirectory() {
String dir = Environment.getExternalStorageDirectory().getAbsolutePath();
File dataDir = new File(dir + filepath);
if (!dataDir.exists())
dataDir.mkdirs();
return dataDir;
}
public String loadRemoteData(String link, String filename) {
File outputFile = null;
try {
Log.i(DownloadThread.class.getSimpleName(), "Downloading File: " + link);
File dataDir = getExternalDirectory();
// Deletes the file if it exists
outputFile = new File(dataDir, filename);
outputFile.delete();
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(outputFile);
URL url = new URL(link);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
//and connect!
urlConnection.connect();
int total = urlConnection.getContentLength();
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
int dataRead = 0;
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
dataRead += bufferLength;
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
} catch (Exception e) {
Log.e(DownloadThread.class.getSimpleName(), "Error Downloading", e);
if (outputFile != null)
outputFile.delete();
return "";
}
return outputFile.getAbsolutePath();
}
}
| apache-2.0 |
OmniKryptec/OmniKryptec-Engine | src/main/java/de/omnikryptec/event/EventSubscription.java | 1050 | /*
* Copyright 2017 - 2019 Roman Borris (pcfreak9000), Paul Hagedorn (Panzer1119)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.omnikryptec.event;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventSubscription {
int priority() default 0;
boolean receiveConsumed() default false;
}
| apache-2.0 |
morgwai/jam | instrumentationExample/src/main/java/pl/morgwai/jam/instrumentation/example/JamExampleListener.java | 974 | /*
* Copyright (C) 2012 Piotr Morgwai Kotarbinski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pl.morgwai.jam.instrumentation.example;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class JamExampleListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new JamExampleServletModule());
}
}
| apache-2.0 |
mirsaeedi/CqrsSample | Kaftar/Kaftar.Core/Data/DataContext/ISetDataContext.cs | 293 | using System.Data.Entity;
using Kaftar.Core.Data.Models;
namespace Kaftar.Core.Data.DataContext
{
public interface ISetDataContext
{
DbSet<TEntity> Set<TEntity>() where TEntity : Entity;
void Update<TEntity>(TEntity entity) where TEntity : Entity;
}
} | apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/repo/Customer1016Repository.java | 284 | package example.repo;
import example.model.Customer1016;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1016Repository extends CrudRepository<Customer1016, Long> {
List<Customer1016> findByLastName(String lastName);
}
| apache-2.0 |
lauthieb/gravitee-management-webui | src/management/application/details/members/application-members.controller.ts | 3469 | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as angular from 'angular';
import ApplicationService from '../../../../services/applications.service';
import NotificationService from '../../../../services/notification.service';
import RoleService from '../../../../services/role.service';
class ApplicationMembersController {
private application: any;
private members: any;
private roles: any;
constructor(
private ApplicationService: ApplicationService,
private NotificationService: NotificationService,
private $mdDialog: angular.material.IDialogService,
private $state: ng.ui.IStateService,
private RoleService: RoleService
) {
'ngInject';
const that = this;
RoleService.list('APPLICATION').then(function (roles) {
that.roles = roles;
});
}
updateMember(member) {
if (member.role) {
this.ApplicationService.addOrUpdateMember(this.application.id, member).then(() => {
this.NotificationService.show(`Member ${member.username} has been updated with role ${member.role}`);
});
}
}
deleteMember(member) {
let index = this.members.indexOf(member);
this.ApplicationService.deleteMember(this.application.id, member.username).then(() => {
this.members.splice(index, 1);
this.NotificationService.show(`${member.username} has been removed`);
});
}
showDeleteMemberConfirm(ev, member) {
ev.stopPropagation();
let that = this;
this.$mdDialog.show({
controller: 'DialogConfirmController',
controllerAs: 'ctrl',
template: require('../../../../components/dialog/confirm.dialog.html'),
clickOutsideToClose: true,
locals: {
title: 'Would you like to remove the member ?',
msg: '',
confirmButton: 'Remove'
}
}).then(function (response) {
if (response) {
that.deleteMember(member);
}
});
}
showAddMemberModal(ev) {
let that = this;
this.$mdDialog.show({
controller: 'DialogAddMemberController',
template: require('./addMember.dialog.html'),
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
locals: {
application: that.application,
applicationMembers: that.members
}
}).then(function (application) {
if (application) {
that.$state.go('management.applications.portal.members', {applicationId: that.application.id}, {reload: true});
}
}, function() {
// You cancelled the dialog
});
}
showPermissionsInformation() {
this.$mdDialog.show({
controller: 'DialogApplicationPermissionsHelpController',
controllerAs: 'ctrl',
template: require('./permissions.dialog.html'),
parent: angular.element(document.body),
clickOutsideToClose:true
});
}
}
export default ApplicationMembersController;
| apache-2.0 |
massakam/pulsar | pulsar-client/src/main/java/org/apache/pulsar/client/impl/NonPersistentAcknowledgmentGroupingTracker.java | 2237 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.common.api.proto.CommandAck.AckType;
/**
* A no-op acknowledgment grouping tracker.
*/
public class NonPersistentAcknowledgmentGroupingTracker implements AcknowledgmentsGroupingTracker {
public static NonPersistentAcknowledgmentGroupingTracker of() {
return INSTANCE;
}
private static final NonPersistentAcknowledgmentGroupingTracker INSTANCE = new NonPersistentAcknowledgmentGroupingTracker();
private NonPersistentAcknowledgmentGroupingTracker() {}
@Override
public boolean isDuplicate(MessageId messageId) {
return false;
}
public CompletableFuture<Void> addAcknowledgment(MessageIdImpl msgId, AckType ackType, Map<String,
Long> properties) {
// no-op
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> addListAcknowledgment(List<MessageId> messageIds, AckType ackType, Map<String, Long> properties) {
// no-op
return CompletableFuture.completedFuture(null);
}
@Override
public void flush() {
// no-op
}
@Override
public void close() {
// no-op
}
@Override
public void flushAndClean() {
// no-op
}
}
| apache-2.0 |
Denive/Digital-Screens | app/src/main/java/com/digital_screens/test_task/di/AppComponent.java | 437 | package com.digital_screens.test_task.di;
import com.digital_screens.test_task.di.modules.AppModule;
import com.digital_screens.test_task.di.modules.UtilsModule;
import com.digital_screens.test_task.presenters.ProgramPresenter;
import javax.inject.Singleton;
import dagger.Component;
@Component(modules = {AppModule.class, UtilsModule.class})
@Singleton
public interface AppComponent {
void inject(ProgramPresenter activity);
}
| apache-2.0 |
Rikkola/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/editors/types/listview/DataTypeListItemTest.java | 50421 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.client.editors.types.listview;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.google.gwtmockito.GwtMockitoTestRunner;
import elemental2.dom.Element;
import elemental2.dom.HTMLElement;
import elemental2.dom.NodeList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.model.ItemDefinition;
import org.kie.workbench.common.dmn.client.editors.types.DataTypeChangedEvent;
import org.kie.workbench.common.dmn.client.editors.types.common.DataType;
import org.kie.workbench.common.dmn.client.editors.types.common.DataTypeManager;
import org.kie.workbench.common.dmn.client.editors.types.listview.common.DataTypeEditModeToggleEvent;
import org.kie.workbench.common.dmn.client.editors.types.listview.common.SmallSwitchComponent;
import org.kie.workbench.common.dmn.client.editors.types.listview.confirmation.DataTypeConfirmation;
import org.kie.workbench.common.dmn.client.editors.types.listview.constraint.DataTypeConstraint;
import org.kie.workbench.common.dmn.client.editors.types.listview.draganddrop.DNDListComponent;
import org.kie.workbench.common.dmn.client.editors.types.listview.validation.DataTypeNameFormatValidator;
import org.kie.workbench.common.dmn.client.editors.types.persistence.ItemDefinitionStore;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType.BOOLEAN;
import static org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType.CONTEXT;
import static org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType.STRING;
import static org.kie.workbench.common.dmn.client.editors.types.persistence.CreationType.ABOVE;
import static org.kie.workbench.common.dmn.client.editors.types.persistence.CreationType.BELOW;
import static org.kie.workbench.common.dmn.client.editors.types.persistence.CreationType.NESTED;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(GwtMockitoTestRunner.class)
public class DataTypeListItemTest {
@Mock
private DataTypeListItem.View view;
@Mock
private DataTypeSelect dataTypeSelectComponent;
@Mock
private DataTypeConstraint dataTypeConstraintComponent;
@Mock
private SmallSwitchComponent dataTypeListComponent;
@Mock
private DataType dataType;
@Mock
private ItemDefinitionStore itemDefinitionStore;
@Mock
private DataTypeList dataTypeList;
@Mock
private DataTypeConfirmation confirmation;
@Mock
private EventSourceMock<DataTypeEditModeToggleEvent> editModeToggleEvent;
@Mock
private DataTypeNameFormatValidator nameFormatValidator;
@Mock
private EventSourceMock<DataTypeChangedEvent> dataTypeChangedEvent;
@Captor
private ArgumentCaptor<DataTypeEditModeToggleEvent> eventArgumentCaptor;
private String structure = "Structure";
private DataTypeManager dataTypeManager;
private DataTypeListItem listItem;
@Before
public void setup() {
dataTypeManager = spy(new DataTypeManager(null, null, itemDefinitionStore, null, null, null, null, null));
doReturn(structure).when(dataTypeManager).structure();
listItem = spy(new DataTypeListItem(view, dataTypeSelectComponent, dataTypeConstraintComponent, dataTypeListComponent, dataTypeManager, confirmation, nameFormatValidator, editModeToggleEvent, dataTypeChangedEvent));
listItem.setup();
listItem.init(dataTypeList);
}
@Test
public void testSetup() {
verify(view).init(listItem);
}
@Test
public void testGetContentElement() {
final HTMLElement expectedElement = mock(HTMLElement.class);
when(view.getElement()).thenReturn(expectedElement);
HTMLElement actualElement = listItem.getContentElement();
assertEquals(expectedElement, actualElement);
}
@Test
public void testSetupDataType() {
final DataType expectedDataType = this.dataType;
final int expectedLevel = 1;
doNothing().when(listItem).setupDragAndDropComponent();
doNothing().when(listItem).setupView();
listItem.setupDataType(expectedDataType, expectedLevel);
final InOrder inOrder = inOrder(listItem);
inOrder.verify(listItem).setupDragAndDropComponent();
inOrder.verify(listItem).setupSelectComponent();
inOrder.verify(listItem).setupListComponent();
inOrder.verify(listItem).setupConstraintComponent();
inOrder.verify(listItem).setupView();
assertEquals(expectedDataType, listItem.getDataType());
assertEquals(expectedLevel, listItem.getLevel());
}
@Test
public void testSetupDragAndDropComponent() {
final DNDListComponent dragAndDropComponent = mock(DNDListComponent.class);
final HTMLElement htmlElement = mock(HTMLElement.class);
final HTMLElement expectedElement = mock(HTMLElement.class);
when(dataTypeList.getDNDListComponent()).thenReturn(dragAndDropComponent);
when(listItem.getContentElement()).thenReturn(htmlElement);
when(dragAndDropComponent.registerNewItem(htmlElement)).thenReturn(expectedElement);
listItem.setupDragAndDropComponent();
final HTMLElement actualElement = listItem.getDragAndDropElement();
assertEquals(expectedElement, actualElement);
}
@Test
public void testSetupConstraintComponent() {
final DataType dataType = mock(DataType.class);
doReturn(dataType).when(listItem).getDataType();
listItem.setupConstraintComponent();
verify(dataTypeConstraintComponent).init(listItem);
verify(listItem).refreshConstraintComponent();
}
@Test
public void testSetupListComponentWhenDataTypeIsList() {
final DataType dataType = mock(DataType.class);
final boolean isList = true;
when(dataType.isList()).thenReturn(isList);
doReturn(dataType).when(listItem).getDataType();
listItem.setupListComponent();
verify(dataTypeListComponent).setValue(isList);
verify(listItem).refreshListYesLabel();
}
@Test
public void testSetupListComponentWhenDataTypeIsNotList() {
final DataType dataType = mock(DataType.class);
final boolean isList = false;
when(dataType.isList()).thenReturn(isList);
doReturn(dataType).when(listItem).getDataType();
listItem.setupListComponent();
verify(dataTypeListComponent).setValue(isList);
verify(listItem).refreshListYesLabel();
}
@Test
public void testSetupSelectComponent() {
final DataType dataType = mock(DataType.class);
doReturn(dataType).when(listItem).getDataType();
listItem.setupSelectComponent();
verify(dataTypeSelectComponent).init(listItem, dataType);
}
@Test
public void testSetupView() {
final DataType dataType = mock(DataType.class);
when(listItem.getDataType()).thenReturn(dataType);
doNothing().when(listItem).setupIndentationLevel();
doNothing().when(listItem).hideTooltips();
listItem.setupView();
verify(view).setupSelectComponent(dataTypeSelectComponent);
verify(view).setupConstraintComponent(dataTypeConstraintComponent);
verify(view).setupListComponent(dataTypeListComponent);
verify(view).setDataType(dataType);
verify(listItem).setupIndentationLevel();
verify(listItem).hideTooltips();
}
@Test
public void testExpandOrCollapseSubTypesWhenViewIsCollapsed() {
when(view.isCollapsed()).thenReturn(true);
listItem.expandOrCollapseSubTypes();
verify(listItem).expand();
}
@Test
public void testExpandOrCollapseSubTypesWhenViewIsNotCollapsed() {
when(view.isCollapsed()).thenReturn(false);
listItem.expandOrCollapseSubTypes();
verify(listItem).collapse();
}
@Test
public void testCollapse() {
listItem.collapse();
verify(view).collapse();
}
@Test
public void testExpand() {
listItem.expand();
verify(view).expand();
}
@Test
public void testRefreshSubItems() {
final DataType dataType = mock(DataType.class);
final List<DataType> dataTypes = singletonList(dataType);
listItem.refreshSubItems(dataTypes, true);
verify(dataTypeList).refreshSubItemsFromListItem(listItem, dataTypes);
verify(listItem, never()).expandOrCollapseSubTypes();
verify(view).enableFocusMode();
verify(view).toggleArrow(anyBoolean());
}
@Test
public void testRefreshSubItemsNotSetFocus() {
final DataType dataType = mock(DataType.class);
final List<DataType> dataTypes = singletonList(dataType);
listItem.refreshSubItems(dataTypes, false);
verify(dataTypeList).refreshSubItemsFromListItem(listItem, dataTypes);
verify(listItem, never()).expandOrCollapseSubTypes();
verify(view, never()).enableFocusMode();
verify(view).toggleArrow(anyBoolean());
}
@Test
public void testEnableEditMode() {
final DataType dataType = mock(DataType.class);
final String expectedName = "name";
final String expectedType = "type";
final String expectedConstraint = "constraint";
final boolean expectedIsList = true;
final String expectedConstraintType = "";
doReturn(dataType).when(listItem).getDataType();
when(dataType.getName()).thenReturn(expectedName);
when(dataType.getType()).thenReturn(expectedType);
when(dataType.getConstraint()).thenReturn(expectedConstraint);
when(dataType.isList()).thenReturn(expectedIsList);
when(view.isOnFocusMode()).thenReturn(false);
listItem.enableEditMode();
assertEquals(expectedName, listItem.getOldName());
assertEquals(expectedType, listItem.getOldType());
assertEquals(expectedConstraint, listItem.getOldConstraint());
assertEquals(expectedIsList, listItem.getOldIsList());
assertEquals(expectedConstraintType, listItem.getOldConstraintType());
verify(view).showSaveButton();
verify(view).showDataTypeNameInput();
verify(view).enableFocusMode();
verify(view).hideListYesLabel();
verify(view).showListContainer();
verify(dataTypeSelectComponent).enableEditMode();
verify(dataTypeConstraintComponent).enableEditMode();
verify(editModeToggleEvent).fire(eventArgumentCaptor.capture());
verify(dataTypeList).fireOnDataTypeListItemUpdateCallback(listItem);
assertTrue(eventArgumentCaptor.getValue().isEditModeEnabled());
}
@Test
public void testEnableEditModeWhenDataTypeListItemIsAlreadyOnEditMode() {
when(view.isOnFocusMode()).thenReturn(true);
listItem.enableEditMode();
verify(view, never()).showSaveButton();
verify(view, never()).showDataTypeNameInput();
verify(view, never()).enableFocusMode();
verify(view, never()).hideListYesLabel();
verify(view, never()).showListContainer();
verify(dataTypeSelectComponent, never()).enableEditMode();
verify(dataTypeConstraintComponent, never()).enableEditMode();
verify(editModeToggleEvent, never()).fire(any());
verify(dataTypeList, never()).fireOnDataTypeListItemUpdateCallback(any(DataTypeListItem.class));
}
@Test
public void testDisableEditMode() {
when(view.isOnFocusMode()).thenReturn(true);
doNothing().when(listItem).discardNewDataType();
doNothing().when(listItem).closeEditMode();
doNothing().when(listItem).hideTooltips();
listItem.disableEditMode();
verify(listItem).discardNewDataType();
verify(listItem).closeEditMode();
verify(listItem).hideTooltips();
}
@Test
public void testDisableEditModeWhenDataTypeListItemIsNotOnEditMode() {
when(view.isOnFocusMode()).thenReturn(false);
listItem.disableEditMode();
verify(listItem, never()).discardNewDataType();
verify(listItem, never()).closeEditMode();
verify(listItem, never()).hideTooltips();
}
@Test
public void testSaveAndCloseEditModeWhenDataTypeIsValid() {
final DataType dataType = spy(makeDataType());
final DataType updatedDataType = spy(makeDataType());
final Command doSaveAndCloseCommand = mock(Command.class);
final Command doDisableEditMode = mock(Command.class);
doReturn(dataType).when(listItem).getDataType();
doReturn(updatedDataType).when(listItem).updateProperties(dataType);
doReturn(true).when(updatedDataType).isValid();
doReturn(doSaveAndCloseCommand).when(listItem).doValidateDataTypeNameAndSave(updatedDataType);
doReturn(doDisableEditMode).when(listItem).doDisableEditMode();
listItem.saveAndCloseEditMode();
verify(confirmation).ifDataTypeDoesNotHaveLostSubDataTypes(updatedDataType, doSaveAndCloseCommand, doDisableEditMode);
}
@Test
public void testDoDisableEditMode() {
doNothing().when(listItem).disableEditMode();
listItem.doDisableEditMode().execute();
verify(listItem).disableEditMode();
}
@Test
public void testSaveAndCloseEditModeWhenDataTypeIsNotValid() {
final DataType dataType = spy(makeDataType());
final DataType updatedDataType = spy(makeDataType());
doReturn(dataType).when(listItem).getDataType();
doReturn(updatedDataType).when(listItem).updateProperties(dataType);
doReturn(false).when(updatedDataType).isValid();
listItem.saveAndCloseEditMode();
verify(confirmation, never()).ifDataTypeDoesNotHaveLostSubDataTypes(any(), any(), any());
verify(listItem).discardDataTypeProperties();
}
@Test
public void testDoValidateDataTypeNameAndSave() {
final DataType dataType = spy(makeDataType());
final Command saveAndCloseEditMode = mock(Command.class);
doReturn(saveAndCloseEditMode).when(listItem).doSaveAndCloseEditMode(dataType);
listItem.doValidateDataTypeNameAndSave(dataType).execute();
verify(nameFormatValidator).ifIsValid(dataType, saveAndCloseEditMode);
}
@Test
public void testDoSaveAndCloseEditMode() {
final DataType dataType = spy(makeDataType());
final List<DataType> updatedDataTypes = singletonList(makeDataType());
final String referenceDataTypeHash = "referenceDataTypeHash";
final String newDataTypeHash = "newDataTypeHash";
doReturn(updatedDataTypes).when(listItem).persist(dataType);
doReturn(dataType).when(listItem).getDataType();
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(dataType, referenceDataTypeHash);
doNothing().when(listItem).insertNewFieldIfDataTypeIsStructure(newDataTypeHash);
when(dataTypeList.calculateParentHash(dataType)).thenReturn(referenceDataTypeHash);
listItem.doSaveAndCloseEditMode(dataType).execute();
verify(dataTypeList).refreshItemsByUpdatedDataTypes(updatedDataTypes);
verify(listItem).closeEditMode();
verify(dataTypeList).fireOnDataTypeListItemUpdateCallback(newDataTypeHash);
verify(listItem).insertNewFieldIfDataTypeIsStructure(newDataTypeHash);
verify(listItem).fireDataChangedEvent();
}
@Test
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructure() {
final DataTypeListItem newListItem = mock(DataTypeListItem.class);
final DataType dataType = mock(DataType.class);
final String hash = "hash";
when(newListItem.getDataType()).thenReturn(dataType);
when(dataType.hasSubDataTypes()).thenReturn(false);
when(newListItem.isStructureType()).thenReturn(true);
when(dataTypeList.findItemByDataTypeHash(hash)).thenReturn(Optional.of(newListItem));
listItem.insertNewFieldIfDataTypeIsStructure(hash);
verify(dataTypeList).insertNestedField(hash);
}
@Test
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructureButHasFields() {
final DataTypeListItem newListItem = mock(DataTypeListItem.class);
final DataType dataType = mock(DataType.class);
final String hash = "hash";
when(newListItem.getDataType()).thenReturn(dataType);
when(dataType.hasSubDataTypes()).thenReturn(true);
when(newListItem.isStructureType()).thenReturn(true);
when(dataTypeList.findItemByDataTypeHash(hash)).thenReturn(Optional.of(newListItem));
listItem.insertNewFieldIfDataTypeIsStructure(hash);
verify(dataTypeList, never()).insertNestedField(anyString());
}
@Test
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsNotStructure() {
final DataTypeListItem newListItem = mock(DataTypeListItem.class);
final DataType dataType = mock(DataType.class);
final String hash = "hash";
when(newListItem.getDataType()).thenReturn(dataType);
when(dataType.hasSubDataTypes()).thenReturn(false);
when(newListItem.isStructureType()).thenReturn(false);
when(dataTypeList.findItemByDataTypeHash(hash)).thenReturn(Optional.of(newListItem));
listItem.insertNewFieldIfDataTypeIsStructure(hash);
verify(dataTypeList, never()).insertNestedField(anyString());
}
@Test
public void testPersist() {
final String uuid = "uuid";
final DataType dataType = spy(makeDataType());
final ItemDefinition itemDefinition = mock(ItemDefinition.class);
final List<DataType> subDataTypes = singletonList(makeDataType());
final List<DataType> affectedDataTypes = emptyList();
when(itemDefinitionStore.get(uuid)).thenReturn(itemDefinition);
when(dataTypeSelectComponent.getSubDataTypes()).thenReturn(subDataTypes);
doReturn(uuid).when(dataType).getUUID();
doReturn(affectedDataTypes).when(dataType).update();
listItem.persist(dataType);
final InOrder inOrder = inOrder(dataTypeManager, dataType);
inOrder.verify(dataTypeManager).from(dataType);
inOrder.verify(dataTypeManager).withSubDataTypes(subDataTypes);
inOrder.verify(dataTypeManager).get();
inOrder.verify(dataType).update();
}
@Test
public void testDiscardNewDataType() {
final DataType dataType = spy(makeDataType());
final List<DataType> subDataTypes = Collections.emptyList();
doNothing().when(listItem).setupSelectComponent();
doNothing().when(listItem).setupListComponent();
doNothing().when(listItem).setupIndentationLevel();
doNothing().when(listItem).refreshSubItems(subDataTypes, true);
doReturn(subDataTypes).when(dataType).getSubDataTypes();
doReturn(dataType).when(listItem).discardDataTypeProperties();
listItem.discardNewDataType();
verify(view).setDataType(dataType);
verify(listItem).setupListComponent();
verify(listItem).setupSelectComponent();
verify(listItem).setupConstraintComponent();
verify(listItem).refreshSubItems(subDataTypes, true);
verify(listItem).setupIndentationLevel();
}
@Test
public void testDiscardDataTypeProperties() {
final DataType dataType = spy(makeDataType());
final String expectedName = "name";
final String expectedType = "type";
final String expectedConstraint = "constraint";
final String expectedConstraintType = "enumeration";
final boolean expectedIsList = true;
doReturn(dataType).when(listItem).getDataType();
doReturn(expectedName).when(listItem).getOldName();
doReturn(expectedType).when(listItem).getOldType();
doReturn(expectedConstraint).when(listItem).getOldConstraint();
doReturn(expectedIsList).when(listItem).getOldIsList();
doReturn(expectedConstraintType).when(listItem).getOldConstraintType();
listItem.discardDataTypeProperties();
assertEquals(expectedName, dataType.getName());
assertEquals(expectedType, dataType.getType());
assertEquals(expectedConstraint, dataType.getConstraint());
assertEquals(expectedIsList, dataType.isList());
assertEquals(expectedConstraintType, dataType.getConstraintType().value());
}
@Test
public void testCloseEditMode() {
doReturn(dataType).when(listItem).getDataType();
listItem.closeEditMode();
verify(view).showEditButton();
verify(view).hideDataTypeNameInput();
verify(view).disableFocusMode();
verify(view).hideListContainer();
verify(listItem).refreshListYesLabel();
verify(dataTypeSelectComponent).disableEditMode();
verify(dataTypeConstraintComponent).disableEditMode();
verify(editModeToggleEvent).fire(eventArgumentCaptor.capture());
assertFalse(eventArgumentCaptor.getValue().isEditModeEnabled());
}
@Test
public void testRefreshListYesLabelWhenDataTypeIsList() {
doReturn(dataType).when(listItem).getDataType();
when(dataType.isList()).thenReturn(true);
listItem.refreshListYesLabel();
verify(view).showListYesLabel();
}
@Test
public void testRefreshListYesLabelWhenDataTypeIsNotList() {
doReturn(dataType).when(listItem).getDataType();
when(dataType.isList()).thenReturn(false);
listItem.refreshListYesLabel();
verify(view).hideListYesLabel();
}
@Test
public void testUpdateProperties() {
final DataType dataType = spy(makeDataType());
final String uuid = "uuid";
final String expectedName = "name";
final String expectedType = "type";
final String expectedConstraint = "constraint";
final boolean expectedList = true;
final ItemDefinition itemDefinition = mock(ItemDefinition.class);
when(dataType.getUUID()).thenReturn(uuid);
when(itemDefinitionStore.get(uuid)).thenReturn(itemDefinition);
when(view.getName()).thenReturn(expectedName);
when(dataTypeSelectComponent.getValue()).thenReturn(expectedType);
when(dataTypeConstraintComponent.getValue()).thenReturn(expectedConstraint);
when(dataTypeListComponent.getValue()).thenReturn(expectedList);
when(dataTypeManager.get()).thenReturn(dataType);
final DataType updatedDataType = listItem.updateProperties(dataType);
assertEquals(expectedName, updatedDataType.getName());
assertEquals(expectedType, updatedDataType.getType());
assertEquals(expectedConstraint, updatedDataType.getConstraint());
assertEquals(expectedList, updatedDataType.isList());
}
@Test
public void testRefresh() {
final DataType dataType = spy(makeDataType());
final String expectedConstraint = "constraint";
final String expectedName = "name";
doReturn(expectedConstraint).when(dataType).getConstraint();
doReturn(expectedName).when(dataType).getName();
doReturn(dataType).when(listItem).getDataType();
doNothing().when(listItem).hideTooltips();
listItem.refresh();
verify(dataTypeSelectComponent).refresh();
verify(dataTypeSelectComponent).init(listItem, dataType);
verify(dataTypeConstraintComponent).refreshView();
verify(view).setName(expectedName);
verify(listItem).setupListComponent();
verify(listItem).setupConstraintComponent();
verify(listItem).hideTooltips();
}
@Test
public void testRemove() {
final DataType dataType = mock(DataType.class);
final Command command = mock(Command.class);
doReturn(dataType).when(listItem).getDataType();
doReturn(command).when(listItem).removeItem();
listItem.remove();
verify(confirmation).ifIsNotReferencedDataType(dataType, command);
}
@Test
public void testRemoveItem() {
final Command command = listItem.removeItem();
doNothing().when(listItem).destroyWithDependentTypes();
command.execute();
verify(dataTypeList).disableEditModeForChildren(listItem);
verify(listItem).destroyWithDependentTypes();
}
@Test
public void testDestroy() {
final DataType dataType = mock(DataType.class);
final DataType dataType0 = mock(DataType.class);
final DataType dataType1 = mock(DataType.class);
final DataType dataType2 = mock(DataType.class);
final DataType dataType3 = mock(DataType.class);
final List<DataType> destroyedDataTypes = new ArrayList<>(asList(dataType0, dataType1, dataType2, dataType3));
final List<DataType> removedDataTypes = asList(dataType1, dataType2);
doReturn(destroyedDataTypes).when(dataType).destroy();
doReturn(removedDataTypes).when(listItem).removeTopLevelDataTypes(destroyedDataTypes);
doReturn(dataType).when(listItem).getDataType();
doNothing().when(listItem).hideTooltips();
listItem.destroy().execute();
verify(dataTypeList).refreshItemsByUpdatedDataTypes(asList(dataType0, dataType3));
verify(listItem).fireDataChangedEvent();
verify(listItem).hideTooltips();
}
@Test
public void testDestroyWithDependentTypes() {
final DataType dataType = mock(DataType.class);
final DataType dataType0 = mock(DataType.class);
final DataType dataType1 = mock(DataType.class);
final List<DataType> removedDataTypes = asList(dataType0, dataType1);
when(dataType.destroy()).thenReturn(removedDataTypes);
doReturn(dataType).when(listItem).getDataType();
doNothing().when(listItem).destroy(any());
listItem.destroyWithDependentTypes();
verify(listItem).destroy(removedDataTypes);
}
@Test
public void testDestroyWithoutDependentTypes() {
final DataType dataType = mock(DataType.class);
final DataType dataType0 = mock(DataType.class);
final List<DataType> removedDataTypes = asList(dataType0);
when(dataType.destroyWithoutDependentTypes()).thenReturn(removedDataTypes);
doReturn(dataType).when(listItem).getDataType();
doNothing().when(listItem).destroy(any());
listItem.destroyWithoutDependentTypes();
verify(listItem).destroy(removedDataTypes);
}
@Test
public void testRemoveTopLevelDataTypesWhenItemDataTypeIsDestroyedDataType() {
final DataType dataType = mock(DataType.class);
final DataType dataType0 = mock(DataType.class);
final DataType dataType1 = mock(DataType.class);
doReturn(dataType).when(listItem).getDataType();
when(listItem.getDataType()).thenReturn(dataType);
when(dataType.getUUID()).thenReturn("012");
when(dataType.getName()).thenReturn("tCity");
when(dataType.getType()).thenReturn("Structure");
when(dataType.isTopLevel()).thenReturn(true);
when(dataType0.getUUID()).thenReturn("345");
when(dataType0.getName()).thenReturn("tCidade");
when(dataType0.getType()).thenReturn("tCity");
when(dataType0.isTopLevel()).thenReturn(true);
when(dataType1.getUUID()).thenReturn("678");
when(dataType1.getName()).thenReturn("tCompany");
when(dataType1.getType()).thenReturn("Structure");
when(dataType1.isTopLevel()).thenReturn(true);
final List<DataType> actualDataTypes = listItem.removeTopLevelDataTypes(asList(dataType0, dataType1));
final List<DataType> expectedDataTypes = singletonList(dataType0);
verify(dataTypeList).removeItem(dataType0);
assertEquals(expectedDataTypes, actualDataTypes);
}
@Test
public void testRemoveTopLevelDataTypesWhenItemDataTypeIsAReferenceToDestroyedDataType() {
final String uuid = "uuid";
final DataType dataType = mock(DataType.class);
final DataType dataType0 = mock(DataType.class);
final DataType dataType1 = mock(DataType.class);
doReturn(dataType).when(listItem).getDataType();
when(listItem.getDataType()).thenReturn(dataType);
when(dataType.getUUID()).thenReturn(uuid);
when(dataType.getUUID()).thenReturn("012");
when(dataType.getName()).thenReturn("tCity");
when(dataType.getType()).thenReturn("Structure");
when(dataType.isTopLevel()).thenReturn(true);
when(dataType0.getUUID()).thenReturn("012");
when(dataType0.getName()).thenReturn("tCity");
when(dataType0.getType()).thenReturn("Structure");
when(dataType0.isTopLevel()).thenReturn(true);
when(dataType1.getUUID()).thenReturn("678");
when(dataType1.getName()).thenReturn("tCompany");
when(dataType1.getType()).thenReturn("Structure");
when(dataType1.isTopLevel()).thenReturn(true);
final List<DataType> actualDataTypes = listItem.removeTopLevelDataTypes(asList(dataType0, dataType1));
final List<DataType> expectedDataTypes = singletonList(dataType0);
verify(dataTypeList).removeItem(dataType0);
assertEquals(expectedDataTypes, actualDataTypes);
}
@Test
public void testInsertFieldAboveWhenTheNewDataTypeIsTopLevel() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final DataType newDataType = mock(DataType.class);
final DataType reference = mock(DataType.class);
final DataTypeListItem newListItem = mock(DataTypeListItem.class);
final List<DataType> updatedDataTypes = asList(mock(DataType.class), mock(DataType.class));
final String referenceDataTypeHash = "tDataType.id";
final String newDataTypeHash = "tDataType.name";
when(newDataType.isTopLevel()).thenReturn(true);
when(newDataType.create(reference, ABOVE)).thenReturn(updatedDataTypes);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
when(dataTypeList.findItemByDataTypeHash(newDataTypeHash)).thenReturn(Optional.of(newListItem));
when(dataTypeList.calculateParentHash(reference)).thenReturn(referenceDataTypeHash);
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(newDataType, referenceDataTypeHash);
doReturn(dataTypeManager).when(dataTypeManager).fromNew();
doReturn(newDataType).when(dataTypeManager).get();
doReturn(reference).when(listItem).getDataType();
listItem.insertFieldAbove();
verify(listItem).closeEditMode();
verify(dataTypeList).insertAbove(newDataType, reference);
verify(dndListComponent).refreshItemsCSSAndHTMLPosition();
verify(listItem).enableEditModeAndUpdateCallbacks(newDataTypeHash);
}
@Test
public void testInsertFieldAboveWhenTheNewDataTypeIsNotTopLevel() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final DataType newDataType = mock(DataType.class);
final DataType reference = mock(DataType.class);
final DataTypeListItem newListItem = mock(DataTypeListItem.class);
final List<DataType> updatedDataTypes = asList(mock(DataType.class), mock(DataType.class));
final String referenceDataTypeHash = "tDataType.id";
final String newDataTypeHash = "tDataType.name";
when(newDataType.isTopLevel()).thenReturn(false);
when(newDataType.create(reference, ABOVE)).thenReturn(updatedDataTypes);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
when(dataTypeList.findItemByDataTypeHash(newDataTypeHash)).thenReturn(Optional.of(newListItem));
when(dataTypeList.calculateParentHash(reference)).thenReturn(referenceDataTypeHash);
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(newDataType, referenceDataTypeHash);
doReturn(dataTypeManager).when(dataTypeManager).fromNew();
doReturn(newDataType).when(dataTypeManager).get();
doReturn(reference).when(listItem).getDataType();
listItem.insertFieldAbove();
verify(listItem).closeEditMode();
verify(dataTypeList).refreshItemsByUpdatedDataTypes(updatedDataTypes);
verify(dndListComponent).refreshItemsCSSAndHTMLPosition();
verify(listItem).enableEditModeAndUpdateCallbacks(newDataTypeHash);
}
@Test
public void testInsertFieldBelowWhenTheNewDataTypeIsTopLevel() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final DataType newDataType = mock(DataType.class);
final DataType reference = mock(DataType.class);
final List<DataType> updatedDataTypes = asList(mock(DataType.class), mock(DataType.class));
final String referenceDataTypeHash = "tDataType.id";
final String newDataTypeHash = "tDataType.name";
when(newDataType.isTopLevel()).thenReturn(true);
when(newDataType.create(reference, BELOW)).thenReturn(updatedDataTypes);
when(dataTypeList.calculateParentHash(reference)).thenReturn(referenceDataTypeHash);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(newDataType, referenceDataTypeHash);
doReturn(dataTypeManager).when(dataTypeManager).fromNew();
doReturn(newDataType).when(dataTypeManager).get();
doReturn(reference).when(listItem).getDataType();
listItem.insertFieldBelow();
verify(listItem).closeEditMode();
verify(listItem).enableEditModeAndUpdateCallbacks(newDataTypeHash);
verify(dataTypeList).insertBelow(newDataType, reference);
}
@Test
public void testInsertFieldBelowWhenTheNewDataTypeIsNotTopLevel() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final DataType newDataType = mock(DataType.class);
final DataType reference = mock(DataType.class);
final List<DataType> updatedDataTypes = asList(mock(DataType.class), mock(DataType.class));
final String referenceDataTypeHash = "tDataType.id";
final String newDataTypeHash = "tDataType.name";
when(newDataType.isTopLevel()).thenReturn(false);
when(newDataType.create(reference, BELOW)).thenReturn(updatedDataTypes);
when(dataTypeList.calculateParentHash(reference)).thenReturn(referenceDataTypeHash);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(newDataType, referenceDataTypeHash);
doReturn(dataTypeManager).when(dataTypeManager).fromNew();
doReturn(newDataType).when(dataTypeManager).get();
doReturn(reference).when(listItem).getDataType();
listItem.insertFieldBelow();
verify(listItem).closeEditMode();
verify(listItem).enableEditModeAndUpdateCallbacks(newDataTypeHash);
verify(dataTypeList).refreshItemsByUpdatedDataTypes(updatedDataTypes);
}
@Test
public void testInsertNestedField() {
final DataType newDataType = mock(DataType.class);
final DataType reference = mock(DataType.class);
final List<DataType> updatedDataTypes = asList(mock(DataType.class), mock(DataType.class));
final String referenceDataTypeHash = "tDataType.id";
final String newDataTypeHash = "tDataType.id.value";
when(newDataType.create(reference, NESTED)).thenReturn(updatedDataTypes);
when(dataTypeList.calculateHash(reference)).thenReturn(referenceDataTypeHash);
doReturn(newDataTypeHash).when(listItem).getNewDataTypeHash(newDataType, referenceDataTypeHash);
doReturn(dataTypeManager).when(dataTypeManager).fromNew();
doReturn(newDataType).when(dataTypeManager).get();
doReturn(reference).when(listItem).getDataType();
listItem.insertNestedField();
verify(dataTypeList).refreshItemsByUpdatedDataTypes(updatedDataTypes);
verify(listItem).enableEditModeAndUpdateCallbacks(newDataTypeHash);
}
@Test
public void testGetNewDataTypeHashWhenReferenceDataTypeHashIsNotEmpty() {
final DataType newDataType = mock(DataType.class);
final String newDataTypeName = "value";
final String referenceDataTypeHash = "tDataType.id";
when(newDataType.getName()).thenReturn(newDataTypeName);
final String actualHash = listItem.getNewDataTypeHash(newDataType, referenceDataTypeHash);
final String expectedHash = "tDataType.id.value";
assertEquals(expectedHash, actualHash);
}
@Test
public void testGetNewDataTypeHashWhenReferenceDataTypeHashIsEmpty() {
final DataType newDataType = mock(DataType.class);
final String newDataTypeName = "value";
final String referenceDataTypeHash = "";
when(newDataType.getName()).thenReturn(newDataTypeName);
final String actualHash = listItem.getNewDataTypeHash(newDataType, referenceDataTypeHash);
final String expectedHash = "value";
assertEquals(expectedHash, actualHash);
}
@Test
public void testRefreshConstraintComponentWhenSelectedTypeIsStructure() {
when(dataTypeSelectComponent.getValue()).thenReturn(structure);
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).disable();
}
@Test
public void testRefreshConstraintComponentWhenSelectedTypeIsBoolean() {
when(dataTypeSelectComponent.getValue()).thenReturn(BOOLEAN.getName());
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).disable();
}
@Test
public void testRefreshConstraintComponentWhenSelectedTypeIsContext() {
when(dataTypeSelectComponent.getValue()).thenReturn(CONTEXT.getName());
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).disable();
}
@Test
public void testRefreshConstraintComponentWhenSelectedTypeIsAList() {
when(dataTypeListComponent.getValue()).thenReturn(true);
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).disable();
}
@Test
public void testRefreshConstraintComponentWhenSelectedTypeIsNotBooleanNeitherStructure() {
when(dataTypeSelectComponent.getValue()).thenReturn(STRING.getName());
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).enable();
}
@Test
public void testRefreshConstraintComponentWhenTypeIsIndirectTypeOfCanNotHaveConstraints() {
doReturn(true).when(listItem).isIndirectCanNotHaveConstraintType();
listItem.refreshConstraintComponent();
verify(dataTypeConstraintComponent).disable();
}
@Test
public void testIsIndirectTypeOfWhenIsBoolean() {
final String currentValue = "tIndirectBoolean";
final DataType dataType1 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1);
when(dataType1.getName()).thenReturn(currentValue);
when(dataType1.getType()).thenReturn(BOOLEAN.getName());
when(dataTypeSelectComponent.getValue()).thenReturn(currentValue);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsBooleanRecursive() {
// some(tIndirectType) -> tIndirectType(tIndirectBoolean) -> tIndirectBoolean(boolean)
final String indirectType = "tIndirectType";
final String tBoolean = "tIndirectBoolean";
final DataType dataType1 = mock(DataType.class);
final DataType dataType2 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1, dataType2);
when(dataType1.getName()).thenReturn(indirectType);
when(dataType1.getType()).thenReturn(tBoolean);
when(dataType2.getName()).thenReturn(tBoolean);
when(dataType2.getType()).thenReturn(BOOLEAN.getName());
when(dataTypeSelectComponent.getValue()).thenReturn(indirectType);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsStructureRecursive() {
// some(tIndirectType) -> tIndirectType(tIndirectStructure) -> tIndirectStructure(Structure)
final String indirectType = "tIndirectType";
final String tIndirectStructure = "tIndirectStructure";
final DataType dataType1 = mock(DataType.class);
final DataType dataType2 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1, dataType2);
when(dataType1.getName()).thenReturn(indirectType);
when(dataType1.getType()).thenReturn(tIndirectStructure);
when(dataType2.getName()).thenReturn(tIndirectStructure);
when(dataType2.getType()).thenReturn(structure);
when(dataTypeSelectComponent.getValue()).thenReturn(indirectType);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsStructure() {
final String currentValue = "tIndirectStructure";
final DataType dataType1 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1);
when(dataType1.getName()).thenReturn(currentValue);
when(dataType1.getType()).thenReturn(structure);
when(dataTypeSelectComponent.getValue()).thenReturn(currentValue);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsContextRecursive() {
// some(tIndirectType) -> tIndirectType(tIndirectContext) -> tIndirectContext(Context)
final String indirectType = "tIndirectType";
final String tIndirectContext = "tIndirectContext";
final DataType dataType1 = mock(DataType.class);
final DataType dataType2 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1, dataType2);
when(dataType1.getName()).thenReturn(indirectType);
when(dataType1.getType()).thenReturn(tIndirectContext);
when(dataType2.getName()).thenReturn(tIndirectContext);
when(dataType2.getType()).thenReturn(CONTEXT.getName());
when(dataTypeSelectComponent.getValue()).thenReturn(indirectType);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsContext() {
final String currentValue = "tIndirectContext";
final DataType dataType1 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1);
when(dataType1.getName()).thenReturn(currentValue);
when(dataType1.getType()).thenReturn(CONTEXT.getName());
when(dataTypeSelectComponent.getValue()).thenReturn(currentValue);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertTrue(actual);
}
@Test
public void testIsIndirectTypeOfWhenIsOtherType() {
final String currentValue = "tIndirectOtherType";
final DataType dataType1 = mock(DataType.class);
final List<DataType> customDataTypes = asList(dataType1);
when(dataType1.getName()).thenReturn(currentValue);
when(dataType1.getType()).thenReturn(STRING.getName());
when(dataTypeSelectComponent.getValue()).thenReturn(currentValue);
when(dataTypeSelectComponent.getCustomDataTypes()).thenReturn(customDataTypes);
final boolean actual = listItem.isIndirectCanNotHaveConstraintType();
assertFalse(actual);
}
@Test
public void testEnableEditModeAndUpdateCallbacks() {
final String dataTypeHash = "dataTypeHash";
listItem.enableEditModeAndUpdateCallbacks(dataTypeHash);
verify(dataTypeList).enableEditMode(dataTypeHash);
verify(dataTypeList).fireOnDataTypeListItemUpdateCallback(dataTypeHash);
}
@Test
public void testIsReadOnlyWhenItReturnsTrue() {
doReturn(dataType).when(listItem).getDataType();
when(dataType.isReadOnly()).thenReturn(true);
assertTrue(listItem.isReadOnly());
}
@Test
public void testIsReadOnlyWhenItReturnsFalse() {
doReturn(dataType).when(listItem).getDataType();
when(dataType.isReadOnly()).thenReturn(false);
assertFalse(listItem.isReadOnly());
}
@Test
public void testRefreshItemsCSSAndHTMLPosition() {
listItem.refreshItemsCSSAndHTMLPosition();
verify(dataTypeList).refreshItemsCSSAndHTMLPosition();
}
@Test
public void testSetPositionX() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final Element element = mock(Element.class);
final int positionX = 2;
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
listItem.setPositionX(element, positionX);
verify(dndListComponent).setPositionX(element, positionX);
}
@Test
public void testSetPositionY() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final Element element = mock(Element.class);
final int positionY = 2;
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
listItem.setPositionY(element, positionY);
verify(dndListComponent).setPositionY(element, positionY);
}
@Test
public void testGetPositionY() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final Element element = mock(Element.class);
final Integer expectedPositionY = 2;
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
when(dndListComponent.getPositionY(element)).thenReturn(expectedPositionY);
final Integer actualPositionY = listItem.getPositionY(element);
assertEquals(expectedPositionY, actualPositionY);
}
@Test
public void testGetDragAndDropListElement() {
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
final HTMLElement expectedHTMLElement = mock(HTMLElement.class);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
when(dndListComponent.getElement()).thenReturn(expectedHTMLElement);
final HTMLElement actualHTMLElement = listItem.getDragAndDropListElement();
assertEquals(expectedHTMLElement, actualHTMLElement);
}
@Test
public void testSetupIndentationLevel() {
final HTMLElement dragAndDropElement = mock(HTMLElement.class);
final DNDListComponent dndListComponent = mock(DNDListComponent.class);
when(dataTypeList.getDNDListComponent()).thenReturn(dndListComponent);
doReturn(dragAndDropElement).when(listItem).getDragAndDropElement();
doReturn(5).when(listItem).getLevel();
listItem.setupIndentationLevel();
verify(dndListComponent).setPositionX(dragAndDropElement, 4);
}
@Test
public void testHideTooltips() {
final HTMLElement listItems = mock(HTMLElement.class);
final NodeList<Element> tooltips = spy(new NodeList<>());
final Element element0 = mock(Element.class);
final Element element1 = mock(Element.class);
doReturn(element0).when(tooltips).getAt(0);
doReturn(element1).when(tooltips).getAt(1);
tooltips.length = 2;
element0.parentNode = listItems;
element1.parentNode = listItems;
doReturn(listItems).when(dataTypeList).getListItems();
doReturn(tooltips).when(listItems).querySelectorAll(".tooltip");
listItem.hideTooltips();
verify(listItems).removeChild(element0);
verify(listItems).removeChild(element1);
}
private DataType makeDataType() {
return new DataType(null);
}
}
| apache-2.0 |
japaric/linalg.rs | src/ops/add/mat.rs | 5868 | use std::ops::Add;
use assign::AddAssign;
use blas::{Axpy, Gemm, Transpose};
use complex::Complex;
use onezero::{One, Zero};
use ops::{Reduce, self};
use traits::Transpose as _0;
use traits::{Matrix, Slice, SliceMut};
use {Chain, Mat, Scaled, Transposed, SubMat, SubMatMut};
// GEMM
// Combinations:
//
// LHS: Mat, Scaled<Mat>, Scaled<Transposed<Mat>>, Transposed<Mat>
// RHS: Chain, Scaled<Chain>
//
// and the reverse operation
//
// -> 16 implementations
// 1 impls
// Core implementations
impl<'a, T> Add<Scaled<Chain<'a, T>>> for Scaled<Mat<T>> where T: Gemm + One + Zero {
type Output = Mat<T>;
fn add(self, rhs: Scaled<Chain<T>>) -> Mat<T> {
unsafe {
use ops::reduce::MatMulMat::*;
assert_eq_size!(self, rhs);
let Scaled(beta, mut c) = self;
let ref beta = beta;
let Scaled(alpha, chain) = rhs;
let ref alpha = alpha;
let a_mul_b = chain.reduce();
let (ref transa, ref transb, a, b) = match a_mul_b {
M_M(ref lhs, ref rhs) => {
(Transpose::No, Transpose::No, lhs.slice(..), rhs.slice(..))
},
M_SM(ref lhs, (transb, b)) => {
(Transpose::No, transb, lhs.slice(..), b)
}
SM_M((transa, a), ref rhs) => {
(transa, Transpose::No, a, rhs.slice(..))
}
SM_SM((transa, a), (transb, b)) => {
(transa, transb, a, b)
}
};
ops::gemm(transa, transb, alpha, a, b, beta, c.slice_mut(..));
c
}
}
}
// 3 impls
// Secondary implementations
impl<'a, T> Add<Chain<'a, T>> for Scaled<Mat<T>> where T: Gemm + One + Zero {
type Output = Mat<T>;
fn add(self, rhs: Chain<T>) -> Mat<T> {
self + Scaled(T::one(), rhs)
}
}
impl<'a, T> Add<Scaled<Chain<'a, T>>> for Scaled<Transposed<Mat<T>>> where T: Gemm + One + Zero {
type Output = Transposed<Mat<T>>;
fn add(self, rhs: Scaled<Chain<T>>) -> Transposed<Mat<T>> {
(self.t() + rhs.t()).t()
}
}
impl<'a, T> Add<Chain<'a, T>> for Scaled<Transposed<Mat<T>>> where T: Gemm + One + Zero {
type Output = Transposed<Mat<T>>;
fn add(self, rhs: Chain<T>) -> Transposed<Mat<T>> {
self + Scaled(T::one(), rhs)
}
}
// 4 impls
// Reverse implementations
impl<'a, T> Add<Scaled<Mat<T>>> for Scaled<Chain<'a, T>> where T: Gemm + One + Zero {
type Output = Mat<T>;
fn add(self, rhs: Scaled<Mat<T>>) -> Mat<T> {
rhs + self
}
}
impl<'a, T> Add<Scaled<Mat<T>>> for Chain<'a, T> where T: Gemm + One + Zero {
type Output = Mat<T>;
fn add(self, rhs: Scaled<Mat<T>>) -> Mat<T> {
rhs + self
}
}
impl<'a, T> Add<Scaled<Transposed<Mat<T>>>> for Scaled<Chain<'a, T>> where T: Gemm + One + Zero {
type Output = Transposed<Mat<T>>;
fn add(self, rhs: Scaled<Transposed<Mat<T>>>) -> Transposed<Mat<T>> {
rhs + self
}
}
impl<'a, T> Add<Scaled<Transposed<Mat<T>>>> for Chain<'a, T> where T: Gemm + One + Zero {
type Output = Transposed<Mat<T>>;
fn add(self, rhs: Scaled<Transposed<Mat<T>>>) -> Transposed<Mat<T>> {
rhs + self
}
}
// 4 impls
assign!(Mat<T> {
Chain<'a, T> { Gemm, One, Zero },
Scaled<Chain<'a, T>> { Gemm, One, Zero },
});
// 4 impls
assign!(Transposed<Mat<T>> {
Chain<'a, T> { Gemm, One, Zero },
Scaled<Chain<'a, T>> { Gemm, One, Zero },
});
// AXPY
// Combinations:
//
// LHS: Mat, Transposed<Mat>
// RHS: &T, T, &Mat, Scaled<Transposed<SubMat>>, Scaled<SubMat>, &Transposed<Mat>,
// Transposed<SubMat>,
// &Transposed<SubMatMut>, SubMat, &SubMatMut
//
// and the reverse operation
//
// -> 40 implementations
// 18 impls
assign!(half Mat<T> {
&'a T { Axpy, One },
T { Axpy, One },
});
assign!(Mat<T> {
&'a Mat<T> { Axpy, One },
Scaled<Transposed<SubMat<'a, T>>> { Axpy },
Scaled<SubMat<'a, T>> { Axpy },
&'a Transposed<Mat<T>> { Axpy, One },
&'a Transposed<SubMatMut<'b, T>> { Axpy, One },
Transposed<SubMat<'a, T>> { Axpy, One },
SubMat<'a, T> { Axpy, One },
&'a SubMatMut<'b, T> { Axpy, One },
});
// 18 impls
assign!(half Transposed<Mat<T>> {
&'a T { Axpy, One },
T { Axpy, One },
});
assign!(Transposed<Mat<T>> {
&'a Mat<T> { Axpy, One },
Scaled<Transposed<SubMat<'a, T>>> { Axpy },
Scaled<SubMat<'a, T>> { Axpy },
&'a Transposed<Mat<T>> { Axpy, One },
&'a Transposed<SubMatMut<'b, T>> { Axpy, One },
Transposed<SubMat<'a, T>> { Axpy, One },
SubMat<'a, T> { Axpy, One },
&'a SubMatMut<'b, T> { Axpy, One },
});
macro_rules! scalar {
($($t:ty),+) => {
$(
impl<'a> Add<Mat<$t>> for &'a $t {
type Output = Mat<$t>;
fn add(self, mut rhs: Mat<$t>) -> Mat<$t> {
rhs.add_assign(self);
rhs
}
}
impl Add<Mat<$t>> for $t {
type Output = Mat<$t>;
fn add(self, mut rhs: Mat<$t>) -> Mat<$t> {
rhs.add_assign(self);
rhs
}
}
impl<'a> Add<Transposed<Mat<$t>>> for &'a $t {
type Output = Transposed<Mat<$t>>;
fn add(self, mut rhs: Transposed<Mat<$t>>) -> Transposed<Mat<$t>> {
rhs.add_assign(self);
rhs
}
}
impl Add<Transposed<Mat<$t>>> for $t {
type Output = Transposed<Mat<$t>>;
fn add(self, mut rhs: Transposed<Mat<$t>>) -> Transposed<Mat<$t>> {
rhs.add_assign(self);
rhs
}
}
)+
};
}
// 4 impls
scalar!(f32, f64, Complex<f32>, Complex<f64>);
| apache-2.0 |
m-m-m/util | resource/src/main/java/net/sf/mmm/util/resource/api/spi/package-info.java | 829 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
/**
* Provides the SPI (service-provider-interface) for {@link net.sf.mmm.util.resource.api.DataResource data-resources}.
* <a name="documentation"></a>
* <h2>Resource-Util SPI</h2> This package provides the {@link net.sf.mmm.util.resource.api.spi.DataResourceProvider}
* interface. You can write an implementation of this interface (annotated with @Named) to register a custom
* implementation of {@link net.sf.mmm.util.resource.api.DataResource} (or
* {@link net.sf.mmm.util.resource.api.BrowsableResource}) to the
* {@link net.sf.mmm.util.resource.api.DataResourceFactory} (or
* {@link net.sf.mmm.util.resource.api.BrowsableResourceFactory}).
*/
package net.sf.mmm.util.resource.api.spi;
| apache-2.0 |
cloudfoundry-incubator/ducati-daemon | executor/commands/create_veth.go | 545 | package commands
import (
"fmt"
"github.com/cloudfoundry-incubator/ducati-daemon/executor"
)
type CreateVeth struct {
Name string
PeerName string
MTU int
}
func (cv CreateVeth) Execute(context executor.Context) error {
err := context.LinkFactory().CreateVeth(cv.Name, cv.PeerName, cv.MTU)
if err != nil {
return fmt.Errorf("create veth: %s", err)
}
return nil
}
func (cs CreateVeth) String() string {
return fmt.Sprintf("ip link add dev %s mtu %d type veth peer name %s mtu %d", cs.Name, cs.MTU, cs.PeerName, cs.MTU)
}
| apache-2.0 |
tara-sova/qreal | qrtranslations/ru/plugins/robots/robotsMetamodel_ru.ts | 199827 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
<name>QObject</name>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="3608"/>
<source>Body:</source>
<translation>Функция:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="3895"/>
<source>Condition:</source>
<translation>Условие:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4439"/>
<source>Iterations:</source>
<translation>Итераций:</translation>
</message>
<message>
<source>Volume (%):</source>
<translation type="vanished">Громкость (%):</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="804"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2190"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4857"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6367"/>
<source>Wait for Completion:</source>
<translation>Ждать завершения:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1731"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1879"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2027"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4998"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5907"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6056"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6204"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9293"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12643"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12792"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13088"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13360"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13509"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13658"/>
<source>Ports:</source>
<translation>Порты:</translation>
</message>
<message>
<source>X: </source>
<translation type="vanished">X: </translation>
</message>
<message>
<source>Y: </source>
<translation type="vanished">Y: </translation>
</message>
<message>
<source>Radius: </source>
<translation type="vanished">Радиус: </translation>
</message>
<message>
<source>Filled: </source>
<translation type="vanished">Заполнен: </translation>
</message>
<message>
<source>X1: </source>
<translation type="vanished">X1: </translation>
</message>
<message>
<source>Y1: </source>
<translation type="vanished">Y1: </translation>
</message>
<message>
<source>X2: </source>
<translation type="vanished">X2: </translation>
</message>
<message>
<source>Y2: </source>
<translation type="vanished">Y2: </translation>
</message>
<message>
<source>Width: </source>
<translation type="vanished">Ширина: </translation>
</message>
<message>
<source>Height: </source>
<translation type="vanished">Высота: </translation>
</message>
<message>
<source>Power (%):</source>
<translation type="vanished">Мощность (%): </translation>
</message>
<message>
<source>Frequency (Hz):</source>
<translation type="vanished">Частота (Гц):</translation>
</message>
<message>
<source>Duration (ms):</source>
<translation type="vanished">Длительность (мс):</translation>
</message>
<message>
<source>Wait for Back</source>
<translation type="vanished">Ждать Назад</translation>
</message>
<message>
<source>Wait for Enter</source>
<translation type="vanished">Ждать Ввод</translation>
</message>
<message>
<source>Text: </source>
<translation type="vanished">Текст:</translation>
</message>
<message>
<source>Right: </source>
<translation type="vanished">Правая: </translation>
</message>
<message>
<source>Left: </source>
<translation type="vanished">Левая: </translation>
</message>
<message>
<source>Enter: </source>
<translation type="vanished">Центральная: </translation>
</message>
<message>
<source>Cancel: </source>
<translation type="vanished">Нижняя: </translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2607"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2755"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2912"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="3070"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6784"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6932"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7089"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7246"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7403"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7561"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7718"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12931"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14093"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14398"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14555"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14860"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14999"/>
<source>Port:</source>
<translation>Порт:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2614"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4578"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6791"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10984"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11954"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12093"/>
<source>Color:</source>
<translation>Цвет:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6939"/>
<source>Intensity:</source>
<translation>Интенсивность:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2769"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2927"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6946"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7103"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7260"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7418"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7575"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12945"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13804"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14107"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14257"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14412"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14569"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15013"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15592"/>
<source>Sign:</source>
<translation>Считанное значение:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7096"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12938"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14100"/>
<source>Tacho Limit:</source>
<translation>Предел оборотов:</translation>
</message>
<message>
<source>Wait for Escape</source>
<translation type="vanished">Ждать Отмена</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2762"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7253"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14562"/>
<source>Percents:</source>
<translation>Проценты:</translation>
</message>
<message>
<source>Distance (cm):</source>
<translation type="vanished">Расстояние (см):</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2174"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4850"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6351"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7568"/>
<source>Volume:</source>
<translation>Громкость:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8881"/>
<source>Expression:</source>
<translation>Выражение:</translation>
</message>
<message>
<source>Delay (ms):</source>
<translation type="vanished">Задержка (мс):</translation>
</message>
<message>
<source>Angle (%):</source>
<translation type="vanished">Угол (%):</translation>
</message>
<message>
<source>Detect Line by Videocamera</source>
<translation type="vanished">Детектировать линию</translation>
</message>
<message>
<source>StartAngle: </source>
<translation type="vanished">Начальный угол:</translation>
</message>
<message>
<source>SpanAngle: </source>
<translation type="vanished">Конечный угол:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10702"/>
<source>Initialize Videocamera</source>
<translation>Включить видеокамеру</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9585"/>
<source>Line Detector into Variable</source>
<translation>Датчик линии в переменную</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="3747"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8014"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8171"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9595"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14712"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="16030"/>
<source>Variable:</source>
<translation>Переменная:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11123"/>
<source>File name:</source>
<translation>Имя файла:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7871"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11534"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15889"/>
<source>Text:</source>
<translation>Текст:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8464"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11673"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11680"/>
<source>Hull number:</source>
<translation>Бортномер:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1437"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5622"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9883"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10067"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10547"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12232"/>
<source>Width:</source>
<translation>Ширина:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12504"/>
<source>Command:</source>
<translation>Команда:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13797"/>
<source>Acceleration:</source>
<translation>Ускорение:</translation>
</message>
<message>
<source>Acceleration Axis:</source>
<translation type="vanished">Ускорение по оси:</translation>
</message>
<message>
<source>Wait for Down</source>
<translation type="vanished">Ждать Вниз</translation>
</message>
<message>
<source>Wait for Enter</source>
<translation type="vanished">Ждать Ввод</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14250"/>
<source>Degrees/sec:</source>
<translation>Градусы/сек:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2919"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7410"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14405"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15006"/>
<source>Distance:</source>
<translation>Расстояние:</translation>
</message>
<message>
<source>Wait for Left</source>
<translation type="vanished">Ждать Влево</translation>
</message>
<message>
<source>Wait for Power</source>
<translation type="vanished">Ждать Питание</translation>
</message>
<message>
<source>Wait for Right</source>
<translation type="vanished">Ждать Вправо</translation>
</message>
<message>
<source>Angle (degrees):</source>
<translation type="vanished">Угол (в градусах):</translation>
</message>
<message>
<source>Mode</source>
<translation type="vanished">Режим</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9445"/>
<source>Detect by Videocamera</source>
<translation>Детектировать по камере</translation>
</message>
<message>
<source>Detector into Variable</source>
<translation type="vanished">Значение детектора в переменную</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14856"/>
<source>F1</source>
<translation>F1</translation>
</message>
<message>
<source>Wait for Up</source>
<translation type="vanished">Ждать Вверх</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15152"/>
<source>Wait gamepad button</source>
<translation>Ждать кнопки на пульте</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2468"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6645"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13954"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15162"/>
<source>Button:</source>
<translation>Кнопка:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1275"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1423"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5137"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5460"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5608"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7857"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9869"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10053"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10385"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10533"/>
<source>X:</source>
<translation>X:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="950"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1282"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1430"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5144"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5467"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5615"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7864"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9876"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10060"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10392"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10540"/>
<source>Y:</source>
<translation>Y:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="957"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5151"/>
<source>Radius:</source>
<translation>Радиус:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="964"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1451"/>
<source>Filled:</source>
<translation>Заполнен:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1109"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5294"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10219"/>
<source>X1:</source>
<translation>X1:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1116"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5301"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10226"/>
<source>Y1:</source>
<translation>Y1:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1123"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5308"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10233"/>
<source>X2:</source>
<translation>X2:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1130"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5315"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10240"/>
<source>Y2:</source>
<translation>Y2:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1444"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5629"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9890"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10074"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10554"/>
<source>Height:</source>
<translation>Высота:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1738"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="1886"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5914"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6063"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13367"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13516"/>
<source>Power:</source>
<translation>Мощность:</translation>
</message>
<message>
<source>Frequency</source>
<translation type="vanished">Частота</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2167"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6344"/>
<source>Hz</source>
<translation>Гц</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2175"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="5915"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6352"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13368"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13517"/>
<source>%</source>
<translation>%</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2182"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6359"/>
<source>Duration</source>
<translation>Длительность</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2183"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6360"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9021"/>
<source>ms</source>
<translation>мс</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2920"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="7411"/>
<source>cm</source>
<translation>см</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="3754"/>
<source>Wait:</source>
<translation>Дождаться нажатия:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="4300"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8457"/>
<source>Thread:</source>
<translation>Задача:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8021"/>
<source>From:</source>
<translation>От:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8028"/>
<source>To:</source>
<translation>До:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="8178"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="14719"/>
<source>Synchronized:</source>
<translation>Дождаться сообщения:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9020"/>
<source>Delay:</source>
<translation>Задержка</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9301"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12651"/>
<source>°</source>
<translation>°</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9442"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10699"/>
<source>Mode:</source>
<translation>Режим:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9897"/>
<source>Start Angle:</source>
<translation>Начальный угол:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9904"/>
<source>Span Angle:</source>
<translation>Размах:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="10842"/>
<source>Enable Video Streaming</source>
<translation>Запустить видео-трансляцию</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="11262"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15882"/>
<source>File:</source>
<translation>Файл:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="13811"/>
<source>Axis:</source>
<translation>Ось:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15299"/>
<source>Wait for Gamepad Connect</source>
<translation>Ждать подключения пульта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15437"/>
<source>Wait for Gamepad Disconnect</source>
<translation>Ждать отключения пульта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15575"/>
<source>Wait for Gamepad Wheel</source>
<translation>Ждать "руля" на пульте</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="9300"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="12650"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15585"/>
<source>Angle:</source>
<translation>Угол:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="2166"/>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="6343"/>
<source>Frequency:</source>
<translation>Частота:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15731"/>
<source>Wait pad press</source>
<translation>Ждать нажатия пульта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="15741"/>
<source>Pad:</source>
<translation>Пульт:</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/elements.h" line="16037"/>
<source>Value:</source>
<translation>Значение:</translation>
</message>
</context>
<context>
<name>RobotsMetamodelPlugin</name>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="27"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="80"/>
<source>Robot`s Behaviour Diagram</source>
<translation>Диаграмма поведения робота</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="31"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="131"/>
<source>Comment</source>
<translation>Комментарий</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="32"/>
<source>Link</source>
<translation>Линия соединения</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="48"/>
<source>Final Node</source>
<translation>Конец</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="49"/>
<source>Fork</source>
<translation>Параллельные задачи</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="50"/>
<source>Function</source>
<translation>Функция</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="52"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="177"/>
<source>Condition</source>
<translation>Условие</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="53"/>
<source>Initial Node</source>
<translation>Начало</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="56"/>
<source>Loop</source>
<translation>Цикл</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="33"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="59"/>
<source>Beep</source>
<translation>Гудок</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="60"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="108"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="110"/>
<source>Clear Encoder</source>
<translation>Сбросить показания энкодера</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="30"/>
<source>Clear Screen</source>
<translation>Очистить экран</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="34"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="61"/>
<source>Draw Circle</source>
<translation>Нарисовать круг</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="35"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="62"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="91"/>
<source>Draw Line</source>
<translation>Нарисовать линию</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="36"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="63"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="92"/>
<source>Draw Pixel</source>
<translation>Нарисовать точку</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="37"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="64"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="93"/>
<source>Draw Rectangle</source>
<translation>Нарисовать прямоугольник</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="38"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="65"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="111"/>
<source>Motors Backward</source>
<translation>Моторы назад</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="39"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="66"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="112"/>
<source>Motors Forward</source>
<translation>Моторы вперёд</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="40"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="67"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="113"/>
<source>Stop Motors</source>
<translation>Моторы стоп</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="41"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="68"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="97"/>
<source>Play Tone</source>
<translation>Играть звук</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="77"/>
<source>Print Text</source>
<translation>Напечатать текст</translation>
</message>
<message>
<source>Wait for Buttons</source>
<translation type="vanished">Ждать нажатия кнопок</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="43"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="70"/>
<source>Wait for Color</source>
<translation>Ждать цвет</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="71"/>
<source>Wait for Color Intensity</source>
<translation>Ждать интенсивность цвета</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="72"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="109"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="116"/>
<source>Wait for Encoder</source>
<translation>Ждать энкодер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="44"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="73"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="119"/>
<source>Wait for Light</source>
<translation>Ждать свет</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="74"/>
<source>Wait for Sonar Distance</source>
<translation>Ждать сонар</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="75"/>
<source>Wait for Sound Sensor</source>
<translation>Ждать сенсор звука</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="46"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="76"/>
<source>Wait for Touch Sensor</source>
<translation>Ждать сенсор касания</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="82"/>
<source>Subprogram</source>
<translation>Подпрограмма</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="83"/>
<source>Subprogram Diagram</source>
<translation>Подпрограмма</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="85"/>
<source>Timer</source>
<translation>Таймер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="86"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="107"/>
<source>Angular Servo</source>
<translation>Угловой сервомотор</translation>
</message>
<message>
<source>Detect Line by Videocamera</source>
<translation type="vanished">Детектировать линию по видео</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="94"/>
<source>Initialize Videocamera</source>
<translation>Включить видеокамеру</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="96"/>
<source>Led</source>
<translation>Светодиод</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="88"/>
<source>Line Detector into Variable</source>
<translation>Датчик линии в переменную</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="99"/>
<source>Sad Smile</source>
<translation>Грустный смайлик</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="100"/>
<source>Say</source>
<translation>Сказать</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="102"/>
<source>Background Color</source>
<translation>Цвет фона</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="105"/>
<source>Smile</source>
<translation>Смайлик</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="106"/>
<source>System Call</source>
<translation>Системный вызов</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="114"/>
<source>Wait for Accelerometer</source>
<translation>Ждать акселерометр</translation>
</message>
<message>
<source>Wait for "Down" button</source>
<translation type="vanished">Ждать нажатия кнопки "Вниз"</translation>
</message>
<message>
<source>Wait for "Enter" button</source>
<translation type="vanished">Ждать нажатия кнопки "Ввод"</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="117"/>
<source>Wait for Gyroscope</source>
<translation>Ждать гироскоп</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="118"/>
<source>Wait for Infrared Distance</source>
<translation>Ждать ИК датчик расстояния</translation>
</message>
<message>
<source>Wait for "Left" button</source>
<translation type="vanished">Ждать нажатия кнопки "Влево"</translation>
</message>
<message>
<source>Wait for "Power" button</source>
<translation type="vanished">Ждать нажатия кнопки "Питание"</translation>
</message>
<message>
<source>Wait for "Right" button</source>
<translation type="vanished">Ждать нажатия кнопки "Вправо"</translation>
</message>
<message>
<source>Wait for "Escape" button</source>
<translation type="vanished">Ждать нажатия кнопки "Отмена"</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="87"/>
<source>Detect by Videocamera</source>
<translation>Детектировать по камере</translation>
</message>
<message>
<source>Detector into Variable</source>
<translation type="vanished">Значение детектора в переменную</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="89"/>
<source>Draw Arc</source>
<translation>Нарисовать дугу</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="90"/>
<source>Draw Ellipse</source>
<translation>Нарисовать эллипс</translation>
</message>
<message>
<source>Receive message</source>
<translation type="vanished">Получить сообщение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="101"/>
<source>Send message</source>
<translation>Послать сообщение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="103"/>
<source>Painter Color</source>
<translation>Цвет кисти</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="104"/>
<source>Painter Width</source>
<translation>Толщина кисти</translation>
</message>
<message>
<source>Wait for message</source>
<translation type="vanished">Ждать сообщения</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="121"/>
<source>Wait for Motion</source>
<translation>Ждать движения</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="122"/>
<source>Wait for Ultrasonic Distance</source>
<translation>Ждать УЗ датчик расстояния</translation>
</message>
<message>
<source>Wait for "Up" button</source>
<translation type="vanished">Ждать нажатия кнопки "Вверх"</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="129"/>
<source>Variable Initialization</source>
<translation>Инициализация переменной</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="132"/>
<source>Guard</source>
<translation>Условие</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="174"/>
<source>Body</source>
<translation>Тело функции</translation>
</message>
<message>
<source>Initialization</source>
<translation type="vanished">Инициализация</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="179"/>
<source>Iterations</source>
<translation>Итерации</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="162"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="181"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="210"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="229"/>
<source>Volume</source>
<translation>Громкость</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="133"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="163"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="182"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="211"/>
<source>Wait for Completion</source>
<translation>Ждать завершения</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="154"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="157"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="159"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="183"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="202"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="205"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="207"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="246"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="290"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="292"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="296"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="297"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="299"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="301"/>
<source>Ports</source>
<translation>Порты</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="134"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="184"/>
<source>Radius</source>
<translation>Радиус</translation>
</message>
<message>
<source>Prepare Marker</source>
<translation type="vanished">Опустить маркер</translation>
</message>
<message>
<source>Remove Marker</source>
<translation type="vanished">Поднять маркер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="84"/>
<source>Switch</source>
<translation>Выбор</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="135"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="147"/>
<source>Filled</source>
<translation>Заполнен</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="137"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="145"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="151"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="186"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="194"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="199"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="234"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="255"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="260"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="268"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="273"/>
<source>X</source>
<translation>X</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="138"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="146"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="152"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="187"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="195"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="200"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="235"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="256"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="261"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="269"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="274"/>
<source>Y</source>
<translation>Y</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="140"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="189"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="263"/>
<source>X1</source>
<translation>X1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="141"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="190"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="264"/>
<source>X2</source>
<translation>X2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="142"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="191"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="265"/>
<source>Y1</source>
<translation>Y1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="143"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="192"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="266"/>
<source>Y2</source>
<translation>Y2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="148"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="196"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="250"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="257"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="270"/>
<source>Height</source>
<translation>Высота</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="150"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="198"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="254"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="259"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="272"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="286"/>
<source>Width</source>
<translation>Ширина</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="153"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="156"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="201"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="204"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="248"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="275"/>
<source>Mode</source>
<translation>Режим</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="155"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="158"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="203"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="206"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="298"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="300"/>
<source>Power (%)</source>
<translation>Мощность (%)</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="160"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="208"/>
<source>Duration</source>
<translation>Длительность</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="161"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="209"/>
<source>Frequency</source>
<translation>Частота</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="232"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="280"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="327"/>
<source>Text</source>
<translation>Текст</translation>
</message>
<message>
<source>Cancel button clicks</source>
<translation type="vanished">Количество нажатий нижней кнопки</translation>
</message>
<message>
<source>Enter button clicks</source>
<translation type="vanished">Количество нажатий центральной кнопки</translation>
</message>
<message>
<source>Left button clicks</source>
<translation type="vanished">Количество нажатий левой кнопки</translation>
</message>
<message>
<source>Right button clicks</source>
<translation type="vanished">Количество нажатий правой кнопки</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="165"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="180"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="213"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="276"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="283"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="285"/>
<source>Color</source>
<translation>Цвет</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="166"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="168"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="171"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="173"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="214"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="216"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="218"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="222"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="225"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="227"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="230"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="293"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="306"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="312"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="315"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="320"/>
<source>Port</source>
<translation>Порт</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="215"/>
<source>Intensity</source>
<translation>Интенсивность</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="169"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="172"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="217"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="219"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="223"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="226"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="228"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="294"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="304"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="307"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="310"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="313"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="316"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="321"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="324"/>
<source>Sign</source>
<translation>Считанное значение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="220"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="295"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="308"/>
<source>Tacho Limit</source>
<translation>Предел оборотов</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="167"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="221"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="314"/>
<source>Percents</source>
<translation>Проценты</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="170"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="224"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="311"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="319"/>
<source>Distance</source>
<translation>Расстояние</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="241"/>
<source>Devices configuration</source>
<translation>Конфигурация устройств</translation>
</message>
<message>
<source>World model</source>
<translation type="vanished">Модель мира</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="245"/>
<source>Delay (ms)</source>
<translation>Задержка (мс)</translation>
</message>
<message>
<source>Angle (%)</source>
<translation type="vanished">Угол (%)</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="252"/>
<source>SpanAngle</source>
<translation>Размах</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="253"/>
<source>StartAngle</source>
<translation>Начальный угол</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="175"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="238"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="240"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="249"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="318"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="329"/>
<source>Variable</source>
<translation>Переменная</translation>
</message>
<message>
<source>Wait for "Back" button</source>
<translation type="vanished">Ждать нажатия кнопки "Назад"</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="45"/>
<source>Wait for Range Sensor</source>
<translation>Ждать сенсор расстояния</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="47"/>
<source>End if</source>
<translation>Конец условия</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="51"/>
<source>Get Button Code</source>
<translation>Получить код кнопки</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="57"/>
<source>Marker Down</source>
<translation>Опустить маркер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="58"/>
<source>Marker Up</source>
<translation>Поднять маркер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="123"/>
<source>Wait Gamepad Button</source>
<translation>Ждать кнопки на пульте</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="125"/>
<source>Wait for Gamepad Disconnect</source>
<translation>Ждать отключения пульта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="126"/>
<source>Wait for Gamepad Wheel</source>
<translation>Ждать "руля" на пульте</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="127"/>
<source>Wait Pad Press</source>
<translation>Ждать нажатия на пульт</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="244"/>
<source>Expression</source>
<translation>Выражение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="277"/>
<source>File Name</source>
<translation>Имя файла</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="287"/>
<source>Code</source>
<translation>Код</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="288"/>
<source>Command</source>
<translation>Команда</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="302"/>
<source>Acceleration</source>
<translation>Ускорение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="303"/>
<source>Acceleration Axis</source>
<translation>Ускорение по оси</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="309"/>
<source>Degrees/sec</source>
<translation>Градусы/сек</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="164"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="212"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="305"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="322"/>
<source>Button</source>
<translation>Кнопка</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="323"/>
<source>Angle</source>
<translation>Угол</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="325"/>
<source>Pad</source>
<translation>Пульт</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="328"/>
<source>Value</source>
<translation>Значение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="350"/>
<source>Algorithms</source>
<translation>Алгоритмы</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="385"/>
<source>Actions</source>
<translation>Действия</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="176"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="414"/>
<source>Wait</source>
<translation>Ожидание</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="440"/>
<source>Drawing</source>
<translation>Рисование</translation>
</message>
<message>
<source>"Enter some text here..."</source>
<translation type="vanished">"Введите текст..."</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="764"/>
<source>Enter some text here...</source>
<translation>Введите текст...</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="799"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="802"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="845"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="850"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="853"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="858"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="865"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="872"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="880"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="881"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="885"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="886"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="888"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="890"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="898"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="899"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="914"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="924"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="930"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="932"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="935"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="939"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="947"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="809"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="866"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="889"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="891"/>
<source>10</source>
<translation>10</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="794"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="811"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="840"/>
<source>50</source>
<translation>50</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="813"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="837"/>
<source>A, B, C</source>
<translation>A, B, C</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="786"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="789"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="832"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="835"/>
<source>B, C</source>
<translation>B, C</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="787"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="790"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="833"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="836"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="920"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="922"/>
<source>100</source>
<translation>100</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="792"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="793"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="838"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="839"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="870"/>
<source>1000</source>
<translation>1000</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="863"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="864"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="909"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2973"/>
<source>1</source>
<translation>1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="848"/>
<source>B</source>
<translation>B</translation>
</message>
<message>
<source>JE1</source>
<translation type="vanished">JE1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="902"/>
<source>media/beep.wav</source>
<translation>media/beep.wav</translation>
</message>
<message>
<source>JM1, JM2, M1, JM3</source>
<translation type="vanished">JM1, JM2, M1, JM3</translation>
</message>
<message>
<source>M1, JM3</source>
<translation type="vanished">M1, JM3</translation>
</message>
<message>
<source>JM1, JM2, JM3, JM4</source>
<translation type="vanished">JM1, JM2, JM3, JM4</translation>
</message>
<message>
<source>JM3, JM4</source>
<translation type="vanished">JM3, JM4</translation>
</message>
<message>
<source>JB1</source>
<translation type="vanished">JB1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="806"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="867"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="869"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="948"/>
<source>x</source>
<translation>x</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="954"/>
<source>This block can hold text notes that are ignored by generators and interpreters. Use it for improving the diagram readability.</source>
<translation>Блок с текстовыми заметками, которые игнорируются при генерации и интерпретации. Используйте его для повышения наглядности диаграммы.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="955"/>
<source>For creating a link between two elements A and B you can just hover a mouse above A, press the right mouse button and (without releasing it) draw a line to the element B. Alternatively you can just 'pull' a link from a small blue circle next to the element.</source>
<translation>Для того, чтобы создать связь между двумя элементами A и B, можно навести курсор на элемент A, нажать правую кнопку мыши и, не отпуская ее, провести линию до элемента B, либо 'вытащить' связь из кружочка справа от элемента.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="971"/>
<source>The final node of the program. If the program consists of some parallel execution lines the reachment of this block terminates the corresponding execution line. This block can`t have outgoing links.</source>
<translation>Конец программы. Если программа состоит из нескольких параллельных участков выполнения, достижение этого блока завершает соответствующий участок выполнения. У данного блока не может быть исходящих связей.</translation>
</message>
<message>
<source>Separates program execution into a number of threads that will be executed concurrently from the programmers`s point of view. For example in such way signal from sensor and some time interval can be waited synchroniously. This block must have at least two outgoing links.</source>
<translation type="vanished">Разделить выполнение программы на несколько потоков, которые с точки зрения программиста будут выполняться параллельно. Так, например, можно одновременно ждать срабатывания сенсора и истечения временного интервала. Блок должен иметь хотя бы две исходящие связи.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="973"/>
<source>Evaluates a value of the given expression. Also new variables can be defined in this block. See the 'Expressions Syntax' chapter in help for more information about 'Function' block syntax.</source>
<translation>Посчитать значение заданного выражения. Также в данном блоке допускается определение переменных. Подробнее про синтаксис допустимых выражений параметра 'Функция' см. в документации в разделе 'Синтаксис выражений'.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="975"/>
<source>Separates program execution in correspondece with the given condition. The 'Condition' parameter value must be some boolean expression that will determine subsequent program execution line. This block must have two outgoing links, at least one of them must have 'Guard' parameter set to 'true' or 'false'. The execution will be proceed trough the link marked with the guard corresponding to 'Condition' parameter of the block.</source>
<translation>Разделить выполнение программы в соответствии с заданным условием. Значением параметра 'Условие' является некое логическое выражение, на основе значения которого будет осуществлен выбор дальнейшего пути выполнения диаграммы. У данного блока должны быть две исходящие связи, у одной из которых должно быть задано значение параметра 'Условие' (возможные варианты — 'истина' и 'ложь'). При невыполнении данного условия выполнение передается по другой связи.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="976"/>
<source>The entry point of the program execution. Each diagram should have only one such block, it must not have incomming links and it must have only one outgoing link. The interpretation process starts from exactly this block.</source>
<translation>Начальная точка выполнения программы. На каждой диаграмме такой блок должен быть только один, в него не должно быть входящих связей, исходящая связь из этого элемента должна быть только одна. Процесс интерпретации диаграммы начинается именно с этого блока.</translation>
</message>
<message>
<source>This block executes a sequence of blocks for a given number of times. The number of repetitions is specified by the 'Iterations' parameter. This block must have two outgoing links. One of them must be marked with the 'iteration' guard (that means that the property 'Guard' of the link must be set to 'iteration' value). Another outgoing link must be unmarked: the program execution will be proceeded through this link when it will go through our 'Loop' block for the given number of times.</source>
<translation type="vanished">Блок, организующий выполнение последовательности блоков несколько раз. Число повторений задается значением параметра 'Итераций'. Блок должен иметь две исходящие связи, одна из которых должна быть помечена значением 'итерация' (то есть значение параметра 'Условие' должно быть 'итерация'). Другая связь, исходящая из блока 'Цикл', должна оставаться непомеченной: по ней будет осуществляться переход, когда программа пройдет через блок 'Цикл' указанное число раз.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="956"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="982"/>
<source>Plays on the robot a sound with the fixed frequency. There are two parameters. The first one is a loudness of the sound, the second means if program should wait for sound completion or go to next block right away.</source>
<translation>Проиграть на роботе звук с фиксированной частотой. Имеется два параметра. Первый - это громкость звука, второй означает ждать ли завершения проигрывания звука или сразу же перейти к следующему блоку. Допустимые значения — истина и ложь.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="983"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1029"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1031"/>
<source>Nullifies tacho limit of the motors on the given ports.</source>
<translation>Сбросить показания количества оборотов моторов по заданным портам.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="953"/>
<source>Clears everything drawn on the robot`s screen.</source>
<translation>Стереть всё, что нарисовано на экране робота.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="957"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="984"/>
<source>Draws on the robot screen a circle with the given center and radius.</source>
<translation>Нарисовать на экране круг с заданным центром и заданным радиусом.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="958"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="985"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1012"/>
<source>Draws a segment on the robot screen. The parameters specify the ends of the segment.</source>
<translation>Нарисовать на экране отрезок. В качестве параметров блоку указываются концы отрезка.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="959"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="986"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1013"/>
<source>Draws one pixel in the specified coordinates on the robot screen.</source>
<translation>Нарисовать на экране точку в указанных координатах.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="960"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="987"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1014"/>
<source>Draws a rectangle on the robot screen. The parameters specify the coordinates of top-left corner, the width and the height of the rectangle.</source>
<translation>Нарисовать на экране прямоугольник. В качестве параметров указываются координаты левого верхнего угла, ширина и высота прямоугольника.</translation>
</message>
<message>
<source>Enables motors on the given ports in reverse mode with the given power. Ports are specified with A, B or C letters divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the usial mode.</source>
<translation type="vanished">Включить моторы в режиме реверса по заданным портам с заданной мощностью. Порты задаются буквами A, B или C, разделенными запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в обычном режиме.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="962"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="989"/>
<source>Enables motors on the given ports with the given power. Ports are specified with A, B or C letters divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the reverse mode.</source>
<translation>Включить моторы по заданным портам с заданной мощностью. Порты задаются буквами A, B или C, разделенными запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в режиме реверса.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="963"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="990"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1034"/>
<source>Disables motors on the given ports.</source>
<translation>Выключить моторы по заданным портам.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="964"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="991"/>
<source>Plays on the robot a sound with the given frequency and duration. This block is similar to the 'Beep' block wuth the only difference that here you can specify sound parameters.</source>
<translation>Проиграть на роботе звук с заданной частотой и длительностью. Аналогичен блоку 'Гудок', но позволяет задавать параметры звука. Имеется параметр, определяющий, ждать ли завершения проигрывания звука или сразу же перейти к следующему блоку.</translation>
</message>
<message>
<source>Prints a given line in the specified coordinates on the robot`s screen. '$' token can be used in front of the identifier for printing its value. This feature is ignored in case when backslash ('\') is written before the '$' token. Example: '\$a = $a' expression will print '$a = 5' if the value of the variable 'a' is 5.</source>
<translation type="vanished">Напечатать заданную строку в заданных координатах на экране. Можно использовать символ доллара ('$') перед идентификатором переменной для вывода ее значения. Данный сценарий игнорируется, если перед символом доллара стоит обратный слеш ('\'). Пример: строка '\$a = $a' напечатает '$a = 5', если значение переменной a равно 5.</translation>
</message>
<message>
<source>Waits till the given robot`s buttons will be pushed the given number of times. The push counters may be specified separately for each button, the block will continue the execution only when each of counter will be reached.</source>
<translation type="vanished">Ждать, пока заданные кнопки на роботе не будут нажаты заданное количество раз. Счётчики нажатия можно задать для каждой кнопки отдельно, блок продолжит выполнение, только когда все счётчики сработают.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="966"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="993"/>
<source>Waits till the color sensor on the given port will recognize the given color.</source>
<translation>Ждать, пока сенсор цвета в режиме распознавания цветов не вернет указанный цвет.</translation>
</message>
<message>
<source>Waits till the value returned by the color sensor on the given port will be greater or lower then the given in the 'Intensity' parameter value (the intensity is specified in percents, 0 to 100).</source>
<translation type="vanished">Ждать, пока значение, возвращаемое сенсором цвета на указанном порту, не будет сравнимо с указанным в значении параметра 'Интенсивность' (задается в процентах). Еще один парамер — номер порта, к которому подключен сенсор цвета. Также параметром указывается операция, которая будет использоваться для сравнения с введенной интенсивностью.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="995"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1030"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1036"/>
<source>Waits till the tacho limit of the motor on the given port will reach the value of the 'Tacho Limit' parameter.</source>
<translation>Ждать, пока показания счетчика количества оборотов на заданном моторе не достинут указанного в значении параметра 'Предел оборотов'.</translation>
</message>
<message>
<source>Waits for "Escape" button press.</source>
<translation type="vanished">Ждать нажатия на нижнюю кнопку.</translation>
</message>
<message>
<source>Waits till the value returned by the light sensor on the given port will be greater or lower then the given in the 'Percents' parameter value (0 to 100).</source>
<translation type="vanished">Ждать, пока значение, возвращаемое сенсором света на указанном порту, не будет сравнимо с указанным в значении параметра 'Проценты'. Еще один парамер — номер порта, к которому подключен сенсор цвета. Также параметром указывается операция, которая будет использоваться для сравнения со значением параметра 'Проценты'.</translation>
</message>
<message>
<source>Waits till the value returned by the ultrasonic sensor on the given port will be greater or lower then the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation type="vanished">Ждать, пока расстояние, возвращаемое ультразвуковым сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние' (расстояние задается в сантиметрах, от 0 до 255). Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<source>Waits till the loudness obtained by the sound sensor on the given port will be greater or lower then the given value.</source>
<translation type="vanished">Ждать, пока громкость, считанная микрофоном на заданном порту, не будет выше или ниже заданного значения.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="969"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="999"/>
<source>Waits till the touch sensor is pressed. The only parameter is a sensor`s port number (1, 2, 3 or 4).</source>
<translation>Ждать, пока не сработает сенсор касания. Параметром указывается номер порта, к которому подключен сенсор касания. Допустимые значения: 1, 2, 3, 4.</translation>
</message>
<message>
<source>Subprogram call. Subprograms are used for splitting repetitive program parts into a separate diagram and then calling it from main diagram or other subprograms. When this block is added into a diagram it will be suggested to enter subprogram name. The double click on subprogram call block may open the corresponding subprogram diagram. Moreover user palette will appear containing existing subrpograms, they can be dragged into a diagram like the usial blocks.</source>
<translation type="vanished">Вызов подпрограммы. Подпрограммы используются для того, чтобы вынести повторяющиеся фрагменты программы на отдельную диаграмму, а потом вызывать фрагмент программы с этой диаграммы в нескольких местах основной программы или других подпрограмм. При добавлении этого блока на диаграмму будет предложено ввести имя подпрограммы, после чего двойным кликом на блоке можно будет перейти на диаграмму, соответствующую данной подпрограмме. Кроме того, появится дополнительная палитра со всеми подпрограммами, подпрограммы из неё можно перетаскивать на сцену и использовать как обычные блоки.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1006"/>
<source>Waits for a given time in milliseconds.</source>
<translation>Ждать заданное количество времени в миллисекундах.</translation>
</message>
<message>
<source>Manages angular servomotor. Sets up rotation angle on the given port in percents from the maximal rotation angle that is defined in roobt`s configuration file. Values from 0 to 100 are correspond to a clockwise rotation and values from -100 to 0 correspond to counterclockwise rotation.</source>
<translation type="vanished">Управление угловым сервомотором. Выставляет угол поворота по заданному порту в процентах от максимального угла поворота, определённого в конфигурационном файле на роботе. Значения от 0 до 100 соответствуют повороту по часовой стрелке, от -100 до 0 --- против часовой стрелки.</translation>
</message>
<message>
<source>Initializes videocamera line detector with the color of the object in the middle of the camera`s sight.</source>
<translation type="vanished">Инициализировать датчик линии по видеокамере цветом объекта в центре поля зрения камеры.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1010"/>
<source>Draws the arc defined by the rectangle beginning at (x, y) with the specified width and height, and the given startAngle and spanAngle.</source>
<translation>Рисует на экране дугу, ограниченную прямоугольником с началом в (x, y) и заданными шириной и высотой, также задаётся начальный и конечный угол дуги.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1011"/>
<source>Draws the ellipse defined by the rectangle beginning at (x, y) with the given width and height.</source>
<translation>Рисует на экране эллипс, ограниченный прямоугольником с началом в (x, y) и заданными шириной и высотой.</translation>
</message>
<message>
<source>Enables line detector by videocamera and draws videostream on the robot`s screen.</source>
<translation type="vanished">Включить датчик линии по видеокамере, вывести на экран картинку.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1017"/>
<source>Sets the color of the led on the robot`s front panel.</source>
<translation>Установить цвет светодиода на передней панели робота.</translation>
</message>
<message>
<source>Stores current videocamera line detector`s value into a given variable.</source>
<translation type="vanished">Сохранить текущее значение датчика линии по видеокамере в заданную переменную.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1018"/>
<source>Plays on the robot a sound file (.wav or .mp3) previously uploaded to it.</source>
<translation>Проигрывает на роботе указанный звуковой файл (в формате .wav или .mp3), который должен быть на него предварительно загружен.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1020"/>
<source>Draws a sad smile on the robot`s screen :(</source>
<translation>Рисует на экране грустный смайлик :(</translation>
</message>
<message>
<source>Synthesizes the given phrase and plays it on the robot.</source>
<translation type="vanished">Воспроизводит заданную фразу на роботе.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1023"/>
<source>Sets the background color of the current picture on the robot`s screen.</source>
<translation>Устанавливает цвет фона активной картинки на экране робота.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1024"/>
<source>Sets the painter color.</source>
<translation>Устанавливает цвет кисти.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1025"/>
<source>Sets the painter width.</source>
<translation>Устанавливает толщину кисти.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1026"/>
<source>Draws a smile on the robot`s screen :)</source>
<translation>Рисует на экране смайлик :)</translation>
</message>
<message>
<source>Invokes bash script-style command on the robot.</source>
<translation type="vanished">Выполняет заданную bash-команду на роботе.</translation>
</message>
<message>
<source>Enables motors on the given ports in reverse mode with the given power. Ports are specified in accordance with TRIK controller notations (for example JM1, JE2) and divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the usial mode.</source>
<translation type="vanished">Включить моторы в режиме реверса по заданным портам с заданной мощностью. Порты задаются так, как они обозначены на плате (например, JM1, JE2), и раделяются запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в обычном режиме.</translation>
</message>
<message>
<source>Enables motors on the given ports with the given power. Ports are specified in accordance with TRIK controller notations (for example JM1, JE2) and divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the reverse mode.</source>
<translation type="vanished">Включить моторы по заданным портам с заданной мощностью. Порты задаются так, как они обозначены на плате (например, JM1, JE2), и раделяются запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в режиме реверса.</translation>
</message>
<message>
<source>Waits for "Down" button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вниз".</translation>
</message>
<message>
<source>Waits for "Enter". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Ввод".</translation>
</message>
<message>
<source>Waits till the value returned by the gyroscope on the given port will be greater or lower then the given in the 'Degrees/sec' parameter value.</source>
<translation type="vanished">Ждать, пока значение, возвращаемое гироскопом на указанном порту, не будет сравнимо с указанным в значении параметра 'Градусы/сек'.</translation>
</message>
<message>
<source>Waits till the value returned by the infrared sensor on the given port will be greater or lower then the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation type="vanished">Ждать, пока расстояние, возвращаемое инфракрасным сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние'. Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<source>Waits for "Left" button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Влево".</translation>
</message>
<message>
<source>Waits for "Power" button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Питание".</translation>
</message>
<message>
<source>Waits for "Right" button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вправо".</translation>
</message>
<message>
<source>Waits for "Up" button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вверх".</translation>
</message>
<message>
<source>Assignes a given value to a given variable.</source>
<translation type="vanished">Присвоить указанной переменной указанное значение.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2985"/>
<source>Composite</source>
<translation>Композиция</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2985"/>
<source>None</source>
<translation>Отсутствует</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2985"/>
<source>Shared</source>
<translation>Общая</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2981"/>
<source>False</source>
<translation>Ложь</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2981"/>
<source>True</source>
<translation>Истина</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2977"/>
<source>greater</source>
<translation>больше</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2977"/>
<source>less</source>
<translation>меньше</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2977"/>
<source>not greater</source>
<translation>не больше</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2977"/>
<source>not less</source>
<translation>не меньше</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2945"/>
<source>Concurrent</source>
<translation>Параллеьный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="871"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2957"/>
<source>E1</source>
<translation>E1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="923"/>
<source>M1, M2, M3, M4</source>
<translation>M1, M2, M3, M4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="919"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="921"/>
<source>M3, M4</source>
<translation>M3, M4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="791"/>
<source>A, B, C, D</source>
<translation>A, B, C, D</translation>
</message>
<message>
<source>'Enter some text here'</source>
<translation type="vanished">'Введите текст'</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2979"/>
<source>B1</source>
<translation>B1</translation>
</message>
<message>
<source>Waits for "Back". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Назад".</translation>
</message>
<message>
<source>Waits for "Down". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вниз".</translation>
</message>
<message>
<source>Waits for "Left". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Влево".</translation>
</message>
<message>
<source>Waits till the value returned by the ultrasonic or infrared range sensor on the given port will be greater or lower then the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation type="vanished">Ждать, пока расстояние, возвращаемое ультразвуковым или инфракрасным сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние' (расстояние задается в сантиметрах, от 0 до 255). Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<source>Waits for "Right". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вправо".</translation>
</message>
<message>
<source>Waits for "Up". button press.</source>
<translation type="vanished">Ждать нажатия на кнопку "Вверх".</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="980"/>
<source>Moves the marker of the 2D model robot down to the floor: the robot will draw its trace on the floor after that. If the marker of another color is already drawing at the moment it will be replaced.</source>
<translation>Опускает маркер робота в 2D модели на пол так, что тот начинает рисовать на полу свою траекторию Если маркер другого цвета уже опущен, то он будет замещен.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="981"/>
<source>Lifts the marker of the 2D model robot up: the robot stops drawing its trace on the floor after that.</source>
<translation>Поднимает маркер робота в 2D модели так, что тот перестает рисовать свою траекторию на полу.</translation>
</message>
<message>
<source>Enables motors on the given ports in reverse mode with the given power. Ports are specified in accordance with TRIK controller notations (for example M1, E2) and divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the usial mode.</source>
<translation type="vanished">Включить моторы в режиме реверса по заданным портам с заданной мощностью. Порты задаются так, как они обозначены на плате (например, M1, E2) и разделяются запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в обычном режиме.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1033"/>
<source>Enables motors on the given ports with the given power. Ports are specified in accordance with TRIK controller notations (for example M1, E2) and divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the reverse mode.</source>
<translation>Включить моторы по заданным портам с заданной мощностью. Порты задаются так, как они обозначены на плате (например, M1, E2) и разделяются запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в режиме реверса.</translation>
</message>
<message>
<source>Waits for android gamepad 'magic button' press. Buttons are identified by numbers from 1 to 5 (from left to right)</source>
<translation type="vanished">Ждёт нажатия на одну из 'магических кнопок' Android-пульта. Кнопки идентифицируются номерами с 1 по 5 (слева направо).</translation>
</message>
<message>
<source>Waits till the value returned by gamepad wheel be greater or less thfn the given in the 'Angle' parameter value. Angle is measured from -100 (max left) to 100 (max right).</source>
<translation type="vanished">Ждёт, пока значение, возвращаемое 'рулём' Android-пульта не будет больше (или меньше) заданного значения. Угол измеряется от -100 (максимально влево) до 100 (максимально вправо).</translation>
</message>
<message>
<source>Waits for android gamepad pad press (left pad has number 1, right pad - number 2).</source>
<translation type="vanished">Ждёт нажатия на одну из активных областей Android-пульта. Левая область имеет номер 1, правая - номер 2.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2945"/>
<source>Guarded</source>
<translation>Защищенный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2945"/>
<source>Sequential</source>
<translation>Последовательный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A1</source>
<translation>A1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="974"/>
<source>Assigns a given variable a value of pressed button. If no button is pressed at the moment and 'Wait' property is false when variable is set to -1.</source>
<translation>Присваивает заданной переменной код нажатой кнопки. Если в данный момент нет нажатых кнопок и свойство 'Дождаться нажатия' ложно, переменная будет иметь значение -1.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A2</source>
<translation>A2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A3</source>
<translation>A3</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A4</source>
<translation>A4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A5</source>
<translation>A5</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2959"/>
<source>A6</source>
<translation>A6</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2967"/>
<source>D1</source>
<translation>D1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2967"/>
<source>D2</source>
<translation>D2</translation>
</message>
<message>
<source>F1</source>
<translation type="vanished">F1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<source>black</source>
<translation>черный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1041"/>
<source>Waits till the motion sensor on the given port is triggered.</source>
<translation>Ждет, пока не сработает сенсор движения.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="281"/>
<source>Hull Number</source>
<translation>Бортномер</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="242"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="282"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
<message>
<source>Initializes videocamera line or object or color detector with the color of the object in the middle of the camera`s sight.</source>
<translation type="vanished">Инициализировать датчик линии или объектов или цвета по видеокамере цветом объекта в центре поля зрения камеры.</translation>
</message>
<message>
<source>Stores current videocamera line or object or color detector`s value into a given variable.</source>
<translation type="vanished">Сохранить текущее значение датчика линии или объекта или цвета по видеокамере в заданную переменную.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1015"/>
<source>Enables line or object or color detector by videocamera and draws videostream on the robot`s screen.</source>
<translation>Включить датчик линии или объекта или цвета по видеокамере, вывести на экран картинку.</translation>
</message>
<message>
<source>Waits for a message from another robot and stores it into a variable when it arrives.</source>
<translation type="vanished">Ждёт сообщения с другого робота и сохраняет его в переменную, когда оно приходит.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1022"/>
<source>Sends message to another robot.</source>
<translation>Посылает сообщение на другого робота.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="42"/>
<source>Wait for button</source>
<translation>Ждать нажатия кнопки</translation>
</message>
<message>
<source>Condition Closure</source>
<translation type="vanished">Замыкание условия</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="54"/>
<source>Join</source>
<translation>Слияние задач</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="55"/>
<source>Kill Thread</source>
<translation>Завершить задачу</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="69"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="115"/>
<source>Wait for Button</source>
<translation>Ждать нажатия кнопки</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="78"/>
<source>Random Initialization</source>
<translation>Случайное число</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="79"/>
<source>Receive Message From Thread</source>
<translation>Получить сообщение из другой задачи</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="81"/>
<source>Send Message To Thread</source>
<translation>Отправить сообщение в задачу</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="95"/>
<source>Enable Video Streaming</source>
<translation>Запустить видео-трансляцию</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="98"/>
<source>Remove File</source>
<translation>Удалить файл</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="120"/>
<source>Wait for Message</source>
<translation>Получить сообщение</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="124"/>
<source>Wait for Gamepad Connect</source>
<translation>Ждать подключения пульта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="128"/>
<source>Write To File</source>
<translation>Записать в файл</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="130"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="136"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="139"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="144"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="149"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="185"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="188"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="193"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="197"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="233"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="251"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="258"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="262"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="267"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="271"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="284"/>
<source>Redraw</source>
<translation>Обновить картинку</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="178"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="243"/>
<source>Thread</source>
<translation>Задача</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="231"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="279"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="289"/>
<source>Evaluate</source>
<translation>Вычислять</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="236"/>
<source>From</source>
<translation>От</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="237"/>
<source>To</source>
<translation>До</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="239"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="317"/>
<source>Synchronized</source>
<translation>Дождаться сообщения</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="278"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="326"/>
<source>File</source>
<translation>Файл</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="808"/>
<source>x > 0</source>
<translation>x > 0</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="861"/>
<source>Enter some text here</source>
<translation>Введите текст</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="874"/>
<source>err</source>
<translation>err</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="875"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="879"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="882"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="884"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="893"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="894"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="895"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="897"/>
<source>5</source>
<translation>5</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="903"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="946"/>
<source>output.txt</source>
<translation>output.txt</translation>
</message>
<message>
<source>"Hi!"</source>
<translation type="vanished">"Привет!"</translation>
</message>
<message>
<source>'echo ' .. '123'</source>
<translation type="vanished">'echo ' .. '123'</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="988"/>
<source>Enables motors on the given ports in reverse mode with the given power. Ports are specified with A, B or C letters divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the usual mode.</source>
<translation>Включить моторы в режиме реверса по заданным портам с заданной мощностью. Порты задаются буквами A, B или C, разделенными запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в обычном режиме.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="965"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="992"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1035"/>
<source>Waits for press of a button on a brick.</source>
<translation>Ждать нажатия на кнопку на корпусе робота.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="967"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="996"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1039"/>
<source>Waits till the value returned by the light sensor on the given port will be greater or less than the given in the 'Percents' parameter value (0 to 100).</source>
<translation>Ждать, пока значение, возвращаемое сенсором света на указанном порту, не будет сравнимо с указанным в значении параметра 'Проценты'. Еще один парамер — номер порта, к которому подключен сенсор цвета. Также параметром указывается операция, которая будет использоваться для сравнения со значением параметра 'Проценты'.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="968"/>
<source>Waits till the value returned by the ultrasonic or infrared range sensor on the given port will be greater or less than the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation>Ждать, пока расстояние, возвращаемое ультразвуковым или инфракрасным сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние' (расстояние задается в сантиметрах, от 0 до 255). Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="970"/>
<source>Unites control flow from different condition branches.</source>
<translation>Соединяет ветви блока "Условие".</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="972"/>
<source>Separates program execution into a number of threads that will be executed concurrently from the programmers`s point of view. For example in such way signal from sensor and some time interval can be waited synchroniously. This block must have at least two outgoing links. 'Guard' property of every link must contain unique thread identifiers, and one of those identifiers must be the same as the identifier of a thread where fork is placed (it must be 'main' if it is the first fork in a program.</source>
<translation>Разделяет исполнение программы на несколько задач, которые будут исполняться параллельно с точки зрения программиста. К примеру, в этом случае ожидание сигнала от сенсора или истечения некоторого промежутка времени могут происходить одновременно. Этот блок должен иметь как минимум две исходящие связи. Свойство "Условие" всех исходящих связей должно содержать уникальные идентификаторы задач, и один из этих идентификаторов должен совпадать с идентификатором задачи, из которой вызван этот блок (считается, что первый блок в программе вызывается из задачи с идентификатором 'main').</translation>
</message>
<message>
<source>Assigns a given variable a value of pressed button.</source>
<translation type="vanished">Присваивает заданной переменной код нажатой кнопки.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="977"/>
<source>Joins a number of threads into one. 'Guard' property of the single outgoing link must contain an identifier of one of threads being joined. The specified thread would wait until the rest of them finish execution, and then proceed in a normal way.</source>
<translation>Сливает несколько параллельных задач в одну. Свойство "Условие" единственной исходящей связи должно содержать идентификатор одной из сливаемых задач. Выполнение указанной задачи приостановится до того момента, как остальные задачи подойдут к этому блоку (закончат выполнение). Затем выполнение продолжается в обычном порядке.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="978"/>
<source>Terminates execution of a specified thread.</source>
<translation>Заканчивает выполнение указанной задачи.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="979"/>
<source>This block executes a sequence of blocks for a given number of times. The number of repetitions is specified by the 'Iterations' parameter. This block must have two outgoing links. One of them must be marked with the 'body' guard (that means that the property 'Guard' of the link must be set to 'body' value). Another outgoing link must be unmarked: the program execution will be proceeded through this link when it will go through our 'Loop' block for the given number of times.</source>
<translation>Блок, организующий выполнение последовательности блоков несколько раз. Число повторений задается значением параметра 'Итераций'. Блок должен иметь две исходящие связи, одна из которых должна быть помечена значением 'тело цикла' (то есть значение параметра 'Условие' должно быть 'тело цикла'). Другая связь, исходящая из блока 'Цикл', должна оставаться непомеченной: по ней будет осуществляться переход, когда программа пройдет через блок 'Цикл' указанное число раз.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="994"/>
<source>Waits till the value returned by the color sensor on the given port will be greater or less than the given in the 'Intensity' parameter value (the intensity is specified in percents, 0 to 100).</source>
<translation>Ждать, пока значение, возвращаемое сенсором цвета на указанном порту, не будет сравнимо с указанным в значении параметра 'Интенсивность' (задается в процентах). Еще один парамер — номер порта, к которому подключен сенсор цвета. Также параметром указывается операция, которая будет использоваться для сравнения с введенной интенсивностью.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="997"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1042"/>
<source>Waits till the value returned by the ultrasonic sensor on the given port will be greater or less than the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation>Ждать, пока расстояние, возвращаемое ультразвуковым сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние' (расстояние задается в сантиметрах, от 0 до 255). Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="998"/>
<source>Waits till the loudness obtained by the sound sensor on the given port will be greater or less than the given value.</source>
<translation>Ждать, пока громкость, считанная микрофоном на заданном порту, не будет выше или ниже заданного значения.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1000"/>
<source>Prints a given line in the specified coordinates on the robot`s screen. '$' token can be used in front of the identifier for printing its value. This feature is ignored in case when backslash ('\') is written before the '$' token. Example: '\$a = $a' expression will print '$a = 5' if the value of the variable 'a' is 5. If 'Evaluate' property is set to true then the value of 'Text' property is interpreted as a formula, otherwise it is interpreted as plain string.</source>
<translation>Напечатать заданную строку в заданных координатах на экране. Можно использовать символ доллара (&apos;$&apos;) перед идентификатором переменной для вывода ее значения. Данный сценарий игнорируется, если перед символом доллара стоит обратный слеш (&apos;\&apos;). Пример: строка &apos;\$a = $a&apos; напечатает &apos;$a = 5&apos;, если значение переменной a равно 5. Если свойство &quot;Вычислять&quot; имеет значение &quot;Истина&quot;, значение свойства &quot;Текст&quot; будет вычислено как формула, иначе оно будет напечатано как есть.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1001"/>
<source>Sets a variable value to a random value inside given interval.</source>
<translation>Присваивает переменной случайное число из заданного интервала.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1002"/>
<source>Receive a message sent to a thread from which this block is called.</source>
<translation>Получить сообщение, посланное другой задачей той задаче, из которой вызван этот блок.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1003"/>
<source>Sends a message to a specified thread.</source>
<translation>Посылает сообщение в указанную задачу.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1004"/>
<source>Subprogram call. Subprograms are used for splitting repetitive program parts into a separate diagram and then calling it from main diagram or other subprograms. When this block is added into a diagram it will be suggested to enter subprogram name. The double click on subprogram call block may open the corresponding subprogram diagram. Moreover user palette will appear containing existing subrpograms, they can be dragged into a diagram like the usual blocks.</source>
<translation>Вызов подпрограммы. Подпрограммы используются для того, чтобы вынести повторяющиеся фрагменты программы на отдельную диаграмму, а потом вызывать фрагмент программы с этой диаграммы в нескольких местах основной программы или других подпрограмм. При добавлении этого блока на диаграмму будет предложено ввести имя подпрограммы, после чего двойным кликом на блоке можно будет перейти на диаграмму, соответствующую данной подпрограмме. Кроме того, появится дополнительная палитра со всеми подпрограммами, подпрограммы из неё можно перетаскивать на сцену и использовать как обычные блоки.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1005"/>
<source>Selects the program execution branch in correspondence with some expression value. The value of the expression written in 'Expression' property is compared to the values on the outgoing links. If equal value is found then execution will be proceeded by that branch. Else branch without a marker will be selected.</source>
<translation>Выбирает ветку, по которой будет продолжено исполнение программы. Значение выражения, указанного в свойстве 'Выражение' сравнивается со значениями на исходящих связях. Если среди них найдено равное, исполнение будет продолжено по этой ветке. В противном случае будет выбрана ветка без маркера.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1016"/>
<source>Enables video stream on robot. Video then can be watched on TRIK gamepad or in browser using URL http://ROBOT.IP.ADDRESS:8080/?action=stream</source>
<translation>Включает видео-трансляцию на роботе. Видео может быть просмотрено, например, на пульте управления ТРИК или в браузере по адресу http://IP.АДРЕС.РОБОТА:8080/?action=stream</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1019"/>
<source>Removes a file. File path may be absolute or relative to a directory containing TRIK Studio executable.</source>
<translation>Удаляет файл. Путь до файла может быть абсолютным или относительно папки с trik-studio.exe.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1021"/>
<source>Synthesizes the given phrase and plays it on the robot. If 'Evaluate' property is set to true then the value of 'Text' property is interpreted as a formula, otherwise it is interpreted as plain string.</source>
<translation>Воспроизводит заданную фразу на роботе. Если свойство &quot;Вычислять&quot; имеет значение &quot;Истина&quot;, значение свойства &quot;Текст&quot; будет вычислено как формула, иначе оно воспроизводится как есть.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1027"/>
<source>Invokes bash script-style command on the robot. If 'Evaluate' property is set to true then the value of 'Command' property is interpreted as a formula, otherwise it is interpreted as plain string.</source>
<translation>Выполняет заданную bash-команду на роботе. Если свойство &quot;Вычислять&quot; имеет значение &quot;Истина&quot;, значение свойства &quot;Команда&quot; будет вычислено как формула, иначе оно будет исполнено как есть.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1032"/>
<source>Enables motors on the given ports in reverse mode with the given power. Ports are specified in accordance with TRIK controller notations (for example M1, E2) and divided by commas. The power is specified in percents with the number from -100 to 100, if negative number is specified then the motor is enabled in the usual mode.</source>
<translation>Включить моторы в режиме реверса по заданным портам с заданной мощностью. Порты задаются так, как они обозначены на плате (например, M1, E2) и разделяются запятыми. Мощность задается в процентах числом от -100 до 100, если задано отрицательное значение, мотор включается в обычном режиме.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1037"/>
<source>Waits till the value returned by the gyroscope on the given port will be greater or less than the given in the 'Degrees/sec' parameter value.</source>
<translation>Ждать, пока значение, возвращаемое гироскопом на указанном порту, не будет сравнимо с указанным в значении параметра 'Градусы/сек'.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1038"/>
<source>Waits till the value returned by the infrared sensor on the given port will be greater or less than the given in the 'Distance' parameter value (the distance is specified in centimeters, 0 to 255).</source>
<translation>Ждать, пока расстояние, возвращаемое инфракрасным сенсором расстояния, не будет сравнимо с указанным в значении параметра 'Расстояние'. Еще один парамер — номер порта, к которому подключен датчик расстояния. Также параметром указывается операция, которая будет использоваться для сравнения с введенным расстоянием.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1040"/>
<source>Stores a message from another robot into a given variable. When no incoming messages are present at the moment, a robot will wait for incoming message if 'Synchronized' property is true, and empty string will be assigned to a variable otherwise.</source>
<translation>Сохраняет сообщение от другого робота в переменной. Если свойство "Дождаться сообщения" установлено, робот будет ждать, когда входящих сообщений нет, иначе переменной присваивается пустая строка.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1043"/>
<source>Waits for Android gamepad 'magic button' press. Buttons are identified by numbers from 1 to 5 (from left to right)</source>
<translation>Ждёт нажатия на одну из 'магических кнопок' Android-пульта. Кнопки идентифицируются номерами с 1 по 5 (слева направо).</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1044"/>
<source>Waits until Android gamepad is connected.</source>
<translation>Ждать, пока не будет подключен Android-пульт.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1045"/>
<source>Waits until Android gamepad is disconnected.</source>
<translation>Ждать, пока Android-пульт не отключится</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1046"/>
<source>Waits till the value returned by gamepad wheel be greater or less than the given in the 'Angle' parameter value. Angle is measured from -100 (max left) to 100 (max right).</source>
<translation>Ждёт, пока значение, возвращаемое 'рулём' Android-пульта не будет больше (или меньше) заданного значения. Угол измеряется от -100 (максимально влево) до 100 (максимально вправо).</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1047"/>
<source>Waits for Android gamepad pad press (left pad has number 1, right pad - number 2).</source>
<translation>Ждёт нажатия на одну из активных областей Android-пульта. Левая область имеет номер 1, правая - номер 2.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1048"/>
<source>Writes a given message to a file. File path may be absolute or relative to a directory containing TRIK Studio executable.</source>
<translation>Записывает заданное значение в файл. Путь до файла может быть абсолютным или относительно папки с trik-studio.exe.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1049"/>
<source>Assigns a given value to a given variable.</source>
<translation>Присвоить данное значение данной переменной.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2957"/>
<source>E2</source>
<translation>E2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2957"/>
<source>E3</source>
<translation>E3</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2957"/>
<source>E4</source>
<translation>E4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2949"/>
<source>body</source>
<translation>тело цикла</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Down</source>
<translation>Вниз</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2979"/>
<source>B2</source>
<translation>B2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2979"/>
<source>B3</source>
<translation>B3</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2979"/>
<source>B4</source>
<translation>B4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2951"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Enter</source>
<translation>Ввод</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<source>Esc</source>
<translation>Отмена</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2951"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Left</source>
<translation>Влево</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2951"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Right</source>
<translation>Вправо</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2961"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Up</source>
<translation>Вверх</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<source>blue</source>
<translation>синий</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="905"/>
<source>Hi!</source>
<translation>Привет!</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="911"/>
<source>echo 123</source>
<translation>echo 123</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="913"/>
<source>S1</source>
<translation>S1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="915"/>
<source>E1, E2, E3, E4</source>
<translation>E1, E2, E3, E4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>cyan</source>
<translation>сине-зелёный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark blue</source>
<translation>тёмно-синий</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark cyan</source>
<translation>тёмносине-зеленый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark gray</source>
<translation>тёмно-серый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark green</source>
<translation>тёмно-зелёный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark magenta</source>
<translation>тёмно-пурпурный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark yellow</source>
<translation>тёмно-жёлтый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>dark red</source>
<translation>тёмно-красный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>gray</source>
<translation>серый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2963"/>
<source>green</source>
<translation>зелёный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>light gray</source>
<translation>светло-серый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<source>magenta</source>
<translation>пурпурный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2963"/>
<source>red</source>
<translation>красный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<source>white</source>
<translation>белый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2943"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2955"/>
<source>yellow</source>
<translation>жёлтый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2951"/>
<source>Escape</source>
<translation>Отмена</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2969"/>
<source>Back</source>
<translation>Назад</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2963"/>
<source>orange</source>
<translation>оранжевый</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2965"/>
<source>Color sensor</source>
<translation>Сенсор цвета</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2947"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2965"/>
<source>Line sensor</source>
<translation>Сенсор линии</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2947"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2965"/>
<source>Object sensor</source>
<translation>Сенсор объекта</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2963"/>
<source>off</source>
<translation>выключен</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="247"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="291"/>
<source>Angle (degrees)</source>
<translation>Угол (в градусах)</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="918"/>
<source>B1, B2, B3, B4</source>
<translation>B1, B2, B3, B4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1007"/>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1028"/>
<source>Manages angular servomotor. Sets up rotation angle on the given port in degrees. Values from 0 to 90 are correspond to a clockwise rotation and values from -90 to 0 correspond to counterclockwise rotation.</source>
<translation>Управление угловым сервомотором. Устанавливает угол поворота вала мотора на данном порту (в градусах). Значения от 0 до 90 соотвествуют повороту по часовой, значения от -90 до 0 --- повороту против часовой.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1008"/>
<source>Initializes videocamera line or object detector with the color of the object in the middle of the camera`s sight.</source>
<translation>Инициализировать датчик линии или объектов по видеокамере цветом объекта в центре поля зрения камеры.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="1009"/>
<source>Stores videocamera line detector`s value into a given variable.</source>
<translation>Сохранить текущее значение датчика линии по видеокамере в заданную переменную.</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2973"/>
<source>2</source>
<translation>2</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2973"/>
<source>3</source>
<translation>3</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2973"/>
<source>4</source>
<translation>4</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2953"/>
<source>In</source>
<translation>Входной</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2953"/>
<source>Inout</source>
<translation>Входной-выходной</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2953"/>
<source>Out</source>
<translation>Выходной</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2953"/>
<source>Return</source>
<translation>Возвращается</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2971"/>
<source>norm</source>
<translation>норма</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2971"/>
<source>x-axis</source>
<translation>ось x</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2971"/>
<source>y-axis</source>
<translation>ось y</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2971"/>
<source>z-axis</source>
<translation>ось z</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2949"/>
<source>false</source>
<translation>ложь</translation>
</message>
<message>
<source>iteration</source>
<translation type="vanished">итерация</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2949"/>
<source>true</source>
<translation>истина</translation>
</message>
<message>
<source>JA1</source>
<translation type="vanished">JA1</translation>
</message>
<message>
<source>JA2</source>
<translation type="vanished">JA2</translation>
</message>
<message>
<source>JA3</source>
<translation type="vanished">JA3</translation>
</message>
<message>
<source>JA4</source>
<translation type="vanished">JA4</translation>
</message>
<message>
<source>JA5</source>
<translation type="vanished">JA5</translation>
</message>
<message>
<source>JA6</source>
<translation type="vanished">JA6</translation>
</message>
<message>
<source>JD1</source>
<translation type="vanished">JD1</translation>
</message>
<message>
<source>JD2</source>
<translation type="vanished">JD2</translation>
</message>
<message>
<source>JF1</source>
<translation type="vanished">JF1</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2975"/>
<source>Package</source>
<translation>Пакет</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2975"/>
<source>Private</source>
<translation>Приватный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2975"/>
<source>Protected</source>
<translation>Защищенный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2975"/>
<source>Public</source>
<translation>Публичный</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2983"/>
<source>break</source>
<translation>тормозить</translation>
</message>
<message>
<location filename="../../../../plugins/robots/editor/generated/generated/pluginInterface.cpp" line="2983"/>
<source>float</source>
<translation>скользить</translation>
</message>
</context>
</TS>
| apache-2.0 |
77ilogin/training | src/test/java/org/apache/commons/beanutils/converters/SqlDateConverterTestCase.java | 3854 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils.converters;
import java.sql.Date;
import java.util.Calendar;
import junit.framework.TestSuite;
/**
* Test Case for the {@link SqlDateConverter} class.
*
* @version $Id: SqlDateConverterTestCase.java 1540186 2013-11-08 21:08:30Z oheger $
*/
public class SqlDateConverterTestCase extends DateConverterTestBase {
/**
* Construct a new Date test case.
* @param name Test Name
*/
public SqlDateConverterTestCase(String name) {
super(name);
}
// ------------------------------------------------------------------------
/**
* Create Test Suite
* @return test suite
*/
public static TestSuite suite() {
return new TestSuite(SqlDateConverterTestCase.class);
}
// ------------------------------------------------------------------------
/**
* Test default String to java.sql.Date conversion
*/
@Override
public void testDefaultStringToTypeConvert() {
// Create & Configure the Converter
DateTimeConverter converter = makeConverter();
converter.setUseLocaleFormat(false);
// Valid String --> java.sql.Date Conversion
String testString = "2006-05-16";
Object expected = toType(testString, "yyyy-MM-dd", null);
validConversion(converter, expected, testString);
// Invalid String --> java.sql.Date Conversion
invalidConversion(converter, "01/01/2006");
}
/**
* Test default java.sql.Date to String conversion
*/
public void testDefaultTypeToStringConvert() {
// Create & Configure the Converter
DateTimeConverter converter = makeConverter();
converter.setUseLocaleFormat(false);
// Valid String --> java.sql.Date Conversion
String expected = "2006-05-16";
Object testVal = toType(expected, "yyyy-MM-dd", null);
stringConversion(converter, expected, testVal);
Object result = converter.convert(String.class, new Integer(2));
assertEquals("Default toString()", "2", result);
}
/**
* Create the Converter with no default value.
* @return A new Converter
*/
@Override
protected DateTimeConverter makeConverter() {
return new SqlDateConverter();
}
/**
* Create the Converter with a default value.
* @param defaultValue The default value
* @return A new Converter
*/
@Override
protected DateTimeConverter makeConverter(Object defaultValue) {
return new SqlDateConverter(defaultValue);
}
/**
* Return the expected type
* @return The expected type
*/
@Override
protected Class<?> getExpectedType() {
return Date.class;
}
/**
* Convert from a Calendar to the appropriate Date type
*
* @param value The Calendar value to convert
* @return The converted value
*/
@Override
protected Object toType(Calendar value) {
return new java.sql.Date(getTimeInMillis(value));
}
}
| apache-2.0 |
ryanchang/osfstore | app/controllers/api/products_controller.rb | 180 | class Api::ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
render json: @product
end
def index
render json: Product.all
end
end
| apache-2.0 |
lizhanhui/data_druid | processing/src/test/java/io/druid/query/search/SearchQueryRunnerWithCaseTest.java | 10858 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.search;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.CharSource;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.guava.Sequences;
import io.druid.query.Druids;
import io.druid.query.QueryRunner;
import io.druid.query.Result;
import io.druid.query.search.search.AutoStrategy;
import io.druid.query.search.search.CursorOnlyStrategy;
import io.druid.query.search.search.SearchHit;
import io.druid.query.search.search.SearchQuery;
import io.druid.query.search.search.SearchQueryConfig;
import io.druid.query.search.search.UseIndexesStrategy;
import io.druid.segment.IncrementalIndexSegment;
import io.druid.segment.QueryableIndex;
import io.druid.segment.QueryableIndexSegment;
import io.druid.segment.TestIndex;
import io.druid.segment.incremental.IncrementalIndex;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.druid.query.QueryRunnerTestHelper.NOOP_QUERYWATCHER;
import static io.druid.query.QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator;
import static io.druid.query.QueryRunnerTestHelper.allGran;
import static io.druid.query.QueryRunnerTestHelper.dataSource;
import static io.druid.query.QueryRunnerTestHelper.fullOnInterval;
import static io.druid.query.QueryRunnerTestHelper.makeQueryRunner;
import static io.druid.query.QueryRunnerTestHelper.marketDimension;
import static io.druid.query.QueryRunnerTestHelper.placementDimension;
import static io.druid.query.QueryRunnerTestHelper.placementishDimension;
import static io.druid.query.QueryRunnerTestHelper.qualityDimension;
import static io.druid.query.QueryRunnerTestHelper.transformToConstructionFeeder;
/**
*/
@RunWith(Parameterized.class)
public class SearchQueryRunnerWithCaseTest
{
@Parameterized.Parameters
public static Iterable<Object[]> constructorFeeder() throws IOException
{
final SearchQueryConfig[] configs = new SearchQueryConfig[3];
configs[0] = new SearchQueryConfig();
configs[0].setSearchStrategy(UseIndexesStrategy.NAME);
configs[1] = new SearchQueryConfig();
configs[1].setSearchStrategy(CursorOnlyStrategy.NAME);
configs[2] = new SearchQueryConfig();
configs[2].setSearchStrategy(AutoStrategy.NAME);
CharSource input = CharSource.wrap(
"2011-01-12T00:00:00.000Z\tspot\tAutoMotive\t1000\t10000.0\t10000.0\t100000\tPREFERRED\ta\u0001preferred\t100.000000\n" +
"2011-01-12T00:00:00.000Z\tSPot\tbusiness\t1100\t11000.0\t11000.0\t110000\tpreferred\tb\u0001Preferred\t100.000000\n" +
"2011-01-12T00:00:00.000Z\tspot\tentertainment\t1200\t12000.0\t12000.0\t120000\tPREFERRed\te\u0001preferred\t100.000000\n" +
"2011-01-13T00:00:00.000Z\tspot\tautomotive\t1000\t10000.0\t10000.0\t100000\tpreferred\ta\u0001preferred\t94.874713"
);
IncrementalIndex index1 = TestIndex.makeRealtimeIndex(input);
IncrementalIndex index2 = TestIndex.makeRealtimeIndex(input);
QueryableIndex index3 = TestIndex.persistRealtimeAndLoadMMapped(index1);
QueryableIndex index4 = TestIndex.persistRealtimeAndLoadMMapped(index2);
final List<QueryRunner<Result<SearchResultValue>>> runners = Lists.newArrayList();
for (int i = 0; i < configs.length; i++) {
runners.addAll(Arrays.asList(
makeQueryRunner(
makeRunnerFactory(configs[i]),
"index1",
new IncrementalIndexSegment(index1, "index1"),
"index1"
),
makeQueryRunner(
makeRunnerFactory(configs[i]),
"index2",
new IncrementalIndexSegment(index2, "index2"),
"index2"
),
makeQueryRunner(
makeRunnerFactory(configs[i]),
"index3",
new QueryableIndexSegment("index3", index3),
"index3"
),
makeQueryRunner(
makeRunnerFactory(configs[i]),
"index4",
new QueryableIndexSegment("index4", index4),
"index4"
)
));
}
return transformToConstructionFeeder(runners);
}
static SearchQueryRunnerFactory makeRunnerFactory(final SearchQueryConfig config)
{
return new SearchQueryRunnerFactory(
new SearchStrategySelector(Suppliers.ofInstance(config)),
new SearchQueryQueryToolChest(
config,
NoopIntervalChunkingQueryRunnerDecorator()
),
NOOP_QUERYWATCHER
);
}
private final QueryRunner runner;
public SearchQueryRunnerWithCaseTest(
QueryRunner runner
)
{
this.runner = runner;
}
private Druids.SearchQueryBuilder testBuilder()
{
return Druids.newSearchQueryBuilder()
.dataSource(dataSource)
.granularity(allGran)
.intervals(fullOnInterval);
}
@Test
public void testSearch()
{
Druids.SearchQueryBuilder builder = testBuilder();
Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
SearchQuery searchQuery;
searchQuery = builder.query("SPOT").build();
expectedResults.put(marketDimension, Sets.newHashSet("spot", "SPot"));
checkSearchQuery(searchQuery, expectedResults);
searchQuery = builder.query("spot", true).build();
expectedResults.put(marketDimension, Sets.newHashSet("spot"));
checkSearchQuery(searchQuery, expectedResults);
searchQuery = builder.query("SPot", true).build();
expectedResults.put(marketDimension, Sets.newHashSet("SPot"));
checkSearchQuery(searchQuery, expectedResults);
}
@Test
public void testSearchSameValueInMultiDims()
{
SearchQuery searchQuery;
Druids.SearchQueryBuilder builder = testBuilder()
.dimensions(Arrays.asList(placementDimension, placementishDimension));
Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
searchQuery = builder.query("PREFERRED").build();
expectedResults.put(placementDimension, Sets.newHashSet("PREFERRED", "preferred", "PREFERRed"));
expectedResults.put(placementishDimension, Sets.newHashSet("preferred", "Preferred"));
checkSearchQuery(searchQuery, expectedResults);
searchQuery = builder.query("preferred", true).build();
expectedResults.put(placementDimension, Sets.newHashSet("preferred"));
expectedResults.put(placementishDimension, Sets.newHashSet("preferred"));
checkSearchQuery(searchQuery, expectedResults);
}
@Test
public void testSearchIntervals()
{
SearchQuery searchQuery;
Druids.SearchQueryBuilder builder = testBuilder()
.dimensions(Arrays.asList(qualityDimension))
.intervals("2011-01-12T00:00:00.000Z/2011-01-13T00:00:00.000Z");
Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
searchQuery = builder.query("otive").build();
expectedResults.put(qualityDimension, Sets.newHashSet("AutoMotive"));
checkSearchQuery(searchQuery, expectedResults);
}
@Test
public void testSearchNoOverrappingIntervals()
{
SearchQuery searchQuery;
Druids.SearchQueryBuilder builder = testBuilder()
.dimensions(Arrays.asList(qualityDimension))
.intervals("2011-01-10T00:00:00.000Z/2011-01-11T00:00:00.000Z");
Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
searchQuery = builder.query("business").build();
expectedResults.put(qualityDimension, Sets.<String>newHashSet());
checkSearchQuery(searchQuery, expectedResults);
}
@Test
public void testFragmentSearch()
{
Druids.SearchQueryBuilder builder = testBuilder();
Map<String, Set<String>> expectedResults = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
SearchQuery searchQuery;
searchQuery = builder.fragments(Arrays.asList("auto", "ve")).build();
expectedResults.put(qualityDimension, Sets.newHashSet("automotive", "AutoMotive"));
checkSearchQuery(searchQuery, expectedResults);
searchQuery = builder.fragments(Arrays.asList("auto", "ve"), true).build();
expectedResults.put(qualityDimension, Sets.newHashSet("automotive"));
checkSearchQuery(searchQuery, expectedResults);
}
private void checkSearchQuery(SearchQuery searchQuery, Map<String, Set<String>> expectedResults)
{
HashMap<String, List> context = new HashMap<>();
Iterable<Result<SearchResultValue>> results = Sequences.toList(
runner.run(searchQuery, context),
Lists.<Result<SearchResultValue>>newArrayList()
);
for (Result<SearchResultValue> result : results) {
Assert.assertEquals(new DateTime("2011-01-12T00:00:00.000Z"), result.getTimestamp());
Assert.assertNotNull(result.getValue());
Iterable<SearchHit> resultValues = result.getValue();
for (SearchHit resultValue : resultValues) {
String dimension = resultValue.getDimension();
String theValue = resultValue.getValue();
Assert.assertTrue(
StringUtils.format("Result had unknown dimension[%s]", dimension),
expectedResults.containsKey(dimension)
);
Set<String> expectedSet = expectedResults.get(dimension);
Assert.assertTrue(
StringUtils.format("Couldn't remove dim[%s], value[%s]", dimension, theValue), expectedSet.remove(theValue)
);
}
}
for (Map.Entry<String, Set<String>> entry : expectedResults.entrySet()) {
Assert.assertTrue(
StringUtils.format(
"Dimension[%s] should have had everything removed, still has[%s]", entry.getKey(), entry.getValue()
),
entry.getValue().isEmpty()
);
}
expectedResults.clear();
}
}
| apache-2.0 |
hou23/fluffy-potato | spring-boot-demo/spring-security/src/main/java/com/marshall/spring_security/service/impl/BaseUserService.java | 1579 | package com.marshall.spring_security.service.impl;
import com.marshall.spring_security.constant.RoleConstant;
import com.marshall.spring_security.entity.UserEntity;
import com.marshall.spring_security.mapper.UserMapper;
import com.marshall.spring_security.service.UserService;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
/**
* @author yaojie.hou
* @create 2018/5/3
*/
@Service
@Primary
//@Log4j
public class BaseUserService implements UserService {
private final UserMapper userMapper;
public BaseUserService(UserMapper userMapper){
this.userMapper = userMapper;
}
@Override
public boolean insert(UserEntity userEntity) {
String username = userEntity.getUsername();
if (exist(username)) {
return false;
}
encryptPassword(userEntity);
userEntity.setRoles(RoleConstant.ROLE_USER);
int result = userMapper.insert(userEntity);
return result == 1;
}
@Override
public UserEntity getByUsername(String username) {
return userMapper.selectByUsername(username);
}
/**
* 判断用户是否存在
* @param username 账号
* @return 密码
*/
private boolean exist(String username){
UserEntity userEntity = userMapper.selectByUsername(username);
return (userEntity != null);
}
/**
* 加密密码
*/
private void encryptPassword(UserEntity userEntity){
String password = userEntity.getPassword();
password = new BCryptPasswordEncoder().encode(password);
userEntity.setPassword(password);
}
}
| apache-2.0 |
stevenhva/InfoLearn_OpenOLAT | src/main/java/de/bps/ims/qti/QTIResultDetailsController.java | 9047 | /**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
* <p>
* Initial code contributed and copyrighted by<br>
* BPS Bildungsportal Sachsen GmbH, http://www.bps-system.de
* <p>
*/
package de.bps.ims.qti;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.table.DefaultColumnDescriptor;
import org.olat.core.gui.components.table.StaticColumnDescriptor;
import org.olat.core.gui.components.table.TableController;
import org.olat.core.gui.components.table.TableEvent;
import org.olat.core.gui.components.table.TableGuiConfiguration;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;
import org.olat.core.gui.control.generic.closablewrapper.CloseableModalController;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.Util;
import org.olat.course.CourseFactory;
import org.olat.course.nodes.AssessableCourseNode;
import org.olat.course.nodes.CourseNode;
import org.olat.ims.qti.QTIResultManager;
import org.olat.ims.qti.QTIResultSet;
import org.olat.ims.qti.QTIResultTableModel;
import org.olat.ims.qti.process.FilePersister;
import org.olat.ims.qti.render.LocalizedXSLTransformer;
import org.olat.repository.RepositoryEntry;
import de.bps.onyx.plugin.OnyxModule;
import de.bps.webservices.clients.onyxreporter.OnyxReporterConnector;
import de.bps.webservices.clients.onyxreporter.OnyxReporterException;
import de.bps.webservices.clients.onyxreporter.ReporterRole;
/**
* Initial Date: 12.01.2005
*
* @author Mike Stock
*/
public class QTIResultDetailsController extends BasicController {
private Long courseResourceableId;
private String nodeIdent;
private Identity identity;
private RepositoryEntry repositoryEntry;
private String type;
private VelocityContainer main, details;
private VelocityContainer onyxReporterVC;
private QTIResultTableModel tableModel;
private TableController tableCtr;
private CloseableModalController cmc;
//<ONYX-705>
private final static OLog log = Tracing.createLoggerFor(QTIResultDetailsController.class);
private CloseableModalController onyxCmc;
//</ONYX-705>
/**
* @param courseResourceableId
* @param nodeIdent
* @param identity
* @param re
* @param type
* @param ureq
* @param wControl
*/
public QTIResultDetailsController(Long courseResourceableId, String nodeIdent, Identity identity, final RepositoryEntry re, final String type,
UserRequest ureq, WindowControl wControl) {
super(ureq, wControl);
Translator translator = Util.createPackageTranslator(org.olat.ims.qti.QTI12ResultDetailsController.class, getTranslator().getLocale(), getTranslator());
setTranslator(translator);
this.courseResourceableId = courseResourceableId;
this.nodeIdent = nodeIdent;
this.identity = identity;
this.repositoryEntry = re;
this.type = type;
init(ureq);
}
private void init(UserRequest ureq) {
main = createVelocityContainer("qtires");
details = createVelocityContainer("qtires_details");
TableGuiConfiguration tableConfig = new TableGuiConfiguration();
tableCtr = new TableController(tableConfig, ureq, getWindowControl(), getTranslator());
tableCtr.addColumnDescriptor(new DefaultColumnDescriptor("column.header.date", 0, null, ureq.getLocale()));
tableCtr.addColumnDescriptor(new DefaultColumnDescriptor("column.header.duration", 1, null, ureq.getLocale()));
tableCtr.addColumnDescriptor(new DefaultColumnDescriptor("column.header.assesspoints", 2, null, ureq.getLocale()));
tableCtr.addColumnDescriptor(new StaticColumnDescriptor("sel", "column.header.details", getTranslator().translate("select")));
QTIResultManager qrm = QTIResultManager.getInstance();
tableModel = new QTIResultTableModel(qrm.getResultSets(courseResourceableId, nodeIdent, repositoryEntry.getKey(), identity), getTranslator());
tableCtr.setTableDataModel(tableModel);
listenTo(tableCtr);
main.put("qtirestable", tableCtr.getInitialComponent());
putInitialPanel(main);
}
/**
* @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, org.olat.core.gui.components.Component, org.olat.core.gui.control.Event)
*/
@Override
public void event(UserRequest ureq, Component source, Event event) {
if (source == main) {
if (event.getCommand().equals("close")) {
fireEvent(ureq, Event.DONE_EVENT);
}
}
}
/**
* @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event)
*/
@Override
public void event(UserRequest ureq, Controller source, Event event) {
if (source == tableCtr) {
TableEvent tEvent = (TableEvent) event;
if (tEvent.getActionId().equals("sel")) {
if (OnyxModule.isOnyxTest(repositoryEntry.getOlatResource())) {
QTIResultSet resultSet = tableModel.getResultSet(tEvent.getRowId());
onyxReporterVC = createVelocityContainer("onyxreporter");
if (showOnyxReporter(ureq, resultSet.getAssessmentID())) {
onyxCmc = new CloseableModalController(getWindowControl(), getTranslator().translate("close"), onyxReporterVC);
onyxCmc.activate();
listenTo(onyxCmc);
} else {
getWindowControl().setError(getTranslator().translate("onyxreporter.error"));
}
} else {
QTIResultSet resultSet = tableModel.getResultSet(tEvent.getRowId());
Document doc = FilePersister.retreiveResultsReporting(identity, type, resultSet.getAssessmentID());
if (doc == null) {
showInfo("error.resreporting.na");
return;
}
StringBuilder resultsHTML = LocalizedXSLTransformer.getInstance(ureq.getLocale()).renderResults(doc);
details.contextPut("reshtml", resultsHTML);
removeAsListenerAndDispose(cmc);
cmc = new CloseableModalController(getWindowControl(), getTranslator().translate("close"), details);
listenTo(cmc);
cmc.activate();
}
}
} else if (source == onyxCmc && CloseableModalController.CLOSE_MODAL_EVENT.equals(event)) {
QTIResultManager qrm = QTIResultManager.getInstance();
tableModel = new QTIResultTableModel(qrm.getResultSets(courseResourceableId, nodeIdent, repositoryEntry.getKey(), identity), getTranslator());
tableCtr.setTableDataModel(tableModel);
}
}
/**
* This methods calls the OnyxReporter and shows it in an iframe.
*
* @param ureq The UserRequest for getting the identity and role of the current user.
*/
private boolean showOnyxReporter(UserRequest ureq, long assassmentId) {
//<ONYX-705>
OnyxReporterConnector onyxReporter = null;
try{
onyxReporter = new OnyxReporterConnector();
} catch (OnyxReporterException e) {
log.error(e.getMessage(), e);
}
//</ONYX-705>
if (onyxReporter != null) {
//make a list of this one student because onyxReporter needs a list
List<Identity> identityList = new ArrayList<Identity>();
identityList.add(identity);
CourseNode cn = CourseFactory.loadCourse(courseResourceableId).getEditorTreeModel().getCourseNode(this.nodeIdent);
//<ONYX-705>
String iframeSrc = "";
try {
iframeSrc = onyxReporter.startReporterGUI(ureq.getIdentity(), identityList, (AssessableCourseNode) cn, assassmentId, ReporterRole.ASSESSMENT);
//</ONYX-705>
} catch (OnyxReporterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
onyxReporterVC.contextPut("showBack", Boolean.TRUE);
onyxReporterVC.contextPut("iframeOK", Boolean.TRUE);
onyxReporterVC.contextPut("onyxReportLink", iframeSrc);
return true;
} else {
return false;
}
}
/**
* @see org.olat.core.gui.control.DefaultController#doDispose(boolean)
*/
@Override
protected void doDispose() {
//
}
}
| apache-2.0 |
fsprojects/powerpack-archive | workyard/tests/codedom/tests/callingfieldtest.cs | 6989 | using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using Microsoft.Samples.CodeDomTestSuite;
public class CallingFieldTest : CodeDomTestTree {
public override string Comment
{
get
{
return "Static Fields with an InitExpression are Not Initialized Correctly";
}
}
public override TestTypes TestType
{
get {
return TestTypes.Everett;
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override string Name {
get {
return "CallingFieldTest";
}
}
public override string Description {
get {
return "Tests calling fields.";
}
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
CodeNamespace nspace = new CodeNamespace ("NSPC");
nspace.Imports.Add (new CodeNamespaceImport ("System"));
cu.Namespaces.Add (nspace);
// declare class with fields
// GENERATES (C#):
// public class ClassWithFields {
// // only if provider supports GeneratorSupport.PublicStaticMembers
// public static string Microsoft = "hi";
// public static int StaticPublicField = 5;
// // ---
//
// public int NonStaticPublicField = 6;
// private int PrivateField = 7;
// public int UsePrivateField(int i) {
// this.PrivateField = i;
// return this.PrivateField;
// }
// }
CodeTypeDeclaration cd = new CodeTypeDeclaration ("ClassWithFields");
cd.IsClass = true;
nspace.Types.Add (cd);
CodeMemberField field;
if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
field = new CodeMemberField ("System.String", "Microsoft");
field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
field.InitExpression = new CodePrimitiveExpression ("hi");
cd.Members.Add (field);
field = new CodeMemberField ();
field.Name = "StaticPublicField";
field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (5);
cd.Members.Add (field);
}
field = new CodeMemberField ();
field.Name = "NonStaticPublicField";
field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (6);
cd.Members.Add (field);
field = new CodeMemberField ();
field.Name = "PrivateField";
field.Attributes = MemberAttributes.Private | MemberAttributes.Final;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (7);
cd.Members.Add (field);
// create a method to test access to private field
CodeMemberMethod cmm = new CodeMemberMethod ();
cmm.Name = "UsePrivateField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "PrivateField"), new CodeArgumentReferenceExpression ("i")));
cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "PrivateField")));
cd.Members.Add (cmm);
// GENERATES (C#):
// public class TestFields {
// public static int UseFields(int i) {
// ClassWithFields number = new ClassWithFields();
// return ((number.NonStaticPublicField + number.UsePrivateField(i))
// + ClassWithFields.StaticPublicField); // <-- only if supported
// }
// }
cd = new CodeTypeDeclaration ("TestFields");
cd.IsClass = true;
nspace.Types.Add (cd);
AddScenario ("CheckUseFields");
cmm = new CodeMemberMethod ();
cmm.Name = "UseFields";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("ClassWithFields"), "number", new CodeObjectCreateExpression ("ClassWithFields")));
CodeBinaryOperatorExpression binaryOpExpression = new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression
(new CodeVariableReferenceExpression ("number"), "NonStaticPublicField"), CodeBinaryOperatorType.Add,
new CodeMethodInvokeExpression (
new CodeVariableReferenceExpression ("number"), "UsePrivateField", new CodeArgumentReferenceExpression ("i")));
if (Supports (provider, GeneratorSupport.PublicStaticMembers))
binaryOpExpression = new CodeBinaryOperatorExpression (binaryOpExpression,
CodeBinaryOperatorType.Add, new CodeFieldReferenceExpression (
new CodeTypeReferenceExpression ("ClassWithFields"), "StaticPublicField"));
cmm.Statements.Add (new CodeMethodReturnStatement (binaryOpExpression));
cd.Members.Add (cmm);
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
object genObject;
Type genType;
AddScenario ("InstantiateTestFields", "Find and instantiate TestFields class.");
if (!FindAndInstantiate("NSPC.TestFields", asm, out genObject, out genType)) // F#: edit .. no nested classes
return;
VerifyScenario ("InstantiateTestFields");
if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
if (VerifyMethod (genType, genObject, "UseFields", new object[]{3}, 14))
VerifyScenario ("CheckUseFields");
} else {
if (VerifyMethod (genType, genObject, "UseFields", new object[]{3}, 9))
VerifyScenario ("CheckUseFields");
}
}
}
| apache-2.0 |
moosbusch/xbLIDO | src/net/opengis/gml/DoubleOrNullList.java | 8651 | /*
* Copyright 2013 Gunnar Kappei.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.opengis.gml;
/**
* An XML doubleOrNullList(@http://www.opengis.net/gml).
*
* This is a list type whose items are net.opengis.gml.DoubleOrNull.
*/
public interface DoubleOrNullList extends org.apache.xmlbeans.XmlAnySimpleType
{
java.util.List getListValue();
java.util.List xgetListValue();
void setListValue(java.util.List list);
/** @deprecated */
@Deprecated
java.util.List listValue();
/** @deprecated */
@Deprecated
java.util.List xlistValue();
/** @deprecated */
@Deprecated
void set(java.util.List list);
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(DoubleOrNullList.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("doubleornulllist53a2type");
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.DoubleOrNullList newValue(java.lang.Object obj) {
return (net.opengis.gml.DoubleOrNullList) type.newValue( obj ); }
public static net.opengis.gml.DoubleOrNullList newInstance() {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.DoubleOrNullList newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.DoubleOrNullList parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.DoubleOrNullList parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.DoubleOrNullList parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.DoubleOrNullList parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.DoubleOrNullList parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.DoubleOrNullList parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.DoubleOrNullList parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.DoubleOrNullList parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.DoubleOrNullList parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.DoubleOrNullList parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.DoubleOrNullList) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| apache-2.0 |
cppfool/folly | folly/String.cpp | 15948 | /*
* Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/String.h>
#include <folly/Format.h>
#include <folly/ScopeGuard.h>
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <stdexcept>
#include <iterator>
#include <cctype>
#include <glog/logging.h>
namespace folly {
namespace {
int stringAppendfImplHelper(char* buf,
size_t bufsize,
const char* format,
va_list args) {
va_list args_copy;
va_copy(args_copy, args);
int bytes_used = vsnprintf(buf, bufsize, format, args_copy);
va_end(args_copy);
return bytes_used;
}
void stringAppendfImpl(std::string& output, const char* format, va_list args) {
// Very simple; first, try to avoid an allocation by using an inline
// buffer. If that fails to hold the output string, allocate one on
// the heap, use it instead.
//
// It is hard to guess the proper size of this buffer; some
// heuristics could be based on the number of format characters, or
// static analysis of a codebase. Or, we can just pick a number
// that seems big enough for simple cases (say, one line of text on
// a terminal) without being large enough to be concerning as a
// stack variable.
std::array<char, 128> inline_buffer;
int bytes_used = stringAppendfImplHelper(
inline_buffer.data(), inline_buffer.size(), format, args);
if (bytes_used < 0) {
throw std::runtime_error(to<std::string>(
"Invalid format string; snprintf returned negative "
"with format string: ",
format));
}
if (static_cast<size_t>(bytes_used) < inline_buffer.size()) {
output.append(inline_buffer.data(), bytes_used);
return;
}
// Couldn't fit. Heap allocate a buffer, oh well.
std::unique_ptr<char[]> heap_buffer(new char[bytes_used + 1]);
int final_bytes_used =
stringAppendfImplHelper(heap_buffer.get(), bytes_used + 1, format, args);
// The second call should require the same length, which is 1 less
// than the buffer size (we don't keep the trailing \0 byte in our
// output string).
CHECK(bytes_used == final_bytes_used);
output.append(heap_buffer.get(), bytes_used);
}
} // anon namespace
std::string stringPrintf(const char* format, ...) {
va_list ap;
va_start(ap, format);
SCOPE_EXIT {
va_end(ap);
};
return stringVPrintf(format, ap);
}
std::string stringVPrintf(const char* format, va_list ap) {
std::string ret;
stringAppendfImpl(ret, format, ap);
return ret;
}
// Basic declarations; allow for parameters of strings and string
// pieces to be specified.
std::string& stringAppendf(std::string* output, const char* format, ...) {
va_list ap;
va_start(ap, format);
SCOPE_EXIT {
va_end(ap);
};
return stringVAppendf(output, format, ap);
}
std::string& stringVAppendf(std::string* output,
const char* format,
va_list ap) {
stringAppendfImpl(*output, format, ap);
return *output;
}
void stringPrintf(std::string* output, const char* format, ...) {
va_list ap;
va_start(ap, format);
SCOPE_EXIT {
va_end(ap);
};
return stringVPrintf(output, format, ap);
}
void stringVPrintf(std::string* output, const char* format, va_list ap) {
output->clear();
stringAppendfImpl(*output, format, ap);
};
namespace {
struct PrettySuffix {
const char* suffix;
double val;
};
const PrettySuffix kPrettyTimeSuffixes[] = {
{ "s ", 1e0L },
{ "ms", 1e-3L },
{ "us", 1e-6L },
{ "ns", 1e-9L },
{ "ps", 1e-12L },
{ "s ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettyBytesMetricSuffixes[] = {
{ "TB", 1e12L },
{ "GB", 1e9L },
{ "MB", 1e6L },
{ "kB", 1e3L },
{ "B ", 0L },
{ 0, 0 },
};
const PrettySuffix kPrettyBytesBinarySuffixes[] = {
{ "TB", int64_t(1) << 40 },
{ "GB", int64_t(1) << 30 },
{ "MB", int64_t(1) << 20 },
{ "kB", int64_t(1) << 10 },
{ "B ", 0L },
{ 0, 0 },
};
const PrettySuffix kPrettyBytesBinaryIECSuffixes[] = {
{ "TiB", int64_t(1) << 40 },
{ "GiB", int64_t(1) << 30 },
{ "MiB", int64_t(1) << 20 },
{ "KiB", int64_t(1) << 10 },
{ "B ", 0L },
{ 0, 0 },
};
const PrettySuffix kPrettyUnitsMetricSuffixes[] = {
{ "tril", 1e12L },
{ "bil", 1e9L },
{ "M", 1e6L },
{ "k", 1e3L },
{ " ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettyUnitsBinarySuffixes[] = {
{ "T", int64_t(1) << 40 },
{ "G", int64_t(1) << 30 },
{ "M", int64_t(1) << 20 },
{ "k", int64_t(1) << 10 },
{ " ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettyUnitsBinaryIECSuffixes[] = {
{ "Ti", int64_t(1) << 40 },
{ "Gi", int64_t(1) << 30 },
{ "Mi", int64_t(1) << 20 },
{ "Ki", int64_t(1) << 10 },
{ " ", 0 },
{ 0, 0 },
};
const PrettySuffix kPrettySISuffixes[] = {
{ "Y", 1e24L },
{ "Z", 1e21L },
{ "E", 1e18L },
{ "P", 1e15L },
{ "T", 1e12L },
{ "G", 1e9L },
{ "M", 1e6L },
{ "k", 1e3L },
{ "h", 1e2L },
{ "da", 1e1L },
{ "d", 1e-1L },
{ "c", 1e-2L },
{ "m", 1e-3L },
{ "u", 1e-6L },
{ "n", 1e-9L },
{ "p", 1e-12L },
{ "f", 1e-15L },
{ "a", 1e-18L },
{ "z", 1e-21L },
{ "y", 1e-24L },
{ " ", 0 },
{ 0, 0}
};
const PrettySuffix* const kPrettySuffixes[PRETTY_NUM_TYPES] = {
kPrettyTimeSuffixes,
kPrettyBytesMetricSuffixes,
kPrettyBytesBinarySuffixes,
kPrettyBytesBinaryIECSuffixes,
kPrettyUnitsMetricSuffixes,
kPrettyUnitsBinarySuffixes,
kPrettyUnitsBinaryIECSuffixes,
kPrettySISuffixes,
};
} // namespace
std::string prettyPrint(double val, PrettyType type, bool addSpace) {
char buf[100];
// pick the suffixes to use
assert(type >= 0);
assert(type < PRETTY_NUM_TYPES);
const PrettySuffix* suffixes = kPrettySuffixes[type];
// find the first suffix we're bigger than -- then use it
double abs_val = fabs(val);
for (int i = 0; suffixes[i].suffix; ++i) {
if (abs_val >= suffixes[i].val) {
snprintf(buf, sizeof buf, "%.4g%s%s",
(suffixes[i].val ? (val / suffixes[i].val)
: val),
(addSpace ? " " : ""),
suffixes[i].suffix);
return std::string(buf);
}
}
// no suffix, we've got a tiny value -- just print it in sci-notation
snprintf(buf, sizeof buf, "%.4g", val);
return std::string(buf);
}
//TODO:
//1) Benchmark & optimize
double prettyToDouble(folly::StringPiece *const prettyString,
const PrettyType type) {
double value = folly::to<double>(prettyString);
while (prettyString->size() > 0 && std::isspace(prettyString->front())) {
prettyString->advance(1); //Skipping spaces between number and suffix
}
const PrettySuffix* suffixes = kPrettySuffixes[type];
int longestPrefixLen = -1;
int bestPrefixId = -1;
for (int j = 0 ; suffixes[j].suffix; ++j) {
if (suffixes[j].suffix[0] == ' '){//Checking for " " -> number rule.
if (longestPrefixLen == -1) {
longestPrefixLen = 0; //No characters to skip
bestPrefixId = j;
}
} else if (prettyString->startsWith(suffixes[j].suffix)) {
int suffixLen = strlen(suffixes[j].suffix);
//We are looking for a longest suffix matching prefix of the string
//after numeric value. We need this in case suffixes have common prefix.
if (suffixLen > longestPrefixLen) {
longestPrefixLen = suffixLen;
bestPrefixId = j;
}
}
}
if (bestPrefixId == -1) { //No valid suffix rule found
throw std::invalid_argument(folly::to<std::string>(
"Unable to parse suffix \"",
prettyString->toString(), "\""));
}
prettyString->advance(longestPrefixLen);
return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val :
value;
}
double prettyToDouble(folly::StringPiece prettyString, const PrettyType type){
double result = prettyToDouble(&prettyString, type);
detail::enforceWhitespace(prettyString.data(),
prettyString.data() + prettyString.size());
return result;
}
std::string hexDump(const void* ptr, size_t size) {
std::ostringstream os;
hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
return os.str();
}
fbstring errnoStr(int err) {
int savedErrno = errno;
// Ensure that we reset errno upon exit.
auto guard(makeGuard([&] { errno = savedErrno; }));
char buf[1024];
buf[0] = '\0';
fbstring result;
// https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
// http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
#if defined(__APPLE__) || defined(__FreeBSD__) ||\
defined(__CYGWIN__) || defined(__ANDROID__) ||\
((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)
// Using XSI-compatible strerror_r
int r = strerror_r(err, buf, sizeof(buf));
// OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
if (r != 0) {
result = to<fbstring>(
"Unknown error ", err,
" (strerror_r failed with error ", errno, ")");
} else {
result.assign(buf);
}
#else
// Using GNU strerror_r
result.assign(strerror_r(err, buf, sizeof(buf)));
#endif
return result;
}
StringPiece skipWhitespace(StringPiece sp) {
// Spaces other than ' ' characters are less common but should be
// checked. This configuration where we loop on the ' '
// separately from oddspaces was empirically fastest.
auto oddspace = [] (char c) {
return c == '\n' || c == '\t' || c == '\r';
};
loop:
for (; !sp.empty() && sp.front() == ' '; sp.pop_front()) {
}
if (!sp.empty() && oddspace(sp.front())) {
sp.pop_front();
goto loop;
}
return sp;
}
namespace {
void toLowerAscii8(char& c) {
// Branchless tolower, based on the input-rotating trick described
// at http://www.azillionmonkeys.com/qed/asmexample.html
//
// This algorithm depends on an observation: each uppercase
// ASCII character can be converted to its lowercase equivalent
// by adding 0x20.
// Step 1: Clear the high order bit. We'll deal with it in Step 5.
unsigned char rotated = c & 0x7f;
// Currently, the value of rotated, as a function of the original c is:
// below 'A': 0- 64
// 'A'-'Z': 65- 90
// above 'Z': 91-127
// Step 2: Add 0x25 (37)
rotated += 0x25;
// Now the value of rotated, as a function of the original c is:
// below 'A': 37-101
// 'A'-'Z': 102-127
// above 'Z': 128-164
// Step 3: clear the high order bit
rotated &= 0x7f;
// below 'A': 37-101
// 'A'-'Z': 102-127
// above 'Z': 0- 36
// Step 4: Add 0x1a (26)
rotated += 0x1a;
// below 'A': 63-127
// 'A'-'Z': 128-153
// above 'Z': 25- 62
// At this point, note that only the uppercase letters have been
// transformed into values with the high order bit set (128 and above).
// Step 5: Shift the high order bit 2 spaces to the right: the spot
// where the only 1 bit in 0x20 is. But first, how we ignored the
// high order bit of the original c in step 1? If that bit was set,
// we may have just gotten a false match on a value in the range
// 128+'A' to 128+'Z'. To correct this, need to clear the high order
// bit of rotated if the high order bit of c is set. Since we don't
// care about the other bits in rotated, the easiest thing to do
// is invert all the bits in c and bitwise-and them with rotated.
rotated &= ~c;
rotated >>= 2;
// Step 6: Apply a mask to clear everything except the 0x20 bit
// in rotated.
rotated &= 0x20;
// At this point, rotated is 0x20 if c is 'A'-'Z' and 0x00 otherwise
// Step 7: Add rotated to c
c += rotated;
}
void toLowerAscii32(uint32_t& c) {
// Besides being branchless, the algorithm in toLowerAscii8() has another
// interesting property: None of the addition operations will cause
// an overflow in the 8-bit value. So we can pack four 8-bit values
// into a uint32_t and run each operation on all four values in parallel
// without having to use any CPU-specific SIMD instructions.
uint32_t rotated = c & uint32_t(0x7f7f7f7fL);
rotated += uint32_t(0x25252525L);
rotated &= uint32_t(0x7f7f7f7fL);
rotated += uint32_t(0x1a1a1a1aL);
// Step 5 involves a shift, so some bits will spill over from each
// 8-bit value into the next. But that's okay, because they're bits
// that will be cleared by the mask in step 6 anyway.
rotated &= ~c;
rotated >>= 2;
rotated &= uint32_t(0x20202020L);
c += rotated;
}
void toLowerAscii64(uint64_t& c) {
// 64-bit version of toLower32
uint64_t rotated = c & uint64_t(0x7f7f7f7f7f7f7f7fL);
rotated += uint64_t(0x2525252525252525L);
rotated &= uint64_t(0x7f7f7f7f7f7f7f7fL);
rotated += uint64_t(0x1a1a1a1a1a1a1a1aL);
rotated &= ~c;
rotated >>= 2;
rotated &= uint64_t(0x2020202020202020L);
c += rotated;
}
} // anon namespace
void toLowerAscii(char* str, size_t length) {
static const size_t kAlignMask64 = 7;
static const size_t kAlignMask32 = 3;
// Convert a character at a time until we reach an address that
// is at least 32-bit aligned
size_t n = (size_t)str;
n &= kAlignMask32;
n = std::min(n, length);
size_t offset = 0;
if (n != 0) {
n = std::min(4 - n, length);
do {
toLowerAscii8(str[offset]);
offset++;
} while (offset < n);
}
n = (size_t)(str + offset);
n &= kAlignMask64;
if ((n != 0) && (offset + 4 <= length)) {
// The next address is 32-bit aligned but not 64-bit aligned.
// Convert the next 4 bytes in order to get to the 64-bit aligned
// part of the input.
toLowerAscii32(*(uint32_t*)(str + offset));
offset += 4;
}
// Convert 8 characters at a time
while (offset + 8 <= length) {
toLowerAscii64(*(uint64_t*)(str + offset));
offset += 8;
}
// Convert 4 characters at a time
while (offset + 4 <= length) {
toLowerAscii32(*(uint32_t*)(str + offset));
offset += 4;
}
// Convert any characters remaining after the last 4-byte aligned group
while (offset < length) {
toLowerAscii8(str[offset]);
offset++;
}
}
namespace detail {
size_t hexDumpLine(const void* ptr, size_t offset, size_t size,
std::string& line) {
// Line layout:
// 8: address
// 1: space
// (1+2)*16: hex bytes, each preceded by a space
// 1: space separating the two halves
// 3: " |"
// 16: characters
// 1: "|"
// Total: 78
line.clear();
line.reserve(78);
const uint8_t* p = reinterpret_cast<const uint8_t*>(ptr) + offset;
size_t n = std::min(size - offset, size_t(16));
format("{:08x} ", offset).appendTo(line);
for (size_t i = 0; i < n; i++) {
if (i == 8) {
line.push_back(' ');
}
format(" {:02x}", p[i]).appendTo(line);
}
// 3 spaces for each byte we're not printing, one separating the halves
// if necessary
line.append(3 * (16 - n) + (n <= 8), ' ');
line.append(" |");
for (size_t i = 0; i < n; i++) {
char c = (p[i] >= 32 && p[i] <= 126 ? static_cast<char>(p[i]) : '.');
line.push_back(c);
}
line.append(16 - n, ' ');
line.push_back('|');
DCHECK_EQ(line.size(), 78);
return n;
}
} // namespace detail
} // namespace folly
#ifdef FOLLY_DEFINED_DMGL
# undef FOLLY_DEFINED_DMGL
# undef DMGL_NO_OPTS
# undef DMGL_PARAMS
# undef DMGL_ANSI
# undef DMGL_JAVA
# undef DMGL_VERBOSE
# undef DMGL_TYPES
# undef DMGL_RET_POSTFIX
#endif
| apache-2.0 |
mchmarny/thingz-agent | main.go | 658 | package main
import (
"log"
"os"
"os/signal"
"runtime"
)
func main() {
runtime.GOMAXPROCS(1) // don't let it go multi-process
// make sure we can shutdown gracefully
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
doneDone := make(chan bool)
errCh := make(chan error, 1)
go func() {
c, err := newCollector()
if err != nil {
errCh <- err
}
errCh <- c.collect()
}()
go func() {
for {
select {
case err := <-errCh:
log.Printf("Error: %v", err)
case ex := <-sigCh:
log.Println("Shutting down due to: ", ex)
doneDone <- true
default:
// nothing to do
}
}
}()
<-doneDone
}
| apache-2.0 |
ssanj/pondskum | src/main/java/com/googlecode/pondskum/gui/swing/suite/GuiController.java | 1626 | /*
* Copyright 2008 Sanjiv Sahayam
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.pondskum.gui.swing.suite;
import com.googlecode.pondskum.client.BigpondUsageInformation;
/**
* Defines how a gui controller should behave. The controller is a controller in an MVC pattern and as such handles all user input and
* notifications to the various guis.
*/
public interface GuiController {
/**
* Notifies the implementation of this interface that the status has changed and should be updated in the views.
* @param status The update to display in the views.
*/
void notifyStatusChange(String status);
/**
* The connection completed successfully and the usage is ready for retrieval.
* @param bigpondUsageInformation The usage information from the connection.
*/
void connectionSucceeded(BigpondUsageInformation bigpondUsageInformation);
/**
* The connection failed and the exception that occurred is ready for retrieval.
* @param exception The exception that occurred.
*/
void connectionFailed(Exception exception);
}
| apache-2.0 |
ColmexBDCV/sufia-oai | app/search_builders/search_builder.rb | 261 | class SearchBuilder < Blacklight::SearchBuilder
include Blacklight::Solr::SearchBuilderBehavior
include Hydra::AccessControlsEnforcement
include CurationConcerns::SearchFilters
include Hydra::PolicyAwareAccessControlsEnforcement
include HasLogger
end
| apache-2.0 |
JetBrains/intellij-scala | scala/scala-impl/testdata/changeSignature/fromJava/OverriderInAnonClass_after.scala | 151 | object Test {
val x = new OverriderInAnonClass {
override def bar(b: Boolean, ii: Int): Boolean = ii + 2
}
x.bar(true, 1)
x.bar(true, 1)
} | apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/GetFunctionConfigurationResult.java | 27639 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.lambda.model;
import java.io.Serializable;
/**
* <p>
* A complex type that describes function metadata.
* </p>
*/
public class GetFunctionConfigurationResult implements Serializable, Cloneable {
/**
* The name of the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*/
private String functionName;
/**
* The Amazon Resource Name (ARN) assigned to the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*/
private String functionArn;
/**
* The runtime environment for the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*/
private String runtime;
/**
* The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+<br/>
*/
private String role;
/**
* The function Lambda calls to begin executing your function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 128<br/>
* <b>Pattern: </b>[^\s]+<br/>
*/
private String handler;
/**
* The size, in bytes, of the function .zip file you uploaded.
*/
private Long codeSize;
/**
* The user-provided description.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*/
private String description;
/**
* The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>1 - <br/>
*/
private Integer timeout;
/**
* The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>128 - 1536<br/>
*/
private Integer memorySize;
/**
* The timestamp of the last time you updated the function.
*/
private String lastModified;
/**
* It is the SHA256 hash of your function deployment package.
*/
private String codeSha256;
/**
* The version of the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*/
private String version;
/**
* The name of the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @return The name of the function.
*/
public String getFunctionName() {
return functionName;
}
/**
* The name of the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionName The name of the function.
*/
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
/**
* The name of the function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionName The name of the function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withFunctionName(String functionName) {
this.functionName = functionName;
return this;
}
/**
* The Amazon Resource Name (ARN) assigned to the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @return The Amazon Resource Name (ARN) assigned to the function.
*/
public String getFunctionArn() {
return functionArn;
}
/**
* The Amazon Resource Name (ARN) assigned to the function.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionArn The Amazon Resource Name (ARN) assigned to the function.
*/
public void setFunctionArn(String functionArn) {
this.functionArn = functionArn;
}
/**
* The Amazon Resource Name (ARN) assigned to the function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:lambda:[a-z]{2}-[a-z]+-\d{1}:\d{12}:function:[a-zA-Z0-9-_]+(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionArn The Amazon Resource Name (ARN) assigned to the function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withFunctionArn(String functionArn) {
this.functionArn = functionArn;
return this;
}
/**
* The runtime environment for the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*
* @return The runtime environment for the Lambda function.
*
* @see Runtime
*/
public String getRuntime() {
return runtime;
}
/**
* The runtime environment for the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*
* @param runtime The runtime environment for the Lambda function.
*
* @see Runtime
*/
public void setRuntime(String runtime) {
this.runtime = runtime;
}
/**
* The runtime environment for the Lambda function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*
* @param runtime The runtime environment for the Lambda function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see Runtime
*/
public GetFunctionConfigurationResult withRuntime(String runtime) {
this.runtime = runtime;
return this;
}
/**
* The runtime environment for the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*
* @param runtime The runtime environment for the Lambda function.
*
* @see Runtime
*/
public void setRuntime(Runtime runtime) {
this.runtime = runtime.toString();
}
/**
* The runtime environment for the Lambda function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>nodejs, java8, python2.7
*
* @param runtime The runtime environment for the Lambda function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see Runtime
*/
public GetFunctionConfigurationResult withRuntime(Runtime runtime) {
this.runtime = runtime.toString();
return this;
}
/**
* The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+<br/>
*
* @return The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
*/
public String getRole() {
return role;
}
/**
* The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+<br/>
*
* @param role The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
*/
public void setRole(String role) {
this.role = role;
}
/**
* The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+<br/>
*
* @param role The Amazon Resource Name (ARN) of the IAM role that Lambda assumes
* when it executes your function to access any other Amazon Web Services
* (AWS) resources.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withRole(String role) {
this.role = role;
return this;
}
/**
* The function Lambda calls to begin executing your function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 128<br/>
* <b>Pattern: </b>[^\s]+<br/>
*
* @return The function Lambda calls to begin executing your function.
*/
public String getHandler() {
return handler;
}
/**
* The function Lambda calls to begin executing your function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 128<br/>
* <b>Pattern: </b>[^\s]+<br/>
*
* @param handler The function Lambda calls to begin executing your function.
*/
public void setHandler(String handler) {
this.handler = handler;
}
/**
* The function Lambda calls to begin executing your function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 128<br/>
* <b>Pattern: </b>[^\s]+<br/>
*
* @param handler The function Lambda calls to begin executing your function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withHandler(String handler) {
this.handler = handler;
return this;
}
/**
* The size, in bytes, of the function .zip file you uploaded.
*
* @return The size, in bytes, of the function .zip file you uploaded.
*/
public Long getCodeSize() {
return codeSize;
}
/**
* The size, in bytes, of the function .zip file you uploaded.
*
* @param codeSize The size, in bytes, of the function .zip file you uploaded.
*/
public void setCodeSize(Long codeSize) {
this.codeSize = codeSize;
}
/**
* The size, in bytes, of the function .zip file you uploaded.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param codeSize The size, in bytes, of the function .zip file you uploaded.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withCodeSize(Long codeSize) {
this.codeSize = codeSize;
return this;
}
/**
* The user-provided description.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @return The user-provided description.
*/
public String getDescription() {
return description;
}
/**
* The user-provided description.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @param description The user-provided description.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* The user-provided description.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @param description The user-provided description.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withDescription(String description) {
this.description = description;
return this;
}
/**
* The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>1 - <br/>
*
* @return The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
*/
public Integer getTimeout() {
return timeout;
}
/**
* The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>1 - <br/>
*
* @param timeout The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
*/
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
/**
* The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>1 - <br/>
*
* @param timeout The function execution time at which Lambda should terminate the
* function. Because the execution time has cost implications, we
* recommend you set this value based on your expected execution time.
* The default is 3 seconds.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withTimeout(Integer timeout) {
this.timeout = timeout;
return this;
}
/**
* The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>128 - 1536<br/>
*
* @return The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
*/
public Integer getMemorySize() {
return memorySize;
}
/**
* The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>128 - 1536<br/>
*
* @param memorySize The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
*/
public void setMemorySize(Integer memorySize) {
this.memorySize = memorySize;
}
/**
* The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>128 - 1536<br/>
*
* @param memorySize The memory size, in MB, you configured for the function. Must be a
* multiple of 64 MB.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withMemorySize(Integer memorySize) {
this.memorySize = memorySize;
return this;
}
/**
* The timestamp of the last time you updated the function.
*
* @return The timestamp of the last time you updated the function.
*/
public String getLastModified() {
return lastModified;
}
/**
* The timestamp of the last time you updated the function.
*
* @param lastModified The timestamp of the last time you updated the function.
*/
public void setLastModified(String lastModified) {
this.lastModified = lastModified;
}
/**
* The timestamp of the last time you updated the function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param lastModified The timestamp of the last time you updated the function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withLastModified(String lastModified) {
this.lastModified = lastModified;
return this;
}
/**
* It is the SHA256 hash of your function deployment package.
*
* @return It is the SHA256 hash of your function deployment package.
*/
public String getCodeSha256() {
return codeSha256;
}
/**
* It is the SHA256 hash of your function deployment package.
*
* @param codeSha256 It is the SHA256 hash of your function deployment package.
*/
public void setCodeSha256(String codeSha256) {
this.codeSha256 = codeSha256;
}
/**
* It is the SHA256 hash of your function deployment package.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param codeSha256 It is the SHA256 hash of your function deployment package.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withCodeSha256(String codeSha256) {
this.codeSha256 = codeSha256;
return this;
}
/**
* The version of the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @return The version of the Lambda function.
*/
public String getVersion() {
return version;
}
/**
* The version of the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @param version The version of the Lambda function.
*/
public void setVersion(String version) {
this.version = version;
}
/**
* The version of the Lambda function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @param version The version of the Lambda function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public GetFunctionConfigurationResult withVersion(String version) {
this.version = version;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFunctionName() != null) sb.append("FunctionName: " + getFunctionName() + ",");
if (getFunctionArn() != null) sb.append("FunctionArn: " + getFunctionArn() + ",");
if (getRuntime() != null) sb.append("Runtime: " + getRuntime() + ",");
if (getRole() != null) sb.append("Role: " + getRole() + ",");
if (getHandler() != null) sb.append("Handler: " + getHandler() + ",");
if (getCodeSize() != null) sb.append("CodeSize: " + getCodeSize() + ",");
if (getDescription() != null) sb.append("Description: " + getDescription() + ",");
if (getTimeout() != null) sb.append("Timeout: " + getTimeout() + ",");
if (getMemorySize() != null) sb.append("MemorySize: " + getMemorySize() + ",");
if (getLastModified() != null) sb.append("LastModified: " + getLastModified() + ",");
if (getCodeSha256() != null) sb.append("CodeSha256: " + getCodeSha256() + ",");
if (getVersion() != null) sb.append("Version: " + getVersion() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFunctionName() == null) ? 0 : getFunctionName().hashCode());
hashCode = prime * hashCode + ((getFunctionArn() == null) ? 0 : getFunctionArn().hashCode());
hashCode = prime * hashCode + ((getRuntime() == null) ? 0 : getRuntime().hashCode());
hashCode = prime * hashCode + ((getRole() == null) ? 0 : getRole().hashCode());
hashCode = prime * hashCode + ((getHandler() == null) ? 0 : getHandler().hashCode());
hashCode = prime * hashCode + ((getCodeSize() == null) ? 0 : getCodeSize().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode());
hashCode = prime * hashCode + ((getMemorySize() == null) ? 0 : getMemorySize().hashCode());
hashCode = prime * hashCode + ((getLastModified() == null) ? 0 : getLastModified().hashCode());
hashCode = prime * hashCode + ((getCodeSha256() == null) ? 0 : getCodeSha256().hashCode());
hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof GetFunctionConfigurationResult == false) return false;
GetFunctionConfigurationResult other = (GetFunctionConfigurationResult)obj;
if (other.getFunctionName() == null ^ this.getFunctionName() == null) return false;
if (other.getFunctionName() != null && other.getFunctionName().equals(this.getFunctionName()) == false) return false;
if (other.getFunctionArn() == null ^ this.getFunctionArn() == null) return false;
if (other.getFunctionArn() != null && other.getFunctionArn().equals(this.getFunctionArn()) == false) return false;
if (other.getRuntime() == null ^ this.getRuntime() == null) return false;
if (other.getRuntime() != null && other.getRuntime().equals(this.getRuntime()) == false) return false;
if (other.getRole() == null ^ this.getRole() == null) return false;
if (other.getRole() != null && other.getRole().equals(this.getRole()) == false) return false;
if (other.getHandler() == null ^ this.getHandler() == null) return false;
if (other.getHandler() != null && other.getHandler().equals(this.getHandler()) == false) return false;
if (other.getCodeSize() == null ^ this.getCodeSize() == null) return false;
if (other.getCodeSize() != null && other.getCodeSize().equals(this.getCodeSize()) == false) return false;
if (other.getDescription() == null ^ this.getDescription() == null) return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false;
if (other.getTimeout() == null ^ this.getTimeout() == null) return false;
if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false) return false;
if (other.getMemorySize() == null ^ this.getMemorySize() == null) return false;
if (other.getMemorySize() != null && other.getMemorySize().equals(this.getMemorySize()) == false) return false;
if (other.getLastModified() == null ^ this.getLastModified() == null) return false;
if (other.getLastModified() != null && other.getLastModified().equals(this.getLastModified()) == false) return false;
if (other.getCodeSha256() == null ^ this.getCodeSha256() == null) return false;
if (other.getCodeSha256() != null && other.getCodeSha256().equals(this.getCodeSha256()) == false) return false;
if (other.getVersion() == null ^ this.getVersion() == null) return false;
if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false) return false;
return true;
}
@Override
public GetFunctionConfigurationResult clone() {
try {
return (GetFunctionConfigurationResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| apache-2.0 |
tatemura/strudel | workload/src/main/java/com/nec/strudel/metrics/ProfilerValue.java | 6312 | /*******************************************************************************
* Copyright 2015, 2016 Junichi Tatemura
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.nec.strudel.metrics;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
import com.nec.strudel.json.JsonValues;
public final class ProfilerValue {
private ProfilerValue() {
// not instantiated
}
protected static Map<String, BigDecimal> jsonToMap(JsonObject json) {
Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
for (String name : json.keySet()) {
BigDecimal value = json.getJsonNumber(name)
.bigDecimalValue();
map.put(name, value);
}
return map;
}
public static Builder builder(String name) {
return new Builder(name);
}
public static Combiner combiner() {
return new Combiner();
}
public static Aggregator aggregator() {
return new Aggregator();
}
public static class Builder {
private final String name;
private final JsonObjectBuilder jsonBuilder =
Json.createObjectBuilder();
Builder(String name) {
this.name = name;
}
public Builder set(String name, long value) {
jsonBuilder.add(name, value);
return this;
}
public Builder set(String name, double value) {
jsonBuilder.add(name, value);
return this;
}
public Builder set(Map<String, ? extends Number> values) {
for (Map.Entry<String, ? extends Number> e : values.entrySet()) {
BigDecimal val = new BigDecimal(
e.getValue().toString());
jsonBuilder.add(e.getKey(), val);
}
return this;
}
public JsonObject build() {
return Json.createObjectBuilder()
.add(name, jsonBuilder.build())
.build();
}
}
public static class Combiner {
private final List<String> keys = new ArrayList<String>();
private final Map<String, JsonValue> values = new HashMap<String, JsonValue>();
public Combiner add(JsonObject valueSet) {
for (Map.Entry<String, JsonValue> e : valueSet.entrySet()) {
add(e.getKey(), e.getValue());
}
return this;
}
public Combiner add(String name, JsonValue value) {
if (!values.containsKey(name)) {
keys.add(name);
}
values.put(name, value);
return this;
}
public Combiner add(String name, long value) {
return add(name, JsonValues.toValue(value));
}
public JsonObject build() {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (String key : keys) {
builder.add(key, values.get(key));
}
return builder.build();
}
}
public static class Aggregator {
private final Map<String, JsonObject> values = new HashMap<String, JsonObject>();
public Aggregator add(JsonObject valueSets) {
for (String key : valueSets.keySet()) {
add(key, valueSets.getJsonObject(key));
}
return this;
}
private Aggregator add(String name, JsonObject value) {
JsonObject value0 = values.get(name);
if (value0 != null) {
values.put(name,
add(value0, value));
} else {
values.put(name, value);
}
return this;
}
private JsonObject add(JsonObject v1, JsonObject v2) {
Map<String, BigDecimal> map1 = jsonToMap(v1);
Map<String, BigDecimal> map2 = jsonToMap(v2);
for (Map.Entry<String, BigDecimal> e : map2.entrySet()) {
BigDecimal v0 = e.getValue();
BigDecimal val = map1.get(e.getKey());
map1.put(e.getKey(),
(val != null ? v0.add(val) : v0));
}
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String, BigDecimal> e : map1.entrySet()) {
builder.add(e.getKey(), e.getValue());
}
return builder.build();
}
private JsonObject toJson(Map<String, JsonObject> values) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String, JsonObject> e : values.entrySet()) {
builder.add(e.getKey(), e.getValue());
}
return builder.build();
}
public JsonObject build() {
return toJson(values);
}
}
public static JsonObject aggregate(JsonObject... values) {
Aggregator aggr = new Aggregator();
for (JsonObject v : values) {
aggr.add(v);
}
return aggr.build();
}
public static JsonObject aggregate(Iterable<JsonObject> values) {
Aggregator aggr = new Aggregator();
for (JsonObject v : values) {
aggr.add(v);
}
return aggr.build();
}
public static JsonObject combine(JsonObject... valueSets) {
Combiner comb = new Combiner();
for (JsonObject v : valueSets) {
comb.add(v);
}
return comb.build();
}
}
| apache-2.0 |
mccraigmccraig/maxent | src/main/java/opennlp/maxent/DomainToModelMap.java | 2776 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreemnets. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opennlp.maxent;
import java.util.*;
import opennlp.model.MaxentModel;
/**
* A class which stores a mapping from ModelDomain objects to MaxentModels.
* This permits an application to replace an old model for a domain with a
* newly trained one in a thread-safe manner. By calling the getModel()
* method, the application can create new instances of classes which use the
* relevant models.
*
* @author Jason Baldridge and Eric Friedman
* @version $Revision: 1.1 $, $Date: 2009/01/22 23:23:34 $
*/
public class DomainToModelMap {
// the underlying object which stores the mapping
private Map map = Collections.synchronizedMap(new HashMap());
/**
* Sets the model for the given domain.
*
* @param domain The ModelDomain object which keys to the model.
* @param model The MaxentModel trained for the domain.
*/
public void setModelForDomain (ModelDomain domain, MaxentModel model) {
map.put(domain, model);
}
/**
* Get the model mapped to by the given ModelDomain key.
*
* @param domain The ModelDomain object which keys to the desired model.
* @return The MaxentModel corresponding to the given domain.
*/
public MaxentModel getModel (ModelDomain domain) {
if (map.containsKey(domain)) {
return (MaxentModel)map.get(domain);
} else {
throw new NoSuchElementException("No model has been created for "+
"domain: " + domain);
}
}
/**
* Removes the mapping for this ModelDomain key from this map if present.
*
* @param domain The ModelDomain key whose mapping is to be removed from
* the map.
*/
public void removeDomain (ModelDomain domain) {
map.remove(domain);
}
/**
* A set view of the ModelDomain keys contained in this map.
*
* @return a set view of the ModelDomain keys contained in this map
*/
public Set keySet () {
return map.keySet();
}
}
| apache-2.0 |
chiradeep/go-nitro | config/network/vrid6_binding.go | 76 | package network
type Vrid6binding struct {
Id int `json:"id,omitempty"`
}
| apache-2.0 |
Reactive-Extensions/RxPy | tests/test_immediatescheduler.py | 3029 | from datetime import datetime, timedelta
from rx.concurrency import Scheduler, ImmediateScheduler
from rx.disposables import Disposable
def test_immediate_now():
res = Scheduler.now() - datetime.utcnow()
assert res < timedelta(milliseconds=1000)
def test_immediate_scheduleaction():
scheduler = ImmediateScheduler()
ran = False;
def action(scheduler, state=None):
nonlocal ran
ran = True
scheduler.schedule(action)
assert ran
def test_immediate_scheduleactionerror():
scheduler = ImmediateScheduler()
class MyException(Exception):
pass
def action(scheduler, state=None):
raise MyException()
try:
return scheduler.schedule(action)
except MyException:
assert True
def test_immediate_simple1():
scheduler = ImmediateScheduler()
xx = 0
def action(scheduler, state=None):
nonlocal xx
xx = state
return Disposable.empty()
scheduler.schedule(action, 42)
assert xx == 42
def test_immediate_simple2():
scheduler = ImmediateScheduler()
xx = 0
def action(scheduler, state=None):
nonlocal xx
xx = state
return Disposable.empty()
scheduler.schedule_absolute(datetime.utcnow(), action, 42);
assert xx == 42
def test_immediate_simple3():
scheduler = ImmediateScheduler()
xx = 0
def action(scheduler, state=None):
nonlocal xx
xx = state
return Disposable.empty()
scheduler.schedule_relative(timedelta(0), action, 42);
assert xx == 42
def test_immediate_recursive1():
scheduler = ImmediateScheduler()
xx = 0
yy = 0
def action(scheduler, x=None):
nonlocal xx
xx = x
def inner_action(scheduler, y):
nonlocal yy
yy = y
return Disposable.empty()
return scheduler.schedule(inner_action, 43)
scheduler.schedule(action, 42)
assert xx == 42
assert yy == 43
def test_immediate_recursive2():
scheduler = ImmediateScheduler()
xx = 0
yy = 0
def action(scheduler, state=None):
nonlocal xx
xx = state
def inner_action(scheduler, state=None):
nonlocal yy
yy = state
return Disposable.empty()
return scheduler.schedule_absolute(datetime.utcnow(), inner_action, 43)
scheduler.schedule_absolute(datetime.utcnow(), action, 42)
assert xx == 42
assert yy == 43
def test_immediate_recursive3():
scheduler = ImmediateScheduler()
xx = 0
yy = 0
def action(scheduler, state=None):
nonlocal xx
xx = state
def inner_action(scheduler, state):
nonlocal yy
yy = state
return Disposable.empty()
return scheduler.schedule_relative(timedelta(0), inner_action, 43)
scheduler.schedule_relative(timedelta(0), action, 42)
assert xx == 42
assert yy == 43
| apache-2.0 |
EtaliaSA/sdk-java | src/main/java/net/etalia/client/http/JsonedException.java | 582 | package net.etalia.client.http;
import java.util.Map;
public class JsonedException extends RuntimeException {
private static final long serialVersionUID = -4745379703039071409L;
private Map<String, Object> properties;
private int statusCode;
public JsonedException(String message, Map<String, Object> properties, int statusCode) {
super(message + properties.toString());
this.properties = properties;
this.statusCode = statusCode;
}
public Map<String, Object> getProperties() {
return properties;
}
public int getStatusCode() {
return statusCode;
}
}
| apache-2.0 |
dotindo/6ba5ea2b | DotWeb/DotWeb/Attributes/ScaffoldAttribute.cs | 1114 | using System;
namespace DotWeb
{
/// <summary>
/// This option corresponds to DevExpress grid view edit mode.
/// </summary>
public enum EditMode
{
Default,
Inline,
Popup,
EditPage
}
/// <summary>
/// Used in entity scaffolding to mark entities to scaffold.
/// </summary>
public class ScaffoldAttribute : Attribute
{
/// <summary>
/// Default constructor.
/// </summary>
public ScaffoldAttribute()
{
Group = "";
OrderNo = 0;
EditMode = EditMode.Default;
}
/// <summary>
/// Scaffolded entity also generates menu item. This property indicates the group where this menu item belongs to.
/// </summary>
public string Group { get; set; }
/// <summary>
/// Menu item order number in the group.
/// </summary>
public int OrderNo { get; set; }
/// <summary>
/// The edit mode for this entity.
/// </summary>
public EditMode EditMode { get; set; }
}
}
| apache-2.0 |
zhangdaiscott/jeecg-boot | jeecg-boot/jeecg-boot-base/jeecg-boot-base-core/src/main/java/org/jeecg/common/constant/WebsocketConst.java | 1183 | package org.jeecg.common.constant;
/**
* @Description: Websocket常量类
* @author: taoyan
* @date: 2020年03月23日
*/
public class WebsocketConst {
/**
* 消息json key:cmd
*/
public static final String MSG_CMD = "cmd";
/**
* 消息json key:msgId
*/
public static final String MSG_ID = "msgId";
/**
* 消息json key:msgTxt
*/
public static final String MSG_TXT = "msgTxt";
/**
* 消息json key:userId
*/
public static final String MSG_USER_ID = "userId";
/**
* 消息类型 heartcheck
*/
public static final String CMD_CHECK = "heartcheck";
/**
* 消息类型 user 用户消息
*/
public static final String CMD_USER = "user";
/**
* 消息类型 topic 系统通知
*/
public static final String CMD_TOPIC = "topic";
/**
* 消息类型 email
*/
public static final String CMD_EMAIL = "email";
/**
* 消息类型 meetingsign 会议签到
*/
public static final String CMD_SIGN = "sign";
/**
* 消息类型 新闻发布/取消
*/
public static final String NEWS_PUBLISH = "publish";
}
| apache-2.0 |
ow2-xlcloud/vcms | impl/src/main/java/org/xlcloud/service/iam/grants/IamEntitlementsManager.java | 9534 | /*
* Copyright 2012 AMG.lab, a Bull Group Company
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xlcloud.service.iam.grants;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.xlcloud.config.ConfigParam;
import org.xlcloud.service.Entitlement;
import org.xlcloud.service.Entitlements;
import org.xlcloud.service.manager.EntitlementsManager;
import com.sun.identity.sm.ServiceManager;
/**
* Manager responsible for grants manaement
*
* @author Jakub Wachowski, AMG.net
*/
public class IamEntitlementsManager implements EntitlementsManager {
@Inject
private UserEntitlementServiceClient userEntitlementClient;
@Inject
private AccessTokenEntitlementServiceClient accessTokenEntitlementClient;
@Inject
@ConfigParam
private String xlcRealmName;
// for example:
// "id=2015453534043454343,ou=user,o=xlc,ou=services,dc=openam,dc=forgerock,dc=org",
private String USER_DN_PATTERN = "id=${ID}" + ",ou=user,o=${REALM},ou=services," + ServiceManager.getBaseDN();
private String GROUP_DN_PATTERN = "id=${ID}" + ",ou=group,o=${REALM},ou=services," + ServiceManager.getBaseDN();
private final String USER_GRANT_PREFIX = "u";
private final String GROUP_GRANT_PREFIX = "g";
private final String ACCESS_TOKEN_GRANT_PREFIX = "at";
private static final Logger LOG = Logger.getLogger(IamEntitlementsManager.class);
public IamEntitlementsManager() {
}
public IamEntitlementsManager( String realm ) {
this();
xlcRealmName = realm;
}
/** {@inheritDoc} */
@Override
public Entitlement createUserEntitlement(Long userId, Entitlement entitlement) {
if (LOG.isDebugEnabled()) {
LOG.debug("createUserEntitlement - userId=" + userId + ", ent=" + entitlement);
}
String subjectUid = getUserDn(userId.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("userDN: " + subjectUid);
}
Entitlement ent = userEntitlementClient.createEntitlement(subjectUid, USER_GRANT_PREFIX + userId, entitlement);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlement: " + ent);
}
return ent;
}
/** {@inheritDoc} */
@Override
public Entitlements createUserEntitlements(Long userId, Entitlements entitlements) {
if (LOG.isDebugEnabled()) {
LOG.debug("createUserEntitlement - userId=" + userId + ", ent=" + entitlements);
}
String subjectUid = getUserDn(userId.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("userDN: " + subjectUid);
}
Entitlements ents = userEntitlementClient.createEntitlements(subjectUid, USER_GRANT_PREFIX + userId, entitlements);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlements: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public Entitlements getUserEntitlements(Long userId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to get entitlements for user " + userId);
}
Entitlements ents = userEntitlementClient.getEntitlements(USER_GRANT_PREFIX + userId);
if (LOG.isDebugEnabled()) {
LOG.debug("Found entitlements: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public Entitlements getTokenEntitlements(String tokenId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to get entitlements for token " + tokenId);
}
Entitlements ents = accessTokenEntitlementClient.getEntitlements(ACCESS_TOKEN_GRANT_PREFIX + tokenId);
if (LOG.isDebugEnabled()) {
LOG.debug("Found entitlements: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public Entitlement createGroupEntitlement(Long groupId, Entitlement entitlement) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating entitlement for group " + groupId + ": " + entitlement);
}
String subjectUid = getGroupDn(groupId.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("groupDN: " + subjectUid);
}
Entitlement ent = userEntitlementClient.createEntitlement(subjectUid, GROUP_GRANT_PREFIX + groupId, entitlement);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlement: " + ent);
}
return ent;
}
/** {@inheritDoc} */
@Override
public Entitlements createGroupEntitlements(Long groupId, Entitlements entitlements) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating entitlements for group " + groupId + ": " + entitlements);
}
String subjectUid = getGroupDn(groupId.toString());
if (LOG.isDebugEnabled()) {
LOG.debug("groupDN: " + subjectUid);
}
Entitlements ents = userEntitlementClient.createEntitlements(subjectUid, GROUP_GRANT_PREFIX + groupId, entitlements);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlement: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public Entitlements getGroupEntitlements(Long groupId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to get entitlements for group " + groupId);
}
Entitlements ents = userEntitlementClient.getEntitlements(GROUP_GRANT_PREFIX + groupId);
if (LOG.isDebugEnabled()) {
LOG.debug("Found entitlements: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public void removeUserEntitlement(Long userId, Long grantId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing entitlement " + grantId + " from user " + userId);
}
userEntitlementClient.removeEntitlement(USER_GRANT_PREFIX + userId, grantId.toString());
}
/** {@inheritDoc} */
@Override
public void removeGroupEntitlement(Long groupId, Long grantId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing entitlement " + grantId + " from group " + groupId);
}
userEntitlementClient.removeEntitlement(GROUP_GRANT_PREFIX + groupId, grantId.toString());
}
/** {@inheritDoc} */
private String getUserDn(String userId) {
return USER_DN_PATTERN.replace("${ID}", userId).replace("${REALM}", xlcRealmName);
}
private String getGroupDn(String groupId) {
return GROUP_DN_PATTERN.replace("${ID}", groupId).replace("${REALM}", xlcRealmName);
}
/** {@inheritDoc} */
@Override
public Entitlement createTokenEntitlement(String tokenId, Entitlement entitlement) {
if (LOG.isDebugEnabled()) {
LOG.debug("createTokenEntitlement - tokenId=" + tokenId + ", ent=" + entitlement);
}
Entitlement ent = accessTokenEntitlementClient.createEntitlement(tokenId, ACCESS_TOKEN_GRANT_PREFIX + tokenId, entitlement);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlement: " + ent);
}
return ent;
}
/** {@inheritDoc} */
@Override
public Entitlements createTokenEntitlements(String tokenId, Entitlements entitlements) {
if (LOG.isDebugEnabled()) {
LOG.debug("createTokenEntitlements - tokenId=" + tokenId + ", ent=" + entitlements);
}
Entitlements ents = accessTokenEntitlementClient.createEntitlements(tokenId, ACCESS_TOKEN_GRANT_PREFIX + tokenId, entitlements);
if (LOG.isDebugEnabled()) {
LOG.debug("created entitlement: " + ents);
}
return ents;
}
/** {@inheritDoc} */
@Override
public void removeTokenEntitlement(String tokenId, Long entitlementId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing entitlement " + entitlementId + " from token " + tokenId);
}
accessTokenEntitlementClient.removeEntitlement(ACCESS_TOKEN_GRANT_PREFIX + tokenId, entitlementId.toString());
}
/** {@inheritDoc} */
@Override
public void removeAllUserEntitlements(Long userId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing all entitlements for user " + userId);
}
userEntitlementClient.removeAllEntitlements(USER_GRANT_PREFIX + userId);
}
/** {@inheritDoc} */
@Override
public void removeAllGroupEntitlements(Long groupId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing all entitlements for group " + groupId);
}
userEntitlementClient.removeAllEntitlements(GROUP_GRANT_PREFIX + groupId);
}
/** {@inheritDoc} */
@Override
public void removeAllTokenEntitlements(String tokenId) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing all entitlements for access token " + tokenId);
}
accessTokenEntitlementClient.removeAllEntitlements(ACCESS_TOKEN_GRANT_PREFIX + tokenId);
}
}
| apache-2.0 |
jphp-compiler/jphp | exts/jphp-sql-ext/src/main/java/org/develnext/jphp/ext/sql/classes/PSqlConnection.java | 7337 | package org.develnext.jphp.ext.sql.classes;
import org.develnext.jphp.ext.sql.SqlExtension;
import php.runtime.Memory;
import php.runtime.annotation.Reflection.*;
import php.runtime.env.Environment;
import php.runtime.lang.BaseObject;
import php.runtime.memory.ArrayMemory;
import php.runtime.memory.LongMemory;
import php.runtime.memory.ReferenceMemory;
import php.runtime.reflection.ClassEntity;
import java.sql.*;
@Abstract
@Name("SqlConnection")
@Namespace(SqlExtension.NS)
public class PSqlConnection extends BaseObject {
public static final int TRANSACTION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;
public static final int TRANSACTION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;
public static final int TRANSACTION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;
public static final int TRANSACTION_NONE = Connection.TRANSACTION_NONE;
public static final int TRANSACTION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;
protected Connection connection;
protected DatabaseMetaData metaData;
public PSqlConnection(Environment env, Connection connection) {
super(env);
this.connection = connection;
try {
this.metaData = connection.getMetaData();
} catch (SQLException e) {
throw new WrapSqlException(env, e);
}
}
public PSqlConnection(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Setter
public void setAutoCommit(boolean value) throws SQLException {
connection.setAutoCommit(value);
}
@Getter
public boolean getAutoCommit() throws SQLException {
return connection.getAutoCommit();
}
@Setter
public void setReadOnly(boolean value) throws SQLException {
connection.setReadOnly(value);
}
@Getter
public boolean getReadOnly() throws SQLException {
return connection.isReadOnly();
}
@Setter
public void setTransactionIsolation(int value) throws SQLException {
connection.setTransactionIsolation(value);
}
@Getter
public int getTransactionIsolation() throws SQLException {
return connection.getTransactionIsolation();
}
@Setter
public void setCatalog(String value) throws SQLException {
connection.setCatalog(value);
}
@Getter
public String getCatalog() throws SQLException {
return connection.getCatalog();
}
@Signature
public Memory getCatalogs(Environment env) throws SQLException {
ResultSet catalogs = metaData.getCatalogs();
ArrayMemory r = new ArrayMemory();
while (catalogs.next()) {
r.add(new PSqlResult(env, catalogs).toArray(env));
}
return r.toConstant();
}
@Signature
public Memory getSchemas(Environment env) throws SQLException {
ResultSet schemas = metaData.getSchemas();
ArrayMemory r = new ArrayMemory();
while (schemas.next()) {
r.add(new PSqlResult(env, schemas).toArray(env));
}
return r.toConstant();
}
@Signature
public Memory getMetaData() throws SQLException {
ArrayMemory r = new ArrayMemory();
r.refOfIndex("userName").assign(metaData.getUserName());
r.refOfIndex("driverName").assign(metaData.getDriverName());
r.refOfIndex("driverVersion").assign(metaData.getDriverVersion());
r.refOfIndex("databaseName").assign(metaData.getDatabaseProductName());
r.refOfIndex("databaseVersion").assign(metaData.getDatabaseProductVersion());
r.refOfIndex("catalogSeparator").assign(metaData.getCatalogSeparator());
r.refOfIndex("catalogTerm").assign(metaData.getCatalogTerm());
r.refOfIndex("schemaTerm").assign(metaData.getSchemaTerm());
r.refOfIndex("procedureTerm").assign(metaData.getProcedureTerm());
r.refOfIndex("searchStringEscape").assign(metaData.getSearchStringEscape());
r.refOfIndex("numericFunctions").assign(metaData.getNumericFunctions());
r.refOfIndex("stringFunctions").assign(metaData.getStringFunctions());
r.refOfIndex("timeDateFunctions").assign(metaData.getTimeDateFunctions());
r.refOfIndex("systemFunctions").assign(metaData.getSystemFunctions());
r.refOfIndex("defaultTransactionIsolation").assign(metaData.getDefaultTransactionIsolation());
r.refOfIndex("identifierQuoteString").assign(metaData.getIdentifierQuoteString());
r.refOfIndex("maxBinaryLiteralLength").assign(metaData.getMaxBinaryLiteralLength());
r.refOfIndex("maxCatalogNameLength").assign(metaData.getMaxCatalogNameLength());
r.refOfIndex("maxCharLiteralLength").assign(metaData.getMaxCharLiteralLength());
r.refOfIndex("maxConnections").assign(metaData.getMaxConnections());
r.refOfIndex("maxColumnNameLength").assign(metaData.getMaxColumnNameLength());
r.refOfIndex("maxColumnsInGroupBy").assign(metaData.getMaxColumnsInGroupBy());
r.refOfIndex("maxColumnsInIndex").assign(metaData.getMaxColumnsInIndex());
r.refOfIndex("maxColumnsInOrderBy").assign(metaData.getMaxColumnsInOrderBy());
r.refOfIndex("maxColumnsInSelect").assign(metaData.getMaxColumnsInSelect());
r.refOfIndex("maxColumnsInTable").assign(metaData.getMaxColumnsInTable());
r.refOfIndex("maxCursorNameLength").assign(metaData.getMaxCursorNameLength());
r.refOfIndex("maxIndexLength").assign(metaData.getMaxIndexLength());
r.refOfIndex("maxProcedureNameLength").assign(metaData.getMaxProcedureNameLength());
r.refOfIndex("maxRowSize").assign(metaData.getMaxRowSize());
r.refOfIndex("maxSchemaNameLength").assign(metaData.getMaxSchemaNameLength());
r.refOfIndex("maxStatementLength").assign(metaData.getMaxStatementLength());
r.refOfIndex("maxTableNameLength").assign(metaData.getMaxTableNameLength());
r.refOfIndex("maxTablesInSelect").assign(metaData.getMaxTablesInSelect());
return r.toConstant();
}
@Signature
public PSqlStatement query(Environment env, String sql) throws Throwable {
return query(env, sql, null);
}
@Signature
public PSqlStatement query(Environment env, String sql, @Nullable ArrayMemory args) throws Throwable {
PreparedStatement statement = connection.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
PSqlStatement sqlStatement = new PSqlStatement(env, statement);
if (args != null) {
int index = 0;
for (ReferenceMemory arg : args) {
env.invokeMethod(sqlStatement, "bind", LongMemory.valueOf(index), arg.getValue());
index += 1;
}
}
return sqlStatement;
}
@Signature
public String identifier(String value) throws SQLException {
String identifierQuoteString = connection.getMetaData().getIdentifierQuoteString();
return identifierQuoteString + value + identifierQuoteString;
}
@Signature
public void close() throws SQLException {
connection.close();
}
@Signature
public void rollback() throws SQLException {
connection.rollback();
}
@Signature
public void commit() throws SQLException {
connection.commit();
}
}
| apache-2.0 |
swcraftersclm/katangapp-frontend | webpack.config.js | 2348 | /**
* Copyright 2016-today Software Craftmanship Toledo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Webpack = require('webpack');
const APP_NAME = 'katanga'
const SRC_PATH = './src';
const OUTPUT_PATH = `${__dirname}/dist`;
module.exports = env => {
const config = {
entry: [ `${SRC_PATH}/app/app.jsx` ],
module: {
rules: [
{
exclude: /node_modules/,
loaders: [
'babel-loader?sourceMap'
],
test: /\.(js|jsx)$/
},
{
loader: ExtractTextPlugin.extract([
'css-loader',
'sass-loader'
]),
test: /\.scss$/
},
{
test: /\.(png|jpg|gif|woff|woff2)$/,
loader: 'url-loader?limit=8192'
},
]
},
output: {
filename: `${APP_NAME}.js`,
path: OUTPUT_PATH
},
plugins: [
new HtmlWebpackPlugin({
inject: 'body',
template: `${SRC_PATH}/index.html`
}),
new ExtractTextPlugin(`${APP_NAME}.css`),
new CopyWebpackPlugin([
{ from: `${SRC_PATH}/404.html`, to: '404.html' },
{ from: `${SRC_PATH}/manifest.json`, to: 'manifest.json' },
{ from: `${SRC_PATH}/assets/icons`, to: 'assets/icons' }
])
],
node: {
fs: "empty"
}
};
if (env && env.dev) {
config.entry.unshift('webpack-dev-server/client?http://localhost:8080/');
config.plugins.unshift(new Webpack.HotModuleReplacementPlugin());
config.devtool = 'source-map';
config.devServer = {
contentBase: './',
hot: true
};
}
return config;
}; | apache-2.0 |
jamslevy/gsoc | app/soc/content/js/edit_survey.js | 5406 |
var DEFAULT_LONG_ANSWER_TEXT = 'Write a Custom Prompt...';
var DEFAULT_SHORT_ANSWER_TEXT = 'Write a Custom Prompt...';
var DEFAULT_OPTION_TEXT = 'Add A New Option...';
var min_rows = 10;
max_rows = min_rows * 2;
jQuery.fn.extend({
preserveDefaultText: function(defaultValue, replaceValue)
{
$(this).focus(function()
{
if(typeof(replaceValue) == 'undefined')
replaceValue = '';
if($(this).val() == defaultValue)
$(this).val(replaceValue);
});
$(this).blur(function(){
if(typeof(replaceValue) == 'undefined')
replaceValue = '';
if($(this).val() == replaceValue)
$(this).val(defaultValue);
});
return $(this).val(defaultValue);
}
});
$(function(){
var widget = $('div#survey_widget');
widget.parents('td.formfieldvalue:first').css({ 'float': 'left',
'width': 200 });
var survey = widget.find('tbody:first')
var options = $('div#survey_options');
var del_el = "<a class='delete'><img src='/soc/content/images/minus.gif'/></a>";
var default_option = "<option>" + DEFAULT_OPTION_TEXT + "</option>";
// Setup for existing surveys
widget.find('label').prepend(del_el).end()
.find('select').append(default_option)
.each(function(){
$(this).attr('name', 'survey_selection__' + $(this).attr('name') ) });
widget.find('input').each(function(){
$(this).attr('name', 'survey_short_answer__' + $(this).attr('name') ) });
widget.find('textarea').each(function(){
$(this).attr('name', 'survey_long_answer__' + $(this).attr('name') ) });
options.find('button').click(function(e){
var field_template = $("<tr><th><label>" + del_el + "</label></th><td> </td></tr>");
var field_name = prompt('enter a field name');
if (!field_name) return alert('invalid field name');
new_field = false;
var type = $(this).attr('id') + "__";
switch($(this).attr('id')){
case "short_answer":
var new_field = "<input type='text'/>";
break;
case "long_answer":
var new_field = "<textarea cols='40' rows='" + min_rows + "' />";
break;
case "selection":
var new_field = "<select><option></option>" + default_option + "</select>";
break;
}
if (new_field) {
field_count = survey.find('tr').length;
new_field_count = field_count + 1;
new_field = $(new_field);
formatted_name = 'survey__' + new_field_count + '__' + type + field_name;
// maybe the name should be serialized in a more common format
$(new_field).attr({ 'id': 'id_' + formatted_name, 'name': formatted_name });
field_template.find('label').attr('for', 'id_' + formatted_name)
.append(field_name + ":").end()
.find('td').append(new_field);
survey.append(field_template).trigger('init');
}
});
survey.bind('init', function(){
widget.find('input').each(function(){
if ($(this).val().length < 1 | $(this).val() == DEFAULT_SHORT_ANSWER_TEXT) $(this).preserveDefaultText(DEFAULT_SHORT_ANSWER_TEXT);
});
widget.find('textarea').each(function(){
if ($(this).val().length < 1 | $(this).val() == DEFAULT_LONG_ANSWER_TEXT) $(this).preserveDefaultText(DEFAULT_LONG_ANSWER_TEXT);
var sizer = sizeTextArea(min_rows, max_rows);
$(this).keyup(sizer).keyup(); // will this work?
});
widget.find('select').change(function(){
if ($(this).find('option:selected').text() == DEFAULT_OPTION_TEXT) {
var option_name = prompt("Name the new option");
if (option_name == null) return false; if (option_name.length < 1) return false;
$(this).prepend("<option>" + option_name + "</option>").find('option').each(function(){
if ($(this).val().length < 1) $(this).remove();
}).end().find('option:first').attr('selected', 'selected');
}
});
widget.find('a.delete img').click(function(){
this_field = $(this).parents('tr:first');
delete_this = confirm("Are you sure you want to delete this field?");
if (delete_this) this_field.remove();
});
}).trigger('init');
// Bind submit
$('form').bind('submit', function(){
// Get all options for select menus
widget.hide().find('select').each(function(){
options = Array();
$(this).find('option').each(function(){
if ($(this).text() != DEFAULT_OPTION_TEXT) options.push($(this).text());
});
$(this).html('').append("<option selected='selected'>" + options + "</option>")
});
widget.find('input').each(function(){
if ( $(this).val() == DEFAULT_SHORT_ANSWER_TEXT) $(this).val('');
});
widget.find('textarea').each(function(){
if ($(this).val() == DEFAULT_LONG_ANSWER_TEXT) $(this).val('');
});
$('input#id_s_html').val(widget.find('div#survey_options').remove().end().html()); // only needed for HTML
});
});
function sizeTextArea(min, max) {
return function(e) {
if (!this.rows || this.rows < min) this.rows = min;
while ((this.clientHeight >= this.scrollHeight
&& this.rows > 1 && this.rows <= max)
|| this.rows > max) this.rows -= 1;
while ((this.clientHeight < this.scrollHeight
|| this.rows < min)
&& this.rows < max) this.rows += 1;
if (this.rows == max
&& this.clientHeight < this.scrollHeight) this.style.overflow = 'auto';
else this.style.overflow = 'hidden';
}
}
| apache-2.0 |