code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php /* Smarty version Smarty-3.1.19, created on 2017-09-23 12:35:41
compiled from "/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl" */ ?>
<?php /*%%SmartyHeaderCode:61757368659c68d5d8d2e84-70988510%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'd65aaeae6f3a1059b7e9527adddd1e40bec16718' =>
array (
0 => '/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl',
1 => 1506184509,
2 => 'file',
),
),
'nocache_hash' => '61757368659c68d5d8d2e84-70988510',
'function' =>
array (
),
'variables' =>
array (
'title' => 0,
'page_header_toolbar_title' => 0,
'page_header_toolbar_btn' => 0,
'current_tab_level' => 0,
'breadcrumbs2' => 0,
'toolbar_btn' => 0,
'k' => 0,
'table' => 0,
'btn' => 0,
'help_link' => 0,
'tab_modules_open' => 0,
'tab_modules_list' => 0,
'tabs' => 0,
'level_1' => 0,
'level_2' => 0,
'level_3' => 0,
'level_4' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => 'content_59c68d5dac6da8_00389838',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_59c68d5dac6da8_00389838')) {function content_59c68d5dac6da8_00389838($_smarty_tpl) {?>
<?php if (!isset($_smarty_tpl->tpl_vars['title']->value)&&isset($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value)) {?>
<?php $_smarty_tpl->tpl_vars['title'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_title']->value, null, 0);?>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value)) {?>
<?php $_smarty_tpl->tpl_vars['toolbar_btn'] = new Smarty_variable($_smarty_tpl->tpl_vars['page_header_toolbar_btn']->value, null, 0);?>
<?php }?>
<div class="bootstrap">
<div class="page-head <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>with-tabs<?php }?>">
<h2 class="page-title">
<?php if (is_array($_smarty_tpl->tpl_vars['title']->value)) {?><?php echo preg_replace('!<[^>]*?>!', ' ', end($_smarty_tpl->tpl_vars['title']->value));?>
<?php } else { ?><?php echo preg_replace('!<[^>]*?>!', ' ', $_smarty_tpl->tpl_vars['title']->value);?>
<?php }?>
</h2>
<ul class="breadcrumb page-breadcrumb">
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!='') {?>
<li class="breadcrumb-container">
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']);?>
</li>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']!=''&&$_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!=$_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']) {?>
<li class="breadcrumb-current">
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?><a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']);?>
"><?php }?>
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']);?>
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?></a><?php }?>
</li>
<?php }?>
</ul>
<div class="page-bar toolbarBox">
<div class="btn-toolbar">
<a href="#" class="toolbar_btn dropdown-toolbar navbar-toggle" data-toggle="collapse"
data-target="#toolbar-nav"><i class="process-icon-dropdown"></i>
<div><?php echo smartyTranslate(array('s'=>'Menu'),$_smarty_tpl);?>
</div>
</a>
<ul id="toolbar-nav" class="nav nav-pills pull-right collapse navbar-collapse">
<?php $_smarty_tpl->tpl_vars['btn'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['btn']->_loop = false;
$_smarty_tpl->tpl_vars['k'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['toolbar_btn']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['btn']->key => $_smarty_tpl->tpl_vars['btn']->value) {
$_smarty_tpl->tpl_vars['btn']->_loop = true;
$_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['btn']->key;
?>
<?php if ($_smarty_tpl->tpl_vars['k']->value!='back'&&$_smarty_tpl->tpl_vars['k']->value!='modules-list') {?>
<li>
<a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?>
-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?>
<?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?>
<?php }?>"
class="toolbar_btn <?php if (isset($_smarty_tpl->tpl_vars['btn']->value['target'])&&$_smarty_tpl->tpl_vars['btn']->value['target']) {?> _blank<?php }?> pointer"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['href'])) {?> href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['href']);?>
"<?php }?>
title="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?><?php echo $_smarty_tpl->tpl_vars['btn']->value['help'];?>
<?php } else { ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?>
<?php }?>"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['js'])&&$_smarty_tpl->tpl_vars['btn']->value['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['btn']->value['js'];?>
"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['modal_target'])&&$_smarty_tpl->tpl_vars['btn']->value['modal_target']) {?> data-target="<?php echo $_smarty_tpl->tpl_vars['btn']->value['modal_target'];?>
" data-toggle="modal"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?> data-toggle="tooltip" data-placement="bottom"<?php }?>>
<i
class="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['icon'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['icon']);?>
<?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?>
<?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?>
<?php }?><?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['class'])) {?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['class']);?>
<?php }?>"></i>
<div<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['force_desc'])&&$_smarty_tpl->tpl_vars['btn']->value['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?>
</div>
</a>
</li>
<?php }?>
<?php } ?>
<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list'])) {?>
<li>
<a
id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?>
-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?>
<?php } else { ?>modules-list<?php }?>"
class="toolbar_btn<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'])) {?> <?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'];?>
<?php }?><?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target']) {?> _blank<?php }?>"
<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'])) {?>href="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'];?>
"<?php }?>
title="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?>
"<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'];?>
"<?php }?>>
<i
class="<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'];?>
<?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?>
<?php } else { ?>modules-list<?php }?><?php }?>"></i>
<div<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?>
</div>
</a>
</li>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['help_link']->value)) {?>
<li>
<a class="toolbar_btn btn-help" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['help_link']->value);?>
" title="<?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?>
">
<i class="process-icon-help"></i>
<div><?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?>
</div>
</a>
</li>
<?php }?>
</ul>
<?php if ((isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value)||isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?>
<script type="text/javascript">
//<![CDATA[
var modules_list_loaded = false;
<?php if (isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value) {?>
$(function () {
$('#modules_list_container').modal('show');
openModulesList();
});
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?>
$('.process-icon-modules-list').parent('a').unbind().bind('click', function (event) {
event.preventDefault();
$('#modules_list_container').modal('show');
openModulesList();
});
<?php }?>
//]]>
</script>
<?php }?>
</div>
</div>
<?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>
<div class="page-head-tabs">
<?php $_smarty_tpl->tpl_vars['level_1'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_1']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['tabs']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_1']->key => $_smarty_tpl->tpl_vars['level_1']->value) {
$_smarty_tpl->tpl_vars['level_1']->_loop = true;
?>
<?php $_smarty_tpl->tpl_vars['level_2'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_2']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_1']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_2']->key => $_smarty_tpl->tpl_vars['level_2']->value) {
$_smarty_tpl->tpl_vars['level_2']->_loop = true;
?>
<?php $_smarty_tpl->tpl_vars['level_3'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_3']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_2']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_3']->key => $_smarty_tpl->tpl_vars['level_3']->value) {
$_smarty_tpl->tpl_vars['level_3']->_loop = true;
?>
<?php if ($_smarty_tpl->tpl_vars['level_3']->value['current']) {?>
<?php $_smarty_tpl->tpl_vars['level_4'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_4']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_3']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_4']->key => $_smarty_tpl->tpl_vars['level_4']->value) {
$_smarty_tpl->tpl_vars['level_4']->_loop = true;
?>
<a href="<?php echo $_smarty_tpl->tpl_vars['level_4']->value['href'];?>
" <?php if ($_smarty_tpl->tpl_vars['level_4']->value['current']) {?>class="current"<?php }?>><?php echo $_smarty_tpl->tpl_vars['level_4']->value['name'];?>
</a>
<?php } ?>
<?php }?>
<?php } ?>
<?php } ?>
<?php } ?>
</div>
<?php }?>
</div>
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayDashboardTop'),$_smarty_tpl);?>
</div>
<?php }} ?>
| Java |
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018- Equinor ASA
//
// ResInsight 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.
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "RiaDefines.h"
#include <QString>
//==================================================================================================
///
//==================================================================================================
class RicWellPathFractureReportItem
{
public:
RicWellPathFractureReportItem( const QString& wellPathNameForExport,
const QString& fractureName,
const QString& fractureTemplateName,
double measuredDepth );
void setData( double trans, size_t connCount, double area );
void setWidthAndConductivity( double width, double conductivity );
void setHeightAndHalfLength( double height, double halfLength );
void setAreaWeightedPermeability( double permeability );
void setUnitSystem( RiaDefines::EclipseUnitSystem unitSystem );
void setPressureDepletionParameters( bool performPressureDepletionScaling,
const QString& timeStepString,
const QString& wbhpString,
double userWBHP,
double actualWBHP,
double minPressureDrop,
double maxPressureDrop );
QString wellPathNameForExport() const;
QString fractureName() const;
QString fractureTemplateName() const;
RiaDefines::EclipseUnitSystem unitSystem() const;
double transmissibility() const;
size_t connectionCount() const;
double fcd() const;
double area() const;
double kfwf() const;
double kf() const;
double wf() const;
double xf() const;
double h() const;
double km() const;
double kmxf() const;
bool performPressureDepletionScaling() const;
QString pressureDepletionTimeStepString() const;
QString pressureDepletionWBHPString() const;
double pressureDepletionUserWBHP() const;
double pressureDepletionActualWBHP() const;
double pressureDepletionMinPressureDrop() const;
double pressureDepletionMaxPressureDrop() const;
bool operator<( const RicWellPathFractureReportItem& other ) const;
private:
RiaDefines::EclipseUnitSystem m_unitSystem;
QString m_wellPathNameForExport;
QString m_wellPathFracture;
QString m_wellPathFractureTemplate;
double m_mesuredDepth;
double m_transmissibility;
size_t m_connectionCount;
double m_area;
double m_kfwf;
double m_kf;
double m_wf;
double m_xf;
double m_h;
double m_km;
bool m_performPressureDepletionScaling;
QString m_pressureDepletionTimeStepString;
QString m_pressureDepletionWBHPString;
double m_pressureDepletionUserWBHP;
double m_pressureDepletionActualWBHP;
double m_pressureDepletionMinPressureDrop;
double m_pressureDepletionMaxPressureDrop;
};
| Java |
/**
*
* This file is part of Tulip (www.tulip-software.org)
*
* Authors: David Auber and the Tulip development Team
* from LaBRI, University of Bordeaux
*
* Tulip is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Tulip 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.
*
*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <cppunit/TestCase.h>
#include <tulip/TulipPluginHeaders.h>
using namespace std;
class Test2 : public tlp::BooleanAlgorithm {
public:
PLUGININFORMATION("Test2","Jezequel","03/11/2004","0","1.0", "")
Test2(tlp::PluginContext* context) : tlp::BooleanAlgorithm(context) {}
~Test2() {}
bool run() {
return true;
}
};
PLUGIN(Test2)
| Java |
/*
Copyright 2019 Equinor ASA.
This file is part of the Open Porous Media project (OPM).
OPM 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.
OPM is distributed in the hope that it will be useful,
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 OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#include <opm/parser/eclipse/EclipseState/Schedule/TimeMap.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/RFTConfig.hpp>
namespace Opm {
RFTConfig::RFTConfig(const TimeMap& time_map) :
tm(time_map)
{
}
bool RFTConfig::rft(const std::string& well_name, std::size_t report_step) const {
if (report_step >= this->tm.size())
throw std::invalid_argument("Invalid ");
const auto well_iter = this->well_open.find(well_name);
if (well_iter != this->well_open.end()) {
// A general "Output RFT when the well is opened" has been configured with WRFT
if (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step) {
if (well_iter->second == report_step)
return true;
}
// A FOPN setting has been configured with the WRFTPLT keyword
if (this->well_open_rft_name.count(well_name) > 0) {
if (well_iter->second == report_step)
return true;
}
}
if (this->rft_config.count(well_name) == 0)
return false;
auto rft_pair = this->rft_config.at(well_name)[report_step];
if (rft_pair.first == RFTConnections::YES)
return (rft_pair.second == report_step);
if (rft_pair.first == RFTConnections::NO)
return false;
if (rft_pair.first == RFTConnections::REPT)
return true;
if (rft_pair.first == RFTConnections::TIMESTEP)
return true;
return false;
}
bool RFTConfig::plt(const std::string& well_name, std::size_t report_step) const {
if (report_step >= this->tm.size())
throw std::invalid_argument("Invalid ");
if (this->plt_config.count(well_name) == 0)
return false;
auto plt_pair = this->plt_config.at(well_name)[report_step];
if (plt_pair.first == PLTConnections::YES)
return (plt_pair.second == report_step);
if (plt_pair.first == PLTConnections::NO)
return false;
if (plt_pair.first == PLTConnections::REPT)
return true;
if (plt_pair.first == PLTConnections::TIMESTEP)
return true;
return false;
}
void RFTConfig::updateRFT(const std::string& well_name, std::size_t report_step, RFTConnections::RFTEnum value) {
if (value == RFTConnections::FOPN)
this->setWellOpenRFT(well_name);
else {
if (this->rft_config.count(well_name) == 0) {
auto state = DynamicState<std::pair<RFTConnections::RFTEnum, std::size_t>>(this->tm, std::make_pair(RFTConnections::NO, 0));
this->rft_config.emplace( well_name, state );
}
this->rft_config.at(well_name).update(report_step, std::make_pair(value, report_step));
}
}
void RFTConfig::updatePLT(const std::string& well_name, std::size_t report_step, PLTConnections::PLTEnum value) {
if (this->plt_config.count(well_name) == 0) {
auto state = DynamicState<std::pair<PLTConnections::PLTEnum, std::size_t>>(this->tm, std::make_pair(PLTConnections::NO, 0));
this->plt_config.emplace( well_name, state );
}
this->plt_config.at(well_name).update(report_step, std::make_pair(value, report_step));
}
bool RFTConfig::getWellOpenRFT(const std::string& well_name, std::size_t report_step) const {
if (this->well_open_rft_name.count(well_name) > 0)
return true;
return (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step);
}
void RFTConfig::setWellOpenRFT(std::size_t report_step) {
this->well_open_rft_time = std::make_pair(true, report_step);
}
void RFTConfig::setWellOpenRFT(const std::string& well_name) {
this->well_open_rft_name.insert( well_name );
}
void RFTConfig::addWellOpen(const std::string& well_name, std::size_t report_step) {
if (this->well_open.count(well_name) == 0)
this->well_open[well_name] = report_step;
}
std::size_t RFTConfig::firstRFTOutput() const {
std::size_t first_rft = this->tm.size();
if (this->well_open_rft_time.first) {
// The WRFT keyword has been used to request RFT output at well open for all wells.
std::size_t rft_time = this->well_open_rft_time.second;
for (const auto& rft_pair : this->well_open) {
if (rft_pair.second >= rft_time)
first_rft = std::min(first_rft, rft_pair.second);
}
} else {
// Go through the individual wells and look for first open settings
for (const auto& rft_pair : this->well_open)
first_rft = std::min(first_rft, rft_pair.second);
}
for (const auto& rft_pair : this->plt_config) {
const auto& dynamic_state = rft_pair.second;
auto pred = [] (const std::pair<PLTConnections::PLTEnum, std::size_t>& ) { return false; };
int this_first_rft = dynamic_state.find_if(pred);
if (this_first_rft >= 0)
first_rft = std::min(first_rft, static_cast<std::size_t>(this_first_rft));
}
return first_rft;
}
bool RFTConfig::active(std::size_t report_step) const {
for (const auto& rft_pair : this->rft_config) {
if (this->rft(rft_pair.first, report_step))
return true;
}
for (const auto& plt_pair : this->plt_config) {
if (this->rft(plt_pair.first, report_step))
return true;
}
return false;
}
}
| Java |
"""Test class for Custom Sync UI
:Requirement: Sync
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Repositories
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo import manifests
from robottelo.api.utils import enable_rhrepo_and_fetchid
from robottelo.constants import (
DISTRO_RHEL6, DISTRO_RHEL7,
DOCKER_REGISTRY_HUB,
DOCKER_UPSTREAM_NAME,
FAKE_1_YUM_REPO,
FEDORA27_OSTREE_REPO,
REPOS,
REPOSET,
REPO_TYPE,
PRDS,
)
from robottelo.decorators import (
fixture,
run_in_one_thread,
skip_if_not_set,
tier2,
upgrade,
skip_if_bug_open,
)
from robottelo.decorators.host import skip_if_os
from robottelo.products import (
RepositoryCollection,
RHELCloudFormsTools,
SatelliteCapsuleRepository,
)
@fixture(scope='module')
def module_org():
return entities.Organization().create()
@fixture(scope='module')
def module_custom_product(module_org):
return entities.Product(organization=module_org).create()
@fixture(scope='module')
def module_org_with_manifest():
org = entities.Organization().create()
manifests.upload_manifest_locked(org.id)
return org
@tier2
def test_positive_sync_custom_repo(session, module_custom_product):
"""Create Content Custom Sync with minimal input parameters
:id: 00fb0b04-0293-42c2-92fa-930c75acee89
:expectedresults: Sync procedure is successful
:CaseImportance: Critical
"""
repo = entities.Repository(
url=FAKE_1_YUM_REPO, product=module_custom_product).create()
with session:
results = session.sync_status.synchronize([
(module_custom_product.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def test_positive_sync_rh_repos(session, module_org_with_manifest):
"""Create Content RedHat Sync with two repos.
:id: e30f6509-0b65-4bcc-a522-b4f3089d3911
:expectedresults: Sync procedure for RedHat Repos is successful
:CaseLevel: Integration
"""
repos = (
SatelliteCapsuleRepository(cdn=True),
RHELCloudFormsTools(cdn=True)
)
distros = [DISTRO_RHEL7, DISTRO_RHEL6]
repo_collections = [
RepositoryCollection(distro=distro, repositories=[repo])
for distro, repo in zip(distros, repos)
]
for repo_collection in repo_collections:
repo_collection.setup(module_org_with_manifest.id, synchronize=False)
repo_paths = [
(
repo.repo_data['product'],
repo.repo_data.get('releasever'),
repo.repo_data.get('arch'),
repo.repo_data['name'],
)
for repo in repos
]
with session:
session.organization.select(org_name=module_org_with_manifest.name)
results = session.sync_status.synchronize(repo_paths)
assert len(results) == len(repo_paths)
assert all([result == 'Syncing Complete.' for result in results])
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@tier2
@upgrade
def test_positive_sync_custom_ostree_repo(session, module_custom_product):
"""Create custom ostree repository and sync it.
:id: e4119b9b-0356-4661-a3ec-e5807224f7d2
:expectedresults: ostree repo should be synced successfully
:CaseLevel: Integration
"""
repo = entities.Repository(
content_type='ostree',
url=FEDORA27_OSTREE_REPO,
product=module_custom_product,
unprotected=False,
).create()
with session:
results = session.sync_status.synchronize([
(module_custom_product.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def test_positive_sync_rh_ostree_repo(session, module_org_with_manifest):
"""Sync CDN based ostree repository.
:id: 4d28fff0-5fda-4eee-aa0c-c5af02c31de5
:Steps:
1. Import a valid manifest
2. Enable the OStree repo and sync it
:expectedresults: ostree repo should be synced successfully from CDN
:CaseLevel: Integration
"""
enable_rhrepo_and_fetchid(
basearch=None,
org_id=module_org_with_manifest.id,
product=PRDS['rhah'],
repo=REPOS['rhaht']['name'],
reposet=REPOSET['rhaht'],
releasever=None,
)
with session:
session.organization.select(org_name=module_org_with_manifest.name)
results = session.sync_status.synchronize([
(PRDS['rhah'], REPOS['rhaht']['name'])])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@tier2
@upgrade
def test_positive_sync_docker_via_sync_status(session, module_org):
"""Create custom docker repo and sync it via the sync status page.
:id: 00b700f4-7e52-48ed-98b2-e49b3be102f2
:expectedresults: Sync procedure for specific docker repository is
successful
:CaseLevel: Integration
"""
product = entities.Product(organization=module_org).create()
repo_name = gen_string('alphanumeric')
with session:
session.repository.create(
product.name,
{'name': repo_name,
'repo_type': REPO_TYPE['docker'],
'repo_content.upstream_url': DOCKER_REGISTRY_HUB,
'repo_content.upstream_repo_name': DOCKER_UPSTREAM_NAME}
)
assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name
result = session.sync_status.synchronize([(product.name, repo_name)])
assert result[0] == 'Syncing Complete.'
| Java |
<?php
$L['Alerts_Title'] = 'Allarmi personalizzati';
$L['Alerts_Description'] = 'Allarmi personalizzati da ${0}';
$L['Alerts_header'] = 'Allarmi personalizzati da ${0}';
$L['Alerts_Configure_header'] = 'Configura download automatico';
$L['Update_Alerts_label'] = 'Scarica allarmi personalizzati';
$L['Refresh_label'] = 'Download configurazioni allarmi';
$L['last_update_label'] = 'Ultimo aggiornamento';
$L['Type_label'] = 'Allarme';
$L['Instance_label'] = 'Parametro';
$L['Threshold_label'] = 'Soglia';
$L['AlertsAutoUpdates_enabled_label'] = 'Abilita download automatico degli allarmi personalizzati (raccomandato)';
$L['AlertsAutoUpdates_disabled_label'] = 'Disabilita download automatico degli allarmi personalizzati';
$L['df_label'] = 'Spazio disco libero';
$L['load_label'] = 'Carico CPU';
$L['ping_droprate_label'] = 'Tasso di pacchetti persi';
$L['ping_label'] = 'Latenza ping';
$L['swap_label'] = 'Swap libero';
$L['Partition_label'] = 'Partizione';
$L['Host_label'] = 'Host';
$L['Intro_label'] = 'Ogni server ha una lista predefinita di allarmi di default. Solo alcuni possono essere personalizzati. <br/> Questa pagina mostra solo gli allarmi personalizzati su <a href="${0}">${0}</a>.';
$L['Download_label'] = 'Di default, le modifiche agli allarmi fatte su <a href="${0}">${0}</a> sono applicate ogni notte. <br/> Il tasto "Scarica allarmi personalizzati" scarica la configurazione subito.';
$L['max_fail_label'] = 'Critica sopra';
$L['min_fail_label'] = 'Critica sotto';
$L['max_warn_label'] = 'Media sopra';
$L['min_warn_label'] = 'Media sotto';
| Java |
// dependencies
define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils',
'plugin/models/chart', 'plugin/models/group',
'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'],
function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) {
/**
* The charts editor holds the tabs for selecting chart types, chart configuration
* and data group selections.
*/
return Backbone.View.extend({
// initialize
initialize: function(app, options){
// link this
var self = this;
// link application
this.app = app;
// get current chart object
this.chart = this.app.chart;
// message element
this.message = new Ui.Message();
// create portlet
this.portlet = new Portlet.View({
icon : 'fa-bar-chart-o',
title: 'Editor',
operations : {
'save' : new Ui.ButtonIcon({
icon : 'fa-save',
tooltip : 'Draw Chart',
title : 'Draw',
onclick : function() {
self._saveChart();
}
}),
'back' : new Ui.ButtonIcon({
icon : 'fa-caret-left',
tooltip : 'Return to Viewer',
title : 'Cancel',
onclick : function() {
// show viewer/viewport
self.app.go('viewer');
// reset chart
self.app.storage.load();
}
})
}
});
//
// grid with chart types
//
this.types = new TypesView(app, {
onchange : function(chart_type) {
// get chart definition
var chart_definition = self.app.types.get(chart_type);
if (!chart_definition) {
console.debug('FAILED - Editor::onchange() - Chart type not supported.');
}
// parse chart definition
self.chart.definition = chart_definition;
// reset type relevant chart content
self.chart.settings.clear();
// update chart type
self.chart.set({type: chart_type});
// set modified flag
self.chart.set('modified', true);
// log
console.debug('Editor::onchange() - Switched chart type.');
},
ondblclick : function(chart_id) {
self._saveChart();
}
});
//
// tabs
//
this.tabs = new Tabs.View({
title_new : 'Add Data',
onnew : function() {
var group = self._addGroupModel();
self.tabs.show(group.id);
}
});
//
// main/default tab
//
// construct elements
this.title = new Ui.Input({
placeholder: 'Chart title',
onchange: function() {
self.chart.set('title', self.title.value());
}
});
// append element
var $main = $('<div/>');
$main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el));
$main.append(Utils.wrap(this.title.$el));
$main.append(Utils.wrap(this.types.$el));
// add tab
this.tabs.add({
id : 'main',
title : 'Start',
$el : $main
});
//
// main settings tab
//
// create settings view
this.settings = new SettingsView(this.app);
// add tab
this.tabs.add({
id : 'settings',
title : 'Configuration',
$el : this.settings.$el
});
// append tabs
this.portlet.append(this.message.$el);
this.portlet.append(this.tabs.$el);
// elements
this.setElement(this.portlet.$el);
// hide back button on startup
this.tabs.hideOperation('back');
// chart events
var self = this;
this.chart.on('change:title', function(chart) {
self._refreshTitle();
});
this.chart.on('change:type', function(chart) {
self.types.value(chart.get('type'));
});
this.chart.on('reset', function(chart) {
self._resetChart();
});
this.app.chart.on('redraw', function(chart) {
self.portlet.showOperation('back');
});
// groups events
this.app.chart.groups.on('add', function(group) {
self._addGroup(group);
});
this.app.chart.groups.on('remove', function(group) {
self._removeGroup(group);
});
this.app.chart.groups.on('reset', function(group) {
self._removeAllGroups();
});
this.app.chart.groups.on('change:key', function(group) {
self._refreshGroupKey();
});
// reset
this._resetChart();
},
// hide
show: function() {
this.$el.show();
},
// hide
hide: function() {
this.$el.hide();
},
// refresh title
_refreshTitle: function() {
var title = this.chart.get('title');
this.portlet.title(title);
this.title.value(title);
},
// refresh group
_refreshGroupKey: function() {
var self = this;
var counter = 0;
this.chart.groups.each(function(group) {
var title = group.get('key', '');
if (title == '') {
title = 'Data label';
}
self.tabs.title(group.id, ++counter + ': ' + title);
});
},
// add group model
_addGroupModel: function() {
var group = new Group({
id : Utils.uuid()
});
this.chart.groups.add(group);
return group;
},
// add group tab
_addGroup: function(group) {
// link this
var self = this;
// create view
var group_view = new GroupView(this.app, {group: group});
// add new tab
this.tabs.add({
id : group.id,
$el : group_view.$el,
ondel : function() {
self.chart.groups.remove(group.id);
}
});
// update titles
this._refreshGroupKey();
// reset
this.chart.set('modified', true);
},
// remove group
_removeGroup: function(group) {
this.tabs.del(group.id);
// update titles
this._refreshGroupKey();
// reset
this.chart.set('modified', true);
},
// remove group
_removeAllGroups: function(group) {
this.tabs.delRemovable();
},
// reset
_resetChart: function() {
// reset chart details
this.chart.set('id', Utils.uuid());
this.chart.set('type', 'nvd3_bar');
this.chart.set('dataset_id', this.app.options.config.dataset_id);
this.chart.set('title', 'New Chart');
// reset back button
this.portlet.hideOperation('back');
},
// create chart
_saveChart: function() {
// update chart data
this.chart.set({
type : this.types.value(),
title : this.title.value(),
date : Utils.time()
});
// make sure that at least one data group is available
if (this.chart.groups.length == 0) {
this.message.update({message: 'Please select data columns before drawing the chart.'});
var group = this._addGroupModel();
this.tabs.show(group.id);
return;
}
// make sure that all necessary columns are assigned
var self = this;
var valid = true;
var chart_def = this.chart.definition;
this.chart.groups.each(function(group) {
if (!valid) {
return;
}
for (var key in chart_def.columns) {
if (group.attributes[key] == 'null') {
self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'});
self.tabs.show(group.id);
valid = false;
return;
}
}
});
// validate if columns have been selected
if (!valid) {
return;
}
// show viewport
this.app.go('viewer');
// wait until chart is ready
var self = this;
this.app.deferred.execute(function() {
// save
self.app.storage.save();
// trigger redraw
self.chart.trigger('redraw');
});
}
});
}); | Java |
{% extends "jblux/base.html" %}
{% block title %}New Character{% endblock %}
{% block content %}
<form method="post" action="{% url jblux_django.jblux.views.new_character %}">
{% csrf_token %}
{% include "jblux/base_form.html" %}
<p><input type="submit" value="Create Character" /></p>
</form>
{% endblock %}
| Java |
/**
* This file is part of RT2D, a 2D OpenGL framework.
*
* - Copyright 2017 Rik Teerling <rik@onandoffables.com>
* - Initial commit
*/
#include "canvas.h"
Canvas::Canvas()
: Entity()
{
this->init(16);
}
Canvas::Canvas(int pixelsize)
: Entity()
{
this->init(pixelsize);
}
Canvas::~Canvas()
{
}
void Canvas::update(float deltaTime)
{
}
void Canvas::init(int pixelsize)
{
this->position = Point2(SWIDTH/2, SHEIGHT/2);
this->scale = Point2(pixelsize, pixelsize);
// width, height, bitdepth, filter, wrap
PixelBuffer tmp = PixelBuffer(SWIDTH/pixelsize, SHEIGHT/pixelsize, 4, 0, 0);
this->addDynamicSprite(&tmp);
// get the pixels from the texture and make the framebuffer point to it
this->_framebuffer = this->sprite()->texture()->pixels();
this->_width = SWIDTH / pixelsize;
this->_height = SHEIGHT / pixelsize;
backgroundcolor = RGBAColor(0, 0, 0, 0);
this->fill(backgroundcolor);
}
void Canvas::setPixel(int x, int y, RGBAColor color)
{
this->_framebuffer->setPixel(x, y, color);
}
RGBAColor Canvas::getPixel(int x, int y)
{
return this->_framebuffer->getPixel(x, y);
}
void Canvas::clearPixel(int x, int y)
{
this->_framebuffer->setPixel(x, y, backgroundcolor);
}
void Canvas::fill(RGBAColor color)
{
// fill framebuffer with color
for (long y=0; y<_framebuffer->height; y++) {
for (long x=0; x<_framebuffer->width; x++) {
this->setPixel(x, y, color);
}
}
}
void Canvas::drawSprite(const PixelSprite& spr)
{
size_t s = spr.pixels.size();
for (size_t i = 0; i < s; i++) {
this->setPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y, spr.pixels[i].color);
}
}
void Canvas::clearSprite(const PixelSprite& spr)
{
size_t s = spr.pixels.size();
for (size_t i = 0; i < s; i++) {
this->clearPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y);
}
}
void Canvas::drawLine(Vector2f from, Vector2f to, RGBAColor color) {
float x0 = from.x;
float y0 = from.y;
float x1 = to.x;
float y1 = to.y;
bool steep = false;
if (std::abs(x0-x1) < std::abs(y0-y1)) {
std::swap(x0, y0);
std::swap(x1, y1);
steep = true;
}
if (x0 > x1) {
std::swap(x0, x1);
std::swap(y0, y1);
}
int dx = x1-x0;
int dy = y1-y0;
int derror2 = std::abs(dy)*2;
int error2 = 0;
int y = y0;
for (int x = x0; x <= x1; x++) {
if (steep) {
this->setPixel(y, x, color);
} else {
this->setPixel(x, y, color);
}
error2 += derror2;
if (error2 > dx) {
y += (y1 > y0 ? 1 : -1);
error2 -= dx*2;
}
}
}
| Java |
#!/usr/bin/env python
from keyring import get_password
from boto.iam.connection import IAMConnection
import lib.LoadBotoConfig as BotoConfig
from sys import exit
envs = ['dev', 'qa', 'staging', 'demo', 'prod']
for env in envs:
id = BotoConfig.config.get(env, 'aws_access_key_id')
key = get_password(BotoConfig.config.get(env, 'keyring'), id)
conn = IAMConnection(aws_access_key_id=id, aws_secret_access_key=key)
print(conn.get_signin_url()) | Java |
<?php
namespace App\Services\Geografico\ObterOsc;
use App\Services\BaseService;
use App\Dao\Geografico\GeolocalizacaoDao;
class Service extends BaseService{
public function executar(){
$conteudoRequisicao = $this->requisicao->getConteudo();
$modelo = new Model($conteudoRequisicao);
if($modelo->obterCodigoResposta() === 200){
$requisicao = $modelo->obterRequisicao();
$geolocalizacaoOsc = (new GeolocalizacaoDao())->obterGeolocalizacaoOsc($requisicao->id_osc);
if($geolocalizacaoOsc){
$this->resposta->prepararResposta($geolocalizacaoOsc, 200);
}else{
$this->resposta->prepararResposta(null, 204);
}
}else{
$this->resposta->prepararResposta($modelo->obterMensagemResposta(), $modelo->obterCodigoResposta());
}
}
} | Java |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Guillaume Saupin <guillaume.saupin@cea.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at the mozilla.org home page
#ifndef EIGEN_SKYLINEMATRIX_H
#define EIGEN_SKYLINEMATRIX_H
#include "SkylineStorage.h"
#include "SkylineMatrixBase.h"
namespace Eigen {
/** \ingroup Skyline_Module
*
* \class SkylineMatrix
*
* \brief The main skyline matrix class
*
* This class implements a skyline matrix using the very uncommon storage
* scheme.
*
* \param _Scalar the scalar type, i.e. the type of the coefficients
* \param _Options Union of bit flags controlling the storage scheme. Currently the only possibility
* is RowMajor. The default is 0 which means column-major.
*
*
*/
namespace internal {
template<typename _Scalar, int _Options>
struct traits<SkylineMatrix<_Scalar, _Options> > {
typedef _Scalar Scalar;
typedef Sparse StorageKind;
enum {
RowsAtCompileTime = Dynamic,
ColsAtCompileTime = Dynamic,
MaxRowsAtCompileTime = Dynamic,
MaxColsAtCompileTime = Dynamic,
Flags = SkylineBit | _Options,
CoeffReadCost = NumTraits<Scalar>::ReadCost,
};
};
}
template<typename _Scalar, int _Options>
class SkylineMatrix
: public SkylineMatrixBase<SkylineMatrix<_Scalar, _Options> > {
public:
EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(SkylineMatrix)
EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, +=)
EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, -=)
using Base::IsRowMajor;
protected:
typedef SkylineMatrix<Scalar, (Flags&~RowMajorBit) | (IsRowMajor ? RowMajorBit : 0) > TransposedSkylineMatrix;
Index m_outerSize;
Index m_innerSize;
public:
Index* m_colStartIndex;
Index* m_rowStartIndex;
SkylineStorage<Scalar> m_data;
public:
inline Index rows() const {
return IsRowMajor ? m_outerSize : m_innerSize;
}
inline Index cols() const {
return IsRowMajor ? m_innerSize : m_outerSize;
}
inline Index innerSize() const {
return m_innerSize;
}
inline Index outerSize() const {
return m_outerSize;
}
inline Index upperNonZeros() const {
return m_data.upperSize();
}
inline Index lowerNonZeros() const {
return m_data.lowerSize();
}
inline Index upperNonZeros(Index j) const {
return m_colStartIndex[j + 1] - m_colStartIndex[j];
}
inline Index lowerNonZeros(Index j) const {
return m_rowStartIndex[j + 1] - m_rowStartIndex[j];
}
inline const Scalar* _diagPtr() const {
return &m_data.diag(0);
}
inline Scalar* _diagPtr() {
return &m_data.diag(0);
}
inline const Scalar* _upperPtr() const {
return &m_data.upper(0);
}
inline Scalar* _upperPtr() {
return &m_data.upper(0);
}
inline const Scalar* _lowerPtr() const {
return &m_data.lower(0);
}
inline Scalar* _lowerPtr() {
return &m_data.lower(0);
}
inline const Index* _upperProfilePtr() const {
return &m_data.upperProfile(0);
}
inline Index* _upperProfilePtr() {
return &m_data.upperProfile(0);
}
inline const Index* _lowerProfilePtr() const {
return &m_data.lowerProfile(0);
}
inline Index* _lowerProfilePtr() {
return &m_data.lowerProfile(0);
}
inline Scalar coeff(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return this->m_data.diag(outer);
if (IsRowMajor) {
if (inner > outer) //upper matrix
{
const Index minOuterIndex = inner - m_data.upperProfile(inner);
if (outer >= minOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
else
return Scalar(0);
}
if (inner < outer) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner >= minInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
else
return Scalar(0);
}
return m_data.upper(m_colStartIndex[inner] + outer - inner);
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer <= maxOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
else
return Scalar(0);
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner <= maxInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
else
return Scalar(0);
}
}
}
inline Scalar& coeffRef(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return this->m_data.diag(outer);
if (IsRowMajor) {
if (col > row) //upper matrix
{
const Index minOuterIndex = inner - m_data.upperProfile(inner);
eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
}
if (col < row) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
}
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
}
}
}
inline Scalar coeffDiag(Index idx) const {
eigen_assert(idx < outerSize());
eigen_assert(idx < innerSize());
return this->m_data.diag(idx);
}
inline Scalar coeffLower(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner >= minInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
else
return Scalar(0);
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner <= maxInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
else
return Scalar(0);
}
}
inline Scalar coeffUpper(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
if (outer >= minOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
else
return Scalar(0);
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer <= maxOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
else
return Scalar(0);
}
}
inline Scalar& coeffRefDiag(Index idx) {
eigen_assert(idx < outerSize());
eigen_assert(idx < innerSize());
return this->m_data.diag(idx);
}
inline Scalar& coeffRefLower(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
}
}
inline bool coeffExistLower(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
return inner >= minInnerIndex;
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
return inner <= maxInnerIndex;
}
}
inline Scalar& coeffRefUpper(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
}
}
inline bool coeffExistUpper(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
return outer >= minOuterIndex;
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
return outer <= maxOuterIndex;
}
}
protected:
public:
class InnerUpperIterator;
class InnerLowerIterator;
class OuterUpperIterator;
class OuterLowerIterator;
/** Removes all non zeros */
inline void setZero() {
m_data.clear();
memset(m_colStartIndex, 0, (m_outerSize + 1) * sizeof (Index));
memset(m_rowStartIndex, 0, (m_outerSize + 1) * sizeof (Index));
}
/** \returns the number of non zero coefficients */
inline Index nonZeros() const {
return m_data.diagSize() + m_data.upperSize() + m_data.lowerSize();
}
/** Preallocates \a reserveSize non zeros */
inline void reserve(Index reserveSize, Index reserveUpperSize, Index reserveLowerSize) {
m_data.reserve(reserveSize, reserveUpperSize, reserveLowerSize);
}
/** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col.
*
* \warning This function can be extremely slow if the non zero coefficients
* are not inserted in a coherent order.
*
* After an insertion session, you should call the finalize() function.
*/
EIGEN_DONT_INLINE Scalar & insert(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return m_data.diag(col);
if (IsRowMajor) {
if (outer < inner) //upper matrix
{
Index minOuterIndex = 0;
minOuterIndex = inner - m_data.upperProfile(inner);
if (outer < minOuterIndex) //The value does not yet exist
{
const Index previousProfile = m_data.upperProfile(inner);
m_data.upperProfile(inner) = inner - outer;
const Index bandIncrement = m_data.upperProfile(inner) - previousProfile;
//shift data stored after this new one
const Index stop = m_colStartIndex[cols()];
const Index start = m_colStartIndex[inner];
for (Index innerIdx = stop; innerIdx >= start; innerIdx--) {
m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx);
}
for (Index innerIdx = cols(); innerIdx > inner; innerIdx--) {
m_colStartIndex[innerIdx] += bandIncrement;
}
//zeros new data
memset(this->_upperPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.upper(m_colStartIndex[inner]);
} else {
return m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
}
}
if (outer > inner) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner < minInnerIndex) //The value does not yet exist
{
const Index previousProfile = m_data.lowerProfile(outer);
m_data.lowerProfile(outer) = outer - inner;
const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile;
//shift data stored after this new one
const Index stop = m_rowStartIndex[rows()];
const Index start = m_rowStartIndex[outer];
for (Index innerIdx = stop; innerIdx >= start; innerIdx--) {
m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx);
}
for (Index innerIdx = rows(); innerIdx > outer; innerIdx--) {
m_rowStartIndex[innerIdx] += bandIncrement;
}
//zeros new data
memset(this->_lowerPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.lower(m_rowStartIndex[outer]);
} else {
return m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
}
}
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer > maxOuterIndex) //The value does not yet exist
{
const Index previousProfile = m_data.upperProfile(inner);
m_data.upperProfile(inner) = outer - inner;
const Index bandIncrement = m_data.upperProfile(inner) - previousProfile;
//shift data stored after this new one
const Index stop = m_rowStartIndex[rows()];
const Index start = m_rowStartIndex[inner + 1];
for (Index innerIdx = stop; innerIdx >= start; innerIdx--) {
m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx);
}
for (Index innerIdx = inner + 1; innerIdx < outerSize() + 1; innerIdx++) {
m_rowStartIndex[innerIdx] += bandIncrement;
}
memset(this->_upperPtr() + m_rowStartIndex[inner] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.upper(m_rowStartIndex[inner] + m_data.upperProfile(inner));
} else {
return m_data.upper(m_rowStartIndex[inner] + (outer - inner));
}
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner > maxInnerIndex) //The value does not yet exist
{
const Index previousProfile = m_data.lowerProfile(outer);
m_data.lowerProfile(outer) = inner - outer;
const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile;
//shift data stored after this new one
const Index stop = m_colStartIndex[cols()];
const Index start = m_colStartIndex[outer + 1];
for (Index innerIdx = stop; innerIdx >= start; innerIdx--) {
m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx);
}
for (Index innerIdx = outer + 1; innerIdx < outerSize() + 1; innerIdx++) {
m_colStartIndex[innerIdx] += bandIncrement;
}
memset(this->_lowerPtr() + m_colStartIndex[outer] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.lower(m_colStartIndex[outer] + m_data.lowerProfile(outer));
} else {
return m_data.lower(m_colStartIndex[outer] + (inner - outer));
}
}
}
}
/** Must be called after inserting a set of non zero entries.
*/
inline void finalize() {
if (IsRowMajor) {
if (rows() > cols())
m_data.resize(cols(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1);
else
m_data.resize(rows(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1);
// eigen_assert(rows() == cols() && "memory reorganisatrion only works with suare matrix");
//
// Scalar* newArray = new Scalar[m_colStartIndex[cols()] + 1 + m_rowStartIndex[rows()] + 1];
// Index dataIdx = 0;
// for (Index row = 0; row < rows(); row++) {
//
// const Index nbLowerElts = m_rowStartIndex[row + 1] - m_rowStartIndex[row];
// // std::cout << "nbLowerElts" << nbLowerElts << std::endl;
// memcpy(newArray + dataIdx, m_data.m_lower + m_rowStartIndex[row], nbLowerElts * sizeof (Scalar));
// m_rowStartIndex[row] = dataIdx;
// dataIdx += nbLowerElts;
//
// const Index nbUpperElts = m_colStartIndex[row + 1] - m_colStartIndex[row];
// memcpy(newArray + dataIdx, m_data.m_upper + m_colStartIndex[row], nbUpperElts * sizeof (Scalar));
// m_colStartIndex[row] = dataIdx;
// dataIdx += nbUpperElts;
//
//
// }
// //todo : don't access m_data profile directly : add an accessor from SkylineMatrix
// m_rowStartIndex[rows()] = m_rowStartIndex[rows()-1] + m_data.lowerProfile(rows()-1);
// m_colStartIndex[cols()] = m_colStartIndex[cols()-1] + m_data.upperProfile(cols()-1);
//
// delete[] m_data.m_lower;
// delete[] m_data.m_upper;
//
// m_data.m_lower = newArray;
// m_data.m_upper = newArray;
} else {
if (rows() > cols())
m_data.resize(cols(), rows(), cols(), m_rowStartIndex[cols()] + 1, m_colStartIndex[cols()] + 1);
else
m_data.resize(rows(), rows(), cols(), m_rowStartIndex[rows()] + 1, m_colStartIndex[rows()] + 1);
}
}
inline void squeeze() {
finalize();
m_data.squeeze();
}
void prune(Scalar reference, RealScalar epsilon = dummy_precision<RealScalar > ()) {
//TODO
}
/** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero
* \sa resizeNonZeros(Index), reserve(), setZero()
*/
void resize(size_t rows, size_t cols) {
const Index diagSize = rows > cols ? cols : rows;
m_innerSize = IsRowMajor ? cols : rows;
eigen_assert(rows == cols && "Skyline matrix must be square matrix");
if (diagSize % 2) { // diagSize is odd
const Index k = (diagSize - 1) / 2;
m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols,
2 * k * k + k + 1,
2 * k * k + k + 1);
} else // diagSize is even
{
const Index k = diagSize / 2;
m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols,
2 * k * k - k + 1,
2 * k * k - k + 1);
}
if (m_colStartIndex && m_rowStartIndex) {
delete[] m_colStartIndex;
delete[] m_rowStartIndex;
}
m_colStartIndex = new Index [cols + 1];
m_rowStartIndex = new Index [rows + 1];
m_outerSize = diagSize;
m_data.reset();
m_data.clear();
m_outerSize = diagSize;
memset(m_colStartIndex, 0, (cols + 1) * sizeof (Index));
memset(m_rowStartIndex, 0, (rows + 1) * sizeof (Index));
}
void resizeNonZeros(Index size) {
m_data.resize(size);
}
inline SkylineMatrix()
: m_outerSize(-1), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
resize(0, 0);
}
inline SkylineMatrix(size_t rows, size_t cols)
: m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
resize(rows, cols);
}
template<typename OtherDerived>
inline SkylineMatrix(const SkylineMatrixBase<OtherDerived>& other)
: m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
*this = other.derived();
}
inline SkylineMatrix(const SkylineMatrix & other)
: Base(), m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
*this = other.derived();
}
inline void swap(SkylineMatrix & other) {
//EIGEN_DBG_SKYLINE(std::cout << "SkylineMatrix:: swap\n");
std::swap(m_colStartIndex, other.m_colStartIndex);
std::swap(m_rowStartIndex, other.m_rowStartIndex);
std::swap(m_innerSize, other.m_innerSize);
std::swap(m_outerSize, other.m_outerSize);
m_data.swap(other.m_data);
}
inline SkylineMatrix & operator=(const SkylineMatrix & other) {
std::cout << "SkylineMatrix& operator=(const SkylineMatrix& other)\n";
if (other.isRValue()) {
swap(other.const_cast_derived());
} else {
resize(other.rows(), other.cols());
memcpy(m_colStartIndex, other.m_colStartIndex, (m_outerSize + 1) * sizeof (Index));
memcpy(m_rowStartIndex, other.m_rowStartIndex, (m_outerSize + 1) * sizeof (Index));
m_data = other.m_data;
}
return *this;
}
template<typename OtherDerived>
inline SkylineMatrix & operator=(const SkylineMatrixBase<OtherDerived>& other) {
const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
if (needToTranspose) {
// TODO
// return *this;
} else {
// there is no special optimization
return SkylineMatrixBase<SkylineMatrix>::operator=(other.derived());
}
}
friend std::ostream & operator <<(std::ostream & s, const SkylineMatrix & m) {
EIGEN_DBG_SKYLINE(
std::cout << "upper elements : " << std::endl;
for (Index i = 0; i < m.m_data.upperSize(); i++)
std::cout << m.m_data.upper(i) << "\t";
std::cout << std::endl;
std::cout << "upper profile : " << std::endl;
for (Index i = 0; i < m.m_data.upperProfileSize(); i++)
std::cout << m.m_data.upperProfile(i) << "\t";
std::cout << std::endl;
std::cout << "lower startIdx : " << std::endl;
for (Index i = 0; i < m.m_data.upperProfileSize(); i++)
std::cout << (IsRowMajor ? m.m_colStartIndex[i] : m.m_rowStartIndex[i]) << "\t";
std::cout << std::endl;
std::cout << "lower elements : " << std::endl;
for (Index i = 0; i < m.m_data.lowerSize(); i++)
std::cout << m.m_data.lower(i) << "\t";
std::cout << std::endl;
std::cout << "lower profile : " << std::endl;
for (Index i = 0; i < m.m_data.lowerProfileSize(); i++)
std::cout << m.m_data.lowerProfile(i) << "\t";
std::cout << std::endl;
std::cout << "lower startIdx : " << std::endl;
for (Index i = 0; i < m.m_data.lowerProfileSize(); i++)
std::cout << (IsRowMajor ? m.m_rowStartIndex[i] : m.m_colStartIndex[i]) << "\t";
std::cout << std::endl;
);
for (Index rowIdx = 0; rowIdx < m.rows(); rowIdx++) {
for (Index colIdx = 0; colIdx < m.cols(); colIdx++) {
s << m.coeff(rowIdx, colIdx) << "\t";
}
s << std::endl;
}
return s;
}
/** Destructor */
inline ~SkylineMatrix() {
delete[] m_colStartIndex;
delete[] m_rowStartIndex;
}
/** Overloaded for performance */
Scalar sum() const;
};
template<typename Scalar, int _Options>
class SkylineMatrix<Scalar, _Options>::InnerUpperIterator {
public:
InnerUpperIterator(const SkylineMatrix& mat, Index outer)
: m_matrix(mat), m_outer(outer),
m_id(_Options == RowMajor ? mat.m_colStartIndex[outer] : mat.m_rowStartIndex[outer] + 1),
m_start(m_id),
m_end(_Options == RowMajor ? mat.m_colStartIndex[outer + 1] : mat.m_rowStartIndex[outer + 1] + 1) {
}
inline InnerUpperIterator & operator++() {
m_id++;
return *this;
}
inline InnerUpperIterator & operator+=(Index shift) {
m_id += shift;
return *this;
}
inline Scalar value() const {
return m_matrix.m_data.upper(m_id);
}
inline Scalar* valuePtr() {
return const_cast<Scalar*> (&(m_matrix.m_data.upper(m_id)));
}
inline Scalar& valueRef() {
return const_cast<Scalar&> (m_matrix.m_data.upper(m_id));
}
inline Index index() const {
return IsRowMajor ? m_outer - m_matrix.m_data.upperProfile(m_outer) + (m_id - m_start) :
m_outer + (m_id - m_start) + 1;
}
inline Index row() const {
return IsRowMajor ? index() : m_outer;
}
inline Index col() const {
return IsRowMajor ? m_outer : index();
}
inline size_t size() const {
return m_matrix.m_data.upperProfile(m_outer);
}
inline operator bool() const {
return (m_id < m_end) && (m_id >= m_start);
}
protected:
const SkylineMatrix& m_matrix;
const Index m_outer;
Index m_id;
const Index m_start;
const Index m_end;
};
template<typename Scalar, int _Options>
class SkylineMatrix<Scalar, _Options>::InnerLowerIterator {
public:
InnerLowerIterator(const SkylineMatrix& mat, Index outer)
: m_matrix(mat),
m_outer(outer),
m_id(_Options == RowMajor ? mat.m_rowStartIndex[outer] : mat.m_colStartIndex[outer] + 1),
m_start(m_id),
m_end(_Options == RowMajor ? mat.m_rowStartIndex[outer + 1] : mat.m_colStartIndex[outer + 1] + 1) {
}
inline InnerLowerIterator & operator++() {
m_id++;
return *this;
}
inline InnerLowerIterator & operator+=(Index shift) {
m_id += shift;
return *this;
}
inline Scalar value() const {
return m_matrix.m_data.lower(m_id);
}
inline Scalar* valuePtr() {
return const_cast<Scalar*> (&(m_matrix.m_data.lower(m_id)));
}
inline Scalar& valueRef() {
return const_cast<Scalar&> (m_matrix.m_data.lower(m_id));
}
inline Index index() const {
return IsRowMajor ? m_outer - m_matrix.m_data.lowerProfile(m_outer) + (m_id - m_start) :
m_outer + (m_id - m_start) + 1;
;
}
inline Index row() const {
return IsRowMajor ? m_outer : index();
}
inline Index col() const {
return IsRowMajor ? index() : m_outer;
}
inline size_t size() const {
return m_matrix.m_data.lowerProfile(m_outer);
}
inline operator bool() const {
return (m_id < m_end) && (m_id >= m_start);
}
protected:
const SkylineMatrix& m_matrix;
const Index m_outer;
Index m_id;
const Index m_start;
const Index m_end;
};
} // end namespace Eigen
#endif // EIGEN_SkylineMatrix_H
| Java |
//cmdtypist: the main of cmdtypist
/*
Program title: CMDTYPIST
Author: Chiatiah Calson
License: GPL 3 or later versions
Date and Time: 5 July 2017 @ 10:40PM
Program Size: 2.8MB
*/
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<ctype.h>
#include <unistd.h>
//cmdtypist.c: Implementing the main
#include"functions_for_cmd_typist.h"//function prototypes and global variables.
#include"display.h"//display fixing
#include"utils.h"//useful functions
#include"files.h"//file manipulations
#include"config.h"//configuration
#include"terminal.h"//manipulating the terminal
char argv[5][18];
int main(int argc, char **argv)//argc=command line counter, argv=pointer to pointer to character(command line arguments)
{
redirect();
lmt_pg_size();
name_display();
read_message_conf();//welcome message for first time users.
int lesson_choice=1;//global variable to hold the number corresponding to the chosen lesson.
//char commands[][10]={"0ls","1edituser","2myown","3--help","4man","5mkuser","6mkrand","7mkstd", "8select","9chblk","10sound","11--off","12--on","13cch","14reset","15timeset","16atv","17raw"};
char commands[][10]={"ls","edituser","myown","--help","man","mkuser","mkrand","mkstd", "select","chblk","sound","--off","--on","cch","reset","timeset","atv","raw"};
if(argc<1||argc>3)
{
fprintf(stderr, "%s\n", "Invalid number of arguments to cmdtypist");
exit(EXIT_FAILURE);
}
switch(argc)//switching command depending on the number of command line arguments.
{
case 1:
if(read_myown_config()!=0)
{
lesson_list();//list all lessons present.
select_lesson(argc,&lesson_choice);
}
main_play(argc,&lesson_choice);
break;
case 2:
if(strcmp(argv[1],commands[2])==0)
{
write_myown_config(0);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[13])==0)
{
write_myown_config(1);
lesson_list();
select_lesson(argc,&lesson_choice);
system("clear");
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[3])==0)
{
FILE *fp;
if((fp=fopen("help.md","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
puts("");
if(fclose(fp))
{
fprintf(stderr, "%s\n", "Fatal Error, Unable to close some files\n");
exit(EXIT_FAILURE);
}
}
else if(strcmp(argv[1],commands[4])==0)
{
FILE *fp;
if((fp=fopen("Readme.txt","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
}
else if(strcmp(argv[1],commands[6])==0)
write_conf_mode(0);
else if(strcmp(argv[1],commands[7])==0)
write_conf_mode(1);
else if(strcmp(argv[1],commands[14])==0)
{
printf("%s","Will reset to default; continue? [y/n]:");
if(get_only_char()=='n')
exit(EXIT_SUCCESS);
reset_default_config(argv[2],argc);
printf("%s\n","Settings reset to default");
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[16])==0)
{
adapt_to_ver();
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[0])==0)
{
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else fprintf(stderr, "%s\n", "Ensure the second argument is corrrectly spelled");
break;
case 3:
if(strcmp(argv[1],commands[5])==0)
{
test_new_user(argv[2]);
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[14])==0&&strcmp(argv[2],commands[17])==0)
{
reset_default_config(argv[2],argc);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[8])==0)
{
if(read_myown_config()==1)
lesson_choice = range_verifier(is_integral(argv[2],argc));
else
{
lesson_choice=1;
fprintf(stderr, "%s\n\n", "You have been redirected here because you are typing in \"myown\"");
}
main_play(argc,&lesson_choice);
}
/*
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--on")==0)//modifying system sound
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--off")==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}*/
else if((strcmp(argv[1],commands[10])==0))//modifying system sound
{
if(strcmp(argv[2],commands[12])==0)
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[2],commands[11])==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}
else
{
fprintf(stderr, "%s\n", "Check argument 3 for errors, can be \"--on or --off\"");
exit(EXIT_SUCCESS);
}
}
else if(strcmp(argv[1],commands[9])==0)
{
write_conf_block_read(is_integral(argv[2],argc));
exit(EXIT_SUCCESS);
}
break;
/*case 4://later update
if((strcmp(argv[1],"timeset")==0))//testing if user wants to play for specific amount of time.
{
if(strcmp(argv[2],"--on")==0)
{
time_set=1;
main_play();
}
else
{
fprintf(stderr, "%s\n", "Argument 3 invalid or not recognized");
exit(EXIT_SUCCESS);
}
}*/
default:
fprintf(stderr, "%s\n", "Argument is invalid, use \"help\" to find out more");
break;
}
return 0;
}
void select_lesson(int argc_cmd, int* user_choice)
{
char firstarg[81];//
if(argc_cmd>0&&argc_cmd<4)//checking on the command line argument.
{
char ch;//
printf("%s", "Enter command >>");
while(scanf("%s",firstarg)!=1||(scanf("%d",&*user_choice))!=1||*user_choice<1||*user_choice>15||strncmp(firstarg,"select",6)!=0)//Ensuring that "select"
{ //is entered accurately and the selected value is within the correct range.
if((strncmp(firstarg,"se",2)==0||strcmp(firstarg,"sel")==0||strcmp(firstarg,"sele")==0||strcmp(firstarg,"selec")==0)&&strcmp(firstarg,"select")!=0)
//Making suggestion to help user prevent errors.
fprintf(stderr, "\n%s\n%s", "Did you mean \"select usernumber\"","Enter command >>");
else if(ch!=1&&strcmp(firstarg,"select")==0)
printf("%s%s", "Lesson number cannot contain symbols or alphas\n","Enter command >>");
else if((*user_choice<1||*user_choice>20)&&strcmp(firstarg,"select")==0)
fprintf(stderr, "%s %d\n", "No lesson entry for ",*user_choice);
else printf("%s\nEnter command >>", "Command not found");
while(ch=getchar()!='\n');//disposing off wrong input string.
}
}
else
{
fprintf(stderr, "%s\n", "Invalid number of arguments, consult \"cmdtypist --help\" for more");
exit(EXIT_FAILURE);
}
/*
if(argc_cmd==3)
if(strncmp(argv[2],"select",6)!=0||lesson_choice<1||lesson_choice>20)
{
fprintf(stderr, "%s\n", "Command not found\n");
if(strncmp(argv[2],"se",2))
fprintf(stderr, "%s\n", "Did you mean \"select\"");
else if(lesson_choice<1||lesson_choice>20)
fprintf(stderr, "%s %d\n", "No lesson entry for ",lesson_choice);
//else if(ch!=1)
printf("%s", "Lesson number cannot contain symbols or alpha letters.\n");
exit(EXIT_FAILURE);
}*/
printf("\n");
}
void urs_or_cchl(void)
{
if(read_myown_config()==0)
{
strcpy(file_to_read,"my_own.txt");
mode=1;
}
else if(read_myown_config()==1)
strcpy(file_to_read,"noslaclessons.txt");
else
{
fprintf(stderr, "%s\n", "Fatal Error, lesson file corrupted or does not exist");
exit(EXIT_FAILURE);
}
}
void lesson_position(long *read_this_length,long *point_to,int *my_choice)//setting up the pointer in a position of the file to start reading.
{
FILE *lesson_point;
urs_or_cchl();
if((lesson_point=fopen(file_to_read,"r+"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
if(read_myown_config()==0)
{
rewind(lesson_point);//return to beginning
*read_this_length=read_file_size(lesson_point);
*point_to=0;
}
else
switch(*my_choice)
{
case 1:
*point_to=0;
if(read_myown_config()==1)
*read_this_length=25510;
break;
case 2:
*point_to=25512L;
*read_this_length=21660;
break;
case 3:
*point_to=39326L;
*read_this_length=397417;
break;
case 4:
*point_to=444591L;
*read_this_length=11142;
break;
case 5:
*point_to=455733L;
*read_this_length=98588;
break;
case 6:
*point_to=554321L;
*read_this_length=19564;
break;
case 7:
*point_to=573885L;
*read_this_length=79999;
break;
case 8:
*point_to=653884L;
*read_this_length=327523;
break;
case 9:
*point_to=981407L;
*read_this_length=208614;
break;
case 10:
*point_to=1190021L;
*read_this_length=400980;
break;
case 11:
*point_to=1591001L;
*read_this_length=625353;
break;
case 12:
*point_to=2216354L;
*read_this_length=1132581;
break;
default:
*point_to=0;
}
if(fclose(lesson_point))
{
fprintf(stderr, "%s\n", "Unable to close lesson file");
exit(EXIT_FAILURE);
}
}
void main_play(int argc_cmd,int *lesson_choice)
{
//lmt_pg_size();
char terminate=0;
long length_to_read;//holds information on how long the text to be read is.
long move_lesson_to;
lesson_position(&length_to_read,&move_lesson_to,lesson_choice);
unsigned short block_count=0;
user_test();//test if a user already exists or not.
long num_of_chars_typed=0;
block_length=read_conf_block_read();
mode=read_conf_mode();
urs_or_cchl();//selects file to read from
remove_ext_ascii();//removes any non ascii 7 bits characters from lesson file.
unsigned int start_time,elapsed_time=0;//elapsed_time: time used during the typing session measured from start time.
unsigned short number_of_lines_count=1;//used to count the total number of lines to print.
const unsigned short chars_to_read=77;//total number of characters to read for each line.
unsigned int i=0;//counter variable for loop counting.
char linetype[150];//char array to hold the total number of characters to to read from file per line.
//lesson_list();
//fseek(noslac_lessonsp,25531L,SEEK_SET);//places the pointer to the position of the file to read.
int wrong_letters=0;//sums up the total number of wrong characters entered during program run.
srand((unsigned)time(NULL));//randomizing seed
FILE *noslac_lessonsp;//lesson pointer
if((noslac_lessonsp=fopen(file_to_read,"r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
fseek(noslac_lessonsp,move_lesson_to,SEEK_SET);
while(block_count <= (int)(length_to_read/((chars_to_read+1) * block_length)))//testing inorder to read the entire lesson chosen.
{
num_of_chars_typed=0;
char time_checker=0;//changes back to zero after every block typing
/*goes =reads a certain number of characters in the file using a loop determined
by the random generator and places the pointer at the end of it's reading. thereby
making the lesson each time to be random*/
if(mode==0)
{
int u=0;//counter
while(u<=rand()%(length_to_read-((chars_to_read+1)*block_length))&&(ch=getc(noslac_lessonsp))!=EOF)//program feels new
u++;
do
fseek(noslac_lessonsp,-2L,SEEK_CUR);
while((ch=getc(noslac_lessonsp))!=' ');//moving backwards from where it is placed
//to start reading from where there is a space or has found an uppercase letter.
}
number_of_lines_count=1;
while(number_of_lines_count<=block_length)//testing for number of lines to read.
{
i=0;
char endl = guess(14, 33);//endl holds the char to end a line in place of usual '\n'
char startl = guess(14, 33); //guess generates a random char
while(i <= chars_to_read)//test on i to get 77 characters. the screen size is exactly 77 characters.
{
linetype[i] = getc(noslac_lessonsp);//getting characters and placing in the linetype array.
if(linetype[0] == ' ')//prevent a the start of a line from ever being a space character
linetype[0] = startl; //replace with random char
if(linetype[chars_to_read] == ' ')//ensuring a line does not end with a space character.
linetype[chars_to_read] = '-';//replacing space character at the end of a line with a -
if(i > 1)
if(linetype[i-1] == ' ' && linetype[i] == ' ')//preventing two consecutive space characters since text read is random.
i -= 2;
//checking and eliminating newlines to prevent brakes.
if(linetype[i]=='\n'){
linetype[i] = endl;
linetype[++i] = ' ';
}
if(linetype[i]==EOF)//making sure a line does not contain any end of file character by any chance
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <possibly a corrupt cmdtypist file OR you haven't placed any text in myown.txt>");
exit(EXIT_FAILURE);
}
i++;
}
linetype[i]='\0';//Adding string terminator and subtracting the number of spaces removed.
if((number_of_lines_count % (block_length)) == 0 && number_of_lines_count != 0)
printf(""LAST_LINE_BLUE"");
else
printf(""RESET"");
puts(linetype);//using puts inorder to print the a line and move to the next for the user to follow
number_of_lines_count++;
i=0;//setting i to 0 to begin new counting.
unsigned short error_store[3000], j=0;//error_store: array of ints to note the index of a wrong character.
while(i <= chars_to_read+1)//adding 1 for the extra enter key after the 77 letters are entered.
{
int u=0;//loop counter
if((ch=getche())!='\n'&&ch!=EOF)//using getche to prevent printing of enter key.
{
putchar(ch);
if(time_checker==0)//Making sure time is initialized only once
{
time_checker=1;
wrong_letters=0;//setting errors to 0 to start next typing session
start_time=(unsigned)time(NULL);//to start timing.
}
}
if(ch==EOF)
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <an unexpected character keyed in>");
exit(EXIT_FAILURE);
}
if(ch == 27 || ch == '\t')/*testing for ESC character or a tab to exit program.
iscntrl ensures a control character is entered to exit the program*/
{
terminate=1;
letter_clear(1);
puts("\n");
break;
}
if((ch==127 || ch == 8)&& i == 0)//not using '\b' since most terminals are 'cooked' (keys like backspace are handled by terminal driver) //checking for both delete and backspace.
letter_clear(adapt_to_ver_read());
else if((ch == 127 || ch == 8) && i > 0)//testing for delete of backspace
{
i--;//decremting the number of characters entered when backspaced is pressed.
letter_clear(adapt_to_ver_read());
j=wrong_letters;
while(j>u)//counting from u to j, to find if there is a wrong character stored in the error_store array of ints.
{
//printf("j=%d and u=%d\n", j,u);
if(error_store[j]==i)//checking through the array for errased wrong charactes initially entered.
{ //also ensuring before any decrement, wrong_letters>0
wrong_letters--;//decrementing the number of wrong letters.
/*if(wrong_letters<0)
{
printf("finally got a case %d\n",wrong_letters);
wrong_letters=0;
}*/
error_store[j]=-99;//-99 is a value which will never be reached.
//this is to mark the erased index as no longer wrong.
break;//Ensuring that immediately there is a match, the while loop is escaped for speed.
}
j--;
}
}
else if(i==78&&ch!='\n')
letter_clear(1);
else if(ch!=linetype[i])
{
if(ch!='\n')//testing for ENTER to prevent its printing by printf which will cause a newline.
{
num_of_chars_typed++;
letter_clear(1);//clearing the wrong character
//printf("\a"RED"%c"RESET"",ch );//to print again with color RED. \a is used to include a beep for wrong charater
printf("%s%c",(sound_config_read())==1? "\a"RED"":""RED"",ch);//\a is used to include a beep for wrong character entries
wrong_letters++;
error_store[wrong_letters]=i;//recording the index of a wrong letter
u=0;
j++; //Incrementing the backspace counter.
i++; //incrementing the number of wrong characters entered.
}
}
else
{
if(ch!='\n')//Preventing printing of newline which causes an escape from current typing position in the console.
{
letter_clear(1);
num_of_chars_typed++;
printf(""GREEN"%c"RESET"", ch);//changing color of correct character to green.
i++;
}
}
if(ch=='\n'&&i==78)
break;//escaping loop when the user keys in an Enter.
}
printf("%s","\n" ); //Prints two spaces to ensure the two console spaces left are used, so next printing goes to next line. Game console is 80 and 78 is being used.
if(terminate==1||argc_cmd==4)
break;
}
elapsed_time = (unsigned)time(NULL) - start_time;/*getting the final time and subtracting from the initial
to get the elapsed time*/
block_count++;
//printf("lines=%d block = %d\n",number_of_lines_count,block_length );
if(terminate==1)//exiting on tabs and other systme keys
{
char user_name[81];
if(elapsed_time <= 10)
{
fprintf(stderr, "%s\n", "Speed not recorded");
printf(""RESET"\n");
exit(EXIT_SUCCESS);
}
get_user_name(user_name);
printf(""GREEN" ");
printf("%s", user_name);
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);
exit(EXIT_SUCCESS);//display current typing speed and error
}
if(((number_of_lines_count-1)%block_length)==0)
{
char user_name[81];
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
printf(""GREEN" ");
get_user_name(user_name);//reading user name from file to display in session
printf("%s", user_name);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);//printing session speed details
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);//writing user speed to speed file
}
}
}
/*Wrong letters algorithm:
if a user is at the first position of the line and presses backspace, then, that backspace is simply cleared and i not incremented
the array error_store[] keeps track of the index(the i position of the wrong character) and increments a counter variable j, which which be used as
A stop point in a for loop when this stored inex is searched.
When ever backspace keyed in(i!=0), i is first decremented and a search is done through out the loop to see if the decremented i was stored in error store,
if so, then the user is erasing a wrong character, so the wrong_letters is decremented.*/
/*solving the case where wrong_letters shows a messy value
changing it's type to int and making sure it's always greater than 0
*/ | Java |
package com.dank.festivalapp.lib;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static final String DATABASE_NAME = "FestivalApp.db";
private static final int DATABASE_VERSION = 1;
private static DataBaseHelper mInstance = null;
private DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DataBaseHelper getInstance(Context ctx) {
/**
* use the application context as suggested by CommonsWare.
* this will ensure that you dont accidentally leak an Activitys
* context (see this article for more information:
* http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
*/
if (mInstance == null) {
mInstance = new DataBaseHelper(ctx);
}
return mInstance;
}
public boolean isTableExists(SQLiteDatabase db, String tableName)
{
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ tableName +"'", null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DataBaseHelper.class.getName(), "TODO ");
}
}
| Java |
/* WebROaR - Ruby Application Server - http://webroar.in/
* Copyright (C) 2009 Goonj LLC
*
* This file is part of WebROaR.
*
* WebROaR 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.
*
* WebROaR 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 WebROaR. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef WR_ACCESS_LOG_H_
#define WR_ACCESS_LOG_H_
#define WR_ACCESS_LOG_FILE "/var/log/webroar/access.log"
#define WR_REQ_USER_AGENT "HTTP_USER_AGENT"
#define WR_REQ_REFERER "HTTP_REFERER"
#include <wr_request.h>
int wr_access_log(wr_req_t*);
#endif /*WR_ACCESS_LOG_H_*/
| Java |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019-2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 install
import (
"bytes"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/gadget/quantity"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/strutil"
)
var (
ensureNodesExist = ensureNodesExistImpl
)
var createdPartitionGUID = []string{
"0FC63DAF-8483-4772-8E79-3D69D8477DE4", // Linux filesystem data
"0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", // Linux swap partition
}
// creationSupported returns whether we support and expect to create partitions
// of the given type, it also means we are ready to remove them for re-installation
// or retried installation if they are appropriately marked with createdPartitionAttr.
func creationSupported(ptype string) bool {
return strutil.ListContains(createdPartitionGUID, strings.ToUpper(ptype))
}
// createMissingPartitions creates the partitions listed in the laid out volume
// pv that are missing from the existing device layout, returning a list of
// structures that have been created.
func createMissingPartitions(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) ([]gadget.OnDiskStructure, error) {
buf, created := buildPartitionList(dl, pv)
if len(created) == 0 {
return created, nil
}
logger.Debugf("create partitions on %s: %s", dl.Device, buf.String())
// Write the partition table. By default sfdisk will try to re-read the
// partition table with the BLKRRPART ioctl but will fail because the
// kernel side rescan removes and adds partitions and we have partitions
// mounted (so it fails on removal). Use --no-reread to skip this attempt.
cmd := exec.Command("sfdisk", "--append", "--no-reread", dl.Device)
cmd.Stdin = buf
if output, err := cmd.CombinedOutput(); err != nil {
return created, osutil.OutputErr(output, err)
}
// Re-read the partition table
if err := reloadPartitionTable(dl.Device); err != nil {
return nil, err
}
// Make sure the devices for the partitions we created are available
if err := ensureNodesExist(created, 5*time.Second); err != nil {
return nil, fmt.Errorf("partition not available: %v", err)
}
return created, nil
}
// buildPartitionList builds a list of partitions based on the current
// device contents and gadget structure list, in sfdisk dump format, and
// returns a partitioning description suitable for sfdisk input and a
// list of the partitions to be created.
func buildPartitionList(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) (sfdiskInput *bytes.Buffer, toBeCreated []gadget.OnDiskStructure) {
sectorSize := dl.SectorSize
// Keep track what partitions we already have on disk
seen := map[quantity.Offset]bool{}
for _, s := range dl.Structure {
start := s.StartOffset / quantity.Offset(sectorSize)
seen[start] = true
}
// Check if the last partition has a system-data role
canExpandData := false
if n := len(pv.LaidOutStructure); n > 0 {
last := pv.LaidOutStructure[n-1]
if last.VolumeStructure.Role == gadget.SystemData {
canExpandData = true
}
}
// The partition index
pIndex := 0
// Write new partition data in named-fields format
buf := &bytes.Buffer{}
for _, p := range pv.LaidOutStructure {
if !p.IsPartition() {
continue
}
pIndex++
s := p.VolumeStructure
// Skip partitions that are already in the volume
start := p.StartOffset / quantity.Offset(sectorSize)
if seen[start] {
continue
}
// Only allow the creation of partitions with known GUIDs
// TODO:UC20: also provide a mechanism for MBR (RPi)
ptype := partitionType(dl.Schema, p.Type)
if dl.Schema == "gpt" && !creationSupported(ptype) {
logger.Noticef("cannot create partition with unsupported type %s", ptype)
continue
}
// Check if the data partition should be expanded
size := s.Size
if s.Role == gadget.SystemData && canExpandData && quantity.Size(p.StartOffset)+s.Size < dl.Size {
size = dl.Size - quantity.Size(p.StartOffset)
}
// Can we use the index here? Get the largest existing partition number and
// build from there could be safer if the disk partitions are not consecutive
// (can this actually happen in our images?)
node := deviceName(dl.Device, pIndex)
fmt.Fprintf(buf, "%s : start=%12d, size=%12d, type=%s, name=%q\n", node,
p.StartOffset/quantity.Offset(sectorSize), size/sectorSize, ptype, s.Name)
toBeCreated = append(toBeCreated, gadget.OnDiskStructure{
LaidOutStructure: p,
Node: node,
Size: size,
})
}
return buf, toBeCreated
}
func partitionType(label, ptype string) string {
t := strings.Split(ptype, ",")
if len(t) < 1 {
return ""
}
if len(t) == 1 {
return t[0]
}
if label == "gpt" {
return t[1]
}
return t[0]
}
func deviceName(name string, index int) string {
if len(name) > 0 {
last := name[len(name)-1]
if last >= '0' && last <= '9' {
return fmt.Sprintf("%sp%d", name, index)
}
}
return fmt.Sprintf("%s%d", name, index)
}
// removeCreatedPartitions removes partitions added during a previous install.
func removeCreatedPartitions(lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume) error {
indexes := make([]string, 0, len(dl.Structure))
for i, s := range dl.Structure {
if wasCreatedDuringInstall(lv, s) {
logger.Noticef("partition %s was created during previous install", s.Node)
indexes = append(indexes, strconv.Itoa(i+1))
}
}
if len(indexes) == 0 {
return nil
}
// Delete disk partitions
logger.Debugf("delete disk partitions %v", indexes)
cmd := exec.Command("sfdisk", append([]string{"--no-reread", "--delete", dl.Device}, indexes...)...)
if output, err := cmd.CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
// Reload the partition table
if err := reloadPartitionTable(dl.Device); err != nil {
return err
}
// Re-read the partition table from the device to update our partition list
if err := gadget.UpdatePartitionList(dl); err != nil {
return err
}
// Ensure all created partitions were removed
if remaining := createdDuringInstall(lv, dl); len(remaining) > 0 {
return fmt.Errorf("cannot remove partitions: %s", strings.Join(remaining, ", "))
}
return nil
}
// ensureNodeExists makes sure the device nodes for all device structures are
// available and notified to udev, within a specified amount of time.
func ensureNodesExistImpl(dss []gadget.OnDiskStructure, timeout time.Duration) error {
t0 := time.Now()
for _, ds := range dss {
found := false
for time.Since(t0) < timeout {
if osutil.FileExists(ds.Node) {
found = true
break
}
time.Sleep(100 * time.Millisecond)
}
if found {
if err := udevTrigger(ds.Node); err != nil {
return err
}
} else {
return fmt.Errorf("device %s not available", ds.Node)
}
}
return nil
}
// reloadPartitionTable instructs the kernel to re-read the partition
// table of a given block device.
func reloadPartitionTable(device string) error {
// Re-read the partition table using the BLKPG ioctl, which doesn't
// remove existing partitions, only appends new partitions with the right
// size and offset. As long as we provide consistent partitioning from
// userspace we're safe.
output, err := exec.Command("partx", "-u", device).CombinedOutput()
if err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// udevTrigger triggers udev for the specified device and waits until
// all events in the udev queue are handled.
func udevTrigger(device string) error {
if output, err := exec.Command("udevadm", "trigger", "--settle", device).CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// wasCreatedDuringInstall returns if the OnDiskStructure was created during
// install by referencing the gadget volume. A structure is only considered to
// be created during install if it is a role that is created during install and
// the start offsets match. We specifically don't look at anything on the
// structure such as filesystem information since this may be incomplete due to
// a failed installation, or due to the partial layout that is created by some
// ARM tools (i.e. ptool and fastboot) when flashing images to internal MMC.
func wasCreatedDuringInstall(lv *gadget.LaidOutVolume, s gadget.OnDiskStructure) bool {
// for a structure to have been created during install, it must be one of
// the system-boot, system-data, or system-save roles from the gadget, and
// as such the on disk structure must exist in the exact same location as
// the role from the gadget, so only return true if the provided structure
// has the exact same StartOffset as one of those roles
for _, gs := range lv.LaidOutStructure {
// TODO: how to handle ubuntu-save here? maybe a higher level function
// should decide whether to delete it or not?
switch gs.Role {
case gadget.SystemSave, gadget.SystemData, gadget.SystemBoot:
// then it was created during install or is to be created during
// install, see if the offset matches the provided on disk structure
// has
if s.StartOffset == gs.StartOffset {
return true
}
}
}
return false
}
// createdDuringInstall returns a list of partitions created during the
// install process.
func createdDuringInstall(lv *gadget.LaidOutVolume, layout *gadget.OnDiskVolume) (created []string) {
created = make([]string, 0, len(layout.Structure))
for _, s := range layout.Structure {
if wasCreatedDuringInstall(lv, s) {
created = append(created, s.Node)
}
}
return created
}
| Java |
--
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: casts; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA casts;
SET search_path = casts, pg_catalog;
--
-- Name: _date_to_bigint(date); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _date_to_bigint(date) RETURNS bigint
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT casts._date_to_integer($1)::bigint
$_$;
--
-- Name: _date_to_integer(date); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _date_to_integer(date) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(YEAR FROM $1)::integer * 10000
+ EXTRACT(MONTH FROM $1)::integer * 100
+ EXTRACT(DAY FROM $1)::integer
$_$;
--
-- Name: _interval_to_bigint(interval); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _interval_to_bigint(interval) RETURNS bigint
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(YEAR FROM $1)::bigint * 10000000000
+ EXTRACT(MONTH FROM $1)::bigint * 100000000
+ EXTRACT(DAY FROM $1)::bigint * 1000000
+ EXTRACT(HOUR FROM $1)::bigint * 10000
+ EXTRACT(MINUTE FROM $1)::bigint * 100
+ EXTRACT(SECONDS FROM $1)::bigint
$_$;
--
-- Name: _text_to_bigint(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_bigint(text) RETURNS bigint
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
--
-- Name: _text_to_date(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_date(text) RETURNS date
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $& if( $_[0] =~ m/^(\d{4}-\d{1,2}-\d{1,2})/ );
return undef;
$_X$;
--
-- Name: _text_to_numeric(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_numeric(text) RETURNS numeric
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $1.$2 if( $_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
--
-- Name: _text_to_time(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_time(text) RETURNS time without time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $& if( $_[0] =~ s/^(\d{1,2}:\d{1,2})(:\d{1,2}(\.\d+)?)?$/$1$2/ );
return undef;
$_X$;
--
-- Name: _text_to_timestamp(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_timestamp(text) RETURNS timestamp without time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ );
return undef;
$_X$;
--
-- Name: _text_to_timestamptz(text); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _text_to_timestamptz(text) RETURNS timestamp with time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ );
return undef;
$_X$;
--
-- Name: _time_to_integer(time without time zone); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _time_to_integer(time without time zone) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(HOUR FROM $1)::integer * 10000
+ EXTRACT(MINUTE FROM $1)::integer * 100
+ EXTRACT(SECONDS FROM $1)::integer
$_$;
--
-- Name: _time_to_integer(time with time zone); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _time_to_integer(time with time zone) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(HOUR FROM $1)::integer * 10000
+ EXTRACT(MINUTE FROM $1)::integer * 100
+ EXTRACT(SECONDS FROM $1)::integer
$_$;
--
-- Name: _unknown_to_bigint(unknown); Type: FUNCTION; Schema: casts; Owner: -
--
CREATE OR REPLACE FUNCTION _unknown_to_bigint(unknown) RETURNS bigint
LANGUAGE plperlu
AS $_X$
return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
SET search_path = pg_catalog;
--
-- Name: CAST (date AS integer); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (date AS integer) WITH FUNCTION casts._date_to_integer(date) AS IMPLICIT;
--
-- Name: CAST (date AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (date AS bigint) WITH FUNCTION casts._date_to_bigint(date) AS IMPLICIT;
--
-- Name: CAST (interval AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (interval AS bigint) WITH FUNCTION casts._interval_to_bigint(interval) AS IMPLICIT;
--
-- Name: CAST (text AS date); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS date) WITH FUNCTION casts._text_to_date(text) AS IMPLICIT;
--
-- Name: CAST (text AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS bigint) WITH FUNCTION casts._text_to_bigint(text) AS IMPLICIT;
--
-- Name: CAST (text AS numeric); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS numeric) WITH FUNCTION casts._text_to_numeric(text) AS IMPLICIT;
--
-- Name: CAST (text AS time without time zone); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS time without time zone) WITH FUNCTION casts._text_to_time(text) AS IMPLICIT;
--
-- Name: CAST (text AS timestamp without time zone); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS timestamp without time zone) WITH FUNCTION casts._text_to_timestamp(text) AS IMPLICIT;
--
-- Name: CAST (text AS timestamp with time zone); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (text AS timestamp with time zone) WITH FUNCTION casts._text_to_timestamptz(text) AS IMPLICIT;
--
-- Name: CAST (time without time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (time without time zone AS integer) WITH FUNCTION casts._time_to_integer(time without time zone) AS IMPLICIT;
--
-- Name: CAST (time with time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (time with time zone AS integer) WITH FUNCTION casts._time_to_integer(time with time zone) AS IMPLICIT;
--
-- Name: CAST (unknown AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
--
CREATE CAST (unknown AS bigint) WITH FUNCTION casts._unknown_to_bigint(unknown) AS IMPLICIT;
--
-- PostgreSQL database dump complete
--
| Java |
# Thème Wordpress du site tela-botanica.org
Ce thème utilise le bundler [Webpack](https://webpack.github.io) et l'outil de
gestion de dépendances [Composer](https://getcomposer.org).
## Pour débuter
Installer [Node](https://nodejs.org)
Installer les dépendences du projet
npm install
composer install
Définir les constantes suivantes dans `wp-config.php`:
```php
/**
* Remplir ces valeurs avec les clés d'API du compte Algolia
*/
define('ALGOLIA_APPLICATION_ID',);
define('ALGOLIA_SEARCH_API_KEY',);
define('ALGOLIA_ADMIN_API_KEY',);
define('ALGOLIA_PREFIX',); // (correspondant à l'environnement en cours, par exemple `prod_`)
```
### Pendant le développement
npm start
Cette commande :
- surveille les fichiers du thème
- recompile automatiquement à chaque modification
### Compiler le thème
npm run build
Cette commande :
- compile `assets/styles/main.scss` dans `dist/bundle.css`
- compile `assets/scripts/main.js` dans `dist/bundle.js`
- inclut en inline les images SVG utilisées dans les feuilles de style
### Déployer le thème avec git
Depuis le serveur :
git pull
composer install
| Java |
// ----------------------------------------------------------------------
// File: VersionedHashRevisionTracker.cc
// Author: Georgios Bitzes - CERN
// ----------------------------------------------------------------------
/************************************************************************
* quarkdb - a redis-like highly available key-value store *
* Copyright (C) 2019 CERN/Switzerland *
* *
* 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/>.*
************************************************************************/
#include "VersionedHashRevisionTracker.hh"
#include "utils/Macros.hh"
#include "Formatter.hh"
namespace quarkdb {
//------------------------------------------------------------------------------
// Indicate which revision we're referring to. When called multiple times
// for the same object, the given value MUST be the same.
//------------------------------------------------------------------------------
void VersionedHashRevision::setRevisionNumber(uint64_t rev) {
if(currentRevision != 0) {
qdb_assert(currentRevision == rev);
}
else {
currentRevision = rev;
}
}
//------------------------------------------------------------------------------
// Add to update batch - empty value indicates deletion
//------------------------------------------------------------------------------
void VersionedHashRevision::addUpdate(std::string_view field, std::string_view value) {
updateBatch.emplace_back(field, value);
}
//------------------------------------------------------------------------------
// Serialize contents
//------------------------------------------------------------------------------
std::string VersionedHashRevision::serialize() const {
return Formatter::vhashRevision(currentRevision, updateBatch).val;
}
//------------------------------------------------------------------------------
// Get revision for a specific key
//------------------------------------------------------------------------------
VersionedHashRevision& VersionedHashRevisionTracker::forKey(std::string_view key) {
return contents[std::string(key)];
}
//------------------------------------------------------------------------------
// Iterate through contents
//------------------------------------------------------------------------------
std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::begin() {
return contents.begin();
}
std::map<std::string, VersionedHashRevision>::iterator VersionedHashRevisionTracker::end() {
return contents.end();
}
}
| Java |
Provisioning a new site
=======================
## Required packages:
* nginx
* Python 3
* Git
* pip
* virtualenv
e.g.,, on Ubuntu:
sudo apt-get install nginx git python3 python3-pip
sudo pip3 install virtualenv
## Nginx Virtual Host config
* see nginx.template.conf
* replace SITENAME with, e.g., staging.my-domain.com
## Systemd service
* see gunicorn-systemd.template.service
* replace SITENAME with, e.g., staging.my-domain.com
## Folder structure:
Assume we have a user account at /home/username
/home/username
└── sites
└── SITENAME
├── database
├── source
├── static
└── virtualenv
| Java |
package ems.server.protocol;
import ems.server.domain.Device;
import ems.server.domain.EventSeverity;
import ems.server.domain.EventType;
import ems.server.utils.EventHelper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* EventAwareResponseHandler
* Created by thebaz on 9/15/14.
*/
public class EventAwareResponseHandler implements ResponseHandler {
private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
private final Device device;
public EventAwareResponseHandler(Device device) {
this.device = device;
format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override
public void onTimeout(String variable) {
EventHelper.getInstance().addEvent(device, EventType.EVENT_NETWORK, EventSeverity.EVENT_WARN);
}
@Override
public void onSuccess(String variable) {
//do nothing
}
@Override
public void onError(String variable, int errorCode, String errorDescription) {
EventSeverity eventSeverity = EventSeverity.EVENT_ERROR;
EventType eventType = EventType.EVENT_PROTOCOL;
String description = "Event of type: \'" + eventType + "\' at: " +
format.format(new Date(System.currentTimeMillis())) + " with severity: \'" +
eventSeverity + "\' for device: " + device.getName() + ". Error code:" +
errorCode + ", Error description: " + errorDescription;
EventHelper.getInstance().addEvent(device, eventType, eventSeverity, description);
}
}
| Java |
<?php
/*
COPYRIGHT 2008 - see www.milliondollarscript.com for a list of authors
This file is part of the Million Dollar Script.
Million Dollar Script 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.
Million Dollar Script 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 the Million Dollar Script. If not, see <http://www.gnu.org/licenses/>.
*/
require_once ('category.inc.php');
require_once ('lists.inc.php');
require_once ('dynamic_forms.php');
global $ad_tag_to_field_id;
global $ad_tag_to_search;
global $CACHE_ENABLED;
if ($CACHE_ENABLED=='YES') {
$dir = dirname(__FILE__);
$dir = preg_split ('%[/\\\]%', $dir);
$blank = array_pop($dir);
$dir = implode('/', $dir);
include ("$dir/cache/form1_cache.inc.php");
$ad_tag_to_search = $tag_to_search;
$ad_tag_to_field_id = $tag_to_field_id;
} else {
$ad_tag_to_search = tag_to_search_init(1);
$ad_tag_to_field_id = ad_tag_to_field_id_init();
}
#####################################
function ad_tag_to_field_id_init () {
global $CACHE_ENABLED;
if ($CACHE_ENABLED=='YES') {
global $ad_tag_to_field_id;
return $ad_tag_to_field_id;
}
global $label;
$sql = "SELECT *, t2.field_label AS NAME FROM `form_fields` as t1, form_field_translations as t2 where t1.field_id = t2.field_id AND t2.lang='".$_SESSION['MDS_LANG']."' AND form_id=1 ORDER BY list_sort_order ";
$result = mysql_query($sql) or die (mysql_error());
# do a query for each field
while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) {
//$form_data = $row[]
$tag_to_field_id[$fields['template_tag']]['field_id'] = $fields['field_id'];
$tag_to_field_id[$fields['template_tag']]['field_type'] = $fields['field_type'];
$tag_to_field_id[$fields['template_tag']]['field_label'] = $fields['NAME'];
}
$tag_to_field_id["ORDER_ID"]['field_id'] = 'order_id';
$tag_to_field_id["ORDER_ID"]['field_label'] = 'Order ID';
//$tag_to_field_id["ORDER_ID"]['field_label'] = $label["employer_resume_list_date"];
$tag_to_field_id["BID"]['field_id'] = 'banner_id';
$tag_to_field_id["BID"]['field_label'] = 'Grid ID';
$tag_to_field_id["USER_ID"]['field_id'] = 'user_id';
$tag_to_field_id["USER_ID"]['field_label'] = 'User ID';
$tag_to_field_id["AD_ID"]['field_id'] = 'ad_id';
$tag_to_field_id["AD_ID"]['field_label'] = 'Ad ID';
$tag_to_field_id["DATE"]['field_id'] = 'ad_date';
$tag_to_field_id["DATE"]['field_label'] = 'Date';
return $tag_to_field_id;
}
######################################################################
function load_ad_values ($ad_id) {
$prams = array();
$sql = "SELECT * FROM `ads` WHERE ad_id='$ad_id' ";
$result = mysql_query($sql) or die ($sql. mysql_error());
if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$prams['ad_id'] = $ad_id;
$prams['user_id'] = $row['user_id'];
$prams['order_id'] = $row['order_id'];
$prams['banner_id'] = $row['banner_id'];
$sql = "SELECT * FROM form_fields WHERE form_id=1 AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
$result = mysql_query($sql) or die(mysql_error());
while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) {
$prams[$fields['field_id']] = $row[$fields['field_id']];
if ($fields['field_type']=='DATE') {
$day = $_REQUEST[$row['field_id']."d"];
$month = $_REQUEST[$row['field_id']."m"];
$year = $_REQUEST[$row['field_id']."y"];
$prams[$fields['field_id']] = "$year-$month-$day";
} elseif (($fields['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) {
if (is_array($_REQUEST[$row['field_id']])) {
$prams[$fields['field_id']] = implode (",", $_REQUEST[$fields['field_id']]);
} else {
$prams[$fields['field_id']] = $_REQUEST[$fields['field_id']];
}
}
}
return $prams;
} else {
return false;
}
}
#########################################################
function assign_ad_template($prams) {
global $label;
$str = $label['mouseover_ad_template'];
$sql = "SELECT * FROM form_fields WHERE form_id='1' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
//echo $sql;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($row['field_type']=='IMAGE') {
if ((file_exists(UPLOAD_PATH.'images/'.$prams[$row['field_id']]))&&($prams[$row['field_id']])) {
$str = str_replace('%'.$row['template_tag'].'%', '<img alt="" src="'. UPLOAD_HTTP_PATH."images/".$prams[$row['field_id']].'" >', $str);
} else {
//$str = str_replace('%'.$row['template_tag'].'%', '<IMG SRC="'.UPLOAD_HTTP_PATH.'images/no-image.gif" WIDTH="150" HEIGHT="150" BORDER="0" ALT="">', $str);
$str = str_replace('%'.$row['template_tag'].'%', '', $str);
}
} else {
$str = str_replace('%'.$row['template_tag'].'%', get_template_value($row['template_tag'],1), $str);
}
$str = str_replace('$'.$row['template_tag'].'$', get_template_field_label($row['template_tag'],1), $str);
}
return $str;
}
#########################################################
function display_ad_form ($form_id, $mode, $prams) {
global $label;
global $error;
global $BID;
if ($prams == '' ) {
$prams['mode'] = $_REQUEST['mode'];
$prams['ad_id']= $_REQUEST['ad_id'];
$prams['banner_id'] = $BID;
$prams['user_id'] = $_REQUEST['user_id'];
$sql = "SELECT * FROM form_fields WHERE form_id='$form_id' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
//echo $sql;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//$prams[$row[field_id]] = $_REQUEST[$row[field_id]];
if ($row['field_type']=='DATE') {
$day = $_REQUEST[$row['field_id']."d"];
$month = $_REQUEST[$row['field_id']."m"];
$year = $_REQUEST[$row['field_id']."y"];
$prams[$row['field_id']] = "$year-$month-$day";
} elseif (($row['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) {
if (is_array($_REQUEST[$row['field_id']])) {
$prams[$row['field_id']] = implode (",", $_REQUEST[$row['field_id']]);
} else {
$prams[$row['field_id']] = $_REQUEST[$row['field_id']];
}
} else {
$prams[$row['field_id']] = stripslashes ($_REQUEST[$row['field_id']]);
}
}
}
if (!defined('SCW_INCLUDE')) {
?>
<script type='text/JavaScript' src='<?php echo BASE_HTTP_PATH."scw/scw_js.php?lang=".$_SESSION['MDS_LANG']; ?>'></script>
<?php
define ('SCW_INCLUDE', 'Y');
}
?>
<form method="POST" action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" name="form1" onsubmit=" form1.savebutton.disabled=true;" enctype="multipart/form-data">
<input type="hidden" name="mode" size="" value="<?php echo $mode; ?>">
<input type="hidden" name="ad_id" size="" value="<?php echo $prams['ad_id']; ?>">
<input type="hidden" name="user_id" size="" value="<?php echo $prams['user_id']; ?>">
<input type="hidden" name="order_id" size="" value="<?php echo $prams['order_id']; ?>">
<input type="hidden" name="banner_id" size="" value="<?php echo $prams['banner_id']; ?>">
<table cellSpacing="1" cellPadding="5" class="ad_data" id="ad" >
<?php if (($error != '' ) && ($mode!='EDIT')) { ?>
<tr>
<td bgcolor="#F2F2F2" colspan="2"><?php echo "<span class='error_msg_label'>".$label['ad_save_error']."</span><br> <b>".$error."</b>"; ?></td>
</tr>
<?php } ?>
<tr bgColor="#ffffff">
<td bgColor="#eaeaea">
<?php if ($mode == "EDIT") {
echo "[Ad Form]";
}
// section 1
display_form ($form_id, $mode, $prams, 1);
?>
</tr>
<tr><td colspan="2" bgcolor="#ffffff">
<input type="hidden" name="save" id="save101" value="">
<?php if ($mode=='edit') { ?>
<input class="form_submit_button" TYPE="SUBMIT" class='big_button' name="savebutton" value="<?php echo $label['ad_save_button'];?>" onClick="save101.value='1';">
<?php } ?>
</td></tr>
</table>
</form>
<?php
}
###########################################################################
function list_ads ($admin=false, $order, $offset, $list_mode='ALL', $user_id='') {
## Globals
global $label;
global $tag_to_field_id;
$tag_to_field_id = ad_tag_to_field_id_init();
###########################################
# Load in the form data, including column names
# (dont forget LANGUAGE TOO)
global $ad_tag_to_field_id;
$records_per_page = 40;
global $label; // languages array
$order_str = $order;
if ($order == '') {
$order = " `order_id` ";
} else {
$order = " `$order` ";
}
global $action;
// process search result
if ($_REQUEST['action'] == 'search') {
$q_string = generate_q_string(1);
$where_sql = generate_search_sql(1);
}
// DATE_FORMAT(`adate`, '%d-%b-%Y') AS formatted_date
$order = $_REQUEST['order_by'];
if ($_REQUEST['ord']=='asc') {
$ord = 'ASC';
} elseif ($_REQUEST['ord']=='desc') {
$ord = 'DESC';
} else {
$ord = 'DESC'; // sort descending by default
}
if ($order == '') {
$order = " `ad_date` ";
} else {
$order = " `$order` ";
}
global $BID;
if ($list_mode == 'USER' ) {
if (!is_numeric($user_id)) {
$user_id = $_SESSION['MDS_ID'];
}
$sql = "Select * FROM `ads` as t1, `orders` as t2 WHERE t1.ad_id=t2.ad_id AND t1.order_id > 0 AND t1.banner_id='".$BID."' AND t1.user_id='".$user_id."' AND (t2.status = 'completed' OR t2.status = 'expired') $where_sql ORDER BY $order $ord ";
} elseif ($list_mode =='TOPLIST') {
// $sql = "SELECT *, DATE_FORMAT(MAX(order_date), '%Y-%c-%d') as max_date, sum(quantity) AS pixels FROM orders, ads where ads.order_id=orders.order_id AND status='completed' and orders.banner_id='$BID' GROUP BY orders.user_id, orders.banner_id order by pixels desc ";
} else {
$sql = "Select * FROM `ads` as t1, `orders` AS t2 WHERE t1.ad_id=t2.ad_id AND t1.banner_id='$BID' and t1.order_id > 0 $where_sql ORDER BY $order $ord ";
}
//echo "[".$sql."]";
$result = mysql_query($sql) or die (mysql_error());
############
# get the count
$count = mysql_num_rows($result);
if ($count > $records_per_page) {
mysql_data_seek($result, $offset);
}
if ($count > 0 ) {
if ($pages == 1) {
} elseif ($list_mode!='USER') {
$pages = ceil($count / $records_per_page);
$cur_page = $_REQUEST['offset'] / $records_per_page;
$cur_page++;
echo "<center>";
//echo "Page $cur_page of $pages - ";
$label["navigation_page"] = str_replace ("%CUR_PAGE%", $cur_page, $label["navigation_page"]);
$label["navigation_page"] = str_replace ("%PAGES%", $pages, $label["navigation_page"]);
echo "<span > ".$label["navigation_page"]."</span> ";
$nav = nav_pages_struct($result, $q_string, $count, $records_per_page);
$LINKS = 10;
render_nav_pages($nav, $LINKS, $q_string, $show_emp, $cat);
echo "</center>";
}
$dir = dirname(__FILE__);
$dir = preg_split ('%[/\\\]%', $dir);
$blank = array_pop($dir);
$dir = implode('/', $dir);
include ($dir.'/mouseover_box.htm'); // edit this file to change the style of the mouseover box!
echo '<script language="JAVASCRIPT">';
include ('mouseover_js.inc.php');
echo '</script>';
?>
<table border='0' bgcolor='#d9d9d9' cellspacing="1" cellpadding="5" id="adslist" >
<tr bgcolor="#EAEAEA">
<?php
if ($admin == true ) {
echo '<td class="list_header_cell"> </td>';
}
if ($list_mode == 'USER' ) {
echo '<td class="list_header_cell"> </td>';
}
echo_list_head_data(1, $admin);
if (($list_mode == 'USER' ) || ($admin)) {
echo '<td class="list_header_cell">'.$label['ads_inc_pixels_col'].'</td>';
echo '<td class="list_header_cell">'.$label['ads_inc_expires_col'].'</td>';
echo '<td class="list_header_cell" >'.$label['ad_list_status'].'</td>';
}
?>
</tr>
<?php
$i=0; global $prams;
while (($prams = mysql_fetch_array($result, MYSQL_ASSOC)) && ($i < $records_per_page)) {
$i++;
?>
<tr bgcolor="ffffff" onmouseover="old_bg=this.getAttribute('bgcolor');this.setAttribute('bgcolor', '#FBFDDB', 0);" onmouseout="this.setAttribute('bgcolor', old_bg, 0);">
<?php
if ($admin == true ) {
echo '<td class="list_data_cell" >';
?>
<!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>!-->
<input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=edit&ad_id=<?php echo $prams['ad_id']; ?>'">
<?php
echo '</td>';
}
if ($list_mode == 'USER' ) {
echo '<td class="list_data_cell">';
?>
<!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>-->
<input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?ad_id=<?php echo $prams['ad_id']; ?>'">
<?php
echo '</td>';
}
echo_ad_list_data($admin);
if (($list_mode == 'USER' ) || ($admin)) {
/////////////////
echo '<td class="list_data_cell"><img src="get_order_image.php?BID='.$BID.'&aid='.$prams['ad_id'].'"></td>';
//////////////////
echo '<td>';
if ($prams['days_expire'] > 0) {
if ($prams['published']!='Y') {
$time_start = strtotime(gmdate('r'));
} else {
$time_start = strtotime($prams['date_published']." GMT");
}
$elapsed_time = strtotime(gmdate('r')) - $time_start;
$elapsed_days = floor ($elapsed_time / 60 / 60 / 24);
$exp_time = ($prams['days_expire'] * 24 * 60 * 60);
$exp_time_to_go = $exp_time - $elapsed_time;
$exp_days_to_go = floor ($exp_time_to_go / 60 / 60 / 24);
$to_go = elapsedtime($exp_time_to_go);
$elapsed = elapsedtime($elapsed_time);
if ($prams['status']=='expired') {
$days = "<a href='orders.php'>".$label['ads_inc_expied_stat']."</a>";
} elseif ($prams['date_published']=='') {
$days = $label['ads_inc_nyp_stat'];
} else {
$days = str_replace ('%ELAPSED%', $elapsed, $label['ads_inc_elapsed_stat']);
$days = str_replace ('%TO_GO%', $to_go, $days);
//$days = "$elapsed elapsed<br> $to_go to go ";
}
//$days = $elapsed_time;
//print_r($prams);
} else {
$days = $label['ads_inc_nev_stat'];
}
echo $days;
echo '</td>';
/////////////////
if ($prams['published']=='Y') {
$pub =$label['ads_inc_pub_stat'];
} else {
$pub = $label['ads_inc_npub_stat'];
}
if ($prams['approved']=='Y') {
$app = $label['ads_inc_app_stat'].', ';
} else {
$app = $label['ads_inc_napp_stat'].', ';
}
//$label['ad_list_st_'.$prams['status']]."
echo '<td class="list_data_cell">'.$app.$pub."</td>";
}
?>
</tr>
<?php
//$prams[file_photo] = '';
// $new_name='';
}
echo "</table>";
} else {
echo "<center><font size='2' face='Arial'><b>".$label["ads_not_found"].".</b></font></center>";
}
return $count;
}
########################################################
function delete_ads_files ($ad_id) {
$sql = "select * from form_fields where form_id=1 ";
$result = mysql_query ($sql) or die (mysql_error());
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$field_id = $row['field_id'];
$field_type = $row['field_type'];
if (($field_type == "FILE")) {
deleteFile("ads", "ad_id", $ad_id, $field_id);
}
if (($field_type == "IMAGE")){
deleteImage("ads", "ad_id", $ad_id, $field_id);
}
}
}
####################
function delete_ad ($ad_id) {
delete_ads_files ($ad_id);
$sql = "delete FROM `ads` WHERE `ad_id`='".$ad_id."' ";
$result = mysql_query($sql) or die (mysql_error().$sql);
}
################################
function search_category_tree_for_ads() {
if (func_num_args() > 0 ) {
$cat_id = func_get_arg(0);
} else {
$cat_id = $_REQUEST[cat];
}
$sql = "select search_set from categories where category_id='$cat_id' ";
$result2 = mysql_query ($sql) or die (mysql_error());
$row = mysql_fetch_array($result2);
$search_set = $row[search_set];
$sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'";
$result = mysql_query ($sql) or die (mysql_error());
$i=0;
if (mysql_num_rows($result) >0) {
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i>0) {
$where_cat .= " OR ";
}
$where_cat .= " `$row[field_id]` IN ($search_set) ";
$i++;
}
}
if ($where_cat=='') {
return " AND 1=2 ";
}
if ($search_set=='') {
return "";
}
return " AND ($where_cat) ";
}
####################
function search_category_for_ads() {
if (func_num_args() > 0 ) {
$cat_id = func_get_arg(0);
} else {
$cat_id = $_REQUEST[cat];
}
$sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'";
$result = mysql_query ($sql) or die (mysql_error());
$i=0;
if (mysql_num_rows($result) >0) {
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i>0) {
$where_cat .= " OR ";
}
$where_cat .= " `$row[field_id]`='$cat_id' ";
$i++;
}
}
if ($where_cat=='') {
return " AND 1=2 ";
}
return " AND ($where_cat) ";
//$sql ="Select * from posts_table where $where_cat ";
//echo $sql."<br/>";
//$result2 = mysql_query ($sql) or die (mysql_error());
}
##################
function generate_ad_id () {
$query ="SELECT max(`ad_id`) FROM `ads`";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$row[0]++;
return $row[0];
}
#################
function temp_ad_exists($sid) {
$query ="SELECT ad_id FROM `ads` where user_id='$sid' ";
$result = mysql_query($query) or die(mysql_error());
// $row = mysql_fetch_row($result);
return mysql_num_rows($result);
}
################################################################
function insert_ad_data() {
if (func_num_args() > 0) {
$admin = func_get_arg(0); // admin mode.
}
$user_id = $_SESSION['MDS_ID'];
if ($user_id=='') {
$user_id = addslashes(session_id());
}
$order_id = $_REQUEST['order_id'];
$ad_date = (gmdate("Y-m-d H:i:s"));
$banner_id = $_REQUEST['banner_id'];
if ($_REQUEST['ad_id'] == '') {
$ad_id = generate_ad_id ();
$now = (gmdate("Y-m-d H:i:s"));
$sql = "REPLACE INTO `ads` (`ad_id`, `order_id`, `user_id`, `ad_date`, `banner_id` ".get_sql_insert_fields(1).") VALUES ('$ad_id', '$order_id', '$user_id', '$ad_date', '$banner_id' ".get_sql_insert_values(1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id).") ";
} else {
$ad_id = $_REQUEST['ad_id'];
if (!$admin) { // make sure that the logged in user is the owner of this ad.
if (!is_numeric($_REQUEST['user_id'])) { // temp order (user_id = session_id())
if ($_REQUEST['user_id']!=session_id()) return false;
} else { // user is logged in
$sql = "select user_id from `ads` WHERE ad_id='".$_REQUEST['ad_id']."'";
$result = mysql_query ($sql) or die(mysql_error());
$row = @mysql_fetch_array($result);
if ($_SESSION['MDS_ID']!==$row['user_id']) {
return false; // not the owner, hacking attempt!
}
}
}
$now = (gmdate("Y-m-d H:i:s"));
$sql = "UPDATE `ads` SET `ad_date`='$now' ".get_sql_update_values (1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id)." WHERE ad_id='".$ad_id."'";
}
//echo "<hr><b>Insert:</b> $sql<hr>";
//print_r ($_FILES);
mysql_query ($sql) or die("[$sql]".mysql_error());
//build_ad_count(0);
return $ad_id;
}
###############################################################
function validate_ad_data($form_id) {
return validate_form_data(1);
return $error;
}
################################################################
function update_blocks_with_ad($ad_id, $user_id) {
global $prams;
$prams = load_ad_values($ad_id);
if ($prams['order_id']>0) {
$sql = "UPDATE blocks SET alt_text='".addslashes(get_template_value('ALT_TEXT', 1))."', url='".addslashes(get_template_value('URL', 1))."' WHERE order_id='".$prams['order_id']."' AND user_id='".$user_id."' ";
mysql_query($sql) or die(mysql_error());
mds_log("Updated blocks with ad URL, ALT_TEXT", $sql);
}
}
?> | Java |
// binary_frame.go
/*
Binary Frame Tool.
Version: 0.1.1.
Date of Creation: 2018-01-28.
Author: McArcher.
This is a simple Tool which draws a binary Frame around the Content.
A Frame consists of logical Ones (1) and has a Spacer of Zeroes (0).
So,
---
XXX
XXX
---
Becomes something with a binary Frame with a Spacer:
-------
1111111
1000001
10XXX01
10XXX01
1000001
1111111
-------
This Technique is a great Thing to enclose Dimensions of the "X" into the
File. It may be useful for Transmission of Signals in Space or other Places
with a great Chances for Signal Corruption. Even when damaged, a Frame or
Remains of a Frame may help a lot in the Process of Data Recovery. This
Frame may be used as a Transport Package when there is no Package of the
Transmission Protocol, and may be used in a universal Range.
To comply with this-day Computers, the Algorithm makes Sizes compatible
with 8-Bit Bytes, but it is also able to use any Size you want.
*/
//==============================================================================
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"os"
"strconv"
)
//==============================================================================
type bit bool
type row_of_bits []bit
type field_of_bits []row_of_bits
//==============================================================================
const bits_in_byte = 8
const FILLED = true
const EMPTY = false
const ACTION_NONE = 0
const ACTION_ENCODE_F1 = 1
const ACTION_ENCODE_F2 = 2
const ACTION_DECODE_F1 = 3
const ACTION_DECODE_F2 = 4
const ERROR_1 = 1
//==============================================================================
var cla_file_in *string
var cla_file_out *string
var cla_action_type *string
var cla_x *string
var cla_y *string
var action_type uint8
var file_input_path string
var file_output_path string
var file_input_content []byte
var file_output_content []byte
var file_input_x uint64
var file_input_y uint64
var file_input_size uint64 // Number of Bytes.
var input_field_size uint64 // Number of Bits.
var output_field_size uint64 // Number of Bits.
var file_input_cols uint64
var file_input_rows uint64
var file_output_cols uint64
var file_output_rows uint64
var field field_of_bits
var field_framed field_of_bits
//==============================================================================
func main() {
var err error
var err_code uint8
var ok bool
// Command Line Arguments.
read_cla()
// Read Input File.
file_input_content, err = ioutil.ReadFile(file_input_path)
check_error(err)
file_input_size = uint64(len(file_input_content))
input_field_size = file_input_size * bits_in_byte
// Check X & Y.
if file_input_x <= 0 {
fmt.Println("Bad X Size.")
os.Exit(ERROR_1)
}
file_input_cols = file_input_x
if (input_field_size % file_input_x) != 0 {
fmt.Println("Bad X Size.")
os.Exit(ERROR_1)
}
file_input_rows = input_field_size / file_input_x
// Do Action.
if action_type == ACTION_ENCODE_F1 {
fmt.Println("Encoding (F1) \"" + file_input_path + "\"...") //
// Output Size.
file_output_cols = file_input_cols + 4
file_output_rows = file_input_rows + 4
output_field_size = file_output_cols * file_output_rows
// Report.
fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows,
".") ///
fmt.Println("Output Data (WxH):", file_output_cols, "x",
file_output_rows, ".") ///
// Bytes -> Field.
field, ok = bytes_to_field(input_field_size, file_input_cols,
file_input_rows, file_input_content)
check_ok(ok)
// Field -> Frame.
field_framed, err_code = pack_data_f1(input_field_size,
file_input_cols, file_input_rows, field)
check_err_code(err_code)
// Frame -> Bytes.
file_output_content, ok = field_to_bytes(output_field_size,
file_output_cols, file_output_rows, field_framed)
check_ok(ok)
// Bytes -> File.
fmt.Println("Writing \"" + file_output_path + "\"...") //
err = ioutil.WriteFile(file_output_path, file_output_content, 0644)
check_error(err)
}
if action_type == ACTION_ENCODE_F2 {
fmt.Println("Encoding (F2) \"" + file_input_path + "\"...") //
// Output Size.
file_output_cols = file_input_cols + 8
file_output_rows = file_input_rows + 8
output_field_size = file_output_cols * file_output_rows
// Report.
fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows,
".") ///
fmt.Println("Output Data (WxH):", file_output_cols, "x",
file_output_rows, ".") ///
// Bytes -> Field.
field, ok = bytes_to_field(input_field_size, file_input_cols,
file_input_rows, file_input_content)
check_ok(ok)
// Field -> Frame.
field_framed, err_code = pack_data_f2(input_field_size,
file_input_cols, file_input_rows, field)
check_err_code(err_code)
// Frame -> Bytes.
file_output_content, ok = field_to_bytes(output_field_size,
file_output_cols, file_output_rows,
field_framed)
check_ok(ok)
// Bytes -> File.
fmt.Println("Writing \"" + file_output_path + "\"...") //
err = ioutil.WriteFile(file_output_path, file_output_content, 0644)
check_error(err)
}
if action_type == ACTION_DECODE_F1 {
fmt.Println("Decoding (F1) \"" + file_input_path + "\"...") //
// Output Size.
file_output_cols = file_input_cols - 4
file_output_rows = file_input_rows - 4
output_field_size = file_output_cols * file_output_rows
// Report.
fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows,
".") ///
fmt.Println("Output Data (WxH):", file_output_cols, "x",
file_output_rows, ".") ///
// Bytes -> Frame.
field_framed, ok = bytes_to_field(input_field_size, file_input_cols,
file_input_rows, file_input_content)
check_ok(ok)
// Frame -> Field.
field, ok = get_data_f1(input_field_size, file_input_cols,
file_input_rows, field_framed)
check_ok(ok)
// Field -> Bytes.
file_output_content, ok = field_to_bytes(output_field_size,
file_output_cols, file_output_rows, field)
check_ok(ok)
// Bytes -> File.
fmt.Println("Writing \"" + file_output_path + "\"...") //
err = ioutil.WriteFile(file_output_path, file_output_content, 0644)
check_error(err)
}
if action_type == ACTION_DECODE_F2 {
fmt.Println("Decoding (F2) \"" + file_input_path + "\"...") //
// Output Size.
file_output_cols = file_input_cols - 8
file_output_rows = file_input_rows - 8
output_field_size = file_output_cols * file_output_rows
// Report.
fmt.Println("Input Data (WxH):", file_input_cols, "x", file_input_rows,
".") ///
fmt.Println("Output Data (WxH):", file_output_cols, "x",
file_output_rows, ".") ///
// Bytes -> Frame.
field_framed, ok = bytes_to_field(input_field_size, file_input_cols,
file_input_rows, file_input_content)
check_ok(ok)
// Frame -> Field.
field, ok = get_data_f2(input_field_size, file_input_cols,
file_input_rows, field_framed)
check_ok(ok)
// Field -> Bytes.
file_output_content, ok = field_to_bytes(output_field_size,
file_output_cols, file_output_rows, field)
check_ok(ok)
// Bytes -> File.
fmt.Println("Writing \"" + file_output_path + "\"...") //
err = ioutil.WriteFile(file_output_path, file_output_content, 0644)
check_error(err)
}
if action_type == ACTION_NONE {
fmt.Println("Idle...") //
}
}
//==============================================================================
// Packs useful Data into Message and surrounds it with a Frame I.
func pack_data_f1(
data_bits_count uint64,
data_columns_count uint64,
data_rows_count uint64,
data field_of_bits) (field_of_bits, uint8) {
const DS = 4
const DO = DS / 2
const data_columns_count_limit = math.MaxUint64 - DS
const data_rows_count_limit = math.MaxUint64 - DS
const ERROR_ALL_CLEAR = 0 // No Error.
const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count).
const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data.
const ERROR_ROWS_ERROR = 3 // Too many Rows in Data.
var data_bits_count_required uint64
var result field_of_bits
// Cursors in Result.
var i uint64 // Current Row #.
var i_max uint64 //
var i_min uint64 //
var j uint64 // Current Column #.
var j_max uint64 //
var j_min uint64 //
// Cursors in Data.
var y uint64 // Current Row #.
var x uint64 // Current Column #.
var result_columns_count uint64
var result_rows_count uint64
var data_first_column_index uint64
var data_first_row_index uint64
//var data_last_column_index uint64
//var data_last_row_index uint64
var result_first_column_index uint64
var result_first_row_index uint64
var result_last_column_index uint64
var result_last_row_index uint64
// Check Input Data.
data_bits_count_required = data_columns_count * data_rows_count
if data_bits_count != data_bits_count_required {
return nil, ERROR_BAD_SIZE
}
if data_columns_count > data_columns_count_limit {
return nil, ERROR_COLUMNS_ERROR
}
if data_rows_count > data_rows_count_limit {
return nil, ERROR_ROWS_ERROR
}
// Indices & Sizes.
result_columns_count = data_columns_count + DS
result_rows_count = data_rows_count + DS
data_first_column_index = 0
data_first_row_index = 0
//data_last_column_index = data_columns_count - 1
//data_last_row_index = data_rows_count - 1
result_first_column_index = 0
result_first_row_index = 0
result_last_column_index = result_columns_count - 1
result_last_row_index = result_rows_count - 1
// Create an empty Field.
result = make(field_of_bits, result_rows_count)
for i = result_first_row_index; i <= result_last_row_index; i++ {
result[i] = make(row_of_bits, result_columns_count)
for j = result_first_column_index; j <= result_last_column_index; j++ {
result[i][j] = EMPTY
}
}
// Draw the Frame I.
for j = result_first_column_index; j <= result_last_column_index; j++ {
result[result_first_row_index][j] = FILLED
result[result_last_row_index][j] = FILLED
}
for i = result_first_row_index; i <= result_last_row_index; i++ {
result[i][result_first_column_index] = FILLED
result[i][result_last_column_index] = FILLED
}
// Draw Frame's Spacer.
i_min = result_first_row_index + 1
i_max = result_last_row_index - 1
j_min = result_first_column_index + 1
j_max = result_last_column_index - 1
for j = j_min; j <= j_max; j++ {
result[i_min][j] = EMPTY
result[i_max][j] = EMPTY
}
for i = i_min; i <= i_max; i++ {
result[i][j_min] = EMPTY
result[i][j_max] = EMPTY
}
// Draw Data.
i_min = result_first_row_index + DO
i_max = result_last_row_index - DO
j_min = result_first_column_index + DO
j_max = result_last_column_index - DO
y = data_first_row_index
for i = i_min; i <= i_max; i++ {
x = data_first_column_index
for j = j_min; j <= j_max; j++ {
result[i][j] = data[y][x]
x++
}
y++
}
return result, ERROR_ALL_CLEAR
}
//==============================================================================
// Packs useful Data into Message and surrounds it with a Frame II.
func pack_data_f2(
data_bits_count uint64,
data_columns_count uint64,
data_rows_count uint64,
data field_of_bits) (field_of_bits, uint8) {
const DS = 8
const DO = DS / 2
const data_columns_count_limit = math.MaxUint64 - DS
const data_rows_count_limit = math.MaxUint64 - DS
const ERROR_ALL_CLEAR = 0 // No Error.
const ERROR_BAD_SIZE = 1 // (Colums * Rows) ≠ (Bit Count).
const ERROR_COLUMNS_ERROR = 2 // Too many Columns in Data.
const ERROR_ROWS_ERROR = 3 // Too many Rows in Data.
var data_bits_count_required uint64
var result field_of_bits
// Cursors in Result.
var i uint64 // Current Row #.
var i_max uint64 //
var i_min uint64 //
var j uint64 // Current Column #.
var j_max uint64 //
var j_min uint64 //
// Cursors in Data.
var y uint64 // Current Row #.
var x uint64 // Current Column #.
var result_columns_count uint64
var result_rows_count uint64
var data_first_column_index uint64
var data_first_row_index uint64
//var data_last_column_index uint64
//var data_last_row_index uint64
var result_first_column_index uint64
var result_first_row_index uint64
var result_last_column_index uint64
var result_last_row_index uint64
// Check Input Data.
data_bits_count_required = data_columns_count * data_rows_count
if data_bits_count != data_bits_count_required {
return nil, ERROR_BAD_SIZE
}
if data_columns_count > data_columns_count_limit {
return nil, ERROR_COLUMNS_ERROR
}
if data_rows_count > data_rows_count_limit {
return nil, ERROR_ROWS_ERROR
}
// Indices & Sizes.
result_columns_count = data_columns_count + DS
result_rows_count = data_rows_count + DS
data_first_column_index = 0
data_first_row_index = 0
//data_last_column_index = data_columns_count - 1
//data_last_row_index = data_rows_count - 1
result_first_column_index = 0
result_first_row_index = 0
result_last_column_index = result_columns_count - 1
result_last_row_index = result_rows_count - 1
// Create an empty Field.
result = make(field_of_bits, result_rows_count)
for i = result_first_row_index; i <= result_last_row_index; i++ {
result[i] = make(row_of_bits, result_columns_count)
for j = result_first_column_index; j <= result_last_column_index; j++ {
result[i][j] = EMPTY
}
}
// Draw the Frame I.
for j = result_first_column_index; j <= result_last_column_index; j++ {
result[result_first_row_index][j] = FILLED
result[result_last_row_index][j] = FILLED
}
for i = result_first_row_index; i <= result_last_row_index; i++ {
result[i][result_first_column_index] = FILLED
result[i][result_last_column_index] = FILLED
}
// Draw Frame's Spacer.
i_min = result_first_row_index + 1
i_max = result_last_row_index - 1
j_min = result_first_column_index + 1
j_max = result_last_column_index - 1
for j = j_min; j <= j_max; j++ {
result[i_min][j] = EMPTY
result[i_max][j] = EMPTY
}
for i = i_min; i <= i_max; i++ {
result[i][j_min] = EMPTY
result[i][j_max] = EMPTY
}
// Draw the Frame II.
i_min = result_first_row_index + 2
i_max = result_last_row_index - 2
j_min = result_first_column_index + 2
j_max = result_last_column_index - 2
for j = j_min; j <= j_max; j++ {
result[i_min][j] = FILLED
result[i_max][j] = FILLED
}
for i = i_min; i <= i_max; i++ {
result[i][j_min] = FILLED
result[i][j_max] = FILLED
}
// Draw Frame's Spacer.
i_min = result_first_row_index + 3
i_max = result_last_row_index - 3
j_min = result_first_column_index + 3
j_max = result_last_column_index - 3
for j = j_min; j <= j_max; j++ {
result[i_min][j] = EMPTY
result[i_max][j] = EMPTY
}
for i = i_min; i <= i_max; i++ {
result[i][j_min] = EMPTY
result[i][j_max] = EMPTY
}
// Draw Data.
i_min = result_first_row_index + DO
i_max = result_last_row_index - DO
j_min = result_first_column_index + DO
j_max = result_last_column_index - DO
y = data_first_row_index
for i = i_min; i <= i_max; i++ {
x = data_first_column_index
for j = j_min; j <= j_max; j++ {
result[i][j] = data[y][x]
x++
}
y++
}
return result, ERROR_ALL_CLEAR
}
//==============================================================================
// Checks Integrity of a Frame I of the Message.
func check_frame_f1(
message_bits_count uint64,
message_columns_count uint64,
message_rows_count uint64,
message field_of_bits) bool {
const message_columns_count_limit = math.MaxUint64
const message_rows_count_limit = math.MaxUint64
const message_rows_count_min = 4 + 1 // Rows in empty Message.
const message_columns_count_min = 4 + 1 // Columns in empty Message.
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
var data_bits_count_required uint64
// Cursors in Message.
var i uint64 // Current Row #.
var i_max uint64 //
var i_min uint64 //
var j uint64 // Current Column #.
var j_max uint64 //
var j_min uint64 //
// Check Input Data.
data_bits_count_required = message_columns_count * message_rows_count
if message_bits_count != data_bits_count_required {
return ERROR
}
if message_columns_count > message_columns_count_limit {
return ERROR
}
if message_rows_count > message_rows_count_limit {
return ERROR
}
// Check Minimum Sizes.
if message_rows_count < message_rows_count_min {
return ERROR
}
if message_columns_count < message_columns_count_min {
return ERROR
}
// Check Dimensions of Array.
if uint64(len(message)) != message_rows_count {
return ERROR
}
i_min = 0
i_max = message_rows_count - 1
for i = i_min; i <= i_max; i++ {
if uint64(len(message[i])) != message_columns_count {
return ERROR
}
}
// Check Frame I.
j_min = 0
j_max = message_columns_count - 1
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != FILLED {
return ERROR
}
if message[i_max][j] != FILLED {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != FILLED {
return ERROR
}
if message[i][j_max] != FILLED {
return ERROR
}
}
// Check Frame's Spacer.
i_min = 1
i_max = message_rows_count - 2
j_min = 1
j_max = message_columns_count - 2
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != EMPTY {
return ERROR
}
if message[i_max][j] != EMPTY {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != EMPTY {
return ERROR
}
if message[i][j_max] != EMPTY {
return ERROR
}
}
return ERROR_ALL_CLEAR
}
//==============================================================================
// Checks Integrity of a Frame II of the Message.
func check_frame_f2(
message_bits_count uint64,
message_columns_count uint64,
message_rows_count uint64,
message field_of_bits) bool {
const message_columns_count_limit = math.MaxUint64
const message_rows_count_limit = math.MaxUint64
const message_rows_count_min = 8 + 1 // Rows in empty Message.
const message_columns_count_min = 8 + 1 // Columns in empty Message.
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
var data_bits_count_required uint64
// Cursors in Message.
var i uint64 // Current Row #.
var i_max uint64 //
var i_min uint64 //
var j uint64 // Current Column #.
var j_max uint64 //
var j_min uint64 //
// Check Input Data.
data_bits_count_required = message_columns_count * message_rows_count
if message_bits_count != data_bits_count_required {
return ERROR
}
if message_columns_count > message_columns_count_limit {
return ERROR
}
if message_rows_count > message_rows_count_limit {
return ERROR
}
// Check Minimum Sizes.
if message_rows_count < message_rows_count_min {
return ERROR
}
if message_columns_count < message_columns_count_min {
return ERROR
}
// Check Dimensions of Array.
if uint64(len(message)) != message_rows_count {
return ERROR
}
i_min = 0
i_max = message_rows_count - 1
for i = i_min; i <= i_max; i++ {
if uint64(len(message[i])) != message_columns_count {
return ERROR
}
}
// Check Frame I.
j_min = 0
j_max = message_columns_count - 1
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != FILLED {
return ERROR
}
if message[i_max][j] != FILLED {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != FILLED {
return ERROR
}
if message[i][j_max] != FILLED {
return ERROR
}
}
// Check Frame's Spacer.
i_min = 1
i_max = message_rows_count - 2
j_min = 1
j_max = message_columns_count - 2
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != EMPTY {
return ERROR
}
if message[i_max][j] != EMPTY {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != EMPTY {
return ERROR
}
if message[i][j_max] != EMPTY {
return ERROR
}
}
// Check Frame II.
i_min = 2
i_max = message_rows_count - 3
j_min = 2
j_max = message_columns_count - 3
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != FILLED {
return ERROR
}
if message[i_max][j] != FILLED {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != FILLED {
return ERROR
}
if message[i][j_max] != FILLED {
return ERROR
}
}
// Check Frame's Spacer.
i_min = 3
i_max = message_rows_count - 4
j_min = 3
j_max = message_columns_count - 4
for j = j_min; j <= j_max; j++ {
if message[i_min][j] != EMPTY {
return ERROR
}
if message[i_max][j] != EMPTY {
return ERROR
}
}
for i = i_min; i <= i_max; i++ {
if message[i][j_min] != EMPTY {
return ERROR
}
if message[i][j_max] != EMPTY {
return ERROR
}
}
return ERROR_ALL_CLEAR
}
//==============================================================================
// Gets Data from Message with Frame I.
func get_data_f1(
message_bits_count uint64,
message_columns_count uint64,
message_rows_count uint64,
message field_of_bits) (field_of_bits, bool) {
const DS = 4
const DO = DS / 2
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
var data field_of_bits
var data_rows_count uint64
var data_columns_count uint64
var cf bool // Result of Frame Check.
// Cursors in Message.
var i uint64 // Current Row #.
var i_min uint64 //
var j uint64 // Current Column #.
var j_min uint64 //
// Cursors in Data.
var y uint64 // Current Row #.
var x uint64 // Current Column #.
// Check Frame.
cf = check_frame_f1(message_bits_count, message_columns_count,
message_rows_count, message)
if cf == ERROR {
return nil, ERROR
}
// Prepare Data.
data_rows_count = message_rows_count - DS
data_columns_count = message_columns_count - DS
//
data = make(field_of_bits, data_rows_count)
for y = 0; y < data_rows_count; y++ {
data[y] = make(row_of_bits, data_columns_count)
for x = 0; x < data_columns_count; x++ {
data[y][x] = EMPTY
}
}
// Get Data.
i_min = DO
j_min = DO
i = i_min
for y = 0; y < data_rows_count; y++ {
j = j_min
for x = 0; x < data_columns_count; x++ {
data[y][x] = message[i][j]
j++
}
i++
}
return data, ERROR_ALL_CLEAR
}
//==============================================================================
// Gets Data from Message with Frame II.
func get_data_f2(
message_bits_count uint64,
message_columns_count uint64,
message_rows_count uint64,
message field_of_bits) (field_of_bits, bool) {
const DS = 8
const DO = DS / 2
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
var data field_of_bits
var data_rows_count uint64
var data_columns_count uint64
var cf bool // Result of Frame Check.
// Cursors in Message.
var i uint64 // Current Row #.
var i_min uint64 //
var j uint64 // Current Column #.
var j_min uint64 //
// Cursors in Data.
var y uint64 // Current Row #.
var x uint64 // Current Column #.
// Check Frame.
cf = check_frame_f2(message_bits_count, message_columns_count,
message_rows_count, message)
if cf == ERROR {
return nil, ERROR
}
// Prepare Data.
data_rows_count = message_rows_count - DS
data_columns_count = message_columns_count - DS
//
data = make(field_of_bits, data_rows_count)
for y = 0; y < data_rows_count; y++ {
data[y] = make(row_of_bits, data_columns_count)
for x = 0; x < data_columns_count; x++ {
data[y][x] = EMPTY
}
}
// Get Data.
i_min = DO
j_min = DO
i = i_min
for y = 0; y < data_rows_count; y++ {
j = j_min
for x = 0; x < data_columns_count; x++ {
data[y][x] = message[i][j]
j++
}
i++
}
return data, ERROR_ALL_CLEAR
}
//==============================================================================
// Converts Field into Array of Bytes.
func field_to_bytes(
field_bits_count uint64,
field_columns_count uint64,
field_rows_count uint64,
field field_of_bits) ([]byte, bool) {
const field_columns_count_limit = math.MaxUint64
const field_rows_count_limit = math.MaxUint64
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
const MSG_1 = "Warning ! The Size of the Output Data can not be stored " +
"using 8-Bit Bytes ! The Size is not a Multiple of 8 !"
var i uint64
var j uint64
// Cursors in Field.
var y uint64
var x uint64
var array []byte
var current_bit bit
var current_byte byte
var bytes_count uint64
var field_bits_count_required uint64
var field_column_first uint64
var field_column_last uint64
field_column_first = 0
field_column_last = field_columns_count - 1
// Check Input Data.
field_bits_count_required = field_columns_count * field_rows_count
if field_bits_count != field_bits_count_required {
log.Println("1")
return nil, ERROR
}
if field_columns_count > field_columns_count_limit {
log.Println("2")
return nil, ERROR
}
if field_rows_count > field_rows_count_limit {
log.Println("3")
return nil, ERROR
}
// Can be converted to Bytes ?
if (field_bits_count % bits_in_byte) != 0 {
fmt.Println(MSG_1)
return nil, ERROR
}
bytes_count = field_bits_count / bits_in_byte
array = make([]byte, bytes_count)
x = 0
y = 0
for i = 0; i < bytes_count; i++ {
current_byte = 0
// Read 8 Bits.
for j = 0; j < bits_in_byte; j++ {
current_bit = field[y][x]
// Save Bit in Byte.
if current_bit == FILLED {
current_byte = current_byte | (128 >> j)
}
// Next Element in Field.
if x == field_column_last {
y++
x = field_column_first
} else {
x++
}
}
// Save to Array.
array[i] = current_byte
}
return array, ERROR_ALL_CLEAR
}
//==============================================================================
// Converts Array of Bytes into Field.
func bytes_to_field(
field_bits_count uint64,
field_columns_count uint64,
field_rows_count uint64,
array []byte) (field_of_bits, bool) {
const field_columns_count_limit = math.MaxUint64
const field_rows_count_limit = math.MaxUint64
const ERROR_ALL_CLEAR = true // No Error.
const ERROR = false
var i uint64
var j uint64
// Cursors in Field.
var y uint64
var x uint64
var field field_of_bits
var current_bit bit
var current_byte byte
var current_byte_tmp byte
var bytes_count uint64
var field_bits_count_required uint64
var field_column_first uint64
var field_column_last uint64
field_column_first = 0
field_column_last = field_columns_count - 1
// Check Input Data.
field_bits_count_required = field_columns_count * field_rows_count
if field_bits_count != field_bits_count_required {
return nil, ERROR
}
if field_columns_count > field_columns_count_limit {
return nil, ERROR
}
if field_rows_count > field_rows_count_limit {
return nil, ERROR
}
// Can be converted to Bytes ?
if (field_bits_count % bits_in_byte) != 0 {
return nil, ERROR
}
bytes_count = uint64(len(array))
if bytes_count*bits_in_byte != field_bits_count {
return nil, ERROR
}
// Create an empty Field.
field = make(field_of_bits, field_rows_count)
for y = 0; y < field_rows_count; y++ {
field[y] = make(row_of_bits, field_columns_count)
for x = 0; x < field_columns_count; x++ {
field[y][x] = EMPTY
}
}
x = 0
y = 0
for i = 0; i < bytes_count; i++ {
current_byte = array[i]
// Read 8 Bits.
for j = 0; j < bits_in_byte; j++ {
current_byte_tmp = (current_byte >> (7 - j)) & 1
if current_byte_tmp == 1 {
current_bit = FILLED
} else {
current_bit = EMPTY
}
// Save Bit in Field.
field[y][x] = current_bit
// Next Element in Field.
if x == field_column_last {
y++
x = field_column_first
} else {
x++
}
}
}
return field, ERROR_ALL_CLEAR
}
//==============================================================================
// Read Command Line Arguments (Keys, Flags, Switches).
func read_cla() {
var err error
// Set Rules.
cla_file_in = flag.String("fi", "input", "File Input.")
cla_file_out = flag.String("fo", "output", "File Output.")
cla_action_type = flag.String("a", "", "Action Type.")
cla_x = flag.String("x", "0", "Columns.")
cla_y = flag.String("y", "0", "Rows.")
// Read C.L.A.
flag.Parse()
// Files.
file_input_path = *cla_file_in
file_output_path = *cla_file_out
// Action Type.
if *cla_action_type == "e1" {
action_type = ACTION_ENCODE_F1
} else if *cla_action_type == "e2" {
action_type = ACTION_ENCODE_F2
} else if *cla_action_type == "d1" {
action_type = ACTION_DECODE_F1
} else if *cla_action_type == "d2" {
action_type = ACTION_DECODE_F2
} else {
action_type = ACTION_NONE
}
// X, Y.
file_input_x, err = strconv.ParseUint(*cla_x, 10, 64)
check_error(err)
file_input_y, err = strconv.ParseUint(*cla_y, 10, 64)
check_error(err)
}
//==============================================================================
func check_error(err error) {
if err != nil {
log.Println(err)
os.Exit(ERROR_1)
}
}
//==============================================================================
func check_ok(ok bool) {
if !ok {
log.Println("Error.")
os.Exit(ERROR_1)
} else {
//fmt.Println("OK.")
}
}
//==============================================================================
func check_err_code(err_code uint8) {
if err_code == 0 {
//fmt.Println("OK.")
} else {
log.Println("Error.")
os.Exit(ERROR_1)
}
}
//==============================================================================
| Java |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 13:37:16 2017
Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn
Function:
旋转使得变换。
"""
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
plt.close('all')
emitX=12
alphaX=-10.
betaX=13.
gammaX=(1.+alphaX**2)/betaX
sigmaX=np.array([[betaX,-alphaX],[-alphaX,gammaX]])*emitX;
numPart=np.int32(1e5);
X=np.random.multivariate_normal([0.,0.],sigmaX,numPart).T
plt.figure(1)
plt.plot(X[0,:],X[1,:],'.')
##
w=tf.Variable(tf.random_normal([1,1]))
w1=tf.cos(w)
w2=tf.sin(w)
P_Row_1=tf.concat([w1,-w2],0)
P_Row_2=tf.concat([w2,w1],0)
P=tf.concat([P_Row_1,P_Row_2],1)
xI=tf.placeholder(tf.float32,[2,None])
xO=tf.matmul(P,xI)
xxp=tf.reduce_mean(xO[0]*xO[1])
lossAlpha=xxp**2
rateLearn=1e-4
optTotal=tf.train.AdamOptimizer(rateLearn)
trainAlpha=optTotal.minimize(lossAlpha)
sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True))
sess.run(tf.global_variables_initializer())
sizeBatch=64
for _ in xrange(8000):
startBatch=np.random.randint(0,high=numPart-sizeBatch-1)
xFeed=X[:,startBatch:startBatch+sizeBatch:]
sess.run(trainAlpha,feed_dict={xI:xFeed})
#print(sess.run(LambdaR))
#print('---------------------------')
print(sess.run(lossAlpha,feed_dict={xI:X}),_)
print('_______________________________________________')
zReal=sess.run(xO,feed_dict={xI:X})
plt.figure(2)
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
plt.figure(10)
plt.hold
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.plot(X[0,:],X[1,:],'b.')
#plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
plt.figure(11)
plt.hold
#plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.plot(X[0,:],X[1,:],'b.')
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
zRealCov=np.cov(zReal)
emitXReal=np.sqrt(np.linalg.det(zRealCov))
print(emitXReal)
| Java |
<?php
theme()->render("2column-right", [
["Header", "top"],
["Post", "content"],
["Comments", "content"],
["SidebarRight", "right"],
["Footer", "bottom"]
]); | Java |
/* This file is part of Arkhados.
Arkhados 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.
Arkhados 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 Arkhados. If not, see <http://www.gnu.org/licenses/>. */
package arkhados.spell.buffs.info;
import arkhados.controls.CRotation;
import arkhados.controls.CTrackLocation;
import arkhados.effects.BuffEffect;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
public class MineralArmorInfo extends BuffInfo {
{
setIconPath("Interface/Images/SpellIcons/MineralArmor.png");
}
@Override
public BuffEffect createBuffEffect(BuffInfoParameters params) {
MineralArmorEffect effect = new MineralArmorEffect(params.duration);
effect.addToCharacter(params);
return effect;
}
}
class MineralArmorEffect extends BuffEffect {
private Node centralNode = null;
public MineralArmorEffect(float timeLeft) {
super(timeLeft);
}
public void addToCharacter(BuffInfoParameters params) {
Node character = (Node) params.buffControl.getSpatial();
Spatial crystals1 = assets.loadModel("Models/crystals.j3o");
Spatial crystals2 = assets.loadModel("Models/crystals.j3o");
Spatial crystals3 = assets.loadModel("Models/crystals.j3o");
Spatial crystals4 = assets.loadModel("Models/crystals.j3o");
centralNode = new Node("mineral-armor-node");
centralNode.attachChild(crystals1);
centralNode.attachChild(crystals2);
centralNode.attachChild(crystals3);
centralNode.attachChild(crystals4);
crystals1.setLocalTranslation(-7.5f, 0f, 0f);
crystals2.setLocalTranslation(7.5f, 0f, 0f);
crystals3.setLocalTranslation(0f, 0f, -7.5f);
crystals4.setLocalTranslation(0f, 0f, 7.5f);
Node world = character.getParent();
world.attachChild(centralNode);
centralNode.addControl(
new CTrackLocation(character, new Vector3f(0f, 10f, 0f)));
centralNode.addControl(new CRotation(0f, 2f, 0f));
}
@Override
public void destroy() {
super.destroy();
centralNode.removeFromParent();
}
}
| Java |
jQuery(document).ready(function(){
if( $('.cd-stretchy-nav').length > 0 ) {
var stretchyNavs = $('.cd-stretchy-nav');
stretchyNavs.each(function(){
var stretchyNav = $(this),
stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger');
stretchyNavTrigger.on('click', function(event){
event.preventDefault();
stretchyNav.toggleClass('nav-is-visible');
});
});
$(document).on('click', function(event){
( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible');
});
};
///toggle en contenido
$(".toggle-view li").on('click', function(e){
e.currentTarget.classList.toggle("active");
});
}); | Java |
use strict;
use warnings;
package RPG::ResultSet::Election;
use base 'DBIx::Class::ResultSet';
use Carp;
sub schedule {
my $self = shift;
my $town = shift || croak "Town not supplied";
my $days = shift || croak "Number of days not supplied";
croak "Already have an election scheduled\n" if $town->current_election;
my $mayor = $town->mayor;
croak "No mayor in this town" unless $mayor;
croak "Invalid day\n" if $days < 3;
my $schema = $self->result_source->schema;
my $today = $schema->resultset('Day')->find_today;
my $day = $today->day_number + $days;
my $election = $self->create(
{
town_id => $town->id,
scheduled_day => $day,
status => 'Open',
}
);
$schema->resultset('Election_Candidate')->create(
{
character_id => $mayor->id,
election_id => $election->id,
},
);
$schema->resultset('Town_History')->create(
{
town_id => $town->id,
day_id => $today->id,
message => $mayor->name . " has called an election for day $day. " . ucfirst $mayor->pronoun('subjective')
. " invites prospective candidates to register to run.",
}
);
$schema->resultset('Global_News')->create(
{
day_id => $today->id,
message => "The town of " . $town->town_name . " has scheduled an election for day $day.",
},
);
return $election;
}
1;
| Java |

#FEWD - Review, Process, and Debugging
###Lesson 11 - Mar 14, 2016
"What was the hardest part of learning to code?
It’s learning to not let errors and complicated functions get you down. Everyone makes mistakes and it’s the process of debugging them that teaches you how to be a better coder." - <a href="http://imagirlwhocodes.com/post/140868820390/amanda-xu-a-swerve-in-another-direction">Amanda Xu</a>
---
##Agenda
* Surveys, please!
* Exit Ticket Review
* Debugging
* Assignment 5 review: from pseudocode to implementation
---
##Exit Tickets
* What is a good way to memorize the most used functions in Jquery/javascript?
Answer: Once you encounter a jQuery function, you'll find that many of them are named pretty transparently after what they do (`.html` and `.css` for example). But as you're starting out, you may still need to look up the documentation or StackOverflow to jog your memory -- that's ok!
* How in the hell do I get good at this?
Answer: Persistence, practice, and patience with yourself!
---
## Resources for practicing
* <a href="http://tympanus.net/codrops/">Codrops tutorials and playground</a>
* <a href="https://www.smashingmagazine.com/2008/09/jquery-examples-and-best-practices/">Continue to learn about best practices</a>
* <a href="https://www.codecademy.com/learn/jquery">Code Academy jQuery course</a>
* <a href="http://jqexercise.droppages.com/">jQuery drills</a> - these range in difficulty and don't offer much to help you learn, but it's great for practicing!
---
##Debugging
<img src="http://www.wired.com/images_blogs/wiredscience/2013/12/moth-660x548.jpg" style="height: 80%">
The very first "bug", <a href="http://www.wired.com/2013/12/googles-doodle-honors-grace-hopper-and-entomology/">discovered by Grace Hopper</a>.
---
##Debugging tips
* The console is your friend:
* The first thing you should always do if your code starts doing things contrary to your expectations is open up your console. A lot of times console will just tell you what went wrong!
* Use `console.log` whenever you need to check if something is working: write out variable values to check that they are updating correctly, log out messages to verify your event handlers are firing correctly, etc. [You can even log out jQuery elements!]
* When a part of your code doesn't work, take a step back and ask yourself these questions:
* What did I expect to happen?
* What happened instead?
* Where in the place in my code where this functionality is being implemented?
* Instead of attempting to throw more code at an already buggy codebase, simplify.
---
##Debug-a-long
* Fixing errors with the <a href="starter/debugging-relaxr">Relaxr blog exercise</a>.
* Fixing errors with the <a href="starter/debugging-compare-that">Compare That exercise</a>.
---
## Assignment 5 : pseudocode to implementation
Pseudocoding the CitiPix app:
* Need to set up a click listener + handler for the submit button.
* When the submit button is clicked, need to get the input value.
* Verify (using `console.log`) that you are getting the value before you continue to the next parts.
* Once you have the input value, our program needs to **DECIDE** if we should add a class to the body based on what was typed. *Because each of these should work approximately the same way, if we figure out one case, we can carry over the technique to the other cases.*
* If the user typed "New York" or "New York City" or "NYC", we should see the nyc.jpg background
* If the user typed "San Francisco" or "SF" or "Bay Area", we should see the sf background
* If the user typed "Los Angeles" or "LA" or "LAX", we should see the la.jpg background
* If the user typed "Austin" or "ATX", we should see the austin.jpg background
* If the user typed "Sydney" or "SYD", we should see the sydney.jpg background
---
## More Practice: Number Guesser
We will build a number guesser game where the computer generates a random number from 1-10, and the user enters numbers into the input field until the number they enter is a match. When the user's guess is incorrect, the program will tell user if they need to guess higher or lower.
<a href="http://codepen.io/emmacunningham/pen/pyNJJy?editors=1010">Starter code</a>
* Write pseudocode for the logic flow of your program
* Convert the pseudocode to real JavaScript code, working on things piece-by-piece
---
##Homework
* Work on the HTML + CSS for your Final Project
* Surveys if you haven't yet filled yours out
---
##Exit Tickets - Lesson #11, Topic: Review & Debugging
###Please fill out the <a href="https://docs.google.com/forms/d/1Iw2zghHfGgeM1p1G16F6kLi7KViv28tG3HVNnoM3PAc/viewform">exit ticket</a> before you leave
| Java |
#include "precomp.h"
#include "stdinc.h"
#include "io_sfen.h"
#include "commandpacket.h"
namespace godwhale {
const CommandPacket::CharSeparator CommandPacket::ms_separator(" ", "");
CommandPacket::CommandPacket(CommandType type)
: m_type(type), m_positionId(-1), m_position(false)
{
}
CommandPacket::CommandPacket(CommandPacket const & other)
: m_positionId(-1), m_position(false)
{
}
CommandPacket::CommandPacket(CommandPacket && other)
: m_positionId(-1), m_position(false)
{
}
/**
* @brief R}hÌÀsDæÊðæ¾µÜ·B
*
* lªå«¢ûªADæÊ͢ŷB
*/
int CommandPacket::getPriority() const
{
switch (m_type) {
// I¹nÌR}hÍ·®ÉÀs
case COMMAND_QUIT:
case COMMAND_STOP:
return 100;
// ÊíÌR}hÍ»ÌÜÜÌÅ
case COMMAND_LOGIN:
case COMMAND_SETPOSITION:
case COMMAND_MAKEROOTMOVE:
case COMMAND_SETPV:
case COMMAND_SETMOVELIST:
case COMMAND_VERIFY:
return 50;
// G[ݽ¢ÈàÌ
case COMMAND_NONE:
return 0;
}
unreachable();
return -1;
}
/**
* @brief strªtargetª¦·g[NŠ驲×Ü·B
*/
bool CommandPacket::isToken(std::string const & str, std::string const & target)
{
return (str.compare(target) == 0);
}
/**
* @brief RSI(remote shogi interface)ðp[XµAR}hɼµÜ·B
*/
shared_ptr<CommandPacket> CommandPacket::parse(std::string const & rsi)
{
if (rsi.empty()) {
throw new std::invalid_argument("rsi");
}
Tokenizer tokens(rsi, ms_separator);
std::string token = *tokens.begin();
if (isToken(token, "login")) {
return parse_Login(rsi, tokens);
}
else if (isToken(token, "setposition")) {
return parse_SetPosition(rsi, tokens);
}
else if (isToken(token, "makerootmove")) {
return parse_MakeRootMove(rsi, tokens);
}
else if (isToken(token, "setmovelist")) {
return parse_SetMoveList(rsi, tokens);
}
else if (isToken(token, "stop")) {
return parse_Stop(rsi, tokens);
}
else if (isToken(token, "quit")) {
return parse_Quit(rsi, tokens);
}
return shared_ptr<CommandPacket>();
}
/**
* @brief R}hðRSI(remote shogi interface)ÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI() const
{
assert(m_type != COMMAND_NONE);
switch (m_type) {
case COMMAND_LOGIN:
return toRSI_Login();
case COMMAND_SETPOSITION:
return toRSI_SetPosition();
case COMMAND_MAKEROOTMOVE:
return toRSI_MakeRootMove();
case COMMAND_SETMOVELIST:
return toRSI_SetMoveList();
case COMMAND_STOP:
return toRSI_Stop();
case COMMAND_QUIT:
return toRSI_Quit();
}
unreachable();
return std::string();
}
#pragma region Login
/**
* @brief loginR}hðp[XµÜ·B
*
* login <address> <port> <login_id> <nthreads>
*/
shared_ptr<CommandPacket> CommandPacket::parse_Login(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_LOGIN));
Tokenizer::iterator begin = ++tokens.begin();
result->m_serverAddress = *begin++;
result->m_serverPort = *begin++;
result->m_loginId = *begin++;
return result;
}
/**
* @brief loginR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_Login() const
{
return (F("login %1% %2% %3%")
% m_serverAddress % m_serverPort % m_loginId)
.str();
}
#pragma endregion
#pragma region SetPosition
/**
* @brief setpositionR}hðp[XµÜ·B
*
* setposition <position_id> [sfen <sfen> | startpos] moves <move1> ... <moven>
* <sfen> = <board_sfen> <turn_sfen> <hand_sfen> <nmoves>
*/
shared_ptr<CommandPacket> CommandPacket::parse_SetPosition(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETPOSITION));
Tokenizer::iterator begin = ++tokens.begin();
result->m_positionId = lexical_cast<int>(*begin++);
std::string token = *begin++;
if (token == "sfen") {
std::string sfen;
sfen += *begin++ + " "; // board
sfen += *begin++ + " "; // turn
sfen += *begin++ + " "; // hand
sfen += *begin++; // nmoves
result->m_position = sfenToPosition(sfen);
}
else if (token == "startpos") {
result->m_position = Position();
}
// movesÍÈ¢±Æª èÜ·B
if (begin == tokens.end()) {
return result;
}
if (*begin++ != "moves") {
throw new ParseException(F("%1%: wµèª³µ èܹñB") % rsi);
}
for (; begin != tokens.end(); ++begin) {
Move move = sfenToMove(result->m_position, *begin);
if (!result->m_position.makeMove(move)) {
LOG_ERROR() << result->m_position;
LOG_ERROR() << *begin << ": wµèª³µ èܹñB";
throw new ParseException(F("%1%: wµèª³µ èܹñB") % *begin);
}
}
return result;
}
/**
* @brief setpositionR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_SetPosition() const
{
Position position = m_position;
std::vector<Move> moves = position.getMoveList();
// ÇÊð·×ÄߵܷB
while (!position.getMoveList().empty()) {
position.unmakeMove();
}
std::string posStr;
if (position.isInitial()) {
posStr = " startpos";
}
else {
posStr = " sfen ";
posStr += positionToSfen(position);
}
std::string movesStr;
if (!moves.empty()) {
movesStr += " moves";
BOOST_FOREACH(Move move, moves) {
movesStr += " ";
movesStr += moveToSfen(move);
}
}
return (F("setposition %1%%2%%3%")
% m_positionId % posStr % movesStr)
.str();
}
#pragma endregion
#pragma region MakeRootMove
/**
* @brief makerootmoveR}hðp[XµÜ·B
*
* makerootmove <position_id> <old_position_id> <move>
*/
shared_ptr<CommandPacket> CommandPacket::parse_MakeRootMove(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_MAKEROOTMOVE));
Tokenizer::iterator begin = ++tokens.begin(); // ÅÌg[NÍòεܷB
result->m_positionId = lexical_cast<int>(*begin++);
result->m_oldPositionId = lexical_cast<int>(*begin++);
// ^¦çê½positionIdÈÇ©çÇÊðõµÜ·B
Position position;
result->m_move = sfenToMove(position, *begin++);
return result;
}
/**
* @brief makerootmoveR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_MakeRootMove() const
{
return (F("makerootmove %1% %2% %3%")
% m_positionId % m_oldPositionId % moveToSfen(m_move))
.str();
}
#pragma endregion
#pragma region SetMoveList
/**
* @brief setmovelistR}hðp[XµÜ·B
*
* setmovelist <position_id> <itd> <pld> <move1> ... <moven>
*/
shared_ptr<CommandPacket> CommandPacket::parse_SetMoveList(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETMOVELIST));
Tokenizer::iterator begin = ++tokens.begin(); // ÅÌg[NÍòεܷB
result->m_positionId = lexical_cast<int>(*begin++);
result->m_iterationDepth = lexical_cast<int>(*begin++);
result->m_plyDepth = lexical_cast<int>(*begin++);
// ^¦çê½positionIdÈÇ©çÇÊðõµÜ·B
Position position;
Tokenizer::iterator end = tokens.end();
for (; begin != end; ++begin) {
Move move = sfenToMove(position, *begin);
if (move.isEmpty()) {
throw ParseException(F("%1%: ³µ¢wµèÅÍ èܹñB") % *begin);
}
result->m_moveList.push_back(move);
}
return result;
}
/**
* @brief setmovelistR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_SetMoveList() const
{
std::string movesStr;
BOOST_FOREACH(Move move, m_moveList) {
movesStr += " ";
movesStr += moveToSfen(move);
}
return (F("setmovelist %1% %2% %3% %4%")
% m_positionId %m_iterationDepth % m_plyDepth % movesStr)
.str();
}
#pragma endregion
#pragma region Stop
/**
* @brief stopR}hðp[XµÜ·B
*/
shared_ptr<CommandPacket> CommandPacket::parse_Stop(std::string const & rsi,
Tokenizer & tokens)
{
return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_STOP));
}
/**
* @brief stopR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_Stop() const
{
return "stop";
}
#pragma endregion
#pragma region Quit
/**
* @brief quitR}hðp[XµÜ·B
*/
shared_ptr<CommandPacket> CommandPacket::parse_Quit(std::string const & rsi,
Tokenizer & tokens)
{
return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_QUIT));
}
/**
* @brief quitR}hðRSIÉÏ·µÜ·B
*/
std::string CommandPacket::toRSI_Quit() const
{
return "quit";
}
#pragma endregion
} // namespace godwhale
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSP;
namespace panelfar
{
public static class PANELFARMeshSimplification
{
//Take the raw part geometry and simplify it so that further simplification of the entire vessel is faster
public static PANELFARPartLocalMesh PreProcessLocalMesh(PANELFARPartLocalMesh mesh)
{
//Array of vertices; indexing must not change
Vector3[] verts = new Vector3[mesh.vertexes.Length];
mesh.vertexes.CopyTo(verts, 0);
//Array of triangles; each triangle points to an index in verts
MeshIndexTriangle[] indexTris = new MeshIndexTriangle[mesh.triangles.Length];
mesh.triangles.CopyTo(indexTris, 0);
//Array of a list of triangles that contain a given vertex; indexing is same as verts, each index in list points to an index in indexTris
List<int>[] trisAttachedToVerts = GetTrisAttachedToVerts(verts, indexTris);
//Array of quadrics associated with a particular vertex; indexing is same as verts
Quadric[] vertQuadrics = CalculateVertQuadrics(verts, indexTris);
//A list of possible vertex pairs that can be contracted into a single point
MinHeap<MeshPairContraction> pairContractions = GeneratePairContractions(indexTris, verts, vertQuadrics);
int faces = (int)Math.Floor(indexTris.Length * 0.5);
faces = DecimateVertices(faces, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
//This will be used to update the old array (which has many empty elements) to a new vertex array and allow the indexTris to be updated as well
Dictionary<int, int> beforeIndexAfterIndex = new Dictionary<int, int>();
int currentIndex = 0;
List<Vector3> newVerts = new List<Vector3>();
for (int i = 0; i < verts.Length; i++)
{
Vector3 v = verts[i];
if (trisAttachedToVerts[i] != null)
{
beforeIndexAfterIndex.Add(i, currentIndex);
currentIndex++;
newVerts.Add(v);
}
}
MeshIndexTriangle[] newIndexTris = new MeshIndexTriangle[faces];
currentIndex = 0;
foreach(MeshIndexTriangle tri in indexTris)
{
if(tri != null)
{
MeshIndexTriangle newTri = new MeshIndexTriangle(beforeIndexAfterIndex[tri.v0], beforeIndexAfterIndex[tri.v1], beforeIndexAfterIndex[tri.v2]);
newIndexTris[currentIndex] = newTri;
currentIndex++;
}
}
mesh.vertexes = newVerts.ToArray();
mesh.triangles = newIndexTris;
return mesh;
}
public static int DecimateVertices(int targetFaces, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int validFaces = indexTris.Length;
int counter = 1;
StringBuilder debug = new StringBuilder();
debug.AppendLine("Target Faces: " + targetFaces);
try
{
while (validFaces > targetFaces)
{
debug.AppendLine("Iteration: " + counter + " Faces: " + validFaces);
//Get the pair contraction with the least error associated with it
MeshPairContraction pair = pairContractions.ExtractDominating();
debug.AppendLine("Contraction between vertices at indicies: " + pair.v0 + " and " + pair.v1);
debug.AppendLine("Tris attached to v0: " + trisAttachedToVerts[pair.v0].Count + " Tris attached to v1: " + trisAttachedToVerts[pair.v1].Count);
//Get faces that will be deleted / changed by contraction
ComputeContraction(ref pair, indexTris, trisAttachedToVerts);
//Act on faces, delete extra vertex, change all references to second vertex
validFaces -= ApplyContraction(ref pair, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
counter++;
}
for(int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
if (tri == null)
continue;
if (trisAttachedToVerts[tri.v0] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v0);
}
if (trisAttachedToVerts[tri.v1] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v1);
}
if (trisAttachedToVerts[tri.v2] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v2);
}
}
debug.AppendLine("Final: Faces: " + validFaces);
}
catch (Exception e)
{
debug.AppendLine("Error: " + e.Message);
debug.AppendLine("Stack trace");
debug.AppendLine(e.StackTrace);
}
Debug.Log(debug.ToString());
return validFaces;
}
public static int ApplyContraction(ref MeshPairContraction pair, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int removedFaces = pair.deletedFaces.Count;
//Move v0, clear v1
verts[pair.v0] = pair.contractedPosition;
verts[pair.v1] = Vector3.zero;
foreach (int triIndex in trisAttachedToVerts[pair.v1])
if (!pair.deletedFaces.Contains(triIndex) && !trisAttachedToVerts[pair.v0].Contains(triIndex))
trisAttachedToVerts[pair.v0].Add(triIndex);
//Clear out all the tris attached to a non-existent vertex
trisAttachedToVerts[pair.v1] = null;
//Accumulate quadrics, clear unused one
vertQuadrics[pair.v0] += vertQuadrics[pair.v1];
vertQuadrics[pair.v1] = new Quadric();
//Adjust deformed triangles
foreach (int changedTri in pair.deformedFaces)
{
MeshIndexTriangle tri = indexTris[changedTri];
if (tri.v0.Equals(pair.v1))
tri.v0 = pair.v0;
else if (tri.v1.Equals(pair.v1))
tri.v1 = pair.v0;
else
tri.v2 = pair.v0;
indexTris[changedTri] = tri;
}
//Clear deleted triangles
foreach(int deletedTri in pair.deletedFaces)
{
indexTris[deletedTri] = null;
}
List<MeshPairContraction> pairList = pairContractions.ToList();
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction otherPair = pairList[i];
if (otherPair.v0.Equals(pair.v1))
{
otherPair.v0 = pair.v0;
}
else if (otherPair.v1.Equals(pair.v1))
{
otherPair.v1 = pair.v0;
}
pairList[i] = otherPair;
}
int count = pairList.Count;
for (int i = 0; i < count; i++ )
{
MeshPairContraction iItem = pairList[i];
for(int j = i + 1; j < count; j++)
{
if (pairList[j].Equals(iItem))
{
pairList.RemoveAt(j); //Remove duplicate element
count--; //Reduce length to iterate over
j--; //Make sure not to skip over a duplicate
}
}
if(iItem.v1 == iItem.v0)
{
pairList.RemoveAt(i); //Remove degenerate edge
count--; //Reduce length to iterate over
i--; //Make sure not to skip over a duplicate
continue;
}
CalculateTargetPositionForPairContraction(ref iItem, verts, vertQuadrics);
pairList[i] = iItem;
}
pairContractions = new MinHeap<MeshPairContraction>(pairList);
return removedFaces;
}
public static void ComputeContraction(ref MeshPairContraction pair, MeshIndexTriangle[] indexTris, List<int>[] trisAttachedToVerts)
{
//This contains a list of all tris that will be changed by this contraction; boolean indicates whether they will be removed or not
Dictionary<int, bool> trisToChange = new Dictionary<int, bool>();
pair.deformedFaces.Clear();
pair.deletedFaces.Clear();
//Iterate through every triangle attached to vertex 0 of this pair and add them to the dict
foreach(int triIndex in trisAttachedToVerts[pair.v0])
{
if(indexTris[triIndex] != null)
trisToChange.Add(triIndex, false);
}
//Iterate through tris attached to vert 1...
foreach (int triIndex in trisAttachedToVerts[pair.v1])
{
if (indexTris[triIndex] == null)
continue;
//if the tri is already there, it will become degenerate during this contraction and should be removed
if (trisToChange.ContainsKey(triIndex))
trisToChange[triIndex] = true;
//else, add it and it will simply be deformed
else
trisToChange.Add(triIndex, false);
}
//Now, divide them into the appropriate lists
foreach(KeyValuePair<int, bool> triIndex in trisToChange)
{
if (triIndex.Value)
pair.deletedFaces.Add(triIndex.Key);
else
pair.deformedFaces.Add(triIndex.Key);
}
}
public static MinHeap<MeshPairContraction> GeneratePairContractions(MeshIndexTriangle[] indexTris, Vector3[] verts, Quadric[] vertQuadrics)
{
List<MeshPairContraction> pairContractions = new List<MeshPairContraction>();
foreach(MeshIndexTriangle tri in indexTris)
{
MeshPairContraction e0 = new MeshPairContraction(tri.v0, tri.v1),
e1 = new MeshPairContraction(tri.v1, tri.v2),
e2 = new MeshPairContraction(tri.v2, tri.v0);
if (!pairContractions.Contains(e0))
pairContractions.Add(e0);
if (!pairContractions.Contains(e1))
pairContractions.Add(e1);
if (!pairContractions.Contains(e2))
pairContractions.Add(e2);
}
//Calculate point that each pair contraction will contract to if it is to be done
CalculateTargetPositionForAllPairContractions(ref pairContractions, verts, vertQuadrics);
MinHeap<MeshPairContraction> heap = new MinHeap<MeshPairContraction>(pairContractions);
return heap;
}
public static void CalculateTargetPositionForAllPairContractions(ref List<MeshPairContraction> pairContractions, Vector3[] verts, Quadric[] vertQuadrics)
{
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction pair = pairContractions[i];
CalculateTargetPositionForPairContraction(ref pair, verts, vertQuadrics);
pairContractions[i] = pair;
}
}
public static void CalculateTargetPositionForPairContraction(ref MeshPairContraction pair, Vector3[] verts, Quadric[] vertQuadrics)
{
Vector3 v0 = verts[pair.v0], v1 = verts[pair.v1];
Quadric Q0 = vertQuadrics[pair.v0], Q1 = vertQuadrics[pair.v1];
Quadric Q = Q0 + Q1;
if (Q.Optimize(ref pair.contractedPosition, 1e-12))
pair.error = Q.Evaluate(pair.contractedPosition);
else
{
double ei = Q.Evaluate(v0), ej = Q.Evaluate(v1);
if (ei < ej)
{
pair.error = ei;
pair.contractedPosition = v0;
}
else
{
pair.error = ej;
pair.contractedPosition = v1;
}
}
}
//This returns an array that contains (in each element) a list of indexes that specify which MeshIndexTriangles (in indexTris) are connected to which Vector3s (in verts)
public static List<int>[] GetTrisAttachedToVerts(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
List<int>[] trisAttachedToVerts = new List<int>[verts.Length];
for (int i = 0; i < trisAttachedToVerts.Length; i++)
{
trisAttachedToVerts[i] = new List<int>();
}
for (int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
trisAttachedToVerts[tri.v0].Add(i);
trisAttachedToVerts[tri.v1].Add(i);
trisAttachedToVerts[tri.v2].Add(i);
}
return trisAttachedToVerts;
}
//Returns an array of quadrics for evaluating the error of each possible contraction
public static Quadric[] CalculateVertQuadrics(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
Quadric[] vertQuadrics = new Quadric[verts.Length];
for (int i = 0; i < vertQuadrics.Length; i++ )
vertQuadrics[i] = new Quadric();
foreach (MeshIndexTriangle tri in indexTris)
{
Vector3 v0, v1, v2;
v0 = verts[tri.v0];
v1 = verts[tri.v1];
v2 = verts[tri.v2];
double area = PANELFARTriangleUtils.triangle_area(v0, v1, v2);
Vector4 p;
if (area > 0)
p = PANELFARTriangleUtils.triangle_plane(v0, v1, v2);
else
{
p = PANELFARTriangleUtils.triangle_plane(v2, v1, v0);
area = -area;
}
Quadric Q = new Quadric(p.x, p.y, p.z, p.w, area);
// Area-weight quadric and add it into the three quadrics for the corners
Q *= Q.area;
vertQuadrics[tri.v0] += Q;
vertQuadrics[tri.v1] += Q;
vertQuadrics[tri.v2] += Q;
}
return vertQuadrics;
}
}
}
| Java |
# CMake generated Testfile for
# Source directory: /home/aviral/GNU-Niyantran/gr36/gr-blocks/include/blocks
# Build directory: /home/aviral/GNU-Niyantran/build/gr36/gr-blocks/include/blocks
#
# This file includes the relevent testing commands required for
# testing this directory and lists subdirectories to be tested as well.
| Java |
import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close() | Java |
#include <iostream>
#include <string>
class Shape {
public :
virtual void draw (void) = 0;
static Shape *Create (std::string type);
};
class circle : public Shape {
public :
void draw(void){
std::cout << "circle" << std::endl;
}
};
class square : public Shape {
public :
void draw(void){
std::cout << "square" << std::endl;
}
};
Shape * Shape::Create (std::string type){
if(type == "circle"){
std::cout << "creating circle" << std::endl;
return new circle();
}
if(type == "square") {
std::cout << "creating circle" << std::endl;
return new square();
}
return NULL;
};
int main (){
Shape *cir = Shape::Create("circle");
if ( cir != NULL ) cir->draw();
return 0;
}
| Java |
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
atomic_int atom_1_r13_0;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 1, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst);
int v7_r6 = v6_r4 ^ v6_r4;
int v8_r6 = v7_r6 + 1;
atomic_store_explicit(&vars[3], v8_r6, memory_order_seq_cst);
int v10_r8 = atomic_load_explicit(&vars[3], memory_order_seq_cst);
int v11_cmpeq = (v10_r8 == v10_r8);
if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
atomic_store_explicit(&vars[4], 1, memory_order_seq_cst);
int v13_r11 = atomic_load_explicit(&vars[4], memory_order_seq_cst);
int v14_r12 = v13_r11 ^ v13_r11;
int v17_r13 = atomic_load_explicit(&vars[0+v14_r12], memory_order_seq_cst);
int v21 = (v2_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v21, memory_order_seq_cst);
int v22 = (v17_r13 == 0);
atomic_store_explicit(&atom_1_r13_0, v22, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[4], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_1_r1_1, 0);
atomic_init(&atom_1_r13_0, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v18 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v19 = atomic_load_explicit(&atom_1_r13_0, memory_order_seq_cst);
int v20_conj = v18 & v19;
if (v20_conj == 1) assert(0);
return 0;
}
| Java |
{% extends "allauth/account/base.html" %}
{% load i18n %}
{% block head_title %}{% trans "Set Password" %}{% endblock %}
{% block content %}
<h1>{% trans "Set Password" %}</h1>
<form method="POST" action="{% url 'account_set_password' %}" class="password_set">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="action" value="{% trans 'Set Password' %}"/>
</form>
{% endblock %}
| Java |
#include "CAN.h"
#include "led.h"
#include "delay.h"
#include "usart.h"
//////////////////////////////////////////////////////////////////////////////////
//±¾³ÌÐòÖ»¹©Ñ§Ï°Ê¹Óã¬Î´¾×÷ÕßÐí¿É£¬²»µÃÓÃÓÚÆäËüÈκÎÓÃ;
//ALIENTEKÕ½½¢STM32¿ª·¢°å
//CANÇý¶¯ ´úÂë
//ÕýµãÔ×Ó@ALIENTEK
//¼¼ÊõÂÛ̳:www.openedv.com
//ÐÞ¸ÄÈÕÆÚ:2012/9/11
//°æ±¾£ºV1.0
//°æÈ¨ËùÓУ¬µÁ°æ±Ø¾¿¡£
//Copyright(C) ¹ãÖÝÊÐÐÇÒíµç×ӿƼ¼ÓÐÏÞ¹«Ë¾ 2009-2019
//All rights reserved
//////////////////////////////////////////////////////////////////////////////////
//CAN³õʼ»¯
//tsjw:ÖØÐÂͬ²½ÌøÔ¾Ê±¼äµ¥Ôª.·¶Î§:1~3; CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq
//tbs2:ʱ¼ä¶Î2µÄʱ¼äµ¥Ôª.·¶Î§:1~8;
//tbs1:ʱ¼ä¶Î1µÄʱ¼äµ¥Ôª.·¶Î§:1~16; CAN_BS1_1tq ~CAN_BS1_16tq
//brp :²¨ÌØÂÊ·ÖÆµÆ÷.·¶Î§:1~1024;(ʵ¼ÊÒª¼Ó1,Ò²¾ÍÊÇ1~1024) tq=(brp)*tpclk1
//×¢ÒâÒÔÉϲÎÊýÈκÎÒ»¸ö¶¼²»ÄÜÉèΪ0,·ñÔò»áÂÒ.
//²¨ÌØÂÊ=Fpclk1/((tsjw+tbs1+tbs2)*brp);
//mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½;
//Fpclk1µÄʱÖÓÔÚ³õʼ»¯µÄʱºòÉèÖÃΪ36M,Èç¹ûÉèÖÃCAN_Normal_Init(1,8,7,5,1);
//Ôò²¨ÌØÂÊΪ:36M/((1+8+7)*5)=450Kbps
//·µ»ØÖµ:0,³õʼ»¯OK;
// ÆäËû,³õʼ»¯Ê§°Ü;
u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
#if CAN_RX0_INT_ENABLE
NVIC_InitTypeDef NVIC_InitStructure;
#endif
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹÄÜPORTAʱÖÓ
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN2, ENABLE);//ʹÄÜCAN2ʱÖÓ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //¸´ÓÃÍÆÍì
GPIO_Init(GPIOB, &GPIO_InitStructure); //³õʼ»¯IO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÉÏÀÊäÈë
GPIO_Init(GPIOB, &GPIO_InitStructure);//³õʼ»¯IO
//CANµ¥ÔªÉèÖÃ
CAN_InitStructure.CAN_TTCM=DISABLE; //·Çʱ¼ä´¥·¢Í¨ÐÅģʽ //
CAN_InitStructure.CAN_ABOM=DISABLE; //Èí¼þ×Ô¶¯ÀëÏß¹ÜÀí //
CAN_InitStructure.CAN_AWUM=DISABLE; //˯Ãßģʽͨ¹ýÈí¼þ»½ÐÑ(Çå³ýCAN->MCRµÄSLEEPλ)//
CAN_InitStructure.CAN_NART=ENABLE; //½ûÖ¹±¨ÎÄ×Ô¶¯´«ËÍ //
CAN_InitStructure.CAN_RFLM=DISABLE; //±¨ÎIJ»Ëø¶¨,еĸ²¸Ç¾ÉµÄ //
CAN_InitStructure.CAN_TXFP=DISABLE; //ÓÅÏȼ¶Óɱ¨Îıêʶ·û¾ö¶¨ //
CAN_InitStructure.CAN_Mode= mode; //ģʽÉèÖ㺠mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; //
//ÉèÖò¨ÌØÂÊ
CAN_InitStructure.CAN_SJW=tsjw; //ÖØÐÂͬ²½ÌøÔ¾¿í¶È(Tsjw)Ϊtsjw+1¸öʱ¼äµ¥Î» CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq
CAN_InitStructure.CAN_BS1=tbs1; //Tbs1=tbs1+1¸öʱ¼äµ¥Î»CAN_BS1_1tq ~CAN_BS1_16tq
CAN_InitStructure.CAN_BS2=tbs2;//Tbs2=tbs2+1¸öʱ¼äµ¥Î»CAN_BS2_1tq ~ CAN_BS2_8tq
CAN_InitStructure.CAN_Prescaler=brp; //·ÖƵϵÊý(Fdiv)Ϊbrp+1 //
CAN_Init(CAN2, &CAN_InitStructure); // ³õʼ»¯CAN1
CAN_FilterInitStructure.CAN_FilterNumber=0; //¹ýÂËÆ÷0
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //32λ
CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;////32λID
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//32λMASK
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;//¹ýÂËÆ÷0¹ØÁªµ½FIFO0
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; //¼¤»î¹ýÂËÆ÷0
CAN_FilterInit(&CAN_FilterInitStructure);//Â˲¨Æ÷³õʼ»¯
return 0;
}
//can·¢ËÍÒ»×éÊý¾Ý(¹Ì¶¨¸ñʽ:IDΪ0X12,±ê×¼Ö¡,Êý¾ÝÖ¡)
//len:Êý¾Ý³¤¶È(×î´óΪ8)
//msg:Êý¾ÝÖ¸Õë,×î´óΪ8¸ö×Ö½Ú.
//·µ»ØÖµ:0,³É¹¦;
// ÆäËû,ʧ°Ü;
u8 Can_Send_Msg(u8* msg,u8 len)
{
u8 mbox;
u16 i=0;
CanTxMsg TxMessage;
TxMessage.StdId=0x12; // ±ê×¼±êʶ·ûΪ0
TxMessage.ExtId=0x12; // ÉèÖÃÀ©Õ¹±êʾ·û£¨29룩
TxMessage.IDE=0; // ʹÓÃÀ©Õ¹±êʶ·û
TxMessage.RTR=0; // ÏûÏ¢ÀàÐÍΪÊý¾ÝÖ¡£¬Ò»Ö¡8λ
TxMessage.DLC=len; // ·¢ËÍÁ½Ö¡ÐÅÏ¢
for(i=0;i<len;i++)
TxMessage.Data[i]=msg[i]; // µÚÒ»Ö¡ÐÅÏ¢
mbox= CAN_Transmit(CAN2, &TxMessage);
i=0;
while((CAN_TransmitStatus(CAN2, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++; //µÈ´ý·¢ËͽáÊø
if(i>=0XFFF)return 1;
return 0;
}
//can¿Ú½ÓÊÕÊý¾Ý²éѯ
//buf:Êý¾Ý»º´æÇø;
//·µ»ØÖµ:0,ÎÞÊý¾Ý±»ÊÕµ½;
// ÆäËû,½ÓÊÕµÄÊý¾Ý³¤¶È;
u8 Can_Receive_Msg(u8 *buf)
{
u32 i;
CanRxMsg RxMessage;
if( CAN_MessagePending(CAN2,CAN_FIFO0)==0)return 0; //ûÓнÓÊÕµ½Êý¾Ý,Ö±½ÓÍ˳ö
CAN_Receive(CAN2, CAN_FIFO0, &RxMessage);//¶ÁÈ¡Êý¾Ý
for(i=0;i<8;i++)
buf[i]=RxMessage.Data[i];
return RxMessage.DLC;
}
| Java |
/*
Author: Juan Rada-Vilela, Ph.D.
Copyright (C) 2010-2014 FuzzyLite Limited
All rights reserved
This file is part of fuzzylite.
fuzzylite is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
fuzzylite 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 Lesser General Public License
for more details.
You should have received a copy of the GNU Lesser General Public License
along with fuzzylite. If not, see <http://www.gnu.org/licenses/>.
fuzzylite™ is a trademark of FuzzyLite Limited.
*/
#include "../../fl/defuzzifier/IntegralDefuzzifier.h"
namespace fl {
int IntegralDefuzzifier::_defaultResolution = 200;
void IntegralDefuzzifier::setDefaultResolution(int defaultResolution) {
_defaultResolution = defaultResolution;
}
int IntegralDefuzzifier::defaultResolution() {
return _defaultResolution;
}
IntegralDefuzzifier::IntegralDefuzzifier(int resolution)
: Defuzzifier(), _resolution(resolution) {
}
IntegralDefuzzifier::~IntegralDefuzzifier() {
}
void IntegralDefuzzifier::setResolution(int resolution) {
this->_resolution = resolution;
}
int IntegralDefuzzifier::getResolution() const {
return this->_resolution;
}
}
| Java |
/*
Liquid War 6 is a unique multiplayer wargame.
Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Christian Mauduit <ufoot@ufoot.org>
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/>.
Liquid War 6 homepage : http://www.gnu.org/software/liquidwar6/
Contact author : ufoot@ufoot.org
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include <CUnit/CUnit.h>
#include "mat.h"
int
main (int argc, const char *argv[])
{
int ret = 0;
lw6sys_context_t *sys_context = NULL;
int mode = 0;
LW6SYS_MAIN_BEGIN (sys_context);
lw6sys_log_clear (sys_context, NULL);
mode = lw6sys_arg_test_mode (sys_context, argc, argv);
if (CU_initialize_registry () == CUE_SUCCESS)
{
if (lw6mat_test_register (sys_context, mode))
{
ret = lw6mat_test_run (sys_context, mode);
}
CU_cleanup_registry ();
}
LW6SYS_TEST_OUTPUT;
LW6SYS_MAIN_END (sys_context);
return (!ret);
}
| Java |
"""
Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std.
"""
import unittest
from iosxe.iosxe import IOSXE
from iosxe.exceptions import AuthError
node = '172.16.92.134'
username = 'cisco'
password = 'cisco'
port = 55443
class TestIOSXE(unittest.TestCase):
def setUp(self):
self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True)
def test_iosxe_is_a_IOSXE(self):
self.assertIsInstance(self.xe, IOSXE)
def test_invalid_user_pass_returns_auth_error(self):
self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things',
disable_warnings=True)
def test_url_base(self):
self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port))
def test_token_uri(self):
self.assertEqual(self.xe.token_uri, '/auth/token-services')
def test_save_config_success(self):
resp = self.xe.save_config()
self.assertEqual(204, resp.status_code)
| Java |
//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.
#ifndef APIQUERYRESULT_HPP
#define APIQUERYRESULT_HPP
#include "definitions.hpp"
#include <QString>
#include <QList>
#include <QHash>
#include "queryresult.hpp"
namespace Huggle
{
//! Key/value node for data from API queries
//! \todo Currently value is provided even for nodes that shouldn't have it
class HUGGLE_EX_CORE ApiQueryResultNode
{
public:
ApiQueryResultNode();
~ApiQueryResultNode();
/*!
* \brief GetAttribute Return the specified attribute if it exists, otherwise return the default
* \param name Name of attribute
* \param default_val Value to return if the attribute is not found
* \return Value of attribute or default value
*/
QString GetAttribute(const QString &name, const QString &default_val = "");
//! Name of attribute
QString Name;
//! Value of attribute
QString Value;
//! Hashtable of attribtues
QHash<QString, QString> Attributes;
QList<ApiQueryResultNode*> ChildNodes;
};
//! Api queries have their own result class so that we can use it to parse them
//! this is a universal result class that uses same format for all known
//! formats we are going to use, including XML or JSON, so that it shouldn't
//! matter which one we use, we always get this structure as output
class HUGGLE_EX_CORE ApiQueryResult : public QueryResult
{
public:
ApiQueryResult();
//! Frees the results from memory
~ApiQueryResult() override;
/*!
* \brief Process Process the data into Nodes and handle any warnings / errors
*/
void Process();
/*!
* \brief GetNode Get the first node with the specified name
* IMPORTANT: do not delete this node, it's a pointer to item in a list which get deleted in destructor of class
* \param node_name Name of node
* \return The specified node or a null pointer if none found
*/
ApiQueryResultNode *GetNode(const QString& node_name);
/*!
* \brief GetNodes Get all nodes with the specified name
* IMPORTANT: do not delete these nodes, they point to items in a list which get deleted in destructor of class
* \param node_name Name of node
* \return QList of pointers to found nodes
*/
QList<ApiQueryResultNode*> GetNodes(const QString& node_name);
QString GetNodeValue(const QString &node_name, const QString &default_value = "");
/*!
* \brief HasWarnings Return if the API has returned any warnings
* \return True if there are warnings, false otherwise
*/
bool HasWarnings();
//! List of result nodes unsorted with no hierarchy
QList<ApiQueryResultNode*> Nodes;
ApiQueryResultNode *Root;
//! Warning from API query
QString Warning;
//! If any error was encountered during the query
bool HasErrors = false;
};
}
#endif // APIQUERYRESULT_HPP
| Java |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = versionTransform;
var _path2 = require('path');
var _path3 = _interopRequireDefault(_path2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var packagePath = _path3.default.resolve(process.cwd(), './package.json');
var _require = require(packagePath);
var version = _require.version;
function versionTransform() {
return {
visitor: {
Identifier: function Identifier(path) {
if (path.node.name === 'VERSION') {
path.replaceWithSourceString('"' + version + '"');
}
}
}
};
}; | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
| Java |
from __future__ import absolute_import
from pywb.framework.wbrequestresponse import WbResponse, WbRequest
from pywb.framework.archivalrouter import ArchivalRouter
from six.moves.urllib.parse import urlsplit
import base64
import socket
import ssl
from io import BytesIO
from pywb.rewrite.url_rewriter import SchemeOnlyUrlRewriter, UrlRewriter
from pywb.rewrite.rewrite_content import RewriteContent
from pywb.utils.wbexception import BadRequestException
from pywb.utils.bufferedreaders import BufferedReader
from pywb.utils.loaders import to_native_str
from pywb.framework.proxy_resolvers import ProxyAuthResolver, CookieResolver, IPCacheResolver
from tempfile import SpooledTemporaryFile
#=================================================================
class ProxyArchivalRouter(ArchivalRouter):
"""
A router which combines both archival and proxy modes support
First, request is treated as a proxy request using ProxyRouter
Second, if not handled by the router, it is treated as a regular
archival mode request.
"""
def __init__(self, routes, **kwargs):
super(ProxyArchivalRouter, self).__init__(routes, **kwargs)
self.proxy = ProxyRouter(routes, **kwargs)
def __call__(self, env):
response = self.proxy(env)
if response:
return response
response = super(ProxyArchivalRouter, self).__call__(env)
if response:
return response
#=================================================================
class ProxyRouter(object):
"""
A router which supports http proxy mode requests
Handles requests of the form: GET http://example.com
The router returns latest capture by default.
However, if Memento protocol support is enabled,
the memento Accept-Datetime header can be used
to select specific capture.
See: http://www.mementoweb.org/guide/rfc/#Pattern1.3
for more details.
"""
BLOCK_SIZE = 4096
DEF_MAGIC_NAME = 'pywb.proxy'
BUFF_RESPONSE_MEM_SIZE = 1024*1024
CERT_DL_PEM = '/pywb-ca.pem'
CERT_DL_P12 = '/pywb-ca.p12'
CA_ROOT_FILE = './ca/pywb-ca.pem'
CA_ROOT_NAME = 'pywb https proxy replay CA'
CA_CERTS_DIR = './ca/certs/'
EXTRA_HEADERS = {'cache-control': 'no-cache',
'connection': 'close',
'p3p': 'CP="NOI ADM DEV COM NAV OUR STP"'}
def __init__(self, routes, **kwargs):
self.error_view = kwargs.get('error_view')
proxy_options = kwargs.get('config', {})
if proxy_options:
proxy_options = proxy_options.get('proxy_options', {})
self.magic_name = proxy_options.get('magic_name')
if not self.magic_name:
self.magic_name = self.DEF_MAGIC_NAME
proxy_options['magic_name'] = self.magic_name
self.extra_headers = proxy_options.get('extra_headers')
if not self.extra_headers:
self.extra_headers = self.EXTRA_HEADERS
proxy_options['extra_headers'] = self.extra_headers
res_type = proxy_options.get('cookie_resolver', True)
if res_type == 'auth' or not res_type:
self.resolver = ProxyAuthResolver(routes, proxy_options)
elif res_type == 'ip':
self.resolver = IPCacheResolver(routes, proxy_options)
#elif res_type == True or res_type == 'cookie':
# self.resolver = CookieResolver(routes, proxy_options)
else:
self.resolver = CookieResolver(routes, proxy_options)
self.use_banner = proxy_options.get('use_banner', True)
self.use_wombat = proxy_options.get('use_client_rewrite', True)
self.proxy_cert_dl_view = proxy_options.get('proxy_cert_download_view')
if not proxy_options.get('enable_https_proxy'):
self.ca = None
return
try:
from certauth.certauth import CertificateAuthority
except ImportError: #pragma: no cover
print('HTTPS proxy is not available as the "certauth" module ' +
'is not installed')
print('Please install via "pip install certauth" ' +
'to enable HTTPS support')
self.ca = None
return
# HTTPS Only Options
ca_file = proxy_options.get('root_ca_file', self.CA_ROOT_FILE)
# attempt to create the root_ca_file if doesn't exist
# (generally recommended to create this seperately)
ca_name = proxy_options.get('root_ca_name', self.CA_ROOT_NAME)
certs_dir = proxy_options.get('certs_dir', self.CA_CERTS_DIR)
self.ca = CertificateAuthority(ca_file=ca_file,
certs_dir=certs_dir,
ca_name=ca_name)
self.use_wildcard = proxy_options.get('use_wildcard_certs', True)
def __call__(self, env):
is_https = (env['REQUEST_METHOD'] == 'CONNECT')
ArchivalRouter.ensure_rel_uri_set(env)
# for non-https requests, check non-proxy urls
if not is_https:
url = env['REL_REQUEST_URI']
if not url.startswith(('http://', 'https://')):
return None
env['pywb.proxy_scheme'] = 'http'
route = None
coll = None
matcher = None
response = None
ts = None
# check resolver, for pre connect resolve
if self.resolver.pre_connect:
route, coll, matcher, ts, response = self.resolver.resolve(env)
if response:
return response
# do connect, then get updated url
if is_https:
response = self.handle_connect(env)
if response:
return response
url = env['REL_REQUEST_URI']
else:
parts = urlsplit(env['REL_REQUEST_URI'])
hostport = parts.netloc.split(':', 1)
env['pywb.proxy_host'] = hostport[0]
env['pywb.proxy_port'] = hostport[1] if len(hostport) == 2 else ''
env['pywb.proxy_req_uri'] = parts.path
if parts.query:
env['pywb.proxy_req_uri'] += '?' + parts.query
env['pywb.proxy_query'] = parts.query
if self.resolver.supports_switching:
env['pywb_proxy_magic'] = self.magic_name
# route (static) and other resources to archival replay
if env['pywb.proxy_host'] == self.magic_name:
env['REL_REQUEST_URI'] = env['pywb.proxy_req_uri']
# special case for proxy install
response = self.handle_cert_install(env)
if response:
return response
return None
# check resolver, post connect
if not self.resolver.pre_connect:
route, coll, matcher, ts, response = self.resolver.resolve(env)
if response:
return response
rel_prefix = ''
custom_prefix = env.get('HTTP_PYWB_REWRITE_PREFIX', '')
if custom_prefix:
host_prefix = custom_prefix
urlrewriter_class = UrlRewriter
abs_prefix = True
# always rewrite to absolute here
rewrite_opts = dict(no_match_rel=True)
else:
host_prefix = env['pywb.proxy_scheme'] + '://' + self.magic_name
urlrewriter_class = SchemeOnlyUrlRewriter
abs_prefix = False
rewrite_opts = {}
# special case for proxy calendar
if (env['pywb.proxy_host'] == 'query.' + self.magic_name):
url = env['pywb.proxy_req_uri'][1:]
rel_prefix = '/'
if ts is not None:
url = ts + '/' + url
wbrequest = route.request_class(env,
request_uri=url,
wb_url_str=url,
coll=coll,
host_prefix=host_prefix,
rel_prefix=rel_prefix,
wburl_class=route.handler.get_wburl_type(),
urlrewriter_class=urlrewriter_class,
use_abs_prefix=abs_prefix,
rewrite_opts=rewrite_opts,
is_proxy=True)
if matcher:
route.apply_filters(wbrequest, matcher)
# full rewrite and banner
if self.use_wombat and self.use_banner:
wbrequest.wb_url.mod = ''
elif self.use_banner:
# banner only, no rewrite
wbrequest.wb_url.mod = 'bn_'
else:
# unaltered, no rewrite or banner
wbrequest.wb_url.mod = 'uo_'
response = route.handler(wbrequest)
if not response:
return None
# add extra headers for replay responses
if wbrequest.wb_url and wbrequest.wb_url.is_replay():
response.status_headers.replace_headers(self.extra_headers)
# check for content-length
res = response.status_headers.get_header('content-length')
try:
if int(res) > 0:
return response
except:
pass
# need to either chunk or buffer to get content-length
if env.get('SERVER_PROTOCOL') == 'HTTP/1.1':
response.status_headers.remove_header('content-length')
response.status_headers.headers.append(('Transfer-Encoding', 'chunked'))
response.body = self._chunk_encode(response.body)
else:
response.body = self._buffer_response(response.status_headers,
response.body)
return response
@staticmethod
def _chunk_encode(orig_iter):
for chunk in orig_iter:
if not len(chunk):
continue
chunk_len = b'%X\r\n' % len(chunk)
yield chunk_len
yield chunk
yield b'\r\n'
yield b'0\r\n\r\n'
@staticmethod
def _buffer_response(status_headers, iterator):
out = SpooledTemporaryFile(ProxyRouter.BUFF_RESPONSE_MEM_SIZE)
size = 0
for buff in iterator:
size += len(buff)
out.write(buff)
content_length_str = str(size)
# remove existing content length
status_headers.replace_header('Content-Length',
content_length_str)
out.seek(0)
return RewriteContent.stream_to_gen(out)
def get_request_socket(self, env):
if not self.ca:
return None
sock = None
if env.get('uwsgi.version'): # pragma: no cover
try:
import uwsgi
fd = uwsgi.connection_fd()
conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
try:
sock = socket.socket(_sock=conn)
except:
sock = conn
except Exception as e:
pass
elif env.get('gunicorn.socket'): # pragma: no cover
sock = env['gunicorn.socket']
if not sock:
# attempt to find socket from wsgi.input
input_ = env.get('wsgi.input')
if input_:
if hasattr(input_, '_sock'): # pragma: no cover
raw = input_._sock
sock = socket.socket(_sock=raw) # pragma: no cover
elif hasattr(input_, 'raw'):
sock = input_.raw._sock
return sock
def handle_connect(self, env):
sock = self.get_request_socket(env)
if not sock:
return WbResponse.text_response('HTTPS Proxy Not Supported',
'405 HTTPS Proxy Not Supported')
sock.send(b'HTTP/1.0 200 Connection Established\r\n')
sock.send(b'Proxy-Connection: close\r\n')
sock.send(b'Server: pywb proxy\r\n')
sock.send(b'\r\n')
hostname, port = env['REL_REQUEST_URI'].split(':')
if not self.use_wildcard:
certfile = self.ca.cert_for_host(hostname)
else:
certfile = self.ca.get_wildcard_cert(hostname)
try:
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
certfile=certfile,
#ciphers="ALL",
suppress_ragged_eofs=False,
ssl_version=ssl.PROTOCOL_SSLv23
)
env['pywb.proxy_ssl_sock'] = ssl_sock
buffreader = BufferedReader(ssl_sock, block_size=self.BLOCK_SIZE)
statusline = to_native_str(buffreader.readline().rstrip())
except Exception as se:
raise BadRequestException(se.message)
statusparts = statusline.split(' ')
if len(statusparts) < 3:
raise BadRequestException('Invalid Proxy Request: ' + statusline)
env['REQUEST_METHOD'] = statusparts[0]
env['REL_REQUEST_URI'] = ('https://' +
env['REL_REQUEST_URI'].replace(':443', '') +
statusparts[1])
env['SERVER_PROTOCOL'] = statusparts[2].strip()
env['pywb.proxy_scheme'] = 'https'
env['pywb.proxy_host'] = hostname
env['pywb.proxy_port'] = port
env['pywb.proxy_req_uri'] = statusparts[1]
queryparts = env['REL_REQUEST_URI'].split('?', 1)
env['PATH_INFO'] = queryparts[0]
env['QUERY_STRING'] = queryparts[1] if len(queryparts) > 1 else ''
env['pywb.proxy_query'] = env['QUERY_STRING']
while True:
line = to_native_str(buffreader.readline())
if line:
line = line.rstrip()
if not line:
break
parts = line.split(':', 1)
if len(parts) < 2:
continue
name = parts[0].strip()
value = parts[1].strip()
name = name.replace('-', '_').upper()
if name not in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
name = 'HTTP_' + name
env[name] = value
env['wsgi.input'] = buffreader
#remain = buffreader.rem_length()
#if remain > 0:
#remainder = buffreader.read()
#env['wsgi.input'] = BufferedReader(BytesIO(remainder))
#remainder = buffreader.read(self.BLOCK_SIZE)
#env['wsgi.input'] = BufferedReader(ssl_sock,
# block_size=self.BLOCK_SIZE,
# starting_data=remainder)
def handle_cert_install(self, env):
if env['pywb.proxy_req_uri'] in ('/', '/index.html', '/index.html'):
available = (self.ca is not None)
if self.proxy_cert_dl_view:
return (self.proxy_cert_dl_view.
render_response(available=available,
pem_path=self.CERT_DL_PEM,
p12_path=self.CERT_DL_P12))
elif env['pywb.proxy_req_uri'] == self.CERT_DL_PEM:
if not self.ca:
return None
buff = b''
with open(self.ca.ca_file, 'rb') as fh:
buff = fh.read()
content_type = 'application/x-x509-ca-cert'
headers = [('Content-Length', str(len(buff)))]
return WbResponse.bin_stream([buff],
content_type=content_type,
headers=headers)
elif env['pywb.proxy_req_uri'] == self.CERT_DL_P12:
if not self.ca:
return None
buff = self.ca.get_root_PKCS12()
content_type = 'application/x-pkcs12'
headers = [('Content-Length', str(len(buff)))]
return WbResponse.bin_stream([buff],
content_type=content_type,
headers=headers)
| Java |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'eo', {
alertUrl: 'Bonvolu tajpi la retadreson de la bildo',
alt: 'Anstataŭiga Teksto',
border: 'Bordero',
btnUpload: 'Sendu al Servilo',
button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?',
hSpace: 'Horizontala Spaco',
img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?',
infoTab: 'Informoj pri Bildo',
linkTab: 'Ligilo',
lockRatio: 'Konservi Proporcion',
menu: 'Atributoj de Bildo',
resetSize: 'Origina Grando',
title: 'Atributoj de Bildo',
titleButton: 'Bildbutonaj Atributoj',
upload: 'Alŝuti',
urlMissing: 'La fontretadreso de la bildo mankas.',
vSpace: 'Vertikala Spaco',
validateBorder: 'La bordero devas esti entjera nombro.',
validateHSpace: 'La horizontala spaco devas esti entjera nombro.',
validateVSpace: 'La vertikala spaco devas esti entjera nombro.'
});
| Java |
/**
* Copyright (c) 2010-11 The AEminium Project (see AUTHORS file)
*
* This file is part of Plaid Programming Language.
*
* Plaid Programming Language 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.
*
* Plaid Programming Language 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 Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>.
*/
package aeminium.runtime.tools.benchmark;
public class RTBench {
private static Benchmark[] benchmarks = {
new TaskCreationBenchmark(),
new IndependentTaskGraph(),
new LinearTaskGraph(),
new FixedParallelMaxDependencies(),
new ChildTaskBenchmark(),
new FibonacciBenchmark()
};
public static void usage() {
System.out.println();
System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND");
System.out.println("");
System.out.println("COMMANDS:");
System.out.println(" list - List available benchmarks.");
System.out.println(" run BENCHMARK - Run specified benchmark.");
System.out.println();
}
public static void main(String[] args) {
if ( args.length == 0 ) {
usage();
return;
}
if ( args[0].equals("list") ) {
for( Benchmark benchmark : benchmarks ) {
System.out.println(benchmark.getName());
}
} else if ( args[0].equals("run") && args.length == 2 ) {
Benchmark benchmark = null;
for ( Benchmark b : benchmarks ) {
if ( b.getName().equals(args[1])) {
benchmark = b;
}
}
if ( benchmark != null ) {
Reporter reporter = new StringBuilderReporter();
reporter.startBenchmark(benchmark.getName());
benchmark.run(reporter);
reporter.stopBenchmark(benchmark.getName());
reporter.flush();
} else {
usage();
}
} else {
usage();
}
}
protected static void reportVMStats(Reporter reporter) {
reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory(),
Runtime.getRuntime().freeMemory()));
}
}
| Java |
<h1><?php the_issuu_message('Document'); ?></h1>
<form action="" method="post" id="document-upload">
<input type="hidden" name="name" value="<?= $doc->name; ?>">
<table class="form-table">
<tbody>
<tr>
<th><label for="title"><?php the_issuu_message('Title'); ?></label></th>
<td><input type="text" name="title" id="title" class="regular-text code" value="<?= $doc->title; ?>"></td>
</tr>
<tr>
<th><label for="description"><?php the_issuu_message('Description'); ?></label></th>
<td>
<textarea name="description" id="description" cols="45" rows="6"><?= $doc->description; ?></textarea>
</td>
</tr>
<tr>
<th><label for="tags">Tags</label></th>
<td>
<textarea name="tags" id="tags" cols="45" rows="6"><?= $tags; ?></textarea>
<p class="description">
<?php the_issuu_message('Use commas to separate tags. Do not use spaces.'); ?>
</p>
</td>
</tr>
<tr>
<th><label><?php the_issuu_message('Publish date'); ?></label></th>
<td>
<input type="text" name="pub[day]" id="dia" placeholder="<?php the_issuu_message('Day'); ?>" class="small-text"
maxlength="2" value="<?= date('d', strtotime($doc->publishDate)); ?>"> /
<input type="text" name="pub[month]" id="mes" placeholder="<?php the_issuu_message('Month'); ?>" class="small-text"
maxlength="2" value="<?= date('m', strtotime($doc->publishDate)); ?>"> /
<input type="text" name="pub[year]" id="ano" placeholder="<?php the_issuu_message('Year'); ?>" class="small-text"
maxlength="4" value="<?= date('Y', strtotime($doc->publishDate)); ?>">
<p class="description">
<?php the_issuu_message('Date of publication of the document.<br><strong>NOTE:</strong> If you do not enter a value, the current date will be used'); ?>
</p>
</td>
</tr>
<tr>
<th><label for="commentsAllowed"><?php the_issuu_message('Allow comments'); ?></label></th>
<td>
<input type="checkbox" name="commentsAllowed" id="commentsAllowed" value="true"
<?= ($doc->commentsAllowed == true)? 'checked' : ''; ?>>
</td>
</tr>
<tr>
<th><label for="downloadable"><?php the_issuu_message('Allow file download'); ?></label></th>
<td>
<input type="checkbox" name="downloadable" id="downloadable" value="true"
<?= ($doc->downloadable == true)? 'checked' : ''; ?>>
</td>
</tr>
<tr>
<th><label><?php the_issuu_message('Access'); ?></label></th>
<td>
<?php if ($doc->access == 'private') : ?>
<p><strong><?php the_issuu_message('Private'); ?></strong></p>
<p class="description">
<?php the_issuu_message('To publish this document <a href="http://issuu.com/home/publications" target="_blank">click here</a>'); ?>
</p>
<?php else: ?>
<p><strong><?php the_issuu_message('Public'); ?></strong></p>
<?php endif; ?>
</td>
</tr>
<tr>
<th>
<input type="submit" class="button-primary" value="<?php the_issuu_message('Update'); ?>">
<h3>
<a href="admin.php?page=issuu-document-admin" style="text-decoration: none;">
<?php the_issuu_message('Back'); ?>
</a>
</h3>
</th>
</tr>
</tbody>
</table>
</form> | Java |
#include "component.h"
#include "entity.h"
namespace entity {
Component::Component(Entity* parent) : QObject(parent) {
if (parent != NULL) {
parent->addComponent(this);
}
}
}
uint qHash(entity::HashableComponent* key, uint seed) {
return key == 0 ? 0 : key->hash(seed);
}
| Java |
/* Copyright (C) 2005-2012 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fontforgeui.h"
#include "groups.h"
#include <unistd.h>
#include <ustring.h>
#include <utype.h>
#include <gkeysym.h>
#include <math.h>
/******************************************************************************/
/******************************** Group Widget ********************************/
/******************************************************************************/
#define COLOR_CHOOSE (-10)
static GTextInfo std_colors[] = {
{ (unichar_t *) N_("Select by Color"), NULL, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Choose..."), NULL, 0, 0, (void *) COLOR_CHOOSE, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Default"), &def_image, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ NULL, &white_image, 0, 0, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &red_image, 0, 0, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &green_image, 0, 0, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &blue_image, 0, 0, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &yellow_image, 0, 0, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &cyan_image, 0, 0, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &magenta_image, 0, 0, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
GTEXTINFO_EMPTY
};
struct groupdlg {
unsigned int oked: 1;
unsigned int done: 1;
unsigned int select_many: 1;
/* define groups can only select one group at a time, select/restrict */
/* to groups can select multiple things */
unsigned int select_kids_too: 1;
/* When we select a parent group do we want to select all the kids? */
Group *root;
Group *oldsel;
int open_cnt, lines_page, off_top, off_left, page_width, bmargin;
int maxl;
GWindow gw,v;
GGadget *vsb, *hsb, *cancel, *ok, *compact;
GGadget *newsub, *delete, *line1, *gpnamelab, *gpname, *glyphslab, *glyphs;
GGadget *idlab, *idname, *iduni, *set, *select, *unique, *colour, *line2;
int fh, as;
GFont *font;
FontView *fv;
void (*select_callback)(struct groupdlg *);
GTimer *showchange;
};
extern int _GScrollBar_Width;
static Group *GroupFindLPos(Group *group,int lpos,int *depth) {
int i;
forever {
if ( group->lpos==lpos )
return( group );
if ( !group->open )
return( NULL );
for ( i=0; i<group->kid_cnt-1; ++i ) {
if ( lpos<group->kids[i+1]->lpos )
break;
}
group = group->kids[i];
++*depth;
}
}
static int GroupPosInParent(Group *group) {
Group *parent = group->parent;
int i;
if ( parent==NULL )
return( 0 );
for ( i=0; i<parent->kid_cnt; ++i )
if ( parent->kids[i]==group )
return( i );
return( -1 );
}
static Group *GroupNext(Group *group,int *depth) {
if ( group->open && group->kids ) {
++*depth;
return( group->kids[0] );
}
forever {
int pos;
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
if ( pos+1<group->parent->kid_cnt )
return( group->parent->kids[pos+1] );
group = group->parent;
--*depth;
}
}
static Group *GroupPrev(struct groupdlg *grp, Group *group,int *depth) {
int pos;
while ( group->parent!=NULL && group==group->parent->kids[0] ) {
group = group->parent;
--*depth;
}
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
group = group->parent->kids[pos-1];
while ( group->open ) {
group = group->kids[group->kid_cnt-1];
++*depth;
}
return( group );
}
static int _GroupSBSizes(struct groupdlg *grp, Group *group, int lpos, int depth) {
int i, len;
group->lpos = lpos++;
len = 5+8*depth+ grp->as + 5 + GDrawGetText8Width(grp->v,group->name,-1);
if ( group->glyphs!=NULL )
len += 5 + GDrawGetText8Width(grp->v,group->glyphs,-1);
if ( len > grp->maxl )
grp->maxl = len;
if ( group->open ) {
for ( i=0; i< group->kid_cnt; ++i )
lpos = _GroupSBSizes(grp,group->kids[i],lpos,depth+1);
}
return( lpos );
}
static int GroupSBSizes(struct groupdlg *grp) {
int lpos;
grp->maxl = 0;
GDrawSetFont(grp->v,grp->font);
lpos = _GroupSBSizes(grp,grp->root,0,0);
grp->maxl += 5; /* margin */
GScrollBarSetBounds(grp->vsb,0,lpos,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
grp->open_cnt = lpos;
return( lpos );
}
static void GroupSelectKids(Group *group,int sel) {
int i;
group->selected = sel;
for ( i=0; i<group->kid_cnt; ++i )
GroupSelectKids(group->kids[i],sel);
}
static void GroupDeselectAllBut(Group *root,Group *group) {
int i;
if ( root!=group )
root->selected = false;
for ( i=0; i<root->kid_cnt; ++i )
GroupDeselectAllBut(root->kids[i],group);
}
static Group *_GroupCurrentlySelected(Group *group) {
int i;
Group *sel;
if ( group->selected )
return( group );
for ( i=0; i<group->kid_cnt; ++i ) {
sel = _GroupCurrentlySelected(group->kids[i]);
if ( sel!=NULL )
return( sel );
}
return( NULL );
}
static Group *GroupCurrentlySelected(struct groupdlg *grp) {
if ( grp->select_many )
return( NULL );
return( _GroupCurrentlySelected(grp->root));
}
static void GroupWExpose(struct groupdlg *grp,GWindow pixmap,GRect *rect) {
int depth, y, len;
Group *group;
GRect r;
Color fg;
GDrawFillRect(pixmap,rect,GDrawGetDefaultBackground(NULL));
GDrawSetLineWidth(pixmap,0);
r.height = r.width = grp->as;
y = (rect->y/grp->fh) * grp->fh + grp->as;
depth=0;
group = GroupFindLPos(grp->root,rect->y/grp->fh+grp->off_top,&depth);
GDrawSetFont(pixmap,grp->font);
while ( group!=NULL ) {
r.y = y-grp->as+1;
r.x = 5+8*depth - grp->off_left;
fg = group->selected ? 0xff0000 : 0x000000;
if ( group->glyphs==NULL ) {
GDrawDrawRect(pixmap,&r,fg);
GDrawDrawLine(pixmap,r.x+2,r.y+grp->as/2,r.x+grp->as-2,r.y+grp->as/2,
fg);
if ( !group->open )
GDrawDrawLine(pixmap,r.x+grp->as/2,r.y+2,r.x+grp->as/2,r.y+grp->as-2,
fg);
}
len = GDrawDrawText8(pixmap,r.x+r.width+5,y,group->name,-1,fg);
if ( group->glyphs )
GDrawDrawText8(pixmap,r.x+r.width+5+len+5,y,group->glyphs,-1,fg);
group = GroupNext(group,&depth);
y += grp->fh;
if ( y-grp->fh>rect->y+rect->height )
break;
}
}
static void GroupWMouse(struct groupdlg *grp,GEvent *event) {
int x;
int depth=0;
Group *group;
group = GroupFindLPos(grp->root,event->u.mouse.y/grp->fh+grp->off_top,&depth);
if ( group==NULL )
return;
x = 5+8*depth - grp->off_left;
if ( event->u.mouse.x<x )
return;
if ( event->u.mouse.x<=x+grp->as ) {
if ( group->glyphs != NULL )
return;
group->open = !group->open;
GroupSBSizes(grp);
} else {
group->selected = !group->selected;
if ( grp->select_kids_too )
GroupSelectKids(group,group->selected);
else if ( group->selected && !grp->select_many )
GroupDeselectAllBut(grp->root,group);
if ( grp->select_callback!=NULL )
(grp->select_callback)(grp);
}
GDrawRequestExpose(grp->v,NULL,false);
}
static void GroupScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_top;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->lines_page;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->lines_page;
break;
case et_sb_bottom:
newpos = grp->open_cnt-grp->lines_page;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->open_cnt-grp->lines_page )
newpos = grp->open_cnt-grp->lines_page;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_top ) {
int diff = newpos-grp->off_top;
grp->off_top = newpos;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,diff*grp->fh);
}
}
static void GroupHScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_left;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->page_width;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->page_width;
break;
case et_sb_bottom:
newpos = grp->maxl-grp->page_width;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->maxl-grp->page_width )
newpos = grp->maxl-grp->page_width;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_left ) {
int diff = newpos-grp->off_left;
grp->off_left = newpos;
GScrollBarSetPos(grp->hsb,grp->off_left);
GDrawScroll(grp->v,NULL,-diff,0);
}
}
static void GroupResize(struct groupdlg *grp,GEvent *event) {
GRect size, wsize;
int lcnt, offy;
int sbsize = GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GDrawGetSize(grp->gw,&size);
lcnt = (size.height-grp->bmargin)/grp->fh;
GGadgetResize(grp->vsb,sbsize,lcnt*grp->fh);
GGadgetMove(grp->vsb,size.width-sbsize,0);
GGadgetResize(grp->hsb,size.width-sbsize,sbsize);
GGadgetMove(grp->hsb,0,lcnt*grp->fh);
GDrawResize(grp->v,size.width-sbsize,lcnt*grp->fh);
grp->page_width = size.width-sbsize;
grp->lines_page = lcnt;
GScrollBarSetBounds(grp->vsb,0,grp->open_cnt,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
GGadgetGetSize(grp->cancel,&wsize);
offy = size.height-wsize.height-6 - wsize.y;
GGadgetMove(grp->cancel,size.width-wsize.width-30, wsize.y+offy);
GGadgetMove(grp->ok , 30-3,wsize.y+offy-3);
if ( grp->newsub!=NULL ) {
GGadgetGetSize(grp->newsub,&wsize);
GGadgetMove(grp->newsub,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->delete,&wsize);
GGadgetMove(grp->delete,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line1,&wsize);
GGadgetMove(grp->line1,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpnamelab,&wsize);
GGadgetMove(grp->gpnamelab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpname,&wsize);
GGadgetMove(grp->gpname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphslab,&wsize);
GGadgetMove(grp->glyphslab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphs,&wsize);
GGadgetMove(grp->glyphs,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idlab,&wsize);
GGadgetMove(grp->idlab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idname,&wsize);
GGadgetMove(grp->idname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->iduni,&wsize);
GGadgetMove(grp->iduni,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->set,&wsize);
GGadgetMove(grp->set,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->select,&wsize);
GGadgetMove(grp->select,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->unique,&wsize);
GGadgetMove(grp->unique,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->colour,&wsize);
GGadgetMove(grp->colour,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line2,&wsize);
GGadgetMove(grp->line2,wsize.x,wsize.y+offy);
} else {
GGadgetGetSize(grp->compact,&wsize);
GGadgetMove(grp->compact,wsize.x,wsize.y+offy);
}
GDrawRequestExpose(grp->v,NULL,true);
GDrawRequestExpose(grp->gw,NULL,true);
}
static void GroupWChangeCurrent(struct groupdlg *grp,Group *current,Group *next ) {
if ( current!=NULL )
current->selected = false;
next->selected = true;
if ( next->lpos<grp->off_top || next->lpos>=grp->off_top+grp->lines_page ) {
if ( next->lpos>=grp->off_top+grp->lines_page )
grp->off_top = next->lpos;
else {
grp->off_top = next->lpos-grp->lines_page-1;
if ( grp->off_top<0 ) grp->off_top = 0;
}
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawRequestExpose(grp->v,NULL,false);
}
}
static int GroupChar(struct groupdlg *grp,GEvent *event) {
int depth = 0;
int pos;
Group *current = GroupCurrentlySelected(grp);
switch (event->u.chr.keysym) {
case GK_F1: case GK_Help:
help("groups.html");
return( true );
case GK_Return: case GK_KP_Enter:
if ( current!=NULL ) {
current->open = !current->open;
GroupSBSizes(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
case GK_Page_Down: case GK_KP_Page_Down:
pos = grp->off_top+(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos >= grp->open_cnt-grp->lines_page )
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Down: case GK_KP_Down:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if ( grp->off_top<grp->open_cnt-1 ) {
++grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupNext(current,&depth));
return( true );
case GK_Up: case GK_KP_Up:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if (grp->off_top!=0 ) {
--grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,-grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupPrev(grp,current,&depth));
return( true );
case GK_Page_Up: case GK_KP_Page_Up:
pos = grp->off_top-(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Left: case GK_KP_Left:
if ( !grp->select_many && current!=NULL )
GroupWChangeCurrent(grp,current,current->parent);
return( true );
case GK_Right: case GK_KP_Right:
if ( !grp->select_many && current != NULL && current->kid_cnt!=0 ) {
if ( !current->open ) {
current->open = !current->open;
GroupSBSizes(grp);
}
GroupWChangeCurrent(grp,current,current->kids[0]);
}
return( true );
case GK_Home: case GK_KP_Home:
if ( grp->off_top!=0 ) {
grp->off_top = 0;
GScrollBarSetPos(grp->vsb,0);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,grp->root);
return( true );
case GK_End: case GK_KP_End:
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
if ( pos!=grp->off_top ) {
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,GroupFindLPos(grp->root,grp->open_cnt-1,&depth));
return( true );
}
return( false );
}
static int grpv_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( GGadgetDispatchEvent(grp->vsb,event));
}
switch ( event->type ) {
case et_expose:
GroupWExpose(grp,gw,&event->u.expose.rect);
break;
case et_char:
return( GroupChar(grp,event));
case et_mouseup:
GroupWMouse(grp,event);
break;
}
return( true );
}
static void GroupWCreate(struct groupdlg *grp,GRect *pos) {
FontRequest rq;
int as, ds, ld;
GGadgetCreateData gcd[5];
GTextInfo label[4];
int sbsize = GDrawPointsToPixels(NULL,_GScrollBar_Width);
GWindowAttrs wattrs;
static GFont *font=NULL;
if ( font==NULL ) {
memset(&rq,'\0',sizeof(rq));
rq.utf8_family_name = SANS_UI_FAMILIES;
rq.point_size = 12;
rq.weight = 400;
font = GDrawInstanciateFont(grp->gw,&rq);
font = GResourceFindFont("Groups.Font",font);
}
grp->font = font;
GDrawWindowFontMetrics(grp->gw,grp->font,&as,&ds,&ld);
grp->fh = as+ds; grp->as = as;
grp->lines_page = (pos->height-grp->bmargin)/grp->fh;
grp->page_width = pos->width-sbsize;
wattrs.mask = wam_events|wam_cursor/*|wam_bordwidth|wam_bordcol*/;
wattrs.event_masks = ~0;
wattrs.border_width = 1;
wattrs.border_color = 0x000000;
wattrs.cursor = ct_pointer;
pos->x = 0; pos->y = 0;
pos->width -= sbsize; pos->height = grp->lines_page*grp->fh;
grp->v = GWidgetCreateSubWindow(grp->gw,pos,grpv_e_h,grp,&wattrs);
GDrawSetVisible(grp->v,true);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.x = pos->width; gcd[0].gd.pos.y = 0;
gcd[0].gd.pos.width = sbsize;
gcd[0].gd.pos.height = pos->height;
gcd[0].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels | gg_sb_vert;
gcd[0].creator = GScrollBarCreate;
gcd[1].gd.pos.x = 0; gcd[1].gd.pos.y = pos->height;
gcd[1].gd.pos.height = sbsize;
gcd[1].gd.pos.width = pos->width;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels;
gcd[1].creator = GScrollBarCreate;
GGadgetsCreate(grp->gw,gcd);
grp->vsb = gcd[0].ret;
grp->hsb = gcd[1].ret;
}
/******************************************************************************/
/******************************** Group Dialogs *******************************/
/******************************************************************************/
static int FindDuplicateNumberInString(int seek,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( seek>=val && seek<=val2 )
return( true );
}
}
return( false );
}
static int FindDuplicateNameInString(char *name,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' )
/* Skip it */;
else {
int ch = *str;
*str = '\0';
if ( strcmp(name,start)==0 ) {
*str = ch;
return( true );
}
*str = ch;
}
}
return( false );
}
static Group *FindDuplicateNumber(Group *top,int val,Group *cur,char *str) {
int i;
Group *grp;
if ( FindDuplicateNumberInString(val,str))
return( cur );
if ( top==cur )
return( NULL );
if ( FindDuplicateNumberInString(val,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateNumber(top->kids[i],val,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static Group *FindDuplicateName(Group *top,char *name,Group *cur,char *str) {
int i;
Group *grp;
if ( FindDuplicateNameInString(name,str))
return( cur );
if ( top==cur )
return( NULL );
if ( FindDuplicateNameInString(name,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateName(top->kids[i],name,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static int GroupValidateGlyphs(Group *cur,char *g,const unichar_t *gu,int unique) {
char *gpt, *start;
Group *top, *grp;
if ( gu!=NULL ) {
for ( ; *gu!='\0'; ++gu ) {
if ( *gu<' ' || *gu>=0x7f || *gu=='(' || *gu==')' ||
*gu=='[' || *gu==']' || *gu=='{' || *gu=='}' ||
*gu=='<' || *gu=='>' || *gu=='%' || *gu=='/' ) {
ff_post_error(_("Glyph names must be valid postscript names"),_("Glyph names must be valid postscript names"));
return( false );
}
}
}
if ( unique ) { /* Can't use cur->unique because it hasn't been set yet */
top = cur;
while ( top->parent!=NULL && top->parent->unique )
top = top->parent;
for ( gpt=g; *gpt!='\0' ; ) {
while ( *gpt==' ' ) ++gpt;
start = gpt;
while ( *gpt!=' ' && *gpt!='\0' ) ++gpt;
if ( start==gpt )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( val2<val ) {
ff_post_error(_("Bad Range"),_("Bad Range, start (%1$04X) is greater than end (%2$04X)"), val, val2 );
return( false );
}
for ( ; val<=val2; ++val )
if ( (grp=FindDuplicateNumber(top,val,cur,gpt))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The code point U+%1$04X occurs in groups %2$.30s and %3$.30s"), val, cur->name, grp->name);
return( false );
}
} else {
int ch = *gpt;
*gpt = '\0';
if ( (grp=FindDuplicateName(top,start,cur,ch!='\0'?gpt+1:NULL))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The glyph name \"%1$.30s\" occurs in groups %2$.30s and %3$.30s"), start, cur->name, grp->name);
*gpt = ch;
return( false );
}
*gpt = ch;
}
}
}
return( true );
}
static int GroupSetKidsUnique(Group *group) {
int i;
group->unique = true;
for ( i=0; i<group->kid_cnt; ++i )
if ( !GroupSetKidsUnique(group->kids[i]))
return( false );
if ( group->glyphs!=NULL ) {
if ( !GroupValidateGlyphs(group,group->glyphs,NULL,true))
return( false );
}
return( true );
}
static int GroupFinishOld(struct groupdlg *grp) {
if ( grp->oldsel!=NULL ) {
const unichar_t *gu = _GGadgetGetTitle(grp->glyphs);
char *g = cu_copy(gu);
int oldunique = grp->oldsel->unique;
if ( !GroupValidateGlyphs(grp->oldsel,g,gu,GGadgetIsChecked(grp->unique))) {
free(g);
return( false );
}
free(grp->oldsel->name);
grp->oldsel->name = GGadgetGetTitle8(grp->gpname);
free(grp->oldsel->glyphs);
if ( *g=='\0' ) {
grp->oldsel->glyphs = NULL;
free(g);
} else
grp->oldsel->glyphs = g;
grp->oldsel->unique = GGadgetIsChecked(grp->unique);
if ( grp->oldsel->unique && !oldunique ) {
/* The just set the unique bit. We must force it set in all */
/* kids. We really should check for uniqueness too!!!!! */
if ( !GroupSetKidsUnique(grp->oldsel))
return( false );
}
}
return( true );
}
static void GroupSelected(struct groupdlg *grp) {
Group *current = GroupCurrentlySelected(grp);
if ( !GroupFinishOld(grp)) {
if ( current!=NULL )
current->selected=false;
if ( grp->oldsel!=NULL )
grp->oldsel->selected = true;
return;
}
grp->oldsel = current;
if ( current == NULL ) {
GGadgetSetEnabled(grp->newsub,false);
GGadgetSetEnabled(grp->delete,false);
GGadgetSetEnabled(grp->gpnamelab,false);
GGadgetSetEnabled(grp->gpname,false);
GGadgetSetEnabled(grp->glyphslab,false);
GGadgetSetEnabled(grp->glyphs,false);
GGadgetSetEnabled(grp->set,false);
GGadgetSetEnabled(grp->select,false);
GGadgetSetEnabled(grp->unique,false);
GGadgetSetEnabled(grp->colour,false);
} else {
unichar_t *glyphs = uc_copy(current->glyphs);
GGadgetSetTitle8(grp->gpname,current->name);
if ( glyphs==NULL ) glyphs = uc_copy("");
GGadgetSetTitle(grp->glyphs,glyphs);
free(glyphs);
GGadgetSetChecked(grp->unique,current->unique);
GGadgetSetEnabled(grp->newsub,current->glyphs==NULL || *current->glyphs=='\0');
GGadgetSetEnabled(grp->delete,current->parent!=NULL);
GGadgetSetEnabled(grp->gpnamelab,true);
GGadgetSetEnabled(grp->gpname,true);
GGadgetSetEnabled(grp->glyphslab,current->kid_cnt==0);
GGadgetSetEnabled(grp->glyphs,current->kid_cnt==0);
GGadgetSetEnabled(grp->set,current->kid_cnt==0);
GGadgetSetEnabled(grp->select,current->kid_cnt==0);
GGadgetSetEnabled(grp->unique,current->parent==NULL || !current->parent->unique);
GGadgetSetEnabled(grp->colour,current->kid_cnt==0);
}
}
static void GroupShowChange(struct groupdlg *grp) {
if ( GroupFinishOld(grp))
GDrawRequestExpose(grp->v,NULL,false);
grp->showchange = NULL;
}
static int Group_GlyphListChanged(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *glyphs = _GGadgetGetTitle(g);
GGadgetSetEnabled(grp->newsub,*glyphs=='\0');
if ( grp->showchange!=NULL )
GDrawCancelTimer(grp->showchange);
grp->showchange = GDrawRequestTimer(grp->gw,500,0,NULL);
}
return( true );
}
static int Group_ToSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *ret = _GGadgetGetTitle(grp->glyphs);
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
const unichar_t *end;
int pos, found=-1;
char *nm;
GDrawSetVisible(fv->gw,true);
GDrawRaise(fv->gw);
memset(fv->b.selected,0,fv->b.map->enccount);
while ( *ret ) {
end = u_strchr(ret,' ');
if ( end==NULL ) end = ret+u_strlen(ret);
nm = cu_copybetween(ret,end);
for ( ret = end; isspace(*ret); ++ret);
if ( (nm[0]=='U' || nm[0]=='u') && nm[1]=='+' ) {
char *end;
int val = strtol(nm+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
if (( pos = SFFindSlot(sf,fv->b.map,val,NULL))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
} else if ( strncasecmp(nm,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(nm+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( pos=0; pos<fv->b.map->enccount; ++pos )
if ( (gid=fv->b.map->map[pos])!=-1 &&
(sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
fv->b.selected[pos] = true;
} else {
if (( pos = SFFindSlot(sf,fv->b.map,-1,nm))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
free(nm);
}
if ( found!=-1 )
FVScrollToChar(fv,found);
GDrawRequestExpose(fv->v,NULL,false);
}
return( true );
}
static int Group_FromSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
unichar_t *vals, *pt;
int i, len, max, gid, k;
SplineChar *sc, dummy;
char buffer[20];
if ( GGadgetIsChecked(grp->idname) ) {
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
len += strlen(sc->name)+1;
if ( fv->b.selected[i]>max ) max = fv->b.selected[i];
}
pt = vals = galloc((len+1)*sizeof(unichar_t));
*pt = '\0';
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
uc_strcpy(pt,sc->name);
pt += u_strlen(pt);
*pt++ = ' ';
}
if ( pt>vals ) pt[-1]='\0';
} else {
vals = NULL;
for ( k=0; k<2; ++k ) {
int last=-2, start=-2;
len = 0;
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
if ( sc->unicodeenc==-1 )
continue;
if ( sc->unicodeenc==last+1 )
last = sc->unicodeenc;
else {
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
start = last = sc->unicodeenc;
}
}
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
if ( !k )
vals = galloc((len+1)*sizeof(unichar_t));
else if ( len!=0 )
vals[len-1] = '\0';
else
*vals = '\0';
}
}
GGadgetSetTitle(grp->glyphs,vals);
free(vals);
}
return( true );
}
static int Group_AddColor(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
GTextInfo *ti = GGadgetGetListItemSelected(g);
int set=false;
Color xcol=0;
if ( ti==NULL )
/* Can't happen */;
else if ( ti->userdata == (void *) COLOR_CHOOSE ) {
struct hslrgb col, font_cols[6];
memset(&col,0,sizeof(col));
col = GWidgetColor(_("Pick a color"),&col,SFFontCols(grp->fv->b.sf,font_cols));
if ( col.rgb ) {
xcol = (((int) rint(255.*col.r))<<16 ) |
(((int) rint(255.*col.g))<<8 ) |
(((int) rint(255.*col.b)) );
set = true;
}
} else {
xcol = (intpt) ti->userdata;
set = true;
}
if ( set ) {
char buffer[40]; unichar_t ubuf[40];
sprintf(buffer," color=#%06x", xcol );
uc_strcpy(ubuf,buffer);
GTextFieldReplace(grp->glyphs,ubuf);
if ( grp->showchange==NULL )
GroupShowChange(grp);
}
GGadgetSelectOneListItem(g,0);
}
return( true );
}
static int Group_NewSubGroup(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *new_grp;
if ( !GroupFinishOld(grp))
return( true );
GDrawRequestExpose(grp->v,NULL,false);
if ( grp->oldsel==NULL )
return( true );
if ( grp->oldsel->glyphs!=NULL && grp->oldsel->glyphs!='\0' ) {
GGadgetSetEnabled(grp->newsub,false);
return( true );
}
grp->oldsel->kids = grealloc(grp->oldsel->kids,(++grp->oldsel->kid_cnt)*sizeof(Group *));
grp->oldsel->kids[grp->oldsel->kid_cnt-1] = new_grp = chunkalloc(sizeof(Group));
new_grp->parent = grp->oldsel;
new_grp->unique = grp->oldsel->unique;
new_grp->name = copy(_("UntitledGroup"));
grp->oldsel->selected = false;
grp->oldsel->open = true;
new_grp->selected = true;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int Group_Delete(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *parent;
int pos, i;
if ( grp->oldsel==NULL || grp->oldsel->parent==NULL )
return( true );
parent = grp->oldsel->parent;
pos = GroupPosInParent(grp->oldsel);
if ( pos==-1 )
return( true );
for ( i=pos; i<parent->kid_cnt-1; ++i )
parent->kids[i] = parent->kids[i+1];
--parent->kid_cnt;
GroupFree(grp->oldsel);
grp->oldsel = NULL;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int displaygrp_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( GGadgetDispatchEvent(grp->vsb,event));
}
if ( grp==NULL )
return( true );
switch ( event->type ) {
case et_expose:
break;
case et_char:
return( GroupChar(grp,event));
break;
case et_timer:
GroupShowChange(grp);
break;
case et_resize:
if ( event->u.resize.sized )
GroupResize(grp,event);
break;
case et_controlevent:
switch ( event->u.control.subtype ) {
case et_scrollbarchange:
if ( event->u.control.g == grp->vsb )
GroupScroll(grp,&event->u.control.u.sb);
else
GroupHScroll(grp,&event->u.control.u.sb);
break;
case et_buttonactivate:
grp->done = true;
grp->oked = event->u.control.g == grp->ok;
break;
}
break;
case et_close:
grp->done = true;
break;
case et_destroy:
if ( grp->newsub!=NULL )
free(grp);
return( true );
}
if ( grp->done && grp->newsub!=NULL ) {
if ( grp->oked ) {
if ( !GroupFinishOld(grp)) {
grp->done = grp->oked = false;
return( true );
}
GroupFree(group_root);
if ( grp->root->kid_cnt==0 && grp->root->glyphs==NULL ) {
group_root = NULL;
GroupFree(grp->root);
} else
group_root = grp->root;
SaveGroupList();
} else
GroupFree(grp->root);
GDrawDestroyWindow(grp->gw);
}
return( true );
}
void DefineGroups(FontView *fv) {
struct groupdlg *grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[20];
GTextInfo label[19];
int h, k,kk;
grp = gcalloc(1,sizeof(*grp));
grp->fv = fv;
grp->select_many = grp->select_kids_too = false;
grp->select_callback = GroupSelected;
if ( group_root==NULL ) {
grp->root = chunkalloc(sizeof(Group));
grp->root->name = copy(_("Groups"));
} else
grp->root = GroupCopy(group_root);
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.restrict_input_to_me = false;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Define Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,482);
grp->gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,grp,&wattrs);
grp->bmargin = GDrawPointsToPixels(NULL,248)+GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GroupWCreate(grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
k = 0;
gcd[k].gd.pos.x = 20;
gcd[k].gd.pos.y = GDrawPixelsToPoints(NULL,h-grp->bmargin)+12;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("New Sub-Group");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_NewSubGroup;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = GDrawPixelsToPoints(NULL,(pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("_Delete");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_Delete;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+8;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Group Name:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 80; gcd[k].gd.pos.width = 115;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-3;
gcd[k].gd.flags = gg_visible;
gcd[k++].creator = GTextFieldCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-2].gd.pos.y+16;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Glyphs:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+14;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-10; gcd[k].gd.pos.height = 4*13+4;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap;
gcd[k].gd.handle_controlevent = Group_GlyphListChanged;
gcd[k++].creator = GTextAreaCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+gcd[k-1].gd.pos.height+5;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
label[k].text = (unichar_t *) _("Identify by");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 90; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-2;
label[k].text = (unichar_t *) _("Name");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = (gg_visible | gg_enabled | gg_cb_on | gg_utf8_popup);
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
gcd[k].gd.pos.x = 140; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
label[k].text = (unichar_t *) _("Unicode");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
label[k].text = (unichar_t *) _("Set From Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+18;
gcd[k].gd.popup_msg = (unichar_t *) _("Set this glyph list to be the glyphs selected in the fontview");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_FromSelection;
gcd[k++].creator = GButtonCreate;
label[k].text = (unichar_t *) _("Select In Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 110; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.popup_msg = (unichar_t *) _("Set the fontview's selection to be the glyphs named here");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_ToSelection;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
label[k].text = (unichar_t *) _("No Glyph Duplicates");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyph names (or unicode code points) may occur at most once in this group and any of its sub-groups");
gcd[k++].creator = GCheckBoxCreate;
for ( kk=0; kk<3; ++kk )
std_colors[kk].text = (unichar_t *) S_((char *) std_colors[kk].text);
std_colors[1].image = GGadgetImageCache("colorwheel.png");
std_colors[0].selected = true;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+15;
gcd[k].gd.label = &std_colors[0];
gcd[k].gd.u.list = std_colors;
gcd[k].gd.handle_controlevent = Group_AddColor;
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k++].creator = GListButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+28;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = 30;
gcd[k].gd.pos.y = h-GDrawPointsToPixels(NULL,32);
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_OK");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_Cancel");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
GGadgetsCreate(grp->gw,gcd);
grp->newsub = gcd[0].ret;
grp->delete = gcd[1].ret;
grp->line1 = gcd[2].ret;
grp->gpnamelab = gcd[3].ret;
grp->gpname = gcd[4].ret;
grp->glyphslab = gcd[5].ret;
grp->glyphs = gcd[6].ret;
grp->idlab = gcd[7].ret;
grp->idname = gcd[8].ret;
grp->iduni = gcd[9].ret;
grp->set = gcd[10].ret;
grp->select = gcd[11].ret;
grp->unique = gcd[12].ret;
grp->colour = gcd[13].ret;
grp->line2 = gcd[14].ret;
grp->ok = gcd[15].ret;
grp->cancel = gcd[16].ret;
GroupSBSizes(grp);
GroupResize(grp,NULL);
GDrawSetVisible(grp->gw,true);
}
static void MapEncAddGid(EncMap *map,SplineFont *sf, int compacted,
int gid, int uni, char *name) {
if ( compacted && gid==-1 )
return;
if ( gid!=-1 && map->backmap[gid]==-1 )
map->backmap[gid] = map->enccount;
if ( map->enccount>=map->encmax )
map->map = grealloc(map->map,(map->encmax+=100)*sizeof(int));
map->map[map->enccount++] = gid;
if ( !compacted ) {
Encoding *enc = map->enc;
if ( enc->char_cnt>=enc->char_max ) {
enc->unicode = grealloc(enc->unicode,(enc->char_max+=256)*sizeof(int));
enc->psnames = grealloc(enc->psnames,enc->char_max*sizeof(char *));
}
if ( uni==-1 && name!=NULL ) {
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
uni = sf->glyphs[gid]->unicodeenc;
else
uni = UniFromName(name,ui_none,&custom);
}
enc->unicode[enc->char_cnt] = uni;
enc->psnames[enc->char_cnt++] = copy( name );
}
}
static void MapAddGroupGlyph(EncMap *map,SplineFont *sf,char *name, int compacted) {
int gid;
if ( (name[0]=='u' || name[0]=='U') && name[1]=='+' && ishexdigit(name[2])) {
char *end;
int val = strtol(name+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
gid = SFFindExistingSlot(sf,val,NULL);
MapEncAddGid(map,sf,compacted,gid,val,NULL);
}
} else if ( strncasecmp(name,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(name+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( gid=0; gid<sf->glyphcnt; ++gid )
if ( (sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
MapEncAddGid(map,sf,compacted,gid,sc->unicodeenc,NULL);
} else {
gid = SFFindExistingSlot(sf,-1,name);
MapEncAddGid(map,sf,compacted,gid,-1,name);
}
}
static int MapAddSelectedGroups(EncMap *map,SplineFont *sf,Group *group, int compacted) {
int i, cnt=0;
char *start, *pt;
int ch;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += MapAddSelectedGroups(map,sf,group->kids[i], compacted);
} else if ( group->selected ) {
for ( pt=group->glyphs; *pt!='\0'; ) {
while ( *pt==' ' ) ++pt;
start = pt;
while ( *pt!=' ' && *pt!='\0' ) ++pt;
ch = *pt; *pt='\0';
if ( *start!='\0' )
MapAddGroupGlyph(map,sf,start, compacted);
*pt=ch;
}
++cnt;
}
return( cnt );
}
static int GroupSelCnt(Group *group, Group **first, Group **second) {
int cnt = 0, i;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += GroupSelCnt(group->kids[i],first,second);
} else if ( group->selected ) {
if ( *first==NULL )
*first = group;
else if ( *second==NULL )
*second = group;
++cnt;
}
return( cnt );
}
static char *EncNameFromGroups(Group *group) {
Group *first = NULL, *second = NULL;
int cnt = GroupSelCnt(group,&first,&second);
char *prefix = P_("Group","Groups",cnt);
char *ret;
switch ( cnt ) {
case 0:
return( copy( _("No Groups")) );
case 1:
ret = galloc(strlen(prefix) + strlen(first->name) + 3 );
sprintf( ret, "%s: %s", prefix, first->name);
break;
case 2:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 5 );
sprintf( ret, "%s: %s, %s", prefix, first->name, second->name );
break;
default:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 9 );
sprintf( ret, "%s: %s, %s ...", prefix, first->name, second->name );
break;
}
return( ret );
}
static void EncodeToGroups(FontView *fv,Group *group, int compacted) {
SplineFont *sf = fv->b.sf;
EncMap *map;
if ( compacted )
map = EncMapNew(0,sf->glyphcnt,&custom);
else {
Encoding *enc = gcalloc(1,sizeof(Encoding));
enc->enc_name = EncNameFromGroups(group);
enc->is_temporary = true;
enc->char_max = 256;
enc->unicode = galloc(256*sizeof(int32));
enc->psnames = galloc(256*sizeof(char *));
map = EncMapNew(0,sf->glyphcnt,enc);
}
if ( MapAddSelectedGroups(map,sf,group,compacted)==0 ) {
ff_post_error(_("Nothing Selected"),_("Nothing Selected"));
EncMapFree(map);
} else if ( map->enccount==0 ) {
ff_post_error(_("Nothing Selected"),_("None of the glyphs in the current font match any names or code points in the selected groups"));
EncMapFree(map);
} else {
fv->b.selected = grealloc(fv->b.selected,map->enccount);
memset(fv->b.selected,0,map->enccount);
EncMapFree(fv->b.map);
fv->b.map = map;
FVSetTitle((FontViewBase *) fv);
FontViewReformatOne((FontViewBase *) fv);
}
}
void DisplayGroups(FontView *fv) {
struct groupdlg grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[6];
GTextInfo label[5];
int h;
memset( &grp,0,sizeof(grp));
grp.fv = fv;
grp.select_many = grp.select_kids_too = true;
grp.root = group_root;
if ( grp.root==NULL ) {
grp.root = chunkalloc(sizeof(Group));
grp.root->name = copy(_("Groups"));
}
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.restrict_input_to_me = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Display By Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,317);
grp.gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,&grp,&wattrs);
grp.bmargin = GDrawPointsToPixels(NULL,50)+GDrawPointsToPixels(grp.gw,_GScrollBar_Width);
GroupWCreate(&grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.width = -1;
gcd[0].gd.pos.x = 30;
gcd[0].gd.pos.y = h-GDrawPointsToPixels(NULL,30);
gcd[0].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[0].text = (unichar_t *) _("_OK");
label[0].text_is_1byte = true;
label[0].text_in_resource = true;
gcd[0].gd.label = &label[0];
gcd[0].creator = GButtonCreate;
gcd[1].gd.pos.width = -1;
gcd[1].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[1].gd.pos.y = gcd[0].gd.pos.y+3;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[1].text = (unichar_t *) _("_Cancel");
label[1].text_is_1byte = true;
label[1].text_in_resource = true;
gcd[1].gd.label = &label[1];
gcd[1].creator = GButtonCreate;
gcd[2].gd.pos.width = -1;
gcd[2].gd.pos.x = 10;
gcd[2].gd.pos.y = gcd[0].gd.pos.y-GDrawPointsToPixels(NULL,17);
gcd[2].gd.flags = gg_visible | gg_enabled | gg_cb_on | gg_pos_in_pixels;
label[2].text = (unichar_t *) _("Compacted");
label[2].text_is_1byte = true;
label[2].text_in_resource = true;
gcd[2].gd.label = &label[2];
gcd[2].creator = GCheckBoxCreate;
GGadgetsCreate(grp.gw,gcd);
grp.ok = gcd[0].ret;
grp.cancel = gcd[1].ret;
grp.compact = gcd[2].ret;
GroupSBSizes(&grp);
GDrawSetVisible(grp.gw,true);
while ( !grp.done )
GDrawProcessOneEvent(NULL);
GDrawSetUserData(grp.gw,NULL);
if ( grp.oked )
EncodeToGroups(fv,grp.root, GGadgetIsChecked(gcd[2].ret));
if ( grp.root!=group_root )
GroupFree(grp.root);
GDrawDestroyWindow(grp.gw);
}
| Java |
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.NumberFormatException;
import java.util.Collections;
public class FanMapMaker {
private static class IntList extends ArrayList<Integer> {}
private void printChargesArray(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge:");
for(int i = 0; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
}
}
private void printChargesArrayStatAll(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge_tab:");
for(int i = 0; i <= size; i++) {
percent = (100*i)/size;
System.out.println("\XORLW\t\t."+i+"\n"+
"\tBTFSC\t\tSTATUS,Z\n"+
"\tMOVLW\t\t."+distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n"
);
}
System.out.println("\tGOTO\t\ttemp2tcharge_tab_end");
}
private void printChargesArrayStatic(int[] distribution, int size) {
int percent;
String tmpRegName = "TMP0";
String endLabel = "temp2tcharge_tab_end";
System.out.println("temp2tcharge_tab:");
System.out.println("\tMOVLW\t\t.255\n\tMOVF\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\tnext1\n\tGOTO\t\t"+endLabel);
for(int i = 1; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
//System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
System.out.println("next"+i+":\n\tMOVLW\t\t."+ distribution[percent]+"\t\t; [" + i + "] " +
percent + "%\n\tDECFSZ\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\t"+
((i<size) ? "next"+(i+1) : endLabel) + "\n\tGOTO\t\t"+endLabel);
}
}
public static void main(String[] a) {
FanMapMaker fmp = new FanMapMaker();
IntList percentToCharge[] = new IntList[101];
int res[] = new int[101];
for(int i = 0; i < percentToCharge.length; i++)
percentToCharge[i] = new IntList();
File decFile = new File("allDec.dat");
File incFile = new File("allInc.dat");
BufferedReader decReader = null;
BufferedReader incReader = null;
Integer tchrg;
Integer fanPercx;
Float sum;
Float fanPerc;
try {
//decReader = new BufferedReader(new FileReader(decFile));
//incReader = new BufferedReader(new FileReader(incFile));
Scanner decScan = new Scanner(decFile);
Scanner incScan = new Scanner(incFile);
int cnt = 0;
while (decScan.hasNext()) {
tchrg = decScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += decScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
while (incScan.hasNext()) {
tchrg = incScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += incScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
for (int i = 0; i < percentToCharge.length; i++) {
Collections.sort(percentToCharge[i]);
//System.out.print("" + i + " " + "[");
for(Integer e: percentToCharge[i]) {
//System.out.print(e + " ");
}
//System.out.println("]");
}
int last = 1;
for (int i = percentToCharge.length - 1; i >= 0; i--) {
if(percentToCharge[i].size() > 0) {
res[i] = percentToCharge[i].get(0);
last = res[i];
} else {
res[i] = last;
}
//System.out.println(i + " " + res[i]);
}
fmp.printChargesArrayStatAll(res, 50);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
/*try {
if (decReader != null) {
//decReader.close();
}
} //catch (IOException e) {
//}
try {
if (incReader != null) {
//incReader.close();
}
} //catch (IOException e) {
//}
*/
}
}
}
| Java |
# -*- coding: utf-8 -*-
import os
from pygal import *
def listeEuler(f, x0, y0, pas, n):
x, y, L = x0, y0, []
for k in range(n):
L += [(x, y)]
x += pas
y += pas * f(x, y)
return L
def euler(f, x0, y0, xf, n):
pas = (xf - x0) / n
courbe = XY()
courbe.title = "Methode d Euler"
courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n))
courbe.render_to_file("courbeEulerPython.svg")
os.system("pause")
| Java |
vti_encoding:SR|utf8-nl
vti_timelastmodified:TW|14 Aug 2014 12:39:17 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|Office-PC\\Rafael
vti_modifiedby:SR|Office-PC\\Rafael
vti_timecreated:TR|01 Nov 2014 09:09:36 -0000
vti_backlinkinfo:VX|
vti_nexttolasttimemodified:TW|14 Aug 2014 12:39:17 -0000
vti_cacheddtm:TX|03 Nov 2015 21:05:11 -0000
vti_filesize:IR|554
vti_cachedneedsrewrite:BR|false
vti_cachedhasbots:BR|false
vti_cachedhastheme:BR|false
vti_cachedhasborder:BR|false
vti_charset:SR|utf-8
vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000
vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:05:11 -0000
| Java |
## Water Model construction
#
# Creates and constructs the model with all demands.
## `config` must be defined before loading this file!
include("world.jl")
include("weather.jl")
if get(config, "demandmodel", nothing) == "USGS"
include("WaterDemand.jl")
else
include("Thermoelectric.jl")
include("Livestock.jl")
include("Agriculture.jl");
include("IrrigationAgriculture.jl");
include("UnivariateAgriculture.jl");
include("IndustrialDemand.jl");
include("UrbanDemand.jl");
include("WaterDemand.jl");
end
## Check if the optimize-surface script has been called
storedresult = cached_fallback("extraction/withdrawals", () -> false)
if storedresult == false
@warn "Missing saved allocation files. Please run optimize-surface.jl"
elseif size(storedresult)[1] != numcanals || size(storedresult)[3] != numsteps
@warn "Cache file does not match current configuration. Please remove."
end
println("Creating model...")
model = newmodel();
# Add all of the components
if get(config, "demandmodel", nothing) != "USGS"
thermoelectric = initthermoelectric(model); # exogenous
livestock = initlivestock(model); # exogenous
irrigationagriculture = initirrigationagriculture(model); # optimization-only
univariateagriculture = initunivariateagriculture(model); # optimization-only
agriculture = initagriculture(model); # optimization-only
industrialdemand = initindustrialdemand(model); # exogenous
urbandemand = initurbandemand(model); # exogenous
end
waterdemand = initwaterdemand(model); # dep. Agriculture, PopulationDemand
# Connect up the components
if get(config, "demandmodel", nothing) != "USGS"
agriculture[:irrcropareas] = irrigationagriculture[:totalareas]
agriculture[:irrcropproduction] = irrigationagriculture[:production]
agriculture[:irrirrigation] = irrigationagriculture[:totalirrigation]
agriculture[:unicropareas] = univariateagriculture[:totalareas2]
agriculture[:unicropproduction] = univariateagriculture[:production]
agriculture[:uniirrigation] = univariateagriculture[:totalirrigation]
waterdemand[:totalirrigation] = agriculture[:allirrigation];
waterdemand[:thermoelectricuse] = thermoelectric[:demand_copy];
waterdemand[:livestockuse] = livestock[:demand_copy];
waterdemand[:urbanuse] = urbandemand[:waterdemand];
waterdemand[:industrialuse] = industrialdemand[:waterdemand];
end
| Java |
// Copyright © 2014, 2015, Travis Snoozy
//
// 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/>.
#include "cuisyntax.hpp"
#include <boost/spirit/include/qi_parse.hpp>
#include <cstdlib>
#include <iostream>
#include <iomanip>
// Boost modules
// Asio
// Program Options
namespace aha {
namespace pawn {
namespace testtool {
std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::hex128_t& hex)
{
std::ios save(NULL);
save.copyfmt(os);
os << std::hex << std::setfill('0') << std::setw(8) << hex.byte1
<< std::setw(8) << hex.byte2
<< std::setw(8) << hex.byte3
<< std::setw(8) << hex.byte4;
os.copyfmt(save);
return os;
}
std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::node_data_t& data)
{
std::ios save(NULL);
save.copyfmt(os);
os << std::setfill(' ') << std::left
<< std::setw(22) << "Key" << data.key << "\n"
<< std::setw(22) << "TX IV" << data.txiv << "\n"
<< std::setw(22) << "RX IV" << data.rxiv << "\n";
std::ios save2(NULL);
save2.copyfmt(os);
os << std::setw(22) << "Timeslot"
<< std::hex << std::setfill('0') << std::setw(4) << data.timeslot << "\n";
os.copyfmt(save2);
os << std::setw(22) << "Timeslot enable" << data.enable_timeslot << "\n"
<< std::setw(22) << "TX encryption enable" << data.enable_tx_encryption << "\n"
<< std::setw(22) << "RX decryption enable" << data.enable_rx_decryption << "\n";
os.copyfmt(save);
return os;
}
enum class option_visitor_result {
SUCCESS,
DOES_NOT_EXIST,
ALREADY_EXISTS,
INVALID_COMMAND,
UNEXPECTED_DATA
};
class option_visitor
: public boost::static_visitor<option_visitor_result>
{
private:
boost::spirit::qi::symbols<char, node_data_t> nodes;
public:
option_visitor_result operator()(const option_display_command_t& cmd)
{
nodes.for_each([](std::string& key, node_data_t& value){
std::cout << "Node " << key << "\n" << value << std::endl;
});
return option_visitor_result::SUCCESS;
}
option_visitor_result operator()(const option_display_node_command_t& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return option_visitor_result::DOES_NOT_EXIST;
}
std::cout << "Node " << cmd.node << "\n" << *node << std::endl;
return option_visitor_result::SUCCESS;
}
option_visitor_result operator()(const option_set_node_command_t& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return option_visitor_result::DOES_NOT_EXIST;
}
switch(cmd.param)
{
case option_set_node_param::KEY:
node->key = boost::get<hex128_t>(cmd.data);
break;
case option_set_node_param::RXDECRYPT:
node->enable_rx_decryption = boost::get<bool>(cmd.data);
break;
case option_set_node_param::RXIV:
node->rxiv = boost::get<hex128_t>(cmd.data);
break;
case option_set_node_param::TIMESLOT:
if(cmd.data.type() == typeid(bool)) {
node->enable_timeslot = boost::get<bool>(cmd.data);
}
else if(cmd.data.type() == typeid(hex128_t)) {
node->timeslot = (uint16_t)boost::get<hex128_t>(cmd.data).byte4;
}
else {
return option_visitor_result::UNEXPECTED_DATA;
}
break;
case option_set_node_param::TXENCRYPT:
node->enable_tx_encryption = boost::get<bool>(cmd.data);
break;
case option_set_node_param::TXIV:
node->txiv = boost::get<hex128_t>(cmd.data);
break;
default:
return option_visitor_result::INVALID_COMMAND;
}
return option_visitor_result::SUCCESS;
}
option_visitor_result operator()(const option_create_node_command_t& cmd)
{
if(nodes.find(cmd.node) != NULL)
{
return option_visitor_result::ALREADY_EXISTS;
}
nodes.at(cmd.node);
return option_visitor_result::SUCCESS;
}
option_visitor_result operator()(const transmit_command_t& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return option_visitor_result::DOES_NOT_EXIST;
}
// TODO: Write this out to the designated serial port.
return option_visitor_result::SUCCESS;
}
};
}}}
using aha::pawn::testtool::option_visitor_result;
int main(int argc, char** argv)
{
std::string input;
std::string message;
aha::pawn::testtool::command_t* command;
std::string::const_iterator begin, end;
aha::pawn::testtool::grammar::cui_grammar<std::string::const_iterator> grammar;
std::getline(std::cin, input);
aha::pawn::testtool::option_visitor option_visitor;
while(input != "quit")
{
command = new aha::pawn::testtool::command_t();
begin = input.begin();
end = input.end();
bool result = boost::spirit::qi::phrase_parse(
begin,
end,
grammar,
boost::spirit::ascii::space,
(*command));
if(result && begin == end)
{
switch(boost::apply_visitor(option_visitor, *command))
{
case option_visitor_result::SUCCESS:
std::cout << "OK.";
break;
case option_visitor_result::DOES_NOT_EXIST:
std::cout << "Node does not exist.";
break;
case option_visitor_result::ALREADY_EXISTS:
std::cout << "Node already exists.";
break;
case option_visitor_result::INVALID_COMMAND:
case option_visitor_result::UNEXPECTED_DATA:
std::cout << "An unexpected error occurred.";
break;
}
std::cout << std::endl;
}
else
{
std::cout << "Could not parse that." << std::endl;
}
delete command;
std::getline(std::cin, input);
}
return EXIT_SUCCESS;
}
// vim: set expandtab ts=4 sts=4 sw=4 fileencoding=utf-8:
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Wed May 02 09:32:45 CEST 2012 -->
<TITLE>
Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp
</TITLE>
<META NAME="date" CONTENT="2012-05-02">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?zisko/multicastor/program/controller//class-useViewController.MessageTyp.html" target="_top"><B>FRAMES</B></A>
<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>zisko.multicastor.program.controller.ViewController.MessageTyp</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#zisko.multicastor.program.controller"><B>zisko.multicastor.program.controller</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="zisko.multicastor.program.controller"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A> in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> that return <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></CODE></FONT></TD>
<TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#valueOf(java.lang.String)">valueOf</A></B>(java.lang.String name)</CODE>
<BR>
Returns the enum constant of this type with the specified name.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A>[]</CODE></FONT></TD>
<TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#values()">values</A></B>()</CODE>
<BR>
Returns an array containing the constants of this enum type, in
the order they are declared.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> with parameters of type <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ViewController.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.html#showMessage(zisko.multicastor.program.controller.ViewController.MessageTyp, java.lang.String)">showMessage</A></B>(<A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A> typ,
java.lang.String message)</CODE>
<BR>
Funktion welche ermueglich Nachrichten in der GUI anzuzeigen.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?zisko/multicastor/program/controller//class-useViewController.MessageTyp.html" target="_top"><B>FRAMES</B></A>
<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| Java |
import {Injectable} from '@angular/core';
import {SnackBarService} from './snack-bar.service';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
@Injectable({
providedIn: 'root'
})
export class TranslatableSnackBarService {
/**
* @param snackBarService
* @param translateService
*/
constructor(private snackBarService: SnackBarService, private translateService: TranslateService) {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.translateService.get('snackbarMessages.dismiss').subscribe((res: string) => {
this.snackBarService.setDefaultAction(res);
});
});
}
/**
* Emit snackbar with given duration
* @param {string} key
* @param {Object} interpolateParams
* @param {number} duration
*/
open(key: string, interpolateParams: Object = {}, duration: number = SnackBarService.defaultDuration): void {
this.translateService.get(key, interpolateParams).subscribe((message: string) => {
this.snackBarService.open(message, duration);
});
}
/**
* Emit snackbar with duration short
* @param {string} key
* @param {Object} interpolateParams
*/
openShort(key: string, interpolateParams: Object = {}): void {
this.open(key, interpolateParams, SnackBarService.durationShort);
}
/**
* Emit snackbar with duration long
* @param {string} key
* @param {Object} interpolateParams
*/
openLong(key: string, interpolateParams: Object = {}): void {
this.open(key, interpolateParams, SnackBarService.durationLong);
}
}
| Java |
import { AccessToken, Project, User, UserFeatureFlag, UserRole } from '@dev/translatr-model';
import { map } from 'rxjs/operators';
// General
export const isAdmin = (user?: User): boolean => user !== undefined && user.role === UserRole.Admin;
// Users
export const hasCreateUserPermission = () => map(isAdmin);
export const hasUserPermissionToDeleteUser = (me: User, user: User) =>
me !== undefined && me.id !== user.id && isAdmin(me);
export const hasEditUserPermission = (user: User) =>
map((me?: User) => (me !== undefined && me.id === user.id) || isAdmin(me));
export const hasDeleteUserPermission = (user: User) =>
map((me?: User) => hasUserPermissionToDeleteUser(me, user));
export const hasDeleteAllUsersPermission = (users: User[]) =>
map((me?: User) =>
users
.map((user: User) => hasUserPermissionToDeleteUser(me, user))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Projects
export const hasUserPermissionToDeleteProject = (me: User, project: Project) =>
(me !== undefined && me.id === project.ownerId) || isAdmin(me);
export const hasEditProjectPermission = (project: Project) =>
map((me?: User) => (me !== undefined && me.id === project.ownerId) || isAdmin(me));
export const hasDeleteProjectPermission = (project: Project) =>
map((me?: User) => hasUserPermissionToDeleteProject(me, project));
export const hasDeleteAllProjectsPermission = (projects: Project[]) =>
map((me?: User) =>
projects
.map((project: Project) => hasUserPermissionToDeleteProject(me, project))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Access Tokens
export const hasUserPermissionToEditAccessToken = (me: User, accessToken: AccessToken) =>
(me !== undefined && me.id === accessToken.userId) || isAdmin(me);
export const hasUserPermissionToDeleteAccessToken = (me: User, accessToken: AccessToken) =>
(me !== undefined && me.id === accessToken.userId) || isAdmin(me);
export const hasEditAccessTokenPermission = (accessToken: AccessToken) =>
map((me?: User) => hasUserPermissionToEditAccessToken(me, accessToken));
export const hasDeleteAccessTokenPermission = (accessToken: AccessToken) =>
map((me?: User) => hasUserPermissionToDeleteAccessToken(me, accessToken));
export const hasDeleteAllAccessTokensPermission = (accessTokens: AccessToken[]) =>
map((me?: User) =>
accessTokens
.map((accessToken: AccessToken) => hasUserPermissionToDeleteAccessToken(me, accessToken))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Feature Flags
export const hasUserPermissionToEditFeatureFlag = (me: User, featureFlag: UserFeatureFlag) =>
(me !== undefined && me.id === featureFlag.userId) || isAdmin(me);
export const hasUserPermissionToDeleteFeatureFlag = (me: User, featureFlag: UserFeatureFlag) =>
(me !== undefined && me.id === featureFlag.userId) || isAdmin(me);
export const hasEditFeatureFlagPermission = (featureFlag: UserFeatureFlag) =>
map((me?: User) => hasUserPermissionToEditFeatureFlag(me, featureFlag));
export const hasDeleteFeatureFlagPermission = (featureFlag: UserFeatureFlag) =>
map((me?: User) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag));
export const hasDeleteAllFeatureFlagsPermission = (featureFlags: UserFeatureFlag[]) =>
map((me?: User) =>
featureFlags
.map((featureFlag: UserFeatureFlag) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
| Java |
package Ashafix::I18N::eu;
use utf8;
use Mojo::Base 'Ashafix::I18N';
our %Lexicon = (
YES => 'BAI',
NO => 'EZ',
edit => 'aldatu',
del => 'ezabatu',
exit => 'Exit',
cancel => 'Cancel',
save => 'Save',
confirm => 'Ziur al zaude ezabatu nahi duzula?\n',
confirm_domain => 'Ziur al zaude domeinu honetako erregistro guztiak ezbatu nahi dituzula? Hau ezin izango da desegin!\n',
check_update => 'Check for update',
invalid_parameter => 'Invalid parameter!',
pFooter_logged_as => 'Logged as %s',
pLogin_welcome => 'Kudeatzailearen logina domeinuak kudeatzeko.',
pLogin_username => 'Erabiltzailea (e-mail)',
pLogin_password => 'Pasahitza',
pLogin_button => 'Erabiltzailea',
pLogin_failed => 'Your email address or password are not correct.',
pLogin_login_users => 'Erabiltzaileen gunera joateko logina.',
pMenu_main => 'Main',
pMenu_overview => 'Laburpena',
pMenu_create_alias => 'Aliasa gehitu',
pMenu_create_alias_domain => 'Add Alias Domain',
pMenu_create_mailbox => 'Postontzia gehitu',
pMenu_fetchmail => 'Fetch Email',
pMenu_sendmail => 'e-maila bidali',
pMenu_password => 'Pasahitza',
pMenu_viewlog => 'Logak ikusi',
pMenu_logout => 'Irten',
pMain_welcome => 'Ongietorri Postfix Adminera!',
pMain_overview => 'Alias eta postontzien zerrenda. Hemendik aldatu / ezabatu ditzakezu.',
pMain_create_alias => 'Zure domeinuarentzako alias berri baten sorkuntza.',
pMain_create_mailbox => 'Zure domeinuarentzako postontzi berri baten sorkuntza.',
pMain_sendmail => 'Duela gutxi sorturiko postontziren batera e-mail bat bidali.',
pMain_password => 'Kudeatzaile konturako pasahitza aldatu.',
pMain_viewlog => 'Logak ikusi.',
pMain_logout => 'Irten.',
pOverview_disabled => 'Disabled',
pOverview_unlimited => 'Unlimited',
pOverview_title => ':: Defined Domains',
pOverview_up_arrow => 'Go Top',
pOverview_right_arrow => 'Next Page',
pOverview_left_arrow => 'Previous Page',
pOverview_alias_domain_title => ':: Domain Aliases',
pOverview_alias_title => ':: Alias',
pOverview_mailbox_title => ':: Mailboxes',
pOverview_button => 'Joan',
pOverview_welcome => 'Laburpena ',
pOverview_alias_domain_aliases => 'Alias Domains',
pOverview_alias_domain_target => '%s is an Alias Domain for:',
pOverview_alias_alias_count => 'Aliasa',
pOverview_alias_mailbox_count => 'Postontziak',
pOverview_alias_address => 'Igorlea',
pOverview_alias_goto => 'Norakoa',
pOverview_alias_modified => 'Azken aldaketa',
pOverview_alias_domain_modified => 'Last Modified',
pOverview_alias_active => 'Active',
pOverview_alias_domain_active => 'Active',
pOverview_alias_edit => 'Alias',
and_x_more => '[and %s more...]',
pOverview_mailbox_username => 'E-mail',
pOverview_mailbox_name => 'Izena',
pOverview_mailbox_quota => 'Kuota (MB)',
pOverview_mailbox_modified => 'Azken aldaketa',
pOverview_mailbox_active => 'Aktibatua',
pOverview_vacation_edit => 'VACATION IS ON',
pOverview_vacation_option => 'Set Vacation',
pOverview_get_domain => 'Domeinua',
pOverview_get_aliases => 'Aliasa',
pOverview_get_alias_domains => 'Domain Aliases',
pOverview_get_mailboxes => 'Postontziak',
pOverview_get_quota => 'Postontzi kuota (MB)',
pOverview_get_modified => 'Azken aldaketa',
pDelete_delete_error => 'Ezinezkoa sarrera ezabatzea ',
pDelete_delete_success => '%s deleted.',
pDelete_postdelete_error => 'Unable to remove mailbox ',
pDelete_domain_error => 'Ez zara domeinu honen jabe',
pDelete_domain_alias_error => 'This domain is not yours ',
pDelete_alias_error => 'Unable to delete alias ',
pCreate_alias_domain_welcome => 'Mirror addresses of one of your domains to another.',
pCreate_alias_domain_alias => 'Alias Domain',
pCreate_alias_domain_alias_text => 'The domain that mails come in for.',
pCreate_alias_domain_target => 'Target Domain',
pCreate_alias_domain_target_text => 'The domain where mails should go to.',
pCreate_alias_domain_active => 'Active',
pCreate_alias_domain_button => 'Add Alias Domain',
pCreate_alias_domain_error1 => 'You are not allowed to create the chosen configuration.',
pCreate_alias_domain_error2 => 'The chosen configuration is invalid, please choose a different one!',
pCreate_alias_domain_error3 => 'Database insert failed.',
pCreate_alias_domain_error4 => 'All domains are already aliased.',
pCreate_alias_domain_success => 'The domain alias has been added to the alias domain table!',
pCreate_alias_welcome => 'Domeinuarentzat alias berri bat sortu.',
pCreate_alias_address => 'Aliasa',
pCreate_alias_address_text_error1 => 'ALIASa okerra da!',
pCreate_alias_address_text_error2 => 'Helbide hau existitzen da, ezberdin bat aukera ezazu mesedez!',
pCreate_alias_address_text_error3 => 'Alias sortze mugara heldu zara!',
pCreate_alias_goto => 'Norakoa',
pCreate_alias_active => 'Active',
pCreate_alias_button => 'Aliasa gehitu',
pCreate_alias_goto_text => 'Nora bidali behar den e-maila.',
pCreate_alias_goto_text_error => 'NORAKO okerra!',
pCreate_alias_result_error => 'Ezinezkoa aliasa alias taulan sartzea!',
pCreate_alias_result_success => 'Aliasa alias taulan gehituta!',
pCreate_alias_catchall_text => 'Alias orokor bat sortzeko "*" erabil ezazu alias gisa. Domeinuz domeinurako birbideraketa baterako Norako gisa "*@domain.tld" erabil ezazu.',
pEdit_alias_welcome => 'Domeinuarentzat aliasa aldatu. Lerroko sarrera bat.',
pEdit_alias_address => 'Aliasa',
pEdit_alias_address_error => 'Ezinezkoa aliasa aurkitzea!',
pEdit_alias_goto => 'Norakoa',
pEdit_alias_active => 'Active',
pEdit_alias_goto_text_error1 => 'Norakoan ez duzu ezer jarri',
pEdit_alias_goto_text_error2 => 'Sartutako e-mail helbidea baliiogabekoa da: ',
pEdit_alias_domain_error => 'Ez zara domeinu honen jabe: ',
pEdit_alias_domain_result_error => 'Unable to modify the alias domain!',
pEdit_alias_forward_and_store => 'Deliver to the local mailbox.',
pEdit_alias_forward_only => 'Forward to given email addresses only.',
pEdit_alias_button => 'Aliasa aldatu',
pEdit_alias_result_error => 'Ezinezkoa aliasa aldatzea!',
pCreate_mailbox_welcome => 'Postontzi berri bat sortu domeinuarentzat.',
pCreate_mailbox_username => 'Erabiltzailea',
pCreate_mailbox_username_text_error1 => 'E-maila baliogabekoa da!',
pCreate_mailbox_username_text_error2 => 'E-mail hau existitzen da. Ezberdin bat aukera ezazu, mesedez!',
pCreate_mailbox_username_text_error3 => 'Postontzi sorkuntza mugara iritsi zara!',
pCreate_mailbox_password => 'Pasahitza',
pCreate_mailbox_password2 => 'Pasahitza (errepikatu)',
pCreate_mailbox_password_text => 'POP3/IMAP-entzat pasahitza',
pCreate_mailbox_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
pCreate_mailbox_name => 'Izena',
pCreate_mailbox_name_text => 'Izen osoa',
pCreate_mailbox_quota => 'Kuota',
pCreate_mailbox_quota_text => 'MB',
pCreate_mailbox_quota_text_error => 'Zehazturiko kuota altuegia da!',
pCreate_mailbox_active => 'Aktibatua',
pCreate_mailbox_mail => 'Postontzia sortu',
pCreate_mailbox_button => 'Postontzia gehitu',
pCreate_mailbox_result_error => 'Ezinezkoa postontzi taulara postontzia gehitzea!',
pCreate_mailbox_result_success => 'Postontzia postontzi taulara sartu da!',
pCreate_mailbox_result_succes_nosubfolders => 'The mailbox has been added to the mailbox table, but none (or only some) of the predefined sub-folders could be created',
pEdit_mailbox_welcome => 'Domeinuarentzat postontzi bat aldatu.',
pEdit_mailbox_username => 'Erabiltzailea',
pEdit_mailbox_username_error => 'Ezinezkoa postontzia aurkitzea!',
pEdit_mailbox_password => 'Pasahitz berria',
pEdit_mailbox_password2 => 'Pasahitz berria (errepikatu)',
pEdit_mailbox_password_text_error => 'Sartutako pasahitzak ez datoz bat!',
pEdit_mailbox_name => 'Izena',
pEdit_mailbox_name_text => 'Full name',
pEdit_mailbox_quota => 'Kuota',
pEdit_mailbox_quota_text => 'MB',
pEdit_mailbox_quota_text_error => 'Zehazturiko kuota altuegia da!',
pEdit_mailbox_domain_error => 'Ez zara domeinu honen jabe: ',
pEdit_mailbox_button => 'Postontzia aldatu',
pEdit_mailbox_result_error => 'Ezinezkoa pasahitza aldatzea!',
pPassword_welcome => 'Login pasahitza aldatu.',
pPassword_admin => 'Login',
pPassword_admin_text_error => 'Emandako LOGINa ez dator inolako postontziekin bat!',
pPassword_password_current => 'Egungo pasahitza',
pPassword_password_current_text_error => 'Ez duzu egungo pasahitzik sartu!',
pPassword_password => 'Pasahitz berria',
pPassword_password2 => 'Pasahitz berria (errepikatu)',
pPassword_password_text_error => 'Sarturiko pasahitzak ez datoz bat edo zuriz daude!',
pPassword_button => 'Pasahitza aldatu',
pPassword_result_error => 'Ezinezkoa pasahitza aldatzea!',
pPassword_result_success => 'Pasahitza aldatuta!',
pEdit_vacation_set => 'Change / Set away message',
pEdit_vacation_remove => 'Remove away message',
pVacation_result_error => 'Unable to update auto response settings!',
pVacation_result_removed => 'Auto response has been removed!',
pVacation_result_added => 'Auto response has been enabled!',
pViewlog_welcome => 'Honen azken 10 ekintzak ikusi ',
pViewlog_timestamp => 'Data/ordua',
pViewlog_username => 'Kudeatzailea',
pViewlog_domain => 'Domeinua',
pViewlog_action => 'Ekintza',
pViewlog_data => 'Datuak',
pViewlog_action_create_mailbox => 'create mailbox',
pViewlog_action_delete_mailbox => 'delete mailbox',
pViewlog_action_edit_mailbox => 'edit mailbox',
pViewlog_action_edit_mailbox_state => 'edit mailbox active',
pViewlog_action_create_alias => 'create alias',
pViewlog_action_create_alias_domain => 'create alias domain',
pViewlog_action_delete_alias => 'delete alias',
pViewlog_action_delete_alias_domain => 'delete alias domain',
pViewlog_action_edit_alias => 'edit alias',
pViewlog_action_edit_alias_state => 'edit alias active',
pViewlog_action_edit_alias_domain_state => 'edit alias domain active',
pViewlog_action_edit_password => 'change password',
pViewlog_button => 'Joan',
pViewlog_result_error => 'Ezinezkoa logak aurkitzea!',
pSendmail_welcome => 'e-mail bat bidali.',
pSendmail_admin => 'Igorlea',
pSendmail_to => 'Norakoa',
pSendmail_to_text_error => 'Norako helbidea hutsa dago edo okerra da!',
pSendmail_subject => 'Gaia',
pSendmail_subject_text => 'Ongi etorri',
pSendmail_body => 'Gorputza',
pSendmail_button => 'Mezua bidali',
pSendmail_result_error => 'Ezinezkoa postontzia sortzea!',
pSendmail_result_success => 'Postontzia sortuta!',
pAdminMenu_list_admin => 'Kudeatzaile zerrenda',
pAdminMenu_list_domain => 'Domeinu zerrenda',
pAdminMenu_list_virtual => 'Helbide birtualen zerrenda',
pAdminMenu_viewlog => 'Logak ikusi',
pAdminMenu_backup => 'Segurtasun kopia',
pAdminMenu_create_domain_admins => 'Domeinu kudeatzaileak',
pAdminMenu_create_admin => 'Kudeatzaile berria',
pAdminMenu_create_domain => 'Domeinu berria',
pAdminMenu_create_alias => 'Aliasa gehitu',
pAdminMenu_create_mailbox => 'Postontzia gehitu',
pAdminList_admin_domain => 'Domeinua',
pAdminList_admin_username => 'Kudeatzailea',
pAdminList_admin_count => 'Domeinuak',
pAdminList_admin_modified => 'Azken aldaketa',
pAdminList_admin_active => 'Aktibatua',
pAdminList_domain_domain => 'Domeinua',
pAdminList_domain_description => 'Deskripzioa',
pAdminList_domain_aliases => 'Aliasa',
pAdminList_domain_mailboxes => 'Postontziak',
pAdminList_domain_maxquota => 'Gehienezko kuota (MB)',
pAdminList_domain_transport => 'Transport',
pAdminList_domain_backupmx => 'Backup MX',
pAdminList_domain_modified => 'Azken aldaketa',
pAdminList_domain_active => 'Aktibatua',
pAdminList_virtual_button => 'Joan',
pAdminList_virtual_welcome => 'Laburpena ',
pAdminList_virtual_alias_alias_count => 'Aliasa',
pAdminList_virtual_alias_mailbox_count => 'Postontziak',
pAdminList_virtual_alias_address => 'Igorlea',
pAdminList_virtual_alias_goto => 'Norakoa',
pAdminList_virtual_alias_modified => 'Azken aldaketa',
pAdminList_virtual_mailbox_username => 'E-mail',
pAdminList_virtual_mailbox_name => 'Izena',
pAdminList_virtual_mailbox_quota => 'Kuota (MB)',
pAdminList_virtual_mailbox_modified => 'Azken aldaketa',
pAdminList_virtual_mailbox_active => 'Aktibatua',
pAdminCreate_domain_welcome => 'Domeinu berria gehitu',
pAdminCreate_domain_domain => 'Domeinua',
pAdminCreate_domain_domain_text_error => 'Domeinua existitzen da!',
pAdminCreate_domain_domain_text_error2 => 'The domain is invalid!',
pAdminCreate_domain_description => 'Deskripzioa',
pAdminCreate_domain_aliases => 'Aliasa',
pAdminCreate_domain_aliases_text => '-1 = desegokitu | 0 = mugagabea',
pAdminCreate_domain_mailboxes => 'Postontziak',
pAdminCreate_domain_mailboxes_text => '-1 = desegokitu | 0 = mugagabea',
pAdminCreate_domain_maxquota => 'Gehienezko kuota',
pAdminCreate_domain_maxquota_text => 'MB -1 = desegokitu | 0 = mugagabea',
pAdminCreate_domain_transport => 'Transport',
pAdminCreate_domain_transport_text => 'Define transport',
pAdminCreate_domain_defaultaliases => 'Aurremugatutako aliasa gehitu',
pAdminCreate_domain_defaultaliases_text => '',
pAdminCreate_domain_backupmx => 'Mail server is backup MX',
pAdminCreate_domain_button => 'Domeinua gehitu',
pAdminCreate_domain_result_error => 'Ezinezkoa domeinua gehitzea!',
pAdminCreate_domain_result_success => 'Domeinua gehituta!',
pAdminDelete_domain_error => 'Unable to remove domain!',
pAdminDelete_alias_domain_error => 'Unable to remove domain alias!',
pAdminEdit_domain_welcome => 'Domeinu bat aldatu',
pAdminEdit_domain_domain => 'Domeinua',
pAdminEdit_domain_description => 'Deskripzioa',
pAdminEdit_domain_aliases => 'Aliasa',
pAdminEdit_domain_aliases_text => '-1 = desegokitu | 0 = mugagabea',
pAdminEdit_domain_mailboxes => 'Postontziak',
pAdminEdit_domain_mailboxes_text => '-1 = desegokitu | 0 = mugagabea',
pAdminEdit_domain_maxquota => 'Gehienezko kuota',
pAdminEdit_domain_maxquota_text => 'MB -1 = desegokitu | 0 = mugagabea',
pAdminEdit_domain_transport => 'Transport',
pAdminEdit_domain_transport_text => 'Define transport',
pAdminEdit_domain_backupmx => 'Mail server is backup MX',
pAdminEdit_domain_active => 'Aktibatua',
pAdminEdit_domain_button => 'Domeinua aldatu',
pAdminEdit_domain_result_error => 'Ezinezkoa domeinua aldatzea!',
pAdminCreate_admin_welcome => 'Domeinu kudeatzaile berri bat gehitu',
pAdminCreate_admin_username => 'Kudeatzailea',
pAdminCreate_admin_username_text => 'E-mail helbidea',
pAdminCreate_admin_username_text_error1 => 'Kudeatzaile e-mailak ez du balio!',
pAdminCreate_admin_username_text_error2 => 'Kudeatzailea existitzen da edo ez du balio!',
pAdminCreate_admin_password => 'Pasahitza',
pAdminCreate_admin_password2 => 'Pasahitza (errepikatu)',
pAdminCreate_admin_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
pAdminCreate_admin_button => 'Kudeatzailea gehitu',
pAdminCreate_admin_result_error => 'Ezinezkoa kudeatzailea gehitzea!',
pAdminCreate_admin_result_success => 'Kudeatzailea gehituta1',
pAdminCreate_admin_address => 'Domeinua',
pAdminEdit_admin_welcome => 'Domeinu kudeatzaile bat aldatu',
pAdminEdit_admin_username => 'Kudeatzailea',
pAdminEdit_admin_password => 'Pasahitza',
pAdminEdit_admin_password2 => 'Pasahitza (errepikatu)',
pAdminEdit_admin_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
pAdminEdit_admin_active => 'Aktibatua',
pAdminEdit_admin_super_admin => 'Super admin',
pAdminEdit_admin_button => 'Kudeatzailea aldatu',
pAdminEdit_admin_result_error => 'Ezinezkoa kudeatzailea aldatzea!',
pAdminEdit_admin_result_success => 'Kudeatzailea aldatu da!',
pUsersLogin_welcome => 'Erabiltzaileen logina pasahitz eta aliasa aldatzeko.',
pUsersLogin_username => 'Login (e-mail)',
pUsersLogin_password => 'Pasahitza',
pUsersLogin_button => 'Login',
pUsersLogin_username_incorrect => 'Login okerra. Ziurta zaitez posta helbidea login gisa sartu duzula!',
pUsersLogin_password_incorrect => 'Pasahitz okerra!',
pUsersMenu_vacation => 'Erantzun automatikoa',
pUsersMenu_edit_alias => 'Berbiderapen helbidea aldatu',
pUsersMenu_password => 'Pasahitza aldatu',
pUsersMain_vacation => 'Konfigura ezazu "lanetik kanpo" motako mezu bat edo erantzun automatikoa zure postarentzat.',
pUsersMain_edit_alias => 'Alda ezazu posta helbidea.',
pUsersMain_password => 'Alda ezazu pasahitza.',
pUsersVacation_welcome => 'Erantzun automatikoa.',
pUsersVacation_welcome_text => 'Erantzun automatiko bat konfiguratuta duzu!',
pUsersVacation_subject => 'Gaia',
pUsersVacation_subject_text => 'Lanetik kanpo',
pUsersVacation_body => 'Gorputza',
pUsersVacation_body_text => '<date>-tik <date> arte kanpoan egongo naiz.
Larrialdiko gaientzat, hemen <contact person> kontakta dezakezu nirekin.
',
pUsersVacation_button_away => 'Aldeginda',
pUsersVacation_button_back => 'Itzulita',
pUsersVacation_result_error => 'Ezinezkoa zure erantzun atomatikoaren konfigurazioa eguneratzea!',
pUsersVacation_result_success => 'Zure erantzun automatikoa borratu da!',
pUsersVacation_activefrom => 'Active from',
pUsersVacation_activeuntil => 'Active until',
pCreate_dbLog_createmailbox => 'create mailbox',
pCreate_dbLog_createalias => 'create alias',
pDelete_dbLog_deletealias => 'delete alias',
pDelete_dbLog_deletemailbox => 'delete mailbox',
pEdit_dbLog_editactive => 'change active state',
pEdit_dbLog_editalias => 'edit alias',
pEdit_dbLog_editmailbox => 'edit mailbox',
pSearch => 'search',
pSearch_welcome => 'Searching for: ',
pReturn_to => 'Return to',
pBroadcast_title => 'Send broadcast message',
pBroadcast_from => 'From',
pBroadcast_name => 'Your name',
pBroadcast_subject => 'Subject',
pBroadcast_message => 'Message',
pBroadcast_send => 'Send message',
pBroadcast_success => 'Your broadcast message was sent.',
pAdminMenu_broadcast_message => 'Broadcast message',
pBroadcast_error_empty => 'The fields Name, Subject and Message should\'t be empty !',
pStatus_undeliverable => 'maybe UNDELIVERABLE ',
pStatus_custom => 'Delivers to ',
pStatus_popimap => 'POP/IMAP ',
pPasswordTooShort => 'Password is too short - requires %s characters',
pInvalidDomainRegex => 'Invalid domain name %s, fails regexp check',
pInvalidDomainDNS => 'Invalid domain %s, and/or not discoverable in DNS',
pInvalidMailRegex => 'Invalid email address, fails regexp check',
pFetchmail_welcome => 'Fetch mail for:',
pFetchmail_new_entry => 'New entry',
pFetchmail_database_save_error => 'Could not save this entry in the database!',
pFetchmail_database_save_success => 'Entry saved in database.',
pFetchmail_error_invalid_id => 'No entry with ID %s found!',
pFetchmail_invalid_mailbox => 'Invalid mailbox!',
pFetchmail_server_missing => 'Please enter the remote server name!',
pFetchmail_user_missing => 'Please enter the remote username!',
pFetchmail_password_missing => 'Please enter the remote password!',
pFetchmail_field_id => 'ID',
pFetchmail_field_mailbox => 'Mailbox',
pFetchmail_field_src_server => 'Server',
pFetchmail_field_src_auth => 'Auth Type',
pFetchmail_field_src_user => 'User',
pFetchmail_field_src_password => 'Password',
pFetchmail_field_src_folder => 'Folder',
pFetchmail_field_poll_time => 'Poll',
pFetchmail_field_fetchall => 'Fetch All',
pFetchmail_field_keep => 'Keep',
pFetchmail_field_protocol => 'Protocol',
pFetchmail_field_usessl => 'SSL active',
pFetchmail_field_extra_options => 'Extra Options',
pFetchmail_field_mda => 'MDA',
pFetchmail_field_date => 'Date',
pFetchmail_field_returned_text => 'Returned Text',
pFetchmail_desc_id => 'Record ID',
pFetchmail_desc_mailbox => 'Local mailbox',
pFetchmail_desc_src_server => 'Remote Server',
pFetchmail_desc_src_auth => 'Mostly \'password\'',
pFetchmail_desc_src_user => 'Remote User',
pFetchmail_desc_src_password => 'Remote Password',
pFetchmail_desc_src_folder => 'Remote Folder',
pFetchmail_desc_poll_time => 'Poll every ... minutes',
pFetchmail_desc_fetchall => 'Retrieve both old (seen) and new messages',
pFetchmail_desc_keep => 'Keep retrieved messages on the remote mailserver',
pFetchmail_desc_protocol => 'Protocol to use',
pFetchmail_desc_usessl => 'SSL encryption',
pFetchmail_desc_extra_options => 'Extra fetchmail Options',
pFetchmail_desc_mda => 'Mail Delivery Agent',
pFetchmail_desc_date => 'Date of last polling/configuration change',
pFetchmail_desc_returned_text => 'Text message from last polling',
); | Java |
package com.bytezone.diskbrowser.nufx;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import com.bytezone.diskbrowser.prodos.write.DiskFullException;
import com.bytezone.diskbrowser.prodos.write.FileAlreadyExistsException;
import com.bytezone.diskbrowser.prodos.write.ProdosDisk;
import com.bytezone.diskbrowser.prodos.write.VolumeCatalogFullException;
// -----------------------------------------------------------------------------------//
public class Binary2
// -----------------------------------------------------------------------------------//
{
private static final String UNDERLINE =
"------------------------------------------------------"
+ "-----------------------";
Binary2Header binary2Header;
byte[] buffer;
List<Binary2Header> headers = new ArrayList<> ();
int totalBlocks;
String fileName;
// ---------------------------------------------------------------------------------//
public Binary2 (Path path) throws IOException
// ---------------------------------------------------------------------------------//
{
fileName = path.toFile ().getName ();
buffer = Files.readAllBytes (path);
read (buffer);
}
// ---------------------------------------------------------------------------------//
private void read (byte[] buffer)
// ---------------------------------------------------------------------------------//
{
int ptr = 0;
do
{
binary2Header = new Binary2Header (buffer, ptr);
System.out.println (binary2Header);
headers.add (binary2Header);
totalBlocks += binary2Header.totalBlocks;
ptr += ((binary2Header.eof - 1) / 128 + 1) * 128 + 128;
} while (binary2Header.filesToFollow > 0);
}
// ---------------------------------------------------------------------------------//
public byte[] getDiskBuffer () throws DiskFullException, VolumeCatalogFullException,
FileAlreadyExistsException, IOException
// ---------------------------------------------------------------------------------//
{
ProdosDisk disk = new ProdosDisk (800, "DiskBrowser");
for (Binary2Header header : headers)
{
byte[] dataBuffer = new byte[header.eof]; // this sux
System.arraycopy (buffer, header.ptr + 128, dataBuffer, 0, dataBuffer.length);
disk.addFile (header.fileName, header.fileType, header.auxType, header.created,
header.modified, dataBuffer, header.eof);
}
disk.close ();
return disk.getBuffer ();
}
// ---------------------------------------------------------------------------------//
@Override
public String toString ()
// ---------------------------------------------------------------------------------//
{
StringBuilder text = new StringBuilder ();
text.append (String.format (
" %-15.15s Files:%5d%n%n",
fileName, headers.size ()));
text.append (" Name Type Auxtyp Modified"
+ " Fmat Length\n");
text.append (String.format ("%s%n", UNDERLINE));
for (Binary2Header header : headers)
text.append (String.format ("%s%n", header.getLine ()));
text.append (String.format ("%s%n", UNDERLINE));
return text.toString ();
}
}
| Java |
package componentes;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class JTextFieldPrazo extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = -8020852662258513751L;
private int iMaxLength;
private JTextField txt;
private long num;
public JTextFieldPrazo(int pMaxLen, JTextField pText) {
super();
iMaxLength = pMaxLen;
txt = pText;
}
public void insertString(int pOffSet, String pString, AttributeSet pAttributSet)
throws BadLocationException {
if (pString == null)
return;
if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres
super.insertString(pOffSet, pString, pAttributSet);
return;
}
long ilen = (getLength() + pString.length());
try {
if(pString.length()==1 && !pString.equals("-"))
setNum(Long.parseLong(pString));
if(pString.equals("0") && txt.getText().length() == 0){
/**return;*/
}
if (ilen <= iMaxLength) // se o comprimento final for menor...
super.insertString(pOffSet, pString, pAttributSet); // ...aceita str
else if (getLength() == iMaxLength)
return; // nada a fazer
else {
String newStr = pString.substring(0, (iMaxLength - getLength()));
super.insertString(pOffSet, newStr, pAttributSet);
}
}
catch(Exception e) {}
}
public long getNum() {
return num;
}
public void setNum(long num) {
this.num = num;
}
} | Java |
CREATE OR REPLACE VIEW clin_measurements.vwsystolicdiastolic AS
SELECT vwmeasurements.fk_patient,
vwpatients.wholename,
vwpatients.fk_person,
vwpatients.surname,
vwpatients.firstname,
vwpatients.title,
vwpatients.sex,
vwpatients.age_numeric,
vwpatients.fk_lu_active_status,
vwpatients.deceased,
vwmeasurements.pk_measurement,
vwmeasurements.consult_date,
vwmeasurements.measurement,
round(vwmeasurements.measurement / 1000::numeric) AS systolic,
vwmeasurements.measurement % 1000::numeric AS diastolic
FROM clin_measurements.vwmeasurements
JOIN contacts.vwpatients ON vwpatients.fk_patient = vwmeasurements.fk_patient
WHERE vwmeasurements.deleted = false AND vwmeasurements.fk_type = 1 AND vwpatients.deceased = false AND vwpatients.fk_lu_active_status = 1
ORDER BY vwmeasurements.fk_patient, vwmeasurements.consult_date DESC;
ALTER TABLE clin_measurements.vwsystolicdiastolic OWNER TO easygp;
GRANT ALL ON TABLE clin_measurements.vwsystolicdiastolic TO staff;
CREATE OR REPLACE VIEW clin_measurements.vwaveragebp AS
SELECT vwsystolicdiastolic.fk_patient,
vwsystolicdiastolic.fk_patient AS pk,
vwsystolicdiastolic.fk_person,
vwsystolicdiastolic.surname,
vwsystolicdiastolic.firstname,
vwsystolicdiastolic.title,
vwsystolicdiastolic.sex,
vwsystolicdiastolic.age_numeric,
round(avg(vwsystolicdiastolic.systolic)) AS average_systolic,
round(avg(vwsystolicdiastolic.diastolic)) AS average_diastolic
FROM clin_measurements.vwsystolicdiastolic
GROUP BY vwsystolicdiastolic.fk_patient, vwsystolicdiastolic.fk_person, vwsystolicdiastolic.surname, vwsystolicdiastolic.firstname, vwsystolicdiastolic.title, vwsystolicdiastolic.sex, vwsystolicdiastolic.age_numeric
ORDER BY vwsystolicdiastolic.surname;
ALTER TABLE clin_measurements.vwaveragebp OWNER TO easygp;
GRANT ALL ON TABLE clin_measurements.vwaveragebp TO staff;
CREATE OR REPLACE VIEW research.vwpatientswithcodedhypertension AS
SELECT DISTINCT ON (vwpatients.surname, vwhealthissues.fk_patient) vwhealthissues.fk_patient AS pk_patient,
vwpatients.fk_person,
vwpatients.firstname,
vwpatients.surname,
vwpatients.sex,
vwpatients.title,
vwpatients.age_numeric,
vwpatients.fk_lu_active_status,
vwpatients.person_deleted,
vwpatients.deceased
FROM clin_history.vwhealthissues
JOIN contacts.vwpatients ON vwpatients.fk_patient = vwhealthissues.fk_patient
WHERE vwhealthissues.fk_code = 'K86005'::text OR vwhealthissues.fk_code = 'K85004'::text
ORDER BY vwpatients.surname;
ALTER TABLE research.vwpatientswithcodedhypertension OWNER TO easygp;
GRANT ALL ON TABLE research.vwpatientswithcodedhypertension TO staff;
update db.lu_version set lu_minor = 488; | Java |
using System;
using System.IO;
using System.Linq;
namespace FocalLengthAnalyzer
{
public class Program
{
public void Main(string[] args)
{
if (args.Count()<1) {
Console.WriteLine("Please pass the path to the directory with jpeg files as the first argument.");
return;
}
if (!Directory.Exists(args[0])) {
Console.WriteLine($"Error: directory {args[0]} does not exits.");
return;
}
var analyzer = new Analyzer();
analyzer.AnalyzeDirectoryContent(args[0]);
}
}
}
| Java |
explain what are they and common ones, and how important are they?
| Java |
#include <stdio.h>
#include <stdlib.h>
//#include <elf.h>
#define ELF_MAGIC 16
//#define MEM_ALLOC_H(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Ehdr));
//#define MEM_ALLOC_S(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Shdr));
#define VALIDATE(ptr) if (!(ptr)) {\
fprintf(stdout, "%s", "Returned NULL\n");\
exit(1);\
}
typedef unsigned short int myElf32_Half;
typedef unsigned int myElf32_Word;
typedef struct {
unsigned char magic_num[ELF_MAGIC];
myElf32_Half elfh_type;
myElf32_Half elfh_machine;
myElf32_Word elfh_version;
myElf32_Word elfh_entry;
myElf32_Word elfh_phoff;
myElf32_Word elfh_shoff;
myElf32_Word elfh_flags;
myElf32_Half elfh_ehsize;
myElf32_Half elfh_phentsize;
myElf32_Half elfh_phnum;
myElf32_Half elfh_shentsize;
myElf32_Half elfh_shnum;
myElf32_Half elfh_shstrndx;
} myElf32_Ehdr;
typedef struct {
myElf32_Word sech_name;
myElf32_Word sech_type;
myElf32_Word sech_flags;
myElf32_Word sech_addr;
myElf32_Word sech_offset;
myElf32_Word sech_size;
myElf32_Word sech_link;
myElf32_Word sech_info;
myElf32_Word sech_addralign;
myElf32_Word sech_entsize;
} myElf32_Shdr;
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import pprint
import proteindf_bridge as bridge
import logging
import logging.config
def get_rest_of_frame_molecule(frame_molecule, selected_molecule):
# calc the rest
selector = bridge.Select_AtomGroup(selected_molecule)
selected = frame_molecule.select(selector)
rest_molecule = frame_molecule ^ selected
return rest_molecule
def assign_rest_molecule(rest_molecule, output_atom_group,
model_id="model_1", chain_id="Z", res_name="UNK"):
chain = bridge.AtomGroup()
res = bridge.AtomGroup()
res.name = res_name
atom_id = 1
for atom in rest_molecule.get_atom_list():
res.set_atom(atom_id, atom)
atom_id += 1
chain.set_group(1, res)
output_atom_group[model_id].set_group(chain_id, chain)
def main():
parser = argparse.ArgumentParser(
description='restructure brd file by reference file')
parser.add_argument('target_brd_path',
nargs=1,
help='target brd file')
parser.add_argument('ref_brd_path',
nargs=1,
help='reference brd file')
parser.add_argument('-o', '--output_path',
nargs=1,
default=["output.brd"])
parser.add_argument('-r', '--range',
nargs=1,
default=[1.0E-5])
parser.add_argument('-v', '--verbose',
action='store_true',
default=False)
args = parser.parse_args()
# print(args)
target_brd_path = args.target_brd_path[0]
ref_brd_path = args.ref_brd_path[0]
output_path = args.output_path[0]
range = float(args.range[0])
verbose = args.verbose
if verbose:
print("target: {}".format(target_brd_path))
print("reference: {}".format(ref_brd_path))
# load
target_ag = bridge.load_atomgroup(target_brd_path)
ref_ag = bridge.load_atomgroup(ref_brd_path)
# matching
#target_selector = bridge.Select_AtomGroup(target_ag)
#restructured = ref_ag.select(target_selector)
# calc the rest
#rest_of_target = get_rest_of_frame_molecule(target_ag, restructured)
#assign_rest_molecule(rest_of_target, restructured)
restructured = target_ag.restructure(ref_ag, range)
if output_path:
if verbose:
print("output brd file: {}".format(output_path))
bridge.save_atomgroup(restructured, output_path)
if __name__ == '__main__':
#import cProfile
#pr = cProfile.Profile()
# pr.enable()
main()
# pr.disable()
# pr.dump_stats('program.profile')
| Java |
package se.vidstige.jadb;
import se.vidstige.jadb.managers.Bash;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class JadbDevice {
public enum State {
Unknown,
Offline,
Device,
Recovery,
BootLoader
};
private final String serial;
private final ITransportFactory transportFactory;
JadbDevice(String serial, String type, ITransportFactory tFactory) {
this.serial = serial;
this.transportFactory = tFactory;
}
static JadbDevice createAny(JadbConnection connection) {
return new JadbDevice(connection);
}
private JadbDevice(ITransportFactory tFactory) {
serial = null;
this.transportFactory = tFactory;
}
private State convertState(String type) {
switch (type) {
case "device": return State.Device;
case "offline": return State.Offline;
case "bootloader": return State.BootLoader;
case "recovery": return State.Recovery;
default: return State.Unknown;
}
}
private Transport getTransport() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:transport-any");
transport.verifyResponse();
} else {
transport.send("host:transport:" + serial);
transport.verifyResponse();
}
return transport;
}
public String getSerial() {
return serial;
}
public State getState() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:get-state");
transport.verifyResponse();
} else {
transport.send("host-serial:" + serial + ":get-state");
transport.verifyResponse();
}
State state = convertState(transport.readString());
transport.close();
return state;
}
/** <p>Execute a shell command.</p>
*
* <p>For Lollipop and later see: {@link #execute(String, String...)}</p>
*
* @param command main command to run. E.g. "ls"
* @param args arguments to the command.
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream executeShell(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream()));
}
/**
*
* @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with
* Stream.copy(in, out), it is possible to achieve the same effect.
*/
@Deprecated
public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
if (output != null) {
AdbFilterOutputStream out = new AdbFilterOutputStream(output);
try {
transport.readResponseTo(out);
} finally {
out.close();
}
}
}
/** <p>Execute a command with raw binary output.</p>
*
* <p>Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary
* data with that version or later. For earlier versions of Android, use
* {@link #executeShell(String, String...)}.</p>
*
* @param command main command to run, e.g. "screencap"
* @param args arguments to the command, e.g. "-p".
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream execute(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "exec:" + shellLine.toString());
return new BufferedInputStream(transport.getInputStream());
}
/**
* Builds a command line string from the command and its arguments.
*
* @param command the command.
* @param args the list of arguments.
* @return the command line.
*/
private StringBuilder buildCmdLine(String command, String... args) {
StringBuilder shellLine = new StringBuilder(command);
for (String arg : args) {
shellLine.append(" ");
shellLine.append(Bash.quote(arg));
}
return shellLine;
}
public List<RemoteFile> list(String remotePath) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("LIST", remotePath);
List<RemoteFile> result = new ArrayList<RemoteFile>();
for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) {
result.add(dent);
}
return result;
}
private int getMode(File file) {
//noinspection OctalInteger
return 0664;
}
public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("SEND", remote.getPath() + "," + Integer.toString(mode));
sync.sendStream(source);
sync.sendStatus("DONE", (int) lastModified);
sync.verifyStatus();
}
public void push(File local, RemoteFile remote) throws IOException, JadbException {
FileInputStream fileStream = new FileInputStream(local);
push(fileStream, local.lastModified(), getMode(local), remote);
fileStream.close();
}
public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("RECV", remote.getPath());
sync.readChunksTo(destination);
}
public void pull(RemoteFile remote, File local) throws IOException, JadbException {
FileOutputStream fileStream = new FileOutputStream(local);
pull(remote, fileStream);
fileStream.close();
}
private void send(Transport transport, String command) throws IOException, JadbException {
transport.send(command);
transport.verifyResponse();
}
@Override
public String toString() {
return "Device: " + serial;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((serial == null) ? 0 : serial.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JadbDevice other = (JadbDevice) obj;
if (serial == null) {
if (other.serial != null)
return false;
} else if (!serial.equals(other.serial))
return false;
return true;
}
}
| Java |
import RPi.GPIO as GPIO
KnockPin = 11
LedPin = 12
Led_status = 1
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
def swLed(ev=None):
global Led_status
Led_status = not Led_status
GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on)
print "LED: " + ("on" if Led_status else "off")
def loop():
GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling
while True:
pass # Don't do anything
def destroy():
GPIO.output(LedPin, GPIO.LOW) # led off
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
| Java |
/*
* Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0.
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.icgc.dcc.submission.server.repository;
import static org.icgc.dcc.submission.core.model.QUser.user;
import java.util.List;
import org.icgc.dcc.submission.core.model.QUser;
import org.icgc.dcc.submission.core.model.User;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.NonNull;
public class UserRepository extends AbstractRepository<User, QUser> {
@Autowired
public UserRepository(@NonNull Morphia morphia, @NonNull Datastore datastore) {
super(morphia, datastore, user);
}
public List<User> findUsers() {
return list();
}
public User findUserByUsername(@NonNull String username) {
return uniqueResult(entity.username.eq(username));
}
public User saveUser(@NonNull User user) {
save(user);
return user;
}
public User updateUser(@NonNull User user) {
return findAndModify(
createQuery()
.filter("username", user.getUsername()),
createUpdateOperations()
.set("failedAttempts", user.getFailedAttempts()),
false, false);
}
}
| Java |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file 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, or (at your option)
# any later version.
# This file 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 GNU Emacs; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA,
# Python program to check if the input year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
| Java |
/*
* 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 Code.Domain;
/**
*
* @author Andres Orduz Grimaldo
*/
public class Jornada {
private int id;
private String nombre;
private TipoJornada tipoJornada;
private Anio anio;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public TipoJornada getTipoJornada() {
return tipoJornada;
}
public void setTipoJornada(TipoJornada tipoJornada) {
this.tipoJornada = tipoJornada;
}
public Anio getAnio() {
return anio;
}
public void setAnio(Anio anio) {
this.anio = anio;
}
} | Java |
<?php
/*
* Copyright (c) 2013 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
*/
namespace WC_Order_Search_Admin\AlgoliaSearch;
use Exception;
class ClientContext
{
/**
* @var string
*/
public $applicationID;
/**
* @var string
*/
public $apiKey;
/**
* @var array
*/
public $readHostsArray;
/**
* @var array
*/
public $writeHostsArray;
/**
* @var resource
*/
public $curlMHandle;
/**
* @var string
*/
public $adminAPIKey;
/**
* @var string
*/
public $endUserIP;
/**
* @var string
*/
public $algoliaUserToken;
/**
* @var int
*/
public $connectTimeout;
/**
* @var FailingHostsCache
*/
private $failingHostsCache;
/**
* @param string|null $applicationID
* @param string|null $apiKey
* @param array|null $hostsArray
* @param bool $placesEnabled
* @param FailingHostsCache|null $failingHostsCache
*
* @throws Exception
*/
public function __construct($applicationID = null, $apiKey = null, $hostsArray = null, $placesEnabled = false, \WC_Order_Search_Admin\AlgoliaSearch\FailingHostsCache $failingHostsCache = null)
{
// connect timeout of 1s by default
$this->connectTimeout = 1;
// global timeout of 30s by default
$this->readTimeout = 30;
// search timeout of 5s by default
$this->searchTimeout = 5;
$this->applicationID = $applicationID;
$this->apiKey = $apiKey;
$this->readHostsArray = $hostsArray;
$this->writeHostsArray = $hostsArray;
if ($this->readHostsArray == null || count($this->readHostsArray) == 0) {
$this->readHostsArray = $this->getDefaultReadHosts($placesEnabled);
$this->writeHostsArray = $this->getDefaultWriteHosts();
}
if (($this->applicationID == null || mb_strlen($this->applicationID) == 0) && $placesEnabled === false) {
throw new \Exception('AlgoliaSearch requires an applicationID.');
}
if (($this->apiKey == null || mb_strlen($this->apiKey) == 0) && $placesEnabled === false) {
throw new \Exception('AlgoliaSearch requires an apiKey.');
}
$this->curlMHandle = null;
$this->adminAPIKey = null;
$this->endUserIP = null;
$this->algoliaUserToken = null;
$this->rateLimitAPIKey = null;
$this->headers = array();
if ($failingHostsCache === null) {
$this->failingHostsCache = new \WC_Order_Search_Admin\AlgoliaSearch\InMemoryFailingHostsCache();
} else {
$this->failingHostsCache = $failingHostsCache;
}
$this->rotateHosts();
}
/**
* @param bool $placesEnabled
*
* @return array
*/
private function getDefaultReadHosts($placesEnabled)
{
if ($placesEnabled) {
$hosts = array('places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, 'places-dsn.algolia.net');
return $hosts;
}
$hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, $this->applicationID . '-dsn.algolia.net');
return $hosts;
}
/**
* @return array
*/
private function getDefaultWriteHosts()
{
$hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, $this->applicationID . '.algolia.net');
return $hosts;
}
/**
* Closes eventually opened curl handles.
*/
public function __destruct()
{
if (is_resource($this->curlMHandle)) {
curl_multi_close($this->curlMHandle);
}
}
/**
* @param $curlHandle
*
* @return resource
*/
public function getMHandle($curlHandle)
{
if (!is_resource($this->curlMHandle)) {
$this->curlMHandle = curl_multi_init();
}
curl_multi_add_handle($this->curlMHandle, $curlHandle);
return $this->curlMHandle;
}
/**
* @param $curlHandle
*/
public function releaseMHandle($curlHandle)
{
curl_multi_remove_handle($this->curlMHandle, $curlHandle);
}
/**
* @param string $ip
*/
public function setForwardedFor($ip)
{
$this->endUserIP = $ip;
}
/**
* @param string $token
*/
public function setAlgoliaUserToken($token)
{
$this->algoliaUserToken = $token;
}
/**
* @param string $adminAPIKey
* @param string $endUserIP
* @param string $rateLimitAPIKey
*/
public function setRateLimit($adminAPIKey, $endUserIP, $rateLimitAPIKey)
{
$this->adminAPIKey = $adminAPIKey;
$this->endUserIP = $endUserIP;
$this->rateLimitAPIKey = $rateLimitAPIKey;
}
/**
* Disables the rate limit.
*/
public function disableRateLimit()
{
$this->adminAPIKey = null;
$this->endUserIP = null;
$this->rateLimitAPIKey = null;
}
/**
* @param string $key
* @param string $value
*/
public function setExtraHeader($key, $value)
{
$this->headers[$key] = $value;
}
/**
* @param string $host
*/
public function addFailingHost($host)
{
$this->failingHostsCache->addFailingHost($host);
}
/**
* @return FailingHostsCache
*/
public function getFailingHostsCache()
{
return $this->failingHostsCache;
}
/**
* This method is called to pass on failing hosts.
* If the host is first either in the failingHosts array, we
* rotate the array to ensure the next API call will be directly made with a working
* host. This mainly ensures we don't add the equivalent of the connection timeout value to each
* request to the API.
*/
public function rotateHosts()
{
$failingHosts = $this->failingHostsCache->getFailingHosts();
$i = 0;
while ($i <= count($this->readHostsArray) && in_array($this->readHostsArray[0], $failingHosts)) {
$i++;
$this->readHostsArray[] = array_shift($this->readHostsArray);
}
$i = 0;
while ($i <= count($this->writeHostsArray) && in_array($this->writeHostsArray[0], $failingHosts)) {
$i++;
$this->writeHostsArray[] = array_shift($this->writeHostsArray);
}
}
}
| Java |
MyTestRepo
==========
j
A Test Repo
| Java |
<?php
/* @var $this yii\web\View */
use yii\data\ActiveDataProvider;
use yii\widgets\ListView;
/* @var $books array */
/* @var $book \app\models\Books */
/* @var $booksPhotos \app\models\BooksPhotos */
/* @var $booksDataProvider ActiveDataProvider */
/* @var $popularBooksDataProvider ActiveDataProvider */
$this->title = Yii::t('seo','{appName} - Coding books | Programming Library', ['appName' => \Yii::$app->name]);
$this->registerMetaTag([
'name' => 'description',
'content' => Yii::t('seo', 'CoBooks is an online library consisting of books about programming, management of IT projects and other areas related to IT. Site for free online reading and downloading books in different formats.')
]);
?>
<div class="row clearfix text-center">
<h2 class="title-one">
<?= Yii::t('seo', 'Free IT e-library') ?>
</h2>
<div id="books-categories" class="portfolio-filter">
<ul class="nav nav-pills text-center">
<li class="active">
<a data-toggle="pill" href="#popular-books">
<?= Yii::t('books', 'Popular Books') ?>
</a>
</li>
<li>
<a data-toggle="pill" href="#last-books">
<?= Yii::t('categories', 'Novelties') ?>
</a>
</li>
</ul>
</div>
<div class="tab-content">
<div id="popular-books" class="tab-pane fade in active">
<div class="books-box">
<?= ListView::widget([
'dataProvider' => $popularBooksDataProvider,
'summary' => false,
'layout' => '{items}',
'itemView' => '/parts/book',
]); ?>
<a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/popular']) ?>">
<?= Yii::t('app', 'View all') ?>
</a>
</div>
</div>
<div id="last-books" class="tab-pane fade">
<div class="books-box">
<?= ListView::widget([
'dataProvider' => $booksDataProvider,
'summary' => false,
'layout' => '{items}',
'itemView' => '/parts/book',
]); ?>
<a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/last']) ?>">
<?= Yii::t('app', 'View all') ?>
</a>
</div>
</div>
</div>
</div>
| Java |
function drawChart(len){
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++){
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;');
}
else{
row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;');
}
for(var j=0; j<len; j++){
var col = document.createElement('div');
if(i%2===0){
if(j%2===0){
col.setAttribute('style','background-color:white; flex: 1;');
}
else{
col.setAttribute('style','background-color:black; flex: 1;');
}
}else{
if(j%2===0){
col.setAttribute('style','background-color:black; flex: 1;');
}
else{
col.setAttribute('style','background-color:white; flex: 1;');
}
}
row.appendChild(col);
}
box.appendChild(row);
}
document.body.appendChild(box);
}
drawChart(5); | Java |
package com.tage.rpgutil.client.gui;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import cpw.mods.fml.common.eventhandler.Cancelable;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.EventPriority;
@Cancelable
public class GuiHealth extends Event
{
public static enum ElementType
{
ARMOR,
HEALTH,
}
} | Java |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using common;
using jm726.lib.wrapper;
using jm726.lib.wrapper.logger;
namespace jm726.lib.wrapper.logger {
/// <summary>
/// Class which uses the ISpy interface to record all method calls to a given object. These are recorded to Xml.
/// Can also play back recordings
///
/// ONLY PUBLIC PROPERTIES WITH GETTERS _AND_ SETTERS WILL BE LOGGED CORRECTLY
/// </summary>
/// <typeparam name="TToLog">The interface which is being logged.</typeparam>
public class XmlLogWriter<TToLog> : Wrapper<TToLog>, IXmlLogWriter<TToLog> where TToLog : class {
#region Private Fields
/// <summary>
/// The log4net logger object used to log information to the console or log events.
/// </summary>
private readonly ILog _logger;
/// <summary>
/// The name of this logger. This is the name of the type being logged with '_Logger' added onto the end.
/// </summary>
private readonly string _name;
/// <summary>
/// The XML document which stores the event logging document as it is being built.
/// </summary>
private XmlDocument _doc;
/// <summary>
/// The root XML node to which all events are to be appended as children.
/// </summary>
private XmlNode _root;
/// <summary>
/// The XML document being built up to log all the events happening to the wrapped instance of TToLog.
/// </summary>
private DateTime _lastEvent;
/// <summary>
/// Wether or not events are to be logged currently.
/// </summary>
private bool _logging;
/// <summary>
/// Whether or not to serialize the return value of the method.
/// </summary>
private bool _recordForPlayback;
#endregion
#region XmlLogWriter Properties
/// <inheritdoc />
public XmlDocument Log {
get { return _doc; }
}
#endregion
#region Constructor
/// <summary>
/// Constructor which creates a generic logger. Instantiates a series of helper fields and stores the TToLog instance which is to be wrapped by this logger.
/// </summary>
/// <param name="spy">The instance of TToLog which this logger will log calls to.</param>
public XmlLogWriter(TToLog instance, bool recordForPlayback = false, bool recursive = true)
: base(instance, "XmlLogWriter", recursive) {
_lastEvent = default(DateTime);
_recordForPlayback = recordForPlayback;
_name = typeof(TToLog).FullName + "_Logger";
_logger = LogManager.GetLogger(_name);
_doc = new XmlDocument();
XmlNode declaration = _doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
_doc.AppendChild(declaration);
}
#endregion
#region Override Abstract Methods from Wrapper
public override void ReportMethodCallVoid(string methodName, object[] parameters) {
if (!_logging) {
CallMethod(methodName, parameters);
return;
}
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
}
public override object ReportMethodCallReturn(string methodName, object[] parameters) {
if (!_logging)
return CallMethod(methodName, parameters);
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return m.Return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument, _recordForPlayback);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
return m.Return;
}
public override void ReportEventTriggered(string eventName, object[] parameters) {
//Do Nothing
}
/// <summary>
/// Log the time at which a method call was made.
/// </summary>
private XmlAttribute GetTimeAttr() {
XmlAttribute time = _doc.CreateAttribute("Time");
if (_lastEvent.Equals(default(DateTime)))
time.Value = "0";
else
time.Value = DateTime.Now.Subtract(_lastEvent).TotalMilliseconds + "";
_lastEvent = DateTime.Now;
return time;
}
#endregion
#region XmlLogWriter Methods
/// <inheritdoc />
public void StartRecording() {
if (_root != null)
_doc.RemoveChild(_root);
XmlNode root = _doc.CreateElement("Events");
_doc.AppendChild(root);
StartRecording(_doc);
}
public void StartRecording(XmlDocument doc) {
XmlNodeList roots = doc.GetElementsByTagName("Events");
if (roots.Count == 0)
throw new ArgumentException("Unable to append events to supplied XML document. Document is not in the correct format");
_doc = doc;
_doc.NodeInserted += (source, args) => {
if (args.NewParent.Name.Equals("Events"))
_lastEvent = DateTime.Now;
};
_root = roots[0];
_lastEvent = default(DateTime);
_logging = true;
}
/// <inheritdoc />
public void StopRecording() {
_logging = false;
}
/// <inheritdoc />
public void PauseRecording() {
_lastEvent = DateTime.Now;
_logging = false;
}
/// <inheritdoc />
public void RestartRecording() {
_logging = false;
}
#endregion
#region Util
/// <summary>
/// Used for extensibility.
///
/// Override this and check the type of the argument to define special behaviour for special types.
/// Original defined so that instance specific IDs can be swapped to general but less unique names in the XML
/// which can then be resolved back to new specific IDs when the sequence is played back.
/// </summary>
/// <param name="arg">The argument to swap for a different type.</param>
/// <returns>The type to swap the argument to.</returns>
protected virtual XmlNode SwitchArgument(ParameterInfo param, object arg) {
return null;
}
#endregion
}
} | Java |
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2017 Igor Mironchik
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/>.
*/
#ifndef TREE__CAMERA_CONTROLLER_HPP__INCLUDED
#define TREE__CAMERA_CONTROLLER_HPP__INCLUDED
// Qt include.
#include <Qt3DCore/QEntity>
// C++ include.
#include <memory>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
class QCamera;
}
QT_END_NAMESPACE
//
// CameraController
//
class CameraControllerPrivate;
class CameraController Q_DECL_FINAL
: public Qt3DCore::QEntity
{
Q_OBJECT
public:
CameraController( Qt3DRender::QCamera * camera,
Qt3DCore::QEntity * parent );
~CameraController();
private slots:
void _q_onTriggered( float );
private:
friend class CameraControllerPrivate;
Q_DISABLE_COPY( CameraController )
std::unique_ptr< CameraControllerPrivate > d;
}; // class CameraController
#endif // TREE__CAMERA_CONTROLLER_HPP__INCLUDED
| Java |
.ui-multiselect { padding:4px 2px 4px 4px; text-align:left }
.ui-multiselect span.ui-icon { float:right }
.ui-multiselect-single .ui-multiselect-checkboxes input { left:-9999px; position:absolute !important; top: auto !important; }
.ui-multiselect-single .ui-multiselect-checkboxes label { padding:5px !important }
.ui-multiselect-header { margin-bottom:3px; padding:3px 0 3px 4px; }
.ui-multiselect-header ul { font-size:0.9em }
.ui-multiselect-header ul li { float:left; padding:0 10px 0 0; }
.ui-multiselect-header a { text-decoration:none; }
.ui-multiselect-header a:hover { text-decoration:underline; }
.ui-multiselect-header span.ui-icon { float:left; }
.ui-multiselect-header .ui-multiselect-close { float:right; padding-right:0; text-align:right; }
.ui-multiselect-menu { display:none; padding:3px; position:absolute; text-align: left; }
.ui-multiselect-checkboxes { overflow-y:auto; position:relative; }
.ui-multiselect-checkboxes label { border:1px solid transparent; cursor:default; display:block; padding:3px 1px; }
.ui-multiselect-checkboxes label input { position:relative; top:1px }
.ui-multiselect-checkboxes label img { height: 30px; vertical-align: middle; padding-right: 3px;}
.ui-multiselect-checkboxes li { clear:both; font-size:0.9em; list-style: none; padding-right:3px; }
.ui-multiselect-checkboxes .ui-multiselect-optgroup { padding: 3px; }
.ui-multiselect-columns { display: inline-block; vertical-align: top; }
.ui-multiselect-checkboxes .ui-multiselect-optgroup a { border-bottom:1px solid; cursor: pointer; display:block; font-weight:bold; margin:1px 0; padding:3px; text-align:center; text-decoration:none; }
@media print{
.ui-multiselect-menu {display: none;}
}
| Java |
# Copyright 2015 Allen Institute for Brain Science
# This file is part of Allen SDK.
#
# Allen SDK 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, version 3 of the License.
#
# Allen SDK 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 Allen SDK. If not, see <http://www.gnu.org/licenses/>.
from allensdk.api.api import Api
import os, json
from collections import OrderedDict
class BiophysicalPerisomaticApi(Api):
_NWB_file_type = 'NWB'
_SWC_file_type = '3DNeuronReconstruction'
_MOD_file_type = 'BiophysicalModelDescription'
_FIT_file_type = 'NeuronalModelParameters'
def __init__(self, base_uri=None):
super(BiophysicalPerisomaticApi, self).__init__(base_uri)
self.cache_stimulus = True
self.ids = {}
self.sweeps = []
self.manifest = {}
def build_rma(self, neuronal_model_id, fmt='json'):
'''Construct a query to find all files related to a neuronal model.
Parameters
----------
neuronal_model_id : integer or string representation
key of experiment to retrieve.
fmt : string, optional
json (default) or xml
Returns
-------
string
RMA query url.
'''
include_associations = ''.join([
'neuronal_model_template(well_known_files(well_known_file_type)),',
'specimen',
'(ephys_result(well_known_files(well_known_file_type)),'
'neuron_reconstructions(well_known_files(well_known_file_type)),',
'ephys_sweeps),',
'well_known_files(well_known_file_type)'])
criteria_associations = ''.join([
("[id$eq%d]," % (neuronal_model_id)),
include_associations])
return ''.join([self.rma_endpoint,
'/query.',
fmt,
'?q=',
'model::NeuronalModel,',
'rma::criteria,',
criteria_associations,
',rma::include,',
include_associations])
def read_json(self, json_parsed_data):
'''Get the list of well_known_file ids from a response body
containing nested sample,microarray_slides,well_known_files.
Parameters
----------
json_parsed_data : dict
Response from the Allen Institute Api RMA.
Returns
-------
list of strings
Well known file ids.
'''
self.ids = {
'stimulus': {},
'morphology': {},
'modfiles': {},
'fit': {}
}
self.sweeps = []
if 'msg' in json_parsed_data:
for neuronal_model in json_parsed_data['msg']:
if 'well_known_files' in neuronal_model:
for well_known_file in neuronal_model['well_known_files']:
if ('id' in well_known_file and
'path' in well_known_file and
self.is_well_known_file_type(well_known_file,
BiophysicalPerisomaticApi._FIT_file_type)):
self.ids['fit'][str(well_known_file['id'])] = \
os.path.split(well_known_file['path'])[1]
if 'neuronal_model_template' in neuronal_model:
neuronal_model_template = neuronal_model['neuronal_model_template']
if 'well_known_files' in neuronal_model_template:
for well_known_file in neuronal_model_template['well_known_files']:
if ('id' in well_known_file and
'path' in well_known_file and
self.is_well_known_file_type(well_known_file,
BiophysicalPerisomaticApi._MOD_file_type)):
self.ids['modfiles'][str(well_known_file['id'])] = \
os.path.join('modfiles',
os.path.split(well_known_file['path'])[1])
if 'specimen' in neuronal_model:
specimen = neuronal_model['specimen']
if 'neuron_reconstructions' in specimen:
for neuron_reconstruction in specimen['neuron_reconstructions']:
if 'well_known_files' in neuron_reconstruction:
for well_known_file in neuron_reconstruction['well_known_files']:
if ('id' in well_known_file and
'path' in well_known_file and
self.is_well_known_file_type(well_known_file,
BiophysicalPerisomaticApi._SWC_file_type)):
self.ids['morphology'][str(well_known_file['id'])] = \
os.path.split(well_known_file['path'])[1]
if 'ephys_result' in specimen:
ephys_result = specimen['ephys_result']
if 'well_known_files' in ephys_result:
for well_known_file in ephys_result['well_known_files']:
if ('id' in well_known_file and
'path' in well_known_file and
self.is_well_known_file_type(well_known_file,
BiophysicalPerisomaticApi._NWB_file_type)):
self.ids['stimulus'][str(well_known_file['id'])] = \
"%d.nwb" % (ephys_result['id'])
self.sweeps = [sweep['sweep_number']
for sweep in specimen['ephys_sweeps']
if sweep['stimulus_name'] != 'Test']
return self.ids
def is_well_known_file_type(self, wkf, name):
'''Check if a structure has the expected name.
Parameters
----------
wkf : dict
A well-known-file structure with nested type information.
name : string
The expected type name
See Also
--------
read_json: where this helper function is used.
'''
try:
return wkf['well_known_file_type']['name'] == name
except:
return False
def get_well_known_file_ids(self, neuronal_model_id):
'''Query the current RMA endpoint with a neuronal_model id
to get the corresponding well known file ids.
Returns
-------
list
A list of well known file id strings.
'''
rma_builder_fn = self.build_rma
json_traversal_fn = self.read_json
return self.do_query(rma_builder_fn, json_traversal_fn, neuronal_model_id)
def create_manifest(self,
fit_path='',
stimulus_filename='',
swc_morphology_path='',
sweeps=[]):
'''Generate a json configuration file with parameters for a
a biophysical experiment.
Parameters
----------
fit_path : string
filename of a json configuration file with cell parameters.
stimulus_filename : string
path to an NWB file with input currents.
swc_morphology_path : string
file in SWC format.
sweeps : array of integers
which sweeps in the stimulus file are to be used.
'''
self.manifest = OrderedDict()
self.manifest['biophys'] = [{
'model_file': [ 'manifest.json', fit_path ]
}]
self.manifest['runs'] = [{
'sweeps': sweeps
}]
self.manifest['neuron'] = [{
'hoc': [ 'stdgui.hoc', 'import3d.hoc' ]
}]
self.manifest['manifest'] = [
{
'type': 'dir',
'spec': '.',
'key': 'BASEDIR'
},
{
'type': 'dir',
'spec': 'work',
'key': 'WORKDIR',
'parent': 'BASEDIR'
},
{
'type': 'file',
'spec': swc_morphology_path,
'key': 'MORPHOLOGY'
},
{
'type': 'dir',
'spec': 'modfiles',
'key': 'MODFILE_DIR'
},
{
'type': 'file',
'format': 'NWB',
'spec': stimulus_filename,
'key': 'stimulus_path'
},
{
'parent_key': 'WORKDIR',
'type': 'file',
'format': 'NWB',
'spec': stimulus_filename,
'key': 'output'
}
]
def cache_data(self,
neuronal_model_id,
working_directory=None):
'''Take a an experiment id, query the Api RMA to get well-known-files
download the files, and store them in the working directory.
Parameters
----------
neuronal_model_id : int or string representation
found in the neuronal_model table in the api
working_directory : string
Absolute path name where the downloaded well-known files will be stored.
'''
if working_directory is None:
working_directory = self.default_working_directory
try:
os.stat(working_directory)
except:
os.mkdir(working_directory)
work_dir = os.path.join(working_directory, 'work')
try:
os.stat(work_dir)
except:
os.mkdir(work_dir)
modfile_dir = os.path.join(working_directory, 'modfiles')
try:
os.stat(modfile_dir)
except:
os.mkdir(modfile_dir)
well_known_file_id_dict = self.get_well_known_file_ids(neuronal_model_id)
for key, id_dict in well_known_file_id_dict.items():
if (not self.cache_stimulus) and (key == 'stimulus'):
continue
for well_known_id, filename in id_dict.items():
well_known_file_url = self.construct_well_known_file_download_url(well_known_id)
cached_file_path = os.path.join(working_directory, filename)
self.retrieve_file_over_http(well_known_file_url, cached_file_path)
fit_path = self.ids['fit'].values()[0]
stimulus_filename = self.ids['stimulus'].values()[0]
swc_morphology_path = self.ids['morphology'].values()[0]
sweeps = sorted(self.sweeps)
self.create_manifest(fit_path,
stimulus_filename,
swc_morphology_path,
sweeps)
manifest_path = os.path.join(working_directory, 'manifest.json')
with open(manifest_path, 'wb') as f:
f.write(json.dumps(self.manifest, indent=2))
| Java |
/* eslint-disable no-self-assign */
import Game from '../../../../gui/html/js/game';
import { Plugin } from '../../../../gui/html/js/plugin';
import Translator from '../../../../gui/html/js/translator';
jest.mock('../../../../gui/html/js/dom');
jest.mock('../../../../gui/html/js/filters');
describe('Game', () => {
const l10n = new Translator();
const defaultDerivedPluginMetadata = {
name: 'test',
isActive: false,
isDirty: false,
isEmpty: false,
isMaster: false,
isLightPlugin: false,
loadsArchive: false,
messages: [],
suggestedTags: [],
currentTags: []
};
const gameData = {
folder: 'test',
generalMessages: [
{
type: 'say',
text: 'test',
language: 'en',
condition: ''
}
],
masterlist: { revision: '0', date: '' },
groups: { masterlist: [], userlist: [] },
plugins: [defaultDerivedPluginMetadata],
bashTags: []
};
describe('#constructor()', () => {
test("should set folder to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.folder).toBe('test');
});
test("should set generalMessages to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.generalMessages).toEqual([
{
type: 'say',
text: 'test',
language: 'en',
condition: ''
}
]);
});
test("should set masterlist to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.masterlist).toEqual({ revision: '0', date: '' });
});
test("should construct plugins from the object's plugins value", () => {
const game = new Game(gameData, l10n);
expect(game.plugins.length).toBe(1);
expect(game.plugins[0]).toHaveProperty('update');
expect(game.plugins[0].name).toBe('test');
expect(game.plugins[0].cardZIndex).toBe(1);
});
test("should set oldLoadOrder to an empty array even if the object's value if defined", () => {
const game = new Game(gameData, l10n);
expect(game.oldLoadOrder).toEqual([]);
});
});
describe('#folder', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('loot-game-folder-change', handleEvent);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener('loot-game-folder-change', handleEvent);
game.folder = game.folder;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
handleEvent = evt => {
expect(evt.detail.folder).toBe('other test');
done();
};
document.addEventListener('loot-game-folder-change', handleEvent);
game.folder = 'other test';
});
});
describe('#generalMessages', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener(
'loot-game-global-messages-change',
handleEvent
);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener(
'loot-game-global-messages-change',
handleEvent
);
game.generalMessages = game.generalMessages;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new and old message strings differ', done => {
const newMessages = [
{
type: 'say',
text: 'bar',
language: 'en',
condition: ''
}
];
handleEvent = evt => {
expect(evt.detail.messages).toEqual(newMessages);
expect(evt.detail.totalDiff).toBe(0);
expect(evt.detail.errorDiff).toBe(0);
expect(evt.detail.warningDiff).toBe(0);
done();
};
document.addEventListener(
'loot-game-global-messages-change',
handleEvent
);
game.generalMessages = newMessages;
});
test('setting value should dispatch an event if the new and old message type counts differ', done => {
const newMessages = [
{
type: 'warn',
text: 'foo',
language: 'en',
condition: ''
},
{
type: 'error',
text: 'bar',
language: 'en',
condition: ''
}
];
game.generalMessages = [];
handleEvent = evt => {
expect(evt.detail.messages).toEqual(newMessages);
expect(evt.detail.totalDiff).toBe(2);
expect(evt.detail.errorDiff).toBe(1);
expect(evt.detail.warningDiff).toBe(1);
done();
};
document.addEventListener(
'loot-game-global-messages-change',
handleEvent
);
game.generalMessages = newMessages;
});
});
describe('#masterlist', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('loot-game-masterlist-change', handleEvent);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener('loot-game-masterlist-change', handleEvent);
game.masterlist = game.masterlist;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
const newMasterlist = {
revision: 'foo',
date: 'bar'
};
handleEvent = evt => {
expect(evt.detail).toEqual(newMasterlist);
done();
};
document.addEventListener('loot-game-masterlist-change', handleEvent);
game.masterlist = newMasterlist;
});
});
describe('#plugins', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('loot-game-plugins-change', handleEvent);
});
test('setting value should dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done();
};
document.addEventListener('loot-game-plugins-change', handleEvent);
game.plugins = game.plugins;
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
const newMessages = [
{
type: 'warn',
text: 'foo',
language: 'en',
condition: ''
},
{
type: 'error',
text: 'bar',
language: 'en',
condition: ''
}
];
const newPlugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'a',
isActive: true,
messages: [newMessages[0]]
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'b',
isDirty: true,
messages: [{ ...newMessages[0], type: 'say' }]
})
];
handleEvent = evt => {
expect(evt.detail.valuesAreTotals).toBe(true);
expect(evt.detail.totalMessageNo).toBe(4);
expect(evt.detail.warnMessageNo).toBe(2);
expect(evt.detail.errorMessageNo).toBe(1);
expect(evt.detail.totalPluginNo).toBe(2);
expect(evt.detail.activePluginNo).toBe(1);
expect(evt.detail.dirtyPluginNo).toBe(1);
done();
};
document.addEventListener('loot-game-plugins-change', handleEvent);
game.generalMessages = newMessages;
game.plugins = newPlugins;
});
});
describe('groups', () => {
test("get should return the game's groups", () => {
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
const game = new Game({ ...gameData, groups }, l10n);
expect(game.groups).toStrictEqual([
{ name: 'a', after: [], isUserAdded: false },
{ name: 'b', after: [], isUserAdded: true }
]);
});
});
describe('#setGroups()', () => {
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
afterEach(() => {
document.removeEventListener('loot-game-groups-change', handleEvent);
});
test('should merge the given masterlist and userlist groups arrays', () => {
const game = new Game(gameData, l10n);
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
game.setGroups(groups);
expect(game.groups).toStrictEqual([
{ name: 'a', after: [], isUserAdded: false },
{ name: 'b', after: [], isUserAdded: true }
]);
});
test('should dispatch an event', done => {
handleEvent = () => {
done();
};
document.addEventListener('loot-game-groups-change', handleEvent);
const game = new Game(gameData, l10n);
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
game.setGroups(groups);
});
});
describe('#getContent()', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should return an object of two empty arrays if there is no game data', () => {
game.plugins = [];
game.generalMessages = [];
expect(game.getContent()).toEqual({
messages: [],
plugins: []
});
});
test('should return a structure containing converted plugin and message structures', () => {
game.generalMessages = [
{
type: 'say',
condition: 'file("foo.esp")',
language: 'fr',
text: 'Bonjour le monde'
}
];
game.plugins = [
new Plugin({
name: 'foo',
crc: 0xdeadbeef,
version: '1.0',
isActive: true,
isEmpty: true,
isMaster: false,
isLightPlugin: false,
loadsArchive: true,
group: 'group1',
messages: [
{
type: 'warn',
condition: 'file("bar.esp")',
language: 'en',
text: 'Hello world'
}
],
currentTags: [
{
name: 'Relev',
isAddition: true,
condition: ''
}
],
suggestedTags: [
{
name: 'Delev',
isAddition: true,
condition: ''
}
],
isDirty: true
})
];
expect(game.getContent()).toEqual({
messages: game.generalMessages,
plugins: [
{
name: game.plugins[0].name,
crc: game.plugins[0].crc,
version: game.plugins[0].version,
isActive: game.plugins[0].isActive,
isEmpty: game.plugins[0].isEmpty,
loadsArchive: game.plugins[0].loadsArchive,
group: game.plugins[0].group,
messages: game.plugins[0].messages,
currentTags: game.plugins[0].currentTags,
suggestedTags: game.plugins[0].suggestedTags,
isDirty: game.plugins[0].isDirty
}
]
});
});
});
describe('#getPluginNames()', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should return an empty array if there are no plugins', () => {
game.plugins = [];
expect(game.getPluginNames().length).toBe(0);
});
test('should return an array of plugin filenames if there are plugins', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
isActive: true,
messages: [{ type: 'warn', text: '', language: 'en', condition: '' }]
})
];
expect(game.getPluginNames()).toEqual(['foo']);
});
});
describe('#getGroupPluginNames()', () => {
let game: Game;
beforeEach(() => {
const plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
group: 'test group'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar',
group: 'other group'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foobar',
group: 'test group'
})
];
game = new Game({ ...gameData, plugins }, l10n);
});
test('should return an empty array if there are no plugins in the given group', () => {
expect(game.getGroupPluginNames('empty group').length).toBe(0);
});
test('should return an array of filenames of plugins in the given group', () => {
expect(game.getGroupPluginNames('test group')).toEqual(['foo', 'foobar']);
});
});
describe('#setSortedPlugins', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('loot-game-plugins-change', handleEvent);
});
test('should append new plugins to the plugins array', () => {
game.setSortedPlugins([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
})
]);
expect(game.plugins[0].name).toBe('foo');
});
test('should update existing plugins with new data', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
isActive: true,
messages: [{ type: 'warn', text: '', language: 'en', condition: '' }]
})
];
game.setSortedPlugins([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
crc: 0xdeadbeef
})
]);
expect(game.plugins[0].crc).toBe(0xdeadbeef);
expect(game.plugins[0].isActive).toBe(false);
});
test('should reorder plugins to given order', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
})
];
game.setSortedPlugins([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
})
]);
expect(game.plugins[0].name).toBe('bar');
expect(game.plugins[1].name).toBe('foo');
});
test('should store old load order', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
})
];
game.setSortedPlugins([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
})
]);
expect(game.oldLoadOrder[0].name).toBe('foo');
expect(game.oldLoadOrder[1].name).toBe('bar');
});
test('should dispatch an event', done => {
handleEvent = () => {
done();
};
document.addEventListener('loot-game-plugins-change', handleEvent);
game.setSortedPlugins([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
})
]);
});
});
describe('#applySort', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should delete the stored old load order', () => {
game.oldLoadOrder = gameData.plugins.map(p => new Plugin(p));
game.applySort();
expect(game.oldLoadOrder).toEqual([]);
});
});
describe('#cancelSort', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should set the current load order to the given plugins', () => {
const oldLoadOrder = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'baz'
})
];
game.oldLoadOrder = oldLoadOrder;
game.plugins = [oldLoadOrder[2], oldLoadOrder[1], oldLoadOrder[0]];
game.cancelSort(
[{ name: 'baz', loadOrderIndex: 0 }, { name: 'foo' }],
[]
);
expect(game.plugins).toEqual([oldLoadOrder[2], oldLoadOrder[0]]);
});
test('should delete the stored old load order', () => {
game.oldLoadOrder = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar'
})
];
game.cancelSort([], []);
expect(game.oldLoadOrder).toEqual([]);
});
test('should set plugin load order indices using the array passed as the first parameter', () => {
game.oldLoadOrder = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
loadOrderIndex: 1
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar',
loadOrderIndex: 0
})
];
game.cancelSort(
[
{ name: 'bar', loadOrderIndex: 0 },
{ name: 'foo', loadOrderIndex: 2 }
],
[]
);
expect(game.plugins[0].name).toBe('bar');
expect(game.plugins[0].loadOrderIndex).toBe(0);
expect(game.plugins[1].name).toBe('foo');
expect(game.plugins[1].loadOrderIndex).toBe(2);
});
test('should set the general messages to the second passed parameter', () => {
game.oldLoadOrder = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
loadOrderIndex: 1
}),
new Plugin({
...defaultDerivedPluginMetadata,
name: 'bar',
loadOrderIndex: 0
})
];
const messages = [
{
type: 'say',
text: 'foo',
language: 'en',
condition: ''
}
];
game.cancelSort([], messages);
expect(game.generalMessages).toEqual(messages);
});
});
describe('#clearMetadata', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should delete stored userlist data for existing plugins', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
userlist: {
name: '',
after: [],
req: [],
inc: [],
msg: [],
tag: [],
dirty: [],
clean: [],
url: []
}
})
];
game.clearMetadata([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo'
})
]);
expect(game.plugins[0].userlist).toBe(undefined);
});
test('should update existing plugin data', () => {
game.plugins = [
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
isActive: true
})
];
game.clearMetadata([
new Plugin({
...defaultDerivedPluginMetadata,
name: 'foo',
crc: 0xdeadbeef
})
]);
expect(game.plugins[0].crc).toBe(0xdeadbeef);
expect(game.plugins[0].isActive).toBe(false);
});
});
});
| Java |
# == Schema Information
#
# Table name: causes
#
# id :integer not null, primary key
# name :string not null
# description :string
# image_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe Cause, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| Java |
<?php
/**
* The template part for displaying single archive from hospital posts
*
* @package Twenty-Sixteen-Child
*
*
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="entry-title-hospital"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );?>
</header><!-- .entry-header -->
<div class="entry-content-hospital">
<?php
$review_description = get_post_meta($post->ID);
if(!empty($review_description['reviewer_name'][0])){
$reviewer_name = $review_description['reviewer_name'][0];
echo '<h3>'.$reviewer_name.'</h3>';
}
the_post_thumbnail('thumbnail');
the_content();
echo '</br>';
echo get_the_tag_list( '<br>Tags: ', ', ','<br>' );
echo '</br>';
edit_post_link( );
?>
</div><!-- .entry-content-hospital -->
</article><!-- #post-## -->
| Java |
// simplewall
// Copyright (c) 2016-2021 Henry++
#pragma once
#include "routine.h"
#include <winsock2.h>
#include <ws2ipdef.h>
#include <ws2tcpip.h>
#include <windns.h>
#include <mstcpip.h>
#include <iphlpapi.h>
#include <aclapi.h>
#include <dbt.h>
#include <fwpmu.h>
#include <mmsystem.h>
#include <netfw.h>
#include <shlguid.h>
#include <shobjidl.h>
#include <softpub.h>
#include <subauth.h>
#include <mscat.h>
#include "app.h"
#include "rapp.h"
#include "main.h"
#include "resource.h"
DECLSPEC_SELECTANY STATIC_DATA config = {0};
DECLSPEC_SELECTANY PROFILE_DATA profile_info = {0};
DECLSPEC_SELECTANY PR_HASHTABLE apps_table = NULL;
DECLSPEC_SELECTANY PR_LIST rules_list = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE rules_config = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE log_table = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE cache_information = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE cache_resolution = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE colors_table = NULL;
DECLSPEC_SELECTANY PR_ARRAY filter_ids = NULL;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apps = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apply = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules_config = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_loglist = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_profile = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_transaction = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_cache_information = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_cache_resolution = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_WORKQUEUE file_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE log_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE resolver_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE resolve_notify_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE wfp_queue = {0};
DECLSPEC_SELECTANY R_FREE_LIST context_free_list = {0};
DECLSPEC_SELECTANY R_FREE_LIST listview_free_list = {0};
// timers array
DECLSPEC_SELECTANY const LONG64 timer_array[] =
{
2 * 60,
5 * 60,
10 * 60,
30 * 60,
1 * 3600,
2 * 3600,
4 * 3600,
6 * 3600
};
// dropped events callback subscription (win7+)
#ifndef FWP_DIRECTION_IN
#define FWP_DIRECTION_IN 0x00003900L
#endif
#ifndef FWP_DIRECTION_OUT
#define FWP_DIRECTION_OUT 0x00003901L
#endif
#include "controls.h"
#include "db.h"
#include "editor.h"
#include "helper.h"
#include "icons.h"
#include "listview.h"
#include "log.h"
#include "messages.h"
#include "network.h"
#include "notifications.h"
#include "packages.h"
#include "profile.h"
#include "search.h"
#include "security.h"
#include "timer.h"
#include "wfp.h"
| Java |
\section{\-Getopt \-Class \-Reference}
\label{interface_getopt}\index{\-Getopt@{\-Getopt}}
{\ttfamily \#import $<$\-Getopt.\-h$>$}
\subsection*{\-Public \-Member \-Functions}
\begin{DoxyCompactItemize}
\item
(void) -\/ {\bf init\-Getopt\-:}
\item
(\-B\-O\-O\-L) -\/ {\bf response\-Is\-Valid}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Message}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Response\-Status}
\item
(int) -\/ {\bf get\-Response\-Code}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaigns\-Id\-List}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-List}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-Code\-List}
\item
(int) -\/ {\bf get\-Campaign\-Status\-Code\-:}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Campaign\-Status\-:}
\end{DoxyCompactItemize}
\subsection{\-Detailed \-Description}
\doxyref{\-Getopt.\-h}{p.}{_getopt_8h_source} \-Mercury\-\_\-i\-O\-S
\-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved.
\-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}.
\doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version.
\doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details.
\-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-://www.\-gnu.\-org/licenses/}$>$. \-The \doxyref{\-Getopt}{p.}{interface_getopt} object contains the response from a \doxyref{\-Mercury\#getopt}{p.}{} request to the \-Mo\-M\-S \-A\-P\-I.
\-Getopt.\-m \-Mercury\-\_\-i\-O\-S
\-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved.
\-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}.
\doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version.
\doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details.
\-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-://www.\-gnu.\-org/licenses/}$>$.
\subsection{\-Member \-Function \-Documentation}
\index{\-Getopt@{\-Getopt}!get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}}
\index{get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaigns\-Id\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaigns\-Id\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_ae67bd34f9a6eefb6991c0d1ba4f1ab5e}
\-Gets the campaign \-I\-Ds. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaigns \-I\-D.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}}
\index{get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Campaign\-Status\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id}
\end{DoxyParamCaption}
}\label{interface_getopt_ae462b8840809c38907beeb65600207c3}
\-Gets a campaign status.
\begin{DoxyParams}{\-Parameters}
{\em campaign\-Id} & \-The campaign \-I\-D. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-The campaign status of the specified campaign.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}}
\index{get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-Code\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Campaign\-Status\-Code\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id}
\end{DoxyParamCaption}
}\label{interface_getopt_a3c5d5461767b0b60b87640e9bed50fa0}
\-Gets a campaign status code.
\begin{DoxyParams}{\-Parameters}
{\em campaign\-Id} & \-The campaign \-I\-D. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-The campaign status code of the specified campaign.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}}
\index{get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-Code\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-Code\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_a9f7cb55ae8322091c2ed5d6b3778cf96}
\-Gets the campaign status codes. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaign status codes.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}}
\index{get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_ab734e471e2498b2e174e13888e1f47d1}
\-Gets the campaign status. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaigns status.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Message@{get\-Message}}
\index{get\-Message@{get\-Message}!Getopt@{\-Getopt}}
\subsubsection[{get\-Message}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Message
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_acd07f968bb1f707190fcbed50f4ffd5b}
\begin{DoxyReturn}{\-Returns}
\-The \-Message.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Response\-Code@{get\-Response\-Code}}
\index{get\-Response\-Code@{get\-Response\-Code}!Getopt@{\-Getopt}}
\subsubsection[{get\-Response\-Code}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Response\-Code
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_a13d89e7b1be7fd70ca00d4dc8fd4bf76}
\begin{DoxyReturn}{\-Returns}
\-The response \-Code.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Response\-Status@{get\-Response\-Status}}
\index{get\-Response\-Status@{get\-Response\-Status}!Getopt@{\-Getopt}}
\subsubsection[{get\-Response\-Status}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Response\-Status
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_a37a6fb2220efa93c9dbe42888df9607b}
\begin{DoxyReturn}{\-Returns}
\-The response \-Status.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!init\-Getopt\-:@{init\-Getopt\-:}}
\index{init\-Getopt\-:@{init\-Getopt\-:}!Getopt@{\-Getopt}}
\subsubsection[{init\-Getopt\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (void) init\-Getopt\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{url\-Getopt}
\end{DoxyParamCaption}
}\label{interface_getopt_a30a685ebe3d4b445be6a116147f0a524}
\-Initializes a new \doxyref{\-Getopt}{p.}{interface_getopt} response object.
\begin{DoxyParams}{\-Parameters}
{\em url\-Getopt} & \-U\-R\-L for calling requests from \-Mogreet \-A\-P\-I. \\
\hline
\end{DoxyParams}
\index{\-Getopt@{\-Getopt}!response\-Is\-Valid@{response\-Is\-Valid}}
\index{response\-Is\-Valid@{response\-Is\-Valid}!Getopt@{\-Getopt}}
\subsubsection[{response\-Is\-Valid}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-B\-O\-O\-L) response\-Is\-Valid
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{interface_getopt_a9ec6a1ac7941b10d44326c16d88e6332}
\-Checks if the response code is 1. \begin{DoxyReturn}{\-Returns}
\-Y\-E\-S if the response code is 1, \-N\-O if it is not
\end{DoxyReturn}
\-The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize}
\item
\-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-h\item
\-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-m\end{DoxyCompactItemize}
| Java |
#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is 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.
#
# GNUHAWK 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/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in sig_source_i"""
def testScaBasicBehavior(self):
#######################################################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
| Java |
/********************************************************************************
** Form generated from reading UI file 'addECGDialog.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ADDECGDIALOG_H
#define UI_ADDECGDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QWidget *layoutWidget;
QHBoxLayout *hboxLayout;
QSpacerItem *horizontalSpacer_2;
QPushButton *okButton;
QSpacerItem *horizontalSpacer;
QPushButton *cancelButton;
QSpacerItem *horizontalSpacer_3;
QLabel *headLabel;
QLabel *nameLabel;
QCheckBox *checkBox;
QLabel *ECGlabel;
QComboBox *ECGBox;
QLineEdit *nameEdit;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(393, 233);
layoutWidget = new QWidget(Dialog);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(20, 180, 351, 33));
hboxLayout = new QHBoxLayout(layoutWidget);
hboxLayout->setSpacing(6);
hboxLayout->setObjectName(QStringLiteral("hboxLayout"));
hboxLayout->setContentsMargins(0, 0, 0, 0);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer_2);
okButton = new QPushButton(layoutWidget);
okButton->setObjectName(QStringLiteral("okButton"));
hboxLayout->addWidget(okButton);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer);
cancelButton = new QPushButton(layoutWidget);
cancelButton->setObjectName(QStringLiteral("cancelButton"));
hboxLayout->addWidget(cancelButton);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer_3);
headLabel = new QLabel(Dialog);
headLabel->setObjectName(QStringLiteral("headLabel"));
headLabel->setGeometry(QRect(20, 20, 331, 16));
QFont font;
font.setPointSize(10);
font.setBold(true);
font.setWeight(75);
headLabel->setFont(font);
nameLabel = new QLabel(Dialog);
nameLabel->setObjectName(QStringLiteral("nameLabel"));
nameLabel->setGeometry(QRect(20, 70, 47, 13));
QFont font1;
font1.setBold(true);
font1.setWeight(75);
nameLabel->setFont(font1);
checkBox = new QCheckBox(Dialog);
checkBox->setObjectName(QStringLiteral("checkBox"));
checkBox->setGeometry(QRect(20, 110, 231, 17));
checkBox->setFont(font1);
ECGlabel = new QLabel(Dialog);
ECGlabel->setObjectName(QStringLiteral("ECGlabel"));
ECGlabel->setGeometry(QRect(20, 140, 81, 16));
ECGlabel->setFont(font1);
ECGBox = new QComboBox(Dialog);
ECGBox->setObjectName(QStringLiteral("ECGBox"));
ECGBox->setGeometry(QRect(100, 140, 271, 22));
ECGBox->setInsertPolicy(QComboBox::InsertAlphabetically);
nameEdit = new QLineEdit(Dialog);
nameEdit->setObjectName(QStringLiteral("nameEdit"));
nameEdit->setGeometry(QRect(100, 70, 271, 20));
headLabel->raise();
nameLabel->raise();
checkBox->raise();
ECGlabel->raise();
ECGBox->raise();
nameEdit->raise();
layoutWidget->raise();
retranslateUi(Dialog);
QObject::connect(okButton, SIGNAL(clicked()), Dialog, SLOT(accept()));
QObject::connect(cancelButton, SIGNAL(clicked()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Add ECG Rhythm", 0));
okButton->setText(QApplication::translate("Dialog", "OK", 0));
cancelButton->setText(QApplication::translate("Dialog", "Cancel", 0));
headLabel->setText(QApplication::translate("Dialog", "Create a New ECG Rhythm", 0));
#ifndef QT_NO_TOOLTIP
nameLabel->setToolTip(QApplication::translate("Dialog", "The Name of the new ECG Rhythm", 0));
#endif // QT_NO_TOOLTIP
nameLabel->setText(QApplication::translate("Dialog", "Name", 0));
checkBox->setText(QApplication::translate("Dialog", "Copy parameters?", 0));
#ifndef QT_NO_TOOLTIP
ECGlabel->setToolTip(QApplication::translate("Dialog", "The set of predeefined rhythms", 0));
#endif // QT_NO_TOOLTIP
ECGlabel->setText(QApplication::translate("Dialog", "ECG Rythms", 0));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ADDECGDIALOG_H
| Java |
#include "trayicon.h"
#include <QApplication>
#include <QMenu>
#include <QTimer>
#include <conf/addressgroup.h>
#include <conf/appgroup.h>
#include <conf/confmanager.h>
#include <conf/firewallconf.h>
#include <form/controls/mainwindow.h>
#include <fortsettings.h>
#include <manager/hotkeymanager.h>
#include <manager/windowmanager.h>
#include <user/iniuser.h>
#include <util/guiutil.h>
#include <util/iconcache.h>
#include "traycontroller.h"
namespace {
const char *const eventSingleClick = "singleClick";
const char *const eventDoubleClick = "doubleClick";
const char *const eventMiddleClick = "middleClick";
const char *const actionShowPrograms = "Programs";
const char *const actionShowOptions = "Options";
const char *const actionShowStatistics = "Statistics";
const char *const actionShowTrafficGraph = "TrafficGraph";
const char *const actionSwitchFilterEnabled = "FilterEnabled";
const char *const actionSwitchStopTraffic = "StopTraffic";
const char *const actionSwitchStopInetTraffic = "StopInetTraffic";
const char *const actionSwitchAutoAllowPrograms = "AutoAllowPrograms";
QString clickNameByType(TrayIcon::ClickType clickType)
{
switch (clickType) {
case TrayIcon::SingleClick:
return eventSingleClick;
case TrayIcon::DoubleClick:
return eventDoubleClick;
case TrayIcon::MiddleClick:
return eventMiddleClick;
default:
return QString();
}
}
QString actionNameByType(TrayIcon::ActionType actionType)
{
switch (actionType) {
case TrayIcon::ActionShowPrograms:
return actionShowPrograms;
case TrayIcon::ActionShowOptions:
return actionShowOptions;
case TrayIcon::ActionShowStatistics:
return actionShowStatistics;
case TrayIcon::ActionShowTrafficGraph:
return actionShowTrafficGraph;
case TrayIcon::ActionSwitchFilterEnabled:
return actionSwitchFilterEnabled;
case TrayIcon::ActionSwitchStopTraffic:
return actionSwitchStopTraffic;
case TrayIcon::ActionSwitchStopInetTraffic:
return actionSwitchStopInetTraffic;
case TrayIcon::ActionSwitchAutoAllowPrograms:
return actionSwitchAutoAllowPrograms;
default:
return QString();
}
}
TrayIcon::ActionType actionTypeByName(const QString &name)
{
if (name.isEmpty())
return TrayIcon::ActionNone;
if (name == actionShowPrograms)
return TrayIcon::ActionShowPrograms;
if (name == actionShowOptions)
return TrayIcon::ActionShowOptions;
if (name == actionShowStatistics)
return TrayIcon::ActionShowStatistics;
if (name == actionShowTrafficGraph)
return TrayIcon::ActionShowTrafficGraph;
if (name == actionSwitchFilterEnabled)
return TrayIcon::ActionSwitchFilterEnabled;
if (name == actionSwitchStopTraffic)
return TrayIcon::ActionSwitchStopTraffic;
if (name == actionSwitchStopInetTraffic)
return TrayIcon::ActionSwitchStopInetTraffic;
if (name == actionSwitchAutoAllowPrograms)
return TrayIcon::ActionSwitchAutoAllowPrograms;
return TrayIcon::ActionNone;
}
TrayIcon::ActionType defaultActionTypeByClick(TrayIcon::ClickType clickType)
{
switch (clickType) {
case TrayIcon::SingleClick:
return TrayIcon::ActionShowPrograms;
case TrayIcon::DoubleClick:
return TrayIcon::ActionShowOptions;
case TrayIcon::MiddleClick:
return TrayIcon::ActionShowStatistics;
default:
return TrayIcon::ActionNone;
}
}
void setActionCheckable(QAction *action, bool checked = false, const QObject *receiver = nullptr,
const char *member = nullptr)
{
action->setCheckable(true);
action->setChecked(checked);
if (receiver) {
QObject::connect(action, SIGNAL(toggled(bool)), receiver, member);
}
}
QAction *addAction(QWidget *widget, const QIcon &icon, const QString &text,
const QObject *receiver = nullptr, const char *member = nullptr, bool checkable = false,
bool checked = false)
{
auto action = new QAction(icon, text, widget);
if (receiver) {
QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
}
if (checkable) {
setActionCheckable(action, checked);
}
widget->addAction(action);
return action;
}
}
TrayIcon::TrayIcon(QObject *parent) :
QSystemTrayIcon(parent), m_trayTriggered(false), m_ctrl(new TrayController(this))
{
setupUi();
setupController();
connect(this, &QSystemTrayIcon::activated, this, &TrayIcon::onTrayActivated);
}
TrayIcon::~TrayIcon()
{
delete m_menu;
}
FortSettings *TrayIcon::settings() const
{
return ctrl()->settings();
}
ConfManager *TrayIcon::confManager() const
{
return ctrl()->confManager();
}
FirewallConf *TrayIcon::conf() const
{
return ctrl()->conf();
}
IniOptions *TrayIcon::ini() const
{
return ctrl()->ini();
}
IniUser *TrayIcon::iniUser() const
{
return ctrl()->iniUser();
}
HotKeyManager *TrayIcon::hotKeyManager() const
{
return ctrl()->hotKeyManager();
}
WindowManager *TrayIcon::windowManager() const
{
return ctrl()->windowManager();
}
void TrayIcon::onMouseClicked(TrayIcon::ClickType clickType)
{
QAction *action = m_clickActions[clickType];
if (action) {
action->trigger();
}
}
void TrayIcon::onTrayActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
m_trayTriggered = true;
QTimer::singleShot(QApplication::doubleClickInterval(), this, [&] {
if (m_trayTriggered) {
m_trayTriggered = false;
onMouseClicked(SingleClick);
}
});
break;
case QSystemTrayIcon::DoubleClick:
if (m_trayTriggered) {
m_trayTriggered = false;
onMouseClicked(DoubleClick);
}
break;
case QSystemTrayIcon::MiddleClick:
m_trayTriggered = false;
onMouseClicked(MiddleClick);
break;
case QSystemTrayIcon::Context:
m_trayTriggered = false;
showTrayMenu(QCursor::pos());
break;
default:
break;
}
}
void TrayIcon::updateTrayIcon(bool alerted)
{
const auto icon = alerted ? GuiUtil::overlayIcon(":/icons/sheild-96.png", ":/icons/error.png")
: IconCache::icon(":/icons/sheild-96.png");
this->setIcon(icon);
}
void TrayIcon::showTrayMenu(const QPoint &pos)
{
m_menu->popup(pos);
}
void TrayIcon::updateTrayMenu(bool onlyFlags)
{
if (!onlyFlags) {
updateAppGroupActions();
}
updateTrayMenuFlags();
updateHotKeys();
}
void TrayIcon::setupController()
{
connect(windowManager(), &WindowManager::optWindowChanged, this,
&TrayIcon::updateTrayMenuFlags);
connect(windowManager(), &WindowManager::graphWindowChanged, m_graphAction,
&QAction::setChecked);
connect(settings(), &FortSettings::passwordCheckedChanged, this,
&TrayIcon::updateTrayMenuFlags);
connect(ctrl(), &TrayController::retranslateUi, this, &TrayIcon::retranslateUi);
retranslateUi();
}
void TrayIcon::retranslateUi()
{
m_programsAction->setText(tr("Programs"));
m_optionsAction->setText(tr("Options"));
m_statisticsAction->setText(tr("Statistics"));
m_zonesAction->setText(tr("Zones"));
m_graphAction->setText(tr("Traffic Graph"));
m_filterEnabledAction->setText(tr("Filter Enabled"));
m_stopTrafficAction->setText(tr("Stop Traffic"));
m_stopInetTrafficAction->setText(tr("Stop Internet Traffic"));
m_autoAllowProgsAction->setText(tr("Auto-Allow New Programs"));
m_quitAction->setText(tr("Quit"));
}
void TrayIcon::setupUi()
{
this->setToolTip(QApplication::applicationDisplayName());
setupTrayMenu();
updateTrayMenu();
updateTrayIcon();
updateClickActions();
}
void TrayIcon::setupTrayMenu()
{
m_menu = new QMenu();
m_programsAction = addAction(m_menu, IconCache::icon(":/icons/application.png"), QString(),
windowManager(), SLOT(showProgramsWindow()));
addHotKey(m_programsAction, iniUser()->hotKeyPrograms());
m_optionsAction = addAction(m_menu, IconCache::icon(":/icons/cog.png"), QString(),
windowManager(), SLOT(showOptionsWindow()));
addHotKey(m_optionsAction, iniUser()->hotKeyOptions());
m_statisticsAction = addAction(m_menu, IconCache::icon(":/icons/chart_bar.png"), QString(),
windowManager(), SLOT(showStatisticsWindow()));
addHotKey(m_statisticsAction, iniUser()->hotKeyStatistics());
m_graphAction = addAction(m_menu, IconCache::icon(":/icons/action_log.png"), QString(),
windowManager(), SLOT(switchGraphWindow()), true, !!windowManager()->graphWindow());
addHotKey(m_graphAction, iniUser()->hotKeyGraph());
m_zonesAction = addAction(m_menu, IconCache::icon(":/icons/ip_class.png"), QString(),
windowManager(), SLOT(showZonesWindow()));
addHotKey(m_zonesAction, iniUser()->hotKeyZones());
m_menu->addSeparator();
m_filterEnabledAction =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(m_filterEnabledAction, iniUser()->hotKeyFilter());
m_stopTrafficAction =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(m_stopTrafficAction, iniUser()->hotKeyStopTraffic());
m_stopInetTrafficAction =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(m_stopInetTrafficAction, iniUser()->hotKeyStopInetTraffic());
m_autoAllowProgsAction =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(m_autoAllowProgsAction, iniUser()->hotKeyAllowAllNew());
m_menu->addSeparator();
for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) {
QAction *a = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
if (i < 12) {
const QString shortcutText =
iniUser()->hotKeyAppGroupModifiers() + "+F" + QString::number(i + 1);
addHotKey(a, shortcutText);
}
m_appGroupActions.append(a);
}
m_menu->addSeparator();
m_quitAction = addAction(m_menu, QIcon(), tr("Quit"), this, SLOT(quitProgram()));
addHotKey(m_quitAction, iniUser()->hotKeyQuit());
}
void TrayIcon::updateTrayMenuFlags()
{
const bool editEnabled = (!settings()->isPasswordRequired() && !windowManager()->optWindow());
m_filterEnabledAction->setEnabled(editEnabled);
m_stopTrafficAction->setEnabled(editEnabled);
m_stopInetTrafficAction->setEnabled(editEnabled);
m_autoAllowProgsAction->setEnabled(editEnabled);
m_filterEnabledAction->setChecked(conf()->filterEnabled());
m_stopTrafficAction->setChecked(conf()->stopTraffic());
m_stopInetTrafficAction->setChecked(conf()->stopInetTraffic());
m_autoAllowProgsAction->setChecked(conf()->allowAllNew());
int appGroupIndex = 0;
for (QAction *action : qAsConst(m_appGroupActions)) {
if (!action->isVisible())
break;
const bool appGroupEnabled = conf()->appGroupEnabled(appGroupIndex++);
action->setEnabled(editEnabled);
action->setChecked(appGroupEnabled);
}
}
void TrayIcon::updateAppGroupActions()
{
const int appGroupsCount = conf()->appGroups().count();
for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) {
QAction *action = m_appGroupActions.at(i);
QString menuLabel;
bool visible = false;
if (i < appGroupsCount) {
const AppGroup *appGroup = conf()->appGroups().at(i);
menuLabel = appGroup->menuLabel();
visible = true;
}
action->setText(menuLabel);
action->setVisible(visible);
action->setEnabled(visible);
}
}
void TrayIcon::saveTrayFlags()
{
conf()->setFilterEnabled(m_filterEnabledAction->isChecked());
conf()->setStopTraffic(m_stopTrafficAction->isChecked());
conf()->setStopInetTraffic(m_stopInetTrafficAction->isChecked());
conf()->setAllowAllNew(m_autoAllowProgsAction->isChecked());
int i = 0;
for (AppGroup *appGroup : conf()->appGroups()) {
const QAction *action = m_appGroupActions.at(i++);
appGroup->setEnabled(action->isChecked());
}
confManager()->saveFlags();
}
void TrayIcon::switchTrayFlag(bool checked)
{
if (iniUser()->confirmTrayFlags()) {
const auto action = qobject_cast<QAction *>(sender());
Q_ASSERT(action);
if (!windowManager()->showQuestionBox(
tr("Are you sure to switch the \"%1\"?").arg(action->text()))) {
action->setChecked(!checked);
return;
}
}
saveTrayFlags();
}
void TrayIcon::quitProgram()
{
if (iniUser()->confirmQuit()) {
if (!windowManager()->showQuestionBox(tr("Are you sure you want to quit the program?")))
return;
}
windowManager()->quitByCheckPassword();
}
void TrayIcon::addHotKey(QAction *action, const QString &shortcutText)
{
if (shortcutText.isEmpty())
return;
const QKeySequence shortcut = QKeySequence::fromString(shortcutText);
hotKeyManager()->addAction(action, shortcut);
}
void TrayIcon::updateHotKeys()
{
hotKeyManager()->setEnabled(iniUser()->hotKeyEnabled());
}
void TrayIcon::removeHotKeys()
{
hotKeyManager()->removeActions();
}
TrayIcon::ActionType TrayIcon::clickEventActionType(ClickType clickType) const
{
const QString eventName = clickNameByType(clickType);
const QString actionName = iniUser()->trayAction(eventName);
const ActionType actionType = actionTypeByName(actionName);
return (actionType != ActionNone) ? actionType : defaultActionTypeByClick(clickType);
}
void TrayIcon::setClickEventActionType(ClickType clickType, ActionType actionType)
{
const QString eventName = clickNameByType(clickType);
const QString actionName = actionNameByType(actionType);
iniUser()->setTrayAction(eventName, actionName);
updateClickActions();
}
void TrayIcon::updateClickActions()
{
m_clickActions[SingleClick] = clickActionFromIni(SingleClick);
m_clickActions[DoubleClick] = clickActionFromIni(DoubleClick);
m_clickActions[MiddleClick] = clickActionFromIni(MiddleClick);
}
QAction *TrayIcon::clickActionFromIni(ClickType clickType) const
{
const ActionType actionType = clickEventActionType(clickType);
return clickActionByType(actionType);
}
QAction *TrayIcon::clickActionByType(ActionType actionType) const
{
switch (actionType) {
case TrayIcon::ActionShowPrograms:
return m_programsAction;
case TrayIcon::ActionShowOptions:
return m_optionsAction;
case TrayIcon::ActionShowStatistics:
return m_statisticsAction;
case TrayIcon::ActionShowTrafficGraph:
return m_graphAction;
case TrayIcon::ActionSwitchFilterEnabled:
return m_filterEnabledAction;
case TrayIcon::ActionSwitchStopTraffic:
return m_stopTrafficAction;
case TrayIcon::ActionSwitchStopInetTraffic:
return m_stopInetTrafficAction;
case TrayIcon::ActionSwitchAutoAllowPrograms:
return m_autoAllowProgsAction;
}
return nullptr;
}
| Java |
package at.ltd.tools.fw.peer2peerFirewall.backend.entities.comparator;
@FunctionalInterface
public interface ComparatorLambda<T> {
int comp(T t1, T t2);
}
| Java |
// Obdi - a REST interface and GUI for deploying software
// Copyright (C) 2014 Mark Clarkson
//
// 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 main
import (
"encoding/json"
"fmt"
"net"
"net/rpc"
"os"
)
type PostedData struct {
Hostname string
}
// ***************************************************************************
// GO RPC PLUGIN
// ***************************************************************************
func (t *Plugin) GetRequest(args *Args, response *[]byte) error {
// List all keys
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
sa := ScriptArgs{
ScriptName: "saltkey-showkeys.sh",
CmdArgs: "",
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var jobid int64
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) PostRequest(args *Args, response *[]byte) error {
// Check for required query string entries
if len(args.QueryString["hostname"]) == 0 {
ReturnError("'type' must be set", response)
return nil
}
if len(args.QueryString["type"]) == 0 {
ReturnError("'type' must be set", response)
return nil
}
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
// Get the ScriptId from the scripts table for:
scriptName := ""
if args.QueryString["type"][0] == "accept" {
scriptName = "saltkey-acceptkeys.sh"
} else {
scriptName = "saltkey-rejectkeys.sh"
}
var jobid int64
sa := ScriptArgs{
ScriptName: scriptName,
CmdArgs: args.QueryString["hostname"][0],
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) DeleteRequest(args *Args, response *[]byte) error {
// Check for required query string entries
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
var jobid int64
sa := ScriptArgs{
ScriptName: "saltkey-deletekeys.sh",
CmdArgs: args.PathParams["id"],
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) HandleRequest(args *Args, response *[]byte) error {
// All plugins must have this.
if len(args.QueryType) > 0 {
switch args.QueryType {
case "GET":
t.GetRequest(args, response)
return nil
case "POST":
t.PostRequest(args, response)
return nil
case "DELETE":
t.DeleteRequest(args, response)
return nil
}
ReturnError("Internal error: Invalid HTTP request type for this plugin "+
args.QueryType, response)
return nil
} else {
ReturnError("Internal error: HTTP request type was not set", response)
return nil
}
}
func main() {
//logit("Plugin starting")
plugin := new(Plugin)
rpc.Register(plugin)
listener, err := net.Listen("tcp", ":"+os.Args[1])
if err != nil {
txt := fmt.Sprintf("Listen error. ", err)
logit(txt)
}
//logit("Plugin listening on port " + os.Args[1])
if conn, err := listener.Accept(); err != nil {
txt := fmt.Sprintf("Accept error. ", err)
logit(txt)
} else {
//logit("New connection established")
rpc.ServeConn(conn)
}
}
| Java |
package com.shumz.think.ex004;
public class ExFour03 {
public ExFour03() {
System.out.println("An instance of ExFour03 was created...");
}
public static void main(String[] args) {
new ExFour03();
}
}
| Java |
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst);
int v7_r6 = v6_r4 ^ v6_r4;
atomic_store_explicit(&vars[3+v7_r6], 1, memory_order_seq_cst);
int v9_r9 = atomic_load_explicit(&vars[3], memory_order_seq_cst);
int v10_r10 = v9_r9 ^ v9_r9;
atomic_store_explicit(&vars[4+v10_r10], 1, memory_order_seq_cst);
int v12_r13 = atomic_load_explicit(&vars[4], memory_order_seq_cst);
int v13_cmpeq = (v12_r13 == v12_r13);
if (v13_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
atomic_store_explicit(&vars[0], 1, memory_order_seq_cst);
int v18 = (v2_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[1], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[4], 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v14 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v15 = (v14 == 2);
int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v17_conj = v15 & v16;
if (v17_conj == 1) assert(0);
return 0;
}
| Java |
package TFC.Handlers.Client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.event.ForgeSubscribe;
import org.lwjgl.opengl.GL11;
import TFC.Core.TFC_Climate;
import TFC.Core.TFC_Settings;
import TFC.Core.Player.PlayerManagerTFC;
import TFC.Core.Player.TFC_PlayerClient;
import TFC.Food.FoodStatsTFC;
import TFC.Items.Tools.ItemChisel;
import TFC.Items.Tools.ItemCustomHoe;
public class RenderOverlayHandler
{
@ForgeSubscribe
public void render(RenderGameOverlayEvent.Pre event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
}
@ForgeSubscribe
public void render(RenderGameOverlayEvent.Post event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
ScaledResolution sr = event.resolution;
int healthRowHeight = sr.getScaledHeight() - 39;
int armorRowHeight = healthRowHeight - 10;
TFC_PlayerClient playerclient = ((TFC.Core.Player.TFC_PlayerClient)Minecraft.getMinecraft().thePlayer.getPlayerBase("TFC Player Client"));
if(playerclient != null)
{
//Draw Health
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
Minecraft.getMinecraft().renderEngine.bindTexture("/bioxx/icons.png");
this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 0, 90, 10);
float maxHealth = playerclient.getMaxHealth();
float percentHealth = Minecraft.getMinecraft().thePlayer.getHealth()/maxHealth;
this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 9, (int) (90*percentHealth), 9);
//Draw Food and Water
FoodStatsTFC foodstats = playerclient.getFoodStatsTFC();
int foodLevel = foodstats.getFoodLevel();
int preFoodLevel = foodstats.getPrevFoodLevel();
float waterLevel = foodstats.waterLevel;
float percentFood = foodLevel/100f;
float percentWater = waterLevel/foodstats.getMaxWater(Minecraft.getMinecraft().thePlayer);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 18, 90, 5);
if(playerclient.guishowFoodRestoreAmount)
{
float percentFood2 = Math.min(percentFood + playerclient.guiFoodRestoreAmount/100f, 1);
GL11.glColor4f(0.0F, 0.6F, 0.0F, 0.3F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*(percentFood2)), 5);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*percentFood), 5);
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 28, 90, 5);
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 33, (int) (90*percentWater), 5);
//Render Tool Mode
if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemCustomHoe)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().hoeMode;
this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 38, 20, 20);
}
else if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemChisel)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().ChiselMode;
this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 58, 20, 20);
}
}
Minecraft.getMinecraft().renderEngine.resetBoundTexture();
}
@ForgeSubscribe
public void renderText(RenderGameOverlayEvent.Text event)
{
if(Minecraft.getMinecraft().gameSettings.showDebugInfo || TFC_Settings.enableDebugMode)
{
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
int xCoord = (int)player.posX;
int yCoord = (int)player.posY;
int zCoord = (int)player.posZ;
event.left.add(String.format("rain: %.0f, temp: %.2f, evt: %.3f", new Object[] {
TFC_Climate.getRainfall(xCoord, yCoord, zCoord),
TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord),
TFC_Climate.manager.getEVTLayerAt(xCoord, zCoord).floatdata1}));
event.left.add("Health: " + player.getHealth());
}
}
public void drawTexturedModalRect(int par1, int par2, int par3, int par4, int par5, int par6)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(par1 + 0, par2 + par6, 0.0, (par3 + 0) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + par6, 0.0, (par3 + par5) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + 0, 0.0, (par3 + par5) * f, (par4 + 0) * f1);
tessellator.addVertexWithUV(par1 + 0, par2 + 0, 0.0, (par3 + 0) * f, (par4 + 0) * f1);
tessellator.draw();
}
}
| Java |
namespace ContaLibre.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | Java |
var path = require('path')
module.exports = {
// Webpack aliases
aliases: {
quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),
src: path.resolve(__dirname, '../src'),
assets: path.resolve(__dirname, '../src/assets'),
components: path.resolve(__dirname, '../src/components')
},
// Progress Bar Webpack plugin format
// https://github.com/clessg/progress-bar-webpack-plugin#options
progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)',
// Default theme to build with ('ios' or 'mat')
defaultTheme: 'mat',
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
publicPath: '',
productionSourceMap: false,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css']
},
dev: {
env: require('./dev.env'),
cssSourceMap: true,
// auto open browser or not
openBrowser: true,
publicPath: '/',
port: 8081,
// If for example you are using Quasar Play
// to generate a QR code then on each dev (re)compilation
// you need to avoid clearing out the console, so set this
// to "false", otherwise you can set it to "true" to always
// have only the messages regarding your last (re)compilation.
clearConsoleOnRebuild: false,
// Proxy your API if using any.
// Also see /build/script.dev.js and search for "proxy api requests"
// https://github.com/chimurai/http-proxy-middleware
proxyTable: {}
}
}
/*
* proxyTable example:
*
proxyTable: {
// proxy all requests starting with /api
'/api': {
target: 'https://some.address.com/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
*/
| Java |
//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
// Copyright (c) 2002-2011 Merkur ( devs@emule-project.net / http://www.emule-project.net )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//
#include <wx/wx.h>
#include <wx/mstream.h>
#include <wx/tokenzr.h>
#include "updownclient.h" // Needed for CUpDownClient
#include "SharedFileList.h" // Needed for CSharedFileList
#include <protocol/Protocols.h>
#include <protocol/ed2k/Client2Client/TCP.h>
#include <protocol/ed2k/ClientSoftware.h>
#include <protocol/kad/Client2Client/UDP.h>
#include <protocol/kad2/Constants.h>
#include <protocol/kad2/Client2Client/TCP.h>
#include <protocol/kad2/Client2Client/UDP.h>
#include <common/ClientVersion.h>
#include <tags/ClientTags.h>
#include <zlib.h> // Needed for inflateEnd
#include <common/Format.h> // Needed for CFormat
#include "SearchList.h" // Needed for CSearchList
#include "DownloadQueue.h" // Needed for CDownloadQueue
#include "UploadQueue.h" // Needed for CUploadQueue
#include "IPFilter.h" // Needed for CIPFilter
#include "ServerConnect.h" // Needed for CServerConnect
#include "ClientCredits.h" // Needed for CClientCredits
#include "ClientCreditsList.h" // Needed for CClientCreditsList
#include "Server.h" // Needed for CServer
#include "Preferences.h" // Needed for CPreferences
#include "MemFile.h" // Needed for CMemFile
#include "Packet.h" // Needed for CPacket
#include "Friend.h" // Needed for CFriend
#include "ClientList.h" // Needed for CClientList
#ifndef AMULE_DAEMON
#include "amuleDlg.h" // Needed for CamuleDlg
#include "CaptchaDialog.h" // Needed for CCaptchaDialog
#include "CaptchaGenerator.h"
#include "ChatWnd.h" // Needed for CChatWnd
#endif
#include "amule.h" // Needed for theApp
#include "PartFile.h" // Needed for CPartFile
#include "ClientTCPSocket.h" // Needed for CClientTCPSocket
#include "ListenSocket.h" // Needed for CListenSocket
#include "FriendList.h" // Needed for CFriendList
#include "Statistics.h" // Needed for theStats
#include "ClientUDPSocket.h"
#include "Logger.h"
#include "DataToText.h" // Needed for GetSoftName()
#include "GuiEvents.h" // Needed for Notify_
#include "ServerList.h" // For CServerList
#include "kademlia/kademlia/Kademlia.h"
#include "kademlia/kademlia/Prefs.h"
#include "kademlia/kademlia/Search.h"
#include "kademlia/kademlia/UDPFirewallTester.h"
#include "kademlia/routing/RoutingZone.h"
//#define __PACKET_DEBUG__
// some client testing variables
static wxString crash_name = wxT("[Invalid User Name]");
static wxString empty_name = wxT("[Empty User Name]");
// members of CUpDownClient
// which are used by down and uploading functions
CUpDownClient::CUpDownClient(CClientTCPSocket* sender)
{
#ifdef __DEBUG__
m_socket = NULL;
SetSocket(sender);
#else
m_socket = sender;
#endif
Init();
}
CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend)
{
m_socket = NULL;
Init();
m_nUserPort = in_port;
if(ed2kID && !IsLowID(in_userid)) {
SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid) );
} else {
SetUserIDHybrid( in_userid);
}
//If highID and ED2K source, incoming ID and IP are equal..
//If highID and Kad source, incoming IP needs swap for the IP
if (!HasLowID()) {
if (ed2kID) {
m_nConnectIP = in_userid;
} else {
m_nConnectIP = wxUINT32_SWAP_ALWAYS(in_userid);
}
// Will be on right endianess now
m_FullUserIP = m_nConnectIP;
}
m_dwServerIP = in_serverip;
m_nServerPort = in_serverport;
SetRequestFile( in_reqfile );
ReGetClientSoft();
if (checkfriend) {
if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
m_bFriendSlot = false;
}
}
}
void CUpDownClient::Init()
{
m_linked = 0;
#ifdef DEBUG_ZOMBIE_CLIENTS
m_linkedDebug = false;
#endif
m_bAddNextConnect = false;
credits = NULL;
m_byChatstate = MS_NONE;
m_nKadState = KS_NONE;
m_nChatCaptchaState = CA_NONE;
m_cShowDR = 0;
m_reqfile = NULL; // No file required yet
m_nTransferredUp = 0;
m_cSendblock = 0;
m_cAsked = 0;
msReceivedPrev = 0;
kBpsDown = 0.0;
bytesReceivedCycle = 0;
m_nServerPort = 0;
m_iFileListRequested = 0;
m_dwLastUpRequest = 0;
m_bEmuleProtocol = false;
m_bCompleteSource = false;
m_bFriendSlot = false;
m_bCommentDirty = false;
m_bReaskPending = false;
m_bUDPPending = false;
m_nUserPort = 0;
m_nPartCount = 0;
m_dwLastAskedTime = 0;
m_nDownloadState = DS_NONE;
m_dwUploadTime = 0;
m_nTransferredDown = 0;
m_nUploadState = US_NONE;
m_dwLastBlockReceived = 0;
m_bUnicodeSupport = false;
m_fSentOutOfPartReqs = 0;
m_nCurQueueSessionPayloadUp = 0;
m_addedPayloadQueueSession = 0;
m_nUpDatarate = 0;
m_nSumForAvgUpDataRate = 0;
m_nRemoteQueueRank = 0;
m_nOldRemoteQueueRank = 0;
m_dwLastSourceRequest = 0;
m_dwLastSourceAnswer = 0;
m_dwLastAskedForSources = 0;
m_SecureIdentState = IS_UNAVAILABLE;
m_dwLastSignatureIP = 0;
m_byInfopacketsReceived = IP_NONE;
m_bIsHybrid = false;
m_bIsML = false;
m_Friend = NULL;
m_iRating = 0;
m_nCurSessionUp = 0;
m_clientSoft=SO_UNKNOWN;
m_bRemoteQueueFull = false;
m_HasValidHash = false;
SetWaitStartTime();
m_fHashsetRequesting = 0;
m_fSharedDirectories = 0;
m_lastPartAsked = 0xffff;
m_nUpCompleteSourcesCount= 0;
m_waitingPosition = 0;
m_score = 0;
m_lastRefreshedDLDisplay = 0;
m_bHelloAnswerPending = false;
m_fSentCancelTransfer = 0;
m_Aggressiveness = 0;
m_LastFileRequest = 0;
m_clientState = CS_NEW;
ClearHelloProperties();
m_pReqFileAICHHash = NULL;
m_fSupportsAICH = 0;
m_fAICHRequested = 0;
m_fSupportsLargeFiles = 0;
m_fExtMultiPacket = 0;
m_fIsSpammer = 0;
m_dwUserIP = 0;
m_nConnectIP = 0;
m_dwServerIP = 0;
m_fNeedOurPublicIP = false;
m_bHashsetRequested = false;
m_lastDownloadingPart = 0;
m_uploadingfile = NULL;
m_OSInfo_sent = false;
/* Kad stuff */
SetBuddyID(NULL);
m_nBuddyIP = 0;
m_nBuddyPort = 0;
m_nUserIDHybrid = 0;
m_nSourceFrom = SF_NONE;
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
SetIP(0);
}
/* Statistics */
m_lastClientSoft = (uint32)(-1);
m_lastClientVersion = 0;
/* Creation time (for buddies timeout) */
m_nCreationTime = ::GetTickCount();
m_MaxBlockRequests = STANDARD_BLOCKS_REQUEST; // Safe starting amount
m_last_block_start = 0;
m_lastaverage = 0;
SetLastBuddyPingPongTime();
m_fRequestsCryptLayer = 0;
m_fSupportsCryptLayer = 0;
m_fRequiresCryptLayer = 0;
m_fSupportsSourceEx2 = 0;
m_fSupportsCaptcha = 0;
m_fDirectUDPCallback = 0;
m_dwDirectCallbackTimeout = 0;
m_hasbeenobfuscatinglately = false;
m_cCaptchasSent = 0;
m_cMessagesReceived = 0;
m_cMessagesSent = 0;
}
CUpDownClient::~CUpDownClient()
{
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddDebugLogLineN(logClient, wxT("Client to check for ") + connection_reason + wxT(" was deleted without connection."));
}
#endif
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
// Indicate that we are not anymore on stats
m_lastClientSoft = (uint32)(-1);
// The socket should have been removed in Safe_Delete, but it
// doesn't hurt to have an extra check.
if (m_socket) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
ClearUploadBlockRequests();
ClearDownloadBlockRequests();
DeleteContents(m_WaitingPackets_list);
// Allow detection of deleted clients that didn't go through Safe_Delete
m_clientState = CS_DYING;
}
void CUpDownClient::ClearHelloProperties()
{
m_nUDPPort = 0;
m_byUDPVer = 0;
m_byDataCompVer = 0;
m_byEmuleVersion = 0;
m_bySourceExchange1Ver = 0;
m_byAcceptCommentVer = 0;
m_byExtendedRequestsVer = 0;
m_byCompatibleClient = 0;
m_nKadPort = 0;
m_bySupportSecIdent = 0;
m_bSupportsPreview = 0;
m_nClientVersion = 0;
m_fSharedDirectories = 0;
m_bMultiPacket = 0;
m_fOsInfoSupport = 0;
m_fValueBasedTypeTags = 0;
SecIdentSupRec = 0;
m_byKadVersion = 0;
m_fRequestsCryptLayer = 0;
m_fSupportsCryptLayer = 0;
m_fRequiresCryptLayer = 0;
m_fSupportsSourceEx2 = 0;
m_fSupportsCaptcha = 0;
m_fDirectUDPCallback = 0;
m_bIsHybrid = false;
m_bIsML = false;
m_fNoViewSharedFiles = true; // that's a sensible default to assume until we get the real value
m_bUnicodeSupport = false;
}
bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
uint8 hashsize = data.ReadUInt8();
if ( 16 != hashsize ) {
/*
* Hint: We can not accept other sizes here because:
* - the magic number is spread all over the source
* - the answer packet lacks the size field
*/
throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
}
// eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
ClearHelloProperties();
return ProcessHelloTypePacket(data);
}
void CUpDownClient::Safe_Delete()
{
// Because we are delaying the deletion, we might end up trying to delete
// it twice, however, this is normal and shouldn't trigger any failures
if ( m_clientState == CS_DYING ) {
return;
}
// If called from background, post an event to process it in main thread
if (!wxThread::IsMain()) {
CoreNotify_Client_Delete(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete CoreNotify_Client_Delete")));
return;
}
m_clientState = CS_DYING;
// Make sure client doesn't get deleted until this method is finished
CClientRef ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker")));
// Close the socket to avoid any more connections and related events
if ( m_socket ) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
// Remove the client from the clientlist if we still have it
if ( theApp->clientlist ) {
theApp->clientlist->RemoveClient( this );
}
// Doing what RemoveClient used to do. Just to be sure...
if (theApp->uploadqueue) {
theApp->uploadqueue->RemoveFromUploadQueue(this);
theApp->uploadqueue->RemoveFromWaitingQueue(this);
}
if (theApp->downloadqueue) {
theApp->downloadqueue->RemoveSource(this);
}
// For security, remove it from the lists unconditionally.
Notify_SharedCtrlRemoveClient(ECID(), (CKnownFile*)NULL);
Notify_SourceCtrlRemoveSource(ECID(), (CPartFile*)NULL);
if (IsAICHReqPending()){
m_fAICHRequested = FALSE;
CAICHHashSet::ClientAICHRequestFailed(this);
}
if (m_Friend) {
m_Friend->UnLinkClient(); // this notifies
m_Friend = NULL;
}
if (m_iRating>0 || !m_strComment.IsEmpty()) {
m_iRating = 0;
m_strComment.Clear();
if (m_reqfile) {
m_reqfile->UpdateFileRatingCommentAvail();
}
}
// Ensure that source-counts gets updated in case
// of a source not on the download-queue
SetRequestFile( NULL );
SetUploadFileID(NULL);
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
#ifdef DEBUG_ZOMBIE_CLIENTS
if (m_linked > 1) {
AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked - 1) % GetLinkedFrom());
m_linkedDebug = true;
}
#endif
}
bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
bool bIsMule = ProcessHelloTypePacket(data);
m_bHelloAnswerPending = false;
return bIsMule;
}
bool CUpDownClient::ProcessHelloTypePacket(const CMemFile& data)
{
uint32 dwEmuleTags = 0;
CMD4Hash hash = data.ReadHash();
SetUserHash( hash );
SetUserIDHybrid( data.ReadUInt32() );
uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why?
uint32 tagcount = data.ReadUInt32();
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case CT_NAME:
m_Username = temptag.GetStr();
break;
case CT_VERSION:
m_nClientVersion = temptag.GetInt();
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
case CT_PORT:
nUserPort = temptag.GetInt();
break;
case CT_EMULE_UDPPORTS:
// 16 KAD Port
// 16 UDP Port
SetKadPort((temptag.GetInt() >> 16) & 0xFFFF);
m_nUDPPort = temptag.GetInt() & 0xFFFF;
dwEmuleTags |= 1;
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort % m_nKadPort);
#endif
break;
case CT_EMULE_BUDDYIP:
// 32 BUDDY IP
m_nBuddyIP = temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP % Uint32toStringIP(m_nBuddyIP));
#endif
break;
case CT_EMULE_BUDDYUDP:
// 16 --Reserved for future use--
// 16 BUDDY Port
m_nBuddyPort = (uint16)temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort);
#endif
break;
case CT_EMULE_MISCOPTIONS1: {
// 3 AICH Version (0 = not supported)
// 1 Unicode
// 4 UDP version
// 4 Data compression version
// 4 Secure Ident
// 4 Source Exchange
// 4 Ext. Requests
// 4 Comments
// 1 PeerCache supported
// 1 No 'View Shared Files' supported
// 1 MultiPacket
// 1 Preview
uint32 flags = temptag.GetInt();
m_fSupportsAICH = (flags >> (4*7+1)) & 0x07;
m_bUnicodeSupport = (flags >> 4*7) & 0x01;
m_byUDPVer = (flags >> 4*6) & 0x0f;
m_byDataCompVer = (flags >> 4*5) & 0x0f;
m_bySupportSecIdent = (flags >> 4*4) & 0x0f;
m_bySourceExchange1Ver = (flags >> 4*3) & 0x0f;
m_byExtendedRequestsVer = (flags >> 4*2) & 0x0f;
m_byAcceptCommentVer = (flags >> 4*1) & 0x0f;
m_fNoViewSharedFiles = (flags >> 1*2) & 0x01;
m_bMultiPacket = (flags >> 1*1) & 0x01;
m_fSupportsPreview = (flags >> 1*0) & 0x01;
dwEmuleTags |= 2;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer);
AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer);
AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent);
AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver);
AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer);
AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer);
AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles);
AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket);
AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories);
AddLogLineNS(wxT("That's all."));
#endif
SecIdentSupRec += 1;
break;
}
case CT_EMULE_MISCOPTIONS2:
// 19 Reserved
// 1 Direct UDP Callback supported and available
// 1 Supports ChatCaptchas
// 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
// 1 Requires CryptLayer
// 1 Requests CryptLayer
// 1 Supports CryptLayer
// 1 Reserved (ModBit)
// 1 Ext Multipacket (Hash+Size instead of Hash)
// 1 Large Files (includes support for 64bit tags)
// 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
m_fDirectUDPCallback = (temptag.GetInt() >> 12) & 0x01;
m_fSupportsCaptcha = (temptag.GetInt() >> 11) & 0x01;
m_fSupportsSourceEx2 = (temptag.GetInt() >> 10) & 0x01;
m_fRequiresCryptLayer = (temptag.GetInt() >> 9) & 0x01;
m_fRequestsCryptLayer = (temptag.GetInt() >> 8) & 0x01;
m_fSupportsCryptLayer = (temptag.GetInt() >> 7) & 0x01;
// reserved 1
m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01;
m_fSupportsLargeFiles = (temptag.GetInt() >> 4) & 0x01;
m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f;
dwEmuleTags |= 8;
m_fRequestsCryptLayer &= m_fSupportsCryptLayer;
m_fRequiresCryptLayer &= m_fRequestsCryptLayer;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback);
AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha);
AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2);
AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket);
AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles);
AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion);
AddLogLineNS(wxT("That's all."));
#endif
break;
// Special tag for Compat. Clients Misc options.
case CT_EMULECOMPAT_OPTIONS:
// 1 Operative System Info
// 1 Value-based-type int tags (experimental!)
m_fValueBasedTypeTags = (temptag.GetInt() >> 1*1) & 0x01;
m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01;
break;
case CT_EMULE_VERSION:
// 8 Compatible Client ID
// 7 Mjr Version (Doesn't really matter..)
// 7 Min Version (Only need 0-99)
// 3 Upd Version (Only need 0-5)
// 7 Bld Version (Only need 0-99)
m_byCompatibleClient = (temptag.GetInt() >> 24);
m_nClientVersion = temptag.GetInt() & 0x00ffffff;
m_byEmuleVersion = 0x99;
m_fSharedDirectories = 1;
dwEmuleTags |= 4;
break;
}
}
m_nUserPort = nUserPort;
m_dwServerIP = data.ReadUInt32();
m_nServerPort = data.ReadUInt16();
// Hybrid now has an extra uint32.. What is it for?
// Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) {
uint32 test = data.ReadUInt32();
/*if (test == 'KDLM') below kdlm is converted to ascii values.
This fixes a warning with gcc 3.4.
K=4b D=44 L=4c M=4d
*/
if (test == 0x4b444c4d) { //if it's == "KDLM"
m_bIsML=true;
} else{
m_bIsHybrid = true;
m_fSharedDirectories = 1;
}
}
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
}
if (thePrefs::AddServersFromClient()) {
CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP));
addsrv->SetListName(addsrv->GetAddress());
if (!theApp->AddServer(addsrv)) {
delete addsrv;
}
}
//(a)If this is a highID user, store the ID in the Hybrid format.
//(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
//(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
//because they will send a ID that is the same as their IP..
if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) {
SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP));
}
// get client credits
CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash);
if (credits == NULL){
credits = pFoundCredits;
if (!theApp->clientlist->ComparePriorUserhash(m_dwUserIP, m_nUserPort, pFoundCredits)){
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
Ban();
}
} else if (credits != pFoundCredits){
// userhash change ok, however two hours "waittime" before it can be used
credits = pFoundCredits;
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
Ban();
}
if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::ProcessHelloTypePacket m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
SetFriendSlot(false);
}
ReGetClientSoft();
m_byInfopacketsReceived |= IP_EDONKEYPROTPACK;
// check if at least CT_EMULEVERSION was received, all other tags are optional
bool bIsMule = (dwEmuleTags & 0x04) == 0x04;
if (bIsMule) {
m_bEmuleProtocol = true;
m_byInfopacketsReceived |= IP_EMULEPROTPACK;
}
if (GetKadPort() && GetKadVersion() > 1) {
Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort());
}
return bIsMule;
}
bool CUpDownClient::SendHelloPacket()
{
if (m_socket == NULL) {
wxFAIL;
return true;
}
// if IP is filtered, don't greet him but disconnect...
if (theApp->ipfilter->IsFiltered(m_socket->GetPeerInt())) {
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
CMemFile data(128);
data.WriteUInt8(16); // size of userhash
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true);
m_bHelloAnswerPending = true;
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
return true;
}
void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) {
if (m_socket == NULL){
wxFAIL;
return;
}
CPacket* packet = NULL;
CMemFile data;
data.WriteUInt8(CURRENT_VERSION_SHORT);
if (OSInfo) {
// Special MuleInfo packet for clients supporting it.
// This means aMule >= 2.0.0 and Hydranode
// Violently mark it as special Mule Info packet
// Sending this makes non-supporting-osinfo clients to refuse to read this
// packet. Anyway, this packet should NEVER get to non-supporting clients.
data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
data.WriteUInt32(1); // One Tag (OS_INFO)
CTagString tag1(ET_OS_INFO,theApp->GetOSType());
tag1.WriteTagToFile(&data);
m_OSInfo_sent = true; // So we don't send it again
} else {
// Normal MuleInfo packet
// Kry - There's no point on upgrading to VBT tags here
// as no client supporting it uses mule info packet.
data.WriteUInt8(EMULE_PROTOCOL);
// Tag number
data.WriteUInt32(9);
CTagInt32 tag1(ET_COMPRESSION,1);
tag1.WriteTagToFile(&data);
CTagInt32 tag2(ET_UDPVER,4);
tag2.WriteTagToFile(&data);
CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort());
tag3.WriteTagToFile(&data);
CTagInt32 tag4(ET_SOURCEEXCHANGE,3);
tag4.WriteTagToFile(&data);
CTagInt32 tag5(ET_COMMENTS,1);
tag5.WriteTagToFile(&data);
CTagInt32 tag6(ET_EXTENDEDREQUEST,2);
tag6.WriteTagToFile(&data);
uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0);
// Kry - Needs the preview code from eMule
/*
// set 'Preview supported' only if 'View Shared Files' allowed
if (thePrefs::CanSeeShares() != vsfaNobody) {
dwTagValue |= 128;
}
*/
CTagInt32 tag7(ET_FEATURES, dwTagValue);
tag7.WriteTagToFile(&data);
CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE);
tag8.WriteTagToFile(&data);
// Support for tag ET_MOD_VERSION
wxString mod_name(MOD_VERSION_LONG);
CTagString tag9(ET_MOD_VERSION, mod_name);
tag9.WriteTagToFile(&data);
// Maella end
}
packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO));
if (m_socket) {
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (!bAnswer) {
if (!OSInfo) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
}
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
}
#endif
}
}
bool CUpDownClient::ProcessMuleInfoPacket(const byte* pachPacket, uint32 nSize)
{
uint8 protocol_version;
const CMemFile data(pachPacket,nSize);
// The version number part of this packet will soon be useless since
// it is only able to go to v.99. Why the version is a uint8 and why
// it was not done as a tag like the eDonkey hello packet is not known.
// Therefore, sooner or later, we are going to have to switch over to
// using the eDonkey hello packet to set the version. No sense making
// a third value sent for versions.
uint8 mule_version = data.ReadUInt8();
protocol_version = data.ReadUInt8();
uint32 tagcount = data.ReadUInt32();
if (protocol_version == 0xFF) {
// OS Info supporting clients sending a recycled Mule info packet
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case ET_OS_INFO:
// Special tag, only supporting clients (aMule/Hydranode)
// It was recycled from a mod's tag, so if the other side
// is not supporting OS Info, we're seriously fucked up :)
m_sClientOSInfo = temptag.GetStr();
// If we didn't send our OSInfo to this client, just send it
if (!m_OSInfo_sent) {
SendMuleInfoPacket(false,true);
}
UpdateStats();
break;
// Your ad... er... I mean TAG, here
default:
break;
}
}
} else {
// Old eMule sending tags
m_byCompatibleClient = 0;
m_byEmuleVersion = mule_version;
if( m_byEmuleVersion == 0x2B ) {
m_byEmuleVersion = 0x22;
}
if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) {
return false;
}
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, false);
switch(temptag.GetNameID()){
case ET_COMPRESSION:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: data compression version
m_byDataCompVer = temptag.GetInt();
break;
case ET_UDPPORT:
// Bits 31-16: 0 - reserved
// Bits 15- 0: UDP port
m_nUDPPort = temptag.GetInt();
break;
case ET_UDPVER:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: UDP protocol version
m_byUDPVer = temptag.GetInt();
break;
case ET_SOURCEEXCHANGE:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: source exchange protocol version
m_bySourceExchange1Ver = temptag.GetInt();
break;
case ET_COMMENTS:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: comments version
m_byAcceptCommentVer = temptag.GetInt();
break;
case ET_EXTENDEDREQUEST:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: extended requests version
m_byExtendedRequestsVer = temptag.GetInt();
break;
case ET_COMPATIBLECLIENT:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: compatible client ID
m_byCompatibleClient = temptag.GetInt();
break;
case ET_FEATURES:
// Bits 31- 8: 0 - reserved
// Bit 7: Preview
// Bit 6- 0: secure identification
m_bySupportSecIdent = temptag.GetInt() & 3;
m_bSupportsPreview = (temptag.GetInt() & 128) > 0;
SecIdentSupRec += 2;
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
default:
AddDebugLogLineN( logPacketErrors,
CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
% temptag.GetFullInfo()
% GetClientFullInfo()
);
break;
}
}
if( m_byDataCompVer == 0 ){
m_bySourceExchange1Ver = 0;
m_byExtendedRequestsVer = 0;
m_byAcceptCommentVer = 0;
m_nUDPPort = 0;
}
//implicitly supported options by older clients
//in the future do not use version to guess about new features
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) {
m_byUDPVer = 1;
}
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) {
m_bySourceExchange1Ver = 1;
}
if(m_byEmuleVersion == 0x24) {
m_byAcceptCommentVer = 1;
}
// Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
// the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
// directory which has a trailing backslash.
if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories
m_fSharedDirectories = 1;
}
ReGetClientSoft();
m_byInfopacketsReceived |= IP_EMULEPROTPACK;
}
return (protocol_version == 0xFF); // This was a OS_Info?
}
void CUpDownClient::SendHelloAnswer()
{
if (m_socket == NULL){
wxFAIL;
return;
}
CMemFile data(128);
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
SendPacket(packet,true);
}
void CUpDownClient::SendHelloTypePacket(CMemFile* data)
{
data->WriteHash(thePrefs::GetUserHash());
data->WriteUInt32(theApp->GetID());
data->WriteUInt16(thePrefs::GetPort());
uint32 tagcount = 6;
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
tagcount += 2;
}
tagcount ++; // eMule misc flags 2 (kad version)
#ifdef __SVN__
// Kry - This is the tagcount!!! Be sure to update it!!
// Last update: CT_EMULECOMPAT_OPTIONS included
data->WriteUInt32(tagcount + 1);
#else
data->WriteUInt32(tagcount); // NO MOD_VERSION
#endif
CTagString tagname(CT_NAME,thePrefs::GetUserNick());
tagname.WriteTagToFile(data, utf8strRaw);
CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32);
tagversion.WriteTagToFile(data);
// eMule UDP Ports
uint32 kadUDPPort = 0;
if(Kademlia::CKademlia::IsConnected()) {
if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
} else {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
}
}
CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
tagUdpPorts.WriteTagToFile(data);
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
tagBuddyIP.WriteTagToFile(data);
CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP,
// ( RESERVED )
((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() )
, GetVBTTags() ? 0 : 32);
tagBuddyPort.WriteTagToFile(data);
}
// aMule Version
CTagVarInt tagMuleVersion(CT_EMULE_VERSION,
(SO_AMULE << 24) |
make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
// | (RESERVED )
, GetVBTTags() ? 0 : 32);
tagMuleVersion.WriteTagToFile(data);
// eMule Misc. Options #1
const uint32 uUdpVer = 4;
const uint32 uDataCompVer = 1;
const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0;
const uint32 uSourceExchangeVer = 3;
const uint32 uExtendedRequestsVer = 2;
const uint32 uAcceptCommentVer = 1;
const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
const uint32 uMultiPacket = 1;
const uint32 uSupportPreview = 0; // No network preview at all.
const uint32 uPeerCache = 0; // No peercache for aMule, baby
const uint32 uUnicodeSupport = 1;
const uint32 nAICHVer = 1; // AICH is ENABLED right now.
CTagVarInt tagMisOptions(CT_EMULE_MISCOPTIONS1,
(nAICHVer << ((4*7)+1)) |
(uUnicodeSupport << 4*7) |
(uUdpVer << 4*6) |
(uDataCompVer << 4*5) |
(uSupportSecIdent << 4*4) |
(uSourceExchangeVer << 4*3) |
(uExtendedRequestsVer << 4*2) |
(uAcceptCommentVer << 4*1) |
(uPeerCache << 1*3) |
(uNoViewSharedFiles << 1*2) |
(uMultiPacket << 1*1) |
(uSupportPreview << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisOptions.WriteTagToFile(data);
// eMule Misc. Options #2
const uint32 uKadVersion = KADEMLIA_VERSION;
const uint32 uSupportLargeFiles = 1;
const uint32 uExtMultiPacket = 1;
const uint32 uReserved = 0; // mod bit
const uint32 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
const uint32 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
const uint32 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
const uint32 uSupportsSourceEx2 = 1;
#ifdef AMULE_DAEMON
// captcha for daemon/remotegui not supported for now
const uint32 uSupportsCaptcha = 0;
#else
const uint32 uSupportsCaptcha = 1;
#endif
// direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
&& !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
CTagVarInt tagMisOptions2(CT_EMULE_MISCOPTIONS2,
// (RESERVED )
(uDirectUDPCallback << 12) |
(uSupportsCaptcha << 11) |
(uSupportsSourceEx2 << 10) |
(uRequiresCryptLayer << 9) |
(uRequestsCryptLayer << 8) |
(uSupportsCryptLayer << 7) |
(uReserved << 6) |
(uExtMultiPacket << 5) |
(uSupportLargeFiles << 4) |
(uKadVersion << 0)
, GetVBTTags() ? 0 : 32 );
tagMisOptions2.WriteTagToFile(data);
const uint32 nOSInfoSupport = 1; // We support OS_INFO
const uint32 nValueBasedTypeTags = 0; // Experimental, disabled
CTagVarInt tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS,
(nValueBasedTypeTags << 1*1) |
(nOSInfoSupport << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisCompatOptions.WriteTagToFile(data);
#ifdef __SVN__
wxString mod_name(MOD_VERSION_LONG);
CTagString tagModName(ET_MOD_VERSION, mod_name);
tagModName.WriteTagToFile(data);
#endif
uint32 dwIP = 0;
uint16 nPort = 0;
if (theApp->IsConnectedED2K()) {
dwIP = theApp->serverconnect->GetCurrentServer()->GetIP();
nPort = theApp->serverconnect->GetCurrentServer()->GetPort();
}
data->WriteUInt32(dwIP);
data->WriteUInt16(nPort);
}
void CUpDownClient::ProcessMuleCommentPacket(const byte* pachPacket, uint32 nSize)
{
if (!m_reqfile) {
throw CInvalidPacket(wxT("Comment packet for unknown file"));
}
if (!m_reqfile->IsPartFile()) {
throw CInvalidPacket(wxT("Comment packet for completed file"));
}
const CMemFile data(pachPacket, nSize);
uint8 rating = data.ReadUInt8();
if (rating > 5) {
AddDebugLogLineN( logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating);
m_iRating = 0;
} else {
m_iRating = rating;
AddDebugLogLineN( logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating);
}
// The comment is unicoded, with a uin32 len and safe read
// (won't break if string size is < than advertised len)
// Truncated to MAXFILECOMMENTLEN size
m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN);
AddDebugLogLineN( logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment);
// Update file rating
m_reqfile->UpdateFileRatingCommentAvail();
}
void CUpDownClient::ClearDownloadBlockRequests()
{
{
std::list<Requested_Block_Struct*>::iterator it = m_DownloadBlocks_list.begin();
for (; it != m_DownloadBlocks_list.end(); ++it) {
Requested_Block_Struct* cur_block = *it;
if (m_reqfile){
m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset);
}
delete cur_block;
}
m_DownloadBlocks_list.clear();
}
{
std::list<Pending_Block_Struct*>::iterator it = m_PendingBlocks_list.begin();
for (; it != m_PendingBlocks_list.end(); ++it) {
Pending_Block_Struct* pending = *it;
if (m_reqfile) {
m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
}
delete pending->block;
// Not always allocated
if (pending->zStream){
inflateEnd(pending->zStream);
delete pending->zStream;
}
delete pending;
}
m_PendingBlocks_list.clear();
}
}
bool CUpDownClient::Disconnected(const wxString& DEBUG_ONLY(strReason), bool bFromSocket)
{
//wxASSERT(theApp->clientlist->IsValidClient(this));
if (HasBeenDeleted()) {
AddDebugLogLineN(logClient, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP()));
return false;
}
// was this a direct callback?
if (m_dwDirectCallbackTimeout != 0) {
theApp->clientlist->RemoveDirectCallback(this);
m_dwDirectCallbackTimeout = 0;
theApp->clientlist->AddDeadSource(this);
AddDebugLogLineN(logClient, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
}
if (GetKadState() == KS_QUEUED_FWCHECK_UDP || GetKadState() == KS_CONNECTING_FWCHECK_UDP) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
} else if (GetKadState() == KS_FWCHECK_UDP) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
} else if (GetKadState() == KS_CONNECTED_BUDDY) {
AddDebugLogLineN(logClient, wxT("Buddy client disconnected - ") + strReason);
}
//If this is a KAD client object, just delete it!
SetKadState(KS_NONE);
if (GetUploadState() == US_UPLOADING) {
// sets US_NONE
theApp->uploadqueue->RemoveFromUploadQueue(this);
}
if (GetDownloadState() == DS_DOWNLOADING) {
SetDownloadState(DS_ONQUEUE);
} else {
// ensure that all possible block requests are removed from the partfile
ClearDownloadBlockRequests();
if (GetDownloadState() == DS_CONNECTED) {
// successfully connected, but probably didn't respond to our filerequest
theApp->clientlist->AddDeadSource(this);
theApp->downloadqueue->RemoveSource(this);
}
}
// we had still an AICH request pending, handle it
if (IsAICHReqPending()) {
m_fAICHRequested = FALSE;
CAICHHashSet::ClientAICHRequestFailed(this);
}
// The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
// after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
// is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
if (((GetDownloadState() == DS_REQHASHSET) || m_fHashsetRequesting) && (m_reqfile)) {
m_reqfile->SetHashSetNeeded(true);
}
SourceItemType source_type = UNAVAILABLE_SOURCE;
SourceItemType peer_type = UNAVAILABLE_SOURCE;
//check if this client is needed in any way, if not delete it
bool bDelete = true;
switch (m_nUploadState) {
case US_ONUPLOADQUEUE:
bDelete = false;
peer_type = AVAILABLE_SOURCE;
break;
};
switch (m_nDownloadState) {
case DS_ONQUEUE:
source_type = A4AF_SOURCE; // Will be checked.
case DS_TOOMANYCONNS:
case DS_NONEEDEDPARTS:
case DS_LOWTOLOWIP:
bDelete = false;
break;
};
switch (m_nUploadState) {
case US_CONNECTING:
case US_WAITCALLBACK:
case US_ERROR:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
switch (m_nDownloadState) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_ERROR:
case DS_BANNED:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
// We keep chat partners in any case
if (GetChatState() != MS_NONE) {
bDelete = false;
m_pendingMessage.Clear();
Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString);
}
// Delete socket
if (!bFromSocket && m_socket) {
wxASSERT (theApp->listensocket->IsValidSocket(m_socket));
m_socket->Safe_Delete();
}
SetSocket(NULL);
if (m_iFileListRequested) {
AddLogLineC(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
m_iFileListRequested = 0;
}
if (bDelete) {
if (m_Friend) {
// Remove the friend linkage
m_Friend->UnLinkClient(); // this notifies
}
} else {
Notify_SharedCtrlRefreshClient(ECID(), peer_type);
Notify_SourceCtrlUpdateSource(ECID(), source_type);
m_fHashsetRequesting = 0;
SetSentCancelTransfer(0);
m_bHelloAnswerPending = false;
m_fSentOutOfPartReqs = 0;
}
AddDebugLogLineN(logClient, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
% (bDelete ? wxT("Deleted") : wxT("Disconnected"))
% m_nDownloadState % m_nUploadState % GetClientFullInfo() % strReason );
return bDelete;
}
//Returned bool is not if the TryToConnect is successful or not..
//false means the client was deleted!
//true means the client was not deleted!
bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon)
{
// Kad reviewed
if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) {
if (!(m_socket && m_socket->IsConnected())) {
if(Disconnected(wxT("Too many connections"))) {
Safe_Delete();
return false;
}
return true;
}
}
// Do not try to connect to source which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
Safe_Delete();
return false;
} else {
return true;
}
}
// Ipfilter check
uint32 uClientIP = GetIP();
if (uClientIP == 0 && !HasLowID()) {
uClientIP = wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid);
}
if (uClientIP) {
// Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
// we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
if (theApp->ipfilter->IsFiltered(uClientIP)) {
AddDebugLogLineN(logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP));
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
// for safety: check again whether that IP is banned
if (theApp->clientlist->IsBannedClient(uClientIP)) {
AddDebugLogLineN(logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP));
if (Disconnected(wxT("Banned IP"))) {
Safe_Delete();
return false;
}
return true;
}
}
if (GetKadState() == KS_QUEUED_FWCHECK) {
SetKadState(KS_CONNECTING_FWCHECK);
} else if (GetKadState() == KS_QUEUED_FWCHECK_UDP) {
SetKadState(KS_CONNECTING_FWCHECK_UDP);
}
if (HasLowID()) {
if (!theApp->CanDoCallback(GetServerIP(), GetServerPort())) {
//We cannot do a callback!
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_LOWTOLOWIP);
} else if (GetDownloadState() == DS_REQHASHSET) {
SetDownloadState(DS_ONQUEUE);
m_reqfile->SetHashSetNeeded(true);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
}
return true;
}
//We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
//If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
//with the condition that the source is firewalled and we are firewalled, we must
//recheck it before the this check..
if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort())
&& !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
//This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
if( Kademlia::CKademlia::IsConnected() ) {
//We are connect to Kad
if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
//There are too many source lookups already or we are already searching this key.
SetDownloadState(DS_TOOMANYCONNSKAD);
return true;
}
}
}
}
if (!m_socket || !m_socket->IsConnected()) {
if (m_socket) {
m_socket->Safe_Delete();
}
m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData());
} else {
ConnectionEstablished();
return true;
}
if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
if (m_dwDirectCallbackTimeout != 0) {
AddDebugLogLineN(logClient, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
return true; // We're already trying a direct connection to this client
}
// a direct callback is possible - since no other parties are involved and only one additional packet overhead
// is used we basically handle it like a normal connection try, no restrictions apply
// we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
m_dwDirectCallbackTimeout = ::GetTickCount() + SEC2MS(45);
theApp->clientlist->AddDirectCallbackClient(this);
AddDebugLogLineN(logClient, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
CMemFile data;
data.WriteUInt16(thePrefs::GetPort()); // needs to know our port
data.WriteHash(thePrefs::GetUserHash()); // and userhash
// our connection settings
data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
AddDebugLogLineN(logClientUDP, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_DIRECTCALLBACKREQ);
theStats::AddUpOverheadOther(packet->GetPacketSize());
theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
} else if (HasLowID()) { // LOWID
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_WAITCALLBACK);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
return true;
}
if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) {
CMemFile data;
// AFAICS, this id must be reversed to be sent to clients
// But if I reverse it, we do a serve violation ;)
data.WriteUInt32(m_nUserIDHybrid);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST);
theStats::AddUpOverheadServer(packet->GetPacketSize());
AddDebugLogLineN(logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
theApp->serverconnect->SendPacket(packet);
SetDownloadState(DS_WAITCALLBACK);
} else {
if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) {
if( !HasValidBuddyID() ) {
theApp->downloadqueue->RemoveSource(this);
if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
Safe_Delete();
return false;
}
return true;
}
if( !Kademlia::CKademlia::IsConnected() ) {
//We are not connected to Kad and this is a Kad Firewalled source..
theApp->downloadqueue->RemoveSource(this);
if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
Safe_Delete();
return false;
}
return true;
}
if( GetDownloadState() == DS_WAITCALLBACK ) {
if( GetBuddyIP() && GetBuddyPort()) {
CMemFile bio(34);
bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
bio.WriteUInt16(thePrefs::GetPort());
CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, KADEMLIA_CALLBACK_REQ);
// eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0);
AddDebugLogLineN(logClientKadUDP, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
theStats::AddUpOverheadKad(packet->GetRealPacketSize());
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
AddLogLineN(_("Searching buddy for lowid connection"));
//Create search to find buddy.
Kademlia::CSearch *findSource = new Kademlia::CSearch;
findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE);
findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
if(Kademlia::CSearchManager::StartSearch(findSource)) {
//Started lookup..
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
//This should never happen..
wxFAIL;
}
}
}
} else {
if (GetDownloadState() == DS_WAITCALLBACK) {
m_bReaskPending = true;
SetDownloadState(DS_ONQUEUE);
}
}
}
} else { // HIGHID
if (!Connect()) {
return false;
}
}
return true;
}
bool CUpDownClient::Connect()
{
m_hasbeenobfuscatinglately = false;
if (!m_socket->IsOk()) {
// Enable or disable crypting based on our and the remote clients preference
if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
m_socket->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
} else {
m_socket->SetConnectionEncryption(false, NULL, false);
}
amuleIPV4Address tmp;
tmp.Hostname(GetConnectIP());
tmp.Service(GetUserPort());
AddDebugLogLineN(logClient, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
m_socket->Connect(tmp, false);
// We should send hello packets AFTER connecting!
// so I moved it to OnConnect
return true;
} else {
return false;
}
}
void CUpDownClient::ConnectionEstablished()
{
/* Kry - First thing, check if this client was just used to retrieve
info. That's some debug thing for myself... check connection_reason
definition */
m_hasbeenobfuscatinglately = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating());
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason % GetClientFullInfo());
connection_reason.Clear(); // So we don't re-print on destructor.
Safe_Delete();
return;
}
#endif
// Check if we should use this client to retrieve our public IP
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) {
SendPublicIPRequest();
}
// was this a direct callback?
if (m_dwDirectCallbackTimeout != 0){
theApp->clientlist->RemoveDirectCallback(this);
m_dwDirectCallbackTimeout = 0;
AddDebugLogLineN(logClient, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
}
switch (GetKadState()) {
case KS_CONNECTING_FWCHECK:
SetKadState(KS_CONNECTED_FWCHECK);
break;
case KS_CONNECTING_BUDDY:
case KS_INCOMING_BUDDY:
SetKadState(KS_CONNECTED_BUDDY);
break;
case KS_CONNECTING_FWCHECK_UDP:
SetKadState(KS_FWCHECK_UDP);
SendFirewallCheckUDPRequest();
break;
default:
break;
}
// ok we have a connection, lets see if we want anything from this client
if (GetChatState() == MS_CONNECTING) {
SetChatState( MS_CHATTING );
}
if (GetChatState() == MS_CHATTING) {
bool result = true;
if (!m_pendingMessage.IsEmpty()) {
result = SendChatMessage(m_pendingMessage);
}
Notify_ChatConnResult(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage);
m_pendingMessage.Clear();
}
switch(GetDownloadState()) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_WAITCALLBACKKAD:
m_bReaskPending = false;
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
if (m_bReaskPending){
m_bReaskPending = false;
if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) {
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
}
switch(GetUploadState()){
case US_CONNECTING:
case US_WAITCALLBACK:
if (theApp->uploadqueue->IsDownloading(this)) {
SetUploadState(US_UPLOADING);
CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT);
theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
SendPacket(packet,true);
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
}
}
if (m_iFileListRequested == 1) {
CPacket* packet = new CPacket(m_fSharedDirectories ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (m_fSharedDirectories) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
}
#endif
}
while (!m_WaitingPackets_list.empty()) {
CPacket* packet = m_WaitingPackets_list.front();
m_WaitingPackets_list.pop_front();
SendPacket(packet);
}
}
int CUpDownClient::GetHashType() const
{
if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) {
return SO_OLDEMULE;
}
if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) {
return SO_EMULE;
}
if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) {
return SO_MLDONKEY;
}
return SO_UNKNOWN;
}
void CUpDownClient::SetSocket(CClientTCPSocket* socket)
{
#ifdef __DEBUG__
if (m_socket == NULL && socket != NULL) {
theStats::SocketAssignedToClient();
} else if (m_socket != NULL && socket == NULL) {
theStats::SocketUnassignedFromClient();
}
#endif
m_socket = socket;
}
void CUpDownClient::ReGetClientSoft()
{
if (m_Username.IsEmpty()) {
m_clientSoft=SO_UNKNOWN;
m_clientVerString = m_clientSoftString = m_clientVersionString = m_fullClientVerString = _("Unknown");
UpdateStats();
return;
}
int iHashType = GetHashType();
wxString clientModString;
if (iHashType == SO_EMULE) {
m_clientSoft = m_byCompatibleClient;
m_clientSoftString = GetSoftName(m_clientSoft);
// Special issues:
if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) {
m_clientSoftString = GetClientModString();
}
// Isn't xMule annoying?
if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
m_clientSoftString += CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
}
if ((m_clientSoft == SO_EMULE) &&
(
wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
|| GetUserName().Find(wxT("xmule.")) != -1
)
) {
// FAKE eMule -a newer xMule faking is ident.
m_clientSoft = SO_LXMULE;
if (GetClientModString().IsEmpty() == false) {
m_clientSoftString = GetClientModString() + _(" (Fake eMule)");
} else {
m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
}
}
// Now, what if we don't know this SO_ID?
if (m_clientSoftString.IsEmpty()) {
if(m_bIsML) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (m_bIsHybrid) {
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (m_byCompatibleClient != 0) {
m_clientSoft = SO_COMPAT_UNK;
#ifdef __DEBUG__
if (
// Exceptions:
(m_byCompatibleClient != 0xf0) // Chinese leech mod
&& (1==1) // Your ad here
) {
AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient);
}
#endif
m_clientSoftString = CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft) % m_byCompatibleClient;
} else {
// If we step here, it might mean 2 things:
// a eMule
// a Compat Client that has sent no MuleInfo packet yet.
m_clientSoft = SO_EMULE;
m_clientSoftString = wxT("eMule");
}
}
if (m_byEmuleVersion == 0) {
m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0);
} else if (m_byEmuleVersion != 0x99) {
uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f);
m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0);
switch (m_clientSoft) {
case SO_AMULE:
m_clientVerString = CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion;
break;
case SO_LPHANT:
m_clientVerString = wxT("< v0.05");
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
break;
}
} else {
uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f;
uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f;
uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07;
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
switch (m_clientSoft) {
case SO_AMULE:
case SO_LXMULE:
case SO_HYDRANODE:
case SO_MLDONKEY:
case SO_NEW_MLDONKEY:
case SO_NEW2_MLDONKEY:
// Kry - xMule started sending correct version tags on 1.9.1b.
// It only took them 4 months, and being told by me and the
// eMule+ developers, so I think they're slowly getting smarter.
// They are based on our implementation, so we use the same format
// for the version string.
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
break;
case SO_LPHANT:
m_clientVerString = CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion-1) % nClientMinVersion % ('a' + nClientUpVersion);
break;
case SO_EMULEPLUS:
m_clientVerString = CFormat(wxT("v%u")) % nClientMajVersion;
if(nClientMinVersion != 0) {
m_clientVerString += CFormat(wxT(".%u")) % nClientMinVersion;
}
if(nClientUpVersion != 0) {
m_clientVerString += CFormat(wxT("%c")) % ('a' + nClientUpVersion - 1);
}
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v%u.%u%c")) % nClientMajVersion % nClientMinVersion % ('a' + nClientUpVersion);
break;
}
}
} else if (m_bIsHybrid) {
// seen:
// 105010 50.10
// 10501 50.1
// 1051 51.0
// 501 50.1
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMajVersion;
uint32 nClientMinVersion;
uint32 nClientUpVersion;
if (m_nClientVersion > 100000) {
uint32 uMaj = m_nClientVersion/100000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100;
nClientUpVersion = m_nClientVersion % 100;
}
else if (m_nClientVersion > 10000) {
uint32 uMaj = m_nClientVersion/10000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10;
nClientUpVersion = m_nClientVersion % 10;
}
else if (m_nClientVersion > 1000) {
uint32 uMaj = m_nClientVersion/1000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = m_nClientVersion - uMaj*1000;
nClientUpVersion = 0;
}
else if (m_nClientVersion > 100) {
uint32 uMin = m_nClientVersion/10;
nClientMajVersion = 0;
nClientMinVersion = uMin;
nClientUpVersion = m_nClientVersion - uMin*10;
}
else{
nClientMajVersion = 0;
nClientMinVersion = m_nClientVersion;
nClientUpVersion = 0;
}
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
if (nClientUpVersion) {
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
} else {
m_clientVerString = CFormat(wxT("v%u.%u")) % nClientMajVersion % nClientMinVersion;
}
} else if (m_bIsML || (iHashType == SO_MLDONKEY)) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else if (iHashType == SO_OLDEMULE) {
m_clientSoft = SO_OLDEMULE;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else {
m_clientSoft = SO_EDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
m_nClientVersion *= 10;
m_clientVerString = CFormat(wxT("v%u.%u")) % (m_nClientVersion / 100000) % ((m_nClientVersion / 1000) % 100);
}
m_clientVersionString = m_clientVerString;
if (!clientModString.IsEmpty()) {
m_clientVerString += wxT(" - ") + clientModString;
}
m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
UpdateStats();
}
void CUpDownClient::RequestSharedFileList()
{
if (m_iFileListRequested == 0) {
AddDebugLogLineN( logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
m_iFileListRequested = 1;
TryToConnect(true);
} else {
AddDebugLogLineN( logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
}
}
void CUpDownClient::ProcessSharedFileList(const byte* pachPacket, uint32 nSize, wxString& pszDirectory)
{
if (m_iFileListRequested > 0) {
m_iFileListRequested--;
theApp->searchlist->ProcessSharedFileList(pachPacket, nSize, this, NULL, pszDirectory);
}
}
void CUpDownClient::ResetFileStatusInfo()
{
m_nPartCount = 0;
if ( m_reqfile ) {
m_reqfile->UpdatePartsFrequency( this, false );
}
m_downPartStatus.clear();
m_clientFilename.Clear();
m_bCompleteSource = false;
m_dwLastAskedTime = 0;
m_iRating = 0;
m_strComment.Clear();
if (m_pReqFileAICHHash != NULL) {
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
}
}
wxString CUpDownClient::GetUploadFileInfo()
{
// build info text and display it
wxString sRet;
sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
if (m_reqfile) {
sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName();
sRet += CFormat(
wxPLURAL("Filestats for this session: Accepted %d of %d request, %s transferred\n", "Filestats for this session: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetRequests())
) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred());
sRet += CFormat(
wxPLURAL("Filestats for all sessions: Accepted %d of %d request, %s transferred\n", "Filestats for all sessions: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetAllTimeRequests())
) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.GetAllTimeTransferred());
} else {
sRet += _("Requested unknown file");
}
return sRet;
}
// sends a packet, if needed it will establish a connection before
// options used: ignore max connections, control packet, delete packet
// !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
bool CUpDownClient::SafeSendPacket(CPacket* packet)
{
if (IsConnected()) {
SendPacket(packet, true);
return true;
} else {
m_WaitingPackets_list.push_back(packet);
return TryToConnect(true);
}
}
void CUpDownClient::SendPublicKeyPacket(){
// send our public key to the client who requested it
if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
CMemFile data;
data.WriteUInt8(theApp->clientcredits->GetPubKeyLen());
data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen());
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_SIGNATURENEEDED;
}
void CUpDownClient::SendSignaturePacket(){
// signate the public key of this client and send it
if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable()) {
return;
}
if (credits->GetSecIDKeyLen() == 0) {
return; // We don't have his public key yet, will be back here later
}
// do we have a challenge value received (actually we should if we are in this function)
if (credits->m_dwCryptRndChallengeFrom == 0){
AddDebugLogLineN( logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
return;
}
// v2
// we will use v1 as default, except if only v2 is supported
bool bUseV2;
if ( (m_bySupportSecIdent&1) == 1 )
bUseV2 = false;
else
bUseV2 = true;
uint8 byChaIPKind = 0;
uint32 ChallengeIP = 0;
if (bUseV2){
if (::IsLowID(theApp->GetED2KID())) {
// we cannot do not know for sure our public ip, so use the remote clients one
ChallengeIP = GetIP();
byChaIPKind = CRYPT_CIP_REMOTECLIENT;
} else {
ChallengeIP = theApp->GetED2KID();
byChaIPKind = CRYPT_CIP_LOCALCLIENT;
}
}
//end v2
byte achBuffer[250];
uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind );
if (siglen == 0){
wxFAIL;
return;
}
CMemFile data;
data.WriteUInt8(siglen);
data.Write(achBuffer, siglen);
if (bUseV2) {
data.WriteUInt8(byChaIPKind);
}
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_ALLREQUESTSSEND;
}
void CUpDownClient::ProcessPublicKeyPacket(const byte* pachPacket, uint32 nSize)
{
theApp->clientlist->AddTrackClient(this);
if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1
|| nSize == 0 || nSize > 250){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// the function will handle everything (mulitple key etc)
if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){
// if this client wants a signature, now we can send him one
if (m_SecureIdentState == IS_SIGNATURENEEDED){
SendSignaturePacket();
}
else if (m_SecureIdentState == IS_KEYANDSIGNEEDED) {
// something is wrong
AddDebugLogLineN( logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
}
} else {
AddDebugLogLineN( logClient, wxT("Failed to use new received public key") );
}
}
void CUpDownClient::ProcessSignaturePacket(const byte* pachPacket, uint32 nSize)
{
// here we spread the good guys from the bad ones ;)
if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){
wxFAIL;
return;
}
uint8 byChaIPKind;
if (pachPacket[0] == nSize-1)
byChaIPKind = 0;
else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0) //v2
byChaIPKind = pachPacket[nSize-1];
else{
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
if (m_dwLastSignatureIP == GetIP()){
AddDebugLogLineN( logClient, wxT("received multiple signatures from one client") );
return;
}
// also make sure this client has a public key
if (credits->GetSecIDKeyLen() == 0){
AddDebugLogLineN( logClient, wxT("received signature for client without public key") );
return;
}
// and one more check: did we ask for a signature and sent a challange packet?
if (credits->m_dwCryptRndChallengeFor == 0){
AddDebugLogLineN( logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
return;
}
// cppcheck-suppress duplicateBranch
if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ) {
// result is saved in function above
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
} else {
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
}
m_dwLastSignatureIP = GetIP();
}
void CUpDownClient::SendSecIdentStatePacket(){
// check if we need public key and signature
if (credits){
uint8 nValue = 0;
if (theApp->CryptoAvailable()){
if (credits->GetSecIDKeyLen() == 0) {
nValue = IS_KEYANDSIGNEEDED;
} else if (m_dwLastSignatureIP != GetIP()) {
nValue = IS_SIGNATURENEEDED;
}
}
if (nValue == 0){
AddDebugLogLineN( logClient, wxT("Not sending SecIdentState Packet, because State is Zero") );
return;
}
// crypt: send random data to sign
uint32 dwRandom = rand()+1;
credits->m_dwCryptRndChallengeFor = dwRandom;
CMemFile data;
data.WriteUInt8(nValue);
data.WriteUInt32(dwRandom);
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
SendPacket(packet,true,true);
} else {
wxFAIL;
}
}
void CUpDownClient::ProcessSecIdentStatePacket(const byte* pachPacket, uint32 nSize)
{
if ( nSize != 5 ) {
return;
}
if ( !credits ) {
wxASSERT( credits );
return;
}
CMemFile data(pachPacket,nSize);
switch ( data.ReadUInt8() ) {
case 0:
m_SecureIdentState = IS_UNAVAILABLE;
break;
case 1:
m_SecureIdentState = IS_SIGNATURENEEDED;
break;
case 2:
m_SecureIdentState = IS_KEYANDSIGNEEDED;
break;
default:
return;
}
credits->m_dwCryptRndChallengeFrom = data.ReadUInt32();
}
void CUpDownClient::InfoPacketsReceived()
{
// indicates that both Information Packets has been received
// needed for actions, which process data from both packets
wxASSERT ( m_byInfopacketsReceived == IP_BOTH );
m_byInfopacketsReceived = IP_NONE;
if (m_bySupportSecIdent){
SendSecIdentStatePacket();
}
}
bool CUpDownClient::CheckHandshakeFinished() const
{
if (m_bHelloAnswerPending) {
// this triggers way too often.. need more time to look at this -> only create a warning
// The reason for this is that 2 clients are connecting to each other at the same time..
AddDebugLogLineN( logClient, wxT("Handshake not finished while processing packet.") );
return false;
}
return true;
}
#ifdef __DEBUG__
wxString CUpDownClient::GetClientFullInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% GetFullIP()
% GetUserPort()
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
#endif
wxString CUpDownClient::GetClientShortInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("'%s' (%s %s %s)") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
void CUpDownClient::SendPublicIPRequest()
{
if (IsConnected()){
CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP());
SendPacket(packet,true);
m_fNeedOurPublicIP = true;
}
}
void CUpDownClient::ProcessPublicIPAnswer(const byte* pbyData, uint32 uSize)
{
if (uSize != 4) {
throw wxString(wxT("Wrong Packet size on Public IP answer"));
}
uint32 dwIP = PeekUInt32(pbyData);
if (m_fNeedOurPublicIP == true){ // did we?
m_fNeedOurPublicIP = false;
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) {
theApp->SetPublicIP(dwIP);
}
}
}
bool CUpDownClient::IsConnected() const
{
return m_socket && m_socket->IsConnected();
}
bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket)
{
if ( m_socket ) {
m_socket->SendPacket(packet, delpacket, controlpacket );
return true;
} else {
AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
return false;
}
}
float CUpDownClient::SetDownloadLimit(uint32 reducedownload)
{
// lfroen: in daemon it actually can happen
wxASSERT( m_socket );
float kBpsClient = CalculateKBpsDown();
if ( m_socket ) {
if (reducedownload) {
// (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
// which is how often it is called per second.
uint32 limit = (uint32)(reducedownload * kBpsClient * 1024.0 / 100000.0 * CORE_TIMER_PERIOD);
if(limit<1024 && reducedownload >= 200) {
// If we're going up and this download is < 1kB,
// we want it to go up fast. Can be reduced later,
// and it'll probably be in a more fair way with
// other downloads that are faster.
limit +=1024;
} else if(limit == 0) {
// This download is not transferring yet... make it
// 1024 so we don't fill the TCP stack and lose the
// connection.
limit = 1024;
}
m_socket->SetDownloadLimit(limit);
} else {
m_socket->DisableDownloadLimit();
}
} else {
AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient);
}
return kBpsClient;
}
void CUpDownClient::SetUserIDHybrid(uint32 nUserID)
{
theApp->clientlist->UpdateClientID( this, nUserID );
m_nUserIDHybrid = nUserID;
}
void CUpDownClient::SetIP( uint32 val )
{
theApp->clientlist->UpdateClientIP( this, val );
m_dwUserIP = val;
m_nConnectIP = val;
m_FullUserIP = val;
}
void CUpDownClient::SetUserHash(const CMD4Hash& userhash)
{
theApp->clientlist->UpdateClientHash( this, userhash );
m_UserHash = userhash;
ValidateHash();
}
EUtf8Str CUpDownClient::GetUnicodeSupport() const
{
return m_bUnicodeSupport ? utf8strRaw : utf8strNone;
}
void CUpDownClient::SetSpammer(bool bVal)
{
if (bVal) {
Ban();
} else if (IsBanned() && m_fIsSpammer) {
UnBan();
}
m_fIsSpammer = bVal;
}
uint8 CUpDownClient::GetSecureIdentState()
{
if (m_SecureIdentState != IS_UNAVAILABLE) {
if (!SecIdentSupRec) {
// This can be caused by a 0.30x based client which sends the old
// style Hello packet, and the mule info packet, but between them they
// send a secure ident state packet (after a hello but before we have
// the SUI capabilities). This is a misbehaving client, and somehow I
// feel like it should be dropped. But then again, it won't harm to use
// this SUI state if they are reporting no SUI (won't be used) and if
// they report using SUI on the mule info packet, it's ok to use it.
AddDebugLogLineN(logClient, wxT("A client sent secure ident state before telling us the SUI capabilities"));
AddDebugLogLineN(logClient, wxT("Client info: ") + GetClientFullInfo());
AddDebugLogLineN(logClient, wxT("This client won't be disconnected, but it should be. :P"));
}
}
return m_SecureIdentState;
}
bool CUpDownClient::SendChatMessage(const wxString& message)
{
if (GetChatCaptchaState() == CA_CAPTCHARECV) {
m_nChatCaptchaState = CA_SOLUTIONSENT;
} else if (GetChatCaptchaState() == CA_SOLUTIONSENT) {
wxFAIL; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
} else {
m_nChatCaptchaState = CA_ACCEPTING;
}
SetSpammer(false);
IncMessagesSent();
// Already connecting?
if (GetChatState() == MS_CONNECTING) {
// Queue all messages till we're able to send them (or discard them)
if (!m_pendingMessage.IsEmpty()) {
m_pendingMessage += wxT("\n");
} else {
// There must be a message to send
// - except if we got disconnected. No need to assert therefore.
}
m_pendingMessage += message;
return false;
}
if (IsConnected()) {
// If we are already connected when we send the first message,
// we have to update the chat status.
SetChatState(MS_CHATTING);
CMemFile data;
data.WriteString(message, GetUnicodeSupport());
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
SendPacket(packet, true, true);
return true;
} else {
m_pendingMessage = message;
SetChatState(MS_CONNECTING);
// True to ignore "Too Many Connections"
TryToConnect(true);
return false;
}
}
/* Kad stuff */
void CUpDownClient::SetBuddyID(const byte* pucBuddyID)
{
if( pucBuddyID == NULL ){
md4clr(m_achBuddyID);
m_bBuddyIDValid = false;
return;
}
m_bBuddyIDValid = true;
md4cpy(m_achBuddyID, pucBuddyID);
}
// Kad added by me
bool CUpDownClient::SendBuddyPing() {
SetLastBuddyPingPongTime();
CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT);
theStats::AddUpOverheadKad(buddyPing->GetPacketSize());
AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
return SafeSendPacket(buddyPing);
}
/* Statistics */
void CUpDownClient::UpdateStats()
{
if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) {
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
m_lastClientSoft = m_clientSoft;
m_lastClientVersion = m_nClientVersion;
m_lastOSInfo = m_sClientOSInfo;
if (m_clientSoft == SO_UNKNOWN) {
theStats::AddUnknownClient();
} else {
theStats::AddKnownClient(this);
}
}
}
bool CUpDownClient::IsIdentified() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED);
}
bool CUpDownClient::IsBadGuy() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY);
}
bool CUpDownClient::SUIFailed() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED);
}
bool CUpDownClient::SUINeeded() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED);
}
bool CUpDownClient::SUINotSupported() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE);
}
uint64 CUpDownClient::GetDownloadedTotal() const
{
return credits ? credits->GetDownloadedTotal() : 0;
}
uint64 CUpDownClient::GetUploadedTotal() const
{
return credits ? credits->GetUploadedTotal() : 0;
}
double CUpDownClient::GetScoreRatio() const
{
return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
}
const wxString CUpDownClient::GetServerName() const
{
wxString ret;
wxString srvaddr = Uint32toStringIP(GetServerIP());
CServer* cserver = theApp->serverlist->GetServerByAddress(
srvaddr, GetServerPort());
if (cserver) {
ret = cserver->GetListName();
} else {
ret = _("Unknown");
}
return ret;
}
bool CUpDownClient::ShouldReceiveCryptUDPPackets() const
{
return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp->GetPublicIP() != 0
&& HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
}
#ifdef AMULE_DAEMON
void CUpDownClient::ProcessCaptchaRequest(CMemFile* WXUNUSED(data)) {}
void CUpDownClient::ProcessCaptchaReqRes(uint8 WXUNUSED(nStatus)) {}
void CUpDownClient::ProcessChatMessage(const wxString WXUNUSED(message)) {}
#else
void CUpDownClient::ProcessCaptchaRequest(CMemFile* data)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
// received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
if (GetChatCaptchaState() == CA_ACCEPTING && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
// read tags (for future use)
uint8 nTagCount = data->ReadUInt8();
if (nTagCount) {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount);
// and ignore them for now
for (uint32 i = 0; i < nTagCount; i++) {
CTag tag(*data, true);
}
}
// sanitize checks - we want a small captcha not a wallpaper
uint32 nSize = (uint32)(data->GetLength() - data->GetPosition());
if ( nSize > 128 && nSize < 4096 ) {
uint64 pos = data->GetPosition();
wxMemoryInputStream memstr(data->GetRawBuffer() + pos, nSize);
wxImage imgCaptcha(memstr, wxBITMAP_TYPE_BMP);
if (imgCaptcha.IsOk() && imgCaptcha.GetHeight() > 10 && imgCaptcha.GetHeight() < 50
&& imgCaptcha.GetWidth() > 10 && imgCaptcha.GetWidth() < 150 ) {
m_nChatCaptchaState = CA_CAPTCHARECV;
CCaptchaDialog * dialog = new CCaptchaDialog(theApp->amuledlg, imgCaptcha, id);
dialog->Show();
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
if (GetChatCaptchaState() == CA_SOLUTIONSENT && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
wxASSERT( nStatus < 3 );
m_nChatCaptchaState = CA_NONE;
theApp->amuledlg->m_chatwnd->ShowCaptchaResult(id, nStatus == 0);
} else {
m_nChatCaptchaState = CA_NONE;
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::ProcessChatMessage(wxString message)
{
if (IsMessageFiltered(message)) {
AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
return;
}
// advanced spamfilter check
if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) {
// captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
// first check if we need to send a captcha request to this client
if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED) {
// we have never sent a message to this client, and no message from him has ever passed our filters
if (GetChatCaptchaState() != CA_CHALLENGESENT) {
// we also aren't currently expecting a captcha response
if (m_fSupportsCaptcha) {
// and he supports captcha, so send him one and store the message (without showing for now)
if (m_cCaptchasSent < 3) { // no more than 3 tries
m_strCaptchaPendingMsg = message;
wxMemoryOutputStream memstr;
memstr.PutC(0); // no tags, for future use
CCaptchaGenerator captcha(4);
if (captcha.WriteCaptchaImage(memstr)){
m_strCaptchaChallenge = captcha.GetCaptchaText();
m_nChatCaptchaState = CA_CHALLENGESENT;
m_cCaptchasSent++;
CMemFile fileAnswer((byte*) memstr.GetOutputStreamBuffer()->GetBufferStart(), memstr.GetLength());
CPacket* packet = new CPacket(fileAnswer, OP_EMULEPROT, OP_CHATCAPTCHAREQ);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge % packet->GetPacketSize());
SafeSendPacket(packet);
} else {
wxFAIL;
}
}
} else {
// client doesn't support captchas, but we require them, tell him that it's not going to work out
// with an answer message (will not be shown and doesn't count as sent message)
if (m_cCaptchasSent < 1) { // don't send this notifier more than once
m_cCaptchasSent++;
// always sent in english
SendChatMessage(wxT("In order to avoid spam messages, this user requires you to solve a captcha before you can send a message to him. However your client does not supports captchas, so you will not be able to chat with this user."));
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
}
}
return;
} else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
// this message must be the answer to the captcha request we sent him, let's verify
wxASSERT( !m_strCaptchaChallenge.IsEmpty() );
if (m_strCaptchaChallenge.CmpNoCase(message.Trim().Right(std::min(message.Length(), m_strCaptchaChallenge.Length()))) == 0) {
// allright
AddDebugLogLineN(logClient, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_CAPTCHASOLVED; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
// replace captchaanswer with withheld message and show it
message = m_strCaptchaPendingMsg;
m_cCaptchasSent = 0;
m_strCaptchaChallenge.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = 0; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
} else { // wrong, cleanup and ignore
AddDebugLogLineN(logClient, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_NONE;
m_strCaptchaChallenge.Clear();
m_strCaptchaPendingMsg.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = (m_cCaptchasSent < 3) ? 1 : 2; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
return; // nothing more todo
}
}
}
}
if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
bool bIsSpam = false;
if (m_fIsSpammer) {
bIsSpam = true;
} else {
// first fixed criteria: If a client sends me an URL in his first message before I respond to him
// there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
if (GetMessagesSent() == 0) {
static wxArrayString urlindicators(wxStringTokenize(wxT("http:|www.|.de |.net |.com |.org |.to |.tk |.cc |.fr |ftp:|ed2k:|https:|ftp.|.info|.biz|.uk|.eu|.es|.tv|.cn|.tw|.ws|.nu|.jp"), wxT("|")));
for (size_t pos = urlindicators.GetCount(); pos--;) {
if (message.Find(urlindicators[pos]) != wxNOT_FOUND) {
bIsSpam = true;
break;
}
}
// second fixed criteria: he sent me 4 or more messages and I didn't answer him once
if (GetMessagesReceived() > 3) {
bIsSpam = true;
}
}
}
if (bIsSpam) {
AddDebugLogLineN(logClient, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
SetSpammer(true);
theApp->amuledlg->m_chatwnd->EndSession(GUI_ID(GetIP(),GetUserPort()));
return;
}
}
wxString logMsg = CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
if(thePrefs::ShowMessagesInLog()) {
logMsg += wxT(": ") + message;
}
AddLogLineC(logMsg);
IncMessagesReceived();
Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message);
}
bool CUpDownClient::IsMessageFiltered(const wxString& message)
{
bool filtered = false;
// If we're chatting to the guy, we don't want to filter!
if (GetChatState() != MS_CHATTING) {
if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
filtered = true;
} else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
filtered = true;
} else if (thePrefs::MustFilterMessages()) {
filtered = thePrefs::IsMessageFiltered(message);
}
}
if (filtered) {
SetSpammer(true);
}
return filtered;
}
#endif
void CUpDownClient::SendSharedDirectories()
{
// This list will contain all (unique) folders.
PathList foldersToSend;
// The shared folders
const unsigned folderCount = theApp->glob_prefs->shareddir_list.size();
for (unsigned i = 0; i < folderCount; ++i) {
foldersToSend.push_back(theApp->glob_prefs->shareddir_list[i]);
}
// ... the categories folders ... (category 0 -> incoming)
for (unsigned i = 0; i < theApp->glob_prefs->GetCatCount(); ++i) {
foldersToSend.push_back(theApp->glob_prefs->GetCategory(i)->path);
}
// Strip duplicates
foldersToSend.sort();
foldersToSend.unique();
// Build packet
CMemFile tempfile(80);
tempfile.WriteUInt32(foldersToSend.size() + 1); // + 1 for the incomplete files
PathList::iterator it = foldersToSend.begin();
for (; it != foldersToSend.end(); ++it) {
// Note: the public shared name contains the 'raw' path, so we can recognize it again.
// the 'raw' path is determined using CPath::GetRaw()
tempfile.WriteString( theApp->sharedfiles->GetPublicSharedDirName(*it), GetUnicodeSupport() );
}
// ... and the Magic thing from the eDonkey Hybrids...
tempfile.WriteString(OP_INCOMPLETE_SHARED_FILES, GetUnicodeSupport());
// Send the packet.
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDDIRSANS);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRSANS to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::SendSharedFilesOfDirectory(const wxString& strReqDir)
{
CKnownFilePtrList list;
if (strReqDir == OP_INCOMPLETE_SHARED_FILES) {
// get all shared files from download queue
int iQueuedFiles = theApp->downloadqueue->GetFileCount();
for (int i = 0; i < iQueuedFiles; i++) {
CPartFile* pFile = theApp->downloadqueue->GetFileByIndex(i);
if (pFile == NULL || pFile->GetStatus(true) != PS_READY) {
continue;
}
list.push_back(pFile);
}
} else {
// get all shared files for the requested directory
const CPath *sharedDir = theApp->sharedfiles->GetDirForPublicSharedDirName(strReqDir);
if (sharedDir) {
theApp->sharedfiles->GetSharedFilesByDirectory(sharedDir->GetRaw(), list);
} else {
AddLogLineC(CFormat(_("User %s (%u) requested sharedfiles-list for not existing directory '%s' -> Ignored")) % GetUserName() % GetUserIDHybrid() % strReqDir);
}
}
CMemFile tempfile(80);
tempfile.WriteString(strReqDir, GetUnicodeSupport());
tempfile.WriteUInt32(list.size());
while (!list.empty()) {
if (!list.front()->IsLargeFile() || SupportsLargeFiles()) {
list.front()->CreateOfferedFilePacket(&tempfile, NULL, this);
}
list.pop_front();
}
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDFILESDIRANS);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILESDIRANS to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::SendFirewallCheckUDPRequest()
{
wxASSERT(GetKadState() == KS_FWCHECK_UDP);
if (!Kademlia::CKademlia::IsRunning()) {
SetKadState(KS_NONE);
return;
} else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
SetKadState(KS_NONE);
return;
}
CMemFile data;
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ);
theStats::AddUpOverheadKad(packet->GetPacketSize());
SafeSendPacket(packet);
}
void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile* data)
{
if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) {
//DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
return;
}
// first search if we know this IP already, if so the result might be biased and we need tell the requester
bool errorAlreadyKnown = false;
if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) {
errorAlreadyKnown = true;
} else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL) {
errorAlreadyKnown = true;
}
uint16_t remoteInternPort = data->ReadUInt16();
uint16_t remoteExternPort = data->ReadUInt16();
uint32_t senderKey = data->ReadUInt32();
if (remoteInternPort == 0) {
//DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
return;
}
// if (senderKey == 0)
// DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
CMemFile testPacket1;
testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket1.WriteUInt16(remoteInternPort);
DebugSend(Kad2FirewallUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
// if the client has a router with PAT (and therefore a different extern port than intern), test this port too
if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) {
CMemFile testPacket2;
testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket2.WriteUInt16(remoteExternPort);
DebugSend(Kad2FirewalledUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
}
//DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
}
void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback)
{
SetCryptLayerSupport((options & 0x01) != 0 && encryption);
SetCryptLayerRequest((options & 0x02) != 0 && encryption);
SetCryptLayerRequires((options & 0x04) != 0 && encryption);
SetDirectUDPCallbackSupport((options & 0x08) != 0 && callback);
}
#ifdef DEBUG_ZOMBIE_CLIENTS
void CUpDownClient::Unlink(const wxString& from)
{
std::multiset<wxString>::iterator it = m_linkedFrom.find(from);
if (it != m_linkedFrom.end()) {
m_linkedFrom.erase(it);
}
m_linked--;
if (!m_linked) {
if (m_linkedDebug) {
AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this);
}
delete this;
}
}
#else
void CUpDownClient::Unlink()
{
m_linked--;
if (!m_linked) {
delete this;
}
}
#endif
// File_checked_for_headers
| Java |
/*
* An Abstract communicator interface which implements listeners.
*/
/*
Copywrite 2013 Will Winder
This file is part of Universal Gcode Sender (UGS).
UGS 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.
UGS 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 UGS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.willwinder.universalgcodesender;
import com.willwinder.universalgcodesender.i18n.Localization;
import com.willwinder.universalgcodesender.listeners.SerialCommunicatorListener;
import com.willwinder.universalgcodesender.types.GcodeCommand;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author wwinder
*/
public abstract class AbstractCommunicator {
public static String DEFAULT_TERMINATOR = "\r\n";
private String lineTerminator;
protected Connection conn;
// Callback interfaces
ArrayList<SerialCommunicatorListener> commandSentListeners;
ArrayList<SerialCommunicatorListener> commandCompleteListeners;
ArrayList<SerialCommunicatorListener> commConsoleListeners;
ArrayList<SerialCommunicatorListener> commVerboseConsoleListeners;
ArrayList<SerialCommunicatorListener> commRawResponseListener;
private final ArrayList<Connection> connections;
public AbstractCommunicator() {
this.lineTerminator = DEFAULT_TERMINATOR;
this.commandSentListeners = new ArrayList<SerialCommunicatorListener>();
this.commandCompleteListeners = new ArrayList<SerialCommunicatorListener>();
this.commConsoleListeners = new ArrayList<SerialCommunicatorListener>();
this.commVerboseConsoleListeners = new ArrayList<SerialCommunicatorListener>();
this.commRawResponseListener = new ArrayList<SerialCommunicatorListener>();
//instanciate all known connection drivers
//TODO: Scan the classpath for classes extending Connection,
// and instantiate them dynamically.
this.connections = new ArrayList<Connection>();
this.addConnectionType(new SerialConnection());
}
final public void addConnectionType(Connection conn) {
this.connections.add(conn);
}
/*********************/
/* Serial Layer API. */
/*********************/
abstract public void setSingleStepMode(boolean enable);
abstract public boolean getSingleStepMode();
abstract public void queueStringForComm(final String input);
abstract public void sendByteImmediately(byte b) throws IOException;
abstract public boolean areActiveCommands();
abstract public void streamCommands();
abstract public void pauseSend();
abstract public void resumeSend();
abstract public void cancelSend();
abstract public void softReset();
abstract public void responseMessage(String response);
//do common operations (related to the connection, that is shared by all communicators)
protected boolean openCommPort(String name, int baud) throws Exception {
//choose port
for(Connection candidate: connections) {
if(candidate.supports(name)) {
conn = candidate;
conn.setCommunicator(this);
break;
}
}
if(conn==null) {
throw new Exception(Localization.getString("communicator.exception.port") + ": "+name);
}
//open it
conn.openPort(name, baud);
return true;
}
//do common things (related to the connection, that is shared by all communicators)
protected void closeCommPort() {
conn.closePort();
}
/** Getters & Setters. */
void setLineTerminator(String terminator) {
if (terminator == null || terminator.length() < 1) {
this.lineTerminator = DEFAULT_TERMINATOR;
} else {
this.lineTerminator = terminator;
}
}
String getLineTerminator() {
return this.lineTerminator;
}
/* ****************** */
/** Listener helpers. */
/* ****************** */
void setListenAll(SerialCommunicatorListener scl) {
this.addCommandSentListener(scl);
this.addCommandCompleteListener(scl);
this.addCommConsoleListener(scl);
this.addCommVerboseConsoleListener(scl);
this.addCommRawResponseListener(scl);
}
void addCommandSentListener(SerialCommunicatorListener scl) {
this.commandSentListeners.add(scl);
}
void addCommandCompleteListener(SerialCommunicatorListener scl) {
this.commandCompleteListeners.add(scl);
}
void addCommConsoleListener(SerialCommunicatorListener scl) {
this.commConsoleListeners.add(scl);
}
void addCommVerboseConsoleListener(SerialCommunicatorListener scl) {
this.commVerboseConsoleListeners.add(scl);
}
void addCommRawResponseListener(SerialCommunicatorListener scl) {
this.commRawResponseListener.add(scl);
}
// Helper for the console listener.
protected void sendMessageToConsoleListener(String msg) {
this.sendMessageToConsoleListener(msg, false);
}
protected void sendMessageToConsoleListener(String msg, boolean verbose) {
// Exit early if there are no listeners.
if (this.commConsoleListeners == null) {
return;
}
int verbosity;
if (!verbose) {
verbosity = CONSOLE_MESSAGE;
}
else {
verbosity = VERBOSE_CONSOLE_MESSAGE;
}
dispatchListenerEvents(verbosity, this.commConsoleListeners, msg);
}
// Serial Communicator Listener Events
protected static final int COMMAND_SENT = 1;
protected static final int COMMAND_COMPLETE = 2;
protected static final int RAW_RESPONSE = 3;
protected static final int CONSOLE_MESSAGE = 4;
protected static final int VERBOSE_CONSOLE_MESSAGE = 5;
/**
* A bunch of methods to dispatch listener events with various arguments.
*/
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, String message) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, message, null);
}
}
}
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, GcodeCommand command) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, null, command);
}
}
}
static protected void sendEventToListener(int event, SerialCommunicatorListener scl,
String string, GcodeCommand command) {
switch(event) {
case COMMAND_SENT:
scl.commandSent(string);
break;
case CONSOLE_MESSAGE:
scl.messageForConsole(string);
break;
case VERBOSE_CONSOLE_MESSAGE:
scl.verboseMessageForConsole(string);
break;
case RAW_RESPONSE:
scl.rawResponseListener(string);
default:
}
}
}
| Java |
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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/>.
*/
import React from 'react'
import ManualLink from 'browser-components/ManualLink'
const title = 'FOREACH'
const subtitle = 'Operate on a collection'
const category = 'cypherHelp'
const content = (
<>
<p>
The <code>FOREACH</code> clause is used to update data within a collection
whether components of a path, or result of aggregation.
</p>
<div className="links">
<div className="link">
<p className="title">Reference</p>
<p className="content">
<ManualLink chapter="cypher-manual" page="/clauses/foreach/">
FOREACH
</ManualLink>{' '}
manual page
</p>
</div>
<div className="link">
<p className="title">Related</p>
<p className="content">
<a help-topic="create">:help CREATE</a>
<a help-topic="delete">:help DELETE</a>
<a help-topic="set">:help SET</a>
<a help-topic="cypher">:help Cypher</a>
</p>
</div>
</div>
<section className="example">
<figure className="runnable">
<pre>
{`MATCH p = (ups)<-[DEPENDS_ON]-(device) WHERE ups.id='EPS-7001'
FOREACH (n IN nodes(p) | SET n.available = FALSE )`}
</pre>
<figcaption>
Mark all devices plugged into a failed UPS as unavailable.
</figcaption>
</figure>
</section>
</>
)
export default { title, subtitle, category, content }
| Java |
/*
* Unplayer
* Copyright (C) 2015-2019 Alexey Rochev <equeim@gmail.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/>.
*/
#include "queuemodel.h"
#include "queue.h"
namespace unplayer
{
QVariant QueueModel::data(const QModelIndex& index, int role) const
{
if (!mQueue || !index.isValid()) {
return QVariant();
}
const QueueTrack* track = mQueue->tracks()[static_cast<size_t>(index.row())].get();
switch (role) {
case UrlRole:
return track->url;
case IsLocalFileRole:
return track->url.isLocalFile();
case FilePathRole:
return track->url.path();
case TitleRole:
return track->title;
case ArtistRole:
return track->artist;
case DisplayedArtistRole:
return track->artist;
case AlbumRole:
return track->album;
case DisplayedAlbumRole:
return track->album;
case DurationRole:
return track->duration;
default:
return QVariant();
}
}
int QueueModel::rowCount(const QModelIndex&) const
{
return mQueue ? static_cast<int>(mQueue->tracks().size()) : 0;
}
Queue* QueueModel::queue() const
{
return mQueue;
}
void QueueModel::setQueue(Queue* queue)
{
if (queue == mQueue || !queue) {
return;
}
mQueue = queue;
QObject::connect(mQueue, &Queue::tracksAboutToBeAdded, this, [=](int count) {
const int first = rowCount();
beginInsertRows(QModelIndex(), first, first + count - 1);
});
QObject::connect(mQueue, &Queue::tracksAdded, this, [=]() {
endInsertRows();
});
QObject::connect(mQueue, &Queue::trackAboutToBeRemoved, this, [=](int index) {
beginRemoveRows(QModelIndex(), index, index);
});
QObject::connect(mQueue, &Queue::trackRemoved, this, [=]() {
endRemoveRows();
});
QObject::connect(mQueue, &Queue::aboutToBeCleared, this, [=]() {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
});
QObject::connect(mQueue, &Queue::cleared, this, [=]() {
endRemoveRows();
});
}
QHash<int, QByteArray> QueueModel::roleNames() const
{
return {{UrlRole, "url"},
{IsLocalFileRole, "isLocalFile"},
{FilePathRole, "filePath"},
{TitleRole, "title"},
{ArtistRole, "artist"},
{DisplayedArtistRole, "displayedArtist"},
{AlbumRole, "album"},
{DisplayedAlbumRole, "displayedAlbum"},
{DurationRole, "duration"}};
}
}
| Java |
#!/usr/bin/env node
'use strict';
/*All Includes needed for the Bot Core*/
var isfile = function(name) {
require('fs').exists(name, function(exists) {
return exists;
});
};
var jsonfile = require('jsonfile');
var configfile = 'config.json';
var Event = require('./modules/Events').eventBus; // One way Events from the Main Core System
var DiscordProxy = require('./modules/DiscordProxy'); // Proxy between Core & Plugins
var Discord = require('discord.io'); // Required for the Bot to do anything with Discord
var Plugins = require('require-all')(__dirname + '/plugins');//Loads all Plugins into the Bot
var express = require('express');
var app = express();
var bodyparser = require("body-parser");
var mongoose = require('mongoose');
/*System Related Variables & Checks*/
var SYSTEM = {
CURRENT_VERSION: require('./package.json').version,
LATEST_VERSION: null,
NPM_URL: "https://registry.npmjs.org/devbot",
HOMEPAGE_URL: require('./package.json').repository.url,
BUGREPORT_URL: require('./package.json').bugs.url,
AUTHOR: require('./package.json').author.name + " <" + require('./package.json').author.email + ">",
WEB: {
IP: "127.0.0.1",
PORT: 1337,
MONGODB: "mongodb://localhost"
}
CONFIG: null
};
console.log(`
▓█████▄ ▓█████ ██▒ █▓ ▄▄▄▄ ▒█████ ▄▄▄█████▓
▒██▀ ██▌▓█ ▀▓██░ █▒▓█████▄ ▒██▒ ██▒▓ ██▒ ▓▒
░██ █▌▒███ ▓██ █▒░▒██▒ ▄██▒██░ ██▒▒ ▓██░ ▒░
░▓█▄ ▌▒▓█ ▄ ▒██ █░░▒██░█▀ ▒██ ██░░ ▓██▓ ░
░▒████▓ ░▒████▒ ▒▀█░ ░▓█ ▀█▓░ ████▓▒░ ▒██▒ ░
▒▒▓ ▒ ░░ ▒░ ░ ░ ▐░ ░▒▓███▀▒░ ▒░▒░▒░ ▒ ░░
░ ▒ ▒ ░ ░ ░ ░ ░░ ▒░▒ ░ ░ ▒ ▒░ ░
░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ▒ ░
░ ░ ░ ░ ░ ░ ░
░ ░ ░
`);
console.log("Current Version: " + SYSTEM.CURRENT_VERSION);
console.log("Created by: " SYSTEM.AUTHOR)
require("request").get(SYSTEM.NPM_URL, function (err, res, body) {
if (err) {
console.log("[ERROR] There was a Error Checking the NPM Registry for Version Information!\nBot Shutting Down.....");
process.exit();
}
console.log("[UPDATE CHECK] Checking for Update....");
var data = JSON.parse((body));
var NPM_VERSION = data['dist-tags'].latest;
if (require("semver").lt(SYSTEM.CURRENT_VERSION, NPM_VERSION)) {
console.log("[UPDATE THE BOT]: This BOT is out of date! Your version is (" + SYSTEM.CURRENT_VERSION + ") but the latest version on NPM is (" + NPM_VERSION + ")\nWhen are you going to Update HUH!");
} else {
console.log("[UPDATE CHECKED] No Updates Found!");
}
if (isfile(configfile) == false) {
console.log("[SETUP START] Seems like this is the first time the bot has been Launched. \n[CONFIG CREATION] Creating config.json and filling it up. Please wait a momment......");
var data = {
TOKEN: null,
TRIGGER: "!",
OWNER: null
};
jsonfile.writeFile(configfile,data, function(err) {
if (err) {
console.log("[ERROR] Error in creating the Config file.\n[ERROR] Please check the permissions. Application Terminating.....");
process.exit();
} else {
console.log("[SETUP COMPLETE] Seems to be all Set. Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!");
process.exit();
}
});
} else {
console.log("[INFORMATION] Config file found! Loading.......");
jsonfile.readFile(configfile, function(err, data) {
if (err) {
console.log("Error in Parsing and Loading the Config file.\nPlease check the permissions.\nApplication Terminating.....");
process.exit();
} else {
SYSTEM.CONFIG = data;
if (SYSTEM.CONFIG.TOKEN == null) {
console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!");
process.exit();
} else if (SYSTEM.CONFIG.OWNER == null) {
console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Owner ID.\nProcess will Close now!");
process.exit();
} else {
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
var Client = new Discord.Client({
token: SYSTEM.CONFIG.TOKEN
});
DiscordProxy.addClient(Client);
DiscordProxy.registerOwner(SYSTEM.CONFIG.OWNER);
Client.on('ready', function(event) {
console.log("[DISCORD] Connected!");
Event.emit("status", true);
});
Client.on('disconnect', function(errMsg, code) {
console.log("[DISCORD] Disconnected!");
Event.emit("status", false);
Client.connect();
});
Client.on('message', function(user, userID, channelID, message, event) {
if (Client.id == userID) return;
Event.emit("message", user, userID, channelID, message, event);
var arr = message.split(" ");
if (arr[0].charAt(0) == SYSTEM.CONFIG.TRIGGER) {
Event.emit("command", arr[0].slice(1), user, userID, channelID, message);
} else if (arr[0].indexOf(Client.id.toString()) > 1) {
Event.emit("direct_command", arr[1], user, userID, channelID, message);
}
});
Client.on('presence', function(user, userID, status, game, event) {
Event.emit("presence", user, userID, status, game, event);
});
app.post("/api/webhook/:webhook/:name", function(req, res) {
console.log("[WEBHOOK RECEIVED] Received a webhook from " + req.params.webhook.toLowerCase() + " for " + req.params.name.toLowerCase());
Event.emit("webhook", req.params.webhook.toLowerCase(), req.params.name.toLowerCase(), req.headers, req.body);
res.status(200).json({ success: true });
});
app.listen(SYSTEM.WEB.IP, SYSTEM.WEB.PORT, function() {
mongoose.connect(SYSTEM.WEB.MONGODB);
Client.connect();
console.log("[BOT] API Handling System Online!");
});
}
}
});
}
});
| Java |
<div class="main-title">15, Sunday <span>2016</span>
</div>
<ul class="stage clearfix">
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>20:15 <small>GMT</small></strong></div>
<div class="cal-to"><strong>22:00 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Aldosivi
<br><small>vs</small>
<br>Atl. Rafaela</div><em><i class="fa fa-map-marker"></i>Argentina - Primera Division</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:30 <small>GMT</small></strong></div>
<div class="cal-to"><strong>0:15 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Barcelona SC
<br><small>vs</small>
<br>Emelec</div><em><i class="fa fa-map-marker"></i>Ecuador - Serie A</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>15:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>16:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Chelsea
<br><small>vs</small>
<br>Leicester City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-loss-hist uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>16:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>17:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Dinamo-Auto
<br><small>vs</small>
<br>Milsami Orhei</div><em><i class="fa fa-map-marker"></i>Moldova - Divizia Nationala</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-number-hist">2.5</div>
<div class="over-under-text-under-hist uppercase">Under<i class="fa fa-angle-down"></i></div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>15:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>16:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Everton
<br><small>vs</small>
<br>Norwich City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>2:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>3:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">FBC Melgar
<br><small>vs</small>
<br>UTC Cajamarca</div><em><i class="fa fa-map-marker"></i>Peru - Primera Division</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-loss-hist uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Guaraní PRG
<br><small>vs</small>
<br>Sol de América</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>13:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>14:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">OB Odense
<br><small>vs</small>
<br>Hobro IK</div><em><i class="fa fa-map-marker"></i>Denmark - Superligaen</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-loss-hist uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>3:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>4:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Orange County B
<br><small>vs</small>
<br>Arizona United</div><em><i class="fa fa-map-marker"></i>USA - USL</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-number-hist">2.5</div>
<div class="over-under-text-under-hist uppercase">Under<i class="fa fa-angle-down"></i></div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Rubio Nu
<br><small>vs</small>
<br>Olimpia PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Sport. Luqueño
<br><small>vs</small>
<br>Nacional PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>16:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>17:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Travnik
<br><small>vs</small>
<br>Drina Zvornik</div><em><i class="fa fa-map-marker"></i>Bosnia - Premier Liga</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>17:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>18:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Zenit
<br><small>vs</small>
<br>Lokomotiv M.</div><em><i class="fa fa-map-marker"></i>Russia - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="over-under-icon-hist">
<div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="over-under-number-hist">2.5</div>
</div>
</div>
<div class="result-top-loss-hist uppercase">LOSS</div>
</div>
</div>
</a>
</ul> | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.