repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
Stalkstalks/OpenXcom
|
src/Ufopaedia/ArticleStateTFTDArmor.cpp
|
3497
|
/*
* Copyright 2010-2015 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "../fmath.h"
#include "ArticleStateTFTD.h"
#include "ArticleStateTFTDArmor.h"
#include "../Mod/ArticleDefinition.h"
#include "../Mod/Mod.h"
#include "../Mod/Armor.h"
#include "../Engine/Game.h"
#include "../Engine/Palette.h"
#include "../Engine/LocalizedText.h"
#include "../Interface/TextList.h"
namespace OpenXcom
{
ArticleStateTFTDArmor::ArticleStateTFTDArmor(ArticleDefinitionTFTD *defs) : ArticleStateTFTD(defs), _row(0)
{
Armor *armor = _game->getMod()->getArmor(defs->id);
_lstInfo = new TextList(150, 64, 168, 110);
add(_lstInfo);
_lstInfo->setColor(Palette::blockOffset(0)+2);
_lstInfo->setColumns(2, 125, 25);
_lstInfo->setDot(true);
// Add armor values
addStat("STR_FRONT_ARMOR", armor->getFrontArmor());
addStat("STR_LEFT_ARMOR", armor->getSideArmor());
addStat("STR_RIGHT_ARMOR", armor->getSideArmor());
addStat("STR_REAR_ARMOR", armor->getRearArmor());
addStat("STR_UNDER_ARMOR", armor->getUnderArmor());
_lstInfo->addRow(0);
++_row;
// Add damage modifiers
for (int i = 0; i < DAMAGE_TYPES; ++i)
{
ItemDamageType dt = (ItemDamageType)i;
int percentage = (int)Round(armor->getDamageModifier(dt) * 100.0f);
std::string damage = getDamageTypeText(dt);
if (percentage != 100 && damage != "STR_UNKNOWN")
{
addStat(damage, Text::formatPercentage(percentage));
}
}
_lstInfo->addRow(0);
++_row;
// Add unit stats
addStat("STR_TIME_UNITS", armor->getStats()->tu, true);
addStat("STR_STAMINA", armor->getStats()->stamina, true);
addStat("STR_HEALTH", armor->getStats()->health, true);
addStat("STR_BRAVERY", armor->getStats()->bravery, true);
addStat("STR_REACTIONS", armor->getStats()->reactions, true);
addStat("STR_FIRING_ACCURACY", armor->getStats()->firing, true);
addStat("STR_THROWING_ACCURACY", armor->getStats()->throwing, true);
addStat("STR_MELEE_ACCURACY", armor->getStats()->melee, true);
addStat("STR_STRENGTH", armor->getStats()->strength, true);
addStat("STR_PSIONIC_STRENGTH", armor->getStats()->psiStrength, true);
addStat("STR_PSIONIC_SKILL", armor->getStats()->psiSkill, true);
centerAllSurfaces();
}
ArticleStateTFTDArmor::~ArticleStateTFTDArmor()
{}
void ArticleStateTFTDArmor::addStat(const std::string &label, int stat, bool plus)
{
if (stat != 0)
{
std::wostringstream ss;
if (plus && stat > 0)
ss << L"+";
ss << stat;
_lstInfo->addRow(2, tr(label).c_str(), ss.str().c_str());
_lstInfo->setCellColor(_row, 1, Palette::blockOffset(15)+4);
++_row;
}
}
void ArticleStateTFTDArmor::addStat(const std::string &label, const std::wstring &stat)
{
_lstInfo->addRow(2, tr(label).c_str(), stat.c_str());
_lstInfo->setCellColor(_row, 1, Palette::blockOffset(15)+4);
++_row;
}
}
|
gpl-3.0
|
TheCrowsJoker/mahara
|
htdocs/skin/design.php
|
34020
|
<?php
/**
*
* @package mahara
* @subpackage skin
* @author Gregor Anzelj
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
* @copyright (C) 2010-2013 Gregor Anzelj <gregor.anzelj@gmail.com>
*
*/
define('INTERNAL', true);
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'skin');
define('SECTION_PAGE', 'design');
require_once(dirname(dirname(__FILE__)) . '/init.php');
require_once('skin.php');
require_once('pieforms/pieform.php');
safe_require('artefact', 'file');
$fieldset = param_alpha('fs', 'viewskin');
$designsiteskin = param_boolean('site', false);
if (!can_use_skins(null, $designsiteskin)) {
throw new FeatureNotEnabledException();
}
if ($designsiteskin) {
define('ADMIN', 1);
if (!$USER->get('admin')) {
$SESSION->add_error_msg(get_string('accessforbiddentoadminsection'));
redirect();
}
define('MENUITEM', 'configsite/siteskins');
$goto = '/admin/site/skins.php';
$redirect = '/admin/site/skins.php';
}
else {
define('MENUITEM', 'myportfolio/skins');
$goto = '/skin/index.php';
$redirect = '/skin/index.php';
}
$id = param_integer('id', 0); // id of Skin to be edited...
$skindata = null;
if ($id > 0) {
$skinobj = new Skin($id);
if ($skinobj->can_edit()) {
$viewskin = $skinobj->get('viewskin');
// check to see if any background images being referenced have not
// been deleted from site and if they have set the value to false
if (!empty($viewskin['body_background_image'])) {
if (!record_exists('artefact', 'id', $viewskin['body_background_image'])) {
$viewskin['body_background_image'] = false;
}
}
if (!empty($viewskin['view_background_image'])) { // TODO remove this
if (!record_exists('artefact', 'id', $viewskin['view_background_image'])) {
$viewskin['view_background_image'] = false;
}
}
}
else {
throw new AccessDeniedException("You can't access and/or edit Skin with id $id");
}
define('TITLE', get_string('editskin', 'skin'));
}
else {
define('TITLE', get_string('createskin', 'skin'));
$skinobj = new Skin();
}
// Set the Skin access options (for creating or editing form)...
$designsiteskin = $designsiteskin || (isset($skinobj) && $skinobj->get('type') == 'site');
if ($designsiteskin) {
$accessoptions = array(
'site' => get_string('siteskinaccess', 'skin')
);
}
else {
$accessoptions = array(
'private' => get_string('privateskinaccess', 'skin'),
'public' => get_string('publicskinaccess', 'skin'),
);
}
// because the page has two artefact choosers in the form
// we need to handle how the browse works differently from normal
$folder = param_integer('folder', null);
$highlight = null;
if ($file = param_integer('file', 0)) {
$highlight = array($file);
}
$skintitle = $skinobj->get('title');
$skindesc = $skinobj->get('description');
$skintype = $skinobj->get('type');
$positions = array(
1 => 'Top left', 2 => 'Top', 3 => 'Top right',
4 => 'Left', 5 => 'Centre', 6 => 'Right',
7 => 'Bottom left', 8 => 'Bottom', 9 => 'Bottom right'
);
$elements = array();
$elements['id'] = array(
'type' => 'hidden',
'value' => $id,
);
$elements['viewskin'] = array(
'type' => 'fieldset',
'legend' => get_string('skingeneraloptions', 'skin'),
'class' => $fieldset != 'viewskin' ? 'collapsed' : '',
'elements' => array(
'viewskin_title' => array(
'type' => 'text',
'title' => get_string('skintitle', 'skin'),
'defaultvalue' => (!empty($skintitle) ? $skintitle : null),
),
'viewskin_description' => array(
'type' => 'textarea',
'rows' => 3,
'cols' => 40,
'resizable' => true,
'title' => get_string('skindescription', 'skin'),
'defaultvalue' => (!empty($skindesc) ? $skindesc : null),
),
'viewskin_access' => array(
'type' => 'select',
'title' => get_string('skinaccessibility1', 'skin'),
'defaultvalue' => (!empty($skintype) ? $skintype : null),
'options' => $accessoptions,
),
),
);
$elements['skinbg'] = array(
'type' => 'fieldset',
'legend' => get_string('skinbackgroundoptions1', 'skin'),
'class' => $fieldset != 'skinbg' ? 'collapsed' : '',
'elements' => array(
'body_background_color' => array(
'type' => 'color',
'title' => get_string('bodybgcolor1', 'skin'),
'defaultvalue' => (!empty($viewskin['body_background_color']) ? $viewskin['body_background_color'] : '#FFFFFF'),
'size' => 7,
'options' => array(
'transparent' => true,
),
)
)
);
// Currently site files don't work properly with site skins. And since site files are the only files that would make
// sense with site skins, we're going to just hide background images entirely for site skins for the time being.
if (!$designsiteskin) {
$elements['skinbg']['elements'] = array_merge($elements['skinbg']['elements'], array(
'body_background_image' => array(
'type' => 'filebrowser',
'title' => get_string('bodybgimage1', 'skin'),
'folder' => ((isset($folder)) ? $folder : 0),
'highlight' => $highlight,
'browse' => ((isset($folder)) ? 1 : 0),
'filters' => array(
'artefacttype' => array('image', 'profileicon'),
),
'page' => get_config('wwwroot') . 'skin/design.php?id=' . $id . '&fs=skinbg',
'config' => array(
'upload' => false,
'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
'resizeonuploaduserdefault' => $USER->get_account_preference('resizeonuploaduserdefault'),
'createfolder' => false,
'edit' => false,
'select' => true,
'selectone' => true,
),
'defaultvalue' => (!empty($viewskin['body_background_image']) ? array(intval($viewskin['body_background_image'])) : array()),
'selectlistcallback' => 'artefact_get_records_by_id',
// TODO: Make this work so skins can include site files
// 'tabs' => true,
),
'body_background_repeat' => array(
'type' => 'select',
'title' => get_string('backgroundrepeat', 'skin'),
'defaultvalue' => (!empty($viewskin['body_background_repeat']) ? intval($viewskin['body_background_repeat']) : 4),
'options' => array(
Skin::BACKGROUND_REPEAT_NO => get_string('backgroundrepeatno', 'skin'),
Skin::BACKGROUND_REPEAT_X => get_string('backgroundrepeatx', 'skin'),
Skin::BACKGROUND_REPEAT_Y => get_string('backgroundrepeaty', 'skin'),
Skin::BACKGROUND_REPEAT_BOTH => get_string('backgroundrepeatboth', 'skin'),
),
),
'body_background_attachment' => array(
'type' => 'radio',
'title' => get_string('backgroundattachment', 'skin'),
'defaultvalue' => (!empty($viewskin['body_background_repeat']) ? $viewskin['body_background_attachment'] : 'scroll'),
'options' => array(
'fixed' => get_string('backgroundfixed', 'skin'),
'scroll' => get_string('backgroundscroll', 'skin'),
),
),
'body_background_position' => array(
'type' => 'radio',
'title' => get_string('backgroundposition', 'skin'),
'defaultvalue' => (!empty($viewskin['body_background_position']) ? intval($viewskin['body_background_position']) : 1),
'rowsize' => 3,
'hiddenlabels' => false,
'options' => $positions,
)
));
}
$elements['viewbg'] = array( // TODO remove this
'type' => 'fieldset',
'legend' => get_string('viewbackgroundoptions', 'skin'),
'class' => 'hidden',
'elements' => array(
'view_background_color' => array(
'type' => 'color',
'title' => get_string('viewbgcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_background_color']) ? $viewskin['view_background_color'] : '#FFFFFF'),
'size' => 7,
'options' => array(
'transparent' => true,
),
)
)
);
if (!$designsiteskin) { // TODO remove this
$elements['viewbg']['elements'] = array_merge($elements['viewbg']['elements'], array(
'view_background_image' => array(
'type' => 'filebrowser',
'title' => get_string('viewbgimage', 'skin'),
'folder' => ((isset($folder)) ? $folder : 0),
'highlight' => $highlight,
'browse' => ((isset($folder)) ? 1 : 0),
'filters' => array(
'artefacttype' => array('image', 'profileicon'),
),
'page' => get_config('wwwroot') . 'skin/design.php?id=' . $id . '&fs=viewbg',
'config' => array(
'upload' => false,
'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
'resizeonuploaduserdefault' => $USER->get_account_preference('resizeonuploaduserdefault'),
'createfolder' => false,
'edit' => false,
'select' => true,
'selectone' => true,
),
'defaultvalue' => (!empty($viewskin['view_background_image']) ? array(intval($viewskin['view_background_image'])) : array()),
'selectlistcallback' => 'artefact_get_records_by_id',
// TODO: make this work, so skins can include site files
// 'tabs' => true,
),
'view_background_repeat' => array(
'type' => 'select',
'title' => get_string('backgroundrepeat', 'skin'),
'defaultvalue' => (!empty($viewskin['view_background_repeat']) ? intval($viewskin['view_background_repeat']) : 4),
'options' => array(
Skin::BACKGROUND_REPEAT_NO => get_string('backgroundrepeatno', 'skin'),
Skin::BACKGROUND_REPEAT_X => get_string('backgroundrepeatx', 'skin'),
Skin::BACKGROUND_REPEAT_Y => get_string('backgroundrepeaty', 'skin'),
Skin::BACKGROUND_REPEAT_BOTH => get_string('backgroundrepeatboth', 'skin'),
),
),
'view_background_attachment' => array(
'type' => 'radio',
'title' => get_string('backgroundattachment', 'skin'),
'defaultvalue' => (!empty($viewskin['view_background_repeat']) ? $viewskin['view_background_attachment'] : 'scroll'),
'options' => array(
'fixed' => get_string('backgroundfixed', 'skin'),
'scroll' => get_string('backgroundscroll', 'skin'),
),
),
'view_background_position' => array(
'type' => 'radio',
'title' => get_string('backgroundposition', 'skin'),
'defaultvalue' => (!empty($viewskin['view_background_position']) ? intval($viewskin['view_background_position']) : 1),
'rowsize' => 3,
'hiddenlabels' => false,
'options' => $positions,
),
'view_background_width' => array(
'type' => 'select',
'title' => get_string('viewwidth', 'skin'),
'defaultvalue' => (!empty($viewskin['view_background_width']) ? intval($viewskin['view_background_width']) : 90),
'options' => array(
50 => '50%',
60 => '60%',
70 => '70%',
80 => '80%',
90 => '90%',
100 => '100%',
),
),
));
}
$elements['viewheader'] = array( // TODO remove this
'type' => 'fieldset',
'legend' => get_string('viewheaderoptions', 'skin'),
'class' => 'hidden',
'elements' => array(
'header_background_color' => array(
'type' => 'color',
'title' => get_string('backgroundcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['header_background_color']) ? $viewskin['header_background_color'] : '#CCCCCC'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'header_text_font_color' => array(
'type' => 'color',
'title' => get_string('textcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['header_text_font_color']) ? $viewskin['header_text_font_color'] : '#000000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'header_link_normal_color' => array(
'type' => 'color',
'title' => get_string('normallinkcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['header_link_normal_color']) ? $viewskin['header_link_normal_color'] : '#0000EE'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'header_link_normal_underline' => array(
'type' => 'switchbox',
'title' => get_string('linkunderlined', 'skin'),
'defaultvalue' => (isset($viewskin['header_link_normal_underline']) and intval($viewskin['header_link_normal_underline']) == 1 ? 'checked' : ''),
),
'header_link_hover_color' => array(
'type' => 'color',
'title' => get_string('hoverlinkcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['header_link_hover_color']) ? $viewskin['header_link_hover_color'] : '#EE0000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'header_link_hover_underline' => array(
'type' => 'switchbox',
'title' => get_string('linkunderlined', 'skin'),
'defaultvalue' => (isset($viewskin['header_link_hover_underline']) and intval($viewskin['header_link_hover_underline']) == 1 ? 'checked' : ''),
),
'header_logo_image' => array(
'type' => 'radio',
'id' => 'designskinform_header_logo',
'title' => get_string('headerlogoimage1', 'skin'),
'defaultvalue' => (!empty($viewskin['header_logo_image']) ? $viewskin['header_logo_image'] : 'normal'),
'options' => array(
'normal' => get_string('headerlogoimagenormal', 'skin'),
'light' => get_string('headerlogoimagelight1', 'skin'),
'dark' => get_string('headerlogoimagedark1', 'skin'),
),
'separator' => '<br />',
),
),
);
$elements['viewcontent'] = array(
'type' => 'fieldset',
'legend' => get_string('viewcontentoptions1', 'skin'),
'class' => $fieldset != 'viewcontent' ? 'collapsed' : '',
'elements' => array(
'view_heading_font_family' => array(
'type' => 'select',
'title' => get_string('headingfontfamily', 'skin'),
'defaultvalue' => (!empty($viewskin['view_heading_font_family']) ? $viewskin['view_heading_font_family'] : 'Arial'),
'width' => 144,
'options' => Skin::get_all_font_options(),
),
'view_text_font_family' => array(
'type' => 'select',
'title' => get_string('textfontfamily', 'skin'),
'defaultvalue' => (!empty($viewskin['view_text_font_family']) ? $viewskin['view_text_font_family'] : 'Arial'),
'width' => 144,
'options' => Skin::get_textonly_font_options(),
),
'view_text_font_size' => array(
'type' => 'select',
'title' => get_string('fontsize', 'skin'),
'defaultvalue' => (!empty($viewskin['view_text_font_size']) ? $viewskin['view_text_font_size'] : 'small'),
'width' => 144,
'options' => array(
'xx-small' => array('value' => get_string('fontsizesmallest', 'skin'), 'style' => 'font-size: xx-small;'),
'x-small' => array('value' => get_string('fontsizesmaller', 'skin'), 'style' => 'font-size: x-small;'),
'small' => array('value' => get_string('fontsizesmall', 'skin'), 'style' => 'font-size: small;'),
'medium' => array('value' => get_string('fontsizemedium', 'skin'), 'style' => 'font-size: medium;'),
'large' => array('value' => get_string('fontsizelarge', 'skin'), 'style' => 'font-size: large;'),
'x-large' => array('value' => get_string('fontsizelarger', 'skin'), 'style' => 'font-size: x-large;'),
'xx-large' => array('value' => get_string('fontsizelargest', 'skin'), 'style' => 'font-size: xx-large;'),
),
),
'view_text_font_color' => array(
'type' => 'color',
'title' => get_string('textcolor', 'skin'),
'description' => get_string('textcolordescription', 'skin'),
'defaultvalue' => (!empty($viewskin['view_text_font_color']) ? $viewskin['view_text_font_color'] : '#000000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_text_heading_color' => array(
'type' => 'color',
'title' => get_string('headingcolor', 'skin'),
'description' => get_string('headingcolordescription', 'skin'),
'defaultvalue' => (!empty($viewskin['view_text_heading_color']) ? $viewskin['view_text_heading_color'] : '#000000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_text_emphasized_color' => array(
'type' => 'color',
'title' => get_string('emphasizedcolor', 'skin'),
'description' => get_string('emphasizedcolordescription', 'skin'),
'defaultvalue' => (!empty($viewskin['view_text_emphasized_color']) ? $viewskin['view_text_emphasized_color'] : '#000000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_link_normal_color' => array(
'type' => 'color',
'title' => get_string('normallinkcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_link_normal_color']) ? $viewskin['view_link_normal_color'] : '#0000EE'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_link_normal_underline' => array(
'type' => 'switchbox',
'title' => get_string('linkunderlined', 'skin'),
'defaultvalue' => (isset($viewskin['view_link_normal_underline']) and intval($viewskin['view_link_normal_underline']) == 1 ? 'checked' : ''),
),
'view_link_hover_color' => array(
'type' => 'color',
'title' => get_string('hoverlinkcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_link_hover_color']) ? $viewskin['view_link_hover_color'] : '#EE0000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_link_hover_underline' => array(
'type' => 'switchbox',
'title' => get_string('linkunderlined', 'skin'),
'defaultvalue' => (isset($viewskin['view_link_hover_underline']) and intval($viewskin['view_link_hover_underline']) == 1 ? 'checked' : ''),
),
),
);
$elements['viewtable'] = array( // TODO remove this
'type' => 'fieldset',
'legend' => get_string('viewtableoptions', 'skin'),
'class' => 'hidden',
'elements' => array(
'view_table_border_color' => array(
'type' => 'color',
'title' => get_string('tableborder', 'skin'),
'defaultvalue' => (!empty($viewskin['view_table_border_color']) ? $viewskin['view_table_border_color'] : '#CCCCCC'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_table_header_color' => array(
'type' => 'color',
'title' => get_string('tableheader', 'skin'),
'defaultvalue' => (!empty($viewskin['view_table_header_color']) ? $viewskin['view_table_header_color'] : '#CCCCCC'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_table_header_text_color' => array(
'type' => 'color',
'title' => get_string('tableheadertext', 'skin'),
'defaultvalue' => (!empty($viewskin['view_table_header_text_color']) ? $viewskin['view_table_header_text_color'] : '#000000'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_table_odd_row_color' => array(
'type' => 'color',
'title' => get_string('tableoddrows', 'skin'),
'defaultvalue' => (!empty($viewskin['view_table_odd_row_color']) ? $viewskin['view_table_odd_row_color'] : '#EEEEEE'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_table_even_row_color' => array(
'type' => 'color',
'title' => get_string('tableevenrows', 'skin'),
'defaultvalue' => (!empty($viewskin['view_table_even_row_color']) ? $viewskin['view_table_even_row_color'] : '#FFFFFF'),
'size' => 7,
'options' => array(
'transparent' => true,
),
),
'view_button_normal_color' => array(
'type' => 'color',
'title' => get_string('normalbuttoncolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_button_normal_color']) ? $viewskin['view_button_normal_color'] : '#CCCCCC'),
'options' => array(
'transparent' => true,
),
),
'view_button_hover_color' => array(
'type' => 'color',
'title' => get_string('hoverbuttoncolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_button_hover_color']) ? $viewskin['view_button_hover_color'] : '#EEEEEE'),
'options' => array(
'transparent' => true,
),
),
'view_button_text_color' => array(
'type' => 'color',
'title' => get_string('buttontextcolor', 'skin'),
'defaultvalue' => (!empty($viewskin['view_button_text_color']) ? $viewskin['view_button_text_color'] : '#FFFFFF'),
'options' => array(
'transparent' => true,
),
),
),
);
$elements['viewadvanced'] = array(
'type' => 'fieldset',
'legend' => get_string('viewadvancedoptions', 'skin'),
'class' => $fieldset != 'viewadvanced' ? 'collapsed' : '',
'elements' => array(
'view_custom_css' => array(
'type' => 'textarea',
'rows' => 7,
'cols' => 50,
'style' => 'font-family:monospace',
'resizable' => true,
'fullwidth' => true,
'title' => get_string('skincustomcss','skin'),
'description' => get_string('skincustomcssdescription', 'skin'),
'defaultvalue' => ((!empty($viewskin['view_custom_css'])) ? $viewskin['view_custom_css'] : null),
),
),
);
$elements['fs'] = array(
'type' => 'hidden',
'value' => $fieldset,
);
$elements['submit'] = array(
'type' => 'submitcancel',
'class' => 'btn-primary',
'value' => array(get_string('save', 'mahara'), get_string('cancel', 'mahara')),
'goto' => get_config('wwwroot') . $goto,
);
$designskinform = pieform(array(
'name' => 'designskinform',
'class' => 'jstabs form-group-nested',
'method' => 'post',
//'jsform' => true,
'plugintype' => 'core',
'pluginname' => 'skin',
'renderer' => 'div', // don't change unless you also modify design.js to not require tables.
'autofocus' => false,
'configdirs' => array(get_config('libroot') . 'form/', get_config('docroot') . 'artefact/file/form/'),
'elements' => $elements
));
$smarty = smarty(array('jquery', 'tabs'), array(), array(
'mahara' => array(
'tab',
'selected',
),
));
$smarty->assign('LANG', substr($CFG->lang, 0, 2));
$smarty->assign('USER', $USER);
$smarty->assign('designskinform', $designskinform);
$smarty->assign('PAGEHEADING', hsc(TITLE));
$smarty->display('skin/design.tpl');
function designskinform_validate(Pieform $form, $values) {
global $USER;
if (isset($values['viewskin_access']) && !($values['viewskin_access'] == 'site')) {
$artefactfields = array(
'body_background_image',
'view_background_image'
);
foreach ($artefactfields as $field) {
if (empty($values[$field])) {
continue;
}
$obj = new ArtefactTypeImage($values[$field]);
// Make sure the user has access to each of the image artefacts they're trying to
// embed. This will indicate that they've hacked the HTTP request, so we don't
// need to bother with a clean response.
if (!$USER->can_publish_artefact($obj)) {
throw new AccessDeniedException();
}
}
}
}
function designskinform_submit(Pieform $form, $values) {
global $USER, $SESSION, $redirect;
$siteskin = (isset($values['viewskin_access']) && ($values['viewskin_access'] == 'site'));
// Only an admin can create a site skin
if ($siteskin && !$USER->get('admin')) {
$values['viewskin_access'] = 'private';
}
// Join all view skin css/formating data to array...
$skin = array();
$skin['body_background_color'] = $values['body_background_color'];
if (!$siteskin) {
$skin['body_background_image'] = $values['body_background_image'];
$skin['body_background_repeat'] = $values['body_background_repeat'];
$skin['body_background_attachment'] = $values['body_background_attachment'];
$skin['body_background_position'] = $values['body_background_position'];
}
$skin['header_background_color'] = $values['header_background_color']; // TODO remove this
$skin['header_text_font_color'] = $values['header_text_font_color']; // TODO remove this
$skin['header_link_normal_color'] = $values['header_link_normal_color']; // TODO remove this
$skin['header_link_normal_underline'] = $values['header_link_normal_underline']; // TODO remove this
$skin['header_link_hover_color'] = $values['header_link_hover_color']; // TODO remove this
$skin['header_link_hover_underline'] = $values['header_link_hover_underline']; // TODO remove this
$skin['header_logo_image'] = $values['header_logo_image']; // TODO remove this
$skin['view_background_color'] = $values['view_background_color']; // TODO remove this
if (!$siteskin) { // TODO remove this
$skin['view_background_image'] = $values['view_background_image'];
$skin['view_background_repeat'] = $values['view_background_repeat'];
$skin['view_background_attachment'] = $values['view_background_attachment'];
$skin['view_background_position'] = $values['view_background_position'];
$skin['view_background_width'] = $values['view_background_width'];
}
$skin['view_text_font_family'] = $values['view_text_font_family'];
$skin['view_heading_font_family'] = $values['view_heading_font_family'];
$skin['view_text_font_size'] = $values['view_text_font_size'];
$skin['view_text_font_color'] = $values['view_text_font_color'];
$skin['view_text_heading_color'] = $values['view_text_heading_color'];
$skin['view_text_emphasized_color'] = $values['view_text_emphasized_color'];
$skin['view_link_normal_color'] = $values['view_link_normal_color'];
$skin['view_link_normal_underline'] = $values['view_link_normal_underline'];
$skin['view_link_hover_color'] = $values['view_link_hover_color'];
$skin['view_link_hover_underline'] = $values['view_link_hover_underline'];
$skin['view_table_border_color'] = $values['view_table_border_color']; // TODO remove this
$skin['view_table_header_color'] = $values['view_table_header_color']; // TODO remove this
$skin['view_table_header_text_color'] = $values['view_table_header_text_color']; // TODO remove this
$skin['view_table_odd_row_color'] = $values['view_table_odd_row_color']; // TODO remove this
$skin['view_table_even_row_color'] = $values['view_table_even_row_color']; // TODO remove this
$skin['view_button_normal_color'] = $values['view_button_normal_color']; // TODO remove this
$skin['view_button_hover_color'] = $values['view_button_hover_color']; // TODO remove this
$skin['view_button_text_color'] = $values['view_button_text_color']; // TODO remove this
$skin['view_custom_css'] = clean_css($values['view_custom_css'], $preserve_css=true);
$viewskin = array();
$viewskin['id'] = $values['id'];
if ($values['viewskin_title'] <> '') {
$viewskin['title'] = $values['viewskin_title'];
}
$viewskin['description'] = $values['viewskin_description'];
$viewskin['owner'] = $USER->get('id');
$viewskin['type'] = $values['viewskin_access'];
$viewskin['viewskin'] = $skin;
Skin::create($viewskin);
$SESSION->add_ok_msg(get_string('skinsaved', 'skin'));
redirect($redirect);
}
|
gpl-3.0
|
dmitry-vlasov/mdl
|
src/mdl/study/mdl_study_Fitness.cpp
|
10674
|
/*****************************************************************************/
/* Project name: mdl - mathematics development language */
/* File Name: mdl_study_Fitness.cpp */
/* Description: a set of trees - for fitness evaluation */
/* Copyright: (c) 2006-2009 Dmitri Vlasov */
/* Author: Dmitri Yurievich Vlasov, Novosibirsk, Russia */
/* Email: vlasov at academ.org */
/* URL: http://mathdevlanguage.sourceforge.net */
/* Modified by: */
/* License: GNU General Public License Version 3 */
/*****************************************************************************/
#pragma once
namespace mdl {
namespace study {
/****************************
* Public members
****************************/
inline
Fitness :: Fitness (Format& format, Sample* sample) :
format_ (format),
subFormat_ (format_),
treeVector_ (NULL),
sample_ (sample) {
//subFormat_.setVerbosity (Config :: VERBOSE_EXT);
//subFormat_.setVerbosity (Config :: VERBOSE_MIN);
}
Fitness :: ~ Fitness() {
deleteAggregateObject (treeVector_);
}
using manipulator :: mode;
void
Fitness :: showTrees() const
{
String message (1024);
prover :: Mode m;
m.setValue (prover :: Mode :: SHOW_UP_TREE_CARD);
m.setValue (prover :: Mode :: SHOW_UP_TREE_LEVELS);
m.setValue (prover :: Mode :: SHOW_UP_TREE_LEVELS_CARD);
message << mode << m;
for (value :: Integer i = 0; i < treeVector_->getSize(); ++ i) {
Tree_* tree = treeVector_->getValue (i);
tree->show (message);
}
std :: cout << message << std :: endl;
}
using manipulator :: endLine;
using manipulator :: underline;
using manipulator :: mode;
value :: Real
Fitness :: eval (const Sample_* sample) const
{
if (sample == NULL) {
return evalAll();
} else {
return evalFor (sample);
}
}
using manipulator :: iterate;
using manipulator :: tab;
using manipulator :: space;
// object :: Object implementation
void
Fitness :: commitSuicide() {
delete this;
}
Size_t
Fitness :: getVolume() const
{
Size_t volume = 0;
volume += format_.getVolume();
volume += subFormat_.getVolume();
volume += getAggregateVolume (treeVector_);
return volume;
}
Size_t
Fitness :: getSizeOf() const {
return sizeof (Fitness);
}
void
Fitness :: show (String& string) const {
}
/****************************
* Private members
****************************/
void
Fitness :: build (Time& timeLimit)
{
if (treeVector_ != NULL) {
delete treeVector_;
}
treeVector_ = new TreeVector_ (sample_->getPrimary().getSize());
format_.message() << "building test trees";
format_.showStart (timeLimit);
Time limit = timeLimit;
const value :: Integer size = sample_->getPrimary().getSize();
for (index :: Assertion k = 0; k < size; ++ k) {
const value :: Integer index = sample_->getPrimary().getValue (k);
const mdl :: Assertion* assertion = Math :: assertions()->getTheorem (index);
if (assertion->getName() == Config :: excludeAssertion()) {
continue;
}
Time treeLimit = limit / (size - k);
addTree (assertion, treeLimit, size);
limit -= format_.getTimer().getSeconds();
}
format_.showFinal();
format_.message() << "fitness = " << eval() << "%";
format_.showMessage();
timeLimit -= format_.getTimer().getSeconds();
}
void
Fitness :: addTree
(
const mdl :: Assertion* assertion,
const Time timeLimit,
const value :: Integer size
)
{
enum {
TREE_SIZE_TO_SAMPLE_SIZE_FACTOR = 1024 * 4
};
const value :: Integer sizeLimit = size * TREE_SIZE_TO_SAMPLE_SIZE_FACTOR;
const form :: Theorem* theorem = dynamic_cast<const form :: Theorem*>(assertion);
for (value :: Integer i = 0; i < theorem->getProofVector().getSize(); ++ i) {
const mdl :: Proof* proof = theorem->getProofVector().getValue (i);
for (index :: Arity j = 0; j < proof->getQedArity(); ++ j) {
const mdl :: proof :: Qed* qed = proof->getQed (j);
const mdl :: proof :: Step* step = qed->getStep();
mdl :: proof :: Question* question = const_cast<mdl :: proof :: Step*>(step)->questionSelf();
Format subSubFormat (subFormat_, true);
//Tree_* tree = new Tree_ (subFormat_, subSubFormat, const_cast<mdl :: proof :: Step*>(step));
Tree_* tree = new Tree_ (subFormat_, subSubFormat, question);
tree->init();
tree->getTimers()->switchOff();
subFormat_.message() << "building a tree for ";
theorem->replicateName (subFormat_.message());
subFormat_.showStart();
tree->growUpForLearning (timeLimit, sizeLimit);
if (subFormat_.isPrintable()) {
prover :: Mode newMode;
prover :: Mode oldMode (subFormat_.message().getMode());
newMode.setValue (prover :: Mode :: SHOW_UP_TREE_CARD);
newMode.setValue (prover :: Mode :: SHOW_UP_TREE_EXP_VOLUME);
//newMode.setValue (prover :: Mode :: SHOW_UP_TREE_LEVELS_CARD);
//newMode.setValue (prover :: Mode :: SHOW_UP_TREE_LEVELS);
subFormat_.message() << mode << newMode;
tree->show (subFormat_.message());
subFormat_.message() << mode << oldMode;
}
subFormat_.showFinal();
treeVector_->add (tree);
}
break;
}
}
#ifdef MULTY_THREADED
value :: Real
Fitness :: evalAllMultyThreaded() const
{
const value :: Integer threadCount = Config :: getConcurrency (Config :: THREADS);
pthread_t threads [threadCount];
Arguments_ arguments [threadCount];
for (int i = 0; i < threadCount; ++ i) {
arguments [i].threadIndex_ = i;
arguments [i].threadCount_ = threadCount;
arguments [i].trees_ = treeVector_;
pthread_create (threads + i, NULL, &evalAllInThread, reinterpret_cast<void*>(arguments + i));
}
value :: Real sumFitness = 0;
for (int i = 0; i < threadCount; ++ i) {
Result_* result = NULL;
pthread_join (threads [i], reinterpret_cast<void**>(&result));
sumFitness += result->fitness_;
delete result;
}
return sumFitness / treeVector_->getSize();
}
value :: Real
Fitness :: evalForMultyThreaded (const Sample_* sample) const
{
const value :: Integer threadCount = Config :: getConcurrency (Config :: THREADS);
pthread_t threads [threadCount];
Arguments_ arguments [threadCount];
for (int i = 0; i < threadCount; ++ i) {
arguments [i].sample_ = sample;
arguments [i].threadIndex_ = i;
arguments [i].threadCount_ = threadCount;
arguments [i].trees_ = treeVector_;
pthread_create (threads + i, NULL, &evalForInThread, reinterpret_cast<void*>(arguments + i));
}
Error* error = NULL;
value :: Real sumFitness = 0;
for (int i = 0; i < threadCount; ++ i) {
Result_* result = NULL;
pthread_join (threads [i], reinterpret_cast<void**>(&result));
sumFitness += result->fitness_;
if (result->error_ != NULL) {
result->error_->setNext (error);
error = result->error_;
}
delete result;
}
if (error == NULL) {
return sumFitness / sample->getSize();
} else {
throw error;
}
}
#endif
inline value :: Real
Fitness :: evalAll() const
{
#ifdef MULTY_THREADED
if (Config :: getConcurrency (Config :: THREADS) == 1) {
return evalAllSingleThreaded();
} else {
return evalAllMultyThreaded();
}
#else
return evalAllSingleThreaded();
#endif
}
inline value :: Real
Fitness :: evalFor (const Sample_* sample) const
{
#ifdef MULTY_THREADED
if (Config :: getConcurrency (Config :: THREADS) == 1) {
return evalForSingleThreaded (sample);
} else {
return evalForMultyThreaded (sample);
}
#else
return evalForSingleThreaded (sample);
#endif
}
value :: Real
Fitness :: evalAllSingleThreaded() const
{
value :: Real sumFitness = 0;
for (value :: Integer i = 0; i < treeVector_->getSize(); ++ i) {
const Tree_* tree = treeVector_->getValue (i);
const value :: Real fitness = tree->evalFitness();
sumFitness += fitness;
}
return sumFitness / treeVector_->getSize();
}
value :: Real
Fitness :: evalForSingleThreaded (const Sample_* sample) const
{
value :: Real sumFitness = 0;
for (value :: Integer i = 0; i < sample->getSize(); ++ i) {
const value :: Integer index = sample->getIndex (i);
const Tree_* tree = treeVector_->getValue (index);
const value :: Real fitness = tree->evalFitness();
sumFitness += fitness;
}
return sumFitness / sample->getSize();
}
/**********************
* Functions
**********************/
#ifdef MULTY_THREADED
void* evalAllInThread (void* pointer)
{
Error* error = NULL;
Memory :: pile().registerThread();
Fitness :: Arguments_* arguments = reinterpret_cast<Fitness :: Arguments_*>(pointer);
value :: Real sumFitness = 0;
const value :: Integer threadCount = arguments->threadCount_;
for (value :: Integer i = 0; i < arguments->trees_->getSize(); ++ i) {
if (i % threadCount != arguments->threadIndex_) {
continue;
}
try {
const Fitness :: Tree_* tree = arguments->trees_->getValue (i);
const value :: Real fitness = tree->evalFitness();
sumFitness += fitness;
} catch (Error* e) {
error = e;
break;
} catch (std :: exception& exception) {
error = new Error (Error :: SEMANTIC, exception.what());
break;
} catch (...) {
error = new Error (Error :: SEMANTIC, "unknown exception.");
break;
}
}
Memory :: pile().releaseThread();
return new Fitness :: Result_ (sumFitness, error);
}
void* evalForInThread (void* pointer)
{
Error* error = NULL;
Memory :: pile().registerThread();
Fitness :: Arguments_* arguments = reinterpret_cast<Fitness :: Arguments_*>(pointer);
value :: Real sumFitness = 0;
const value :: Integer threadCount = arguments->threadCount_;
typedef
sampler :: Sample<allocator :: Heap>
Sample_;
const Sample_* sample = arguments->sample_;
for (value :: Integer i = 0; i < sample->getSize(); ++ i) {
if (i % threadCount != arguments->threadIndex_) {
continue;
}
try {
const value :: Integer index = sample->getIndex (i);
const Fitness :: Tree_* tree = arguments->trees_->getValue (index);
const value :: Real fitness = tree->evalFitness();
sumFitness += fitness;
} catch (Error* e) {
error = e;
break;
} catch (std :: exception& exception) {
error = new Error (Error :: SEMANTIC, exception.what());
break;
} catch (...) {
error = new Error (Error :: SEMANTIC, "unknown exception.");
break;
}
}
Memory :: pile().releaseThread();
return new Fitness :: Result_ (sumFitness, error);
}
#endif
}
}
|
gpl-3.0
|
mvcds/valid
|
MVCDS.Valid/MVCDS.Valid.Test.Unit/Get_Results.cs
|
1267
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVCDS.Valid.Library.Validators;
namespace MVCDS.Valid.Test.Unit
{
[TestClass]
public class Get_Results
{
[TestMethod]
public void Compose_A_Rule_Using_Functions()
{
Validator<string> validator = new Validator<string>("password's length")
.Fail(s => s == null)
.Prepare(s => s.Trim())
.Fail(s => string.IsNullOrWhiteSpace(s))
.Succeed(s => s.Length >= 3 && s.Length <= 16);
Assert.IsFalse(validator.Validate(null));
Assert.IsFalse(validator.Validate(new string('a', 1)));
Assert.IsTrue(validator.Validate(new string('a', 5)));
Assert.IsFalse(validator.Validate(new string('a', 25)));
}
[TestMethod]
public void Validate_As_String()
{
StringValidator validator = new StringValidator("password's length", 3, 16, false);
Assert.IsFalse(validator.Validate(null));
Assert.IsFalse(validator.Validate(new string('a', 1)));
Assert.IsTrue(validator.Validate(new string('a', 5)));
Assert.IsFalse(validator.Validate(new string('a', 25)));
}
}
}
|
gpl-3.0
|
waveform80/tvrip
|
tvrip/const.py
|
1029
|
# vim: set et sw=4 sts=4:
# Copyright 2012-2017 Dave Jones <dave@waveform.org.uk>.
#
# This file is part of tvrip.
#
# tvrip 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.
#
# tvrip 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
# tvrip. If not, see <http://www.gnu.org/licenses/>.
"""Contains suite-level constants defined as globals"""
import os
# The path under which tvrip-related data will be kept
XDG_CONFIG_HOME = os.environ.get(
'XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
DATADIR = os.environ.get(
'TVRIP_CONFIG', os.path.join(XDG_CONFIG_HOME, 'tvrip'))
|
gpl-3.0
|
geosolutions-it/geofence
|
src/services/modules/rest/api/src/main/java/it/geosolutions/geofence/services/rest/model/RESTShortInstanceList.java
|
2067
|
/*
* Copyright (C) 2007 - 2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* 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 it.geosolutions.geofence.services.rest.model;
import it.geosolutions.geofence.services.dto.ShortInstance;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author ETj (etj at geo-solutions.it)
*/
@XmlRootElement(name = "GSInstanceList")
public class RESTShortInstanceList implements Iterable<ShortInstance> {
private List<ShortInstance> list;
public RESTShortInstanceList() {
this(10);
}
public RESTShortInstanceList(List<ShortInstance> list) {
this.list = list;
}
public RESTShortInstanceList(int initialCapacity) {
list = new ArrayList<ShortInstance>(initialCapacity);
}
@XmlElement(name = "Instance")
public List<ShortInstance> getList() {
return list;
}
public void setList(List<ShortInstance> list) {
this.list = list;
}
public void add(ShortInstance instance) {
list.add(instance);
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + list.size() + " gs instances]";
}
@Override
public Iterator<ShortInstance> iterator() {
return list.iterator();
}
}
|
gpl-3.0
|
rightscale/rainbows
|
lib/rainbows/event_machine.rb
|
4324
|
# -*- encoding: binary -*-
require 'eventmachine'
EM::VERSION >= '0.12.10' or abort 'eventmachine 0.12.10 is required'
# Implements a basic single-threaded event model with
# {EventMachine}[http://rubyeventmachine.com/]. It is capable of
# handling thousands of simultaneous client connections, but with only
# a single-threaded app dispatch. It is suited for slow clients,
# and can work with slow applications via asynchronous libraries such as
# {async_sinatra}[http://github.com/raggi/async_sinatra],
# {Cramp}[http://cramp.in/],
# and {rack-fiber_pool}[http://github.com/mperham/rack-fiber_pool].
#
# It does not require your Rack application to be thread-safe,
# reentrancy is only required for the DevFdResponse body
# generator.
#
# Compatibility: Whatever \EventMachine ~> 0.12.10 and Unicorn both
# support, currently Ruby 1.8/1.9.
#
# This model is compatible with users of "async.callback" in the Rack
# environment such as
# {async_sinatra}[http://github.com/raggi/async_sinatra].
#
# For a complete asynchronous framework,
# {Cramp}[http://cramp.in/] is fully
# supported when using this concurrency model.
#
# This model is fully-compatible with
# {rack-fiber_pool}[http://github.com/mperham/rack-fiber_pool]
# which allows each request to run inside its own \Fiber after
# all request processing is complete.
#
# Merb (and other frameworks/apps) supporting +deferred?+ execution as
# documented at Rainbows::EventMachine::TryDefer
#
# This model does not implement as streaming "rack.input" which allows
# the Rack application to process data as it arrives. This means
# "rack.input" will be fully buffered in memory or to a temporary file
# before the application is entered.
#
# === RubyGem Requirements
#
# * event_machine 0.12.10
module Rainbows::EventMachine
autoload :ResponsePipe, 'rainbows/event_machine/response_pipe'
autoload :ResponseChunkPipe, 'rainbows/event_machine/response_chunk_pipe'
autoload :TryDefer, 'rainbows/event_machine/try_defer'
autoload :Client, 'rainbows/event_machine/client'
include Rainbows::Base
# Cramp (and possibly others) can subclass Rainbows::EventMachine::Client
# and provide the :em_client_class option. We /don't/ want to load
# Rainbows::EventMachine::Client in the master process since we need
# reloadability.
def em_client_class
case klass = Rainbows::O[:em_client_class]
when Proc
klass.call # e.g.: proc { Cramp::WebSocket::Rainbows }
when Symbol, String
eval(klass.to_s) # Object.const_get won't resolve multi-level paths
else # @use should be either :EventMachine or :NeverBlock
Rainbows.const_get(@use).const_get(:Client)
end
end
# runs inside each forked worker, this sits around and waits
# for connections and doesn't die until the parent dies (or is
# given a INT, QUIT, or TERM signal)
def worker_loop(worker) # :nodoc:
init_worker_process(worker)
server = Rainbows.server
server.app.respond_to?(:deferred?) and
server.app = TryDefer.new(server.app)
# enable them both, should be non-fatal if not supported
EM.epoll
EM.kqueue
logger.info "#@use: epoll=#{EM.epoll?} kqueue=#{EM.kqueue?}"
client_class = em_client_class
max = worker_connections + LISTENERS.size
Rainbows::EventMachine::Server.const_set(:MAX, max)
Rainbows::EventMachine::Server.const_set(:CL, client_class)
Rainbows::EventMachine::Client.const_set(:APP, Rainbows.server.app)
EM.run {
conns = EM.instance_variable_get(:@conns) or
raise RuntimeError, "EM @conns instance variable not accessible!"
Rainbows::EventMachine::Server.const_set(:CUR, conns)
Rainbows.at_quit do
EM.next_tick do
LISTENERS.clear
conns.each_value do |c|
case c
when client_class
c.quit
when Rainbows::EventMachine::Server
c.detach
end
end
end
end
EM.add_periodic_timer(1) do
EM.stop if ! Rainbows.tick && conns.empty? && EM.reactor_running?
end
LISTENERS.map! do |s|
EM.watch(s, Rainbows::EventMachine::Server) do |c|
c.notify_readable = true
end
end
}
EM.reactor_thread.join if EM.reactor_running?
end
end
# :enddoc:
require 'rainbows/event_machine/server'
|
gpl-3.0
|
arthurgregorio/web-budget
|
src/main/java/br/com/webbudget/domain/entities/configuration/StoreType.java
|
1422
|
/*
* Copyright (C) 2018 Arthur Gregorio, AG.Software
*
* 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 br.com.webbudget.domain.entities.configuration;
/**
* This enum represents the types of authentication strategies to use with the {@link User}.
*
* @author Arthur Gregorio
*
* @version 1.0.0
* @since 3.0.0, 07/03/2018
*/
public enum StoreType {
LDAP("store-type.ldap"),
LOCAL("store-type.local");
private final String description;
/**
* Constructor
*
* @param description the description for this enum, also is the i18n key
*/
StoreType(String description) {
this.description = description;
}
/**
* {@inheritDoc}
*
* @return
*/
@Override
public String toString() {
return this.description;
}
}
|
gpl-3.0
|
sguazt/dcsj-sharegrid-portal
|
src/java/it/unipmn/di/dcs/sharegrid/web/faces/component/UIOutputAccordionPanelComponent.java
|
2712
|
/*
* Copyright (C) 2008 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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 it.unipmn.di.dcs.sharegrid.web.faces.component;
import it.unipmn.di.dcs.sharegrid.web.faces.util.FacesConstants;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;
/**
* The Accordion Panel {@code UIComponent} can be used to create a single panel
* for the Accordion component.
*
* @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a>
*/
public class UIOutputAccordionPanelComponent extends AbstractUIOutputComponent
{
public static final String COMPONENT_FAMILY = FacesConstants.OutputAccordionPanelComponentFamily;
public static final String COMPONENT_TYPE = FacesConstants.OutputAccordionPanelComponentType;
public static final String RENDERER_TYPE = FacesConstants.HtmlOutputAccordionPanelRendererType;
private Object[] values;
/** A constructor. */
public UIOutputAccordionPanelComponent()
{
super();
this.setRendererType( UIOutputAccordionPanelComponent.RENDERER_TYPE );
}
@Override
public String getFamily()
{
return UIOutputAccordionPanelComponent.COMPONENT_FAMILY;
}
@Override
public void restoreState(FacesContext context, Object state)
{
this.values = (Object[]) state;
super.restoreState(context, this.values[0]);
this.heading = (String) this.values[1];
}
@Override
public Object saveState(FacesContext context)
{
if (this.values == null)
{
this.values = new Object[2];
}
this.values[0] = super.saveState(context);
this.values[1] = this.heading;
return this.values;
}
private String heading = null;
private boolean headingSet = false;
public String getHeading()
{
if (null != this.heading)
{
return this.heading;
}
ValueExpression ve = this.getValueExpression("heading");
if (ve != null)
{
return (String) ve.getValue(this.getFacesContext().getELContext());
}
return null;
}
public void setHeading(String value)
{
this.heading = value;
}
}
|
gpl-3.0
|
kgullikson88/General
|
PlotCCF.py
|
708
|
import matplotlib.pyplot as plt
def MakePlot(x, y, title="", fig=None, labelsize=20, titlesize=25, plotcolor='black', linewidth=2):
if fig == None:
fig = plt.figure()
elif isinstance(fig, int):
fig = plt.figure(fig)
plt.plot(x, y, color=plotcolor, lw=linewidth)
plt.xlabel("Velocity (km/s)", fontsize=labelsize)
plt.ylabel("CCF", fontsize=labelsize)
plt.title(title, fontsize=titlesize)
ax = fig.gca()
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(labelsize)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(labelsize)
plt.subplots_adjust(left=0.15, bottom=0.1, right=0.95, top=0.95)
return fig
|
gpl-3.0
|
Etherous/Emerge
|
asset.image/src/main/java/net/etherous/emerge/asset/image/TextureAtlas.java
|
1103
|
/*
* Copyright (c) 2015 Brandon Lyon
*
* This file is part of Emerge Game Engine (Emerge)
*
* Emerge is free software: you can redistribute it and/or modify
* it under the terms of version 3 of the GNU General Public License as
* published by the Free Software Foundation.
*
* Emerge 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 Emerge. If not, see <http://www.gnu.org/licenses/>.
*/
package net.etherous.emerge.asset.image;
/**
* A texture atlas takes multiple other texture assets and arranges them efficiently on a grid. The atlas can then be
* accessed as a typical texture. This has advantages in certain instances, such as being able to render more faces
* without needing switch texture bindings, reducing the number of GL calls required to render a scene
*/
// TODO: Implement
public class TextureAtlas
{
}
|
gpl-3.0
|
lukewatts/thistle
|
app/core/providers/Whoops/WhoopsServiceProvider.php
|
4011
|
<?php
namespace Thistle\App\Core\Provider\Whoops;
/**
* Whoops - php errors for cool kids
* @author Filipe Dobreira <http://github.com/filp>
*/
use RuntimeException;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Whoops\Handler\Handler;
use Whoops\Handler\PlainTextHandler;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
class WhoopsServiceProvider implements ServiceProviderInterface
{
/**
* @param Application $app
*/
public function register(Application $app)
{
// There's only ever going to be one error page...right?
$app['whoops.error_page_handler'] = $app->share(function () {
if (PHP_SAPI === 'cli') {
return new PlainTextHandler();
} else {
return new PrettyPageHandler();
}
});
// Retrieves info on the Silex environment and ships it off
// to the PrettyPageHandler's data tables:
// This works by adding a new handler to the stack that runs
// before the error page, retrieving the shared page handler
// instance, and working with it to add new data tables
$app['whoops.silex_info_handler'] = $app->protect(function () use ($app) {
try {
/** @var Request $request */
$request = $app['request'];
} catch (RuntimeException $e) {
// This error occurred too early in the application's life
// and the request instance is not yet available.
return;
}
/** @var Handler $errorPageHandler */
$errorPageHandler = $app["whoops.error_page_handler"];
if ($errorPageHandler instanceof PrettyPageHandler) {
/** @var PrettyPageHandler $errorPageHandler */
// General application info:
$errorPageHandler->addDataTable('Silex Application', array(
'Charset' => $app['charset'],
'Locale' => $app['locale'],
'Route Class' => $app['route_class'],
'Dispatcher Class' => $app['dispatcher_class'],
'Application Class' => get_class($app),
));
// Request info:
$errorPageHandler->addDataTable('Silex Application (Request)', array(
'URI' => $request->getUri(),
'Request URI' => $request->getRequestUri(),
'Path Info' => $request->getPathInfo(),
'Query String' => $request->getQueryString() ?: '<none>',
'HTTP Method' => $request->getMethod(),
'Script Name' => $request->getScriptName(),
'Base Path' => $request->getBasePath(),
'Base URL' => $request->getBaseUrl(),
'Scheme' => $request->getScheme(),
'Port' => $request->getPort(),
'Host' => $request->getHost(),
));
}
});
$app['whoops'] = $app->share(function () use ($app) {
$run = new Run();
$run->allowQuit(false);
$run->pushHandler($app['whoops.error_page_handler']);
$run->pushHandler($app['whoops.silex_info_handler']);
return $run;
});
$app->error(function ($e) use ($app) {
$method = Run::EXCEPTION_HANDLER;
ob_start();
$app['whoops']->$method($e);
$response = ob_get_clean();
$code = $e instanceof HttpException ? $e->getStatusCode() : 500;
return new Response($response, $code);
});
$app['whoops']->register();
}
/**
* @see Silex\ServiceProviderInterface::boot
*/
public function boot(Application $app)
{
}
}
|
gpl-3.0
|
hluk/CopyQ
|
src/gui/tabwidget.cpp
|
13865
|
/*
Copyright (c) 2020, Lukas Holecek <hluk@email.cz>
This file is part of CopyQ.
CopyQ 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.
CopyQ 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 CopyQ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tabwidget.h"
#include "tabbar.h"
#include "tabtree.h"
#include "common/config.h"
#include <QAction>
#include <QBoxLayout>
#include <QEvent>
#include <QMainWindow>
#include <QMimeData>
#include <QPoint>
#include <QSettings>
#include <QStackedWidget>
#include <QToolBar>
namespace {
QString getTabWidgetConfigurationFilePath()
{
return getConfigurationFilePath("_tabs.ini");
}
template <typename Receiver, typename Slot>
void addTabAction(QWidget *widget, const QKeySequence &shortcut,
Receiver *receiver, Slot slot,
Qt::ShortcutContext context = Qt::WindowShortcut)
{
auto act = new QAction(widget);
act->setShortcut(shortcut);
act->setShortcutContext(context);
QObject::connect(act, &QAction::triggered, receiver, slot);
widget->addAction(act);
}
} // namespace
TabWidget::TabWidget(QWidget *parent)
: QWidget(parent)
, m_toolBar(new QToolBar(this))
, m_toolBarTree(new QToolBar(this))
, m_stackedWidget(nullptr)
, m_hideTabBar(false)
, m_showTabItemCount(false)
{
// Set object name for tool bars so they can be saved with QMainWindow::saveState().
m_toolBar->setObjectName("toolBarTabBar");
m_toolBarTree->setObjectName("toolBarTabTree");
m_toolBar->setContextMenuPolicy(Qt::NoContextMenu);
m_toolBarTree->setContextMenuPolicy(Qt::NoContextMenu);
m_toolBar->installEventFilter(this);
connect( m_toolBar, &QToolBar::orientationChanged,
this, &TabWidget::onToolBarOrientationChanged );
auto layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
setLayout(layout);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
m_stackedWidget = new QStackedWidget(this);
layout->addWidget(m_stackedWidget);
createTabBar();
addTabAction(this, QKeySequence::PreviousChild, this, &TabWidget::previousTab);
addTabAction(this, QKeySequence::NextChild, this, &TabWidget::nextTab);
loadTabInfo();
}
QString TabWidget::getCurrentTabPath() const
{
return m_tabs->getCurrentTabPath();
}
bool TabWidget::isTabGroup(const QString &tab) const
{
return m_tabs->isTabGroup(tab);
}
bool TabWidget::isTabGroupSelected() const
{
QWidget *w = currentWidget();
return w != nullptr && w->isHidden();
}
int TabWidget::currentIndex() const
{
return m_stackedWidget->currentIndex();
}
QWidget *TabWidget::widget(int tabIndex) const
{
return m_stackedWidget->widget(tabIndex);
}
int TabWidget::count() const
{
return m_stackedWidget->count();
}
QString TabWidget::tabName(int tabIndex) const
{
return m_tabs->tabName(tabIndex);
}
void TabWidget::setTabName(int tabIndex, const QString &tabName)
{
const QString oldTabName = this->tabName(tabIndex);
if ( m_tabItemCounters.contains(oldTabName) )
m_tabItemCounters.insert( tabName, m_tabItemCounters.take(oldTabName) );
m_tabs->setTabName(tabIndex, tabName);
m_tabs->adjustSize();
}
void TabWidget::setTabItemCountVisible(bool visible)
{
m_showTabItemCount = visible;
for (int i = 0; i < count(); ++i)
updateTabItemCount( tabName(i) );
m_tabs->adjustSize();
}
void TabWidget::setTabIcon(const QString &tabName, const QString &icon)
{
m_tabs->setTabIcon(tabName, icon);
}
void TabWidget::insertTab(int tabIndex, QWidget *widget, const QString &tabName)
{
const bool firstTab = count() == 0;
m_stackedWidget->insertWidget(tabIndex, widget);
m_tabs->insertTab(tabIndex, tabName);
m_toolBarCurrent->layout()->setSizeConstraint(QLayout::SetMinAndMaxSize);
if (firstTab)
emit currentChanged(0, -1);
updateTabItemCount(tabName);
updateToolBar();
}
void TabWidget::removeTab(int tabIndex)
{
if (tabIndex == currentIndex())
setCurrentIndex(tabIndex == 0 ? 1 : 0);
const QString tabName = this->tabName(tabIndex);
m_tabItemCounters.remove(tabName);
// Item count must be updated If tab is removed but tab group remains.
m_tabs->setTabItemCount(tabName, QString());
QWidget *w = m_stackedWidget->widget(tabIndex);
m_stackedWidget->removeWidget(w);
delete w;
m_tabs->removeTab(tabIndex);
updateToolBar();
}
QStringList TabWidget::tabs() const
{
QStringList tabs;
tabs.reserve( count() );
for( int i = 0; i < count(); ++i )
tabs.append( tabName(i) );
return tabs;
}
void TabWidget::addToolBars(QMainWindow *mainWindow)
{
mainWindow->addToolBar(Qt::TopToolBarArea, m_toolBar);
mainWindow->addToolBar(Qt::LeftToolBarArea, m_toolBarTree);
}
void TabWidget::saveTabInfo()
{
QStringList tabs;
tabs.reserve( count() );
for ( int i = 0; i < count(); ++i )
tabs.append( tabName(i) );
QSettings settings(getTabWidgetConfigurationFilePath(), QSettings::IniFormat);
m_tabs->updateCollapsedTabs(&m_collapsedTabs);
settings.setValue("TabWidget/collapsed_tabs", m_collapsedTabs);
QVariantMap tabItemCounters;
for (const auto &key : tabs) {
const int count = m_tabItemCounters.value(key, -1);
if (count >= 0)
tabItemCounters[key] = count;
}
settings.setValue("TabWidget/tab_item_counters", tabItemCounters);
}
void TabWidget::loadTabInfo()
{
QSettings settings(getTabWidgetConfigurationFilePath(), QSettings::IniFormat);
m_collapsedTabs = settings.value("TabWidget/collapsed_tabs").toStringList();
QVariantMap tabItemCounters = settings.value("TabWidget/tab_item_counters").toMap();
m_tabItemCounters.clear();
for (auto it = tabItemCounters.constBegin(); it != tabItemCounters.constEnd(); ++it)
m_tabItemCounters[it.key()] = it.value().toInt();
}
void TabWidget::updateTabs(QSettings &settings)
{
m_tabs->setCollapsedTabs(m_collapsedTabs);
QHash<QString, QString> tabIcons;
const int size = settings.beginReadArray(QStringLiteral("Tabs"));
for(int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
const QString name = settings.value(QStringLiteral("name")).toString();
const QString icon = settings.value(QStringLiteral("icon")).toString();
tabIcons[name] = icon;
}
settings.endArray();
m_tabs->updateTabIcons(tabIcons);
}
void TabWidget::setCurrentIndex(int tabIndex)
{
if (m_ignoreCurrentTabChanges)
return;
QWidget *w = currentWidget();
const int current = isTabGroupSelected() ? -1 : currentIndex();
if (tabIndex == current)
return;
if (tabIndex != -1) {
m_stackedWidget->setCurrentIndex(tabIndex);
w = currentWidget();
if (w == nullptr)
return;
w->show();
if (m_toolBarCurrent->hasFocus())
w->setFocus();
m_tabs->setCurrentTab(tabIndex);
} else if (w != nullptr) {
if (w->hasFocus())
m_toolBarCurrent->setFocus();
w->hide();
}
emit currentChanged(tabIndex, current);
}
void TabWidget::nextTab()
{
m_tabs->nextTab();
}
void TabWidget::previousTab()
{
m_tabs->previousTab();
}
void TabWidget::setTabBarHidden(bool hidden)
{
m_hideTabBar = hidden;
updateToolBar();
}
void TabWidget::setTreeModeEnabled(bool enabled)
{
setTreeModeEnabled(enabled, this->tabs());
}
void TabWidget::setTabItemCount(const QString &tabName, int itemCount)
{
if ( m_tabItemCounters.value(tabName, -1) == itemCount)
return;
m_tabItemCounters[tabName] = itemCount;
updateTabItemCount(tabName);
}
void TabWidget::setTabsOrder(const QStringList &tabs)
{
QStringList currentTabs = this->tabs();
if (tabs == currentTabs)
return;
m_ignoreCurrentTabChanges = true;
for (int i = 0; i < tabs.size(); ++i) {
const int tabIndex = currentTabs.indexOf(tabs[i]);
if (tabIndex != -1 && tabIndex != i) {
QWidget *widget = m_stackedWidget->widget(tabIndex);
m_stackedWidget->removeWidget(widget);
m_stackedWidget->insertWidget(i, widget);
currentTabs.move(tabIndex, i);
}
}
m_stackedWidget->setCurrentIndex( currentIndex() );
setTreeModeEnabled(m_toolBarCurrent == m_toolBarTree, currentTabs);
m_ignoreCurrentTabChanges = false;
}
bool TabWidget::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::Move)
updateToolBar();
return false;
}
void TabWidget::onTabMoved(int from, int to)
{
m_stackedWidget->insertWidget(to, m_stackedWidget->widget(from));
emit tabMoved(from, to);
}
void TabWidget::onTabsMoved(const QString &oldPrefix, const QString &newPrefix, const QList<int> &indexes)
{
const int newCurrentIndex = indexes.indexOf(currentIndex());
Q_ASSERT(newCurrentIndex != -1);
m_stackedWidget->hide();
QVector<QWidget*> widgets;
widgets.reserve(m_stackedWidget->count());
while ( m_stackedWidget->count() > 0 ) {
QWidget *w = m_stackedWidget->widget(0);
widgets.append(w);
m_stackedWidget->removeWidget(w);
}
for (int index : indexes) {
Q_ASSERT(index >= 0);
Q_ASSERT(index < widgets.count());
m_stackedWidget->insertWidget(-1, widgets[index]);
}
m_stackedWidget->setCurrentIndex(newCurrentIndex);
m_stackedWidget->show();
emit tabsMoved(oldPrefix, newPrefix);
}
void TabWidget::onToolBarOrientationChanged(Qt::Orientation orientation)
{
if (m_tabBar) {
if (orientation == Qt::Vertical)
m_tabBar->setShape(QTabBar::RoundedWest);
else
m_tabBar->setShape(QTabBar::RoundedNorth);
}
}
void TabWidget::onTreeItemClicked()
{
auto w = currentWidget();
if (w)
w->setFocus(Qt::MouseFocusReason);
}
void TabWidget::createTabBar()
{
auto tabBar = new TabBar(this);
tabBar->setObjectName("tab_bar");
tabBar->setExpanding(false);
tabBar->setMovable(true);
connect( tabBar, &TabBar::tabBarMenuRequested,
this, &TabWidget::tabBarMenuRequested );
connect( tabBar, &TabBar::tabRenamed,
this, &TabWidget::tabRenamed );
connect( tabBar, &QTabBar::tabCloseRequested,
this, &TabWidget::tabCloseRequested );
connect( tabBar, &TabBar::dropItems,
this, &TabWidget::dropItems );
connect( tabBar, &QTabBar::currentChanged,
this, &TabWidget::setCurrentIndex );
connect( tabBar, &QTabBar::tabMoved,
this, &TabWidget::onTabMoved );
delete m_tabs;
m_tabs = tabBar;
m_tabBar = tabBar;
m_toolBarCurrent = m_toolBar;
m_toolBarCurrent->addWidget(tabBar);
}
void TabWidget::createTabTree()
{
auto tabTree = new TabTree(this);
tabTree->setObjectName("tab_tree");
connect( tabTree, &TabTree::tabTreeMenuRequested,
this, &TabWidget::tabTreeMenuRequested );
connect( tabTree, &TabTree::tabsMoved,
this, &TabWidget::onTabsMoved );
connect( tabTree, &TabTree::dropItems,
this, &TabWidget::dropItems );
connect( tabTree, &TabTree::currentTabChanged,
this, &TabWidget::setCurrentIndex );
connect( tabTree, &QTreeWidget::itemClicked,
this, &TabWidget::onTreeItemClicked );
delete m_tabs;
m_tabs = tabTree;
m_tabBar = nullptr;
m_toolBarCurrent = m_toolBarTree;
m_toolBarCurrent->addWidget(tabTree);
}
void TabWidget::updateToolBar()
{
bool forceHide = count() == 1;
m_toolBar->setVisible(!forceHide && !m_hideTabBar && m_toolBarCurrent == m_toolBar);
m_toolBarTree->setVisible(!forceHide && !m_hideTabBar && m_toolBarCurrent == m_toolBarTree);
if (m_tabBar) {
QMainWindow *mainWindow = qobject_cast<QMainWindow*>(m_toolBar->window());
if (mainWindow) {
Qt::ToolBarArea area = mainWindow->toolBarArea(m_toolBar);
if (area == Qt::LeftToolBarArea)
m_tabBar->setShape(QTabBar::RoundedWest);
else if (area == Qt::RightToolBarArea)
m_tabBar->setShape(QTabBar::RoundedEast);
else if (area == Qt::TopToolBarArea)
m_tabBar->setShape(QTabBar::RoundedNorth);
else if (area == Qt::BottomToolBarArea)
m_tabBar->setShape(QTabBar::RoundedSouth);
}
}
m_tabs->adjustSize();
}
void TabWidget::updateTabItemCount(const QString &name)
{
m_tabs->setTabItemCount(name, itemCountLabel(name));
m_tabs->adjustSize();
}
QString TabWidget::itemCountLabel(const QString &name)
{
if (!m_showTabItemCount)
return QString();
const int count = m_tabItemCounters.value(name, -1);
return count > 0 ? QString::number(count) : count == 0 ? QString() : QLatin1String("?");
}
void TabWidget::setTreeModeEnabled(bool enabled, const QStringList &tabs)
{
if (enabled)
createTabTree();
else
createTabBar();
m_ignoreCurrentTabChanges = true;
for (int i = 0; i < tabs.size(); ++i) {
const QString &tabName = tabs[i];
m_tabs->insertTab(i, tabName);
m_tabs->setTabItemCount(tabName, itemCountLabel(tabName));
}
m_tabs->setCurrentTab( currentIndex() );
m_ignoreCurrentTabChanges = false;
updateToolBar();
}
|
gpl-3.0
|
e8yes/e8yesvision
|
test/testcnnfeature.cpp
|
167
|
#include "testcnnfeature.h"
test::test_cnnfeature::test_cnnfeature()
{
}
test::test_cnnfeature::~test_cnnfeature()
{
}
void
test::test_cnnfeature::run() const
{
}
|
gpl-3.0
|
sergey-donchenko/laravel52_admin_template
|
app/Listeners/Files/LoadFileListener.php
|
5796
|
<?php
namespace App\Listeners\Files;
use App\Events\Files\FileWasLoaded;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Helpers\File as cFile;
use Carbon\Carbon;
use Config;
use Image;
use App\Repositories\FileRepository;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class LoadFileListener
{
/**
* Injected variable
*
* @var Object (Illuminate\Filesystem\Filesystem)
*/
protected $files = null;
/**
* File repository
*
* @var Object (App\Repositories\FileRepository)
*/
protected $storage = null;
/**
* Create the event listener.
*
* @param Filesystem $file - injected variable
*
*/
public function __construct(Filesystem $file, FileRepository $storage)
{
// Injsct the filesystem instance
$this->files = $file;
// Inject the file storage instance
$this->storage = $storage;
}
/**
* Handle the event.
*
* @param FileWasLoaded $event
* @return void
*/
public function handle(FileWasLoaded $event)
{
$aParams = $event->aParams;
$file = array_key_exists('file', $aParams) ? $aParams['file'] : null;
$type = array_key_exists('type', $aParams) ? $aParams['type'] : '---';
$id = array_key_exists('id', $aParams) && $aParams['id'] > 0 ? $aParams['id'] : null;
$prefix = array_key_exists('prefix', $aParams) ? $aParams['prefix'] : '';
$token = array_key_exists('token_id', $aParams) ? $aParams['token_id'] : null;
$date = array_key_exists('date', $aParams) ? $aParams['date'] : Carbon::now();
$sFolder = cFile::getDestinationFolder($date) . $type;
$sResultFile = '';
$iReturnCode = Config::get('constants.DONE_STATUS.FAILURE');
$iResultId = 0;
if ( $file instanceof UploadedFile) {
$sFileName = cFile::generateName() . '.';
if ( $this->files->exists($sFolder) === false ) {
$this->files->makeDirectory($sFolder, $mode = 0777, true, true);
}
$sFileName .= $file->guessExtension();
$sMimeType = $file->getMimeType();
$iFileSize = $file->getSize();
$sOrigFileName = $file->getClientOriginalName();
// Path where we are going to move to this file
$sPath = sprintf(
cFile::getPathByDate($date) .
$type . DIRECTORY_SEPARATOR . '%s', $sFileName
);
// Result path
$sResultFile = sprintf(
cFile::getPathByDate($date) .
$type . DIRECTORY_SEPARATOR . '%s', $prefix . $sFileName
);
if ( $file->move($sFolder, $sFileName) ) {
$iFileId = $this->storage->store([
'path' => $sPath,
'file_type' => $sMimeType,
'file_name' => $sOrigFileName,
'file_size' => $iFileSize,
'content_id' => $id,
'session_id' => $token,
'content_type' => $type
]);
if ( $iFileId ) {
$aThumbnails = cFile::getThumbnailSizes( $type, cFile::isImage($sMimeType) );
$sStoragePath = cFile::getStoragePath();
$iResultId = $iFileId;
foreach($aThumbnails as $oThumb) {
$sXFolderPath = sprintf(
cFile::getPathByDate($date) .
$type . DIRECTORY_SEPARATOR . '%s', $oThumb->ident
);
$sXFolderFullPath = $sStoragePath . DIRECTORY_SEPARATOR . $sXFolderPath;
$sResizedFileName = sprintf($sXFolderPath . DIRECTORY_SEPARATOR . '%s', $sFileName);
if ( $this->files->exists($sXFolderFullPath) === false ) {
$this->files->makeDirectory($sXFolderFullPath, $mode = 0777, true, true);
}
if ( $this->files->exists( $sStoragePath . DIRECTORY_SEPARATOR . $sPath ) ) {
Image::make($sStoragePath . DIRECTORY_SEPARATOR . $sPath)
// ->insert( cFile::applyWatermark(), 'bottom-right', 10, 10 )
->resize(
$oThumb->width > 0 ? $oThumb->width : null,
$oThumb->height > 0 ? $oThumb->height : null,
function ($constraint) {
$constraint->aspectRatio();
}
)
->save(sprintf($sXFolderFullPath . DIRECTORY_SEPARATOR . '%s', $sFileName));
$this->storage->store([
'path' => $sResizedFileName,
'file_type' => $sMimeType,
'file_name' => $sOrigFileName,
'file_size' => $iFileSize,
'content_id' => $id,
'parent_id' => $iResultId,
'content_type' => $type
]);
}
}
$iReturnCode = Config::get('constants.DONE_STATUS.SUCCESS');
}
}
}
return (object) array(
'code' => $iReturnCode,
'id' => $iResultId,
'filepath' => $sResultFile
);
}
}
|
gpl-3.0
|
boompieman/iim_project
|
nxt_1.4.4/src/net/sourceforge/nite/gui/textviewer/NTextElementPositionComparator.java
|
1489
|
/**
* Natural Interactivity Tools Engineering
* Copyright (c) 2003, Jean Carletta, Jonathan Kilgour, Judy Robertson
* See the README file in this distribution for licence.
*/
// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3)
// Source File Name: NTextElementComparator.java
package net.sourceforge.nite.gui.textviewer;
import java.util.Comparator;
// Referenced classes of package nite.gui.textviewer:
// NTextElement
public class NTextElementPositionComparator
implements Comparator
{
public NTextElementPositionComparator()
{
}
/** Compare objects assuming that both are text elements. If both
* are non-null, the element with a smaller position is assument
* to precede the one with the larger position. The null element
* is assumed to precede anything. **/
public int compare(Object obj1, Object obj2)
{
NTextElement e1 = (NTextElement)obj1;
NTextElement e2 = (NTextElement)obj2;
if( e1 == null && e2 == null ) {
return 0;
} else if( e1 == null ) {
return -1;
} else if( e2 == null ) {
return 1;
} else if( e1.equals( e2 )) {
return 0;
} else {
int pos1 = e1.getPosition();
int pos2 = e2.getPosition();
if (pos1== pos2) {
return 0;
} else if (pos1 < pos2) {
return -1;
} else { //pos2 > pos1
return 1;
}
}
}
}
|
gpl-3.0
|
idega/net.jxta
|
src/java/net/jxta/endpoint/MessengerState.java
|
16298
|
/*
*
* $Id: MessengerState.java,v 1.1 2007/01/16 11:01:27 thomas Exp $
*
* Copyright (c) 2004 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Sun Microsystems, Inc. for Project JXTA."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA",
* nor may "JXTA" appear in their name, without prior written
* permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 SUN MICROSYSTEMS OR
* ITS 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.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of Project JXTA. For more
* information on Project JXTA, please see
* <http://www.jxta.org/>.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.endpoint;
/**
* This class implements the complete standard messenger life cycle state machine that all messengers must obey. Compliant
* messengers can be built by implementing and using this class as an engine to orchestrate descreet operations.
*
* In order to use this class, one must implement the various abstract Action methods, so that they trigger the required
* operations.
*
* Synchronization has to be externally provided and usualy needs to extend around sections wider than just
* the invocation of this classe's methods. For example, if the user of this class maintains a queue, the state of the
* queue must be kept consistent with the invocation of {@link #msgsEvent}, {@link #saturatedEvent}, and {@link #idleEvent}, which all
* denote different states of that queue. It is suggested to use the instance of this class as the synchronization object.
**/
public abstract class MessengerState {
// All the transition map setup is rather terse because java tends to make it extremely verbose. We do not want
// to end up with 1000 lines of code for what amounts to initializing a table.
// Below is a method reference. It permits to put "what to do" in a variable. The doIt method is given the target object
// because we want our entire transition table to be a static singleton. Otherwise it would cost too much initializing each
// instance of this class.
private interface Action {
public void doIt(MessengerState s);
}
// Action method "pointers".
// The transition table is static. Otherwise it would cost too much initializing each instance of this class.
private static Action Connect = new Action(){public void doIt(MessengerState s){s.connectAction();} };
private static Action Closein = new Action(){public void doIt(MessengerState s){s.closeInputAction();} };
private static Action Start = new Action(){public void doIt(MessengerState s){s.startAction();} };
private static Action Closeout = new Action(){public void doIt(MessengerState s){s.closeOutputAction();} };
private static Action Failall = new Action(){public void doIt(MessengerState s){s.failAllAction();} };
private static Action Closeio = new Action(){public void doIt(MessengerState s){s.closeInputAction();s.closeOutputAction();}};
private static Action Closefail = new Action(){public void doIt(MessengerState s){s.closeInputAction();s.failAllAction();} };
private static Action Nop = new Action(){public void doIt(MessengerState s){}; };
// A state: what transition each event causes when in that state.
private static class State {
int number;
State stResolve ; Action acResolve ;
State stMsgs ; Action acMsgs ;
State stSaturated ; Action acSaturated ;
State stClose ; Action acClose ;
State stShutdown ; Action acShutdown ;
State stUp ; Action acUp ;
State stDown ; Action acDown ;
State stIdle ; Action acIdle ;
void init(int stateNum, Object[] data) {
number = stateNum;
stResolve = (State) data[0]; acResolve = (Action) data[1];
stMsgs = (State) data[2]; acMsgs = (Action) data[3];
stSaturated = (State) data[4]; acSaturated = (Action) data[5];
stClose = (State) data[6]; acClose = (Action) data[7];
stShutdown = (State) data[8]; acShutdown = (Action) data[9];
stUp = (State) data[10]; acUp = (Action) data[11];
stDown = (State) data[12]; acDown = (Action) data[13];
stIdle = (State) data[14]; acIdle = (Action) data[15];
}
}
// All the states. (We put them together in a class essentially to simplify initialization).
static class TransitionMap {
static State Unresolved = new State();
static State ResPending = new State();
static State Resolving = new State();
static State ResolSat = new State();
static State Connected = new State();
static State Disconned = new State();
static State Reconning = new State();
static State ReconSat = new State();
static State Sending = new State();
static State SendingSat = new State();
static State ResClosing = new State();
static State ReconClosing= new State();
static State Closing = new State();
static State Disconning = new State();
static State Unresable = new State();
static State Closed = new State();
static State Broken = new State();
// The states need to exist before init, because they refer to each other.
// We overwrite them in-place with the complete data.
static {
Object[][] tmpMap = {
/* STATE resolve, msgs, saturated, close, shutdown, up, down, idle */
/*UNRESOLVED */{Resolving,Connect,ResPending,Connect,ResolSat,Connect,Closed,Closein, Broken,Closein, Connected,Nop, Unresolved,Nop, Unresolved,Nop },
/*RESOLPENDING */{ResPending,Nop, ResPending,Nop, ResolSat,Nop, ResClosing,Closein, Broken,Closefail, Sending,Start, Unresable,Closefail, Resolving,Nop },
/*RESOLVING */{Resolving,Nop, ResPending,Nop, ResolSat,Nop, Closed,Closein, Broken,Closein, Connected,Nop, Unresable,Closein, Resolving,Nop },
/*RESOLSATURATED */{ResolSat,Nop, ResPending,Nop, ResolSat,Nop, ResClosing,Closein, Broken,Closefail, SendingSat,Start, Unresable,Closefail, Resolving,Nop },
/*CONNECTED */{Connected,Nop, Sending,Start, SendingSat,Start,Closed,Closeio, Broken,Closeio, Connected,Nop, Disconned,Nop, Connected,Nop },
/*DISCONNECTED */{Disconned,Nop, Reconning,Connect, ReconSat,Connect,Closed,Closein, Broken,Closein, Connected,Nop, Disconned,Nop, Disconned,Nop },
/*RECONNECTING */{Reconning,Nop, Reconning,Nop, ReconSat,Nop, ReconClosing,Closein,Broken,Closefail, Sending,Start, Broken,Closefail, Disconned,Nop },
/*RECONSATURATED */{ReconSat,Nop, Reconning,Nop, ReconSat,Nop, ReconClosing,Closein,Broken,Closefail, SendingSat,Start, Broken,Closefail, Disconned,Nop },
/*SENDING */{Sending,Nop, Sending,Nop, SendingSat,Nop, Closing,Closein, Disconning,Closeio, Sending,Nop, Reconning,Connect, Connected,Nop },
/*SENDINGSATURATED*/{SendingSat,Nop, Sending,Nop, SendingSat,Nop, Closing,Closein, Disconning,Closeio, SendingSat,Nop, ReconSat,Connect, Connected,Nop },
/*RESOLCLOSING */{ResClosing,Nop, ResClosing,Nop, ResClosing,Nop, ResClosing,Nop, Broken,Failall, Closing,Start, Unresable,Failall, ResClosing,Nop },
/*RECONCLOSING */{ReconClosing,Nop, ReconClosing,Nop, ReconClosing,Nop,ReconClosing,Nop, Broken,Failall, Closing,Start, Broken,Failall, ReconClosing,Nop},
/*CLOSING */{Closing,Nop, Closing,Nop, Closing,Nop, Closing,Nop, Disconning,Closeout,Closing,Nop, ReconClosing,Connect,Closed,Closeout },
/*DISCONNECTING */{Disconning,Nop, Disconning,Nop, Disconning,Nop, Disconning,Nop, Disconning,Nop, Disconning,Nop, Broken,Failall, Broken,Nop },
/*UNRESOLVABLE */{Unresable,Nop, Unresable,Nop, Unresable,Nop, Unresable,Nop, Unresable,Nop, Unresable,Closeout,Unresable,Nop, Unresable,Nop },
/*CLOSED */{Closed,Nop, Closed,Nop, Closed,Nop, Closed,Nop, Closed,Nop, Closed,Closeout, Closed,Nop, Closed,Nop },
/*BROKEN */{Broken,Nop, Broken,Nop, Broken,Nop, Broken,Nop, Broken,Nop, Broken,Closeout, Broken,Nop, Broken,Nop }
};
// install the tmp map in its proper place.
Unresolved.init (Messenger.UNRESOLVED , tmpMap[0]);
ResPending.init (Messenger.RESOLPENDING , tmpMap[1]);
Resolving.init (Messenger.RESOLVING , tmpMap[2]);
ResolSat.init (Messenger.RESOLSATURATED , tmpMap[3]);
Connected.init (Messenger.CONNECTED , tmpMap[4]);
Disconned.init (Messenger.DISCONNECTED , tmpMap[5]);
Reconning.init (Messenger.RECONNECTING , tmpMap[6]);
ReconSat.init (Messenger.RECONSATURATED , tmpMap[7]);
Sending.init (Messenger.SENDING , tmpMap[8]);
SendingSat.init (Messenger.SENDINGSATURATED, tmpMap[9]);
ResClosing.init (Messenger.RESOLCLOSING , tmpMap[10]);
ReconClosing.init(Messenger.RECONCLOSING , tmpMap[11]);
Closing.init (Messenger.CLOSING , tmpMap[12]);
Disconning.init (Messenger.DISCONNECTING , tmpMap[13]);
Unresable.init (Messenger.UNRESOLVABLE , tmpMap[14]);
Closed.init (Messenger.CLOSED , tmpMap[15]);
Broken.init (Messenger.BROKEN , tmpMap[16]);
}
}
private volatile State state = null;
/**
* Constructs a new messenger state machine.
* The transistion map is static and we refer to it only to grab the first state. After that, states
* refer to each other. The only reason they are members in the map is so that we can make references during init.
* @param connected If true, the initial state is {@link Messenger#CONNECTED} else, {@link Messenger#UNRESOLVED}.
**/
protected MessengerState(boolean connected) {
state = connected ? TransitionMap.Connected : TransitionMap.Unresolved;
}
/**
* @return The current state.
**/
public int getState() {
// getState is always just a peek. It needs no sync.
return state.number;
}
/**
* Event input.
**/
public void resolveEvent() { Action a = state.acResolve; state = state.stResolve; a.doIt(this); }
public void msgsEvent() { Action a = state.acMsgs; state = state.stMsgs; a.doIt(this); }
public void saturatedEvent() { Action a = state.acSaturated; state = state.stSaturated; a.doIt(this); }
public void closeEvent() { Action a = state.acClose; state = state.stClose; a.doIt(this); }
public void shutdownEvent() { Action a = state.acShutdown; state = state.stShutdown; a.doIt(this); }
public void upEvent() { Action a = state.acUp; state = state.stUp; a.doIt(this); }
public void downEvent() { Action a = state.acDown; state = state.stDown; a.doIt(this); }
public void idleEvent() { Action a = state.acIdle; state = state.stIdle; a.doIt(this); }
/**
* Actions they're always called in sequence by event methods.
*
* Actions must not call event methods in sequence.
**/
/**
* Try to make a connection. Called whenever transitioning from a state that neither needs nor has a connection to a state
* that needs a connection and does not have it. Call upEvent when successfull, or downEvent when failed.
**/
protected abstract void connectAction();
/**
* Start sending. Called whenever transitioning to a state that has both a connection and messages to send from a state that
* lacked either attributes. So, will be called after sending stopped due to broken cnx or idle condition. Call downEvent
* when stopping due to broken or closed connection, call {@link #idleEvent} when no pending message is left.
**/
protected abstract void startAction();
/**
* Reject new messages from now on. Called whenever transitioning from a state that is {@link Messenger#USABLE} to a state
* that is not. No event expected once done.
**/
protected abstract void closeInputAction();
/**
* Drain pending messages, all failed. Called once output is down and there are still pending messages.
* Call {@link #idleEvent} when done, as a normal result of no pending messages being left.
**/
protected abstract void failAllAction();
/**
* Force close output. Called whenever the underlying connection is to be discarded and never to be needed again. That is
* either because orderly close has completed, or shutdown is in progress. No event expected once done, but this action
* <b>must</b> cause any sending in progress to stop eventually. The fact that the sending has stopped must be reported as
* usual: either with a {@link #downEvent}, if the output closure caused the sending process to fail, or with an {@link
* #idleEvent} if the sending of the last message could be sent successfully despite the attempt at interrupting it.
*
* Sending is said to be in progress if, and only if, the last call to startAction is more recent than the last call to
* {@link #idleEvent} or {@link #downEvent}.
*
* It is advisable to also cancel an ongoing connect action, but not mandatory. If a {@link #connectAction} later succeeds,
* then {@link #upEvent} <b>must</b> be called as usual. This will result in another call to {@link #closeOutputAction}.
**/
protected abstract void closeOutputAction();
}
|
gpl-3.0
|
GGCrew/hotsroster
|
app/models/roster.rb
|
2662
|
class Roster < ActiveRecord::Base
belongs_to :hero
belongs_to :date_range
#..#
scope :unrestricted, -> { where(player_level: 1) }
scope :restricted, -> { where.not(player_level: 1) }
#..#
validates :hero, :date_range, presence: true
validates :hero, uniqueness: { scope: :date_range, message: 'and DateRange have already been taken.' }
#..#
def self.import_from_blizzard
# TODO: split into import_from_hero_page and import_from_forum
SOURCE_URLS[:rosters].each do |country, address|
# Loop through all pages via pagination
page_query_string = '?page=1'
loop do
url = URI.parse(address + page_query_string)
html = Net::HTTP.get(url) # TODO: error handling
if html.blank?
# TODO: Send alert to admin
end
page = Nokogiri::HTML(html)
post_list = page.css('div.Topic-content div.TopicPost')
if post_list.empty?
# TODO: Send alert to admin
end
for post in post_list
post_detail = post.css('div.TopicPost-bodyContent')
date_range = DateRange.import_from_post(post_detail)
heroes = Hero.parse_from_post(post_detail)
# Import into Roster
for hero in heroes
Roster.find_or_create_by!({
date_range: date_range,
hero: hero[:hero],
player_level: hero[:player_level]
})
end
end
# Check for pagination
next_page_link = page.css('div.Topic-pagination--header a.Pagination-button--next').first
break unless next_page_link # Exit loop if there isn't a "next page" link
page_query_string = next_page_link[:href]
break if page_query_string.nil? # Exit loop if there isn't a valid "href" value
end # END: Loop through all pages via pagination
end
return true
end
def self.date_range_of_latest_roster_size_change
# Count each date_range's roster size
# Using the database sort commands because they should be more efficient than Ruby's sorting/reverse methods
# The key:value pairs represent date_range_id:roster_size_for_that_date
counts = self.joins(:date_range).group(:date_range_id).order('date_ranges.start DESC, date_ranges.end DESC').count
# This trick works because Ruby's Array.uniq method maintains the order of the first appearance of a value
values = counts.values.uniq[0..1]
current_size = values.first
previous_size = values.last
# Get key of last rotation with previous roster size
previous_key = counts.key(previous_size)
# Get key of first rotation with current roster size
counts_keys = counts.keys
previous_key_index = counts_keys.index(previous_key)
current_key = counts.keys[previous_key_index - 1]
return DateRange.find(current_key)
end
end
|
gpl-3.0
|
Pedals2Paddles/ardupilot
|
libraries/SITL/SIM_Submarine.cpp
|
9518
|
/*
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/>.
*/
/*
Submarine simulator class
*/
#include "SIM_Submarine.h"
#include <AP_Motors/AP_Motors.h>
#include <stdio.h>
using namespace SITL;
static Thruster vectored_thrusters[] =
{ // Motor # Roll Factor Pitch Factor Yaw Factor Throttle Factor Forward Factor Lateral Factor
Thruster(0, 0, 0, 1.0f, 0, -1.0f, 1.0f),
Thruster(1, 0, 0, -1.0f, 0, -1.0f, -1.0f),
Thruster(2, 0, 0, -1.0f, 0, 1.0f, 1.0f),
Thruster(3, 0, 0, 1.0f, 0, 1.0f, -1.0f),
Thruster(4, 1.0f, 0, 0, -1.0f, 0, 0),
Thruster(5, -1.0f, 0, 0, -1.0f, 0, 0)
};
static Thruster vectored_6dof_thrusters[] =
{
// Motor # Roll Factor Pitch Factor Yaw Factor Throttle Factor Forward Factor Lateral Factor
Thruster(0, 0, 0, 1.0f, 0, -1.0f, 1.0f),
Thruster(1, 0, 0, -1.0f, 0, -1.0f, -1.0f),
Thruster(2, 0, 0, -1.0f, 0, 1.0f, 1.0f),
Thruster(3, 0, 0, 1.0f, 0, 1.0f, -1.0f),
Thruster(4, 1.0f, -1.0f, 0, -1.0f, 0, 0),
Thruster(5, -1.0f, -1.0f, 0, -1.0f, 0, 0),
Thruster(6, 1.0f, 1.0f, 0, -1.0f, 0, 0),
Thruster(7, -1.0f, 1.0f, 0, -1.0f, 0, 0)
};
Submarine::Submarine(const char *frame_str) :
Aircraft(frame_str),
frame(NULL)
{
frame_height = 0.0;
ground_behavior = GROUND_BEHAVIOR_NONE;
// default to vectored frame
thrusters = vectored_thrusters;
n_thrusters = 6;
if (strstr(frame_str, "vectored_6dof")) {
thrusters = vectored_6dof_thrusters;
n_thrusters = 8;
}
}
// calculate rotational and linear accelerations
void Submarine::calculate_forces(const struct sitl_input &input, Vector3f &rot_accel, Vector3f &body_accel)
{
rot_accel = Vector3f(0,0,0);
// slight positive buoyancy
body_accel = dcm.transposed() * Vector3f(0, 0, -calculate_buoyancy_acceleration());
for (int i = 0; i < n_thrusters; i++) {
Thruster t = thrusters[i];
int16_t pwm = input.servos[t.servo];
float output = 0;
// if valid pwm and not in the esc deadzone
// TODO: extract deadzone from parameters/vehicle code
if (pwm < 2000 && pwm > 1000 && (pwm < 1475 || pwm > 1525)) {
output = (pwm - 1500) / 400.0; // range -1~1
}
float thrust = output * fabs(output) * frame_property.thrust; // approximate pwm to thrust function using a quadratic curve
body_accel += t.linear * thrust / frame_property.weight;
rot_accel += t.rotational * thrust * frame_property.thruster_mount_radius / frame_property.moment_of_inertia;
}
float floor_depth = calculate_sea_floor_depth(position);
range = floor_depth - position.z;
// Limit movement at the sea floor
if (position.z > floor_depth && body_accel.z > -GRAVITY_MSS) {
body_accel.z = -GRAVITY_MSS;
}
// Calculate linear drag forces
Vector3f linear_drag_forces;
calculate_drag_force(velocity_air_bf, frame_property.linear_drag_coefficient, linear_drag_forces);
// Add forces in body frame accel
body_accel -= linear_drag_forces / frame_property.weight;
// Calculate angular drag forces
// TODO: This results in the wrong units. Fix the math.
Vector3f angular_drag_torque;
calculate_angular_drag_torque(gyro, frame_property.angular_drag_coefficient, angular_drag_torque);
// Calculate torque induced by buoyancy foams on the frame
Vector3f buoyancy_torque;
calculate_buoyancy_torque(buoyancy_torque);
// Add forces in body frame accel
rot_accel -= angular_drag_torque / frame_property.moment_of_inertia;
rot_accel += buoyancy_torque / frame_property.moment_of_inertia;
add_shove_forces(rot_accel, body_accel);
}
/**
* @brief Calculate the torque induced by buoyancy foam
*
* @param torque Output torques
*/
void Submarine::calculate_buoyancy_torque(Vector3f &torque)
{
// Let's assume 2 Liters water displacement at the top, and ~ 2kg of weight at the bottom.
const Vector3f force_up(0,0,-40); // 40 N upwards
const Vector3f force_position = dcm.transposed() * Vector3f(0, 0, 0.15); // offset in meters
torque = force_position % force_up;
}
/**
* @brief Calculate sea floor depth from submarine position
* This creates a non planar floor for rangefinder sensor test
* TODO: Create a better sea floor with procedural generatation
*
* @param position
* @return float
*/
float Submarine::calculate_sea_floor_depth(const Vector3f &/*position*/)
{
return 50;
}
/**
* @brief Calculate drag force against body
*
* @param velocity Body frame velocity of fluid
* @param drag_coefficient Drag coefficient of body
* @param force Output forces
* $ F_D = rho * v^2 * A * C_D / 2 $
* rho = water density (kg/m^3), V = velocity (m/s), A = area (m^2), C_D = drag_coefficient
*/
void Submarine::calculate_drag_force(const Vector3f &velocity, const Vector3f &drag_coefficient, Vector3f &force)
{
/**
* @brief It's necessary to keep the velocity orientation from the body frame.
* To do so, a mathematical artifice is used to do velocity square but without loosing the direction.
* $(|V|/V)*V^2$ = $|V|*V$
*/
const Vector3f velocity_2(
fabsf(velocity.x) * velocity.x,
fabsf(velocity.y) * velocity.y,
fabsf(velocity.z) * velocity.z
);
force = (velocity_2 * water_density) * frame_property.equivalent_sphere_area / 2.0f;
force *= drag_coefficient;
}
/**
* @brief Calculate angular drag torque using the equivalente sphere area and assuming a laminar external flow.
*
* $F_D = C_D*A*\rho*V^2/2$
* where:
* $F_D$ is the drag force
* $C_D$ is the drag coefficient
* $A$ is the surface area in contact with the fluid
* $/rho$ is the fluid density (1000kg/m³ for water)
* $V$ is the fluid velocity velocity relative to the surface
*
* @param angular_velocity Body frame velocity of fluid
* @param drag_coefficient Rotational drag coefficient of body
*/
void Submarine::calculate_angular_drag_torque(const Vector3f &angular_velocity, const Vector3f &drag_coefficient, Vector3f &torque)
{
/**
* @brief It's necessary to keep the velocity orientation from the body frame.
* To do so, a mathematical artifice is used to do velocity square but without loosing the direction.
* $(|V|/V)*V^2$ = $|V|*V$
*/
Vector3f v_2(
fabsf(angular_velocity.x) * angular_velocity.x,
fabsf(angular_velocity.y) * angular_velocity.y,
fabsf(angular_velocity.z) * angular_velocity.z
);
Vector3f f_d = v_2 *= drag_coefficient * frame_property.equivalent_sphere_area * 1000 / 2;
torque = f_d * frame_property.equivalent_sphere_radius;
}
/**
* @brief Calculate buoyancy force of the frame
*
* @return float
*/
float Submarine::calculate_buoyancy_acceleration()
{
float below_water_level = position.z - frame_property.height/2;
// Completely above water level
if (below_water_level < 0) {
return 0.0f;
}
// Completely below water level
if (below_water_level > frame_property.height/2) {
return frame_property.buoyancy_acceleration;
}
// bouyant force is proportional to fraction of height in water
return frame_property.buoyancy_acceleration * below_water_level/frame_property.height;
};
/*
update the Submarine simulation by one time step
*/
void Submarine::update(const struct sitl_input &input)
{
// get wind vector setup
update_wind(input);
Vector3f rot_accel;
calculate_forces(input, rot_accel, accel_body);
update_dynamics(rot_accel);
// update lat/lon/altitude
update_position();
time_advance();
// update magnetic field
update_mag_field_bf();
}
/*
return true if we are on the ground
*/
bool Submarine::on_ground() const
{
return false;
}
|
gpl-3.0
|
raulsmail/GlowPower
|
src/main/java/com/bluepowermod/containers/ContainerDiskDrive.java
|
534
|
package com.bluepowermod.containers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import com.bluepowermod.tileentities.tier3.TileDiskDrive;
public class ContainerDiskDrive extends Container {
private final TileDiskDrive diskDrive;
public ContainerDiskDrive(InventoryPlayer invPlayer, TileDiskDrive ent) {
this.diskDrive = ent;
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
return true;
}
}
|
gpl-3.0
|
rhomicom-systems-tech-gh/Rhomicom-ERP-Web
|
self/cs/plugins/fullcalendar-daygrid/main.js
|
81961
|
/*!
FullCalendar Day Grid Plugin v4.4.0
Docs & License: https://fullcalendar.io/
(c) 2019 Adam Shaw
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@fullcalendar/core')) :
typeof define === 'function' && define.amd ? define(['exports', '@fullcalendar/core'], factory) :
(global = global || self, factory(global.FullCalendarDayGrid = {}, global.FullCalendar));
}(this, function (exports, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var DayGridDateProfileGenerator = /** @class */ (function (_super) {
__extends(DayGridDateProfileGenerator, _super);
function DayGridDateProfileGenerator() {
return _super !== null && _super.apply(this, arguments) || this;
}
// Computes the date range that will be rendered.
DayGridDateProfileGenerator.prototype.buildRenderRange = function (currentRange, currentRangeUnit, isRangeAllDay) {
var dateEnv = this.dateEnv;
var renderRange = _super.prototype.buildRenderRange.call(this, currentRange, currentRangeUnit, isRangeAllDay);
var start = renderRange.start;
var end = renderRange.end;
var endOfWeek;
// year and month views should be aligned with weeks. this is already done for week
if (/^(year|month)$/.test(currentRangeUnit)) {
start = dateEnv.startOfWeek(start);
// make end-of-week if not already
endOfWeek = dateEnv.startOfWeek(end);
if (endOfWeek.valueOf() !== end.valueOf()) {
end = core.addWeeks(endOfWeek, 1);
}
}
// ensure 6 weeks
if (this.options.monthMode &&
this.options.fixedWeekCount) {
var rowCnt = Math.ceil(// could be partial weeks due to hiddenDays
core.diffWeeks(start, end));
end = core.addWeeks(end, 6 - rowCnt);
}
return { start: start, end: end };
};
return DayGridDateProfileGenerator;
}(core.DateProfileGenerator));
/* A rectangular panel that is absolutely positioned over other content
------------------------------------------------------------------------------------------------------------------------
Options:
- className (string)
- content (HTML string, element, or element array)
- parentEl
- top
- left
- right (the x coord of where the right edge should be. not a "CSS" right)
- autoHide (boolean)
- show (callback)
- hide (callback)
*/
var Popover = /** @class */ (function () {
function Popover(options) {
var _this = this;
this.isHidden = true;
this.margin = 10; // the space required between the popover and the edges of the scroll container
// Triggered when the user clicks *anywhere* in the document, for the autoHide feature
this.documentMousedown = function (ev) {
// only hide the popover if the click happened outside the popover
if (_this.el && !_this.el.contains(ev.target)) {
_this.hide();
}
};
this.options = options;
}
// Shows the popover on the specified position. Renders it if not already
Popover.prototype.show = function () {
if (this.isHidden) {
if (!this.el) {
this.render();
}
this.el.style.display = '';
this.position();
this.isHidden = false;
this.trigger('show');
}
};
// Hides the popover, through CSS, but does not remove it from the DOM
Popover.prototype.hide = function () {
if (!this.isHidden) {
this.el.style.display = 'none';
this.isHidden = true;
this.trigger('hide');
}
};
// Creates `this.el` and renders content inside of it
Popover.prototype.render = function () {
var _this = this;
var options = this.options;
var el = this.el = core.createElement('div', {
className: 'fc-popover ' + (options.className || ''),
style: {
top: '0',
left: '0'
}
});
if (typeof options.content === 'function') {
options.content(el);
}
options.parentEl.appendChild(el);
// when a click happens on anything inside with a 'fc-close' className, hide the popover
core.listenBySelector(el, 'click', '.fc-close', function (ev) {
_this.hide();
});
if (options.autoHide) {
document.addEventListener('mousedown', this.documentMousedown);
}
};
// Hides and unregisters any handlers
Popover.prototype.destroy = function () {
this.hide();
if (this.el) {
core.removeElement(this.el);
this.el = null;
}
document.removeEventListener('mousedown', this.documentMousedown);
};
// Positions the popover optimally, using the top/left/right options
Popover.prototype.position = function () {
var options = this.options;
var el = this.el;
var elDims = el.getBoundingClientRect(); // only used for width,height
var origin = core.computeRect(el.offsetParent);
var clippingRect = core.computeClippingRect(options.parentEl);
var top; // the "position" (not "offset") values for the popover
var left; //
// compute top and left
top = options.top || 0;
if (options.left !== undefined) {
left = options.left;
}
else if (options.right !== undefined) {
left = options.right - elDims.width; // derive the left value from the right value
}
else {
left = 0;
}
// constrain to the view port. if constrained by two edges, give precedence to top/left
top = Math.min(top, clippingRect.bottom - elDims.height - this.margin);
top = Math.max(top, clippingRect.top + this.margin);
left = Math.min(left, clippingRect.right - elDims.width - this.margin);
left = Math.max(left, clippingRect.left + this.margin);
core.applyStyle(el, {
top: top - origin.top,
left: left - origin.left
});
};
// Triggers a callback. Calls a function in the option hash of the same name.
// Arguments beyond the first `name` are forwarded on.
// TODO: better code reuse for this. Repeat code
// can kill this???
Popover.prototype.trigger = function (name) {
if (this.options[name]) {
this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
}
};
return Popover;
}());
/* Event-rendering methods for the DayGrid class
----------------------------------------------------------------------------------------------------------------------*/
// "Simple" is bad a name. has nothing to do with SimpleDayGrid
var SimpleDayGridEventRenderer = /** @class */ (function (_super) {
__extends(SimpleDayGridEventRenderer, _super);
function SimpleDayGridEventRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
// Builds the HTML to be used for the default element for an individual segment
SimpleDayGridEventRenderer.prototype.renderSegHtml = function (seg, mirrorInfo) {
var context = this.context;
var eventRange = seg.eventRange;
var eventDef = eventRange.def;
var eventUi = eventRange.ui;
var allDay = eventDef.allDay;
var isDraggable = core.computeEventDraggable(context, eventDef, eventUi);
var isResizableFromStart = allDay && seg.isStart && core.computeEventStartResizable(context, eventDef, eventUi);
var isResizableFromEnd = allDay && seg.isEnd && core.computeEventEndResizable(context, eventDef, eventUi);
var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd, mirrorInfo);
var skinCss = core.cssToStr(this.getSkinCss(eventUi));
var timeHtml = '';
var timeText;
var titleHtml;
classes.unshift('fc-day-grid-event', 'fc-h-event');
// Only display a timed events time if it is the starting segment
if (seg.isStart) {
timeText = this.getTimeText(eventRange);
if (timeText) {
timeHtml = '<span class="fc-time">' + core.htmlEscape(timeText) + '</span>';
}
}
titleHtml =
'<span class="fc-title">' +
(core.htmlEscape(eventDef.title || '') || ' ') + // we always want one line of height
'</span>';
return '<a class="' + classes.join(' ') + '"' +
(eventDef.url ?
' href="' + core.htmlEscape(eventDef.url) + '"' :
'') +
(skinCss ?
' style="' + skinCss + '"' :
'') +
'>' +
'<div class="fc-content">' +
(context.options.dir === 'rtl' ?
titleHtml + ' ' + timeHtml : // put a natural space in between
timeHtml + ' ' + titleHtml //
) +
'</div>' +
(isResizableFromStart ?
'<div class="fc-resizer fc-start-resizer"></div>' :
'') +
(isResizableFromEnd ?
'<div class="fc-resizer fc-end-resizer"></div>' :
'') +
'</a>';
};
// Computes a default event time formatting string if `eventTimeFormat` is not explicitly defined
SimpleDayGridEventRenderer.prototype.computeEventTimeFormat = function () {
return {
hour: 'numeric',
minute: '2-digit',
omitZeroMinute: true,
meridiem: 'narrow'
};
};
SimpleDayGridEventRenderer.prototype.computeDisplayEventEnd = function () {
return false; // TODO: somehow consider the originating DayGrid's column count
};
return SimpleDayGridEventRenderer;
}(core.FgEventRenderer));
/* Event-rendering methods for the DayGrid class
----------------------------------------------------------------------------------------------------------------------*/
var DayGridEventRenderer = /** @class */ (function (_super) {
__extends(DayGridEventRenderer, _super);
function DayGridEventRenderer(dayGrid) {
var _this = _super.call(this) || this;
_this.dayGrid = dayGrid;
return _this;
}
// Renders the given foreground event segments onto the grid
DayGridEventRenderer.prototype.attachSegs = function (segs, mirrorInfo) {
var rowStructs = this.rowStructs = this.renderSegRows(segs);
// append to each row's content skeleton
this.dayGrid.rowEls.forEach(function (rowNode, i) {
rowNode.querySelector('.fc-content-skeleton > table').appendChild(rowStructs[i].tbodyEl);
});
// removes the "more.." events popover
if (!mirrorInfo) {
this.dayGrid.removeSegPopover();
}
};
// Unrenders all currently rendered foreground event segments
DayGridEventRenderer.prototype.detachSegs = function () {
var rowStructs = this.rowStructs || [];
var rowStruct;
while ((rowStruct = rowStructs.pop())) {
core.removeElement(rowStruct.tbodyEl);
}
this.rowStructs = null;
};
// Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
// Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
// PRECONDITION: each segment shoud already have a rendered and assigned `.el`
DayGridEventRenderer.prototype.renderSegRows = function (segs) {
var rowStructs = [];
var segRows;
var row;
segRows = this.groupSegRows(segs); // group into nested arrays
// iterate each row of segment groupings
for (row = 0; row < segRows.length; row++) {
rowStructs.push(this.renderSegRow(row, segRows[row]));
}
return rowStructs;
};
// Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
// the segments. Returns object with a bunch of internal data about how the render was calculated.
// NOTE: modifies rowSegs
DayGridEventRenderer.prototype.renderSegRow = function (row, rowSegs) {
var isRtl = this.context.isRtl;
var dayGrid = this.dayGrid;
var colCnt = dayGrid.colCnt;
var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
var tbody = document.createElement('tbody');
var segMatrix = []; // lookup for which segments are rendered into which level+col cells
var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
var i;
var levelSegs;
var col;
var tr;
var j;
var seg;
var td;
// populates empty cells from the current column (`col`) to `endCol`
function emptyCellsUntil(endCol) {
while (col < endCol) {
// try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
td = (loneCellMatrix[i - 1] || [])[col];
if (td) {
td.rowSpan = (td.rowSpan || 1) + 1;
}
else {
td = document.createElement('td');
tr.appendChild(td);
}
cellMatrix[i][col] = td;
loneCellMatrix[i][col] = td;
col++;
}
}
for (i = 0; i < levelCnt; i++) { // iterate through all levels
levelSegs = segLevels[i];
col = 0;
tr = document.createElement('tr');
segMatrix.push([]);
cellMatrix.push([]);
loneCellMatrix.push([]);
// levelCnt might be 1 even though there are no actual levels. protect against this.
// this single empty row is useful for styling.
if (levelSegs) {
for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
seg = levelSegs[j];
var leftCol = isRtl ? (colCnt - 1 - seg.lastCol) : seg.firstCol;
var rightCol = isRtl ? (colCnt - 1 - seg.firstCol) : seg.lastCol;
emptyCellsUntil(leftCol);
// create a container that occupies or more columns. append the event element.
td = core.createElement('td', { className: 'fc-event-container' }, seg.el);
if (leftCol !== rightCol) {
td.colSpan = rightCol - leftCol + 1;
}
else { // a single-column segment
loneCellMatrix[i][col] = td;
}
while (col <= rightCol) {
cellMatrix[i][col] = td;
segMatrix[i][col] = seg;
col++;
}
tr.appendChild(td);
}
}
emptyCellsUntil(colCnt); // finish off the row
var introHtml = dayGrid.renderProps.renderIntroHtml();
if (introHtml) {
if (isRtl) {
core.appendToElement(tr, introHtml);
}
else {
core.prependToElement(tr, introHtml);
}
}
tbody.appendChild(tr);
}
return {
row: row,
tbodyEl: tbody,
cellMatrix: cellMatrix,
segMatrix: segMatrix,
segLevels: segLevels,
segs: rowSegs
};
};
// Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
// NOTE: modifies segs
DayGridEventRenderer.prototype.buildSegLevels = function (segs) {
var isRtl = this.context.isRtl;
var colCnt = this.dayGrid.colCnt;
var levels = [];
var i;
var seg;
var j;
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segs = this.sortEventSegs(segs);
for (i = 0; i < segs.length; i++) {
seg = segs[i];
// loop through levels, starting with the topmost, until the segment doesn't collide with other segments
for (j = 0; j < levels.length; j++) {
if (!isDaySegCollision(seg, levels[j])) {
break;
}
}
// `j` now holds the desired subrow index
seg.level = j;
seg.leftCol = isRtl ? (colCnt - 1 - seg.lastCol) : seg.firstCol; // for sorting only
seg.rightCol = isRtl ? (colCnt - 1 - seg.firstCol) : seg.lastCol // for sorting only
;
(levels[j] || (levels[j] = [])).push(seg);
}
// order segments left-to-right. very important if calendar is RTL
for (j = 0; j < levels.length; j++) {
levels[j].sort(compareDaySegCols);
}
return levels;
};
// Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
DayGridEventRenderer.prototype.groupSegRows = function (segs) {
var segRows = [];
var i;
for (i = 0; i < this.dayGrid.rowCnt; i++) {
segRows.push([]);
}
for (i = 0; i < segs.length; i++) {
segRows[segs[i].row].push(segs[i]);
}
return segRows;
};
// Computes a default `displayEventEnd` value if one is not expliclty defined
DayGridEventRenderer.prototype.computeDisplayEventEnd = function () {
return this.dayGrid.colCnt === 1; // we'll likely have space if there's only one day
};
return DayGridEventRenderer;
}(SimpleDayGridEventRenderer));
// Computes whether two segments' columns collide. They are assumed to be in the same row.
function isDaySegCollision(seg, otherSegs) {
var i;
var otherSeg;
for (i = 0; i < otherSegs.length; i++) {
otherSeg = otherSegs[i];
if (otherSeg.firstCol <= seg.lastCol &&
otherSeg.lastCol >= seg.firstCol) {
return true;
}
}
return false;
}
// A cmp function for determining the leftmost event
function compareDaySegCols(a, b) {
return a.leftCol - b.leftCol;
}
var DayGridMirrorRenderer = /** @class */ (function (_super) {
__extends(DayGridMirrorRenderer, _super);
function DayGridMirrorRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
DayGridMirrorRenderer.prototype.attachSegs = function (segs, mirrorInfo) {
var sourceSeg = mirrorInfo.sourceSeg;
var rowStructs = this.rowStructs = this.renderSegRows(segs);
// inject each new event skeleton into each associated row
this.dayGrid.rowEls.forEach(function (rowNode, row) {
var skeletonEl = core.htmlToElement('<div class="fc-mirror-skeleton"><table></table></div>'); // will be absolutely positioned
var skeletonTopEl;
var skeletonTop;
// If there is an original segment, match the top position. Otherwise, put it at the row's top level
if (sourceSeg && sourceSeg.row === row) {
skeletonTopEl = sourceSeg.el;
}
else {
skeletonTopEl = rowNode.querySelector('.fc-content-skeleton tbody');
if (!skeletonTopEl) { // when no events
skeletonTopEl = rowNode.querySelector('.fc-content-skeleton table');
}
}
skeletonTop = skeletonTopEl.getBoundingClientRect().top -
rowNode.getBoundingClientRect().top; // the offsetParent origin
skeletonEl.style.top = skeletonTop + 'px';
skeletonEl.querySelector('table').appendChild(rowStructs[row].tbodyEl);
rowNode.appendChild(skeletonEl);
});
};
return DayGridMirrorRenderer;
}(DayGridEventRenderer));
var EMPTY_CELL_HTML = '<td style="pointer-events:none"></td>';
var DayGridFillRenderer = /** @class */ (function (_super) {
__extends(DayGridFillRenderer, _super);
function DayGridFillRenderer(dayGrid) {
var _this = _super.call(this) || this;
_this.fillSegTag = 'td'; // override the default tag name
_this.dayGrid = dayGrid;
return _this;
}
DayGridFillRenderer.prototype.renderSegs = function (type, context, segs) {
// don't render timed background events
if (type === 'bgEvent') {
segs = segs.filter(function (seg) {
return seg.eventRange.def.allDay;
});
}
_super.prototype.renderSegs.call(this, type, context, segs);
};
DayGridFillRenderer.prototype.attachSegs = function (type, segs) {
var els = [];
var i;
var seg;
var skeletonEl;
for (i = 0; i < segs.length; i++) {
seg = segs[i];
skeletonEl = this.renderFillRow(type, seg);
this.dayGrid.rowEls[seg.row].appendChild(skeletonEl);
els.push(skeletonEl);
}
return els;
};
// Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
DayGridFillRenderer.prototype.renderFillRow = function (type, seg) {
var dayGrid = this.dayGrid;
var isRtl = this.context.isRtl;
var colCnt = dayGrid.colCnt;
var leftCol = isRtl ? (colCnt - 1 - seg.lastCol) : seg.firstCol;
var rightCol = isRtl ? (colCnt - 1 - seg.firstCol) : seg.lastCol;
var startCol = leftCol;
var endCol = rightCol + 1;
var className;
var skeletonEl;
var trEl;
if (type === 'businessHours') {
className = 'bgevent';
}
else {
className = type.toLowerCase();
}
skeletonEl = core.htmlToElement('<div class="fc-' + className + '-skeleton">' +
'<table><tr></tr></table>' +
'</div>');
trEl = skeletonEl.getElementsByTagName('tr')[0];
if (startCol > 0) {
core.appendToElement(trEl,
// will create (startCol + 1) td's
new Array(startCol + 1).join(EMPTY_CELL_HTML));
}
seg.el.colSpan = endCol - startCol;
trEl.appendChild(seg.el);
if (endCol < colCnt) {
core.appendToElement(trEl,
// will create (colCnt - endCol) td's
new Array(colCnt - endCol + 1).join(EMPTY_CELL_HTML));
}
var introHtml = dayGrid.renderProps.renderIntroHtml();
if (introHtml) {
if (isRtl) {
core.appendToElement(trEl, introHtml);
}
else {
core.prependToElement(trEl, introHtml);
}
}
return skeletonEl;
};
return DayGridFillRenderer;
}(core.FillRenderer));
var DayTile = /** @class */ (function (_super) {
__extends(DayTile, _super);
function DayTile(el) {
var _this = _super.call(this, el) || this;
var eventRenderer = _this.eventRenderer = new DayTileEventRenderer(_this);
var renderFrame = _this.renderFrame = core.memoizeRendering(_this._renderFrame);
_this.renderFgEvents = core.memoizeRendering(eventRenderer.renderSegs.bind(eventRenderer), eventRenderer.unrender.bind(eventRenderer), [renderFrame]);
_this.renderEventSelection = core.memoizeRendering(eventRenderer.selectByInstanceId.bind(eventRenderer), eventRenderer.unselectByInstanceId.bind(eventRenderer), [_this.renderFgEvents]);
_this.renderEventDrag = core.memoizeRendering(eventRenderer.hideByHash.bind(eventRenderer), eventRenderer.showByHash.bind(eventRenderer), [renderFrame]);
_this.renderEventResize = core.memoizeRendering(eventRenderer.hideByHash.bind(eventRenderer), eventRenderer.showByHash.bind(eventRenderer), [renderFrame]);
return _this;
}
DayTile.prototype.firstContext = function (context) {
context.calendar.registerInteractiveComponent(this, {
el: this.el,
useEventCenter: false
});
};
DayTile.prototype.render = function (props, context) {
this.renderFrame(props.date);
this.renderFgEvents(context, props.fgSegs);
this.renderEventSelection(props.eventSelection);
this.renderEventDrag(props.eventDragInstances);
this.renderEventResize(props.eventResizeInstances);
};
DayTile.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.renderFrame.unrender(); // should unrender everything else
this.context.calendar.unregisterInteractiveComponent(this);
};
DayTile.prototype._renderFrame = function (date) {
var _a = this.context, theme = _a.theme, dateEnv = _a.dateEnv, options = _a.options;
var title = dateEnv.format(date, core.createFormatter(options.dayPopoverFormat) // TODO: cache
);
this.el.innerHTML =
'<div class="fc-header ' + theme.getClass('popoverHeader') + '">' +
'<span class="fc-title">' +
core.htmlEscape(title) +
'</span>' +
'<span class="fc-close ' + theme.getIconClass('close') + '"></span>' +
'</div>' +
'<div class="fc-body ' + theme.getClass('popoverContent') + '">' +
'<div class="fc-event-container"></div>' +
'</div>';
this.segContainerEl = this.el.querySelector('.fc-event-container');
};
DayTile.prototype.queryHit = function (positionLeft, positionTop, elWidth, elHeight) {
var date = this.props.date; // HACK
if (positionLeft < elWidth && positionTop < elHeight) {
return {
component: this,
dateSpan: {
allDay: true,
range: { start: date, end: core.addDays(date, 1) }
},
dayEl: this.el,
rect: {
left: 0,
top: 0,
right: elWidth,
bottom: elHeight
},
layer: 1
};
}
};
return DayTile;
}(core.DateComponent));
var DayTileEventRenderer = /** @class */ (function (_super) {
__extends(DayTileEventRenderer, _super);
function DayTileEventRenderer(dayTile) {
var _this = _super.call(this) || this;
_this.dayTile = dayTile;
return _this;
}
DayTileEventRenderer.prototype.attachSegs = function (segs) {
for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {
var seg = segs_1[_i];
this.dayTile.segContainerEl.appendChild(seg.el);
}
};
DayTileEventRenderer.prototype.detachSegs = function (segs) {
for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
var seg = segs_2[_i];
core.removeElement(seg.el);
}
};
return DayTileEventRenderer;
}(SimpleDayGridEventRenderer));
var DayBgRow = /** @class */ (function () {
function DayBgRow(context) {
this.context = context;
}
DayBgRow.prototype.renderHtml = function (props) {
var parts = [];
if (props.renderIntroHtml) {
parts.push(props.renderIntroHtml());
}
for (var _i = 0, _a = props.cells; _i < _a.length; _i++) {
var cell = _a[_i];
parts.push(renderCellHtml(cell.date, props.dateProfile, this.context, cell.htmlAttrs));
}
if (!props.cells.length) {
parts.push('<td class="fc-day ' + this.context.theme.getClass('widgetContent') + '"></td>');
}
if (this.context.options.dir === 'rtl') {
parts.reverse();
}
return '<tr>' + parts.join('') + '</tr>';
};
return DayBgRow;
}());
function renderCellHtml(date, dateProfile, context, otherAttrs) {
var dateEnv = context.dateEnv, theme = context.theme;
var isDateValid = core.rangeContainsMarker(dateProfile.activeRange, date); // TODO: called too frequently. cache somehow.
var classes = core.getDayClasses(date, dateProfile, context);
classes.unshift('fc-day', theme.getClass('widgetContent'));
return '<td class="' + classes.join(' ') + '"' +
(isDateValid ?
' data-date="' + dateEnv.formatIso(date, { omitTime: true }) + '"' :
'') +
(otherAttrs ?
' ' + otherAttrs :
'') +
'></td>';
}
var DAY_NUM_FORMAT = core.createFormatter({ day: 'numeric' });
var WEEK_NUM_FORMAT = core.createFormatter({ week: 'numeric' });
var DayGrid = /** @class */ (function (_super) {
__extends(DayGrid, _super);
function DayGrid(el, renderProps) {
var _this = _super.call(this, el) || this;
_this.bottomCoordPadding = 0; // hack for extending the hit area for the last row of the coordinate grid
_this.isCellSizesDirty = false;
_this.renderProps = renderProps;
var eventRenderer = _this.eventRenderer = new DayGridEventRenderer(_this);
var fillRenderer = _this.fillRenderer = new DayGridFillRenderer(_this);
_this.mirrorRenderer = new DayGridMirrorRenderer(_this);
var renderCells = _this.renderCells = core.memoizeRendering(_this._renderCells, _this._unrenderCells);
_this.renderBusinessHours = core.memoizeRendering(fillRenderer.renderSegs.bind(fillRenderer, 'businessHours'), fillRenderer.unrender.bind(fillRenderer, 'businessHours'), [renderCells]);
_this.renderDateSelection = core.memoizeRendering(fillRenderer.renderSegs.bind(fillRenderer, 'highlight'), fillRenderer.unrender.bind(fillRenderer, 'highlight'), [renderCells]);
_this.renderBgEvents = core.memoizeRendering(fillRenderer.renderSegs.bind(fillRenderer, 'bgEvent'), fillRenderer.unrender.bind(fillRenderer, 'bgEvent'), [renderCells]);
_this.renderFgEvents = core.memoizeRendering(eventRenderer.renderSegs.bind(eventRenderer), eventRenderer.unrender.bind(eventRenderer), [renderCells]);
_this.renderEventSelection = core.memoizeRendering(eventRenderer.selectByInstanceId.bind(eventRenderer), eventRenderer.unselectByInstanceId.bind(eventRenderer), [_this.renderFgEvents]);
_this.renderEventDrag = core.memoizeRendering(_this._renderEventDrag, _this._unrenderEventDrag, [renderCells]);
_this.renderEventResize = core.memoizeRendering(_this._renderEventResize, _this._unrenderEventResize, [renderCells]);
return _this;
}
DayGrid.prototype.render = function (props, context) {
var cells = props.cells;
this.rowCnt = cells.length;
this.colCnt = cells[0].length;
this.renderCells(cells, props.isRigid);
this.renderBusinessHours(context, props.businessHourSegs);
this.renderDateSelection(context, props.dateSelectionSegs);
this.renderBgEvents(context, props.bgEventSegs);
this.renderFgEvents(context, props.fgEventSegs);
this.renderEventSelection(props.eventSelection);
this.renderEventDrag(props.eventDrag);
this.renderEventResize(props.eventResize);
if (this.segPopoverTile) {
this.updateSegPopoverTile();
}
};
DayGrid.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.renderCells.unrender(); // will unrender everything else
};
DayGrid.prototype.getCellRange = function (row, col) {
var start = this.props.cells[row][col].date;
var end = core.addDays(start, 1);
return { start: start, end: end };
};
DayGrid.prototype.updateSegPopoverTile = function (date, segs) {
var ownProps = this.props;
this.segPopoverTile.receiveProps({
date: date || this.segPopoverTile.props.date,
fgSegs: segs || this.segPopoverTile.props.fgSegs,
eventSelection: ownProps.eventSelection,
eventDragInstances: ownProps.eventDrag ? ownProps.eventDrag.affectedInstances : null,
eventResizeInstances: ownProps.eventResize ? ownProps.eventResize.affectedInstances : null
}, this.context);
};
/* Date Rendering
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype._renderCells = function (cells, isRigid) {
var _a = this.context, calendar = _a.calendar, view = _a.view, isRtl = _a.isRtl, dateEnv = _a.dateEnv;
var _b = this, rowCnt = _b.rowCnt, colCnt = _b.colCnt;
var html = '';
var row;
var col;
for (row = 0; row < rowCnt; row++) {
html += this.renderDayRowHtml(row, isRigid);
}
this.el.innerHTML = html;
this.rowEls = core.findElements(this.el, '.fc-row');
this.cellEls = core.findElements(this.el, '.fc-day, .fc-disabled-day');
if (isRtl) {
this.cellEls.reverse();
}
this.rowPositions = new core.PositionCache(this.el, this.rowEls, false, true // vertical
);
this.colPositions = new core.PositionCache(this.el, this.cellEls.slice(0, colCnt), // only the first row
true, false // horizontal
);
// trigger dayRender with each cell's element
for (row = 0; row < rowCnt; row++) {
for (col = 0; col < colCnt; col++) {
calendar.publiclyTrigger('dayRender', [
{
date: dateEnv.toDate(cells[row][col].date),
el: this.getCellEl(row, col),
view: view
}
]);
}
}
this.isCellSizesDirty = true;
};
DayGrid.prototype._unrenderCells = function () {
this.removeSegPopover();
};
// Generates the HTML for a single row, which is a div that wraps a table.
// `row` is the row number.
DayGrid.prototype.renderDayRowHtml = function (row, isRigid) {
var theme = this.context.theme;
var classes = ['fc-row', 'fc-week', theme.getClass('dayRow')];
if (isRigid) {
classes.push('fc-rigid');
}
var bgRow = new DayBgRow(this.context);
return '' +
'<div class="' + classes.join(' ') + '">' +
'<div class="fc-bg">' +
'<table class="' + theme.getClass('tableGrid') + '">' +
bgRow.renderHtml({
cells: this.props.cells[row],
dateProfile: this.props.dateProfile,
renderIntroHtml: this.renderProps.renderBgIntroHtml
}) +
'</table>' +
'</div>' +
'<div class="fc-content-skeleton">' +
'<table>' +
(this.getIsNumbersVisible() ?
'<thead>' +
this.renderNumberTrHtml(row) +
'</thead>' :
'') +
'</table>' +
'</div>' +
'</div>';
};
DayGrid.prototype.getIsNumbersVisible = function () {
return this.getIsDayNumbersVisible() ||
this.renderProps.cellWeekNumbersVisible ||
this.renderProps.colWeekNumbersVisible;
};
DayGrid.prototype.getIsDayNumbersVisible = function () {
return this.rowCnt > 1;
};
/* Grid Number Rendering
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype.renderNumberTrHtml = function (row) {
var isRtl = this.context.isRtl;
var intro = this.renderProps.renderNumberIntroHtml(row, this);
return '' +
'<tr>' +
(isRtl ? '' : intro) +
this.renderNumberCellsHtml(row) +
(isRtl ? intro : '') +
'</tr>';
};
DayGrid.prototype.renderNumberCellsHtml = function (row) {
var htmls = [];
var col;
var date;
for (col = 0; col < this.colCnt; col++) {
date = this.props.cells[row][col].date;
htmls.push(this.renderNumberCellHtml(date));
}
if (this.context.isRtl) {
htmls.reverse();
}
return htmls.join('');
};
// Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
// The number row will only exist if either day numbers or week numbers are turned on.
DayGrid.prototype.renderNumberCellHtml = function (date) {
var _a = this.context, dateEnv = _a.dateEnv, options = _a.options;
var html = '';
var isDateValid = core.rangeContainsMarker(this.props.dateProfile.activeRange, date); // TODO: called too frequently. cache somehow.
var isDayNumberVisible = this.getIsDayNumbersVisible() && isDateValid;
var classes;
var weekCalcFirstDow;
if (!isDayNumberVisible && !this.renderProps.cellWeekNumbersVisible) {
// no numbers in day cell (week number must be along the side)
return '<td></td>'; // will create an empty space above events :(
}
classes = core.getDayClasses(date, this.props.dateProfile, this.context);
classes.unshift('fc-day-top');
if (this.renderProps.cellWeekNumbersVisible) {
weekCalcFirstDow = dateEnv.weekDow;
}
html += '<td class="' + classes.join(' ') + '"' +
(isDateValid ?
' data-date="' + dateEnv.formatIso(date, { omitTime: true }) + '"' :
'') +
'>';
if (this.renderProps.cellWeekNumbersVisible && (date.getUTCDay() === weekCalcFirstDow)) {
html += core.buildGotoAnchorHtml(options, dateEnv, { date: date, type: 'week' }, { 'class': 'fc-week-number' }, dateEnv.format(date, WEEK_NUM_FORMAT) // inner HTML
);
}
if (isDayNumberVisible) {
html += core.buildGotoAnchorHtml(options, dateEnv, date, { 'class': 'fc-day-number' }, dateEnv.format(date, DAY_NUM_FORMAT) // inner HTML
);
}
html += '</td>';
return html;
};
/* Sizing
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype.updateSize = function (isResize) {
var calendar = this.context.calendar;
var _a = this, fillRenderer = _a.fillRenderer, eventRenderer = _a.eventRenderer, mirrorRenderer = _a.mirrorRenderer;
if (isResize ||
this.isCellSizesDirty ||
calendar.isEventsUpdated // hack
) {
this.buildPositionCaches();
this.isCellSizesDirty = false;
}
fillRenderer.computeSizes(isResize);
eventRenderer.computeSizes(isResize);
mirrorRenderer.computeSizes(isResize);
fillRenderer.assignSizes(isResize);
eventRenderer.assignSizes(isResize);
mirrorRenderer.assignSizes(isResize);
};
DayGrid.prototype.buildPositionCaches = function () {
this.buildColPositions();
this.buildRowPositions();
};
DayGrid.prototype.buildColPositions = function () {
this.colPositions.build();
};
DayGrid.prototype.buildRowPositions = function () {
this.rowPositions.build();
this.rowPositions.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
};
/* Hit System
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype.positionToHit = function (leftPosition, topPosition) {
var _a = this, colPositions = _a.colPositions, rowPositions = _a.rowPositions;
var col = colPositions.leftToIndex(leftPosition);
var row = rowPositions.topToIndex(topPosition);
if (row != null && col != null) {
return {
row: row,
col: col,
dateSpan: {
range: this.getCellRange(row, col),
allDay: true
},
dayEl: this.getCellEl(row, col),
relativeRect: {
left: colPositions.lefts[col],
right: colPositions.rights[col],
top: rowPositions.tops[row],
bottom: rowPositions.bottoms[row]
}
};
}
};
/* Cell System
------------------------------------------------------------------------------------------------------------------*/
// FYI: the first column is the leftmost column, regardless of date
DayGrid.prototype.getCellEl = function (row, col) {
return this.cellEls[row * this.colCnt + col];
};
/* Event Drag Visualization
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype._renderEventDrag = function (state) {
if (state) {
this.eventRenderer.hideByHash(state.affectedInstances);
this.fillRenderer.renderSegs('highlight', this.context, state.segs);
}
};
DayGrid.prototype._unrenderEventDrag = function (state) {
if (state) {
this.eventRenderer.showByHash(state.affectedInstances);
this.fillRenderer.unrender('highlight', this.context);
}
};
/* Event Resize Visualization
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype._renderEventResize = function (state) {
if (state) {
this.eventRenderer.hideByHash(state.affectedInstances);
this.fillRenderer.renderSegs('highlight', this.context, state.segs);
this.mirrorRenderer.renderSegs(this.context, state.segs, { isResizing: true, sourceSeg: state.sourceSeg });
}
};
DayGrid.prototype._unrenderEventResize = function (state) {
if (state) {
this.eventRenderer.showByHash(state.affectedInstances);
this.fillRenderer.unrender('highlight', this.context);
this.mirrorRenderer.unrender(this.context, state.segs, { isResizing: true, sourceSeg: state.sourceSeg });
}
};
/* More+ Link Popover
------------------------------------------------------------------------------------------------------------------*/
DayGrid.prototype.removeSegPopover = function () {
if (this.segPopover) {
this.segPopover.hide(); // in handler, will call segPopover's removeElement
}
};
// Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
// `levelLimit` can be false (don't limit), a number, or true (should be computed).
DayGrid.prototype.limitRows = function (levelLimit) {
var rowStructs = this.eventRenderer.rowStructs || [];
var row; // row #
var rowLevelLimit;
for (row = 0; row < rowStructs.length; row++) {
this.unlimitRow(row);
if (!levelLimit) {
rowLevelLimit = false;
}
else if (typeof levelLimit === 'number') {
rowLevelLimit = levelLimit;
}
else {
rowLevelLimit = this.computeRowLevelLimit(row);
}
if (rowLevelLimit !== false) {
this.limitRow(row, rowLevelLimit);
}
}
};
// Computes the number of levels a row will accomodate without going outside its bounds.
// Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
// `row` is the row number.
DayGrid.prototype.computeRowLevelLimit = function (row) {
var rowEl = this.rowEls[row]; // the containing "fake" row div
var rowBottom = rowEl.getBoundingClientRect().bottom; // relative to viewport!
var trEls = core.findChildren(this.eventRenderer.rowStructs[row].tbodyEl);
var i;
var trEl;
// Reveal one level <tr> at a time and stop when we find one out of bounds
for (i = 0; i < trEls.length; i++) {
trEl = trEls[i];
trEl.classList.remove('fc-limited'); // reset to original state (reveal)
if (trEl.getBoundingClientRect().bottom > rowBottom) {
return i;
}
}
return false; // should not limit at all
};
// Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
// `row` is the row number.
// `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
DayGrid.prototype.limitRow = function (row, levelLimit) {
var _this = this;
var colCnt = this.colCnt;
var isRtl = this.context.isRtl;
var rowStruct = this.eventRenderer.rowStructs[row];
var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
var col = 0; // col #, left-to-right (not chronologically)
var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
var cellMatrix; // a matrix (by level, then column) of all <td> elements in the row
var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
var i;
var seg;
var segsBelow; // array of segment objects below `seg` in the current `col`
var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
var td;
var rowSpan;
var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
var j;
var moreTd;
var moreWrap;
var moreLink;
// Iterates through empty level cells and places "more" links inside if need be
var emptyCellsUntil = function (endCol) {
while (col < endCol) {
segsBelow = _this.getCellSegs(row, col, levelLimit);
if (segsBelow.length) {
td = cellMatrix[levelLimit - 1][col];
moreLink = _this.renderMoreLink(row, col, segsBelow);
moreWrap = core.createElement('div', null, moreLink);
td.appendChild(moreWrap);
moreNodes.push(moreWrap);
}
col++;
}
};
if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
levelSegs = rowStruct.segLevels[levelLimit - 1];
cellMatrix = rowStruct.cellMatrix;
limitedNodes = core.findChildren(rowStruct.tbodyEl).slice(levelLimit); // get level <tr> elements past the limit
limitedNodes.forEach(function (node) {
node.classList.add('fc-limited'); // hide elements and get a simple DOM-nodes array
});
// iterate though segments in the last allowable level
for (i = 0; i < levelSegs.length; i++) {
seg = levelSegs[i];
var leftCol = isRtl ? (colCnt - 1 - seg.lastCol) : seg.firstCol;
var rightCol = isRtl ? (colCnt - 1 - seg.firstCol) : seg.lastCol;
emptyCellsUntil(leftCol); // process empty cells before the segment
// determine *all* segments below `seg` that occupy the same columns
colSegsBelow = [];
totalSegsBelow = 0;
while (col <= rightCol) {
segsBelow = this.getCellSegs(row, col, levelLimit);
colSegsBelow.push(segsBelow);
totalSegsBelow += segsBelow.length;
col++;
}
if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
td = cellMatrix[levelLimit - 1][leftCol]; // the segment's parent cell
rowSpan = td.rowSpan || 1;
segMoreNodes = [];
// make a replacement <td> for each column the segment occupies. will be one for each colspan
for (j = 0; j < colSegsBelow.length; j++) {
moreTd = core.createElement('td', { className: 'fc-more-cell', rowSpan: rowSpan });
segsBelow = colSegsBelow[j];
moreLink = this.renderMoreLink(row, leftCol + j, [seg].concat(segsBelow) // count seg as hidden too
);
moreWrap = core.createElement('div', null, moreLink);
moreTd.appendChild(moreWrap);
segMoreNodes.push(moreTd);
moreNodes.push(moreTd);
}
td.classList.add('fc-limited');
core.insertAfterElement(td, segMoreNodes);
limitedNodes.push(td);
}
}
emptyCellsUntil(this.colCnt); // finish off the level
rowStruct.moreEls = moreNodes; // for easy undoing later
rowStruct.limitedEls = limitedNodes; // for easy undoing later
}
};
// Reveals all levels and removes all "more"-related elements for a grid's row.
// `row` is a row number.
DayGrid.prototype.unlimitRow = function (row) {
var rowStruct = this.eventRenderer.rowStructs[row];
if (rowStruct.moreEls) {
rowStruct.moreEls.forEach(core.removeElement);
rowStruct.moreEls = null;
}
if (rowStruct.limitedEls) {
rowStruct.limitedEls.forEach(function (limitedEl) {
limitedEl.classList.remove('fc-limited');
});
rowStruct.limitedEls = null;
}
};
// Renders an <a> element that represents hidden event element for a cell.
// Responsible for attaching click handler as well.
DayGrid.prototype.renderMoreLink = function (row, col, hiddenSegs) {
var _this = this;
var _a = this.context, calendar = _a.calendar, view = _a.view, dateEnv = _a.dateEnv, options = _a.options, isRtl = _a.isRtl;
var a = core.createElement('a', { className: 'fc-more' });
a.innerText = this.getMoreLinkText(hiddenSegs.length);
a.addEventListener('click', function (ev) {
var clickOption = options.eventLimitClick;
var _col = isRtl ? _this.colCnt - col - 1 : col; // HACK: props.cells has different dir system?
var date = _this.props.cells[row][_col].date;
var moreEl = ev.currentTarget;
var dayEl = _this.getCellEl(row, col);
var allSegs = _this.getCellSegs(row, col);
// rescope the segments to be within the cell's date
var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
if (typeof clickOption === 'function') {
// the returned value can be an atomic option
clickOption = calendar.publiclyTrigger('eventLimitClick', [
{
date: dateEnv.toDate(date),
allDay: true,
dayEl: dayEl,
moreEl: moreEl,
segs: reslicedAllSegs,
hiddenSegs: reslicedHiddenSegs,
jsEvent: ev,
view: view
}
]);
}
if (clickOption === 'popover') {
_this.showSegPopover(row, col, moreEl, reslicedAllSegs);
}
else if (typeof clickOption === 'string') { // a view name
calendar.zoomTo(date, clickOption);
}
});
return a;
};
// Reveals the popover that displays all events within a cell
DayGrid.prototype.showSegPopover = function (row, col, moreLink, segs) {
var _this = this;
var _a = this.context, calendar = _a.calendar, view = _a.view, theme = _a.theme, isRtl = _a.isRtl;
var _col = isRtl ? this.colCnt - col - 1 : col; // HACK: props.cells has different dir system?
var moreWrap = moreLink.parentNode; // the <div> wrapper around the <a>
var topEl; // the element we want to match the top coordinate of
var options;
if (this.rowCnt === 1) {
topEl = view.el; // will cause the popover to cover any sort of header
}
else {
topEl = this.rowEls[row]; // will align with top of row
}
options = {
className: 'fc-more-popover ' + theme.getClass('popover'),
parentEl: view.el,
top: core.computeRect(topEl).top,
autoHide: true,
content: function (el) {
_this.segPopoverTile = new DayTile(el);
_this.updateSegPopoverTile(_this.props.cells[row][_col].date, segs);
},
hide: function () {
_this.segPopoverTile.destroy();
_this.segPopoverTile = null;
_this.segPopover.destroy();
_this.segPopover = null;
}
};
// Determine horizontal coordinate.
// We use the moreWrap instead of the <td> to avoid border confusion.
if (isRtl) {
options.right = core.computeRect(moreWrap).right + 1; // +1 to be over cell border
}
else {
options.left = core.computeRect(moreWrap).left - 1; // -1 to be over cell border
}
this.segPopover = new Popover(options);
this.segPopover.show();
calendar.releaseAfterSizingTriggers(); // hack for eventPositioned
};
// Given the events within an array of segment objects, reslice them to be in a single day
DayGrid.prototype.resliceDaySegs = function (segs, dayDate) {
var dayStart = dayDate;
var dayEnd = core.addDays(dayStart, 1);
var dayRange = { start: dayStart, end: dayEnd };
var newSegs = [];
for (var _i = 0, segs_1 = segs; _i < segs_1.length; _i++) {
var seg = segs_1[_i];
var eventRange = seg.eventRange;
var origRange = eventRange.range;
var slicedRange = core.intersectRanges(origRange, dayRange);
if (slicedRange) {
newSegs.push(__assign({}, seg, { eventRange: {
def: eventRange.def,
ui: __assign({}, eventRange.ui, { durationEditable: false }),
instance: eventRange.instance,
range: slicedRange
}, isStart: seg.isStart && slicedRange.start.valueOf() === origRange.start.valueOf(), isEnd: seg.isEnd && slicedRange.end.valueOf() === origRange.end.valueOf() }));
}
}
return newSegs;
};
// Generates the text that should be inside a "more" link, given the number of events it represents
DayGrid.prototype.getMoreLinkText = function (num) {
var opt = this.context.options.eventLimitText;
if (typeof opt === 'function') {
return opt(num);
}
else {
return '+' + num + ' ' + opt;
}
};
// Returns segments within a given cell.
// If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
DayGrid.prototype.getCellSegs = function (row, col, startLevel) {
var segMatrix = this.eventRenderer.rowStructs[row].segMatrix;
var level = startLevel || 0;
var segs = [];
var seg;
while (level < segMatrix.length) {
seg = segMatrix[level][col];
if (seg) {
segs.push(seg);
}
level++;
}
return segs;
};
return DayGrid;
}(core.DateComponent));
var WEEK_NUM_FORMAT$1 = core.createFormatter({ week: 'numeric' });
/* An abstract class for the daygrid views, as well as month view. Renders one or more rows of day cells.
----------------------------------------------------------------------------------------------------------------------*/
// It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
// It is responsible for managing width/height.
var AbstractDayGridView = /** @class */ (function (_super) {
__extends(AbstractDayGridView, _super);
function AbstractDayGridView() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.processOptions = core.memoize(_this._processOptions);
_this.renderSkeleton = core.memoizeRendering(_this._renderSkeleton, _this._unrenderSkeleton);
/* Header Rendering
------------------------------------------------------------------------------------------------------------------*/
// Generates the HTML that will go before the day-of week header cells
_this.renderHeadIntroHtml = function () {
var _a = _this.context, theme = _a.theme, options = _a.options;
if (_this.colWeekNumbersVisible) {
return '' +
'<th class="fc-week-number ' + theme.getClass('widgetHeader') + '" ' + _this.weekNumberStyleAttr() + '>' +
'<span>' + // needed for matchCellWidths
core.htmlEscape(options.weekLabel) +
'</span>' +
'</th>';
}
return '';
};
/* Day Grid Rendering
------------------------------------------------------------------------------------------------------------------*/
// Generates the HTML that will go before content-skeleton cells that display the day/week numbers
_this.renderDayGridNumberIntroHtml = function (row, dayGrid) {
var _a = _this.context, options = _a.options, dateEnv = _a.dateEnv;
var weekStart = dayGrid.props.cells[row][0].date;
if (_this.colWeekNumbersVisible) {
return '' +
'<td class="fc-week-number" ' + _this.weekNumberStyleAttr() + '>' +
core.buildGotoAnchorHtml(// aside from link, important for matchCellWidths
options, dateEnv, { date: weekStart, type: 'week', forceOff: dayGrid.colCnt === 1 }, dateEnv.format(weekStart, WEEK_NUM_FORMAT$1) // inner HTML
) +
'</td>';
}
return '';
};
// Generates the HTML that goes before the day bg cells for each day-row
_this.renderDayGridBgIntroHtml = function () {
var theme = _this.context.theme;
if (_this.colWeekNumbersVisible) {
return '<td class="fc-week-number ' + theme.getClass('widgetContent') + '" ' + _this.weekNumberStyleAttr() + '></td>';
}
return '';
};
// Generates the HTML that goes before every other type of row generated by DayGrid.
// Affects mirror-skeleton and highlight-skeleton rows.
_this.renderDayGridIntroHtml = function () {
if (_this.colWeekNumbersVisible) {
return '<td class="fc-week-number" ' + _this.weekNumberStyleAttr() + '></td>';
}
return '';
};
return _this;
}
AbstractDayGridView.prototype._processOptions = function (options) {
if (options.weekNumbers) {
if (options.weekNumbersWithinDays) {
this.cellWeekNumbersVisible = true;
this.colWeekNumbersVisible = false;
}
else {
this.cellWeekNumbersVisible = false;
this.colWeekNumbersVisible = true;
}
}
else {
this.colWeekNumbersVisible = false;
this.cellWeekNumbersVisible = false;
}
};
AbstractDayGridView.prototype.render = function (props, context) {
_super.prototype.render.call(this, props, context);
this.processOptions(context.options);
this.renderSkeleton(context);
};
AbstractDayGridView.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.renderSkeleton.unrender();
};
AbstractDayGridView.prototype._renderSkeleton = function (context) {
this.el.classList.add('fc-dayGrid-view');
this.el.innerHTML = this.renderSkeletonHtml();
this.scroller = new core.ScrollComponent('hidden', // overflow x
'auto' // overflow y
);
var dayGridContainerEl = this.scroller.el;
this.el.querySelector('.fc-body > tr > td').appendChild(dayGridContainerEl);
dayGridContainerEl.classList.add('fc-day-grid-container');
var dayGridEl = core.createElement('div', { className: 'fc-day-grid' });
dayGridContainerEl.appendChild(dayGridEl);
this.dayGrid = new DayGrid(dayGridEl, {
renderNumberIntroHtml: this.renderDayGridNumberIntroHtml,
renderBgIntroHtml: this.renderDayGridBgIntroHtml,
renderIntroHtml: this.renderDayGridIntroHtml,
colWeekNumbersVisible: this.colWeekNumbersVisible,
cellWeekNumbersVisible: this.cellWeekNumbersVisible
});
};
AbstractDayGridView.prototype._unrenderSkeleton = function () {
this.el.classList.remove('fc-dayGrid-view');
this.dayGrid.destroy();
this.scroller.destroy();
};
// Builds the HTML skeleton for the view.
// The day-grid component will render inside of a container defined by this HTML.
AbstractDayGridView.prototype.renderSkeletonHtml = function () {
var _a = this.context, theme = _a.theme, options = _a.options;
return '' +
'<table class="' + theme.getClass('tableGrid') + '">' +
(options.columnHeader ?
'<thead class="fc-head">' +
'<tr>' +
'<td class="fc-head-container ' + theme.getClass('widgetHeader') + '"> </td>' +
'</tr>' +
'</thead>' :
'') +
'<tbody class="fc-body">' +
'<tr>' +
'<td class="' + theme.getClass('widgetContent') + '"></td>' +
'</tr>' +
'</tbody>' +
'</table>';
};
// Generates an HTML attribute string for setting the width of the week number column, if it is known
AbstractDayGridView.prototype.weekNumberStyleAttr = function () {
if (this.weekNumberWidth != null) {
return 'style="width:' + this.weekNumberWidth + 'px"';
}
return '';
};
// Determines whether each row should have a constant height
AbstractDayGridView.prototype.hasRigidRows = function () {
var eventLimit = this.context.options.eventLimit;
return eventLimit && typeof eventLimit !== 'number';
};
/* Dimensions
------------------------------------------------------------------------------------------------------------------*/
AbstractDayGridView.prototype.updateSize = function (isResize, viewHeight, isAuto) {
_super.prototype.updateSize.call(this, isResize, viewHeight, isAuto); // will call updateBaseSize. important that executes first
this.dayGrid.updateSize(isResize);
};
// Refreshes the horizontal dimensions of the view
AbstractDayGridView.prototype.updateBaseSize = function (isResize, viewHeight, isAuto) {
var dayGrid = this.dayGrid;
var eventLimit = this.context.options.eventLimit;
var headRowEl = this.header ? this.header.el : null; // HACK
var scrollerHeight;
var scrollbarWidths;
// hack to give the view some height prior to dayGrid's columns being rendered
// TODO: separate setting height from scroller VS dayGrid.
if (!dayGrid.rowEls) {
if (!isAuto) {
scrollerHeight = this.computeScrollerHeight(viewHeight);
this.scroller.setHeight(scrollerHeight);
}
return;
}
if (this.colWeekNumbersVisible) {
// Make sure all week number cells running down the side have the same width.
this.weekNumberWidth = core.matchCellWidths(core.findElements(this.el, '.fc-week-number'));
}
// reset all heights to be natural
this.scroller.clear();
if (headRowEl) {
core.uncompensateScroll(headRowEl);
}
dayGrid.removeSegPopover(); // kill the "more" popover if displayed
// is the event limit a constant level number?
if (eventLimit && typeof eventLimit === 'number') {
dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
}
// distribute the height to the rows
// (viewHeight is a "recommended" value if isAuto)
scrollerHeight = this.computeScrollerHeight(viewHeight);
this.setGridHeight(scrollerHeight, isAuto);
// is the event limit dynamically calculated?
if (eventLimit && typeof eventLimit !== 'number') {
dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
}
if (!isAuto) { // should we force dimensions of the scroll container?
this.scroller.setHeight(scrollerHeight);
scrollbarWidths = this.scroller.getScrollbarWidths();
if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
if (headRowEl) {
core.compensateScroll(headRowEl, scrollbarWidths);
}
// doing the scrollbar compensation might have created text overflow which created more height. redo
scrollerHeight = this.computeScrollerHeight(viewHeight);
this.scroller.setHeight(scrollerHeight);
}
// guarantees the same scrollbar widths
this.scroller.lockOverflow(scrollbarWidths);
}
};
// given a desired total height of the view, returns what the height of the scroller should be
AbstractDayGridView.prototype.computeScrollerHeight = function (viewHeight) {
return viewHeight -
core.subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
};
// Sets the height of just the DayGrid component in this view
AbstractDayGridView.prototype.setGridHeight = function (height, isAuto) {
if (this.context.options.monthMode) {
// if auto, make the height of each row the height that it would be if there were 6 weeks
if (isAuto) {
height *= this.dayGrid.rowCnt / 6;
}
core.distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
}
else {
if (isAuto) {
core.undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
}
else {
core.distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
}
}
};
/* Scroll
------------------------------------------------------------------------------------------------------------------*/
AbstractDayGridView.prototype.computeDateScroll = function (duration) {
return { top: 0 };
};
AbstractDayGridView.prototype.queryDateScroll = function () {
return { top: this.scroller.getScrollTop() };
};
AbstractDayGridView.prototype.applyDateScroll = function (scroll) {
if (scroll.top !== undefined) {
this.scroller.setScrollTop(scroll.top);
}
};
return AbstractDayGridView;
}(core.View));
AbstractDayGridView.prototype.dateProfileGeneratorClass = DayGridDateProfileGenerator;
var SimpleDayGrid = /** @class */ (function (_super) {
__extends(SimpleDayGrid, _super);
function SimpleDayGrid(dayGrid) {
var _this = _super.call(this, dayGrid.el) || this;
_this.slicer = new DayGridSlicer();
_this.dayGrid = dayGrid;
return _this;
}
SimpleDayGrid.prototype.firstContext = function (context) {
context.calendar.registerInteractiveComponent(this, { el: this.dayGrid.el });
};
SimpleDayGrid.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.context.calendar.unregisterInteractiveComponent(this);
};
SimpleDayGrid.prototype.render = function (props, context) {
var dayGrid = this.dayGrid;
var dateProfile = props.dateProfile, dayTable = props.dayTable;
dayGrid.receiveProps(__assign({}, this.slicer.sliceProps(props, dateProfile, props.nextDayThreshold, context.calendar, dayGrid, dayTable), { dateProfile: dateProfile, cells: dayTable.cells, isRigid: props.isRigid }), context);
};
SimpleDayGrid.prototype.buildPositionCaches = function () {
this.dayGrid.buildPositionCaches();
};
SimpleDayGrid.prototype.queryHit = function (positionLeft, positionTop) {
var rawHit = this.dayGrid.positionToHit(positionLeft, positionTop);
if (rawHit) {
return {
component: this.dayGrid,
dateSpan: rawHit.dateSpan,
dayEl: rawHit.dayEl,
rect: {
left: rawHit.relativeRect.left,
right: rawHit.relativeRect.right,
top: rawHit.relativeRect.top,
bottom: rawHit.relativeRect.bottom
},
layer: 0
};
}
};
return SimpleDayGrid;
}(core.DateComponent));
var DayGridSlicer = /** @class */ (function (_super) {
__extends(DayGridSlicer, _super);
function DayGridSlicer() {
return _super !== null && _super.apply(this, arguments) || this;
}
DayGridSlicer.prototype.sliceRange = function (dateRange, dayTable) {
return dayTable.sliceRange(dateRange);
};
return DayGridSlicer;
}(core.Slicer));
var DayGridView = /** @class */ (function (_super) {
__extends(DayGridView, _super);
function DayGridView() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.buildDayTable = core.memoize(buildDayTable);
return _this;
}
DayGridView.prototype.render = function (props, context) {
_super.prototype.render.call(this, props, context); // will call _renderSkeleton/_unrenderSkeleton
var dateProfile = this.props.dateProfile;
var dayTable = this.dayTable =
this.buildDayTable(dateProfile, props.dateProfileGenerator);
if (this.header) {
this.header.receiveProps({
dateProfile: dateProfile,
dates: dayTable.headerDates,
datesRepDistinctDays: dayTable.rowCnt === 1,
renderIntroHtml: this.renderHeadIntroHtml
}, context);
}
this.simpleDayGrid.receiveProps({
dateProfile: dateProfile,
dayTable: dayTable,
businessHours: props.businessHours,
dateSelection: props.dateSelection,
eventStore: props.eventStore,
eventUiBases: props.eventUiBases,
eventSelection: props.eventSelection,
eventDrag: props.eventDrag,
eventResize: props.eventResize,
isRigid: this.hasRigidRows(),
nextDayThreshold: this.context.nextDayThreshold
}, context);
};
DayGridView.prototype._renderSkeleton = function (context) {
_super.prototype._renderSkeleton.call(this, context);
if (context.options.columnHeader) {
this.header = new core.DayHeader(this.el.querySelector('.fc-head-container'));
}
this.simpleDayGrid = new SimpleDayGrid(this.dayGrid);
};
DayGridView.prototype._unrenderSkeleton = function () {
_super.prototype._unrenderSkeleton.call(this);
if (this.header) {
this.header.destroy();
}
this.simpleDayGrid.destroy();
};
return DayGridView;
}(AbstractDayGridView));
function buildDayTable(dateProfile, dateProfileGenerator) {
var daySeries = new core.DaySeries(dateProfile.renderRange, dateProfileGenerator);
return new core.DayTable(daySeries, /year|month|week/.test(dateProfile.currentRangeUnit));
}
var main = core.createPlugin({
defaultView: 'dayGridMonth',
views: {
dayGrid: DayGridView,
dayGridDay: {
type: 'dayGrid',
duration: { days: 1 }
},
dayGridWeek: {
type: 'dayGrid',
duration: { weeks: 1 }
},
dayGridMonth: {
type: 'dayGrid',
duration: { months: 1 },
monthMode: true,
fixedWeekCount: true
}
}
});
exports.AbstractDayGridView = AbstractDayGridView;
exports.DayBgRow = DayBgRow;
exports.DayGrid = DayGrid;
exports.DayGridSlicer = DayGridSlicer;
exports.DayGridView = DayGridView;
exports.SimpleDayGrid = SimpleDayGrid;
exports.buildBasicDayTable = buildDayTable;
exports.default = main;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
gpl-3.0
|
google-code/async-msgcomp
|
android/mctest/src/com/saville/mctest/McTest.java
|
2219
|
/*
* Copyright 2008 Wink Saville
*
* 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 com.saville.mctest;
import android.os.Bundle;
import com.saville.debug.Log;
import com.saville.msgcomp.*;
import com.saville.mc.*;
import com.saville.testclient.*;
public class McTest extends McActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle, "McTest");
setContentView(R.layout.main);
int srvrDstId = lookup("TestHmcServer");
if (srvrDstId >= 0) {
Msg msg;
Log.print("McTest: onCreate; send a msg to TestHmcServer");
msg = getMsg();
msg.dstId = srvrDstId;
msg.dstSubId = 0;
msg.guid = 0;
msg.cmd = 0 | McConst.NOISY;
sendMsg(msg);
Log.print("McTest: onCreate; Start McTestClient");
new TestClient("TestClient");
int clientDstId = lookup("TestClient");
if (clientDstId >= 0) {
msg = getMsg();
msg.dstId = clientDstId;
msg.dstSubId = 0;
msg.guid = 0;
msg.cmd = 0;
msg.arg1 = 5; // Count
msg.arg2 = srvrDstId; // ServerDstId
msg.arg3 = 0 | McConst.NOISY; // ServerCmd
sendMsg(msg);
} else {
Log.print("McTest: could not find 'McTestClient'");
}
} else {
Log.print("McTest: could not find 'TestHmcServer'");
}
Log.print("McTest: onCreate; X");
}
public void processMsg(Msg msg) {
}
}
|
gpl-3.0
|
biboudis/SensorAdapterForOGCSOS1.0.0
|
src/adapter/Sensor.java
|
1020
|
/*******************************************************************************
* Copyright (c) 2012 IDIRA project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Aggelos Biboudis - initial API and implementation
******************************************************************************/
package adapter;
/**
* @author Aggelos Biboudis
* Describes the operations that a sensor can perform. This interface is
* relevant to the sensor values retrieval and the method followed is driven
* by the implementor.
*/
public interface Sensor {
/**
* Starts the sensor.
*/
void start();
/**
* Stops the sensor.
*/
void stop();
/**
* @return A boolean value indicating if the sensor can retrieve values currently.
*/
boolean isReady();
}
|
gpl-3.0
|
PentagramPro/OrbitalDefender
|
Assets/Src/SaveLoad/ObjectSerializer.cs
|
5382
|
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.18408
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ObjectSerializer
{
static BindingFlags getFieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
static ClassSerializer defaultSerializer = new ClassSerializer();
static Dictionary<Type,ClassSerializer> serializers = new Dictionary<Type, ClassSerializer>()
{
{typeof(Transform),new TransformSerializer()},
{typeof(Rigidbody2D),new Rigidbody2DSerializer()},
{typeof(Animator),new AnimatorSerializer()}
};
class ClassSerializer{
public virtual void Save(StringWriterEx str, object obj)
{
Type t = obj.GetType();
var fields= t.GetFields(getFieldFlags).Where(f=>f.GetCustomAttributes(typeof(StoreThis),true).Length>0).ToArray();
str.WriteLine(fields.Length);
//Debug.Log(" > Class has "+fields.Length+" fields");
foreach(FieldInfo f in fields)
{
str.WriteLine(f.Name);
str.WriteLine(StoreBase.SaveField(f,obj));
}
}
public virtual void Load(StringReaderEx str, object obj)
{
Type t = obj.GetType();
var fields= t.GetFields(getFieldFlags).Where(f=>f.GetCustomAttributes(typeof(StoreThis),true).Length>0).ToArray();
int len = str.ReadLineInt();
if(fields.Length!=len)
throw new UnityException("Incorrect save file");
for(int i=0;i<len;i++)
{
string fieldName = str.ReadLine();
string fieldData = str.ReadLine();
//Debug.Log(" > Loading field "+fieldName);
FieldInfo finfo = fields.Where(f=>f.Name==fieldName).First();
if(finfo==null)
continue;
StoreBase.LoadField(finfo,obj,fieldData);
}
}
}
class TransformSerializer : ClassSerializer
{
public override void Save(StringWriterEx str, object obj)
{
Transform tr = obj as Transform;
str.WriteLine(tr.position);
str.WriteLine(tr.localScale);
str.WriteLine(tr.rotation.eulerAngles);
}
public override void Load(StringReaderEx str, object obj)
{
Transform tr = obj as Transform;
tr.position = str.ReadLineVector3();
tr.localScale = str.ReadLineVector3();
tr.rotation = Quaternion.Euler(str.ReadLineVector3());
}
}
class Rigidbody2DSerializer : ClassSerializer
{
public override void Save(StringWriterEx str, object obj)
{
Rigidbody2D r = obj as Rigidbody2D;
str.WriteLine(r.isKinematic);
str.WriteLine(r.gravityScale);
}
public override void Load(StringReaderEx str, object obj)
{
Rigidbody2D r = obj as Rigidbody2D;
r.isKinematic = str.ReadLineBool();
r.gravityScale = str.ReadLineFloat();
}
}
class AnimatorSerializer : ClassSerializer
{
public override void Save(StringWriterEx str, object obj)
{
Animator a = obj as Animator;
AnimatorStateInfo s = a.GetCurrentAnimatorStateInfo(0);
str.WriteLine(s.nameHash);
str.WriteLine(s.normalizedTime);
}
public override void Load(StringReaderEx str, object obj)
{
Animator a = obj as Animator;
a.Play(str.ReadLineInt(),0,str.ReadLineFloat());
}
}
static ClassSerializer GetClassSerializer(Component c)
{
Type t = c.GetType();
if(serializers.ContainsKey(t))
return serializers[t];
return defaultSerializer;
}
public static void StoreComponent(StringWriterEx str, Component c)
{
GetClassSerializer(c).Save(str,c);
}
public static void LoadComponent(StringReaderEx str, Component c)
{
GetClassSerializer(c).Load(str,c);
Type t = c.GetType();
MethodInfo[] methods = t.GetMethods(getFieldFlags).Where(i => (i.GetCustomAttributes(typeof(ExecuteAfterLoad),true).Length>0)).ToArray();
foreach(MethodInfo m in methods)
{
m.Invoke(c,null);
}
}
public static void StoreObject(StringWriterEx str, GameObject obj)
{
Component[] components = obj.GetComponents<Component>();
str.WriteLine(obj.activeSelf);
str.WriteLine(components.Length);
foreach(Component c in components)
{
str.WriteLine(c.GetType().Name);
if(c is Behaviour)
str.WriteLine((c as Behaviour).enabled);
else
str.WriteLine("true");
StoreComponent(str,c);
//StoreClass<Component>(str,c);
}
}
public static void LoadObject(StringReaderEx str, GameObject obj)
{
Component[] components = obj.GetComponents<Component>();
Dictionary<string,Component> byName = new Dictionary<string, Component>();
foreach(Component c in components)
byName[c.GetType().Name] = c;
bool isActive = str.ReadLineBool();
int len = str.ReadLineInt();
for(int i=0;i<len;i++)
{
string name = str.ReadLine();
bool enabled = str.ReadLineBool();
if(byName.ContainsKey(name))
{
Component c = byName[name];
if(c is Behaviour)
(c as Behaviour).enabled = enabled;
LoadComponent(str,c);
//LoadClass<Component>(str,c);
}
}
obj.SetActive(isActive);
}
}
|
gpl-3.0
|
karek314/lisk-network-stats
|
lib/collection.js
|
6385
|
var _ = require('lodash');
var Blockchain = require('./history');
var Node = require('./node');
var Collection = function Collection(externalAPI)
{
this._items = [];
this._blockchain = new Blockchain();
this._askedForHistory = false;
this._askedForHistoryTime = 0;
this._debounced = null;
this._externalAPI = externalAPI;
this._highestBlock = 0;
return this;
}
Collection.prototype.setupSockets = function()
{
this._externalAPI.on('connection', function (spark)
{
this._externalAPI.on('latestBlock', function (data)
{
spark.emit('latestBlock', {
number: this._highestBlock
});
});
});
}
Collection.prototype.add = function(data, callback)
{
var node = this.getNodeOrNew({ id : data.id }, data);
node.setInfo(data, callback);
}
Collection.prototype.update = function(id, stats, callback)
{
var node = this.getNode({ id: id });
if (!node)
{
callback('Node not found', null);
}
else
{
// this._blockchain.clean(this.getBestBlockFromItems());
var block = this._blockchain.add(stats.block, id, node.trusted);
if (!block)
{
callback('Block data wrong', null);
}
else
{
var propagationHistory = this._blockchain.getNodePropagation(id);
stats.block.arrived = block.block.arrived;
stats.block.received = block.block.received;
stats.block.propagation = block.block.propagation;
node.setStats(stats, propagationHistory, callback);
}
}
}
Collection.prototype.addBlock = function(id, stats, callback)
{
var node = this.getNode({ id: id });
if (!node)
{
callback('Node not found', null);
}
else
{
// this._blockchain.clean(this.getBestBlockFromItems());
var block = this._blockchain.add(stats, id, node.trusted);
if (!block)
{
callback('Block undefined', null);
}
else
{
var propagationHistory = this._blockchain.getNodePropagation(id);
stats.arrived = block.block.arrived;
stats.received = block.block.received;
stats.propagation = block.block.propagation;
if(block.block.number > this._highestBlock)
{
this._highestBlock = block.block.number;
this._externalAPI.write({
action:"lastBlock",
number: this._highestBlock
});
}
node.setBlock(stats, propagationHistory, callback);
}
}
}
Collection.prototype.updatePending = function(id, stats, callback)
{
var node = this.getNode({ id: id });
if (!node)
return false;
node.setPending(stats, callback);
}
Collection.prototype.updateStats = function(id, stats, callback)
{
var node = this.getNode({ id: id });
if (!node)
{
callback('Node not found', null);
}
else
{
node.setBasicStats(stats, callback);
}
}
// TODO: Async series
Collection.prototype.addHistory = function(id, blocks, callback)
{
var node = this.getNode({ id: id });
if (!node)
{
callback('Node not found', null)
}
else
{
blocks = blocks.reverse();
// this._blockchain.clean(this.getBestBlockFromItems());
for (var i = 0; i <= blocks.length - 1; i++)
{
this._blockchain.add(blocks[i], id, node.trusted, true);
};
this.getCharts();
}
this.askedForHistory(false);
}
Collection.prototype.updateLatency = function(id, latency, callback)
{
var node = this.getNode({ id: id });
if (!node)
return false;
node.setLatency(latency, callback);
}
Collection.prototype.inactive = function(id, callback)
{
var node = this.getNode({ spark: id });
if (!node)
{
callback('Node not found', null);
}
else
{
node.setState(false);
callback(null, node.getStats());
}
}
Collection.prototype.getIndex = function(search)
{
return _.findIndex(this._items, search);
}
Collection.prototype.getNode = function(search)
{
var index = this.getIndex(search);
if(index >= 0)
return this._items[index];
return false;
}
Collection.prototype.getNodeByIndex = function(index)
{
if(this._items[index])
return this._items[index];
return false;
}
Collection.prototype.getIndexOrNew = function(search, data)
{
var index = this.getIndex(search);
return (index >= 0 ? index : this._items.push(new Node(data)) - 1);
}
Collection.prototype.getNodeOrNew = function(search, data)
{
return this.getNodeByIndex(this.getIndexOrNew(search, data));
}
Collection.prototype.all = function()
{
this.removeOldNodes();
return this._items;
}
Collection.prototype.removeOldNodes = function()
{
var deleteList = []
for(var i = this._items.length - 1; i >= 0; i--)
{
if( this._items[i].isInactiveAndOld() )
{
deleteList.push(i);
}
}
if(deleteList.length > 0)
{
for(var i = 0; i < deleteList.length; i++)
{
this._items.splice(deleteList[i], 1);
}
}
}
Collection.prototype.blockPropagationChart = function()
{
return this._blockchain.getBlockPropagation();
}
Collection.prototype.getUncleCount = function()
{
return this._blockchain.getUncleCount();
}
Collection.prototype.setChartsCallback = function(callback)
{
this._blockchain.setCallback(callback);
}
Collection.prototype.getCharts = function()
{
this.getChartsDebounced();
}
Collection.prototype.getChartsDebounced = function()
{
var self = this;
if( this._debounced === null) {
this._debounced = _.debounce(function(){
self._blockchain.getCharts();
}, 1000, {
leading: false,
maxWait: 5000,
trailing: true
});
}
this._debounced();
}
Collection.prototype.getHistory = function()
{
return this._blockchain;
}
Collection.prototype.getBestBlockFromItems = function()
{
return Math.max(this._blockchain.bestBlockNumber(), _.result(_.max(this._items, function(item) {
// return ( !item.trusted ? 0 : item.stats.block.number );
return ( item.stats.block.number );
}), 'stats.block.number', 0));
}
Collection.prototype.canNodeUpdate = function(id) {
var node = this.getNode({id: id});
if(!node){
return false;
}
if(node.canUpdate()){
var diff = this._blockchain.bestBlockNumber() - node.getBlockNumber();
return (diff <= 0);
}
return false;
}
Collection.prototype.requiresUpdate = function(id) {
return ( this.canNodeUpdate(id) && this._blockchain.requiresUpdate() && (!this._askedForHistory || _.now() - this._askedForHistoryTime > 2*60*1000) );
}
Collection.prototype.askedForHistory = function(set)
{
if( !_.isUndefined(set) )
{
this._askedForHistory = set;
if(set === true)
{
this._askedForHistoryTime = _.now();
}
}
return (this._askedForHistory || _.now() - this._askedForHistoryTime < 2*60*1000);
}
module.exports = Collection;
|
gpl-3.0
|
Token3/books-source-code
|
algorithm/src/main/java/divideandconquer/MergeSort.java
|
1371
|
package divideandconquer;
/**
* Created by ZHEN on 16/7/20.
*
* <p>Time Complexity is O(nlogn)
*/
public class MergeSort {
final int[] arrays = {
49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15,
35, 25, 53, 51
};
public MergeSort() {
sort(arrays, 0, arrays.length - 1);
for (int num : arrays) {
System.out.print(num + " ");
}
}
public void sort(int[] data, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
// sort left array
sort(data, left, middle);
// sort right array
sort(data, middle + 1, right);
// merge two arrays
merge(data, left, middle, right);
}
}
public void merge(int[] data, int left, int middle, int right) {
int[] tmpArray = new int[data.length];
int start = left;
int tmp = left;
int tmpMiddle = middle + 1;
while (left <= middle && tmpMiddle <= right) {
if (data[left] <= data[tmpMiddle]) {
tmpArray[tmp++] = data[left++];
} else {
tmpArray[tmp++] = data[tmpMiddle++];
}
}
while (left <= middle) {
tmpArray[tmp++] = data[left++];
}
while (tmpMiddle <= right) {
tmpArray[tmp++] = data[tmpMiddle++];
}
while (start <= right) {
data[start] = tmpArray[start++];
}
}
}
|
gpl-3.0
|
jfruitet/referentiel_scales
|
mod/referentiel/format/csv/format.php
|
148160
|
<?php
// Based on default.php, included by ../import.php
class rformat_csv extends rformat_default {
var $sep = ";";
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return $this->guillemets(str_replace($cherche, $remplace, $texte));
}
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return true;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
global $USER;
$xp = "#Moodle Referentiel CSV Export;latin1;".referentiel_get_user_info($USER->id)."\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Turns item into an xml segment
* @param item object
* @return string xml segment
*/
function write_item( $item ) {
global $CFG;
// initial string;
$expout = "";
// add comment
//
if ($item){
// DEBUG
// echo "<br />\n";
// print_r($item);
$code = $item->code_item;
$description_item = $this->purge_sep($item->description_item);
$ref_referentiel = $item->ref_referentiel;
$ref_competence = $item->ref_competence;
$type_item = $item->type_item;
$poids_item = $item->poids_item;
$num_item = $item->num_item;
$empreinte_item = $item->empreinte_item;
$expout .= stripslashes($this->output_codage_caractere($code)).";".stripslashes($this->output_codage_caractere($description_item)).";".$this->output_codage_caractere($type_item).";$poids_item;$num_item;$empreinte_item\n";
}
return $expout;
}
/**
* Turns competence into an xml segment
* @param competence object
* @return string xml segment
*/
function write_competence( $competence ) {
global $CFG;
// initial string;
$expout = "";
// add comment
if ($competence){
$code_competence = $competence->code_competence;
$description_competence = $this->purge_sep($competence->description_competence);
$ref_domaine = $competence->ref_domaine;
$num_competence = $competence->num_competence;
$nb_item_competences = $competence->nb_item_competences;
// MODIF 2012/03/08
$type_competence = trim($competence->type_competence);
$seuil_competence = trim($competence->seuil_competence);
// MODIF 2012/03/26
$minima_competence = $competence->minima_competence;
$expout .= stripslashes($this->output_codage_caractere($code_competence)).";".stripslashes($this->output_codage_caractere($description_competence)).";$num_competence;$nb_item_competences;$type_competence;$seuil_competence;$minima_competence\n";
// ITEM
$compteur_item=0;
$records_items = referentiel_get_item_competences($competence->id);
if ($records_items){
// DEBUG
// echo "<br/>DEBUG :: ITEMS <br />\n";
// print_r($records_items);
$expout .= "#code_item;description_item;type_item;poids_item;num_item;empreinte_item\n";
foreach ($records_items as $record_i){
// DEBUG
// echo "<br/>DEBUG :: ITEM <br />\n";
// print_r($record_i);
$expout .= $this->write_item( $record_i );
}
}
}
return $expout;
}
/**
* Turns domaine into an xml segment
* @param domaine object
* @return string xml segment
*/
function write_domaine( $domaine ) {
global $CFG;
// initial string;
$expout = "";
// add comment
if ($domaine){
$code_domaine = $domaine->code_domaine;
$description_domaine = $this->purge_sep($domaine->description_domaine);
$ref_referentiel = $domaine->ref_referentiel;
$num_domaine = $domaine->num_domaine;
$nb_competences = $domaine->nb_competences;
// MODIF 2012/03/08
$type_domaine = $domaine->type_domaine;
$seuil_domaine = $domaine->seuil_domaine;
// MODIF 2012/03/26
$minima_domaine = $domaine->minima_domaine;
$expout .= stripslashes($this->output_codage_caractere($code_domaine)).";".stripslashes($this->output_codage_caractere($description_domaine)).";$num_domaine;$nb_competences;$type_domaine;$seuil_domaine;$minima_domaine\n";
// LISTE DES COMPETENCES DE CE DOMAINE
$compteur_competence=0;
$records_competences = referentiel_get_competences($domaine->id);
if ($records_competences){
// DEBUG
// echo "<br/>DEBUG :: COMPETENCES <br />\n";
// print_r($records_competences);
foreach ($records_competences as $record_c){
$expout .= "#code_competence;description_competence;num_competence;nb_item_competences;type_competence;seuil_competence;minima_competence\n";
$expout .= $this->write_competence( $record_c );
}
}
}
return $expout;
}
/**
* Turns protocol into an xml segment
* @param protocol object
* @return string xml segment
*/
// MODIF JF 2012/03/09
function write_protocol( $protocole ){
global $CFG;
// initial string;
$expout = "";
// add comment
// $expout .= "\n\n<!-- protocole: $protocole->id -->\n";
//
if ($protocole){
$id = $protocole->id;
$ref_occurrence = $protocole->ref_occurrence;
$seuil_referentiel = $protocole->seuil_referentiel;
$minima_referentiel = $protocole->minima_referentiel;
$l_domaines_oblig = $this->purge_sep(trim($protocole->l_domaines_oblig));
$l_seuils_domaines = $this->purge_sep(trim($protocole->l_seuils_domaines));
$l_minimas_domaines = $this->purge_sep(trim($protocole->l_minimas_domaines));
$l_competences_oblig = $this->purge_sep(trim($protocole->l_competences_oblig));
$l_seuils_competences = $this->purge_sep(trim($protocole->l_seuils_competences));
$l_minimas_competences = $this->purge_sep(trim($protocole->l_minimas_competences));
$l_items_oblig = $this->purge_sep(trim($protocole->l_items_oblig));
$timemodified = $protocole->timemodified;
$actif = $protocole->actif;
$commentaire = $this->purge_sep(trim($protocole->commentaire));
$expout .= $seuil_referentiel.";".$minima_referentiel
.";".stripslashes($this->output_codage_caractere($l_domaines_oblig))
.";".stripslashes($this->output_codage_caractere($l_seuils_domaines))
.";".stripslashes($this->output_codage_caractere($l_minimas_domaines))
.";".stripslashes($this->output_codage_caractere($l_competences_oblig))
.";".stripslashes($this->output_codage_caractere($l_seuils_competences))
.";".stripslashes($this->output_codage_caractere($l_minimas_competences))
.";".stripslashes($this->output_codage_caractere($l_items_oblig))
.";".$timemodified
.";".$actif
.";".stripslashes($this->output_codage_caractere($commentaire))."\n";
}
return $expout;
}
/**
* Turns referentiel into an xml segment
* @param competence object
* @return string xml segment
*/
function write_referentiel() {
global $CFG;
// initial string;
$expout = "";
// add header
$expout .= "#code_referentiel;nom_referentiel;description_referentiel;url_referentiel;date_creation;nb_domaines;seuil_certificat;liste_codes_competences;liste_empreintes;logo_referentiel;minima_certificat\n";
if ($this->rreferentiel){
$id = $this->rreferentiel->id;
$name = $this->rreferentiel->name;
$code_referentiel = $this->rreferentiel->code_referentiel;
$description_referentiel = $this->purge_sep($this->rreferentiel->description_referentiel);
$url_referentiel = $this->rreferentiel->url_referentiel;
$seuil_certificat = $this->rreferentiel->seuil_certificat;
$minima_certificat = $this->rreferentiel->minima_certificat;
$timemodified = $this->rreferentiel->timemodified;
$nb_domaines = $this->rreferentiel->nb_domaines;
$liste_codes_competence = $this->rreferentiel->liste_codes_competence;
$local = $this->rreferentiel->local;
$liste_empreintes_competence = $this->rreferentiel->liste_empreintes_competence;
$logo_referentiel = $this->rreferentiel->logo_referentiel;
// PAS DE LOGO ICI
// $expout .= stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($name)).";".$this->output_codage_caractere($description_referentiel).";$url_referentiel;$timemodified;$nb_domaines;$seuil_certificat;".stripslashes($this->output_codage_caractere($liste_codes_competence)).";".stripslashes($this->output_codage_caractere($liste_empreintes_competence)).";".$logo_referentiel."\n";
$expout .= stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($name)).";".$this->output_codage_caractere($description_referentiel).";$url_referentiel;".referentiel_timestamp_date_special($timemodified).";$nb_domaines;$seuil_certificat;".stripslashes($this->output_codage_caractere($liste_codes_competence)).";".stripslashes($this->output_codage_caractere($liste_empreintes_competence)).";$minima_certificat\n";
// DOMAINES
if (isset($this->rreferentiel->id) && ($this->rreferentiel->id>0)){
// MODIF JF 2012/03/09
// PROTOCOLE
if (!empty($this->rreferentiel->id)){
if ($record_protocol=referentiel_get_protocol($this->rreferentiel->id)){
$expout .= "#protocole_seuil;protocole_minima;l_domaines_oblig;l_seuils_domaines;l_minimas_domaines;l_competences_oblig;l_seuils_competences;l_minimas_competences;l_items_oblig;timemodified;actif;commentaire\n";
$expout .= $this->write_protocol( $record_protocol );
}
}
// LISTE DES DOMAINES
$compteur_domaine=0;
$records_domaine = referentiel_get_domaines($this->rreferentiel->id);
if ($records_domaine){
// afficher
// DEBUG
// echo "<br/>DEBUG ::<br />\n";
// print_r($records_domaine);
foreach ($records_domaine as $record_d){
// DEBUG
// echo "<br/>DEBUG ::<br />\n";
// print_r($records_domaine);
$expout .= "#code_domaine;description_domaine;num_domaine;nb_competences;type_domaine;seuil_domaine;minima_domaine\n";
$expout .= $this->write_domaine( $record_d );
}
}
}
}
return $expout;
}
/***************************************************************************
// IMPORT FUNCTIONS START HERE
***************************************************************************/
/**
* @param array referentiel array from xml tree
* @return object import_referentiel object
* modifie la base de donnees
*/
function importation_referentiel_possible(){
// selon les parametres soit cree une nouvelle instance
// soit modifie une instance courante de referentiel
global $CFG;
if (!isset($this->action) || (isset($this->action) && ($this->action!="selectreferentiel") && ($this->action!="importreferentiel"))){
if (!(isset($this->course->id) && ($this->course->id>0))
||
!(isset($this->rreferentiel->id) && ($this->rreferentiel->id>0))
||
!(isset($this->coursemodule->id) && ($this->coursemodule->id>0))
){
$this->error( get_string( 'incompletedata', 'referentiel' ) );
return false;
}
}
else if (isset($this->action) && ($this->action=="selectreferentiel")){
if (!(isset($this->course->id) && ($this->course->id>0))){
$this->error( get_string( 'incompletedata', 'referentiel' ) );
return false;
}
}
else if (isset($this->action) && ($this->action=="importreferentiel")){
if (!(isset($this->course->id) && ($this->course->id>0))){
$this->error( get_string( 'incompletedata', 'referentiel' ) );
return false;
}
}
return true;
}
/**
* @param array referentiel array from xml tree
* @return object import_referentiel object
* modifie la base de donnees
*/
function import_referentiel( $lines ) {
// recupere le tableau de lignes
// selon les parametres soit cree une nouvelle instance
// soit modifie une instance courante de referentiel
global $SESSION;
global $USER;
global $CFG;
if (!$this->importation_referentiel_possible()){
exit;
}
// initialiser les variables
// id du nouveau referentiel si celui ci doit être cree
$new_referentiel_id=0;
$auteur="";
$l_id_referentiel = "id_referentiel";
$l_code_referentiel = "code_referentiel";
$l_description_referentiel = "description_referentiel";
$l_date_creation = "date_creation";
$l_nb_domaine = "nb_domaine";
$l_seuil_certification = "seuil_certificat";
$l_local = "local";
$l_name = "name";
$l_url_referentiel = "url_referentiel";
$l_liste_competences= "liste_competences";
$l_liste_empreintes= "liste_empreintes";
$l_logo= "logo_referentiel";
$ok_referentiel_charge=false;
// MODIF JF 2012/03/09
$ok_protocole_charge=false;
$ok_domaine_charge=false;
$ok_competence_charge=false;
$ok_item_charge=false;
$risque_ecrasement=false;
// get some error strings
$error_noname = get_string( 'xmlimportnoname', 'referentiel' );
$error_nocode = get_string( 'xmlimportnocode', 'referentiel' );
$error_override = get_string( 'overriderisk', 'referentiel' );
// DEBUT
// Decodage
$line = 0;
// TRAITER LA LIGNE D'ENTETE
$nbl=count($lines);
if ($nbl>0){ // premiere ligne entete fichier csv
// echo "<br />DEBUG :: forme/csv/format.php :: 424\n";
// echo "<br />LIGNE $line --------------<br />\n".$lines[$line]."<br />\n";
// "#Moodle Referentiel CSV Export;latin1;Prénom NOM\n";
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
$line++;
if (substr($lines[$line],0,1)=='#'){
// labels
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted - ignoring\n");
}
}
if (isset($fields[1]) && ($fields[1]!="")){
$this->table_caractere_input=trim($fields[1]);
}
$auteur=trim($fields[2]);
}
}
else{
$this->error("ERROR : CSV File incorrect\n");
}
// echo "<br />DEBUG :: 991 : $this->table_caractere_input\n";
if ($nbl>1){ // deuxieme ligne : entete referentiel
// echo "<br />$line : ".$lines[$line]."\n";
// #code_referentiel;name;description_referentiel;url_referentiel;date_creation;
// nb_domaines;seuil_certification;liste_competences
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
}
if (substr($lines[$line],0,1)=='#'){
// labels
$l_code_referentiel = trim($fields[0]);
$l_name = trim($fields[1]);
$l_description_referentiel = trim($fields[2]);
if (isset($fields[3]))
$l_url_referentiel = trim($fields[3]);
else
$l_url_referentiel = "";
if (isset($fields[4]))
$l_date_creation = trim($fields[4]);
else
$l_date_creation = "";
if (isset($fields[5]))
$l_nb_domaines = trim($fields[5]);
else
$l_nb_domaines = "";
if (isset($fields[6]))
$l_seuil_certificat = trim($fields[6]);
else
$l_seuil_certificat = "";
if (isset($fields[7]))
$l_liste_competences = trim($fields[7]);
else
$l_liste_competences = "";
if (isset($fields[8]))
$l_liste_empreintes = trim($fields[8]);
else
$l_liste_empreintes = "";
if (isset($fields[9]))
$l_logo = trim($fields[9]);
else
$l_logo = "";
// MODIF JF 2012/03/26
if (isset($fields[10]))
$l_minima_certificat = trim($fields[10]);
else
$l_minima_certificat = "";
}
else{
// data : referentiel
$code_referentiel = $this->input_codage_caractere(trim($fields[0]));
$name = $this->input_codage_caractere(trim($fields[1]));
$description_referentiel = $this->input_codage_caractere(trim($fields[2]));
if (isset($fields[3]))
$url_referentiel = trim($fields[3]);
else
$url_referentiel = "";
if (isset($fields[4]))
$date_creation = trim($fields[4]);
else
$date_creation = "";
if (isset($fields[5]))
$nb_domaines = trim($fields[5]);
else
$nb_domaines = "";
if (isset($fields[6]))
$seuil_certificat = trim($fields[6]);
else
$seuil_certificat = 0.0;
if (isset($fields[7]))
$liste_competences = $this->input_codage_caractere(trim($fields[7]));
else
$liste_competences = "";
if (isset($fields[8]))
$liste_empreintes = $this->input_codage_caractere(trim($fields[8]));
else
$liste_empreintes = "";
if (isset($fields[9]))
$logo_referentiel = trim($fields[9]);
else
$logo_referentiel = "";
// MODIF JF 2012/03/26
if (isset($fields[10]))
$minima_certificat = trim($fields[10]);
else
$minima_certificat = 0;
$ok_referentiel_charge=true;
}
$line++;
}
// maintenant les données indispensables
while (($line<$nbl) && ($ok_referentiel_charge==false)){ // data : referentiel
// echo "<br />$line : ".$lines[$line]."\n";
// #referentiel_id;code_referentiel;description_referentiel;date_creation;
// nb_domaines;seuil_certificat;local;name;url_referentiel;liste_competences
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
continue;
}
// DEBUG
// echo "<br />DEBUG : ./mod/refrentiel/format/csv/format.php :: 560<br >\n";
// print_r($fields);
// data : referentiel
$code_referentiel = $this->input_codage_caractere(trim($fields[0]));
$name = $this->input_codage_caractere(trim($fields[1]));
$description_referentiel = $this->input_codage_caractere(trim($fields[2]));
if (isset($fields[3]))
$url_referentiel = trim($fields[3]);
else
$url_referentiel = "";
if (isset($fields[4]))
$date_creation = trim($fields[4]);
else
$date_creation = "";
if (isset($fields[5]))
$nb_domaines = trim($fields[5]);
else
$nb_domaines = "";
if (isset($fields[6]))
$seuil_certificat = trim($fields[6]);
else
$seuil_certificat = 0.0;
if (isset($fields[7]))
$liste_competences= $this->input_codage_caractere(trim($fields[7]));
else
$liste_competences= "";
if (isset($fields[8]))
$liste_empreintes = $this->input_codage_caractere(trim($fields[8]));
else
$liste_empreintes = "";
if (isset($fields[9]))
$logo_referentiel = trim($fields[9]);
else
$logo_referentiel = "";
// MODIF JF 2012/03/26
if (isset($fields[10]))
$minima_certificat = trim($fields[10]);
else
$minima_certificat = 0;
$ok_referentiel_charge=true;
$line++;
}
if (!$ok_referentiel_charge){
$this->error( get_string( 'incompletedata', 'referentiel' ) );
}
// this routine initialises the import object
$re = $this->defaultreferentiel();
$re->name=str_replace("'", " ",$name);
// $re->name=addslashes($name);
$re->code_referentiel=$code_referentiel;
$re->description_referentiel=str_replace("'", "`",$description_referentiel);
// $re->description_referentiel=addslashes($description_referentiel);
$re->url_referentiel=$url_referentiel;
$re->seuil_certificat=$seuil_certificat;
$re->minima_certificat=$minima_certificat;
$re->timemodified = $date_creation;
$re->nb_domaines=$nb_domaines;
$re->liste_codes_competence=$liste_competences;
$re->liste_empreintes_competence=$liste_empreintes;
$re->logo_referentiel=$logo_referentiel;
/*
// GROS BUG
if ($id_referentiel!=""){
$re->id=$id_referentiel;
}
*/
$re->id=0;
// DEBUG
// print_r($re);
// RISQUE ECRASEMENT ?
$risque_ecrasement = false; //
if (($this->rreferentiel) && ($this->rreferentiel->id>0)){ // charger le referentiel associé à l'instance
$this->rreferentiel = referentiel_get_referentiel_referentiel($this->rreferentiel->id);
if ($this->rreferentiel){
$risque_ecrasement = (($this->rreferentiel->name==$re->name) && ($this->rreferentiel->code_referentiel==$re->code_referentiel));
}
}
// SI OUI arrêter
if ($risque_ecrasement==true){
if ($this->override!=1){
$this->error($error_override);
}
else {
// le referentiel courant est remplace
$new_referentiel_id=$this->rreferentiel->id;
$re->id=$new_referentiel_id;
}
}
$re->export_process = false;
$re->import_process = true;
// le referentiel est toujours place dans le cours local d'appel
$re->course = $this->course->id;
$risque_ecrasement=false;
if (!isset($this->action) || ($this->action!="importreferentiel")){
// importer dans le cours courant en remplacement du referentiel courant
// Verifier si ecrasement referentiel local
if (isset($re->name) && ($re->name!="")
&&
isset($re->code_referentiel) && ($re->code_referentiel!="")
&&
isset($re->id) && ($re->id>0)
&&
isset($re->course) && ($re->course>0))
{
// sauvegarder ?
if ($this->course->id==$re->course){
if (
(isset($this->rreferentiel->id) && ($this->rreferentiel->id==$re->id))
||
(
(isset($this->rreferentiel->name) && ($this->rreferentiel->name==$re->name))
&&
(isset($this->rreferentiel->code_referentiel) && ($this->rreferentiel->code_referentiel==$re->code_referentiel))
)
)
{
$risque_ecrasement=true;
}
}
}
}
// DEBUG
/*
if ($risque_ecrasement)
echo "<br />DEBUG : 607 : Risque d'ecrasement N:$this->newinstance O:$this->override\n";
else
echo "<br />DEBUG : 607 : Pas de risque d'ecrasement N:$this->newinstance O:$this->override\n";
*/
if (($risque_ecrasement==false) || ($this->newinstance==1)) {
// Enregistrer dans la base comme un nouveau referentiel du cours courant
// DEBUG
// echo "<br />DEBUG csv/format.php ligne 704<br />\n";
// print_object($re);
// exit;
$new_referentiel_id=referentiel_add_referentiel($re); // retourne un id de la table refrentiel_referentiel
$this->setReferentielId($new_referentiel_id);
}
else if (($risque_ecrasement==true) && ($this->override==1)) {
// Enregistrer dans la base en remplaçant la version courante (update)
// NE FAUDRAIT IL PAS SUPPRIMER LE REFERENTIEL AVANT DE LA RECHARGER ?
$re->instance=$this->rreferentiel->id;
$re->referentiel_id=$this->rreferentiel->id;
// DEBUG
// echo "<br />DEBUG csv/format.php ligne 638<br />MISE A JOUR : ".$r->rreferentiel_id."\n";
$ok=referentiel_update_referentiel($re); // retourne un id de la table referentiel_referentiel
$new_referentiel_id=$this->rreferentiel->id;
}
else {
// ni nouvelle instance ni recouvrement
$this->error("ERREUR 2 ".$error_override );
return false;
}
if (isset($new_referentiel_id) && ($new_referentiel_id>0)){
// IMPORTER LE RESTE DU REFERENTIEL
$dindex=0;
$cindex=0;
$iindex=0;
$re->domaines = array();
$new_domaine_id=0;
$new_competence_id=0;
$numero_domaine=0; // compteur pour suppleer le numero si non importe
$numero_competence=0;
$numero_item=0;
$num_domaine=0;
$num_competence=0;
$type_domaine=0;
$seuil_domaine=0.0;
$type_competence=0;
$seuil_competence=0.0;
$minima_domaine=0.0;
$minima_competence=0;
$num_item=0;
$is="";
$pindex=0;
$is_protocole = false;
$ok_protocole_charge=false;
$nbprotocoles=0;
$is_domaine=false;
$is_competence=false;
$is_item=false;
$mode="add";
while ($line<$nbl) {
// echo "<br />DEBUG 652 :: <br />".$lines[$line]."\n";
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
if (count($fields) < 2 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
continue;
}
// print_r($fields);
// Label ou data ?
// echo "<br />".substr($fields[0],0,1)."\n";
if (substr($fields[0],0,1)=='#'){
// labels
// on s'en sert pour construire l'arbre
$is=trim($fields[0]);
$is_protocole=false;
$is_domaine=false;
$is_competence=false;
$is_item=false;
switch($is){
case '#protocole_seuil' :
// #protocole_seuil;l_domaines_oblig;l_seuils_domaines;l_competences_oblig;l_seuils_competences;l_items_oblig;timemodified;actif;commentaire
$is_protocole=true;
break;
case '#code_domaine' :
// #code_domaine;description_domaine;num_domaine;nb_competences;type_domaine;seuil_domaine
$is_domaine=true;
break;
case '#code_competence' :
// #code_competence;description_competence;num_competence;nb_item_competences;type_competence;seuil_competence
$is_competence=true;
break;
case '#code_item' :
// #code_item;description_item;type_item;poids_item;num_item
$is_item=true;
break;
default :
$this->error("ERROR : CSV File incorrect line number:".$line."\n");
break;
}
}
else if (isset($is) && ($is!="")){
// data
switch($is){
// MODIF JF 2012/03/09
case '#protocole_seuil' :
// Protocole
// data
$seuil_referentiel = trim($fields[0]);
$minima_referentiel = trim($fields[1]);
$l_domaines_oblig=addslashes($this->input_codage_caractere(trim($fields[2])));
$l_seuils_domaines=addslashes($this->input_codage_caractere(trim($fields[3])));
$l_minimas_domaines=addslashes($this->input_codage_caractere(trim($fields[4])));
$l_competences_oblig=addslashes($this->input_codage_caractere(trim($fields[5])));
$l_seuils_competences=addslashes($this->input_codage_caractere(trim($fields[6])));
$l_minimas_competences=addslashes($this->input_codage_caractere(trim($fields[7])));
$l_items_oblig=addslashes($this->input_codage_caractere(trim($fields[8])));
$timemodified = trim($fields[9]);
$actif = trim($fields[10]);
$commentaire=addslashes($this->input_codage_caractere(trim($fields[11])));
// Creer un enregistrement
$new_protocole = $this->defaultprotocole();
// sauvegarder dans la base
// remplacer l'id du referentiel importe par l'id du referentiel cree
// trafiquer les donnees pour appeler la fonction ad hoc
$new_protocole->ref_occurrence=$new_referentiel_id;
// $new_protocole->id=$this->getpath( $protocole, array('#','p_id',0,'#'), '', false, '');
// $new_protocole->ref_occurrence;
$new_protocole->seuil_referentiel=$seuil_referentiel;
$new_protocole->minima_referentiel=$minima_referentiel;
// A recreer a partir des domaines et competences pourr eviter incoherences
// La suite initialise en chargeant les domaines / compétences / items
// $new_protocole->l_domaines_oblig=$l_competences_oblig;
// $new_protocole->l_seuils_domaines= $l_seuils_domaines;
// $new_protocole->l_competences_oblig=$l_competences_oblig;
// $new_protocole->l_seuils_competences=$l_seuils_competences;
// $new_protocole->l_minimas_competences=$l_minimas_competences;
// $new_protocole->l_items_oblig= $l_items_oblig;
$new_protocole->timemodified=$timemodified;
$new_protocole->actif=$actif;
$new_protocole->commentaire=$commentaire;
// sauvegarder dans la base
// remplacer l'id du referentiel importe par l'id du referentiel cree
// trafiquer les donnees pour appeler la fonction ad hoc
$new_protocole->ref_occurrence=$new_referentiel_id;
// DEBUG
// echo "<br />DEBUG ./format/csv/format.php :: 710<br />\n";
// print_object($new_protocole);
if (referentiel_add_protocol($new_protocole)){
$nbprotocoles++;
}
// enregistrer
$pindex++;
$re->protocoles[$pindex]=$new_protocole;
$ok_protocole_charge=true;
break;
case '#code_domaine' :
// $code_domaine;$description_domaine;$num_domaine;$nb_competences
// Domaines
// data
$code_domaine = addslashes($this->input_codage_caractere(trim($fields[0])));
$description_domaine = addslashes($this->input_codage_caractere(trim($fields[1])));
$num_domaine = trim($fields[2]);
$nb_competences = trim($fields[3]);
if (isset($fields[4])){
$type_domaine = trim($fields[4]);
}
else{
$type_domaine = 0;
}
if (isset($fields[5])){
$seuil_domaine = trim($fields[5]);
}
else{
$seuil_domaine = 0;
}
if (isset($fields[6])){
$minima_domaine = trim($fields[6]);
}
else{
$minima_domaine = 0;
}
if ($code_domaine!=""){
// Creer un domaine
$numero_domaine++;
$new_domaine = array();
$new_domaine = $this->defaultdomaine();
$new_domaine->code_domaine=$code_domaine;
if ($description_domaine!="")
$new_domaine->description_domaine = $description_domaine;
if ($num_domaine!="")
$new_domaine->num_domaine=$num_domaine;
else
$new_domaine->num_domaine=$numero_domaine;
if ($nb_competences!="")
$new_domaine->nb_competences=$nb_competences;
else
$new_domaine->nb_competences=0;
if ($type_domaine!="")
$new_domaine->type_domaine=$type_domaine;
else
$new_domaine->type_domaine=0;
if ($seuil_domaine!="")
$new_domaine->seuil_domaine=$seuil_domaine;
else
$new_domaine->seuil_domaine=0.0;
if ($minima_domaine!="")
$new_domaine->minima_domaine=$minima_domaine;
else
$new_domaine->minima_domaine=0;
$new_domaine->ref_referentiel=$new_referentiel_id;
// sauvegarder dans la base
// remplacer l'id du referentiel importe par l'id du referentiel cree
// trafiquer les donnees pour appeler la fonction ad hoc
$new_domaine->ref_referentiel=$new_referentiel_id;
$new_domaine->instance=$new_referentiel_id; // pour que ca marche
$new_domaine->new_code_domaine=$new_domaine->code_domaine;
$new_domaine->new_description_domaine=$new_domaine->description_domaine;
$new_domaine->new_num_domaine=$new_domaine->num_domaine;
$new_domaine->new_nb_competences=$new_domaine->num_domaine;
$new_domaine->new_type_domaine=$new_domaine->type_domaine;
$new_domaine->new_seuil_domaine=$new_domaine->seuil_domaine;
$new_domaine->new_minima_domaine=$new_domaine->minima_domaine;
$new_domaine_id=referentiel_add_domaine($new_domaine);
if (isset($new_domaine_id) && ($new_domaine_id>0)){
$new_domaine->id=$new_domaine_id;
}
else{
$new_domaine->id=0;
}
// enregistrer
$dindex++;
$re->domaines[$dindex]=$new_domaine;
$cindex=0;
$re->domaines[$dindex]->competences=array();
$numero_competence=0;
$ok_domaine_charge=true;
}
else{
$ok_domaine_charge=false;
}
break;
case '#code_competence' :
// $competence_id;$code_competence;$description_competence;$ref_domaine;
// $num_competence;$nb_item_competences
$code_competence = addslashes($this->input_codage_caractere(trim($fields[0])));
$description_competence = addslashes($this->input_codage_caractere(trim($fields[1])));
$num_competence = trim($fields[2]);
$nb_item_competences = trim($fields[3]);
if (isset($fields[4])){
$type_competence = trim($fields[4]);
}
else{
$type_competence = 0;
}
if (isset($fields[5])){
$seuil_competence = trim($fields[5]);
}
else{
$seuil_competence = 0;
}
if (isset($fields[6])){
$minima_competence = trim($fields[6]);
}
else{
$minima_competence = 0;
}
if (($code_competence!="") && ($ok_domaine_charge) && ($new_domaine_id>0)){
// Creer une competence
$new_competence_id=0;
$numero_competence++;
$new_competence = array();
$new_competence = $this->defaultcompetence();
$new_competence->id=0;
$new_competence->code_competence=$code_competence;
if ($description_competence!="")
$new_competence->description_competence = $description_competence;
if ($num_competence!="")
$new_competence->num_competence=$num_competence;
else
$new_competence->num_competence=$numero_competence;
if ($nb_item_competences!="")
$new_competence->nb_item_competences=$nb_item_competences;
else
$new_competence->nb_item_competences=0;
if ($type_competence!="")
$new_competence->type_competence=$type_competence;
else
$new_competence->type_competence=0;
if ($seuil_competence!="")
$new_competence->seuil_competence=$seuil_competence;
else
$new_competence->seuil_competence=0.0;
if ($minima_competence!="")
$new_competence->minima_competence=$minima_competence;
else
$new_competence->minima_competence=0;
if (isset($new_domaine_id) && ($new_domaine_id>0)){
$new_competence->ref_domaine=$new_domaine_id;
}
else{
$new_competence->ref_domaine=0;
}
// sauvegarder dans la base
// remplacer l'id du referentiel importe par l'id du referentiel cree
$new_competence->ref_domaine=$new_domaine_id;
// trafiquer les donnees pour appeler la fonction ad hoc
$new_competence->instance=$new_referentiel_id; // pour que ca marche
$new_competence->new_code_competence=$new_competence->code_competence;
$new_competence->new_description_competence=$new_competence->description_competence;
$new_competence->new_ref_domaine=$new_domaine_id;
$new_competence->new_num_competence=$new_competence->num_competence;
$new_competence->new_nb_item_competences=$new_competence->nb_item_competences;
$new_competence->new_type_competence=$new_competence->type_competence;
$new_competence->new_seuil_competence=$new_competence->seuil_competence;
$new_competence->new_minima_competence=$new_competence->minima_competence;
// creation
$new_competence_id=referentiel_add_competence($new_competence);
$new_competence->id=$new_competence_id;
// enregistrer
$cindex++;
$re->domaines[$dindex]->competences[$cindex]=$new_competence;
$iindex=0; // nouveaux items à suivre
$re->domaines[$dindex]->competences[$cindex]->items=array();
$numero_item=0;
$ok_competence_charge=true;
}
else{
$ok_competence_charge=false;
}
break;
case '#code_item' :
// $code_item;$description_item;$type_item;$poids_item;$num_item;$empreinte_item
$code_item = $this->input_codage_caractere(addslashes(trim($fields[0])));
$description_item = $this->input_codage_caractere(addslashes(trim($fields[1])));
$type_item = $this->input_codage_caractere(addslashes(trim($fields[2])));
$poids_item = trim($fields[3]);
$num_item = trim($fields[4]);
if (isset($fields[5]) && (trim($fields[5])!="")){
$empreinte_item = trim($fields[5]);
}
else{
$empreinte_item = "1";
}
if (($code_item!="") && ($ok_competence_charge) && ($new_competence_id>0)){
// Creer un domaine
$numero_item++;
$new_item = array();
$new_item = $this->defaultitem();
$new_item->code_item=$code_item;
if ($description_item!="")
$new_item->description_item = $description_item;
$new_item->ref_referentiel=$new_referentiel_id;
$new_item->ref_competence=$new_competence_id;
$new_item->type_item=$type_item;
$new_item->poids_item=$poids_item;
if ($num_item!="")
$new_item->num_item=$num_item;
else
$new_item->num_item=$numero_item;
$new_item->empreinte_item=$empreinte_item;
// sauvegarder dans la base
// remplacer l'id du referentiel importe par l'id du referentiel cree
$new_item->ref_referentiel=$new_referentiel_id;
$new_item->ref_competence=$new_competence_id;
// trafiquer les donnees pour pouvoir appeler la fonction ad hoc
$new_item->instance=$new_item->ref_referentiel;
$new_item->new_ref_competence=$new_item->ref_competence;
$new_item->new_code_item=$new_item->code_item;
$new_item->new_description_item=$new_item->description_item;
$new_item->new_num_item=$new_item->num_item;
$new_item->new_type_item=$new_item->type_item;
$new_item->new_poids_item=$new_item->poids_item;
$new_item->new_empreinte_item=$new_item->empreinte_item;
// creer
$new_item_id=referentiel_add_item($new_item);
$new_item->id=$new_item_id;
$iindex++;
$re->domaines[$dindex]->competences[$cindex]->items[$iindex]=$new_item;
$ok_item_charge=true;
}
else{
$ok_item_charge=false;
}
break;
default :
$this->error("ERROR : CSV File incorrect line number:".$line."\n");
break;
}
}
// that's all folks
$line++;
} // end of while loop
if ($mode=="add"){
// rien de special ici ?
}
return $re;
}
return false;
}
/**
* parse the array of lines into an array of questions
* this *could* burn memory - but it won't happen that much
* so fingers crossed!
* @param array lines array of lines from the input file
* @return array (of objects) question objects
*/
function read_import_referentiel($lines) {
// we just need it as one array
$re=$this->import_referentiel($lines);
return $re;
}
}
/** ******************************************
EXPORT ACTIVITES
*/
// ACTIVITES : export des activites
class aformat_csv extends aformat_default {
// NON SUPPORTE POUR LE FORMAT CSV
var $sep = ";";
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return $this->guillemets(str_replace($cherche, $remplace, $texte));
}
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return false;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
$xp = "Moodle Referentiel CSV Export\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Include an image encoded in base 64
* @param string imagepath The location of the image file
* @return string xml code segment
*/
function writeimage( $imagepath ) {
global $CFG;
if (empty($imagepath)) {
return '';
}
$courseid = $this->course->id;
if (!$binary = file_get_contents( "{$CFG->dataroot}/$courseid/$imagepath" )) {
return '';
}
$content = " <image_base64>\n".addslashes(base64_encode( $binary ))."\n".
"\n </image_base64>\n";
return $content;
}
/**
* generates <text></text> tags, processing raw text therein
* @param int ilev the current indent level
* @param boolean short stick it on one line
* @return string formatted text
*/
function write_ligne( $raw, $sep="/", $nmaxcar=80) {
// insere un saut de ligne apres le 80 caractere
$nbcar=strlen($raw);
if ($nbcar>$nmaxcar){
$s1=substr( $raw,0,$nmaxcar);
$pos1=strrpos($s1,$sep);
if ($pos1>0){
$s1=substr( $raw,0,$pos1);
$s2=substr( $raw,$pos1+1);
}
else {
$s1=substr( $raw,0,$nmaxcar);
$s2=substr( $raw,$nmaxcar);
}
return $s1." ".$s2;
}
else{
return $raw;
}
}
/**
* Turns document into an xml segment
* @param document object
* @return string xml segment
*/
function write_document( $document ) {
global $CFG;
// initial string;
$expout = "";
if ($document){
$id_document = $document->id ;
$type_document = trim($document->type_document);
$description_document = $this->purge_sep($document->description_document);
$url_document = $document->url_document;
$ref_activite = $document->ref_activite;
$timestamp = $document->timestamp;
$expout .= "$id_document;".stripslashes($this->output_codage_caractere($type_document)).";".stripslashes($this->output_codage_caractere($description_document)).";$url_document;$ref_activite;$timestamp\n";
}
return $expout;
}
/**
* Turns activite into an xml segment
* @param activite object
* @return string xml segment
*/
function write_activite( $activite ) {
global $CFG;
// initial string;
$expout = "";
// add comment
if ($activite){
// DEBUG
// echo "<br />\n";
// print_r($activite);
$id_activite = $activite->id;
$type_activite = $this->purge_sep(strip_tags($activite->type_activite));
$description_activite = $this->purge_sep(strip_tags($activite->description_activite));
$competences_activite = trim($activite->competences_activite);
$commentaire_activite = $this->purge_sep($activite->commentaire_activite);
$ref_instance = $activite->ref_instance;
$ref_referentiel = $activite->ref_referentiel;
$ref_course = $activite->ref_course;
$userid = trim($activite->userid);
$teacherid = $activite->teacherid;
$date_creation = $activite->date_creation;
$date_modif_student = $activite->date_modif_student;
$date_modif = $activite->date_modif;
$approved = $activite->approved;
$firstname=referentiel_get_user_prenom($activite->userid);
$lastname=referentiel_get_user_nom($activite->userid);
$teacher_firstname=referentiel_get_user_prenom($activite->teacherid);
$teacher_lastname=referentiel_get_user_nom($activite->teacherid);
$expout .= "#id_activite;type_activite;description_activite;competences_activite;commentaire_activite;ref_instance;ref_referentiel;ref_course;userid;lastname;firstname;teacherid;teacher_lastname;teacher_firstname;date_creation;date_modif_student;date_modif;approved\n";
$expout .= "$id_activite;".stripslashes($this->output_codage_caractere($type_activite)).";".stripslashes($this->output_codage_caractere($description_activite)).";".stripslashes($this->output_codage_caractere($competences_activite)).";".stripslashes($this->output_codage_caractere($commentaire_activite)).";$ref_instance;$ref_referentiel;$ref_course;$userid;".stripslashes($this->output_codage_caractere($lastname)).";".stripslashes($this->output_codage_caractere($firstname)).";".$teacherid;"".stripslashes($this->output_codage_caractere($lastname)).";".stripslashes($this->output_codage_caractere($firstname)).";".referentiel_timestamp_date_special($date_creation).";".referentiel_timestamp_date_special($date_modif_student).";".referentiel_timestamp_date_special($date_modif).";$approved\n";
// DOCUMENTS
$records_documents = referentiel_get_documents($activite->id);
if ($records_documents){
$expout .= "#id_document;type_document;description_document;url_document;ref_activite;timestamp\n";
foreach ($records_documents as $record_d){
$expout .= $this->write_document( $record_d );
}
}
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
function write_liste_activites() {
global $CFG;
// initial string;
$expout = "";
//
if ($this->ireferentiel){
$id = $this->ireferentiel->id;
$name = $this->purge_sep($this->ireferentiel->name);
$description_instance = $this->purge_sep($this->ireferentiel->description_instance);
$label_domaine = trim($this->ireferentiel->label_domaine);
$label_competence = trim($this->ireferentiel->label_competence);
$label_item = trim($this->ireferentiel->label_item);
$date_instance = $this->ireferentiel->date_instance;
$course = $this->ireferentiel->course;
$ref_referentiel = $this->ireferentiel->ref_referentiel;
$visible = $this->ireferentiel->visible;
// $expout .= "#Instance de referentiel : $this->ireferentiel->name\n";
$expout .= "#id_instance;name;description_instance;label_domaine;label_competence;label_item;date_instance;course;ref_referentiel;visible\n";
$expout .= "$id;".stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($description_instance)).";".stripslashes($this->output_codage_caractere($label_domaine)).";".stripslashes($this->output_codage_caractere($label_competence)).";".stripslashes($this->output_codage_caractere($label_item)).";".referentiel_timestamp_date_special($date_instance).";$course;$ref_referentiel;$visible\n";
// ACTIVITES
if (isset($this->ireferentiel->id) && ($this->ireferentiel->id>0)){
$records_activites = referentiel_get_activites_instance($this->ireferentiel->id);
if ($records_activites){
foreach ($records_activites as $record_a){
// DEBUG
// print_r($record_a);
// echo "<br />\n";
$expout .= $this->write_activite( $record_a );
}
}
}
}
return $expout;
}
}
// ##########################################################################################################
// *************************************
// CERTIFICATS : export des certificats
// *************************************
class cformat_csv extends cformat_default {
var $sep = ";";
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return $this->guillemets(str_replace($cherche, $remplace, $texte));
}
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return true;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
$xp = "#Moodle Certification CSV Export;latin1;\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Include an image encoded in base 64
* @param string imagepath The location of the image file
* @return string xml code segment
*/
function writeimage( $imagepath ) {
global $CFG;
if (empty($imagepath)) {
return '';
}
$courseid = $this->course->id;
if (!$binary = file_get_contents( "{$CFG->dataroot}/$courseid/$imagepath" )) {
return '';
}
$content = " <image_base64>\n".addslashes(base64_encode( $binary ))."\n".
"\n </image_base64>\n";
return $content;
}
/**
* generates <text></text> tags, processing raw text therein
* @param int ilev the current indent level
* @param boolean short stick it on one line
* @return string formatted text
*/
function write_ligne( $raw, $sep="/", $nmaxcar=80) {
// insere un saut de ligne apres le 80 caracter
$nbcar=strlen($raw);
if ($nbcar>$nmaxcar){
$s1=substr( $raw,0,$nmaxcar);
$pos1=strrpos($s1,$sep);
if ($pos1>0){
$s1=substr( $raw,0,$pos1);
$s2=substr( $raw,$pos1+1);
}
else {
$s1=substr( $raw,0,$nmaxcar);
$s2=substr( $raw,$nmaxcar);
}
return $s1." ".$s2;
}
else{
return $raw;
}
}
function write_item( $item ) {
global $CFG;
// initial string;
$expout = "";
// add comment
// $expout .= "\nitem: $item->id\n";
// $expout .= "id;code_item;description_item;ref_referentiel;ref_competence;type_item;poids_item;num_item\n";
//
if ($item){
// DEBUG
// echo "<br />\n";
// print_r($item);
$id_item = $item->id;
$code = $item->code_item;
$description_item = $this->purge_sep($item->description_item);
$ref_referentiel = $item->ref_referentiel;
$ref_competence = $item->ref_competence;
$type_item = $item->type_item;
$poids_item = $item->poids_item;
$num_item = $item->num_item;
$empreinte_item = $item->empreinte_item;
$expout .= "$id_item;".stripslashes($this->output_codage_caractere($code)).";".stripslashes($this->output_codage_caractere($description_item)).";".$this->output_codage_caractere($type_item).";$poids_item;$num_item;$empreinte_item\n";
}
return $expout;
}
/**
* Turns competence into an xml segment
* @param competence object
* @return string xml segment
*/
function write_competence( $competence ) {
global $CFG;
// initial string;
$expout = "";
// add comment
// $expout .= "\ncompetence: $competence->id\n";
if ($competence){
$id_competence = $competence->id;
$code = $competence->code_competence;
$description_competence = $this->purge_sep($competence->description_competence);
$ref_domaine = $competence->ref_domaine;
$num_competence = $competence->num_competence;
$nb_item_competences = $competence->nb_item_competences;
$expout .= "$id_competence;".stripslashes($this->output_codage_caractere($code)).";".stripslashes($this->output_codage_caractere($description_competence)).";$ref_domaine;$num_competence;$nb_item_competences\n";
// ITEM
$compteur_item=0;
$records_items = referentiel_get_item_competences($competence->id);
if ($records_items){
// DEBUG
// echo "<br/>DEBUG :: ITEMS <br />\n";
// print_r($records_items);
$expout .= "#id_item;code_item;description_item;ref_referentiel;ref_competence;type_item;poids_item;num_item\n";
foreach ($records_items as $record_i){
// DEBUG
// echo "<br/>DEBUG :: ITEM <br />\n";
// print_r($record_i);
$expout .= $this->write_item( $record_i );
}
}
}
return $expout;
}
/**
* Turns domaine into an xml segment
* @param domaine object
* @return string xml segment
*/
function write_domaine( $domaine ) {
global $CFG;
// initial string;
$expout = "#domaine_id;code;description;ref_referentiel;num_domaine;nb_competences\n";
// add comment
if ($domaine){
$code = $domaine->code_domaine;
$description_domaine = $this->purge_sep($domaine->description_domaine);
$ref_referentiel = $domaine->ref_referentiel;
$num_domaine = $domaine->num_domaine;
$nb_competences = $domaine->nb_competences;
$expout .= stripslashes($this->output_codage_caractere($code)).";".stripslashes($this->output_codage_caractere($description_domaine)).";$ref_referentiel;$num_domaine;$nb_competences\n";
// LISTE DES COMPETENCES DE CE DOMAINE
$compteur_competence=0;
$records_competences = referentiel_get_competences($domaine->id);
if ($records_competences){
// DEBUG
// echo "<br/>DEBUG :: COMPETENCES <br />\n";
// print_r($records_competences);
foreach ($records_competences as $record_c){
$expout .= "#id_competence;code_competence;description_competence;num_competence;nb_item_competences\n";
$expout .= $this->write_competence( $record_c );
}
}
}
return $expout;
}
/**
* Turns referentiel into an xml segment
* @param competence object
* @return string xml segment
*/
function write_referentiel() {
global $CFG;
// initial string;
$expout ="";
if ($this->rreferentiel){
$id = $this->rreferentiel->id;
$name = $this->rreferentiel->name;
$code_referentiel = $this->rreferentiel->code_referentiel;
$description_referentiel = $this->purge_sep($this->rreferentiel->description_referentiel);
$url_referentiel = $this->rreferentiel->url_referentiel;
$seuil_certificat = $this->rreferentiel->seuil_certificat;
$timemodified = $this->rreferentiel->timemodified;
$nb_domaines = $this->rreferentiel->nb_domaines;
$liste_codes_competence = $this->rreferentiel->liste_codes_competence;
$liste_empreintes_competence = $this->rreferentiel->liste_empreintes_competence;
$local = $this->rreferentiel->local;
// $expout = "#Referentiel : ".$this->rreferentiel->id." : ".stripslashes($this->output_codage_caractere($this->rreferentiel->name))."\n";
// add header
if ($this->format_condense==1){
$expout .= "#name;code_referentiel;description_referentiel;\n";
$expout .= stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($description_referentiel))."\n";
$expout .= "#user_id;login;num_etudiant;NOM;Prenom;";
$expout .= $this->liste_codes_competences($this->rreferentiel->id);
if ($this->export_pedagos){
$expout .= "promotion;formation;pedagogie;composante;num_groupe;commentaire;date_cloture";
}
$expout .= "\n";
}
else if ($this->format_condense==2){
$expout .= "#name;code_referentiel;description_referentiel;\n";
$expout .= stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($description_referentiel))."\n";
}
else{
$expout .= "#id_referentiel;name;code_referentiel;description_referentiel;url_referentiel;seuil_certificat;timemodified;nb_domaines;liste_codes_competences;liste_empreintes_competences;local\n";
$expout .= "$id;".stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($description_referentiel)).";$url_referentiel;$seuil_certificat;".referentiel_timestamp_date_special($timemodified).";$nb_domaines;".stripslashes($this->output_codage_caractere($liste_codes_competence)).";".stripslashes($this->output_codage_caractere($liste_empreintes_competence)).";$local\n";
// DOMAINES
if (isset($this->rreferentiel->id) && ($this->rreferentiel->id>0)){
// LISTE DES DOMAINES
$compteur_domaine=0;
$records_domaine = referentiel_get_domaines($this->rreferentiel->id);
if ($records_domaine){
// afficher
// DEBUG
// echo "<br/>DEBUG ::<br />\n";
// print_r($records_domaine);
foreach ($records_domaine as $record_d){
// DEBUG
// echo "<br/>DEBUG ::<br />\n";
// print_r($records_domaine);
$expout .= $this->write_domaine( $record_d );
}
}
}
}
}
return $expout;
}
function write_etablissement( $record ) {
// initial string;
$expout = "";
// add comment
// $expout .= "\netablissement: $record->id\n";
if ($record){
// $expout .= "#id_etablissement;num_etablissement;nom_etablissement;dresse_etablissement\n";
$id = trim( $record->id );
$num_etablissement = trim( $record->num_etablissement);
$nom_etablissement = $this->purge_sep($record->nom_etablissement);
$adresse_etablissement = $this->purge_sep($record->adresse_etablissement);
$expout .= "$id;".stripslashes($this->output_codage_caractere($num_etablissement)).";".stripslashes($this->output_codage_caractere($nom_etablissement)).";".stripslashes($this->output_codage_caractere($adresse_etablissement))."\n";
}
return $expout;
}
function write_liste_etablissements() {
global $CFG;
// initial string;
$expout = "";
// ETABLISSEMENTS
$records_all_etablissements = referentiel_get_etablissements();
if ($records_all_etablissements){
$expout .= "#id_etablissement;num_etablissement;nom_etablissement;adresse_etablissement\n";
foreach ($records_all_etablissements as $record){
if ($record){
$expout.=$this->write_etablissement($record);
}
}
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
/**
*
* @param referentiel instanceobject
* @return string xml segment
*/
function write_certificat( $record ) {
global $CFG;
// initial string;
$expout = "";
// $expout .= "\ncertificat : $record->id\n";
// USER
if ($record){
//$expout .= "#id_etudiant;user_id;login;num_etudiant;NOM;Prenom;ddn_etudiant;lieu_naissance;departement_naissance;adresse_etudiant;ref_etablissement;id_certificat;commentaire_certificat;competences_certificat;decision_jury;date_decision;ref_referentiel;verrou;valide;evaluation\n";
$ok_etudiant=false;
$record_etudiant = referentiel_get_etudiant_user($record->userid);
if (!$record_etudiant){
// creer l'enregistrement car on en a besoin immediatement
if (referentiel_add_etudiant_user($record->userid)){
$record_etudiant = referentiel_get_etudiant_user($record->userid);
}
}
if ($record_etudiant){
$id_etudiant = trim($record_etudiant->id );
$ref_etablissement = trim($record_etudiant->ref_etablissement);
$num_etudiant = trim($record_etudiant->num_etudiant);
$ddn_etudiant = trim($record_etudiant->ddn_etudiant);
$lieu_naissance = $this->purge_sep($record_etudiant->lieu_naissance);
$departement_naissance = $this->purge_sep($record_etudiant->departement_naissance);
$adresse_etudiant = $this->purge_sep($record_etudiant->adresse_etudiant);
$login = trim(referentiel_get_user_login($record->userid));
/*
if ($num_etudiant==$login){
$texte=$num_etudiant;
}
elseif ($num_etudiant==''){
$texte=$login;
}
else{
$texte=$num_etudiant." (".$login.")";
}
*/
if (!$this->format_condense){
$expout .= "$id_etudiant;".$record->userid.";".$this->output_codage_caractere($login).";".$this->output_codage_caractere($num_etudiant).";".stripslashes($this->output_codage_caractere(referentiel_get_user_nom($record->userid))).";".stripslashes($this->output_codage_caractere(referentiel_get_user_prenom($record->userid))).";$ddn_etudiant;".stripslashes($this->output_codage_caractere($lieu_naissance)).";".stripslashes($this->output_codage_caractere($departement_naissance)).";".stripslashes($this->output_codage_caractere($adresse_etudiant)).";$ref_etablissement;";
}
elseif ($this->format_condense==1){
$expout .= $record->userid.";".$this->output_codage_caractere($login).";".$this->output_codage_caractere($num_etudiant).";".stripslashes($this->output_codage_caractere(referentiel_get_user_nom($record->userid))).";".stripslashes($this->output_codage_caractere(referentiel_get_user_prenom($record->userid))).";";
}
elseif ($this->format_condense==2){
$expout .= $this->output_codage_caractere($login).";".$this->output_codage_caractere($num_etudiant).";".stripslashes($this->output_codage_caractere(referentiel_get_user_nom($record->userid))).";".stripslashes($this->output_codage_caractere(referentiel_get_user_prenom($record->userid))).";";
}
$ok_etudiant=true;
}
if ($ok_etudiant==false){
if (!$this->format_condense){
$expout .= ";".$record->userid.";;;;;;;;;;;";
}
else if ($this->format_condense==1){
$expout .= $record->userid.";;;;;";
}
}
// DEBUG
// echo "<br />DEBUG LIGNE 1021<br />\n";
// print_r($this->ireferentiel);
$id = trim( $record->id );
$commentaire_certificat = $this->purge_sep($record->commentaire_certificat);
$synthese_certificat = $this->purge_sep($record->synthese_certificat);
$competences_certificat = trim($record->competences_certificat) ;
$decision_jury = $this->purge_sep($record->decision_jury);
$date_decision = trim($record->date_decision);
$userid = trim( $record->userid);
$teacherid = trim( $record->teacherid);
$ref_referentiel = trim( $record->ref_referentiel);
$verrou = trim( $record->verrou );
$valide = trim( $record->valide );
$evaluation = trim( $record->evaluation );
$synthese_certificat = $this->purge_sep($record->synthese_certificat);
if (!$this->format_condense){
$expout .= "$id;".stripslashes($this->output_codage_caractere($commentaire_certificat)).";".stripslashes($this->output_codage_caractere($synthese_certificat)).";".stripslashes($this->output_codage_caractere($competences_certificat)).";".stripslashes($this->output_codage_caractere($decision_jury)).";".referentiel_timestamp_date_special($date_decision).";$ref_referentiel;$verrou;$valide;$evaluation;$synthese_certificat;";
}
elseif ($this->format_condense==1){
$expout .= $this->certificat_pourcentage($competences_certificat, $this->ref_referentiel);
}
else{
$expout .= stripslashes($this->output_codage_caractere($decision_jury)).";".$this->certificat_items_binaire($competences_certificat, $this->ref_referentiel);
}
// PEDAGOGIES
if ($this->export_pedagos){
// $expout .= "promotion;formation;pedagogie;composante;num_groupe;commentaire;date_cloture";
$rec_pedago=referentiel_get_pedagogie_user($userid, $ref_referentiel);
if ($rec_pedago){
$expout .= stripslashes($this->output_codage_caractere($rec_pedago->promotion)).";".stripslashes($this->output_codage_caractere($rec_pedago->formation)).";".stripslashes($this->output_codage_caractere($rec_pedago->pedagogie)).";".stripslashes($this->output_codage_caractere($rec_pedago->composante)).";".stripslashes($this->output_codage_caractere($rec_pedago->num_groupe)).";".stripslashes($this->output_codage_caractere($rec_pedago->commentaire)).";".stripslashes($this->output_codage_caractere($rec_pedago->date_cloture));
}
}
$expout .= "\n";
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
function write_certification() {
global $CFG;
// initial string;
$expout = "";
//
if ($this->ireferentiel){
$id = $this->ireferentiel->id;
$name = trim($this->ireferentiel->name);
$description_instance = $this->purge_sep($this->ireferentiel->description_instance);
$label_domaine = trim($this->ireferentiel->label_domaine);
$label_competence = trim($this->ireferentiel->label_competence);
$label_item = trim($this->ireferentiel->label_item);
$date_instance = $this->ireferentiel->date_instance;
$course = $this->ireferentiel->course;
$ref_referentiel = $this->ireferentiel->ref_referentiel;
$visible = $this->ireferentiel->visible;
if ($this->format_condense==0){
// $expout .= "#Instance de referentiel : $this->ireferentiel->name\n";
$expout .= "#id_instance;name;description_instance;label_domaine;label_competence;label_item;date_instance;course;ref_referentiel;visible\n";
$expout .= "$id;".stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($description_instance)).";".stripslashes($this->output_codage_caractere($label_domaine)).";".stripslashes($this->output_codage_caractere($label_competence)).";".stripslashes($this->output_codage_caractere($label_item)).";".referentiel_timestamp_date_special($date_instance).";$course;$ref_referentiel;$visible\n";
}
}
if (empty($this->rreferentiel) && (!empty($this->ireferentiel->ref_referentiel) && ($this->ireferentiel->ref_referentiel>0))){
$this->rreferentiel = referentiel_get_referentiel_referentiel($this->ireferentiel->ref_referentiel);
}
if (!empty($this->rreferentiel)){
$expout .= $this->write_referentiel();
if (!$this->records_certificats){
$this->records_certificats = referentiel_get_certificats($this->rreferentiel->id);
}
if ($this->records_certificats){
if (!$this->format_condense){
$expout .= "#id_etudiant;user_id;login;num_etudiant;NOM;Prenom;ddn_etudiant;lieu_naissance;departement_naissance;adresse_etudiant;ref_etablissement;id_certificat;commentaire_certificat;synthese_certificat;competences_certificat;decision_jury;date_decision;ref_referentiel;verrou;valide;evaluation;";
if ($this->export_pedagos){
$expout .= "promotion;formation;pedagogie;composante;num_groupe;commentaire;date_cloture";
}
$expout .= "\n";
}
else if ($this->format_condense==1){
// $expout .= $this->write_liste_etablissements($this->rreferentiel);
// $expout .= "#user_id;login;num_etudiant;NOM;Prenom;\n";
// la suite de l'entete est reportée dans l'affichage du referentiel car il faut aussi afficher les codes des items...
}
else if ($this->format_condense==2){
$expout .= "#login;num_etudiant;NOM;Prenom;decision_jury;";
$expout .= $this->liste_codes_items($this->ref_referentiel);
if ($this->export_pedagos){
$expout .= "promotion;formation;pedagogie;composante;num_groupe;commentaire;date_cloture";
}
$expout .= "\n";
}
foreach ($this->records_certificats as $record){
$expout .= $this->write_certificat( $record );
}
}
}
return $expout;
}
// -------------------
function liste_codes_competences($ref_referentiel){
global $OK_REFERENTIEL_DATA;
// COMPETENCES
global $t_competence; // codes des competences
// affichage
$s='';
if ($ref_referentiel){
if (!isset($OK_REFERENTIEL_DATA) || ($OK_REFERENTIEL_DATA==false) ){
$OK_REFERENTIEL_DATA=referentiel_initialise_data_referentiel($ref_referentiel);
}
if (isset($OK_REFERENTIEL_DATA) && ($OK_REFERENTIEL_DATA==true)){
for ($i=0; $i<count($t_competence); $i++){
$s.=$t_competence[$i].';';
}
}
}
return $s;
}
// -------------------
function liste_codes_items($ref_referentiel){
// retourne la liste des items
// ITEMS
global $t_item_code;
// affichage
$s='';
// donnees globales du referentiel
if ($ref_referentiel){
if (!isset($OK_REFERENTIEL_DATA) || ($OK_REFERENTIEL_DATA==false) ){
$OK_REFERENTIEL_DATA=referentiel_initialise_data_referentiel($ref_referentiel);
}
if (isset($OK_REFERENTIEL_DATA) && ($OK_REFERENTIEL_DATA==true)){
for ($i=0; $i<count($t_item_code); $i++){
$s.=$t_item_code[$i].';';
}
}
}
return $s;
}
// -------------------
function certificat_items_binaire($liste_code, $ref_referentiel){
// retourne les valeur 0/1 pour chaque item de competence
$separateur1='/';
$separateur2=':';
global $OK_REFERENTIEL_DATA;
// ITEMS
global $t_item_code;
global $t_item_coeff; // coefficient poids determine par le modele de calcul (soit poids soit poids / empreinte)
global $t_item_domaine; // index du domaine associé à un item
global $t_item_competence; // index de la competence associée à un item
global $t_item_poids; // poids
global $t_item_empreinte;
global $t_nb_item_domaine;
global $t_nb_item_competence;
$t_certif_item_valeur=array(); // table des nombres d'items valides
// affichage
$s='';
// donnees globales du referentiel
if ($ref_referentiel){
if (!isset($OK_REFERENTIEL_DATA) || ($OK_REFERENTIEL_DATA==false) ){
$OK_REFERENTIEL_DATA=referentiel_initialise_data_referentiel($ref_referentiel);
}
if (isset($OK_REFERENTIEL_DATA) && ($OK_REFERENTIEL_DATA==true)){
// DEBUG
// echo "<br />CODE <br />\n";
// referentiel_affiche_data_referentiel($ref_referentiel, $params);
// recuperer les items valides
$tc=array();
$liste_code=referentiel_purge_dernier_separateur($liste_code, $separateur1);
// DEBUG
// echo "<br />DEBUG :: print_lib_certificat.php :: 917 :: LISTE : $liste_code<br />\n";
if (!empty($liste_code) && ($separateur1!="") && ($separateur2!="")){
$tc = explode ($separateur1, $liste_code);
$i=0;
while ($i<count($tc)){
$t_cc=explode($separateur2, $tc[$i]); // tableau des items valides
if (isset($t_cc[1])){
if (isset($t_item_poids[$i]) && isset($t_item_empreinte[$i])){
if (($t_item_poids[$i]>0) && ($t_item_empreinte[$i]>0)){
// echo "<br />".min($t_cc[1],$t_item_empreinte[$i]);
$t_certif_item_valeur[$i]=min($t_cc[1],$t_item_empreinte[$i]);
// calculer le taux
$coeff=(float)$t_certif_item_valeur[$i] * (float)$t_item_coeff[$i];
// stocker la valeur pour l'item
$t_certif_item_coeff[$i]=$coeff;
}
else{
// echo "<br />".min($t_cc[1],$t_item_empreinte[$i]);
$t_certif_item_valeur[$i]=0.0;
$t_certif_item_coeff[$i]=0.0;
}
}
}
$i++;
}
// ITEMS
/*
for ($i=0; $i<count($t_item_code); $i++){
$s.=$t_item_code[$i].';';
}
$s.="\n";
*/
for ($i=0; $i<count($t_item_coeff); $i++){
if ($t_item_empreinte[$i]){
if ($t_certif_item_valeur[$i]>=$t_item_empreinte[$i]){
$s.='1;';
}
else{
$s.='0;';
}
}
else {
$s.=';';
}
}
}
}
}
return $s;
}
// -------------------
function certificat_pourcentage($liste_code, $ref_referentiel){
// retourne les pourcentages par competence
$separateur1='/';
$separateur2=':';
global $OK_REFERENTIEL_DATA;
global $t_domaine;
global $t_domaine_coeff;
// COMPETENCES
global $t_competence;
global $t_competence_coeff;
// ITEMS
global $t_item_code;
global $t_item_coeff; // coefficient poids determine par le modele de calcul (soit poids soit poids / empreinte)
global $t_item_domaine; // index du domaine associé à un item
global $t_item_competence; // index de la competence associée à un item
global $t_item_poids; // poids
global $t_item_empreinte;
global $t_nb_item_domaine;
global $t_nb_item_competence;
$t_certif_item_valeur=array(); // table des nombres d'items valides
$t_certif_item_coeff=array(); // somme des poids du domaine
$t_certif_competence_poids=array(); // somme des poids de la competence
$t_certif_domaine_poids=array(); // poids certifies
for ($i=0; $i<count($t_item_code); $i++){
$t_certif_item_valeur[$i]=0.0;
$t_certif_item_coeff[$i]=0.0;
}
for ($i=0; $i<count($t_competence); $i++){
$t_certif_competence_poids[$i]=0.0;
}
for ($i=0; $i<count($t_domaine); $i++){
$t_certif_domaine_poids[$i]=0.0;
}
// affichage
$s='';
// donnees globales du referentiel
if ($ref_referentiel){
if (!isset($OK_REFERENTIEL_DATA) || ($OK_REFERENTIEL_DATA==false) ){
$OK_REFERENTIEL_DATA=referentiel_initialise_data_referentiel($ref_referentiel);
}
if (isset($OK_REFERENTIEL_DATA) && ($OK_REFERENTIEL_DATA==true)){
// DEBUG
// echo "<br />CODE <br />\n";
// referentiel_affiche_data_referentiel($ref_referentiel, $params);
// recuperer les items valides
$tc=array();
$liste_code=referentiel_purge_dernier_separateur($liste_code, $separateur1);
// DEBUG
// echo "<br />DEBUG :: print_lib_certificat.php :: 917 :: LISTE : $liste_code<br />\n";
if (!empty($liste_code) && ($separateur1!="") && ($separateur2!="")){
$tc = explode ($separateur1, $liste_code);
for ($i=0; $i<count($t_item_domaine); $i++){
$t_certif_domaine_poids[$i]=0.0;
}
for ($i=0; $i<count($t_item_competence); $i++){
$t_certif_competence_poids[$i]=0.0;
}
$i=0;
while ($i<count($tc)){
$t_cc=explode($separateur2, $tc[$i]); // tableau des items valides
if (isset($t_cc[1])){
if (isset($t_item_poids[$i]) && isset($t_item_empreinte[$i])){
if (($t_item_poids[$i]>0) && ($t_item_empreinte[$i]>0)){
// echo "<br />".min($t_cc[1],$t_item_empreinte[$i]);
$t_certif_item_valeur[$i]=min($t_cc[1],$t_item_empreinte[$i]);
// calculer le taux
$coeff=(float)$t_certif_item_valeur[$i] * (float)$t_item_coeff[$i];
// stocker la valeur pour l'item
$t_certif_item_coeff[$i]=$coeff;
// stocker le taux pour la competence
$t_certif_domaine_poids[$t_item_domaine[$i]]+=$coeff;
// stocker le taux pour le domaine
$t_certif_competence_poids[$t_item_competence[$i]]+=$coeff;
}
else{
// echo "<br />".min($t_cc[1],$t_item_empreinte[$i]);
$t_certif_item_valeur[$i]=0.0;
$t_certif_item_coeff[$i]=0.0;
// $t_certif_domaine_poids[$t_item_domaine[$i]]+=0.0;
// $t_certif_competence_poids[$t_item_competence[$i]]+=0.0;
}
}
}
$i++;
}
/*
for ($i=0; $i<count($t_domaine_coeff); $i++){
if ($t_domaine_coeff[$i]){
$s.=$t_domaine[$i].';';
}
else{
$s.=$t_domaine[$i].';';
}
}
$s.="\n";
for ($i=0; $i<count($t_domaine_coeff); $i++){
if ($t_domaine_coeff[$i]){
$s.=referentiel_pourcentage($t_certif_domaine_poids[$i], $t_domaine_coeff[$i]).'%;';
}
else{
$s.='0%;';
}
}
$s.="\n";
*/
/*
for ($i=0; $i<count($t_competence); $i++){
$s.=$t_competence[$i].';';
}
$s.="\n";
*/
for ($i=0; $i<count($t_competence); $i++){
if ($t_competence_coeff[$i]){
$s.=referentiel_pourcentage($t_certif_competence_poids[$i], $t_competence_coeff[$i]).'%;';
}
else{
$s.='0%;';
}
}
// $s.="\n";
// ITEMS
/*
for ($i=0; $i<count($t_item_code); $i++){
if ($t_item_empreinte[$i]){
if ($t_certif_item_valeur[$i]>=$t_item_empreinte[$i])
$s.=$t_item_code[$i].';';
else
$s.=$t_item_code[$i].';';
}
else{
$s.=';';
}
}
$s.="\n";
for ($i=0; $i<count($t_item_coeff); $i++){
if ($t_item_empreinte[$i]){
if ($t_certif_item_valeur[$i]>=$t_item_empreinte[$i]){
$s.='100%;';
}
else{
$s.=referentiel_pourcentage($t_certif_item_valeur[$i], $t_item_empreinte[$i]).'%;';
}
}
else {
$s.=';';
}
}
$s.="\n";
*/
}
}
}
return $s;
}
/***************************************************************************
// IMPORT FUNCTIONS START HERE
***************************************************************************/
/**
* @param array referentiel array from xml tree
* @return object import_referentiel object
* modifie la base de donnees
*/
function import_certifs( $lines ) {
// recupere le tableau de lignes
// selon les parametres soit cree une nouvelle instance
// soit modifie une instance courante de students
global $SESSION;
global $USER;
global $CFG;
global $DB;
// DEBUG
// print_r($lines);
$code_ref ='';
$t_items=array(); // les codes d'items du referentiel
$in_referentiel=false;
$in_certif=false;
// initialiser les variables
$date_creation="";
// get some error strings
$error_noname = get_string( 'xmlimportnoname', 'referentiel' );
$error_nocode = get_string( 'xmlimportnocode', 'referentiel' );
$error_override = get_string( 'overriderisk', 'referentiel' );
// DEBUT
// Decodage
$line = 0;
// TRAITER LA LIGNE D'ENTETE
$nbl=count($lines);
if ($nbl>0){ // premiere ligne entete fichier csv
// echo "<br />2378:: format/csv :: $line : ".$lines[$line]."\n";
//"#Moodle Referentiel Students CSV Export;latin1;Y:2009m:06d:11\n"
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
// DEBUG
// echo "<br /> DEBUG :: 2325 <br />\n";
// print_r($fields);
$line++;
if (substr($lines[$line],0,1)=='#'){
// labels
/// If a line is incorrectly formatted
if (count($fields) < 2 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted - ignoring\n");
}
}
if (isset($fields[1]) && ($fields[1]!="")){
$this->table_caractere_input=trim($fields[1]);
}
if (isset($fields[2]) && ($fields[2]!="")){
$date_creation=trim($fields[2]);
}
}
}
else{
$this->error("ERROR : CSV File incorrect\n");
}
// echo "<br />DEBUG :: 2348 : $this->table_caractere_input\n";
if ($nbl>1){ // deuxieme ligne : entete certificat
// echo "<br />$line : ".$lines[$line]."\n";
while ($line<$nbl){ // data : referentiel
// #name;code_referentiel;description_referentiel;
//
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
/// If a line is incorrectly formatted
$nbfields= count($fields);
if ($nbfields < 3 ) {
if ( $nbfields > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
}
else{
if (substr($lines[$line],0,1)=='#'){
// labels
$l_s0 = trim($fields[0]);
if ($l_s0=="#name"){
$l_name_ref = trim($fields[0]);
$l_code_ref = trim($fields[1]);
$l_desc_ref = trim($fields[2]);
$in_referentiel=true;
$in_certif=false;
}
else if ($l_s0=="#login"){
// #name;code_referentiel;description_referentiel;
$l_login = trim($fields[0]);
$l_num_etudiant = trim($fields[1]);
$l_nom = trim($fields[2]);
$l_prenom = trim($fields[3]);
$l_decidion_jury = trim($fields[4]);
$i=5;
// On peut ameliorer la robustesse en recherchant si le code appartient au referentiel
while (($i<$nbfields) && (trim($fields[$i]) != 'promotion')){ // items
$t_items[]=trim($fields[$i]);
$i++;
}
$liste_codes_competences='';
for ($j=0; $j<count($t_items); $j++) {
if ($t_items[$j]){
$liste_codes_competences.=$t_items[$j].'/';
}
}
// DEBUG
// echo "<br />DEBUG :: 2395 Liste codes : '$liste_codes_competences'<br />\n";
$in_referentiel=false;
$in_certif=true;
}
}
else{
// data :
if ($in_referentiel==true){ // referentiel
$name_ref = $this->input_codage_caractere(trim($fields[0]));
$code_ref = $this->input_codage_caractere(trim($fields[1]));
$desc_ref = $this->input_codage_caractere(trim($fields[2]));
// DEBUG
// echo "<br />DEBUG :: 2427 :: format/csv ::<br />\n";
// echo ($name_ref, $code_ref, $desc_ref);
}
elseif ($in_certif==true){ // etudiant
$login = trim($fields[0]);
$num_etudiant = $this->input_codage_caractere(trim($fields[1]));
$nom = $this->input_codage_caractere(trim($fields[2]));
$prenom = $this->input_codage_caractere(trim($fields[3]));
$decision = $this->input_codage_caractere(trim($fields[4]));
$t_items_values=array(); // 0 : non valide / 1 : valide $i=5;
$i=5;
while (($i<$nbfields) && (($fields[$i]=='0') || ($fields[$i]=='1'))) { // items
if (($fields[$i]=='0') || ($fields[$i]=='1')){
$t_items_values[]=trim($fields[$i]);
}
$i++;
}
// echo "<br />T_ITEMS_VALUES<br />\n";
// print_r($t_items_values);
$liste_competences='';
for ($i=0; $i<count($t_items_values); $i++) {
$liste_competences.=$t_items[$i].':'.$t_items_values[$i].'/';
}
// rechercher l'id
if ($login!=''){
$user_id=referentiel_get_userid_by_login($login);
}
if (!empty($user_id)){ // utilisateur inscrit
// Verifier referentiel
// DEBUG
// echo "<br />DEBUG :: 2432 CODE_REF : $code_ref<br />Liste competences : '$liste_competences'<br />\n";
// print_object($this->rreferentiel);
if (!empty($this->rreferentiel)
&& ($this->rreferentiel->code_referentiel==$code_ref)
&& ($this->rreferentiel->liste_codes_competence==$liste_codes_competences)){
/*
// this routine initialises the import object
$import_certif = new stdClass();
$import_certif->login=$login;
$import_certif->nom=$nom;
$import_certif->prenom=$prenom;
$import_certif->userid=$user_id;
$import_certif->decision=$decision;
$import_certif->competences_certificat=$liste_competences;
$import_certif->ref_referentiel = $this->rreferentiel->id;
// DEBUG
//echo "<br /> DEBUG ./format/csv :: 2478\n";
//print_object($import_certif);
*/
// sauvegarde dans la base uniquement pour les certificats existants
if ($certificat=$DB->get_record('referentiel_certificat', array("userid"=>$user_id, "ref_referentiel"=>$this->rreferentiel->id))){
$certificat->decision_jury=$decision;
$certificat->verrou=1;
$certificat->valide=1;
// mise à jour simple de la table certificat
$certificat->competences_certificat=$liste_competences;
if (!$DB->update_record("referentiel_certificat", $certificat)){
$this->error("ERROR update certificate");
}
// Creation d'une activité pour les nouvelles compétences
if (!empty($this->import_activity)){
$this->creer_activite_supplementaire($certificat, $liste_competences);
}
}
}
}
}
}
}
$line++;
}
}
return true;
}
/**
* parse the array of lines into an array
* this *could* burn memory - but it won't happen that much
* so fingers crossed!
* @param array lines array of lines from the input file
* @return array of student object
*/
function read_import_certifs($lines) {
// we just need it as one array
return $this->import_certifs($lines);
}
// Creation d'une activité pour les nouvelles compétences
function creer_activite_supplementaire($certificat, $liste_competences){
global $DB;
global $USER;
// calculer le delta
$liste_competences_acquises='';
// $t_values_old=array();
$t_codes_new=array();
$t_values_new=array();
/*
$t_items_old=explode('/', $certificat->competences_certificat);
for ($i=0; $i<count($t_items_old); $i++){
if (!empty($t_items_old[$i])){
// comparer
$value_old=explode(':', $t_items_old[$i]);
if (isset($value_old[1])){
$t_values_old[]=trim($value_old[1]);
}
}
}
*/
$t_items_new=explode('/', $liste_competences);
for ($i=0; $i<count($t_items_new); $i++){
if (!empty($t_items_new[$i])){
// comparer
$value_new=explode(':', $t_items_new[$i]);
if (isset($value_new[0]) && isset($value_new[1])){
$t_codes_new[]=trim($value_new[0]);
$t_values_new[]=trim($value_new[1]);
}
}
}
for ($i=0; $i<count($t_values_new); $i++){
if ($t_values_new[$i]!='0'){
$liste_competences_acquises.= $t_codes_new[$i].'/';
}
}
/*
// comparer
$ok_modif=false;
if (count($t_values_new)==count($t_values_old)){
for ($i=0; $i<count($t_values_new); $i++){
if ($t_values_new[$i]!='0'){
$liste_competences_acquises.=
if ($t_values_old[$i]!=$t_values_new[$i]){
//
if ($t_values_new[$i]
$ok_modif=true;
}
}
}
*/
// creer une activité
$import_activity = new stdClass();
$import_activity->type_activite=get_string('imported_activity_type','referentiel');
$import_activity->description_activite=get_string('imported_activity_description','referentiel');
$import_activity->competences_activite=$liste_competences_acquises;
$import_activity->commentaire_activite=get_string('imported_activity_comment','referentiel', date("Y/m/d H:i:s",time()));
$import_activity->ref_instance=$this->ireferentiel->id;
$import_activity->ref_referentiel=$this->ireferentiel->ref_referentiel;
$import_activity->ref_course=$this->ireferentiel->course;
$import_activity->userid=$certificat->userid;
$import_activity->teacherid=$USER->id;
$import_activity->date_creation=time();
$import_activity->date_modif_student=time();
$import_activity->date_modif=time();
$import_activity->approved=1;
$import_activity->ref_task=0;
$import_activity->mailed=1;
$import_activity->mailnow=0;
// DEBUG
// echo "<br /> DEBUG ./format/csv :: 2583\n";
// print_object($import_activity);
$activite_id= $DB->insert_record("referentiel_activite", $import_activity);
// DEBUG
// echo "ACTIVITE ID / $activite_id<br />";
/*
if (($activite_id>0) && ($import_activity->competences_activite!='')){
// mise a jour du certificat
// referentiel_mise_a_jour_competences_certificat_user('', $import_activity->competences_activite, $import_activity->userid, $activite->ref_referentiel, $import_activity->approved, true, false);
}
*/
}
} // fin de la classe cformat
// ################################################################################################################
// ETUDIANTS : export des etudiants
class eformat_csv extends eformat_default {
var $sep = ";";
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return $this->guillemets(str_replace($cherche, $remplace, $texte));
}
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return true;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
$xp = "#Moodle Referentiel Students CSV Export;latin1;".referentiel_timestamp_date_special(time())."\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Include an image encoded in base 64
* @param string imagepath The location of the image file
* @return string xml code segment
*/
function writeimage( $imagepath ) {
global $CFG;
if (empty($imagepath)) {
return '';
}
$courseid = $this->course->id;
if (!$binary = file_get_contents( "{$CFG->dataroot}/$courseid/$imagepath" )) {
return '';
}
$content = " <image_base64>\n".addslashes(base64_encode( $binary ))."\n".
"\n </image_base64>\n";
return $content;
}
/**
* generates <text></text> tags, processing raw text therein
* @param int ilev the current indent level
* @param boolean short stick it on one line
* @return string formatted text
*/
function write_ligne( $raw, $sep="/", $nmaxcar=80) {
// insere un saut de ligne apres le 80 caracter
$nbcar=strlen($raw);
if ($nbcar>$nmaxcar){
$s1=substr( $raw,0,$nmaxcar);
$pos1=strrpos($s1,$sep);
if ($pos1>0){
$s1=substr( $raw,0,$pos1);
$s2=substr( $raw,$pos1+1);
}
else {
$s1=substr( $raw,0,$nmaxcar);
$s2=substr( $raw,$nmaxcar);
}
return $s1." ".$s2;
}
else{
return $raw;
}
}
function write_etablissement($record) {
// initial string;
$expout = "";
// add comment
// $expout .= "\netablissement: $record->id\n";
if ($record){
//$expout .= "#id_etablissement;num_etablissement;nom_etablissement;adresse_etablissement\n";
$id = trim( $record->id );
$num_etablissement = trim( $record->num_etablissement);
$nom_etablissement = $this->output_codage_caractere($this->purge_sep($record->nom_etablissement));
$adresse_etablissement = $this->output_codage_caractere($this->purge_sep($record->adresse_etablissement));
$logo = trim( $record->logo_etablissement);
$expout .= "$id;".stripslashes($this->output_codage_caractere($num_etablissement)).";$nom_etablissement;$adresse_etablissement\n";
}
return $expout;
}
function write_etudiant( $record ) {
// initial string;
$expout = "";
// add comment
// $expout .= "\netudiant: $record->id -->\n";
if ($record){
$id = trim( $record->id );
$userid = trim( $record->userid );
$ref_etablissement = trim( $record->ref_etablissement);
$num_etudiant = trim( $record->num_etudiant);
$ddn_etudiant = trim( $record->ddn_etudiant);
$lieu_naissance = $this->output_codage_caractere($this->purge_sep($record->lieu_naissance));
$departement_naissance = $this->output_codage_caractere($this->purge_sep($record->departement_naissance));
$adresse_etudiant = $this->output_codage_caractere($this->purge_sep($record->adresse_etudiant));
$login=trim(referentiel_get_user_login($record->userid ));
if ($num_etudiant==$login){
$texte=$num_etudiant;
}
elseif ($num_etudiant==''){
$texte=$login;
}
else{
$texte=$num_etudiant;
}
$expout .= "$id;$userid;$login;".$this->output_codage_caractere(referentiel_get_user_prenom($record->userid)).";".$this->output_codage_caractere(referentiel_get_user_nom($record->userid)).";".$this->output_codage_caractere($texte).";$ddn_etudiant;$lieu_naissance;$departement_naissance;$adresse_etudiant;$ref_etablissement\n";
/*
// Etablissement
$record_etablissement=referentiel_get_etablissement($record->ref_etablissement);
if ($record_etablissement){
$expout .= $this->write_etablissement( $record_etablissement );
}
*/
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
function write_liste_etudiants() {
global $CFG;
// initial string;
$expout = "";
if ($this->ireferentiel){
$id = $this->ireferentiel->id;
$name = $this->output_codage_caractere(trim($this->ireferentiel->name));
$description_instance = $this->output_codage_caractere($this->purge_sep($this->ireferentiel->description_instance));
$label_domaine = $this->output_codage_caractere(trim($this->ireferentiel->label_domaine));
$label_competence = $this->output_codage_caractere(trim($this->ireferentiel->label_competence));
$label_item = $this->output_codage_caractere(trim($this->ireferentiel->label_item));
$date_instance = $this->ireferentiel->date_instance;
$course = $this->ireferentiel->course;
$ref_referentiel = $this->ireferentiel->ref_referentiel;
$visible = $this->ireferentiel->visible;
// $expout .= "Instance de referentiel : $this->ireferentiel->name\n";
// $expout .= "id;name;description_instance;label_domaine;label_competence;label_item;date_instance;course;ref_referentiel;visible\n";
// $expout .= "$id;$name;$description_instance;$label_domaine;$label_competence;$label_item;$date_instance;$course;$ref_referentiel;$visible\n";
if (isset($this->ireferentiel->course) && ($this->ireferentiel->course>0)){
// ETUDIANTS
$records_all_students = referentiel_get_students_course($this->ireferentiel->course);
if ($records_all_students){
$expout .= "#id_etudiant;user_id;login;Prenom;NOM;num_etudiant;ddn_etudiant;lieu_naissance;departement_naissance;adresse_etudiant;ref_etablissement\n";
foreach ($records_all_students as $record){
// USER
if (isset($record->userid) && ($record->userid>0)){
$record_etudiant = referentiel_get_etudiant_user($record->userid);
if ($record_etudiant){
$expout .= $this->write_etudiant( $record_etudiant );
}
}
}
}
}
}
return $expout;
}
function write_liste_etablissements() {
global $CFG;
// initial string;
$expout = "";
// ETABLISSEMENTS
$records_all_etablissements = referentiel_get_etablissements();
if ($records_all_etablissements){
$expout .= "#id_etablissement;num_etablissement;nom_etablissement;adresse_etablissement\n";
foreach ($records_all_etablissements as $record){
if ($record){
$expout.=$this->write_etablissement($record);
}
}
}
return $expout;
}
// IMPORTATION
/***************************************************************************
// IMPORT FUNCTIONS START HERE
***************************************************************************/
/**
* @param array referentiel array from xml tree
* @return object import_referentiel object
* modifie la base de donnees
*/
function import_etablissements_etudiants( $lines ) {
// recupere le tableau de lignes
// selon les parametres soit cree une nouvelle instance
// soit modifie une instance courante de students
global $SESSION;
global $USER;
global $CFG;
global $DB;
// initialiser les variables
$date_creation="";
$in_etablissement=false; // drapeau
$in_etudiant=false; // drapeau
$t_id_etablissements=array(); // table de reaffectation des id d'etablissement
// get some error strings
$error_noname = get_string( 'xmlimportnoname', 'referentiel' );
$error_nocode = get_string( 'xmlimportnocode', 'referentiel' );
$error_override = get_string( 'overriderisk', 'referentiel' );
// DEBUT
// Decodage
$line = 0;
// TRAITER LA LIGNE D'ENTETE
$nbl=count($lines);
if ($nbl>0){ // premiere ligne entete fichier csv
// echo "<br />2378:: format/csv :: $line : ".$lines[$line]."\n";
//"#Moodle Referentiel Students CSV Export;latin1;Y:2009m:06d:11\n"
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
$line++;
if (substr($lines[$line],0,1)=='#'){
// labels
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted - ignoring\n");
}
}
if (isset($fields[1]) && ($fields[1]!="")){
$this->table_caractere_input=trim($fields[1]);
}
$date_creation=trim($fields[2]);
}
}
else{
$this->error("ERROR : CSV File incorrect\n");
}
// echo "<br />DEBUG :: 2073 : $this->table_caractere_input\n";
if ($nbl>1){ // deuxieme ligne : entete etablissment
// echo "<br />$line : ".$lines[$line]."\n";
while ($line<$nbl){ // data : referentiel
// #id_etablissement;num_etablissement;nom_etablissement;adresse_etablissement
//
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
}
else{
if (substr($lines[$line],0,1)=='#'){
// labels
$l_id = trim($fields[0]);
if ($l_id=="#id_etablissement"){
$l_id_etablissement = trim($fields[0]);
$l_num_etablissement = trim($fields[1]);
$l_nom_etablissement = trim($fields[2]);
$l_adresse_etablissement = trim($fields[3]);
if (isset($fields[4]))
$l_logo_etablissement = trim($fields[4]);
else
$l_logo_etablissement = "";
$in_etablissement=true;
$in_etudiant=false;
}
else if ($l_id=="#id_etudiant"){
// #id_etudiant;user_id;login;NOM_Prenom;num_etudiant;ddn_etudiant;lieu_naissance;departement_naissance;adresse_etudiant;ref_etablissement
$l_id_etudiant = trim($fields[0]);
$l_user_id = trim($fields[1]);
$l_login = trim($fields[2]);
$l_Prenom = trim($fields[3]);
$l_NOM = trim($fields[4]);
$l_num_etudiant = trim($fields[5]);
$l_ddn_etudiant = trim($fields[6]);
$l_lieu_naissance = trim($fields[7]);
$l_departement_naissance = trim($fields[8]);
$l_adresse_etudiant = trim($fields[9]);
$l_ref_etablissement = trim($fields[10]);
$in_etablissement=false;
$in_etudiant=true;
}
}
else{
// data :
if ($in_etablissement==true){ // etablissement
$id_etablissement = trim($fields[0]);
$num_etablissement = $this->input_codage_caractere(trim($fields[1]));
$nom_etablissement = $this->input_codage_caractere(trim($fields[2]));
$adresse_etablissement = $this->input_codage_caractere(trim($fields[3]));
if (isset($fields[4]))
$logo_etablissement = trim($fields[4]);
else
$logo_etablissement = "";
// this routine initialises the import object
$import_etablissement = new stdClass();
$import_etablissement->id=0;
$import_etablissement->num_etablissement=$num_etablissement;
$import_etablissement->nom_etablissement=str_replace("'", " ",$nom_etablissement);
$import_etablissement->adresse_etablissement=str_replace("'", " ",$adresse_etablissement);
$import_etablissement->logo_etablissement=$logo_etablissement;
// sauvegarde dans la base
if (!empty($num_etablissement)){
// rechercher
$etablissement_id=referentiel_get_id_etablissement($num_etablissement);
}
if (!empty($etablissement_id)){ // reindexer
$t_id_etablissements[$id_etablissement]=$etablissement_id;
$id_etablissement=$etablissement_id;
}
else{ // etablissement inconnu
$new_id_etablissement=$DB->insert_record("referentiel_etablissement", $import_etablissement);
$t_id_etablissements[$id_etablissement]=$new_id_etablissement;
$id_etablissement=$new_id_etablissement;
}
if ($id_etablissement!=0){
$import_etablissement->id=$id_etablissement;
if (!$DB->update_record("referentiel_etablissement", $import_etablissement)){
// DEBUG
// echo "<br /> ERREUR UPDATE etablissement\n";
}
}
// DEBUG
// echo "<br />DEBUG :: 2479 :: format/csv ::<br />\n";
// print_object($import_etablissement);
}
elseif ($in_etudiant==true){ // etudiant
$id_etudiant = trim($fields[0]);
$user_id = $this->input_codage_caractere(trim($fields[1]));
$login = $this->input_codage_caractere(trim($fields[2]));
$Prenom = $this->input_codage_caractere(trim($fields[3]));
$NOM = $this->input_codage_caractere(trim($fields[4]));
$num_etudiant = $this->input_codage_caractere(trim($fields[5]));
$ddn_etudiant = trim($fields[6]);
$lieu_naissance = $this->input_codage_caractere(trim($fields[7]));
$departement_naissance = $this->input_codage_caractere(trim($fields[8]));
$adresse_etudiant = $this->input_codage_caractere(trim($fields[9]));
$ref_etablissement = trim($fields[10]);
// rechercher l'id
if ($login!=''){
$user_id=referentiel_get_userid_by_login($login);
if (!empty($user_id)){
$id_etudiant=referentiel_get_etudiant_id_by_userid($user_id);
}
}
else if (($user_id!='') && ($user_id>0)){
// rechercher l'id s'il existe
$id_etudiant=referentiel_get_etudiant_id_by_userid($user_id);
}
if (!empty($user_id)){ // utilisateur inscrit
// this routine initialises the import object
$import_etudiant = new stdClass();
$import_etudiant->id=0;
$import_etudiant->num_etudiant=$num_etudiant;
$import_etudiant->adresse_etudiant=str_replace("'", " ",$adresse_etudiant);
$import_etudiant->ddn_etudiant = $ddn_etudiant ;
$import_etudiant->lieu_naissance =$lieu_naissance;
$import_etudiant->departement_naissance = $departement_naissance;
$import_etudiant->ref_etablissement = $t_id_etablissements[$ref_etablissement];
$import_etudiant->userid = $user_id;
// DEBUG
// echo "<br />DEBUG :: 2513 :: format/csv ::<br />\n";
// print_object($import_etudiant);
// sauvegarde dans la base
if ($id_etudiant==0){
$new_etudiant_id=$DB->insert_record("referentiel_etudiant", $import_etudiant);
}
else{
$import_etudiant->id=$id_etudiant;
if (!$DB->update_record("referentiel_etudiant", $import_etudiant)){
// DEBUG
// echo "<br /> ERREUR UPDATE etudiant\n";
}
}
}
}
}
}
$line++;
}
}
return true;
}
/**
* parse the array of lines into an array
* this *could* burn memory - but it won't happen that much
* so fingers crossed!
* @param array lines array of lines from the input file
* @return array of student object
*/
function read_import_students($lines) {
// we just need it as one array
return $this->import_etablissements_etudiants($lines);
}
}
/** ******************************************
EXPORT TASKS
*/
// TASKS : export des taches
class tformat_csv extends tformat_default {
var $sep = ";";
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return $this->guillemets(str_replace($cherche, $remplace, $texte));
}
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return false;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
$xp = "Moodle Referentiel CSV Export\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Include an image encoded in base 64
* @param string imagepath The location of the image file
* @return string xml code segment
*/
function writeimage( $imagepath ) {
global $CFG;
if (empty($imagepath)) {
return '';
}
$courseid = $this->course->id;
if (!$binary = file_get_contents( "{$CFG->dataroot}/$courseid/$imagepath" )) {
return '';
}
$content = " <image_base64>\n".addslashes(base64_encode( $binary ))."\n".
"\n </image_base64>\n";
return $content;
}
/**
* generates <text></text> tags, processing raw text therein
* @param int ilev the current indent level
* @param boolean short stick it on one line
* @return string formatted text
*/
function write_ligne( $raw, $sep="/", $nmaxcar=80) {
// insere un saut de ligne apres le 80 caractere
$nbcar=strlen($raw);
if ($nbcar>$nmaxcar){
$s1=substr( $raw,0,$nmaxcar);
$pos1=strrpos($s1,$sep);
if ($pos1>0){
$s1=substr( $raw,0,$pos1);
$s2=substr( $raw,$pos1+1);
}
else {
$s1=substr( $raw,0,$nmaxcar);
$s2=substr( $raw,$nmaxcar);
}
return $s1." ".$s2;
}
else{
return $raw;
}
}
/**
* Turns consigne into an xml segment
* @param consigne object
* @return string xml segment
*/
function write_consigne( $consigne ) {
global $CFG;
// initial string;
$expout = "";
if ($consigne){
$id_consigne = $consigne->id ;
$type_consigne = trim($consigne->type_consigne);
$description_consigne = $this->purge_sep($consigne->description_consigne);
$url_consigne = $consigne->url_consigne;
$ref_task = $consigne->ref_task;
$tiemstamp= $consigne->timestamp;
$expout .= "$id_consigne;".stripslashes($this->output_codage_caractere($type_consigne)).";".stripslashes($this->output_codage_caractere($description_consigne)).";$url_consigne;$ref_task;$timestamp\n";
}
return $expout;
}
/**
* Turns task into an csv segment
* @param task object
* @return string csv segment
*/
function write_task( $task ) {
global $CFG;
// initial string;
$expout = "";
// add comment
if ($task){
// DEBUG
// echo "<br />\n";
// print_r($task);
$id_task = $task->id;
$type_task = trim($task->type_task);
$description_task = $this->purge_sep($task->description_task);
$competences_task = trim($task->competences_task);
$criteres_evaluation = $this->purge_sep($task->criteres_evaluation);
$ref_instance = $task->ref_instance;
$ref_referentiel = $task->ref_referentiel;
$ref_course = $task->ref_course;
$auteurid = trim($task->auteurid);
$date_creation = $task->date_creation;
$date_modif = $task->date_modif;
$date_debut = $task->date_debut;
$date_fin = $task->date_fin;
$expout .= "#id_task;type_task;description_task;competences_task;criteres_evaluation;ref_instance;ref_referentiel;ref_course;auteurid;date_creation;date_modif;date_debut;date_fin\n";
$expout .= "$id_task;".stripslashes($this->output_codage_caractere($type_task)).";".stripslashes($this->output_codage_caractere($description_task)).";".stripslashes($this->output_codage_caractere($competences_task)).";".stripslashes($this->output_codage_caractere($criteres_evaluation)).";$ref_instance;$ref_referentiel;$ref_course;$auteurid;".referentiel_timestamp_date_special($date_creation).";".referentiel_timestamp_date_special($date_modif).";".referentiel_timestamp_date_special($date_debut).";".referentiel_timestamp_date_special($date_fin)."\n";
// consigneS
$records_consignes = referentiel_get_consignes($task->id);
if ($records_consignes){
$expout .= "#id_consigne;type_consigne;description_consigne;url_consigne;ref_task;timestamp\n";
foreach ($records_consignes as $record_d){
$expout .= $this->write_consigne( $record_d );
}
}
}
return $expout;
}
/**
* Turns referentiel into an xml segment
* @param competence object
* @return string xml segment
*/
function write_referentiel_reduit() {
global $CFG;
// initial string;
$expout = "";
// add header
if ($this->rreferentiel){
$name = $this->rreferentiel->name;
$code_referentiel = $this->rreferentiel->code_referentiel;
$mail_auteur_referentiel = $this->rreferentiel->mail_auteur_referentiel;
$cle_referentiel = $this->rreferentiel->cle_referentiel;
$pass_referentiel = $this->rreferentiel->pass_referentiel;
$description_referentiel = $this->rreferentiel->description_referentiel;
$url_referentiel = $this->rreferentiel->url_referentiel;
$seuil_certificat = $this->rreferentiel->seuil_certificat;
$timemodified = $this->rreferentiel->timemodified;
$nb_domaines = $this->rreferentiel->nb_domaines;
$liste_codes_competence = $this->rreferentiel->liste_codes_competence;
$liste_empreintes_competence = $this->rreferentiel->liste_empreintes_competence;
$local = $this->rreferentiel->local;
$logo_referentiel = $this->rreferentiel->logo_referentiel;
// INFORMATION REDUITE
$expout .= "#code_referentiel;nom_referentiel;description_referentiel;cle_referentiel;liste_codes_competences\n";
$expout .= stripslashes($this->output_codage_caractere($code_referentiel)).";".stripslashes($this->output_codage_caractere($name)).";".$this->output_codage_caractere($description_referentiel).";$cle_referentiel;".stripslashes($this->output_codage_caractere($liste_codes_competence))."\n";
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
function write_liste_tasks() {
global $CFG;
// initial string;
$expout = "";
if ($this->rreferentiel){
$expout .= $this->write_referentiel_reduit();
}
//
if ($this->ireferentiel){
$id = $this->ireferentiel->id;
$name = trim($this->ireferentiel->name);
$description_instance = $this->purge_sep($this->ireferentiel->description_instance);
$label_domaine = trim($this->ireferentiel->label_domaine);
$label_competence = trim($this->ireferentiel->label_competence);
$label_item = trim($this->ireferentiel->label_item);
$date_instance = $this->ireferentiel->date_instance;
$course = $this->ireferentiel->course;
$ref_referentiel = $this->ireferentiel->ref_referentiel;
$visible = $this->ireferentiel->visible;
/* INUTILE ICI
// $expout .= "#Instance de referentiel : $this->ireferentiel->name\n";
$expout .= "#id_instance;name;description_instance;label_domaine;label_competence;label_item;date_instance;course;ref_referentiel;visible\n";
$expout .= "$id;".stripslashes($this->output_codage_caractere($name)).";".stripslashes($this->output_codage_caractere($description_instance)).";".stripslashes($this->output_codage_caractere($label_domaine)).";".stripslashes($this->output_codage_caractere($label_competence)).";".stripslashes($this->output_codage_caractere($label_item)).";".referentiel_timestamp_date_special($date_instance).";$course;$ref_referentiel;$visible\n";
*/
// tasks
if (isset($this->ireferentiel->id) && ($this->ireferentiel->id>0)){
$records_tasks = referentiel_get_tasks_instance($this->ireferentiel->id);
if ($records_tasks){
foreach ($records_tasks as $record_a){
// DEBUG
// print_r($record_a);
// echo "<br />\n";
$expout .= $this->write_task( $record_a );
}
}
}
}
return $expout;
}
// fin de la classe
}
// ################################################################################################################
// pedagos : export des pedagos
class pformat_csv extends pformat_default {
var $sep = ";";
// ----------------
function guillemets($texte){
return '"'.trim($texte).'"';
return trim($texte);
}
// ----------------
function purge_sep($texte){
$cherche= array('"',$this->sep,"\r\n", "\n", "\r");
$remplace= array("''",",", " ", " ", " ");
return str_replace($cherche, $remplace, $texte);
}
var $table_caractere_input='latin1'; // par defaut import latin1
var $table_caractere_output='latin1'; // par defaut export latin1
// ----------------
function recode_latin1_vers_utf8($string) {
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
// ----------------
function recode_utf8_vers_latin1($string) {
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}
/**
* @param
* @return string recode latin1
*
*/
function input_codage_caractere($s){
if (!isset($this->table_caractere_input) || ($this->table_caractere_input=="")){
$this->table_caractere_input='latin1';
}
if ($this->table_caractere_input=='latin1'){
$s=$this->recode_latin1_vers_utf8($s);
}
return $s;
}
/**
* @param
* @return string recode utf8
*
*/
function output_codage_caractere($s){
if (!isset($this->table_caractere_output) || ($this->table_caractere_output=="")){
$this->table_caractere_output='latin1';
}
if ($this->table_caractere_output=='latin1'){
$s=$this->recode_utf8_vers_latin1($s);
}
return $s;
}
function provide_export() {
return true;
}
function provide_import() {
return true;
}
function repchar( $text ) {
// escapes 'reserved' characters # = ~ { ) and removes new lines
$reserved = array( '#','=','~','{','}',"\n","\r" );
$escaped = array( '\#','\=','\~','\{','\}',' ','' );
return str_replace( $reserved, $escaped, $text );
}
function presave_process( $content ) {
// override method to allow us to add xhtml headers and footers
global $CFG;
$xp = "#Moodle Referentiel pedagos CSV Export;latin1;".referentiel_timestamp_date_special(time())."\n";
$xp .= $content;
return $xp;
}
function export_file_extension() {
return ".csv";
}
/**
* Include an image encoded in base 64
* @param string imagepath The location of the image file
* @return string xml code segment
*/
function writeimage( $imagepath ) {
global $CFG;
if (empty($imagepath)) {
return '';
}
$courseid = $this->course->id;
if (!$binary = file_get_contents( "{$CFG->dataroot}/$courseid/$imagepath" )) {
return '';
}
$content = " <image_base64>\n".addslashes(base64_encode( $binary ))."\n".
"\n </image_base64>\n";
return $content;
}
/**
* generates <text></text> tags, processing raw text therein
* @param int ilev the current indent level
* @param boolean short stick it on one line
* @return string formatted text
*/
function write_ligne( $raw, $sep="/", $nmaxcar=80) {
// insere un saut de ligne apres le 80 caracter
$nbcar=strlen($raw);
if ($nbcar>$nmaxcar){
$s1=substr( $raw,0,$nmaxcar);
$pos1=strrpos($s1,$sep);
if ($pos1>0){
$s1=substr( $raw,0,$pos1);
$s2=substr( $raw,$pos1+1);
}
else {
$s1=substr( $raw,0,$nmaxcar);
$s2=substr( $raw,$nmaxcar);
}
return $s1." ".$s2;
}
else{
return $raw;
}
}
function write_pedago($record_asso, $record_pedago ) {
// initial string;
$expout = "";
// add comment
// $expout .= "\npedago: $record->id -->\n";
if ($record_asso && $record_pedago){
$id = trim( $record_pedago->id );
$userid = trim( $record_asso->userid );
$username=referentiel_get_user_login($userid);
$refrefid = trim( $record_asso->refrefid);
$date_cloture = trim( $record_pedago->date_cloture);
$promotion = $this->output_codage_caractere($this->purge_sep($record_pedago->promotion));
$formation = $this->output_codage_caractere($this->purge_sep($record_pedago->formation));
$pedagogie = $this->output_codage_caractere($this->purge_sep($record_pedago->pedagogie));
$composante = $this->output_codage_caractere($this->purge_sep($record_pedago->composante));
$num_groupe= $this->output_codage_caractere($this->purge_sep($record_pedago->num_groupe));
$commentaire = $this->output_codage_caractere($this->purge_sep($record_pedago->commentaire));
$expout .= "$username;".$this->output_codage_caractere(referentiel_get_user_prenom($record_asso->userid)).";".$this->output_codage_caractere(referentiel_get_user_nom($record_asso->userid)).";$date_cloture;$promotion;$formation;$pedagogie;$composante;$num_groupe;$commentaire;".$this->output_codage_caractere($this->rreferentiel->code_referentiel).";\n";
}
return $expout;
}
/**
* Turns referentiel instance into an xml segment
* @param referentiel instanceobject
* @return string xml segment
*/
function write_liste_pedagos() {
global $CFG;
// initial string;
$expout = "";
if ($this->ireferentiel){
$id = $this->ireferentiel->id;
$name = $this->output_codage_caractere(trim($this->ireferentiel->name));
$description_instance = $this->output_codage_caractere($this->purge_sep($this->ireferentiel->description_instance));
$label_domaine = $this->output_codage_caractere(trim($this->ireferentiel->label_domaine));
$label_competence = $this->output_codage_caractere(trim($this->ireferentiel->label_competence));
$label_item = $this->output_codage_caractere(trim($this->ireferentiel->label_item));
$date_instance = $this->ireferentiel->date_instance;
$course = $this->ireferentiel->course;
$ref_referentiel = $this->ireferentiel->ref_referentiel;
$visible = $this->ireferentiel->visible;
if (isset($this->ireferentiel->course) && ($this->ireferentiel->course>0)){
// ETUDIANTS
$records_all_students = referentiel_get_students_course($this->ireferentiel->course);
if ($records_all_students){
$expout .= "#username;firstname;lastname;date_cloture;promotion;formation;pedagogie;composante;num_groupe;commentaire;referentiel\n";
foreach ($records_all_students as $record_user){
// USER
if (isset($record_user->userid) && ($record_user->userid>0)){
$record_assos=referentiel_get_a_user_pedago($record_user->userid, $this->ireferentiel->ref_referentiel);
if ($record_assos){
foreach($record_assos as $record_asso){
$record_pedago = referentiel_get_pedagogie($record_asso->refpedago);
if ($record_pedago){
$expout .= $this->write_pedago($record_asso, $record_pedago);
}
}
}
}
}
}
}
}
return $expout;
}
// IMPORTATION
/***************************************************************************
// IMPORT FUNCTIONS START HERE
***************************************************************************/
/**
* @param array referentiel array from xml tree
* @return object import_referentiel object
* modifie la base de donnees
*/
function import_pedagogies( $lines ) {
// recupere le tableau de lignes
// selon les parametres soit cree une nouvelle instance
// soit modifie une instance courante de la table referentiel_a_user_scol
global $SESSION;
global $USER;
global $CFG;
global $DB;
// initialiser les variables
$date_creation="";
$in_pedago=false; // drapeau
// get some error strings
$error_noname = get_string( 'xmlimportnoname', 'referentiel' );
$error_nocode = get_string( 'xmlimportnocode', 'referentiel' );
$error_override = get_string( 'overriderisk', 'referentiel' );
$error_message='';
// DEBUT
// Decodage
$line = 0;
// TRAITER LA LIGNE D'ENTETE
$nbl=count($lines);
if ($nbl>0){ // premiere ligne entete fichier csv
// echo "<br />$line : ".$lines[$line]."\n";
//"#Moodle Referentiel pedagos CSV Export;latin1;Y:2009m:06d:11\n"
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
$line++;
if (substr($lines[$line],0,1)=='#'){
// labels
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted - ignoring\n");
}
}
if (isset($fields[1]) && ($fields[1]!="")){
$this->table_caractere_input=trim($fields[1]);
}
$date_creation=trim($fields[2]);
}
}
else{
$this->error("ERROR : CSV File incorrect\n");
}
if ($nbl>1){ // deuxieme ligne
// echo "<br />$line : ".$lines[$line]."\n";
while ($line<$nbl){ // data : referentiel
$fields = explode($this->sep, str_replace( "\r", "", $lines[$line] ) );
/// If a line is incorrectly formatted
if (count($fields) < 3 ) {
if ( count($fields) > 1 or strlen($fields[0]) > 1) { // no error for blank lines
$this->error("ERROR ".$lines[$line].": Line ".$line."incorrectly formatted");
}
}
else{
if (substr($lines[$line],0,1)=='#'){
// labels
// $id;$username;".$this->output_codage_caractere(referentiel_get_user_prenom($record->userid)).";".$this->output_codage_caractere(referentiel_get_user_nom($record->userid)).";$num_groupe;$date_cloture;$promotion;$formation;$pedagogie;$composante;$refrefid\n";
// #username;firstname;lastname;num_groupe;date_cloture;promotion;formation;pedagogie;composante;referentiel;
$l_username = trim($fields[0]);
$l_firstname= trim($fields[1]);
$l_lastname= trim($fields[2]);
$l_date_cloture = trim($fields[3]);
$l_promotion = trim($fields[4]);
$l_formation = trim($fields[5]);
$l_pedagogie = trim($fields[6]);
$l_composante = trim($fields[7]);
if (!empty($fields[8])){
$l_num_groupe = trim($fields[8]);
}
else{
$l_num_groupe = '';
}
if (!empty($fields[9])){
$l_commentaire = trim($fields[9]);
}
else{
$l_commentaire = '';
}
if (!empty($fields[10])){
$l_referentiel = trim($fields[10]);
}
else{
$l_referentiel = '';
}
}
else{
$login = $this->input_codage_caractere(trim($fields[0])); // username
$firstname= $this->input_codage_caractere(trim($fields[1]));
$lastname = $this->input_codage_caractere(trim($fields[2]));
if (!empty($fields[3])){
$date_cloture = $this->input_codage_caractere(trim($fields[3]));
}
else{
$date_cloture = '';
}
if (!empty($fields[4])){
$promotion = $this->input_codage_caractere(trim($fields[4]));
}
else{
$promotion = '';
}
if (!empty($fields[5])){
$formation = $this->input_codage_caractere(trim($fields[5]));
}
else{
$formation = '';
}
if (!empty($fields[6])){
$pedagogie = $this->input_codage_caractere(trim($fields[6]));
}
else{
$pedagogie = '';
}
if (!empty($fields[7])){
$composante = $this->input_codage_caractere(trim($fields[7]));
}
else{
$composante = '';
}
if (!empty($fields[8])){
$num_groupe = $this->input_codage_caractere(trim($fields[8]));
}
else{
$num_groupe ='';
}
if (!empty($fields[9])){
$commentaire = $this->input_codage_caractere(trim($fields[9]));
}
else{
$commentaire = '';
}
if (!empty($fields[10])){
$code_referentiel = $this->input_codage_caractere(trim($fields[10]));
}
else{
$code_referentiel ='';
}
// rechercher la formation
if (!empty($formation) && !empty($pedagogie) && !empty($composante)){
$import_pedago = new stdClass();
$import_pedago->promotion =addslashes($promotion);
$import_pedago->num_groupe = addslashes($num_groupe);
$import_pedago->date_cloture = $date_cloture;
$import_pedago->formation =addslashes($formation);
$import_pedago->pedagogie =addslashes($pedagogie);
$import_pedago->composante =addslashes($composante);
$import_pedago->commentaire =addslashes($commentaire);
$userid=0;
if ($login!=''){
$userid=referentiel_get_userid_by_login($login);
}
if ($userid){ // this routine initialises the import object
$import_association = new stdClass();
$import_association->userid=$userid;
// $tref=referentiel_get_infos_from_code_ref($code_referentiel); // probablement vide
$import_association->refrefid = $this->ref_referentiel;
}
// verification dans la base
$trouve_pedago=0;
$creerasso=0; // insertion association necessaire
if ($userid){
$rec_assos=referentiel_get_a_user_pedago($userid, $this->ref_referentiel);
if ($rec_assos){
// un enregistrement existe
$creerasso=1; // un enregistrement existe : update necessaire
foreach($rec_assos as $rec_asso){
if ($rec_asso){
$import_association->id=$rec_asso->id;
$rec_pedago=referentiel_get_pedagogie($rec_asso->refpedago);
if ($rec_pedago && !$trouve_pedago){ // sinon pas utile de chercher plus loin
if (($rec_pedago->num_groupe == $num_groupe)
//&&
//($rec_pedago->date_cloture == $date_cloture)
&&
($rec_pedago->promotion == $promotion)
&&
($rec_pedago->formation == $formation)
&&
($rec_pedago->pedagogie == $pedagogie)
&&
($rec_pedago->composante == $composante)){ // deja connu
$trouve_pedago=$rec_pedago->id;
$creerasso=2; // rien a faire pour l'association
}
}
}
}
}
}
else{
// MODIF JF 2013/05/23
// il faut probablement ajouter cet utilisateur à Moodle, mais comment faire ?
// A tout le moins signaler la difficulté
$error_message.='<br/>'.get_string('user_unknown','referentiel',$login.' '.$firstname.' '.$lastname);
}
if (!$trouve_pedago){ // verifier si une pedagogie identique existe
$rec_pedago=referentiel_get_id_pedago_from_data($num_groupe, $date_cloture, $promotion, $formation, $pedagogie, $composante);
if ($rec_pedago){
$trouve_pedago=$rec_pedago->id;
}
}
if (!$trouve_pedago){ // enregistrer pedagogie
$trouve_pedago=$DB->insert_record("referentiel_pedagogie", $import_pedago);
}
if ($trouve_pedago){ // mettre a jour association si necessaire
// faut-il mettre quelque chose à jour ?
$rec_pedago=referentiel_get_pedagogie($trouve_pedago);
if (!empty($commentaire) && ($commentaire!=$rec_pedago->commentaire)){
$rec_pedago->commentaire=$commentaire;
referentiel_update_pedagogie_record($rec_pedago);
}
if (!empty($date_cloture) && ($date_cloture!=$rec_pedago->date_cloture)){
$rec_pedago->date_cloture=$date_cloture;
referentiel_update_pedagogie_record($rec_pedago);
}
if ($userid){
$import_association->refpedago = $trouve_pedago;
if ($creerasso==1){ // update
$DB->update_record("referentiel_a_user_pedagogie", $import_association);
}
elseif ($creerasso==0){ // insertion
$id_asso=$DB->insert_record("referentiel_a_user_pedagogie", $import_association);
}
}
}
}
}
}
$line++;
}
}
if (!empty($error_message)){
echo '<div class="error">';
echo get_string('import_pedagogie_error','referentiel')."\n";
echo $error_message."\n";
echo '</div>'."\n";
}
return true;
}
/**
* parse the array of lines into an array
* this *could* burn memory - but it won't happen that much
* so fingers crossed!
* @param array lines array of lines from the input file
* @return array of pedago object
*/
function read_import_pedagos($lines) {
// we just need it as one array
return $this->import_pedagogies($lines);
}
// ###############"" Fin de la classe pformat
}
// ##########################################################################################################
// ################################################################################################################
// archive : export des pedagos
class zformat_csv extends zformat_default {
function provide_export() {
return false;
}
function provide_import() {
return false;
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////
?>
|
gpl-3.0
|
AlexJF/TrackMyMoney
|
app/src/main/java/net/alexjf/tmm/adapters/CategoryAdapter.java
|
2300
|
/*******************************************************************************
* Copyright (c) 2013 - Alexandre Jorge Fonseca (alexjf.net)
* License: GPL v3 (http://www.gnu.org/licenses/gpl-3.0.txt)
******************************************************************************/
package net.alexjf.tmm.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import net.alexjf.tmm.R;
import net.alexjf.tmm.domain.Category;
import net.alexjf.tmm.exceptions.DatabaseException;
import net.alexjf.tmm.utils.DrawableResolver;
import java.util.List;
public class CategoryAdapter extends ArrayAdapter<Category> {
private static final int ROW_VIEW_RESID = R.layout.list_row_category;
private static final int ROW_VIEW_NAMETEXTID = R.id.category_name;
public CategoryAdapter(Context context) {
super(context, ROW_VIEW_RESID, ROW_VIEW_NAMETEXTID);
}
public CategoryAdapter(Context context, List<Category> objects) {
super(context, ROW_VIEW_RESID, ROW_VIEW_NAMETEXTID, objects);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
return getCustomView(position, view, parent);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View view, ViewGroup parent) {
// only inflate the view if it's null
if (view == null) {
LayoutInflater vi = (LayoutInflater) this.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(ROW_VIEW_RESID, null);
}
Category cat = getItem(position);
try {
cat.load();
ImageView iconImageView = (ImageView) view.findViewById(R.id.category_icon);
String iconName = cat.getIcon();
int iconId = DrawableResolver.getInstance().getDrawableId(iconName);
if (iconId != 0) {
iconImageView.setImageResource(iconId);
}
TextView nameLabel = (TextView) view.findViewById(R.id.category_name);
nameLabel.setText(cat.getName());
} catch (DatabaseException e) {
Log.e("TMM", e.getMessage(), e);
}
return view;
}
}
|
gpl-3.0
|
trackplus/Genji
|
src/main/java/com/aurel/track/linkType/ILinkType.java
|
8061
|
/**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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/>.
*/
/* $Id:$ */
package com.aurel.track.linkType;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import com.aurel.track.beans.TPersonBean;
import com.aurel.track.beans.TWorkItemBean;
import com.aurel.track.beans.TWorkItemLinkBean;
import com.aurel.track.errors.ErrorData;
import com.aurel.track.util.ParameterMetadata;
/**
* Interface for link types
* @author Tamas
*
*/
public interface ILinkType {
//the parent child relationship used in the filter
public static final int PARENT_CHILD = 0;
public static interface PARENT_CHILD_EXPRESSION {
public static final int ALL_CHILDREN = 1;
public static final int ALL_NOT_CLOSED_CHILDREN = 2;
public static final int ALL_PARENTS = 3;
public static final int FIRST_LEVEL = 3;
public static final int FIRST_LEVEL_NOT_CLOSED = 4;
public static final int LEVEL_X = 5;
public static final int LEVEL_X_NOT_CLOSED = 6;
}
/**
* Defines the possible link directions
* 1. the linkDirection of a workItemLinkBean can be either
* LEFT_TO_RIGHT or RIGHT_TO_LEFT
* 2. the linkDirection of a linkTypeBean can be either
* UNIDIRECTIONAL_OUTWARD or UNIDIRECTIONAL_INWARD or BIDIRECTIONAL
* 3. the linkType plugin's getPossibleDirection() can be
* UNIDIRECTIONAL_OUTWARD or UNIDIRECTIONAL_INWARD or BIDIRECTIONAL or ANY
* ANY means that by instantiating a new link type of a specific linkType plugin
* the administrator can choose either UNIDIRECTIONAL_OUTWARD or UNIDIRECTIONAL_INWARD or BIDIRECTIONAL
* as linkDirection
* @author Tamas
*
*/
public static interface LINK_DIRECTION {
//for bidirectional relationships see the successors from predecessor with the "normal" name of the bidirectional relationship
public static final int LEFT_TO_RIGHT = 1;
//only the predecessor sees the successors but not vice versa: used for link types
public static final int UNIDIRECTIONAL_OUTWARD = 1;
//for bidirectional relationships see the predecessor from successor with the reverse name of the bidirectional relationship
public static final int RIGHT_TO_LEFT = 2;
//only the successor sees the predecessors but not vice versa
public static final int UNIDIRECTIONAL_INWARD = 2;
//predecessor sees the successors and vice versa
public static final int BIDIRECTIONAL = 3;
public static final int ANY=4; //any of the previous values
}
public static interface FILTER_EXPRESSION_HIERARCHICAL {
public static final int LEFT_TO_RIGHT_FIRST_LEVEL = 1;
public static final int RIGHT_TO_LEFT_FIRST_LEVEL = 2;
public static final int LEFT_TO_RIGHT_LEVEL_X = 3;
public static final int RIGHT_TO_LEFT_LEVEL_X = 4;
public static final int LEFT_TO_RIGHT_ALL = 5;
public static final int RIGHT_TO_LEFT_ALL = 6;
}
public static interface FILTER_EXPRESSION_PLAIN {
public static final int LEFT_TO_RIGHT = FILTER_EXPRESSION_HIERARCHICAL.LEFT_TO_RIGHT_FIRST_LEVEL;
public static final int RIGHT_TO_LEFT = FILTER_EXPRESSION_HIERARCHICAL.RIGHT_TO_LEFT_FIRST_LEVEL;
}
public String getPluginID();
/**
* Called before the link is created
* @return
*/
boolean beforeCreateLink();
/**
* Called after the link is created
*/
void afterCreateLink();
/**
* Get the possible direction for the links
* @return
*/
int getPossibleDirection();
/**
* Whether this link type appears in gantt view
* @return
*/
boolean isGanttSpecific();
/**
* Whether this link type is inline
* (never created explicitly, only implicitly in the background by including an item inline in a document)
* @return
*/
boolean isInline();
/**
* Gets the item link specific data
* @param workItemLinkBean
* @return
*/
ItemLinkSpecificData getItemLinkSpecificData(TWorkItemLinkBean workItemLinkBean);
/**
* Gets the itemLinkSpecificData as a string map for serializing
* @param itemLinkSpecificData
* @param locale
* @return
*/
Map<String, String> serializeItemLinkSpecificData(ItemLinkSpecificData itemLinkSpecificData, Locale locale);
/**
* Validation called before saving the issue
* @param workItemBean
* @param workItemBeanOriginal
* @param person
* @param predToSuccLinksOfType
* @param succToPredLinksOfType
* @param confirm whether the user confirmed
* @param locale
* @return
*/
List<ErrorData> validateBeforeIssueSave(TWorkItemBean workItemBean,
TWorkItemBean workItemBeanOriginal, Integer person,
List<TWorkItemLinkBean> predToSuccLinksOfType,
List<TWorkItemLinkBean> succToPredLinksOfType, boolean confirm, Locale locale);
/**
* Called after the issue is saved
* @param workItemBean
* @param workItemBeanOriginal
* @param personID
* @param predToSuccLinksOfType
* @param succToPredLinksOfType
* @param locale
*/
void afterIssueSave(TWorkItemBean workItemBean, TWorkItemBean workItemBeanOriginal, Integer personID, List<TWorkItemLinkBean> predToSuccLinksOfType,
List<TWorkItemLinkBean> succToPredLinksOfType, Locale locale);
/**
* Whether this link type appears in the tree query as
* selectable for query result superset
* @return
*/
boolean selectableForQueryResultSuperset();
/**
* Whether the linkType is hierarchical (more than one level)
* Makes sense only if selectableAsQueryResultSuperset returns true
* @return
*/
boolean isHierarchical();
/**
* Prepares the parameters in the Link tab
* @param workItemLinkBean
* @param linkDirection
* @param locale
* @return
*/
String prepareParametersOnLinkTab(TWorkItemLinkBean workItemLinkBean, Integer linkDirection, Locale locale);
/**
* Prepare the parameters map
* Used in webservice
* @param workItemLinkBean
* @return
*/
Map<String, String> prepareParametersMap(TWorkItemLinkBean workItemLinkBean);
/**
* Gets the parameter metadata as a list
* @param locale
* @return
*/
List<ParameterMetadata> getParameterMetadata(Locale locale);
/**
* Gets the JavaScript class for configuring the link type specific part
* @return
*/
String getLinkTypeJSClass();
/**
* Gets the link type specific configuration as JSON
* @param workItemLinkBean
* @param personBean
* @param locale
* @return
*/
String getSpecificJSON(TWorkItemLinkBean workItemLinkBean, TPersonBean personBean, Locale locale);
/**
* Sets the workItemLinkBean according to the values submitted in the parameters map
* @param parametersMap the parameters from link configuration
* @param workItemLinkBean
* @param personBean the current user
* @param locale
* @return
*/
List<ErrorData> unwrapParametersBeforeSave(Map<String, String> parametersMap, TWorkItemLinkBean workItemLinkBean, TPersonBean personBean, Locale locale);
/**
* Validates the workItemLink before save
* @param workItemLinkBean
* @param workItemLinkOriginal
* @param workItemsLinksMap
* @param predWorkItem
* @param succWorkItem
* @param personBean
* @param locale
* @return
*/
List<ErrorData> validateBeforeSave(TWorkItemLinkBean workItemLinkBean, TWorkItemLinkBean workItemLinkOriginal,
SortedMap<Integer, TWorkItemLinkBean> workItemsLinksMap,
TWorkItemBean predWorkItem, TWorkItemBean succWorkItem, TPersonBean personBean, Locale locale);
}
|
gpl-3.0
|
makeone/makeone
|
test/unit/software_test.rb
|
155
|
require 'test_helper'
class SoftwareTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
|
gpl-3.0
|
Deadleg/Slide
|
app/src/main/java/me/ccrama/redditslide/Activities/Settings.java
|
17947
|
package me.ccrama.redditslide.Activities;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.afollestad.materialdialogs.AlertDialogWrapper;
import me.ccrama.redditslide.Authentication;
import me.ccrama.redditslide.DragSort.ReorderSubreddits;
import me.ccrama.redditslide.FDroid;
import me.ccrama.redditslide.R;
import me.ccrama.redditslide.Reddit;
import me.ccrama.redditslide.SettingValues;
import me.ccrama.redditslide.Visuals.Palette;
import me.ccrama.redditslide.util.OnSingleClickListener;
/**
* Created by ccrama on 3/5/2015.
*/
public class Settings extends BaseActivity {
private final static int RESTART_SETTINGS_RESULT = 2;
private int scrollY;
private SharedPreferences.OnSharedPreferenceChangeListener prefsListener;
public static boolean changed;
//whether or not a Setting was changed
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESTART_SETTINGS_RESULT) {
Intent i = new Intent(Settings.this, Settings.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra("position", scrollY);
startActivity(i);
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyColorTheme();
setContentView(R.layout.activity_settings);
setupAppBar(R.id.toolbar, R.string.title_settings, true, true);
SettingValues.expandedSettings = true;
setSettingItems();
final ScrollView mScrollView = ((ScrollView) findViewById(R.id.base));
prefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Settings.changed = true;
}
};
SettingValues.prefs.registerOnSharedPreferenceChangeListener(prefsListener);
mScrollView.post(new Runnable() {
@Override
public void run() {
ViewTreeObserver observer = mScrollView.getViewTreeObserver();
if (getIntent().hasExtra("position")) {
mScrollView.scrollTo(0, getIntent().getIntExtra("position", 0));
}
observer.addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
scrollY = mScrollView.getScrollY();
}
});
}
});
}
private void setSettingItems() {
View pro = findViewById(R.id.pro);
if (SettingValues.tabletUI) {
pro.setVisibility(View.GONE);
} else {
pro.setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
new AlertDialogWrapper.Builder(Settings.this).setTitle(
R.string.settings_support_slide)
.setMessage(R.string.pro_upgrade_msg)
.setPositiveButton(R.string.btn_yes_exclaim,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
"market://details?id=me.ccrama.slideforreddittabletuiunlock")));
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
}
}
})
.setNegativeButton(R.string.btn_no_danks,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
})
.show();
}
});
}
findViewById(R.id.general).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsGeneral.class);
startActivityForResult(i, RESTART_SETTINGS_RESULT);
}
});
findViewById(R.id.history).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsHistory.class);
startActivity(i);
}
});
findViewById(R.id.about).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsAbout.class);
startActivity(i);
}
});
findViewById(R.id.offline).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Settings.this, ManageOfflineContent.class);
startActivity(i);
}
});
findViewById(R.id.datasave).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsData.class);
startActivity(i);
}
});
findViewById(R.id.subtheme).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsSubreddit.class);
startActivityForResult(i, RESTART_SETTINGS_RESULT);
}
});
findViewById(R.id.filter).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsFilter.class);
startActivity(i);
}
});
findViewById(R.id.synccit).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsSynccit.class);
startActivity(i);
}
});
findViewById(R.id.reorder).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View view) {
Intent inte = new Intent(Settings.this, ReorderSubreddits.class);
Settings.this.startActivity(inte);
}
});
findViewById(R.id.theme).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsTheme.class);
startActivityForResult(i, RESTART_SETTINGS_RESULT);
}
});
findViewById(R.id.handling).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsHandling.class);
startActivity(i);
}
});
findViewById(R.id.layout).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, EditCardsLayout.class);
startActivity(i);
}
});
findViewById(R.id.backup).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsBackup.class);
startActivity(i);
}
});
findViewById(R.id.font).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsFont.class);
startActivity(i);
}
});
findViewById(R.id.tablet).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View view) {
/* Intent inte = new Intent(Overview.this, Overview.class);
inte.putExtra("type", UpdateSubreddits.COLLECTIONS);
Overview.this.startActivity(inte);*/
if (SettingValues.tabletUI) {
LayoutInflater inflater = getLayoutInflater();
final View dialoglayout = inflater.inflate(R.layout.tabletui, null);
final AlertDialogWrapper.Builder builder =
new AlertDialogWrapper.Builder(Settings.this);
final Resources res = getResources();
dialoglayout.findViewById(R.id.title)
.setBackgroundColor(Palette.getDefaultColor());
//todo final Slider portrait = (Slider) dialoglayout.findViewById(R.id.portrait);
final SeekBar landscape = (SeekBar) dialoglayout.findViewById(R.id.landscape);
//todo portrait.setBackgroundColor(Palette.getDefaultColor());
landscape.setProgress(Reddit.dpWidth - 1);
((TextView) dialoglayout.findViewById(R.id.progressnumber)).setText(
res.getQuantityString(R.plurals.landscape_columns,
landscape.getProgress() + 1, landscape.getProgress() + 1));
landscape.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
((TextView) dialoglayout.findViewById(R.id.progressnumber)).setText(
res.getQuantityString(R.plurals.landscape_columns,
landscape.getProgress() + 1,
landscape.getProgress() + 1));
Settings.changed = true;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final Dialog dialog = builder.setView(dialoglayout).create();
dialog.show();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Reddit.dpWidth = landscape.getProgress() + 1;
Reddit.colors.edit()
.putInt("tabletOVERRIDE", landscape.getProgress() + 1)
.apply();
}
});
SwitchCompat s = (SwitchCompat) dialog.findViewById(R.id.dualcolumns);
s.setChecked(SettingValues.dualPortrait);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SettingValues.dualPortrait = isChecked;
SettingValues.prefs.edit()
.putBoolean(SettingValues.PREF_DUAL_PORTRAIT, isChecked)
.apply();
}
});
SwitchCompat s2 = (SwitchCompat) dialog.findViewById(R.id.fullcomment);
s2.setChecked(SettingValues.fullCommentOverride);
s2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SettingValues.fullCommentOverride = isChecked;
SettingValues.prefs.edit()
.putBoolean(SettingValues.PREF_FULL_COMMENT_OVERRIDE, isChecked)
.apply();
}
});
} else {
new AlertDialogWrapper.Builder(Settings.this).setTitle(
"Mutli-Column Settings are a Pro feature")
.setMessage(R.string.pro_upgrade_msg)
.setPositiveButton(R.string.btn_yes_exclaim,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
"market://details?id=me.ccrama.slideforreddittabletuiunlock")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://play.google.com/store/apps/details?id=me.ccrama.slideforreddittabletuiunlock")));
}
}
})
.setNegativeButton(R.string.btn_no_danks,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.show();
}
}
});
if(FDroid.isFDroid){
((TextView) findViewById(R.id.donatetext)).setText("Donate via PayPal");
}
findViewById(R.id.support).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
if(FDroid.isFDroid){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=56FKCCYLX7L72"));
startActivity(browserIntent);
} else {
Intent inte = new Intent(Settings.this, DonateView.class);
Settings.this.startActivity(inte);
}
}
});
findViewById(R.id.comments).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent inte = new Intent(Settings.this, SettingsComments.class);
Settings.this.startActivity(inte);
}
});
if (Authentication.isLoggedIn) {
findViewById(R.id.reddit_settings).setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
Intent i = new Intent(Settings.this, SettingsReddit.class);
startActivity(i);
}
});
} else {
findViewById(R.id.reddit_settings).setEnabled(false);
findViewById(R.id.reddit_settings).setAlpha(0.25f);
}
}
@Override
public void onDestroy() {
super.onDestroy();
SettingValues.prefs.unregisterOnSharedPreferenceChangeListener(prefsListener);
}
}
|
gpl-3.0
|
M2PSM-BlindVideoGames/Demo
|
Assets/Scripts/MoveCircle.cs
|
666
|
using UnityEngine;
using System.Collections;
public class MoveCircle : MonoBehaviour {
public float speed = 0.3f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Move();
}
void Move()
{
if (Input.GetKey(KeyCode.S))
transform.Translate(Vector3.back * speed);
else if (Input.GetKey(KeyCode.Z))
transform.Translate(Vector3.forward * speed);
if (Input.GetKey(KeyCode.Q))
transform.Translate(Vector3.left * speed);
else if (Input.GetKey(KeyCode.D))
transform.Translate(Vector3.right * speed);
}
}
|
gpl-3.0
|
rlktradewright/manifest-generator
|
GenerateManifest/Program.cs
|
12701
|
#region License
// The MIT License (MIT)
//
// Copyright (c) 2017-2018 Richard L King (TradeWright Software Systems)
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using TradeWright.ManifestUtilities;
namespace TradeWright.GenerateManifest
{
class Program
{
private struct Parameters
{
internal string projectFile;
internal string objectFile;
internal string assemblyInfo;
internal string description;
internal string outFile;
internal bool useVersion6CommonControls;
internal bool inlineExternalObjects;
internal string assemblyName;
internal string assemblyVersion;
internal string assemblyDescription;
internal IEnumerable<string> assemblyFiles;
internal IEnumerable<string> dependentAssemblyIDs;
}
static int Main(string[] args)
{
try
{
var parameters = new Parameters();
if (!GetParameters(ref parameters)) return 1;
using (MemoryStream data = GenerateManifest(parameters))
{
if (parameters.outFile != String.Empty)
{
WriteManifestToFile(parameters, data);
}
else
{
WriteManifestToConsole(data);
}
return 0;
}
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
return 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return 1;
}
}
private static bool GetParameters(ref Parameters parameters)
{
var clp = new CommandLineParser(Environment.CommandLine, " ");
if (clp.get_IsSwitchSet("?") || clp.get_IsSwitchSet("HELP"))
{
ShowUsage();
return false;
}
if (!getProjectFile(ref parameters, clp))
{
return false;
}
else if (!getObjectFile(ref parameters, clp))
{
return false;
}
else if (!getAssemblyDetails(ref parameters, ref clp))
{
return false;
}
parameters.description = clp.get_SwitchValue("DESC");
parameters.outFile = clp.get_SwitchValue("OUT");
parameters.useVersion6CommonControls = clp.get_IsSwitchSet("V6CC");
parameters.inlineExternalObjects = clp.get_IsSwitchSet("INLINE");
if ((String.IsNullOrEmpty(parameters.projectFile) && String.IsNullOrEmpty(parameters.objectFile) && String.IsNullOrEmpty(parameters.assemblyInfo)) ||
(!String.IsNullOrEmpty(parameters.projectFile) && !String.IsNullOrEmpty(parameters.objectFile) && !String.IsNullOrEmpty(parameters.assemblyInfo)))
{
Console.WriteLine("Invalid arguments: only one of /Proj, /Bin and /Ass may be supplied\n");
ShowUsage();
return false;
}
return true;
}
private static bool getAssemblyDetails(ref Parameters parameters, ref CommandLineParser clp)
{
if (clp.get_IsSwitchSet("ASS"))
{
parameters.assemblyInfo = clp.get_SwitchValue("ASS");
var assClp = new CommandLineParser(parameters.assemblyInfo, ",");
if (assClp.NumberOfArgs != 4)
{
Console.WriteLine("Invalid arguments\n");
ShowUsage();
return false;
}
parameters.assemblyName = assClp.get_Arg(0);
parameters.assemblyVersion = assClp.get_Arg(1);
parameters.assemblyDescription = assClp.get_Arg(2);
if (!File.Exists(assClp.get_Arg(3)))
{
Console.WriteLine("Invalid argument: file {0} does not exist", assClp.get_Arg(3));
return false;
}
parameters.assemblyFiles = from f in LineReader(assClp.get_Arg(3))
where !String.IsNullOrEmpty(f) && !f.StartsWith("//")
select f;
}
return true;
}
private static bool getObjectFile(ref Parameters parameters, CommandLineParser clp)
{
if (clp.get_IsSwitchSet("BIN"))
{
parameters.objectFile = clp.get_SwitchValue("BIN");
if (!File.Exists(parameters.objectFile))
{
Console.WriteLine("Invalid argument: file {0} does not exist", parameters.projectFile);
return false;
}
}
return true;
}
private static bool getProjectFile(ref Parameters parameters, CommandLineParser clp)
{
if (clp.get_IsSwitchSet("PROJ"))
{
parameters.projectFile = clp.get_SwitchValue("PROJ");
if (!File.Exists(parameters.projectFile))
{
Console.WriteLine("Invalid argument: file {0} does not exist", parameters.projectFile);
return false;
}
IEnumerable<string> manFileReader = null;
if (File.Exists(parameters.projectFile + ".man"))
{
manFileReader = LineReader(parameters.projectFile + ".man");
}
IEnumerable<string> depFileReader = null;
var depFilename = clp.get_SwitchValue("DEP");
if (! string.IsNullOrEmpty(depFilename))
{
if (!File.Exists(depFilename))
{
Console.WriteLine("Invalid argument: file {0} does not exist", depFilename);
return false;
}
depFileReader = LineReader(depFilename);
}
if (manFileReader != null && depFileReader != null)
{
parameters.dependentAssemblyIDs = manFileReader.Union(depFileReader);
}
else if (manFileReader != null)
{
parameters.dependentAssemblyIDs = manFileReader;
}
else if (depFileReader != null)
{
parameters.dependentAssemblyIDs = depFileReader;
}
}
return true;
}
private static MemoryStream GenerateManifest(Parameters parameters)
{
var gen = new ManifestGenerator();
MemoryStream data = null;
if (!String.IsNullOrEmpty(parameters.projectFile))
{
data = gen.GenerateFromProject(parameters.projectFile, parameters.useVersion6CommonControls, parameters.inlineExternalObjects, parameters.dependentAssemblyIDs);
}
else if (!String.IsNullOrEmpty(parameters.objectFile))
{
data = gen.GenerateFromObjectFile(parameters.objectFile, parameters.description);
}
else if (!String.IsNullOrEmpty(parameters.assemblyName))
{
data = gen.GenerateFromFiles(parameters.assemblyName, parameters.assemblyVersion, parameters.assemblyDescription, parameters.inlineExternalObjects, parameters.assemblyFiles);
}
return data;
}
private static IEnumerable<String> LineReader(String fileName)
{
String line;
using (var file = File.OpenText(fileName))
{
while ((line = file.ReadLine()) != null)
{
yield return line.Trim();
}
}
}
private static void WriteManifestToConsole(MemoryStream data)
{
data.Position = 0;
XmlReader reader = XmlReader.Create(data);
reader.Read();
Console.WriteLine("<?xml {0} ?>", reader.Value);
reader.MoveToContent();
Console.WriteLine(reader.ReadOuterXml());
reader.Close();
}
private static void WriteManifestToFile(Parameters parameters, MemoryStream data)
{
using (FileStream fs = new FileStream(parameters.outFile, FileMode.Create))
{
data.WriteTo(fs);
}
}
private static void ShowUsage()
{
//========1=========2=========3=========4=========5=========6=========7=========8
Console.Write(
@"Creates a manifest for a dll or exe, or for a multifile assembly.
GenerateManifest {/Proj:<projectFileName> [/V6CC] /Dep:<depFilename> |
/Bin:<objectFilename> [/Desc:<description>] |
/Ass:<name>,<version>,<description>,<filenamesFile>}
[/Inline]
[/Out:<outputManifestFilename>]
/Proj Creates a manifest for the Visual Basic 6 project in
<projectFileName>. If a file called <projectFileName>.man
exists or /Dep:<depFilename> is specified, then the manifest
is generated with the dependent assemblies specified in
<projectFileName>.man and/or <depFilename>, instead of
taking the dependencies from the project file (see below
for further details).
/V6CC Specifies that the project uses Microsoft Common Controls
Version 6 (ignored if not an exe project).
/Dep Specifies a file containing external dependencies for this
project (see below for further details).
/Inline Specifies that <dependentAsssembly> elements are not to be
included for external references. Rather a <file> element
containing the COM class information is to be generated for
each external reference. Ignored if a <projectFileName>.man
file exists. This switch is relevant only when /Proj or /Ass
are specified, and is ignored otherwise.
/Bin Creates a manifest for the exe, dll or ocx in
<objectFilename>.
/Ass Creates a multi-file assembly manifest for the projects or
object files contained in file <filenamesFile>.
/Desc This is used for the manifest's description element.
/Out Stores the manifest in <outputManifestFilename>. If not
supplied, the manifest is written to stdout.
<projectFileName>.man and <depFilename>
Contains details of one dependent assembly per line. Each
line is formatted as a complete <assemblyIdentity> element,
including the final </assemblyIdentity> tag. Blank lines and
lines beginning // are ignored.
<filenamesFile>
Contains one project or object filename per line. Object
files must be .dll or .ocx files. Blank lines and lines
beginning // are ignored.
");
}
}
}
|
gpl-3.0
|
sethten/MoDesserts
|
mcp50/temp/src/minecraft_server/net/minecraft/src/BlockOreStorage.java
|
572
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
// Referenced classes of package net.minecraft.src:
// Block, Material
public class BlockOreStorage extends Block
{
public BlockOreStorage(int p_i337_1_, int p_i337_2_)
{
super(p_i337_1_, Material.field_522_e);
field_575_bb = p_i337_2_;
}
public int func_241_a(int p_241_1_)
{
return field_575_bb;
}
}
|
gpl-3.0
|
claudiofus/WeatherApp
|
app/src/main/java/com/claudiofus/clock2/timers/data/TimerCursor.java
|
1996
|
/*
* Copyright 2017 Phillip Hsu
*
* This file is part of ClockPlus.
*
* ClockPlus 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.
*
* ClockPlus 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 ClockPlus. If not, see <http://www.gnu.org/licenses/>.
*/
package com.claudiofus.clock2.timers.data;
import android.database.Cursor;
import com.claudiofus.clock2.data.BaseItemCursor;
import com.claudiofus.clock2.timers.Timer;
/**
* Created by Phillip Hsu on 7/30/2016.
*/
public class TimerCursor extends BaseItemCursor<Timer> {
public TimerCursor(Cursor cursor) {
super(cursor);
}
@Override
public Timer getItem() {
if (isBeforeFirst() || isAfterLast())
return null;
int hour = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_HOUR));
int minute = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_MINUTE));
int second = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_SECOND));
String label = getString(getColumnIndexOrThrow(TimersTable.COLUMN_LABEL));
// String group = getString(getColumnIndexOrThrow(COLUMN_GROUP));
Timer t = Timer.create(hour, minute, second, ""/*group*/, label);
t.setId(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_ID)));
t.setEndTime(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_END_TIME)));
t.setPauseTime(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_PAUSE_TIME)));
t.setDuration(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_DURATION)));
return t;
}
}
|
gpl-3.0
|
Itsinmybackpack/CreateUO
|
Server/ExpansionInfo.cs
|
6426
|
#region Header
// **************************************\
// _ _ _ __ ___ _ _ ___ |
// |# |# |# |## |### |# |# |### |
// |# |# |# |# |# |# |# |# |# |
// |# |# |# |# |# |# |# |# |# |
// _|# |#__|# _|# |# |#__|# |#__|# |
// |## |## |## |# |## |### |
// [http://www.playuo.org] |
// **************************************/
// [2014] ExpansionInfo.cs
// ************************************/
#endregion
#region References
using System;
#endregion
namespace Server
{
public enum Expansion
{
None,
T2A,
UOR,
UOTD,
LBR,
AOS,
SE,
ML,
SA,
HS
}
[Flags]
public enum ClientFlags
{
None = 0x00000000,
Felucca = 0x00000001,
Trammel = 0x00000002,
Ilshenar = 0x00000004,
Malas = 0x00000008,
Tokuno = 0x00000010,
TerMur = 0x00000020,
Unk1 = 0x00000040,
Unk2 = 0x00000080,
UOTD = 0x00000100
}
[Flags]
public enum FeatureFlags
{
None = 0x00000000,
T2A = 0x00000001,
UOR = 0x00000002,
UOTD = 0x00000004,
LBR = 0x00000008,
AOS = 0x00000010,
SixthCharacterSlot = 0x00000020,
SE = 0x00000040,
ML = 0x00000080,
EigthAge = 0x00000100,
NinthAge = 0x00000200, /* Crystal/Shadow Custom House Tiles */
TenthAge = 0x00000400,
InceasedStorage = 0x00000800, /* Increased Housing/Bank Storage */
SeventhCharacterSlot = 0x00001000,
RoleplayFaces = 0x00002000,
TrialAccount = 0x00004000,
LiveAccount = 0x00008000,
SA = 0x00010000,
HS = 0x00020000,
Gothic = 0x00040000,
Rustic = 0x00080000,
ExpansionNone = None,
ExpansionT2A = T2A,
ExpansionUOR = ExpansionT2A | UOR,
ExpansionUOTD = ExpansionUOR | UOTD,
ExpansionLBR = ExpansionUOTD | LBR,
ExpansionAOS = ExpansionLBR | AOS | LiveAccount,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML | NinthAge,
ExpansionSA = ExpansionML | SA | Gothic | Rustic,
ExpansionHS = ExpansionSA | HS
}
[Flags]
public enum CharacterListFlags
{
None = 0x00000000,
Unk1 = 0x00000001,
OverwriteConfigButton = 0x00000002,
OneCharacterSlot = 0x00000014,
ContextMenus = 0x00000008,
SlotLimit = 0x00000010,
AOS = 0x00000020,
SixthCharacterSlot = 0x00000040,
SE = 0x00000080,
ML = 0x00000100,
Unk2 = 0x00000200,
UO3DClientType = 0x00000400,
Unk3 = 0x00000800,
SeventhCharacterSlot = 0x00001000,
Unk4 = 0x00002000,
NewMovementSystem = 0x00004000,
NewFeluccaAreas = 0x00008000,
ExpansionNone = ContextMenus, //
ExpansionT2A = ContextMenus, //
ExpansionUOR = ContextMenus, // None
ExpansionUOTD = ContextMenus, //
ExpansionLBR = ContextMenus, //
ExpansionAOS = ContextMenus | AOS,
ExpansionSE = ExpansionAOS | SE,
ExpansionML = ExpansionSE | ML,
ExpansionSA = ExpansionML,
ExpansionHS = ExpansionSA
}
public class ExpansionInfo
{
public static ExpansionInfo[] Table { get { return m_Table; } }
private static readonly ExpansionInfo[] m_Table = new[]
{
new ExpansionInfo(0, "None", ClientFlags.None, FeatureFlags.ExpansionNone, CharacterListFlags.ExpansionNone, 0x0000),
new ExpansionInfo(
1, "The Second Age", ClientFlags.Felucca, FeatureFlags.ExpansionT2A, CharacterListFlags.ExpansionT2A, 0x0000),
new ExpansionInfo(
2, "Renaissance", ClientFlags.Trammel, FeatureFlags.ExpansionUOR, CharacterListFlags.ExpansionUOR, 0x0000),
new ExpansionInfo(
3, "Third Dawn", ClientFlags.Ilshenar, FeatureFlags.ExpansionUOTD, CharacterListFlags.ExpansionUOTD, 0x0000),
new ExpansionInfo(
4, "Blackthorn's Revenge", ClientFlags.Ilshenar, FeatureFlags.ExpansionLBR, CharacterListFlags.ExpansionLBR, 0x0000)
,
new ExpansionInfo(
5, "Age of Shadows", ClientFlags.Malas, FeatureFlags.ExpansionAOS, CharacterListFlags.ExpansionAOS, 0x0000),
new ExpansionInfo(
6, "Samurai Empire", ClientFlags.Tokuno, FeatureFlags.ExpansionSE, CharacterListFlags.ExpansionSE, 0x00C0),
// 0x20 | 0x80
new ExpansionInfo(
7, "Mondain's Legacy", new ClientVersion("5.0.0a"), FeatureFlags.ExpansionML, CharacterListFlags.ExpansionML, 0x02C0)
, // 0x20 | 0x80 | 0x200
new ExpansionInfo(
8, "Stygian Abyss", ClientFlags.TerMur, FeatureFlags.ExpansionSA, CharacterListFlags.ExpansionSA, 0xD02C0),
// 0x20 | 0x80 | 0x200 | 0x10000 | 0x40000 | 0x80000
new ExpansionInfo(
9, "High Seas", new ClientVersion("7.0.9.0"), FeatureFlags.ExpansionHS, CharacterListFlags.ExpansionHS, 0xD02C0)
// 0x20 | 0x80 | 0x200 | 0x10000 | 0x40000 | 0x80000
};
private readonly string m_Name;
private readonly int m_ID;
private readonly int m_CustomHousingFlag;
private readonly ClientFlags m_ClientFlags;
private readonly FeatureFlags m_SupportedFeatures;
private readonly CharacterListFlags m_CharListFlags;
private readonly ClientVersion m_RequiredClient; // Used as an alternative to the flags
public string Name { get { return m_Name; } }
public int ID { get { return m_ID; } }
public ClientFlags ClientFlags { get { return m_ClientFlags; } }
public FeatureFlags SupportedFeatures { get { return m_SupportedFeatures; } }
public CharacterListFlags CharacterListFlags { get { return m_CharListFlags; } }
public int CustomHousingFlag { get { return m_CustomHousingFlag; } }
public ClientVersion RequiredClient { get { return m_RequiredClient; } }
public ExpansionInfo(
int id,
string name,
ClientFlags clientFlags,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
int customHousingFlag)
{
m_Name = name;
m_ID = id;
m_ClientFlags = clientFlags;
m_SupportedFeatures = supportedFeatures;
m_CharListFlags = charListFlags;
m_CustomHousingFlag = customHousingFlag;
}
public ExpansionInfo(
int id,
string name,
ClientVersion requiredClient,
FeatureFlags supportedFeatures,
CharacterListFlags charListFlags,
int customHousingFlag)
{
m_Name = name;
m_ID = id;
m_SupportedFeatures = supportedFeatures;
m_CharListFlags = charListFlags;
m_CustomHousingFlag = customHousingFlag;
m_RequiredClient = requiredClient;
}
public static ExpansionInfo GetInfo(Expansion ex)
{
return GetInfo((int)ex);
}
public static ExpansionInfo GetInfo(int ex)
{
int v = ex;
if (v < 0 || v >= m_Table.Length)
{
v = 0;
}
return m_Table[v];
}
public static ExpansionInfo CurrentExpansion { get { return GetInfo(Core.Expansion); } }
public override string ToString()
{
return m_Name;
}
}
}
|
gpl-3.0
|
kovacssupki/ForumForYou
|
backend/controllers/users.js
|
280
|
'use strict';
var fs = require("co-fs");
exports = module.exports = ( Users ) => {
return function* ( ) {
var users = yield Users.find({}).exec();
this.success(users);
};
};
exports[ 'singleton' ] = true;
exports[ '@require' ] = [
'models/user'
];
|
gpl-3.0
|
fcunhaneto/bit-note
|
template-parts/content.php
|
352
|
<?php bit_note_nav_pages() ?>
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( array( 'post-article', 'panel', 'panel-default' ) ); ?>>
<?php get_template_part( 'template-parts/content', 'header' ); ?>
<div class="panel-body">
<?php the_excerpt(); ?>
</div>
</article>
<?php endwhile; ?>
|
gpl-3.0
|
FJD-CEPH/aCNViewer
|
code/FileHandler.py
|
21032
|
''' Team: - Prapat Suriyaphol
- Masao Yamaguchi
- Victor Renault
Research project: Trans-ethnic Genomics Study of Multigenic Disorders
by Japan/France International Collaboration
Project: Set up a database based system to help the study
Research director: Dr. Fumihiko Matsuda '''
import types
import os
import glob
import gzip
from Utilities import Utilities, getLastErrorMessage
from ObjectBase import *
try:
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Color, Alignment
except ImportError:
# print 'Warning: module openpyxl could not be loaded'
Workbook = PatternFill = Color = None
def getFileList(dirName, afterFileName=None):
fileList = None
if isinstance(dirName, types.ListType):
fileList = dirName
else:
if ',' in dirName:
fileList = dirName.split(',')
elif Utilities.doesDirExist(dirName):
fileList = glob.glob(os.path.join(dirName, '*'))
elif Utilities.doesFileExist(dirName):
fileList = [dirName]
else:
fileList = glob.glob(dirName)
if afterFileName:
idx = fileList.index(afterFileName)
print idx, (idx + 1) * 1. / len(fileList)
fileList = fileList[idx:]
return fileList
class FileParser(object):
NO_SPLIT = 0
_sep = '\t'
def __init__(self, fileName):
self.fileName = fileName
def _getFileHandler(self):
if isinstance(self.fileName, types.FileType):
return self.fileName
# print 'TYPE', type(self.fileName)
fileExt = Utilities.getFileExtension(self.fileName)
if fileExt == 'gz':
# fh = Utilities.popen('cat %s | gunzip' % self.fileName)
fh = os.popen('gunzip -c %s 2> /dev/null' % self.fileName)
# fh = gzip.open(self.fileName)
elif fileExt == 'xz':
fh = os.popen('xz -dc ' + self.fileName)
elif fileExt == 'bz2':
fh = os.popen('bunzip2 -c ' + self.fileName)
else:
fh = open(self.fileName)
return fh
def readFileAtOnce(self):
fh = self._getFileHandler()
lineList = fh.readlines()
fh.close()
return lineList
def _stripLine(self, line):
line = '0' + line
line = line.strip('\n\r')
return line[1:]
def getColumnNameToIdxDict(self):
splittedLine = self.getSplittedLine()
colDict = dict([[colName, idx]
for idx, colName in enumerate(splittedLine)])
if len(colDict) != len(splittedLine):
print splittedLine
raise NotImplementedError
return colDict
def getSplittedLine(self, char=None):
if char is None:
char = self._sep
line = self.getNextLine()
if line is None:
return
if char == self.NO_SPLIT:
return line
if char is None:
return line.split()
return line.split(char)
def getNextLine(self):
raise NotImplementedError
class ReadFileAtOnceParser(FileParser):
def __init__(self, fileName, bufferSize=10000, sep='\t'):
super(ReadFileAtOnceParser, self).__init__(fileName)
self.__fh = self._getFileHandler()
self.__bufferSize = bufferSize
self.__lineList = self.__getLineListFromFile()
self._sep = sep
def __iter__(self):
while self.hasLinesLeft():
yield self.getSplittedLine(self._sep)
def __len__(self):
return len(self.__lineList)
def __getLineListFromFile(self):
if self.__bufferSize:
return self.__fh.readlines(self.__bufferSize)
return self.__fh.readlines()
def getLineList(self):
if self.__bufferSize:
raise NotImplementedError
return self.__lineList
def getNextLine(self):
if len(self.__lineList) == 0:
return
line = self.popFirst()
if line is None:
return
return self._stripLine(line)
def hasLinesLeft(self):
return len(self.__lineList) > 0
def popFirst(self):
line = self.__lineList.pop(0)
if len(self.__lineList) == 0:
self.__lineList = self.__getLineListFromFile()
return line
def restore(self, elt):
if isinstance(elt, types.ListType):
elt = self._sep.join(elt)
self.__lineList = [elt] + self.__lineList
class ExcelCell:
def __init__(self, value, color=None, bgColor=None, style=None,
alignment=None, otherParamDict=None):
self.value = value
self.color = color
self.bgColor = bgColor
self.style = style
self.alignment = alignment
self.otherParamDict = otherParamDict
class CsvFileWriter:
def __init__(self, fileName, fileOption='w', exportInExcel=False,
useBuffer=True, otherParamDict=None):
self._fileName = fileName
self.__isExcel = False
self.__otherParamDict = otherParamDict
if isinstance(fileName, types.FileType):
self.__fh = fileName
exportInExcel = False
else:
fileExt = Utilities.getFileExtension(fileName)
if fileExt == 'gz':
# self.__fh = gzip.open(fileName, fileOption)
# from subprocess import Popen,PIPE
# GZ = Popen('gzip > %s' % fileName,stdin=PIPE,shell=True)
# self.__fh = GZ.stdin
# self.__gz = GZ
self.__fh = open(fileName[:-3], fileOption)
elif fileExt == 'xlsx':
self.__wb = Workbook(guess_types=True)
self.__fh = self.__wb.active
if otherParamDict and 'title' in otherParamDict:
self.__fh.title = otherParamDict['title']
self.__isExcel = True
self.__lineNb = 1
else:
self.__fh = open(fileName, fileOption)
if Utilities.getFileExtension(fileName) == 'xls':
exportInExcel = False
self.__exportInExcel = exportInExcel
self.__useBuffer = useBuffer
self.__buffer = []
def _addNewWorkSheet(self, title=None):
paramDict = {}
if title:
paramDict['title'] = title
self.__fh = self.__wb.create_sheet(**paramDict)
self.__lineNb = 1
def __del__(self):
if self.__isExcel:
self.__wb.save(self._fileName)
return
if not hasattr(self.__fh, 'closed') or not self.__fh.closed:
self.close()
if self.__exportInExcel:
self.exportInExcelFormat()
def writeListsInColumn(self, *args):
lineToWriteList = []
while True:
lineToWrite = []
isFinished = True
for list in args:
if len(list):
value = list.pop(0)
isFinished = False
else:
value = ''
lineToWrite.append(value)
if isFinished:
break
lineToWriteList.append(lineToWrite)
self.writeAllLinesAtOnce(lineToWriteList)
def __convertAllEltInListToString(self, eltList):
if isinstance(eltList, types.StringType):
return [eltList]
return [str(elt) for elt in eltList]
def _writeAndEmptyBuffer(self):
self.__fh.write('\n'.join(self.__buffer) + '\n')
self.__buffer = []
def __writeExcelLine(self, fieldList):
line = []
cellToChangeDict = {}
for i, field in enumerate(fieldList):
if i < 26:
column = chr(ord('A') + i)
else:
column = 'A' + chr(ord('A') + i % 26)
if isinstance(field, ExcelCell):
cellToChangeDict['%s%d' % (
column, self.__lineNb)] = field.color, field.bgColor,
field.style, field.alignment, field.otherParamDict
field = field.value
line.append(field)
self.__fh.append(line)
for cellKey, (color, bgColor, style, alignment, otherParamDict) in \
cellToChangeDict.iteritems():
if color or style:
paramDict = {}
if color:
paramDict['color'] = color
if style:
if style == 'italic':
paramDict['italic'] = True
elif style == 'bold':
paramDict['bold'] = True
if otherParamDict:
paramDict.update(otherParamDict)
try:
newFont = self.__fh[cellKey].font.copy(**paramDict)
except:
print paramDict, cellKey
print len(fieldList), fieldList
raise
self.__fh[cellKey].font = newFont
if bgColor:
self.__fh[cellKey].fill = PatternFill(
"solid", fgColor=Color(bgColor))
if alignment or (self.__otherParamDict and
'alignment' in self.__otherParamDict):
if not alignment:
alignment = self.__otherParamDict['alignment']
self.__fh[cellKey].alignment = Alignment(**alignment)
self.__lineNb += 1
def write(self, fieldList, sep='\t'):
if self.__isExcel:
self.__writeExcelLine(fieldList)
return
fieldList = self.__convertAllEltInListToString(fieldList)
fieldStr = sep.join(fieldList)
if self.__useBuffer:
self.__buffer.append(fieldStr)
else:
self.__fh.write(fieldStr + '\n')
if self.__useBuffer and len(self.__buffer) >= 20000:
self._writeAndEmptyBuffer()
def writeAllLinesAtOnce(self, lineList, sep='\t'):
lineList = [sep.join(self.__convertAllEltInListToString(
fieldList)) for fieldList in lineList]
self.__fh.write('\n'.join(lineList) + '\n')
def close(self):
if self.__isExcel:
self.__wb.save(self._fileName)
return
if len(self.__buffer):
self._writeAndEmptyBuffer()
if not hasattr(self.__fh, 'closed') or not self.__fh.closed:
self.__fh.close()
try:
self.__fh.closed = True
except AttributeError:
pass
if self._fileName[-3:] == '.gz':
# self.__gz.wait()
Utilities.mySystem('gzip -f %s' % self._fileName[:-3])
def exportInExcelFormat(self):
if not self.__fh.closed:
self.close()
self.excelfileName = Utilities.createExcelFileFromFileAndReturnName(
self._fileName)
class SaveFileInRepository:
def getArchiveFileName(self, obj):
dateTag = obj.getDateTag()
timeStampStr = dateTag.strftime("%Y%m%d_%H%M%S")
return '.'.join([obj.getFileName(), timeStampStr])
def save(self, obj):
obj._archiveFileName = self.getArchiveFileName(obj)
newFileName = os.path.join(obj.getSaveDir(), obj._archiveFileName)
try:
os.rename(obj.getOriginalFileName(), newFileName)
except:
print 'Can not rename file from "%s" to "%s"' % (
obj.getOriginalFileName(), newFileName)
raise
class FileNameGetter:
def __init__(self, fileName):
self.__fileName = fileName
self.__fileExt = Utilities.getFileExtension(fileName)
def get(self, newFileExt, checkFileNames=True):
shift = 0
if newFileExt[0] in ['_', '.']:
shift = -1
newFileName = self.__fileName[
:-len(self.__fileExt) + shift] + newFileExt
if checkFileNames and newFileName == self.__fileName:
raise NotImplementedError('new file name is the same as original \
one: file = "%s", fileExt = [%s], newFileExt = [%s]' % (self.__fileName,
self.__fileExt,
newFileExt))
# if '..' in newFileName:
# print self.__fileName, self.__fileExt, newFileExt, newFileName
# raise NotImplementedError
return newFileName
class FastaSeq:
def __init__(self, seqName, seq):
self.seqName = seqName
self.seq = seq
def getShortSeqName(self):
partList = self.seqName.split('|')
seqName = self.seqName
if partList[0] == '>gi':
seqName = '|'.join([partList[1], partList[3]])
else:
seqName = seqName.lstrip('>').strip().split()[0]
return seqName.lstrip('>').strip()
def __len__(self):
return len(self.seq)
def writeInFastQ(self, step, fh, fh2=None, insertSize=None, test=None):
qualityStr = 'I' * step
seqName = self.getShortSeqName()
end = len(self) - step + 1
if insertSize:
end -= (insertSize + step)
for i in xrange(end):
header = '%s|%d-%d' % (seqName, i + 1, i + step)
header += '/%d'
for line in ['@%s' % (header % 1), self.seq[i:i + step], '+',
qualityStr]:
fh.write(line)
if fh2:
seq2 = self.seq[i + step +
insertSize:i + 2 * step + insertSize]
if not test:
seq2 = Sequence.getReverseComplementString(seq2)
for line in ['@%s' % (header % (2)), seq2, '+', qualityStr]:
fh2.write(line)
class ParseFastaFile(object):
'''
classdocs
'''
def __init__(self, name):
'''
Constructor
'''
self.filename = name
self.sequences = {}
def _getFastaSeqForChr(self, chrName):
fh = ReadFileAtOnceParser(self.filename)
while fh.hasLinesLeft():
fastaSeq = self._getNextSeqFromFh(fh)
if not fastaSeq:
break
fastaSeqChrName = fastaSeq.getShortSeqName().split('_')[0]
if fastaSeqChrName != chrName:
print 'Passing [%s]' % fastaSeqChrName
continue
return fastaSeq
def _getNextSeqFromFh(self, fh, allowEmptyLines=False):
header = fh.popFirst().strip()
if not header:
return
seq = ''
while fh.hasLinesLeft():
currentSeq = fh.popFirst().strip()
if allowEmptyLines and not currentSeq:
break
if currentSeq[0] == '>':
fh.restore(currentSeq)
break
seq += currentSeq
if header[0] != '>':
raise NotImplementedError(
'Expecting ">" as 1st header character but found [%s]' %
header)
return FastaSeq(header, seq)
def _getIdxFileName(self):
return self.filename + '_idx'
def _createFastaIdxFile(self):
idxFile = self._getIdxFileName()
if not os.path.isfile(idxFile):
Utilities.mySystem('grep ">" %s > %s' % (self.filename, idxFile))
def _getSequenceNameListFromFile(self, filtered=False, excludeMT=False):
self._createFastaIdxFile()
fh = open(self._getIdxFileName())
for seqName in fh:
seqName = seqName.lstrip('>').strip().split()[0]
if filtered:
seqName = FastaSeq(
seqName, None).getShortSeqName().split('_')[0]
hasChrPrefix = seqName[:3] == 'chr'
if (not hasChrPrefix and
(not ValueParser().isNb(seqName) and len(seqName) not in
[1, 2])) or (hasChrPrefix and
not ValueParser().isNb(seqName[3:]) and
len(seqName) not in [4, 5]):
continue
if not ValueParser().isNb(seqName.replace('chr', '')) and \
seqName.replace('chr', '') not in ['X', 'Y', 'M', 'MT']:
continue
if excludeMT and seqName in ['M', 'MT', 'chrM', 'chrMT']:
continue
yield seqName
fh.close()
def parse(self):
descriptions = {}
if self.filename.split('.')[-1] == 'gz':
import gzip
infile = gzip.open(self.filename, 'r')
else:
infile = open(self.filename, 'r')
lines = infile.readlines()
infile.close()
curDescription = ''
for l in lines:
if l.startswith('#') or l == '\n':
pass
elif l.startswith('>'):
print l
curDescription = l.replace('>', '')
self.sequences[curDescription] = ''
name = l.split('|')[3]
if name not in descriptions:
descriptions[name] = 1
else:
descriptions[name] += 1
else:
self.sequences[curDescription] += l.replace('\n', '')
for d in self.sequences:
print d
class MergeAnnotationFiles:
def __getChrListFromIdxFile(self, fileName):
fh = ReadFileAtOnceParser(fileName)
chrList = []
for splittedLine in fh:
chrList.append(splittedLine[0])
return chrList
def __getChrListFromRefFile(self, fileName):
if Utilities.getFileExtension(fileName) == 'sizes':
return self.__getChrListFromIdxFile(fileName)
idxFileName = fileName + '_idx'
if not os.path.isfile(idxFileName):
cmd = 'grep ">" %s > %s' % (fileName, idxFileName)
Utilities.mySystem(cmd)
fh = ReadFileAtOnceParser(idxFileName)
chrList = []
for splittedLine in fh:
chrName = splittedLine[0].lstrip('>').split('|')[0].strip()
chrList.append(chrName.split()[0])
return chrList
def __isRefFileForHuman(self, fileName):
partList = fileName.split(os.path.sep)
for part in partList:
part = part.lower()
if 'homo' in part and 'sapiens' in part:
return True
def __getFileListFromPatternAndChrList(self, pattern, chrList):
fileList = []
for chrName in chrList:
fileName = pattern % chrName
if os.path.isfile(fileName):
fileList.append(fileName)
return fileList
def process(self, pattern, outputFileName, refFileName=None,
hasHeader=None, chrNameList=None):
chrList = range(1, 23) + ['X', 'Y', 'MT', 'M']
if refFileName and not self.__isRefFileForHuman(refFileName):
chrList = self.__getChrListFromRefFile(refFileName)
if chrNameList:
chrList = chrNameList
print ':' * 50
print pattern, outputFileName, chrList
fileList = self.__getFileListFromPatternAndChrList(pattern, chrList)
if not fileList and chrList:
if chrList[0][:3] == 'chr':
fileList = self.__getFileListFromPatternAndChrList(
pattern, [chrName[3:] for chrName in chrList])
else:
fileList = self.__getFileListFromPatternAndChrList(
pattern, ['chr%s' % chrName for chrName in chrList])
# os.system('cat %s > %s' % (' '.join(fileList), outputFileName))
toCompress = False
if outputFileName[-3:] == '.gz':
outputFileName = '.'.join(outputFileName.split('.')[:-1])
toCompress = True
if not fileList:
print pattern, outputFileName, chrList, fileList
raise NotImplementedError
if hasHeader:
cmd = 'head -1 %s > %s' % (fileList[0], outputFileName)
if os.path.basename(fileList[0]).split('.')[-1] == 'gz':
cmd = 'zcat %s | head -1 > %s' % (fileList[0], outputFileName)
Utilities.mySystem(cmd)
for fileName in fileList:
if os.path.basename(fileName).split('.')[-1] == 'gz':
cmd = 'zcat'
if hasHeader:
cmd = "zcat %s | sed -n '1!p' >> %s" % (
fileName, outputFileName)
else:
cmd += ' %s >> %s' % (fileName, outputFileName)
else:
cmd = 'cat'
if hasHeader:
cmd = "sed -n '1!p'"
cmd += ' %s >> %s' % (fileName, outputFileName)
Utilities.mySystem(cmd)
if toCompress:
Utilities.mySystem('gzip %s' % outputFileName)
def run(options, args):
print FileNameGetter(options.fileName).get(options.fileExt)
runFromTerminal(__name__, [CommandParameter('f', 'fileName', 'string'),
CommandParameter('F', 'fileExt', 'string')], run)
|
gpl-3.0
|
openssbd/OpenSSBD
|
SSBD/static/WEB/js/view4d.js
|
45132
|
<script>
var bdml_id = {{ bdml_id }};
var time_t = {{ t }};
var last_t = 0;
var base_url = "/SSBD/";
var ssbd_url;
var scale_url = base_url+"api/v1/scale/"+bdml_id+"/";
ssbd_url = base_url+"BDML/vertices/"+bdml_id+"/t/"+time_t+"/etype/";
console.log(ssbd_url);
var param = "?callback=?"; // for allowing cross domain query
var camera, controls, scene, renderer;
var geometry;
var line=[];
var sphere=[];
var points;
var basic_material;
var lambert_material;
var mouseX = 300;
var mouseY = 300;
var line_error = 0;
var point_error = 0;
var sphere_error = 0;
var j = 0; // index for line, sphere
var camx = {{ cam_x }};
var camy = {{ cam_y }};
var camz = {{ cam_z }};
var avgx = {{ avgx }};
var avgy = {{ avgy }};
var avgz = {{ avgz }};
var xmax = {{ xmax }};
var ymax = {{ ymax }};
var zmax = {{ zmax }};
var xmin = {{ xmin }};
var ymin = {{ ymin }};
var zmin = {{ zmin }};
var xscale = {{ xscale }};
var yscale = {{ yscale }};
var zscale = {{ zscale }};
var scaleup = {{ scaleup }};
var tunit = '{{ tunit }}';
var tscale = {{ tscale }};
// console.log("num_components="+num_components+" num_entities="+num_entities)
// alert("num_components="+num_components+" num_entities="+num_entities)
// max_tp is the maximum number of time points.
// Currently in order to make the viewer work for Kimura data, it is set to use a hard code time scale of 0.01, i.e. 1/100
// so for time pt 100, we call it timept 1 instead in the actual code.
// scaletime is recorded in each of the json files, so that it provide a record that the timept was shrunk 1/100 times.
if (max_tp > 10000){
var scaletime = 0.01;
}
else {
var scaletime = 1;
}
// var progresspct = 40;
function updateProgressBar(){
filecount++;
// console.log("filecount=%d", filecount);
progresspct = Math.floor( filecount / totalnumfile * 100 );
$('#progressbar').progressbar({value : progresspct});
// console.log("filecount=%d, totalnumfile=%d, progresspct=%d", filecount, totalnumfile, progresspct);
var msg = "LOADING ...... "+filecount+"/"+totalnumfile+" ("+progresspct+"% )";
// console.log(msg)
$( "#messagetxt" ).val( msg );
if (progresspct == 100){
$('#progressbar').progressbar({complete: function(){$("#messagetxt").val("LOADING 100% Complete")}})
}
return progresspct;
}
function SSBDviewStart(){
//grab our container div
var container = document.getElementById("container");
if ( ! Detector.webgl ) {
var warning = Detector.getWebGLErrorMessage();
alert("Cannot detect WebGL, please enable WebGL or use another browser");
document.getElementById('container').appendChild(warning);
}
// create a Three.js renderer and add it to container div
renderer = new THREE.WebGLRenderer();
renderer.setSize(container.offsetWidth, container.offsetHeight)
container.appendChild(renderer.domElement);
// create a new Three.js scene
scene = new THREE.Scene();
//creat a camera and add it to the scene
camera = new THREE.PerspectiveCamera(45, container.offsetWidth/container.offsetHeight, 1, 6000);
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 0.8;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = false;
controls.dynamicDampingFactor = 0.5;
controls.CAMERA_RADIUS =20;
if( camz == 0 ){
camz = 500;
}
// controls.target.set(camx,cam, camz);
var midx = ((xmax-xmin)/2);
var midy = ((ymax-ymin)/2);
var midz = ((zmax-zmin)/2);
// controls.target.set(midx*xscale*scaleup,midy*yscale*scaleup,midz*zscale*scaleup);
controls.target.set(midx*scaleup,midy*scaleup,midz*scaleup);
controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]
controls.addEventListener( 'change', render );
if ({{ zscale }} == 0){
zscale = 1;
}
// LIGHT
var light = new THREE.PointLight(0xffffff);
// alert("camx="+camx+" camy="+camy+" camz="+camz);
light.position.set(camx*2, camy*2, camz*10);
scene.add(light);
// need to add an ambient light
// for ambient colors to be visible
// make the ambient light darker so that
// it doesn't overwhelm (like emmisive light)
var light2 = new THREE.AmbientLight(0x333333);
light2.position.set( light.position );
scene.add(light2);
resetCamera();
scene.add(camera);
makeGrid();
makeCoordinateArrows();
line_error = SSBDviewDrawlines();
point_error = SSBDviewDrawpoints();
sphere_error = SSBDviewDrawspheres();
// VisibleLines();
animate();
function resetCamera(){
// camera.position.set (camx*2,camy*2,camz*2);
camera.position.set (camx,camy,camz*7);
controls.target.set(camx, camy, camz);
}
/** INNACCESSIBLE OBJECTS **/
///////////////////
// GUI SETUP //
///////////////////
var gui = new dat.GUI({ autoPlace: true });
document.getElementById('gui-container').appendChild(gui.domElement);
var parameters =
{
resetCam: function() { resetCamera(); },
rotatevisible : false,
gridvisible : false,
axisvisible : true,
colour : "#ffffff",
material: "Lambert",
objectvisible : true,
// scalefactor: scaleup,
};
// GUI -- parameters
gui.add( parameters, 'resetCam' ).name("Reset Camera");
var rotationVisibility = gui.add( parameters, 'rotatevisible').name('Toggle Rotate').listen();
var gridVisibility = gui.add( parameters, 'gridvisible').name('Toggle Grid').listen();
var axisVisibility = gui.add( parameters, 'axisvisible').name('Toggle Axis').listen();
// var objectVisibility = gui.add( parameters, 'objectvisible').name('Toggle Objects').listen();
// var objectColour = gui.addColor( parameters, 'colour').name('Colour').listen();
// var objectMaterial = gui.add( parameters, 'material', [ "Lambert", "Wireframe" ] ).name('Material Type').listen();
/*
var timeMin = gui.add( parameters, 'timept_min').min({{ min_t }}).max({{ max_t}}).step(1).name('Time Pt from').listen();
var timeMax = gui.add( parameters, 'timept_max').min({{ min_t }}).max({{ max_t}}).step(1).name('Time Pt to').listen();
*/
rotationVisibility.onChange(function(gvalue){
updateRotate();
});
gridVisibility.onChange(function(gvalue){
updateGrid();
});
axisVisibility.onChange(function(avalue){
updateAxis();
});
/*
objectVisibility.onChange(function(avalue){
updateObject();
});
*/
/*
objectColour.onChange(function(cvalue){
updateObjectColour();
});
*/
/*
objectMaterial.onChange(function(mvalue){
updateSphereObject();
});
*/
function removeObject(){
if ( line != [] ){
line.forEach(function(lvalue){
// console.log(lvalue);
scene.remove(lvalue);
});
} // end if line
if ( sphere !== []){
for(i=0; i<sphere.length; i=i+1) {
// console.log("sphere.length="+sphere.length);
// console.log("i="+i);
scene.remove(sphere[i]);
}
}
if ( points ){
scene.remove(points);
}
render();
} // end removeObject
function updateObject(){
if ( line != [] ){
line.forEach(function(lvalue){
console.log(lvalue);
lvalue.visible = parameters.objectvisible;
});
} // end if line
if ( sphere !== []){
for(i=0; i<sphere.length; i=i+1) {
console.log("sphere.length="+sphere.length);
console.log("i="+i);
sphere[i].visible = parameters.objectvisible;
}
}
if ( points ){
points.visible = parameters.objectvisible;
}
render();
} // end updateObject
function updateObjectColour(){
if ( line != [] ){
line.forEach(function(lvalue){
console.log(lvalue);
lvalue.material.color.setHex( parameters.colour.replace("#", "0x"));
});
}
if ( sphere !== []){
for(i=0; i<sphere.length; i=i+1) {
console.log("sphere.length="+sphere.length);
console.log("i="+i);
sphere[i].material.color.setHex( parameters.colour.replace("#", "0x"));
}
}
if ( points ){
points.material.color.setHex( parameters.colour.replace("#", "0x"));
}
render();
}
function updateSphereObject(){
var newMaterial;
var matvalue = parameters.material;
var matcolour = parameters.colour.replace("#","0x");
console.log(matcolour)
if ( sphere !== []){
if (matvalue == "Wireframe"){
for(i=0; i<sphere.length; i=i+1) {
sphere[i].material = basic_material;
sphere[i].material.color.setHex( matcolour );
sphere[i].material.needsUpdate = true;
}
} // end if Basic
else if (matvalue == "Lambert"){
for(i=0; i<sphere.length; i=i+1) {
sphere[i].material = lambert_material;
sphere[i].material.color.setHex( matcolour );
sphere[i].material.needsUpdate = true;
}
} // end if lambert
// newMaterial = new THREE.MeshBasicMaterial( { wireframe: true } );
// sphere.material = basic_material;
render();
} // end if sphere
} // end updateSphereObject
var cam_rotation = false;
function updateRotate(){
cam_rotation = parameters.rotatevisible;
render();
}
function rotation_cam(){
var uscale;
var timer = Date.now() * 0.0004;
// camera.position.x = 1000*Math.cos(timer);
var r = Math.sqrt(Math.pow((camx-avgx),2)+Math.pow((camy-avgy), 2));
if(xscale < zscale){
uscale = xscale;
}
else {
uscale = zscale;
}
camera.position.x = (camx+r*Math.cos(timer)*uscale*scaleup*3);
// camera.position.x = (controls.position.x+r*Math.cos(timer)*uscale*scaleup*3);
// camera.position.y += (- mouseY - camera.position.y)*0.05;
camera.position.z = (camz+r*Math.sin(timer)*uscale*scaleup*3);
// camera.position.z = (controls.position.z+r*Math.sin(timer)*uscale*scaleup*3);
camera.lookAt(controls.target);
} // end rotation_cam
/* GRID */
var grid;
function makeGrid() {
var gridGeometry = new THREE.Geometry();
var i;
var xmax = {{ xmax }};
var ymax = {{ ymax }};
var xmin = {{ xmin }};
var ymin = {{ ymin }};
// var int = ( xmax - xmin )*xscale*scaleup/10;
// var xmargin = xmax-xmin;
// var ymargin = ymax-ymin;
// var gridminx = (xmin-xmargin)*xscale*scaleup;
// var gridmaxx = (xmax+xmargin)*xscale*scaleup;
// var gridminy = (ymin-ymargin)*yscale*scaleup;
// var gridmaxy = (ymax+ymargin)*yscale*scaleup;
var int = ( xmax - xmin )/10;
var xmargin = xmax-xmin;
var ymargin = ymax-ymin;
var gridminx = (xmin-xmargin);
var gridmaxx = (xmax+xmargin);
var gridminy = (ymin-ymargin);
var gridmaxy = (ymax+ymargin);
console.log("gridminx="+gridminx+" gridminy="+gridminy+" int="+int);
for(i=gridminx; i<gridmaxx; i=i+int) {
gridGeometry.vertices.push( new THREE.Vector3( i, gridminy, 0 ) );
gridGeometry.vertices.push( new THREE.Vector3( i, gridmaxy, 0 ) );
}
for(i=gridminy; i<gridmaxy; i=i+int) {
gridGeometry.vertices.push( new THREE.Vector3( gridminx, i, 0 ) );
gridGeometry.vertices.push( new THREE.Vector3( gridmaxx, i, 0 ) );
}
var gridMaterial = new THREE.LineBasicMaterial( { color: 0xBBBBBB } );
grid = new THREE.Line(gridGeometry, gridMaterial, THREE.LinePieces);
grid.visible = false;
scene.add( grid );
render();
return grid;
}
function updateGrid(){
grid.visible = parameters.gridvisible;
render();
}
/* COORDINATE ARROWS */
var coordinateArrows;
function makeCoordinateArrows() {
coordinateArrows = new THREE.Object3D();
var org = new THREE.Vector3( 0, 0, 0);
var dir = new THREE.Vector3( 0, 0, 1);
coordinateArrows.add( new THREE.ArrowHelper( dir, org, 8, 0x0000FF ) ); // Blue = z
dir = new THREE.Vector3( 0, 1, 0 );
coordinateArrows.add( new THREE.ArrowHelper( dir, org, 8, 0x00FF00 ) ); // Green = y
dir = new THREE.Vector3( 1, 0, 0 );
coordinateArrows.add( new THREE.ArrowHelper( dir, org, 8, 0xFF0000 ) ); // Red = x
scene.add( coordinateArrows );
render();
return coordinateArrows;
}
function updateAxis(){
coordinateArrows.traverse(function (child){
child.visible = parameters.axisvisible;
});
render();
}
function SSBDviewDrawlines(){
// ** Global variable ** entity is an array of objects {id: entityid, time: t, line: l}
entity = new Array();
// var material = new THREE.LineBasicMaterial( {color: 0xffffff, opacity: 1, lineWidth:3, visible:true})
var material = new THREE.LineBasicMaterial( {color: 0xffffff, opacity: 1, lineWidth:3})
var lastid = 0;
// var datatime = 0;
var entityid=0;
var listjsonstring = 'data/ssbd_id_'+bdml_id+'/line.json';
// alert("listjsonstring="+listjsonstring);
var jsonlistfile = "{% static 'WEB/'%}"+listjsonstring;
// alert("jsonlistfile="+jsonlistfile);
$.getJSON(jsonlistfile, function(filedata) {
console.log("filedata=%O", filedata)
filestoload=filedata.filelist;
console.log("filestoload=%O", filestoload)
totalnumfile=totalnumfile+filestoload.length;
console.log("totalnumfile=%O", totalnumfile)
}) // getJSON
.done(function(){
while(filestoload.length!=0) {
// console.log("filestoload.length=%d", filestoload.length);
loadstaticlinefiles();
// VisibleLines();
}
}) // end .done
.error(function(jqXhr, textStatus, error) {
console.log("ERROR: " + textStatus + ", " + error);
}); // end error
function loadstaticlinefiles(){
var k = 0; // line index
var file = filestoload.shift();
console.log("file=%s", file);
var a = $.getJSON(file, function(data) {
var entityid = data.vertices[0];
var datatime = data.vertices[5];
console.log("Json has data property. entityid="+entityid);
console.log("Json has data property. datatime="+datatime);
if (data.hasOwnProperty('scale_array')){
var scale_array = JSON.parse(data.scale_array);
scaletime = scale_array[5];
console.log("Json has scale_array property. scaletime="+scaletime);
}
else{
scaletime = 1;
}
// alert("scale_array="+scale_array)
// alert("scale_array[5]="+scale_array[5])
// console.log("loadstaticlinefiles.scaletime="+scaletime)
if (data.hasOwnProperty('timept')){
var lntimept = parseInt(data.timept);
// console.log("Json has timept property. lntimept="+lntimept);
}
else{
lntimept = datatime/tscale;
// console.log("Json has NO timept property. lntimept="+lntimept);
}
// console.log("entityid="+entityid+" data.vertices[0]="+data.vertices[0]+" datatime="+datatime)
geometry = new THREE.Geometry();
geometry.dynamic = true;
geometry.verticesNeedUpdate = true;
geometry.normalsNeedUpdate = true;
// console.log("locadstaticfiles->getJSON->time_t="+time_t);
if(data.vertices !== "error"){
// data array is in the form [entity_id, coord_id,x,y,z,t ... ]
// console.log("locadstaticfiles->getJSON->j=%d",j);
// entity[datatime/tscale]=new Array();
entity[lntimept]=new Array();
for(var i= 0, len = data.vertices.length; i < len; i=i+6){
// if it is the same line entity, keep ending vertices
// console.log("entityid=%d, data.vertices[%d]=%d", entityid, i, data.vertices[i])
if (data.vertices[i] == entityid){
geometry.vertices.push(new THREE.Vector3(
(data.vertices[i+2]),
(data.vertices[i+3]),
data.vertices[i+4]));
// datatime = data.vertices[i+5]
}
else {
// if it is a different entity, add the current vertices to a new line
// and add to the entity[j]; start a new line with a new geometry, update entityid
var dataline = new THREE.Line(geometry, material);
// Adding the new line into an array of lines entity
//finish ending a new line entity[j], now start a new line.
geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(
(data.vertices[i+2]),
(data.vertices[i+3]),
data.vertices[i+4]));
// datatime = data.vertices[i+5]
dataline.visible = false;
entity[lntimept][k] = {id:entityid, time:datatime, line:dataline};
//starting a new line here, reset entityid
entityid = data.vertices[i];
// show it onscreen
// console.log("entity[%d][%d].line=%f", lntimept, k, entity[lntimept][k]);
scene.add(entity[lntimept][k].line);
k=k+1;
} // end else
// if there is only 1 line!!
if(k==0) {
var dataline = new THREE.Line(geometry, material);
dataline.visible = false;
entity[lntimept][k] = {id:entityid, time:datatime, line:dataline};
scene.add(entity[lntimept][k].line);
}
//finish ending a new line entity[j]
}; // end for loop
} //end if vertices length
else{
line_error = 1;
}
} // function data
) // getJSON ssdb_url
.fail(function(){
console.log("error on getJSON fail")
})
// return {"line_error" : line_error}
.done(function(){
updateProgressBar();
})
}; // end of loadstaticfiles
}; // end of SSBDviewDrawlines
function SSBDviewDrawpoints(){
// * Global variables * entitypt is an array of objects {id: entityptid, time: t, point: l}
entitypt = new Array();
var material = new THREE.ParticleBasicMaterial( {color: 0xffffff, size:1})
var lastid = 0;
// var datatime = 0;
var entityptid=0;
var listjsonstring = 'data/ssbd_id_'+bdml_id+'/point.json';
// alert("listjsonstring="+listjsonstring);
var jsonlistfile = "{% static 'WEB/'%}"+listjsonstring;
// alert("jsonlistfile="+jsonlistfile);
$.getJSON(jsonlistfile, function(filedata) {
// console.log("filedata=%O", filedata)
filestoload=filedata.filelist;
// console.log("filestoload=%O", filestoload)
}) // getJSON
.done(function(){
time_t = min_t;
// console.log("Original filestoload.length=%d", filestoload.length);
totalnumfile=totalnumfile+filestoload.length;
while(filestoload.length!=0) {
// console.log("filestoload.length=%d", filestoload.length);
loadptstaticfiles(6);
}
// console.log("done loading");
}) // end .done
.error(function(jqXhr, textStatus, error) {
console.log("ERROR: " + textStatus + ", " + error);
});
function loadptstaticfiles(interval){
var file = filestoload.shift();
var a = $.getJSON(file, function(data) {
var pttimept = parseInt(data.timept);
var entityptid = data.vertices[0];
var datatime = data.vertices[5];
if(data.vertices !== "error"){
// data array is in the form [entity_id, coord_id,x,y,z,t ... ]
// ** Global variable ** entitypt for storing entity points
entitypt[pttimept]=new Array();
// visibilitypt[pttimept] = false;
var geometry = new THREE.Geometry();
var datapoint = new THREE.ParticleSystem(geometry, material);
var j=0; // point index
for(var i= 0, len = data.vertices.length; i < len; i=i+interval){
geometry.dynamic = true;
geometry.verticesNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.vertices.push(new THREE.Vector3(
(data.vertices[i+2]),
(data.vertices[i+3]),
data.vertices[i+4])
);
// ToDo: how to automatically calculate the size??
datapoint.material.size=0.01;
datapoint.visible = false;
// datapoint.visible = function(pttimept){ return visibilitypt[pttimept]};
entityptid = data.vertices[i];
// Adding new point into an array of point entity
entitypt[pttimept][j] = {id:entityptid, time:datatime, point:datapoint};
// console.log("entitypt[%d][%d]=%0", pttimept, j, entitypt[pttimept][j]);
//starting a new pt here, reset entityid
// show it onscreen
// scene.add(entitypt[pttimept][j].point);
//finish ending a new point entity[j]
j++;
}; // end for loop
// show it onscreen
scene.add(datapoint);
} //end if vertices length
else{
point_error = 1;
}
} // end function data
) // getJSON ssdb_url
.done(function(){
updateProgressBar();
}) // .done function data
.fail(function(){
console.log("error on getJSON fail")
})
}; // end of loadptstaticfiles
}; // end of SSBDviewDrawpoints
function SSBDviewDrawspheres(){
// * Global variables * entitySph is an array of objects {id: entityptid, time: t, sphere: l}
entitySph = new Array();
// checking number of entities read
// var count_entities = 0;
// Default segments and rings size
// var segments = 4, rings = 4;
var segments = 5, rings = 5;
// trying to be adaptive on segments and ring size based on the number of time points.
// ToDo: It should based on the number of entities
if (num_entities < 5000) {
segments = 8;
rings = 8;
} // end if < 70
if (num_entities < 2000) {
segments = 16;
rings = 16;
} // end if < 50
var basic_material = new THREE.MeshBasicMaterial( {color: 0xffffff, wireframe: true, transparent: true} );
var lambert_material = new THREE.MeshLambertMaterial( {color: 0xffffff, opacity: 1, shininess:30} );
var pt_material = new THREE.ParticleBasicMaterial( {color: 0xffffff, size:1})
// var sphere_material = basic_material;
var sphere_material = lambert_material;
var lastid = 0;
// var j = 0; // time pt index
// var datatime = 0;
var entitySphid=0;
var listjsonstring = 'data/ssbd_id_'+bdml_id+'/sphere.json';
// alert("listjsonstring="+listjsonstring);
var jsonlistfile = "{% static 'WEB/'%}"+listjsonstring;
// alert("jsonlistfile="+jsonlistfile);
$.getJSON(jsonlistfile, function(filedata) {
// console.log("filedata=%O", filedata)
filestoload=filedata.filelist;
// console.log("filestoload=%O", filestoload)
}) // getJSON
.done(function(){
time_t = min_t;
totalnumfile=totalnumfile+filestoload.length;
console.log("Original filestoload.length=%d", filestoload.length);
while(filestoload.length!=0) {
console.log("filestoload.length=%d", filestoload.length);
// console.log("count_entities=%d", count_entities);
if(num_components < 25000){
console.log("drawing sphere")
loadsphstaticfiles();
}
else{
console.log("drawing pt")
loadsphptstaticfiles(7);
}
}
console.log("done loading");
}) // end .done
.error(function(jqXhr, textStatus, error) {
console.log("ERROR: " + textStatus + ", " + error);
});
function loadsphstaticfiles(){
var file = filestoload.shift();
console.log("file=%s", file);
var a = $.getJSON(file, function(filedata) {
// console.log("filedata=%0", filedata);
data=filedata; })
.done(function(){
// console.log("data=%0", data);
// console.log("data[timept]="+data["timept"]);
// console.log("data.timept="+data.timept);
// console.log("assigning to pttimept")
var sphtimept = parseInt(data.timept);
// console.log("sphtimept=%d", sphtimept);
var entitySphid = data.vertices[0];
var datatime = data.vertices[5];
// console.log("entityid=%d, data.vertices[0]=%d", entityid, data.vertices[0])
// console.log("entityptid="+entityptid+" data.vertices[0]="+data.vertices[0]+" datatime="+datatime)
group = new THREE.Object3D();
totalgeometry = new THREE.Geometry();
// console.log("locadstaticfiles->getJSON->time_t="+time_t)
// console.log("data.vertices="+data.vertices);
if(data.vertices !== "error"){
// ** Global variable ** entitypt for storing entity points
entitySph[sphtimept]=new Array();
var j=0; // sphere index
// data array is in the form [entity_id, coord_id,x,y,z,t,r ... ]
console.log('vertices.length='+data.vertices.length);
// count_entities = count_entities+data.vertices.length/7;
// console.log('count_entities='+count_entities);
for(var i= 0, len = data.vertices.length; i < len; i=i+7){
var sphere_geometry = new THREE.SphereGeometry(data.vertices[i+6], segments, rings)
var sphere = new THREE.Mesh(sphere_geometry, sphere_material);
// var sphere = new THREE.Mesh(new THREE.SphereGeometry(data.vertices[i+6], segments, rings), sphere_material);
// sphere.position.x.copy(data.vertices[i+2]);
// sphere.position.y.copy(data.vertices[i+3]);
// sphere.position.z.copy(data.vertices[i+4]);
sphere.position.x = data.vertices[i+2];
sphere.position.y = data.vertices[i+3];
sphere.position.z = data.vertices[i+4];
sphere.radius = data.vertices[i+6];
sphere.wireframe = 1;
sphere.visible = false;
// datapoint.visible = function(pttimept){ return visibilitypt[pttimept]};
entitySphid = data.vertices[i];
// Adding new point into an array of point entity
// Todo : inefficient to copy sphere[j] into entitySph. Extend sphere to incorporate time and id will be better.
entitySph[sphtimept][j] = {id:entitySphid, time:datatime, sphere:sphere};
// console.log("entitySph[%d][%d]=%0", sphtimept, j, entitySph[sphtimept][j]);
//starting a new pt here, reset entityid
// show it onscreen
// THREE.GeometryUtils.merge(totalgeometry, entitySph[sphtimept][j].sphere, 0);
group.add(entitySph[sphtimept][j].sphere)
//old deleteable scene.add(entitySph[sphtimept][j].sphere);
//finish ending a new point entity[j]
j++;
}; // end for loop
// show it onscreen
scene.add(group);
// scene.add(new THREE.Mesh(totalgeometry, sphere_material));
updateProgressBar();
} //end if vertices length
else{
point_error = 1;
}
} // .done function data
) // getJSON ssdb_url
.fail(function(){
// console.log("error on getJSON fail")
})
}; // end of loadptstaticfiles
function loadsphptstaticfiles(interval){
var file = filestoload.shift();
console.log("file=%s", file);
var material = new THREE.ParticleBasicMaterial( {color: 0xffffff, size:1})
var a = $.getJSON(file, function(data) {
var pttimept = parseInt(data.timept);
var entityptid = data.vertices[0];
var datatime = data.vertices[5];
if(data.vertices !== "error"){
// data array is in the form [entity_id, coord_id,x,y,z,t ... ]
// ** Global variable ** entitypt for storing entity points
entitypt[pttimept]=new Array();
// visibilitypt[pttimept] = false;
var geometry = new THREE.Geometry();
var datapoint = new THREE.ParticleSystem(geometry, material);
var j=0; // point index
console.log('data.vertices.length='+data.vertices.length);
// count_entities = count_entities+data.vertices.length/7;
for(var i= 0, len = data.vertices.length; i < len; i=i+interval){
geometry.dynamic = true;
geometry.verticesNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.vertices.push(new THREE.Vector3(
(data.vertices[i+2]),
(data.vertices[i+3]),
data.vertices[i+4])
);
// ToDo: how to automatically calculate the size??
datapoint.material.size=0.01;
datapoint.visible = false;
// datapoint.visible = function(pttimept){ return visibilitypt[pttimept]};
entityptid = data.vertices[i];
// Adding new point into an array of point entity
entitypt[pttimept][j] = {id:entityptid, time:datatime, point:datapoint};
// console.log("entitypt[%d][%d]=%0", pttimept, j, entitypt[pttimept][j]);
//starting a new pt here, reset entityid
// show it onscreen
// scene.add(entitypt[pttimept][j].point);
//finish ending a new point entity[j]
j++;
}; // end for loop
// show it onscreen
scene.add(datapoint);
} //end if vertices length
else{
point_error = 1;
}
} // end function data
) // getJSON ssdb_url
.done(function(){
updateProgressBar();
}) // .done function data
.fail(function(){
console.log("error on getJSON fail")
})
}; // end of loadsphptstaticfiles
}; // end of SSBDviewDrawSpheres
function VisibleLines(){
// switching everything off
time_r = time_t;
// console.log("VisibleLines: time_r="+time_r+"; time_t="+time_t);
// console.log("VisibleLines false last_t=%d", last_t);
if (last_t !== time_t) {
// console.log("Checking1 typeof entity[%d]=%0 ...", time_r, entity[time_r]);
if (typeof entity[last_t] !== "undefined") {
// console.log("VisibleLines1 before if entity[%d].length=%d",last_t,entity[last_t].length);
if (entity[last_t].length !== null) {
// console.log("Visibleline2 entity[%d].length=%d",time_r,entity[time_r].length);
for (var i = 0; i < entity[last_t].length; i++) {
// console.log("VisibleLines3 false entity[%d]=%0",i,entity[i]);
entity[last_t][i].line.visible = false;
} // end for
} // end if length
} // end if typeof
// console.log("Checking2 typeof entitypt[%d]=%0 ...", time_r, entitypt[time_r]);
if (typeof entitypt[last_t] !== "undefined") {
// console.log("VisiblePoints1 before if entitypt[%d].length=%d",time_r,entitypt[time_r].length);
if (entitypt[last_t].length !== null) {
// console.log("VisiblePoints2 entitypt[%d].length=%d",time_r,entitypt[time_r].length);
// console.log("Checking3 typeof entitypt[%d]=%0 ...", last_t, entitypt[last_t]);
if (typeof entitypt[last_t] !== "undefined"){
// visibilitypt[last_t] = false;
// console.log("VisiblePoints3 entitypt[%d].length=%d",last_t,entitypt[last_t].length);
for (var i = 0; i < entitypt[last_t].length; i++) {
// console.log("Entering for loop with i=%d", i)
// console.log("VisiblePoints4 false entitypt[%d][%d].point.visible =%s",last_t,i,entitypt[last_t][i].point.visible.valueOf());
entitypt[last_t][i].point.visible = false;
// console.log("VisiblePoints5 false entitypt[%d][%d].point.visible =%s",last_t,0,entitypt[last_t][0].point.visible.valueOf());
}// end for
// console.log("finishing for loop")
}// end if typeof
} // end if length
} // end if typeof
if (typeof entitySph[last_t] !== "undefined") {
// console.log("VisiblePoints1 before if entitypt[%d].length=%d",time_r,entitypt[time_r].length);
if (entitySph[last_t].length !== null) {
// console.log("VisiblePoints2 entitypt[%d].length=%d",time_r,entitypt[time_r].length);
// console.log("Checking3 typeof entitypt[%d]=%0 ...", last_t, entitypt[last_t]);
if (typeof entitySph[last_t] !== "undefined"){
// visibilitypt[last_t] = false;
// console.log("VisiblePoints3 entitypt[%d].length=%d",last_t,entitypt[last_t].length);
for (var i = 0; i < entitySph[last_t].length; i++) {
// console.log("Entering for loop with i=%d", i)
// console.log("VisibleSphere false entitySph[%d][%d].sphere.visible =%s",last_t,i,entitySph[last_t][i].sphere.visible.valueOf());
entitySph[last_t][i].sphere.visible = false;
// console.log("VisibleSphere2 false entitySph[%d][%d].sphere.visible =%s",last_t,i,entitySph[last_t][i].sphere.visible.valueOf());
// console.log("VisiblePoints5 false entitypt[%d][%d].point.visible =%s",last_t,0,entitypt[last_t][0].point.visible.valueOf());
}// end for
// console.log("finishing for loop")
}// end if typeof
} // end if length
} // end if typeof
} // end if only make invisible if last_t is not time_t
// console.log("Checking4 typeof entity[%d]=%0 ...", time_r, entity[time_r]);
if (typeof entity[time_r] !== "undefined") {
// console.log("VisibleLines4 before if entity[%d].length=%d",time_r,entity[time_r].length);
if (entity[time_r].length !== null) {
for (var i = 0; i < entity[time_r].length; i++) {
// console.log("VisibleLines5 true entity[%d][%d]=%O",time_r,i,entity[time_r][i]);
entity[time_r][i].line.visible = true;
// console.debug("setting true for visible for loop entity["+0+"]['line].geometry.vertices=%O",entity[0].line.geometry.vertices);
} // end for
} // end if length
} // end if typeof
// console.log("Checking5 typeof entitypt[%d]=%0 ...", time_r, entitypt[time_r]);
if (typeof entitypt[time_r] !== "undefined") {
// console.log("VisiblePoints false entitypt[%d].point.length=%d",time_r,entitypt[time_r].point.length);
if (entitypt[time_r].length !== null) {
// visibilitypt[time_r] = true;
// console.log("visibilitypt[%d]=%s",time_r, visibilitypt[time_r]);
for (var i = 0; i < entitypt[time_r].length; i++) {
// console.log("Entering for loop with i=%d", i)
// console.log("VisiblePoints6 false entitypt[%d][%d].point.visible =%s",time_r,i,entitypt[time_r][i].point.visible.valueOf());
entitypt[time_r][i].point.visible = true;
// console.log("VisiblePoints7 true entitypt[%d][%d].point.visible =%s",time_r,0,entitypt[time_r][0].point.visible.valueOf());
} // end for
// console.log("finishing for loop")
} // end if length
} // end if typeof
if (typeof entitySph[time_r] !== "undefined") {
// console.log("VisiblePoints false entitypt[%d].point.length=%d",time_r,entitypt[time_r].point.length);
if (entitySph[time_r].length !== null) {
// visibilitypt[time_r] = true;
for (var i = 0; i < entitySph[time_r].length; i++) {
// console.log("Entering for loop with i=%d", i)
// console.log("VisibleSphere3 true entitySph[%d][%d].sphere.visible =%s",time_r,i,entitySph[time_r][i].sphere.visible.valueOf());
entitySph[time_r][i].sphere.visible = true;
// console.log("VisibleSphere4 true entitySph[%d][%d].sphere.visible =%s",time_r,i,entitySph[time_r][i].sphere.visible.valueOf());
// console.log("VisiblePoints7 true entitypt[%d][%d].point.visible =%s",time_r,0,entitypt[time_r][0].point.visible.valueOf());
} // end for
// console.log("finishing for loop")
} // end if length
} // end if typeof
render();
} // end VisibleLines
function render() {
renderer.render( scene, camera );
}
function animate(){
if (cam_rotation == true){
rotation_cam();
}
requestAnimationFrame(animate);
controls.update();
render();
}
$(function() {
$( "#time-slider" ).slider({
range: "min",
min: min_tp,
max: max_tp*scaletime,
// value: Math.floor(time_tp/100)*100,
value: time_tp,
slide: function( event, ui ) { // slide the bar and change the value at #timepoint
$( "#timepoint" ).val( ui.value/scaletime );
$( "#time" ).val( ui.value*tscale );
// last_t = time_t;
last_tp = time_tp;
// time_tp = Math.floor(ui.value/100)*100;
time_tp = ui.value;
last_t = last_tp;
time_t = time_tp;
VisibleLines();
},
stop: function(event, ui){ // when the slider stop, display a new dataset using the stop value
last_t = ui.value;
// last_t = Math.floor(ui.value/100)*100;
// ssbd_url = base_url+"BDML/vertices/"+bdml_id+"/t/"+time_t+"/etype/";
// removeObject();
// line_error = SSBDviewDrawlines();
// point_error = SSBDviewDrawpoints();
// sphere_error = SSBDviewDrawspheres();
} // end of stop
}); // end .slider
$( "#timepoint" ).val( $( "#time-slider" ).slider( "value") );
$( "#tunit" ).val( tunit );
}); //end of time-slider
$(function(){
$("#diccanvas").drawImage({
source:"img/img-z000.jpg",
width: 600,
height: 600,
fromCenter: false
});
img.onload = function() {
var mFocalPlane = 30;
canvas.drawImage(img, 0, mFocalPlane * 300, 300, 300, 0, 0, 300, 300);
}
}); // end of diccanvas
}; // end of SSBDviewStart
</script>
|
gpl-3.0
|
benlaug/labgen-of
|
src/TextProperties.cpp
|
3646
|
/**
* Copyright - Benjamin Laugraud <blaugraud@ulg.ac.be> - 2017
* http://www.montefiore.ulg.ac.be/~blaugraud
* http://www.telecom.ulg.ac.be/labgen
*
* This file is part of LaBGen-OF.
*
* LaBGen-OF 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.
*
* LaBGen-OF 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 LaBGen-OF. If not, see <http://www.gnu.org/licenses/>.
*/
#include <opencv2/imgproc/imgproc.hpp>
#include <labgen-of/TextProperties.hpp>
using namespace std;
using namespace cv;
using namespace ns_labgen_of;
/* ========================================================================== *
* TextProperties *
* ========================================================================== */
TextProperties::TextProperties(
Font font,
double scale,
const Scalar& color,
const Scalar& background_color,
int32_t thickness,
LineType line_type,
Justification justification
) :
font(font),
scale(scale),
color(color),
background_color(background_color),
thickness(thickness),
line_type(line_type),
justification(justification) {
compute_metrics();
}
/******************************************************************************/
TextProperties::Font TextProperties::get_font() const {
return font;
}
/******************************************************************************/
double TextProperties::get_scale() const {
return scale;
}
/******************************************************************************/
const cv::Scalar& TextProperties::get_color() const {
return color;
}
/******************************************************************************/
const cv::Scalar& TextProperties::get_background_color() const {
return background_color;
}
/******************************************************************************/
int32_t TextProperties::get_thickness() const {
return thickness;
}
/******************************************************************************/
TextProperties::LineType TextProperties::get_line_type() const {
return line_type;
}
/******************************************************************************/
TextProperties::Justification TextProperties::get_justification() const {
return justification;
}
/******************************************************************************/
int32_t TextProperties::get_text_height() const {
return text_height;
}
/******************************************************************************/
int32_t TextProperties::get_baseline() const {
return baseline;
}
/******************************************************************************/
int32_t TextProperties::estimate_width(const string& text, double scale) const {
Size text_size = getTextSize(text, font, scale, thickness, nullptr);
return text_size.width;
}
/******************************************************************************/
void TextProperties::compute_metrics() {
Size text_size = getTextSize("Tp", font, scale, thickness, &baseline);
text_height = text_size.height + baseline;
if (line_type == LineType::LINE_ANTI_ALIASED) {
text_height += 4;
baseline += 2;
}
}
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/bitrix/modules/blog/install/components/bitrix/blog.popular_posts/lang/en/.parameters.php
|
61
|
Bitrix 16.5 Business Demo = 6b20ba8113f61df9b131767e8db3c4e7
|
gpl-3.0
|
deniskin82/hypertable
|
src/cc/Hypertable/RangeServer/tests/FileBlockCache_test.cc
|
5129
|
/** -*- c++ -*-
* Copyright (C) 2007-2012 Hypertable, Inc.
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable 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 Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "Common/Compat.h"
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <list>
#include <vector>
extern "C" {
#include <limits.h>
#include <sys/types.h>
#include <unistd.h>
}
#include "Common/Error.h"
#include "Common/Logger.h"
#include "Common/System.h"
#include "Hypertable/RangeServer/FileBlockCache.h"
#ifdef _WIN32
#define random rand
#define srandom srand
#endif
using namespace Hypertable;
using namespace std;
namespace {
struct BufferRecord {
int file_id;
uint32_t file_offset;
uint32_t length;
};
struct LtBufferRecord {
bool operator()(const struct BufferRecord &br1,
const struct BufferRecord &br2) const {
if (br1.file_id == br2.file_id) {
if (br1.file_offset == br2.file_offset)
return br1.length < br2.length;
return br1.file_offset < br2.file_offset;
}
return br1.file_id < br2.file_id;
}
};
}
#define TOTAL_ALLOC_LIMIT 100000000
#define TARGET_BUFSIZE (2 * 65536)
#define MAX_FILE_ID 10
#define MAX_FILE_OFFSET 100
int main(int argc, char **argv) {
FileBlockCache *cache;
vector<BufferRecord> input_data;
list<BufferRecord> history;
BufferRecord rec;
unsigned long seed = (unsigned long)getpid();
uint64_t total_alloc = 0;
uint64_t total_memory = TOTAL_ALLOC_LIMIT;
int file_id;
uint32_t file_offset;
uint8_t *block;
uint32_t length;
int index;
set<BufferRecord, LtBufferRecord> lru;
System::initialize(System::locate_install_dir(argv[0]));
for (int i=1; i<argc; i++) {
if (!strncmp(argv[i], "--seed=", 7))
seed = atoi(&argv[i][7]);
else if (!strncmp(argv[i], "--total-memory=", 15))
total_memory = std::max((int64_t)strtoll(&argv[i][15], 0, 0), (int64_t)(TARGET_BUFSIZE * 2));
}
uint64_t cache_memory = total_memory / 2;
cache = new FileBlockCache(cache_memory, cache_memory, false);
srandom(seed);
input_data.reserve(MAX_FILE_ID*MAX_FILE_OFFSET);
for (int i=0; i<MAX_FILE_ID; i++) {
for (int j=0; j<MAX_FILE_OFFSET; j++) {
rec.file_id = i;
rec.file_offset = j;
rec.length = (uint32_t)(random() % TARGET_BUFSIZE);
input_data.push_back(rec);
}
}
cout << "FileBlockCache_test SEED = " << seed << ", total-memory = " << total_memory << endl;
while (total_alloc < total_memory) {
index = (int)(random() % (MAX_FILE_ID*MAX_FILE_OFFSET));
file_id = input_data[index].file_id;
file_offset = input_data[index].file_offset;
if (cache->checkout(file_id, file_offset, &block, &length))
cache->checkin(file_id, file_offset);
else {
length = input_data[index].length;
block = new uint8_t [ length ];
HT_EXPECT(cache->insert(file_id, file_offset, block, length, true),
Error::FAILED_EXPECTATION);
total_alloc += length;
cache->checkin(file_id, file_offset);
}
history.push_front(input_data[index]);
}
/**
* Now verify that our idea of LRU is actually in the cache
*/
total_alloc = 0;
list<BufferRecord>::iterator history_iter = history.begin();
while (total_alloc < total_memory) {
rec.file_id = (*history_iter).file_id;
rec.file_offset = (*history_iter).file_offset;
rec.length = (*history_iter).length;
if (lru.find(rec) == lru.end()) {
if (total_alloc + rec.length > cache_memory)
break;
lru.insert(rec);
total_alloc += rec.length;
if (!cache->contains(rec.file_id, rec.file_offset)) {
HT_ERRORF("computed LRU does not match cache's (id=%d, offset=%u)",
rec.file_id, rec.file_offset);
return 1;
}
}
++history_iter;
}
/**
* Now verify that all of the remaining items that
* should *not* be in our LRU are, indeed, not in the cache
*/
if (cache->contains(rec.file_id, rec.file_offset)) {
HT_ERROR("computed LRU does not match cache's");
return 1;
}
while (history_iter != history.end()) {
rec.file_id = (*history_iter).file_id;
rec.file_offset = (*history_iter).file_offset;
rec.length = (*history_iter).length;
if (lru.find(rec) == lru.end()) {
if (cache->contains(rec.file_id, rec.file_offset)) {
HT_ERROR("computed LRU does not match cache's");
return 1;
}
}
++history_iter;
}
delete cache;
return 0;
}
|
gpl-3.0
|
edsiddos/phpMyCall
|
application/views/admin/usuarios/alterar.php
|
1943
|
<div class="container">
<?php
if ((!empty($_SESSION ['msg_erro'])) || (!empty($_SESSION ['msg_sucesso']))) {
?>
<div class="alert <?= empty($_SESSION['msg_erro']) ? 'alert-success' : 'alert-danger'; ?> text-center">
<?= empty($_SESSION['msg_erro']) ? $_SESSION['msg_sucesso'] : $_SESSION['msg_erro']; ?>
</div>
<?php
unset($_SESSION ['msg_erro']);
unset($_SESSION ['msg_sucesso']);
}
?>
<?php
echo form_open('usuarios/nova_senha', array('method' => 'post', 'name' => 'alterar'));
echo form_fieldset('Alterar Senha');
$label_attr = array('class' => 'control-label col-md-4');
$input_attr = array('class' => 'form-control', 'required' => TRUE, 'pattern' => '([0-9]|[a-z]|[A-Z]){5,50}');
?>
<div class="row">
<div class="form-group col-md-12">
<?= form_label('Nova Senha:', 'nova_senha', $label_attr) ?>
<div class="col-md-8">
<?php
$field_senha = array('id' => 'nova_senha', 'name' => 'nova_senha', 'placeholder' => 'Nova Senha');
echo form_password($field_senha, '', $input_attr);
?>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<?= form_label('Redigite a nova senha:', 'redigite', $label_attr) ?>
<div class="col-md-8">
<?php
$field_redigite = array('id' => 'redigite', 'name' => 'redigite', 'placeholder' => 'Digite novamente a nova senha');
echo form_password($field_redigite, '', $input_attr);
?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-offset-4 col-md-4">
<?= form_button(array('type' => 'submit', 'class' => 'btn btn-default col-md-12'), 'Alterar') ?>
</div>
</div>
<?= form_close() ?>
</div>
|
gpl-3.0
|
RaisingTheDerp/raisingthebar
|
root/dlls/hl2_dll/weapon_manhack.cpp
|
2503
|
/***
*
* Copyright (c) 1999, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "cbase.h"
#include "basehlcombatweapon.h"
#include "player.h"
#include "gamerules.h"
#include "ammodef.h"
#include "in_buttons.h"
#include "bone_setup.h"
class CWeapon_Manhack : public CBaseHLCombatWeapon
{
DECLARE_DATADESC();
public:
DECLARE_CLASS( CWeapon_Manhack, CBaseHLCombatWeapon );
DECLARE_SERVERCLASS();
void Spawn( void );
void Precache( void );
void ItemPostFrame( void );
void PrimaryAttack( void );
void SecondaryAttack( void );
float m_flBladeYaw;
};
IMPLEMENT_SERVERCLASS_ST( CWeapon_Manhack, DT_Weapon_Manhack)
END_SEND_TABLE()
LINK_ENTITY_TO_CLASS( weapon_manhack, CWeapon_Manhack );
PRECACHE_WEAPON_REGISTER(weapon_manhack);
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CWeapon_Manhack )
DEFINE_FIELD( CWeapon_Manhack, m_flBladeYaw, FIELD_FLOAT ),
END_DATADESC()
void CWeapon_Manhack::Spawn( )
{
// Call base class first
BaseClass::Spawn();
Precache( );
SetModel( GetViewModel() );
FallInit();// get ready to fall down.
m_flBladeYaw = NULL;
AddSolidFlags( FSOLID_NOT_SOLID );
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CWeapon_Manhack::ItemPostFrame( void )
{
WeaponIdle( );
}
void CWeapon_Manhack::Precache( void )
{
BaseClass::Precache();
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CWeapon_Manhack::PrimaryAttack()
{
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CWeapon_Manhack::SecondaryAttack()
{
}
|
gpl-3.0
|
noodlewiz/xjavab
|
xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/glx/GetMinmaxReply.java
|
1090
|
//
// DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!!
//
// Copyright (c) 2014 Vincent W. Chen.
//
// This file is part of XJavaB.
//
// XJavaB 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.
//
// XJavaB 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 XJavaB. If not, see <http://www.gnu.org/licenses/>.
//
package com.noodlewiz.xjavab.ext.glx;
import java.util.List;
import com.noodlewiz.xjavab.core.XReply;
public class GetMinmaxReply
implements XReply
{
public final List<Byte> data;
public GetMinmaxReply(final List<Byte> data) {
this.data = data;
}
}
|
gpl-3.0
|
fergalmoran/dss.web
|
client/app/directives/waveform/waveform.directive.js
|
2190
|
'use strict';
angular.module('dssWebApp')
.directive('dssWaveform', function (AudioService, PLAYSTATES, AUDIO_EVENTS) {
return {
templateUrl: 'app/directives/waveform/waveform.html',
restrict: 'EA',
link: function (scope, elem, attrs) {
elem.ready(function () {
var scrubBar = $('.scrubbar', elem);
scope.maxWidth = $('.scrubbar', elem).outerWidth(false);
$('.scrub-prog-img').width($('.scrub-bg').width());
$('.scrub-bg').bind('widthChange', function () {
console.log("WidthChange");
$('.scrub-prog-img').width($('.scrub-bg').width());
});
scrubBar.mousemove(function (e) {
$('.scrubBox-hover', scrubBar).css({
'left': (e.clientX - scrubBar.offset().left)
});
});
scope.$on(AUDIO_EVENTS.audioProgress, function (event, duration, position) {
if (scope.playState == PLAYSTATES.playing) {
scope.elapsed = position / 1000;
scope.playPos = (position / duration) * scope.maxWidth;
if (!scope.$$phase) {
scope.$apply();
}
}
});
scope.$on(AUDIO_EVENTS.audioFinished, function (id) {
scope.playState = PLAYSTATES.stopped;
});
scope.setPosition = function (event) {
console.log("AudioPlayer: setPosition", event);
if (scope.playState != PLAYSTATES.stopped) {
var newPosition = ((event.pageX - (scrubBar.offset().left)) / (scope.maxWidth) * 100);
AudioService.setPosition(newPosition);
}
};
});
},
controller: function ($scope) {
}
};
});
|
gpl-3.0
|
3dct/open_iA
|
modules/DynamicVolumeLines/iANonLinearAxisTicker.cpp
|
4023
|
/************************************* open_iA ************************************ *
* ********** A tool for visual analysis and processing of 3D CT images ********** *
* *********************************************************************************** *
* Copyright (C) 2016-2021 C. Heinzl, M. Reiter, A. Reh, W. Li, M. Arikan, Ar. & Al. *
* Amirkhanov, J. Weissenböck, B. Fröhler, M. Schiwarth, P. Weinberger *
* *********************************************************************************** *
* 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/ *
* *********************************************************************************** *
* Contact: FH OÖ Forschungs & Entwicklungs GmbH, Campus Wels, CT-Gruppe, *
* Stelzhamerstraße 23, 4600 Wels / Austria, Email: c.heinzl@fh-wels.at *
* ************************************************************************************/
#include "iANonLinearAxisTicker.h"
iANonLinearAxisTicker::iANonLinearAxisTicker() :
m_tickVector(QVector<double>(0)),
m_tickStep(0)
{
}
void iANonLinearAxisTicker::setTickData(const QVector<double> &tickVector)
{
m_tickVector = tickVector;
// TODO: check getMantissa?
m_tickVector.size() < 10 ? m_tickStep = 1 :
m_tickStep = pow(10, (floor(log10(m_tickVector.size())) - 1));
}
void iANonLinearAxisTicker::setAxis(QCPAxis *xAxis)
{
m_xAxis = xAxis;
}
QVector<double> iANonLinearAxisTicker::createTickVector(double tickStep,
const QCPRange &range)
{
Q_UNUSED(tickStep) Q_UNUSED(range)
QVector<double> result;
for (int i = 0; i < m_tickVector.size(); i += m_tickStep)
{
result.append(m_tickVector[i]);
}
return result;
}
QVector<double> iANonLinearAxisTicker::createSubTickVector(int subTickCount,
const QVector<double> &ticks)
{
Q_UNUSED(subTickCount)
QVector<double> result;
auto start = std::lower_bound(m_tickVector.begin(), m_tickVector.end(), ticks.first());
int startIdx = start - m_tickVector.begin();
auto end = std::lower_bound(m_tickVector.begin(), m_tickVector.end(), ticks.last());
int endIdx = end - m_tickVector.begin();
int indicesAfterLastMajorTick = 0;
if ((endIdx + m_tickStep) > m_tickVector.size() - 1)
{
indicesAfterLastMajorTick = m_tickVector.size() - 1 - endIdx;
}
for (int i = startIdx; i <= endIdx + indicesAfterLastMajorTick; ++i)
{
if ((i % m_tickStep) != 0)
{
result.append(m_tickVector[i]);
}
}
return result;
}
QVector<QString> iANonLinearAxisTicker::createLabelVector(const QVector<double> &ticks,
const QLocale &locale, QChar formatChar, int precision)
{
//TODO: set dist automatically
QVector<QString> result;
if (ticks.size() == 0)
{
return result;
}
int prev = 1;
for (int i = 0; i < ticks.size(); ++i)
{
if (i > 0)
{
double dist = m_xAxis->coordToPixel(ticks[i]) -
m_xAxis->coordToPixel(ticks[i - prev]);
if (dist < 20.0)
{
prev++;
result.append(QString(""));
continue;
}
}
prev = 1;
auto start = std::lower_bound(m_tickVector.begin(), m_tickVector.end(), ticks[i]);
int startIdx = start - m_tickVector.begin();
result.append(QCPAxisTicker::getTickLabel(startIdx, locale, formatChar, precision));
}
return result;
}
|
gpl-3.0
|
terry3/front_end_quiz
|
js/components/sectionView.react.js
|
1124
|
import React from 'react';
import { FeqActions } from '../actions/FeqActions';
import { FeqStore } from '../stores/FeqStore';
export default class SectionView extends React.Component {
constructor(props) {
super(props);
this.state = this.getFeqSectionState();
}
getFeqSectionState() {
return {
viewType: FeqStore.getSection(),
currentSectionNum: FeqStore.getCurrentSectionNum()
};
}
componentDidMount() {
FeqStore.addChangeListener(this._onChange.bind(this));
}
componentWillUnmount() {
FeqStore.removeChangeListener(this._onChange.bind(this));
}
_onClick() {
FeqActions.showState('question');
}
_onChange() {
this.setState(this.getFeqSectionState());
}
render() {
if (this.props.showState !== 'section') {
return null;
}
return (<div>
<h1>第{this.state.currentSectionNum}/{this.props.totalViewNum}
战</h1>
<h2>{this.state.viewType}</h2>
<button className="btn btn-ready"
onClick={this._onClick.bind(this)}>我准备好了</button>
</div>);
}
};
|
gpl-3.0
|
petxo/clitellum
|
clitellum/examples/channels/factories/custom_factory.py
|
166
|
from clitellum.endpoints.channels import factories
from config import Config
cfg = Config("myoutbound.cfg")
pb = factories.CreateOutBoundChannelFromConfig(cfg)
|
gpl-3.0
|
CCAFS/AMKN
|
wp-content/themes/amkn_theme/ccafs-sites/food-livelihood/on-farm.php
|
1366
|
<?php
$bmsId = get_post_meta($post->ID, 'siteId', true);
$tableId = "bs_production_divs";
$description = $wpdb->get_row("SELECT * FROM bs_descriptions WHERE bms_id='" . $bmsId . "' AND table_id='" . $tableId . "'");
$urlJson = get_bloginfo('template_url') . "/ccafs-sites/json.php?table=" . $tableId . "&bmsid=" . $bmsId;
?>
<div id="url-site" style="visibility: hidden;"><?php echo $urlJson ?></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="<?php echo get_bloginfo('template_url'); ?>/ccafs-sites/food-livelihood/js/on-farm.js"></script>
<script src="<?php echo get_bloginfo('template_url'); ?>/ccafs-sites/libs/highcharts-3.0.5/highcharts.js"></script>
<script src="<?php echo get_bloginfo('template_url'); ?>/ccafs-sites/libs/highcharts-3.0.5/modules/exporting.js"></script>
<h4>On-farm diversity in products produced, consumed, and sold</h4>
<div id="container-description" style="float: left;width: 30%;">
<?php echo $description->description ?>
</div>
<div id="container-chart" style="float: right;width: 60%; height: auto; margin: 0 auto"></div>
<?php if ($description->source):?>
<div class='source'><a href='<?php echo $description->source ?>' target="_blank">Source: Baseline survey, <?php echo $description->source_date?></a></div>
<?php endif;?>
|
gpl-3.0
|
mancoast/CPythonPyc_test
|
fail/311_test_struct.py
|
21957
|
import array
import unittest
import struct
import warnings
from functools import wraps
from test.support import TestFailed, verbose, run_unittest
import sys
ISBIGENDIAN = sys.byteorder == "big"
IS32BIT = sys.maxsize == 0x7fffffff
del sys
def string_reverse(s):
return s[::-1]
def bigendian_to_native(value):
if ISBIGENDIAN:
return value
else:
return string_reverse(value)
class StructTest(unittest.TestCase):
def test_isbigendian(self):
self.assertEqual((struct.pack('=i', 1)[0] == 0), ISBIGENDIAN)
def test_consistence(self):
self.assertRaises(struct.error, struct.calcsize, 'Z')
sz = struct.calcsize('i')
self.assertEqual(sz * 3, struct.calcsize('iii'))
fmt = 'cbxxxxxxhhhhiillffd?'
fmt3 = '3c3b18x12h6i6l6f3d3?'
sz = struct.calcsize(fmt)
sz3 = struct.calcsize(fmt3)
self.assertEqual(sz * 3, sz3)
self.assertRaises(struct.error, struct.pack, 'iii', 3)
self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
self.assertRaises(struct.error, struct.pack, 'i', 'foo')
self.assertRaises(struct.error, struct.pack, 'P', 'foo')
self.assertRaises(struct.error, struct.unpack, 'd', b'flap')
s = struct.pack('ii', 1, 2)
self.assertRaises(struct.error, struct.unpack, 'iii', s)
self.assertRaises(struct.error, struct.unpack, 'i', s)
def test_transitiveness(self):
c = b'a'
b = 1
h = 255
i = 65535
l = 65536
f = 3.1415
d = 3.1415
t = True
for prefix in ('', '@', '<', '>', '=', '!'):
for format in ('xcbhilfd?', 'xcBHILfd?'):
format = prefix + format
s = struct.pack(format, c, b, h, i, l, f, d, t)
cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
self.assertEqual(cp, c)
self.assertEqual(bp, b)
self.assertEqual(hp, h)
self.assertEqual(ip, i)
self.assertEqual(lp, l)
self.assertEqual(int(100 * fp), int(100 * f))
self.assertEqual(int(100 * dp), int(100 * d))
self.assertEqual(tp, t)
def test_new_features(self):
# Test some of the new features in detail
# (format, argument, big-endian result, little-endian result, asymmetric)
tests = [
('c', 'a', 'a', 'a', 0),
('xc', 'a', '\0a', '\0a', 0),
('cx', 'a', 'a\0', 'a\0', 0),
('s', 'a', 'a', 'a', 0),
('0s', 'helloworld', '', '', 1),
('1s', 'helloworld', 'h', 'h', 1),
('9s', 'helloworld', 'helloworl', 'helloworl', 1),
('10s', 'helloworld', 'helloworld', 'helloworld', 0),
('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1),
('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1),
('b', 7, '\7', '\7', 0),
('b', -7, '\371', '\371', 0),
('B', 7, '\7', '\7', 0),
('B', 249, '\371', '\371', 0),
('h', 700, '\002\274', '\274\002', 0),
('h', -700, '\375D', 'D\375', 0),
('H', 700, '\002\274', '\274\002', 0),
('H', 0x10000-700, '\375D', 'D\375', 0),
('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
('I', 70000000, '\004,\035\200', '\200\035,\004', 0),
('I', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
('L', 70000000, '\004,\035\200', '\200\035,\004', 0),
('L', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
('d', 2.0, '@\000\000\000\000\000\000\000',
'\000\000\000\000\000\000\000@', 0),
('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
('d', -2.0, '\300\000\000\000\000\000\000\000',
'\000\000\000\000\000\000\000\300', 0),
('?', 0, '\0', '\0', 0),
('?', 3, '\1', '\1', 1),
('?', True, '\1', '\1', 0),
('?', [], '\0', '\0', 1),
('?', (1,), '\1', '\1', 1),
]
for fmt, arg, big, lil, asy in tests:
big = bytes(big, "latin-1")
lil = bytes(lil, "latin-1")
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
('='+fmt, ISBIGENDIAN and big or lil)]:
res = struct.pack(xfmt, arg)
self.assertEqual(res, exp)
self.assertEqual(struct.calcsize(xfmt), len(res))
rev = struct.unpack(xfmt, res)[0]
if isinstance(arg, str):
# Strings are returned as bytes since you can't know the
# encoding of the string when packed.
arg = bytes(arg, 'latin1')
if rev != arg:
self.assertTrue(asy)
def test_native_qQ(self):
# can't pack -1 as unsigned regardless
self.assertRaises((struct.error, OverflowError), struct.pack, "Q", -1)
# can't pack string as 'q' regardless
self.assertRaises(struct.error, struct.pack, "q", "a")
# ditto, but 'Q'
self.assertRaises(struct.error, struct.pack, "Q", "a")
try:
struct.pack("q", 5)
except struct.error:
# does not have native q/Q
pass
else:
nbytes = struct.calcsize('q')
# The expected values here are in big-endian format, primarily
# because I'm on a little-endian machine and so this is the
# clearest way (for me) to force the code to get exercised.
for format, input, expected in (
('q', -1, '\xff' * nbytes),
('q', 0, '\x00' * nbytes),
('Q', 0, '\x00' * nbytes),
('q', 1, '\x00' * (nbytes-1) + '\x01'),
('Q', (1 << (8*nbytes))-1, '\xff' * nbytes),
('q', (1 << (8*nbytes-1))-1, '\x7f' + '\xff' * (nbytes - 1))):
expected = bytes(expected, "latin-1")
got = struct.pack(format, input)
native_expected = bigendian_to_native(expected)
self.assertEqual(got, native_expected)
retrieved = struct.unpack(format, got)[0]
self.assertEqual(retrieved, input)
def test_standard_integers(self):
# Standard integer tests (bBhHiIlLqQ).
import binascii
class IntTester(unittest.TestCase):
def __init__(self, formatpair, bytesize):
super(IntTester, self).__init__(methodName='test_one')
self.assertEqual(len(formatpair), 2)
self.formatpair = formatpair
for direction in "<>!=":
for code in formatpair:
format = direction + code
self.assertEqual(struct.calcsize(format), bytesize)
self.bytesize = bytesize
self.bitsize = bytesize * 8
self.signed_code, self.unsigned_code = formatpair
self.unsigned_min = 0
self.unsigned_max = 2**self.bitsize - 1
self.signed_min = -(2**(self.bitsize-1))
self.signed_max = 2**(self.bitsize-1) - 1
def test_one(self, x, pack=struct.pack,
unpack=struct.unpack,
unhexlify=binascii.unhexlify):
# Try signed.
code = self.signed_code
if self.signed_min <= x <= self.signed_max:
# Try big-endian.
expected = x
if x < 0:
expected += 1 << self.bitsize
self.assertTrue(expected > 0)
expected = hex(expected)[2:] # chop "0x"
if len(expected) & 1:
expected = "0" + expected
expected = unhexlify(expected)
expected = b"\x00" * (self.bytesize - len(expected)) + expected
# Pack work?
format = ">" + code
got = pack(format, x)
self.assertEqual(got, expected)
# Unpack work?
retrieved = unpack(format, got)[0]
self.assertEqual(x, retrieved)
# Adding any byte should cause a "too big" error.
self.assertRaises((struct.error, TypeError),
unpack, format, b'\x01' + got)
# Try little-endian.
format = "<" + code
expected = string_reverse(expected)
# Pack work?
got = pack(format, x)
self.assertEqual(got, expected)
# Unpack work?
retrieved = unpack(format, got)[0]
self.assertEqual(x, retrieved)
# Adding any byte should cause a "too big" error.
self.assertRaises((struct.error, TypeError),
unpack, format, b'\x01' + got)
else:
# x is out of range -- verify pack realizes that.
self.assertRaises(struct.error, pack, ">" + code, x)
self.assertRaises(struct.error, pack, "<" + code, x)
# Much the same for unsigned.
code = self.unsigned_code
if self.unsigned_min <= x <= self.unsigned_max:
# Try big-endian.
format = ">" + code
expected = x
expected = hex(expected)[2:] # chop "0x"
if len(expected) & 1:
expected = "0" + expected
expected = unhexlify(expected)
expected = b"\x00" * (self.bytesize - len(expected)) + expected
# Pack work?
got = pack(format, x)
self.assertEqual(got, expected)
# Unpack work?
retrieved = unpack(format, got)[0]
self.assertEqual(x, retrieved)
# Adding any byte should cause a "too big" error.
self.assertRaises((struct.error, TypeError),
unpack, format, b'\x01' + got)
# Try little-endian.
format = "<" + code
expected = string_reverse(expected)
# Pack work?
got = pack(format, x)
self.assertEqual(got, expected)
# Unpack work?
retrieved = unpack(format, got)[0]
self.assertEqual(x, retrieved)
# Adding any byte should cause a "too big" error.
self.assertRaises((struct.error, TypeError),
unpack, format, b'\x01' + got)
else:
# x is out of range -- verify pack realizes that.
self.assertRaises(struct.error, pack, ">" + code, x)
self.assertRaises(struct.error, pack, "<" + code, x)
def run(self):
from random import randrange
# Create all interesting powers of 2.
values = []
for exp in range(self.bitsize + 3):
values.append(1 << exp)
# Add some random values.
for i in range(self.bitsize):
val = 0
for j in range(self.bytesize):
val = (val << 8) | randrange(256)
values.append(val)
# Try all those, and their negations, and +-1 from them. Note
# that this tests all power-of-2 boundaries in range, and a few out
# of range, plus +-(2**n +- 1).
for base in values:
for val in -base, base:
for incr in -1, 0, 1:
x = val + incr
try:
x = int(x)
except OverflowError:
pass
self.test_one(x)
# Some error cases.
for direction in "<>":
for code in self.formatpair:
for badobject in "a string", 3+42j, randrange, -1729.0:
self.assertRaises(struct.error,
struct.pack, direction + code,
badobject)
for args in [("bB", 1),
("hH", 2),
("iI", 4),
("lL", 4),
("qQ", 8)]:
t = IntTester(*args)
t.run()
def test_p_code(self):
# Test p ("Pascal string") code.
for code, input, expected, expectedback in [
('p','abc', '\x00', b''),
('1p', 'abc', '\x00', b''),
('2p', 'abc', '\x01a', b'a'),
('3p', 'abc', '\x02ab', b'ab'),
('4p', 'abc', '\x03abc', b'abc'),
('5p', 'abc', '\x03abc\x00', b'abc'),
('6p', 'abc', '\x03abc\x00\x00', b'abc'),
('1000p', 'x'*1000, '\xff' + 'x'*999, b'x'*255)]:
expected = bytes(expected, "latin-1")
got = struct.pack(code, input)
self.assertEqual(got, expected)
(got,) = struct.unpack(code, got)
self.assertEqual(got, expectedback)
def test_705836(self):
# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
# from the low-order discarded bits could propagate into the exponent
# field, causing the result to be wrong by a factor of 2.
import math
for base in range(1, 33):
# smaller <- largest representable float less than base.
delta = 0.5
while base - delta / 2.0 != base:
delta /= 2.0
smaller = base - delta
# Packing this rounds away a solid string of trailing 1 bits.
packed = struct.pack("<f", smaller)
unpacked = struct.unpack("<f", packed)[0]
# This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
# 16, respectively.
self.assertEqual(base, unpacked)
bigpacked = struct.pack(">f", smaller)
self.assertEqual(bigpacked, string_reverse(packed))
unpacked = struct.unpack(">f", bigpacked)[0]
self.assertEqual(base, unpacked)
# Largest finite IEEE single.
big = (1 << 24) - 1
big = math.ldexp(big, 127 - 23)
packed = struct.pack(">f", big)
unpacked = struct.unpack(">f", packed)[0]
self.assertEqual(big, unpacked)
# The same, but tack on a 1 bit so it rounds up to infinity.
big = (1 << 25) - 1
big = math.ldexp(big, 127 - 24)
self.assertRaises(OverflowError, struct.pack, ">f", big)
def test_1229380(self):
# SF bug 1229380. No struct.pack exception for some out of
# range integers
import sys
for endian in ('', '>', '<'):
for fmt in ('B', 'H', 'I', 'L'):
self.assertRaises((struct.error, OverflowError), struct.pack,
endian + fmt, -1)
self.assertRaises((struct.error, OverflowError), struct.pack,
endian + 'B', 300)
self.assertRaises((struct.error, OverflowError), struct.pack,
endian + 'H', 70000)
self.assertRaises((struct.error, OverflowError), struct.pack,
endian + 'I', sys.maxsize * 4)
self.assertRaises((struct.error, OverflowError), struct.pack,
endian + 'L', sys.maxsize * 4)
def test_1530559(self):
for endian in ('', '>', '<'):
for fmt in ('B', 'H', 'I', 'L', 'Q', 'b', 'h', 'i', 'l', 'q'):
self.assertRaises(struct.error, struct.pack, endian + fmt, 1.0)
self.assertRaises(struct.error, struct.pack, endian + fmt, 1.5)
self.assertRaises(struct.error, struct.pack, 'P', 1.0)
self.assertRaises(struct.error, struct.pack, 'P', 1.5)
def test_unpack_from(self):
test_string = b'abcd01234'
fmt = '4s'
s = struct.Struct(fmt)
for cls in (bytes, bytearray):
data = cls(test_string)
if not isinstance(data, (bytes, bytearray)):
bytes_data = bytes(data, 'latin1')
else:
bytes_data = data
self.assertEqual(s.unpack_from(data), (b'abcd',))
self.assertEqual(s.unpack_from(data, 2), (b'cd01',))
self.assertEqual(s.unpack_from(data, 4), (b'0123',))
for i in range(6):
self.assertEqual(s.unpack_from(data, i), (bytes_data[i:i+4],))
for i in range(6, len(test_string) + 1):
self.assertRaises(struct.error, s.unpack_from, data, i)
for cls in (bytes, bytearray):
data = cls(test_string)
self.assertEqual(struct.unpack_from(fmt, data), (b'abcd',))
self.assertEqual(struct.unpack_from(fmt, data, 2), (b'cd01',))
self.assertEqual(struct.unpack_from(fmt, data, 4), (b'0123',))
for i in range(6):
self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
for i in range(6, len(test_string) + 1):
self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
def test_pack_into(self):
test_string = b'Reykjavik rocks, eow!'
writable_buf = array.array('b', b' '*100)
fmt = '21s'
s = struct.Struct(fmt)
# Test without offset
s.pack_into(writable_buf, 0, test_string)
from_buf = writable_buf.tostring()[:len(test_string)]
self.assertEqual(from_buf, test_string)
# Test with offset.
s.pack_into(writable_buf, 10, test_string)
from_buf = writable_buf.tostring()[:len(test_string)+10]
self.assertEqual(from_buf, test_string[:10] + test_string)
# Go beyond boundaries.
small_buf = array.array('b', b' '*10)
self.assertRaises(struct.error, s.pack_into, small_buf, 0, test_string)
self.assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
# Test bogus offset (issue 3694)
sb = small_buf
self.assertRaises(TypeError, struct.pack_into, b'1', sb, None)
def test_pack_into_fn(self):
test_string = b'Reykjavik rocks, eow!'
writable_buf = array.array('b', b' '*100)
fmt = '21s'
pack_into = lambda *args: struct.pack_into(fmt, *args)
# Test without offset.
pack_into(writable_buf, 0, test_string)
from_buf = writable_buf.tostring()[:len(test_string)]
self.assertEqual(from_buf, test_string)
# Test with offset.
pack_into(writable_buf, 10, test_string)
from_buf = writable_buf.tostring()[:len(test_string)+10]
self.assertEqual(from_buf, test_string[:10] + test_string)
# Go beyond boundaries.
small_buf = array.array('b', b' '*10)
self.assertRaises(struct.error, pack_into, small_buf, 0, test_string)
self.assertRaises(struct.error, pack_into, small_buf, 2, test_string)
def test_unpack_with_buffer(self):
# SF bug 1563759: struct.unpack doens't support buffer protocol objects
data1 = array.array('B', b'\x12\x34\x56\x78')
data2 = memoryview(b'\x12\x34\x56\x78') # XXX b'......XXXX......', 6, 4
for data in [data1, data2]:
value, = struct.unpack('>I', data)
self.assertEqual(value, 0x12345678)
def test_bool(self):
for prefix in tuple("<>!=")+('',):
false = (), [], [], '', 0
true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
falseFormat = prefix + '?' * len(false)
packedFalse = struct.pack(falseFormat, *false)
unpackedFalse = struct.unpack(falseFormat, packedFalse)
trueFormat = prefix + '?' * len(true)
packedTrue = struct.pack(trueFormat, *true)
unpackedTrue = struct.unpack(trueFormat, packedTrue)
self.assertEqual(len(true), len(unpackedTrue))
self.assertEqual(len(false), len(unpackedFalse))
for t in unpackedFalse:
self.assertFalse(t)
for t in unpackedTrue:
self.assertTrue(t)
packed = struct.pack(prefix+'?', 1)
self.assertEqual(len(packed), struct.calcsize(prefix+'?'))
if len(packed) != 1:
self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
%packed)
for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
self.assertTrue(struct.unpack('>?', c)[0])
if IS32BIT:
def test_crasher(self):
self.assertRaises(MemoryError, struct.pack, "357913941b", "a")
def test_main():
run_unittest(StructTest)
if __name__ == '__main__':
test_main()
|
gpl-3.0
|
automenta/adams-core
|
src/main/java/adams/gui/core/BaseScrollPane.java
|
4246
|
/*
* 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/>.
*/
/**
* BaseScrollPane.java
* Copyright (C) 2011 University of Waikato, Hamilton, New Zealand
*/
package adams.gui.core;
import java.awt.Component;
import javax.swing.JScrollPane;
/**
* JScrollPane with proper scroll unit/block increments.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 4584 $
*/
public class BaseScrollPane
extends JScrollPane {
/** for serialization. */
private static final long serialVersionUID = 256425097215624088L;
/** the default unit increment for the scrollbars. */
public final static int UNIT_INCREMENT = 20;
/** the default block increment for the scrollbars. */
public final static int BLOCK_INCREMENT = 100;
/**
* Creates an empty (no viewport view) <code>JScrollPane</code>
* where both horizontal and vertical scrollbars appear when needed.
*/
public BaseScrollPane() {
super();
initialize();
}
/**
* Creates an empty (no viewport view) <code>BaseScrollPane</code>
* with specified
* scrollbar policies. The available policy settings are listed at
* {@link #setVerticalScrollBarPolicy} and
* {@link #setHorizontalScrollBarPolicy}.
*
* @param vsbPolicy an integer that specifies the vertical scrollbar policy
* @param hsbPolicy an integer that specifies the horizontal scrollbar policy
*/
public BaseScrollPane(int vsbPolicy, int hsbPolicy) {
super(vsbPolicy, hsbPolicy);
initialize();
}
/**
* Creates a <code>BaseScrollPane</code> that displays the
* contents of the specified
* component, where both horizontal and vertical scrollbars appear
* whenever the component's contents are larger than the view.
*
* @param view the component to display in the scrollpane's viewport
*/
public BaseScrollPane(Component view) {
super(view);
initialize();
}
/**
* Creates a <code>BaseScrollPane</code> that displays the view
* component in a viewport
* whose view position can be controlled with a pair of scrollbars.
* The scrollbar policies specify when the scrollbars are displayed,
* For example, if <code>vsbPolicy</code> is
* <code>VERTICAL_SCROLLBAR_AS_NEEDED</code>
* then the vertical scrollbar only appears if the view doesn't fit
* vertically. The available policy settings are listed at
* {@link #setVerticalScrollBarPolicy} and
* {@link #setHorizontalScrollBarPolicy}.
*
* @param view the component to display in the scrollpanes viewport
* @param vsbPolicy an integer that specifies the vertical
* scrollbar policy
* @param hsbPolicy an integer that specifies the horizontal
* scrollbar policy
*/
public BaseScrollPane(Component view, int vsbPolicy, int hsbPolicy) {
super(view, vsbPolicy, hsbPolicy);
initialize();
}
/**
* Initializes the scrollpane.
*/
protected void initialize() {
setScrollBarUnitIncrement(UNIT_INCREMENT);
setScrollBarBlockIncrement(BLOCK_INCREMENT);
setWheelScrollingEnabled(true);
}
/**
* Sets the unit increments of both bars.
*
* @param inc the increment to use
* @see #UNIT_INCREMENT
*/
public void setScrollBarUnitIncrement(int inc) {
getVerticalScrollBar().setUnitIncrement(inc);
getHorizontalScrollBar().setUnitIncrement(inc);
}
/**
* Sets the block increments of both bars.
*
* @param inc the increment to use
* @see #BLOCK_INCREMENT
*/
public void setScrollBarBlockIncrement(int inc) {
getVerticalScrollBar().setBlockIncrement(inc);
getHorizontalScrollBar().setBlockIncrement(inc);
}
}
|
gpl-3.0
|
lowleveldesign/diagnostics-kit
|
LowLevelDesign.Diagnostics.Castle/Config/GlobalConfig.cs
|
2158
|
/**
* Part of the Diagnostics Kit
*
* Copyright (C) 2016 Sebastian Solnica
*
* 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.
*/
using LowLevelDesign.Diagnostics.LogStore.Commons.Config;
using System;
using System.Runtime.Caching;
using System.Security.Claims;
using System.Threading.Tasks;
namespace LowLevelDesign.Diagnostics.Castle.Config
{
public class GlobalConfig
{
public static readonly String AdminRoleClaim = ClaimTypes.Role + ":admin";
private const String AuthSettingKey = "auth:enabled";
private const int ConfigCacheInvalidationInMinutes = 5;
private const String CachePrefix = "conf:";
private MemoryCache cache = MemoryCache.Default;
private readonly IAppConfigurationManager confManager;
public GlobalConfig(IAppConfigurationManager confManager)
{
this.confManager = confManager;
}
public bool IsAuthenticationEnabled()
{
var o = cache.Get(CachePrefix + AuthSettingKey);
if (o == null) {
bool flag;
Boolean.TryParse(confManager.GetGlobalSetting(AuthSettingKey), out flag);
cache.Set(CachePrefix + AuthSettingKey, flag, new CacheItemPolicy {
AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(ConfigCacheInvalidationInMinutes)
});
return flag;
}
return (bool)o;
}
public async Task ToggleAuthentication(bool enabled)
{
await confManager.SetGlobalSettingAsync(AuthSettingKey, enabled.ToString());
cache.Remove(CachePrefix + AuthSettingKey);
}
}
}
|
gpl-3.0
|
goncalomb/CustomItemsAPI
|
src/main/java/com/goncalomb/bukkit/customitemsapi/items/KingsCrown.java
|
3398
|
/*
* Copyright (C) 2013 - Gonçalo Baltazar <http://goncalomb.com>
*
* This file is part of CustomItemsAPI.
*
* CustomItemsAPI 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.
*
* CustomItemsAPI 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 CustomItemsAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package com.goncalomb.bukkit.customitemsapi.items;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.material.MaterialData;
import com.goncalomb.bukkit.bkglib.Lang;
import com.goncalomb.bukkit.bkglib.utils.UtilsMc;
import com.goncalomb.bukkit.customitemsapi.CustomItemsAPI;
import com.goncalomb.bukkit.customitemsapi.api.CustomItem;
import com.goncalomb.bukkit.customitemsapi.api.PlayerDetails;
public class KingsCrown extends CustomItem {
private boolean _shouldBroadcastMessage = true;
public KingsCrown() {
super("kings-crown", ChatColor.GOLD + "King's Crown", new MaterialData(Material.GOLD_HELMET));
addEnchantment(Enchantment.PROTECTION_FALL, 4);
}
private boolean shouldBroadcastMessage() {
if (_shouldBroadcastMessage) {
_shouldBroadcastMessage = false;
// Prevent too much spam.
Bukkit.getScheduler().runTaskLater(getPlugin(), new Runnable() {
@Override
public void run() {
_shouldBroadcastMessage = true;
}
}, 200); // 10 seconds.
return true;
}
return false;
}
@Override
public void onPickup(PlayerPickupItemEvent event) {
PlayerInventory inv = event.getPlayer().getInventory();
ItemStack lastHelmet = inv.getHelmet();
if (lastHelmet == null || inv.addItem(lastHelmet).size() == 0) {
inv.setHelmet(event.getItem().getItemStack());
event.getItem().remove();
event.setCancelled(true);
if (shouldBroadcastMessage()) {
UtilsMc.broadcastToWorld(event.getPlayer().getWorld(), Lang._(CustomItemsAPI.class, "crown.found", event.getPlayer().getName(), getName()));
}
}
}
@Override
public void onDrop(PlayerDropItemEvent event) {
lostCrown(event.getPlayer());
}
@Override
public void onDespawn(ItemDespawnEvent event) {
if (shouldBroadcastMessage()) {
UtilsMc.broadcastToWorld(event.getEntity().getWorld(), Lang._(CustomItemsAPI.class, "crown.despawn", getName()));
}
}
@Override
public void onPlayerDeath(PlayerDeathEvent event, PlayerDetails details) {
lostCrown(event.getEntity());
}
private void lostCrown(Player player) {
if (shouldBroadcastMessage()) {
UtilsMc.broadcastToWorld(player.getWorld(), Lang._(CustomItemsAPI.class, "crown.lost", player.getName(), getName()));
}
}
}
|
gpl-3.0
|
rhomicom-systems-tech-gh/Rhomicom-ERP-Desktop
|
RhomicomERP/splash/Properties/Settings.Designer.cs
|
1061
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace splash.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
|
gpl-3.0
|
tilosradio/web2-backend
|
src/main/java/hu/tilos/radio/backend/data/ShowReferenceConverter.java
|
710
|
package hu.tilos.radio.backend.data;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import org.bson.types.ObjectId;
import org.springframework.core.convert.converter.Converter;
public class ShowReferenceConverter implements Converter<DBObject, ShowReference> {
@Override
public ShowReference convert(DBObject dbObject) {
ShowReference showReference = new ShowReference();
showReference.setAlias((String) dbObject.get("alias"));
showReference.setName((String) dbObject.get("name"));
DBRef ref = (DBRef) dbObject.get("ref");
ObjectId refId = (ObjectId) ref.getId();
showReference.setId(refId.toHexString());
return showReference;
}
}
|
gpl-3.0
|
IntersectAustralia/anznn
|
config/routes.rb
|
3422
|
Anznn::Application.routes.draw do
devise_for :users, :controllers => {:registrations => "user_registers", :passwords => "user_passwords"}
as :user do
get "/users/profile", :to => "user_registers#profile" #page which gives options to edit details or change password
get "/users/edit_password", :to => "user_registers#edit_password" #allow users to edit their own password
put "/users/update_password", :to => "user_registers#update_password" #allow users to edit their own password
end
resources :responses, :only => [:new, :create, :edit, :update, :show, :destroy] do
member do
get :review_answers
post :submit
end
collection do
get :stats
get :prepare_download
get :download
get :batch_delete
get :submitted_baby_codes
put :confirm_batch_delete
put :perform_batch_delete
end
end
resources :configuration_items, :only => [] do
collection do
get :edit_year_of_registration
put :update_year_of_registration
end
end
resources :batch_files, :only => [:new, :create, :index] do
member do
get :summary_report
get :detail_report
post :force_submit
end
end
resource :pages do
get :home
end
namespace :admin do
resources :users, :only => [:show, :index] do
collection do
get :access_requests
end
member do
put :reject
put :reject_as_spam
put :deactivate
put :activate
get :edit_role
patch :update_role
get :edit_approval
patch :approve
end
end
end
root :to => "pages#home"
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
|
gpl-3.0
|
mitani/dashlet-subpanels
|
include/Smarty/plugins/function.html_select_date.php
|
11619
|
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {html_select_date} plugin
*
* Type: function<br>
* Name: html_select_date<br>
* Purpose: Prints the dropdowns for date selection.
*
* ChangeLog:<br>
* - 1.0 initial release
* - 1.1 added support for +/- N syntax for begin
* and end year values. (Monte)
* - 1.2 added support for yyyy-mm-dd syntax for
* time value. (Jan Rosier)
* - 1.3 added support for choosing format for
* month values (Gary Loescher)
* - 1.3.1 added support for choosing format for
* day values (Marcus Bointon)
* - 1.3.2 suppport negative timestamps, force year
* dropdown to include given date unless explicitly set (Monte)
* @link http://smarty.php.net/manual/en/language.function.html.select.date.php {html_select_date}
* (Smarty online manual)
* @author Andrei Zmievski
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_html_select_date($params, &$smarty)
{
require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');
require_once $smarty->_get_plugin_filepath('shared','make_timestamp');
require_once $smarty->_get_plugin_filepath('function','html_options');
/* Default values. */
$prefix = "Date_";
$start_year = strftime("%Y");
$end_year = $start_year;
$display_days = true;
$display_months = true;
$display_years = true;
$month_format = "%B";
/* Write months as numbers by default GL */
$month_value_format = "%m";
$day_format = "%02d";
/* Write day values using this format MB */
$day_value_format = "%d";
$year_as_text = false;
/* Display years in reverse order? Ie. 2000,1999,.... */
$reverse_years = false;
/* Should the select boxes be part of an array when returned from PHP?
e.g. setting it to "birthday", would create "birthday[Day]",
"birthday[Month]" & "birthday[Year]". Can be combined with prefix */
$field_array = null;
/* <select size>'s of the different <select> tags.
If not set, uses default dropdown. */
$day_size = null;
$month_size = null;
$year_size = null;
/* Unparsed attributes common to *ALL* the <select>/<input> tags.
An example might be in the template: all_extra ='class ="foo"'. */
$all_extra = null;
/* Separate attributes for the tags. */
$day_extra = null;
$month_extra = null;
$year_extra = null;
/* Order in which to display the fields.
"D" -> day, "M" -> month, "Y" -> year. */
$field_order = 'MDY';
/* String printed between the different fields. */
$field_separator = "\n";
$time = time();
$all_empty = null;
$day_empty = null;
$month_empty = null;
$year_empty = null;
$extra_attrs = '';
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'prefix':
case 'time':
case 'start_year':
case 'end_year':
case 'month_format':
case 'day_format':
case 'day_value_format':
case 'field_array':
case 'day_size':
case 'month_size':
case 'year_size':
case 'all_extra':
case 'day_extra':
case 'month_extra':
case 'year_extra':
case 'field_order':
case 'field_separator':
case 'month_value_format':
case 'month_empty':
case 'day_empty':
case 'year_empty':
$$_key = (string)$_value;
break;
case 'all_empty':
$$_key = (string)$_value;
$day_empty = $month_empty = $year_empty = $all_empty;
break;
case 'display_days':
case 'display_months':
case 'display_years':
case 'year_as_text':
case 'reverse_years':
$$_key = (bool)$_value;
break;
default:
if(!is_array($_value)) {
$extra_attrs .= ' '.$_key.'="'.smarty_function_escape_special_chars($_value).'"';
} else {
$smarty->trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if(preg_match('!^-\d+$!',$time)) {
// negative timestamp, use date()
$time = date('Y-m-d',$time);
}
// If $time is not in format yyyy-mm-dd
if (!preg_match('/^\d{0,4}-\d{0,2}-\d{0,2}$/', $time)) {
// use smarty_make_timestamp to get an unix timestamp and
// strftime to make yyyy-mm-dd
$time = strftime('%Y-%m-%d', smarty_make_timestamp($time));
}
// Now split this in pieces, which later can be used to set the select
$time = explode("-", $time);
// make syntax "+N" or "-N" work with start_year and end_year
if (preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match)) {
if ($match[1] == '+') {
$end_year = strftime('%Y') + $match[2];
} else {
$end_year = strftime('%Y') - $match[2];
}
}
if (preg_match('!^(\+|\-)\s*(\d+)$!', $start_year, $match)) {
if ($match[1] == '+') {
$start_year = strftime('%Y') + $match[2];
} else {
$start_year = strftime('%Y') - $match[2];
}
}
if (strlen($time[0]) > 0) {
if ($start_year > $time[0] && !isset($params['start_year'])) {
// force start year to include given date if not explicitly set
$start_year = $time[0];
}
if($end_year < $time[0] && !isset($params['end_year'])) {
// force end year to include given date if not explicitly set
$end_year = $time[0];
}
}
$field_order = strtoupper($field_order);
$html_result = $month_result = $day_result = $year_result = "";
if ($display_months) {
$month_names = array();
$month_values = array();
if(isset($month_empty)) {
$month_names[''] = $month_empty;
$month_values[''] = '';
}
for ($i = 1; $i <= 12; $i++) {
$month_names[$i] = strftime($month_format, mktime(0, 0, 0, $i, 1, 2000));
$month_values[$i] = strftime($month_value_format, mktime(0, 0, 0, $i, 1, 2000));
}
$month_result .= '<select name=';
if (null !== $field_array){
$month_result .= '"' . $field_array . '[' . $prefix . 'Month]"';
} else {
$month_result .= '"' . $prefix . 'Month"';
}
if (null !== $month_size){
$month_result .= ' size="' . $month_size . '"';
}
if (null !== $month_extra){
$month_result .= ' ' . $month_extra;
}
if (null !== $all_extra){
$month_result .= ' ' . $all_extra;
}
$month_result .= $extra_attrs . '>'."\n";
$month_result .= smarty_function_html_options(array('output' => $month_names,
'values' => $month_values,
'selected' => (int)$time[1] ? strftime($month_value_format, mktime(0, 0, 0, (int)$time[1], 1, 2000)) : '',
'print_result' => false),
$smarty);
$month_result .= '</select>';
}
if ($display_days) {
$days = array();
if (isset($day_empty)) {
$days[''] = $day_empty;
$day_values[''] = '';
}
for ($i = 1; $i <= 31; $i++) {
$days[] = sprintf($day_format, $i);
$day_values[] = sprintf($day_value_format, $i);
}
$day_result .= '<select name=';
if (null !== $field_array){
$day_result .= '"' . $field_array . '[' . $prefix . 'Day]"';
} else {
$day_result .= '"' . $prefix . 'Day"';
}
if (null !== $day_size){
$day_result .= ' size="' . $day_size . '"';
}
if (null !== $all_extra){
$day_result .= ' ' . $all_extra;
}
if (null !== $day_extra){
$day_result .= ' ' . $day_extra;
}
$day_result .= $extra_attrs . '>'."\n";
$day_result .= smarty_function_html_options(array('output' => $days,
'values' => $day_values,
'selected' => $time[2],
'print_result' => false),
$smarty);
$day_result .= '</select>';
}
if ($display_years) {
if (null !== $field_array){
$year_name = $field_array . '[' . $prefix . 'Year]';
} else {
$year_name = $prefix . 'Year';
}
if ($year_as_text) {
$year_result .= '<input type="text" name="' . $year_name . '" value="' . $time[0] . '" size="4" maxlength="4"';
if (null !== $all_extra){
$year_result .= ' ' . $all_extra;
}
if (null !== $year_extra){
$year_result .= ' ' . $year_extra;
}
$year_result .= ' />';
} else {
$years = range((int)$start_year, (int)$end_year);
if ($reverse_years) {
rsort($years, SORT_NUMERIC);
} else {
sort($years, SORT_NUMERIC);
}
$yearvals = $years;
if(isset($year_empty)) {
array_unshift($years, $year_empty);
array_unshift($yearvals, '');
}
$year_result .= '<select name="' . $year_name . '"';
if (null !== $year_size){
$year_result .= ' size="' . $year_size . '"';
}
if (null !== $all_extra){
$year_result .= ' ' . $all_extra;
}
if (null !== $year_extra){
$year_result .= ' ' . $year_extra;
}
$year_result .= $extra_attrs . '>'."\n";
$year_result .= smarty_function_html_options(array('output' => $years,
'values' => $yearvals,
'selected' => $time[0],
'print_result' => false),
$smarty);
$year_result .= '</select>';
}
}
// Loop thru the field_order field
for ($i = 0; $i <= 2; $i++){
$c = substr($field_order, $i, 1);
switch ($c){
case 'D':
$html_result .= $day_result;
break;
case 'M':
$html_result .= $month_result;
break;
case 'Y':
$html_result .= $year_result;
break;
}
// Add the field seperator
if($i != 2) {
$html_result .= $field_separator;
}
}
return $html_result;
}
/* vim: set expandtab: */
?>
|
gpl-3.0
|
joevandebilt/ADFGX-Cipher
|
ADFGX Decoder/ADFGX Standalone Decoder/Decoder.Designer.cs
|
38018
|
namespace ADFGXDecoder
{
partial class Decoder
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Decoder));
this.txtInput = new System.Windows.Forms.TextBox();
this.decode = new System.Windows.Forms.Button();
this.txtKeywords = new System.Windows.Forms.TextBox();
this.cmdMenu = new System.Windows.Forms.Button();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.panel1 = new System.Windows.Forms.Panel();
this.rdbDynamic = new System.Windows.Forms.RadioButton();
this.rdbStatic = new System.Windows.Forms.RadioButton();
this.label16 = new System.Windows.Forms.Label();
this.cmbNumberOfThreads = new System.Windows.Forms.ComboBox();
this.txtKeyword = new System.Windows.Forms.TextBox();
this.cmdLongWay = new System.Windows.Forms.Button();
this.cmdRandom = new System.Windows.Forms.Button();
this.label15 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtKey25 = new System.Windows.Forms.TextBox();
this.txtKey20 = new System.Windows.Forms.TextBox();
this.txtKey15 = new System.Windows.Forms.TextBox();
this.txtKey10 = new System.Windows.Forms.TextBox();
this.txtKey5 = new System.Windows.Forms.TextBox();
this.txtKey24 = new System.Windows.Forms.TextBox();
this.txtKey19 = new System.Windows.Forms.TextBox();
this.txtKey14 = new System.Windows.Forms.TextBox();
this.txtKey9 = new System.Windows.Forms.TextBox();
this.txtKey4 = new System.Windows.Forms.TextBox();
this.txtKey23 = new System.Windows.Forms.TextBox();
this.txtKey18 = new System.Windows.Forms.TextBox();
this.txtKey13 = new System.Windows.Forms.TextBox();
this.txtKey8 = new System.Windows.Forms.TextBox();
this.txtKey3 = new System.Windows.Forms.TextBox();
this.txtKey22 = new System.Windows.Forms.TextBox();
this.txtKey17 = new System.Windows.Forms.TextBox();
this.txtKey12 = new System.Windows.Forms.TextBox();
this.txtKey7 = new System.Windows.Forms.TextBox();
this.txtKey2 = new System.Windows.Forms.TextBox();
this.txtKey21 = new System.Windows.Forms.TextBox();
this.txtKey16 = new System.Windows.Forms.TextBox();
this.txtKey11 = new System.Windows.Forms.TextBox();
this.txtKey6 = new System.Windows.Forms.TextBox();
this.txtKey1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.txtOutput = new System.Windows.Forms.RichTextBox();
this.cmdClear = new System.Windows.Forms.Button();
this.cmdSaveToFile = new System.Windows.Forms.Button();
this.rtbTreeComposition = new System.Windows.Forms.RadioButton();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// txtInput
//
this.txtInput.Location = new System.Drawing.Point(79, 80);
this.txtInput.Multiline = true;
this.txtInput.Name = "txtInput";
this.txtInput.Size = new System.Drawing.Size(589, 29);
this.txtInput.TabIndex = 0;
this.txtInput.Text = "FFGXGDGFFAGFGGDDGFFFXXFFFDGFFGFDGFFGFDGGFFFGFGAAFXFXDXXFXDGFFAGGFF----AF";
//
// decode
//
this.decode.Location = new System.Drawing.Point(34, 115);
this.decode.Name = "decode";
this.decode.Size = new System.Drawing.Size(126, 36);
this.decode.TabIndex = 1;
this.decode.Text = "Decode";
this.decode.UseVisualStyleBackColor = true;
this.decode.Click += new System.EventHandler(this.decode_Click);
//
// txtKeywords
//
this.txtKeywords.Location = new System.Drawing.Point(34, 25);
this.txtKeywords.Multiline = true;
this.txtKeywords.Name = "txtKeywords";
this.txtKeywords.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtKeywords.Size = new System.Drawing.Size(700, 49);
this.txtKeywords.TabIndex = 2;
this.txtKeywords.Text = resources.GetString("txtKeywords.Text");
//
// cmdMenu
//
this.cmdMenu.Location = new System.Drawing.Point(166, 115);
this.cmdMenu.Name = "cmdMenu";
this.cmdMenu.Size = new System.Drawing.Size(133, 36);
this.cmdMenu.TabIndex = 4;
this.cmdMenu.Text = "Main Menu";
this.cmdMenu.UseVisualStyleBackColor = true;
this.cmdMenu.Click += new System.EventHandler(this.cmdMenu_Click);
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(377, 121);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(148, 17);
this.radioButton1.TabIndex = 5;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "Find Unique Combinations";
this.radioButton1.UseVisualStyleBackColor = true;
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Location = new System.Drawing.Point(377, 144);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(223, 17);
this.radioButton2.TabIndex = 6;
this.radioButton2.TabStop = true;
this.radioButton2.Text = "Find Unique Translations using Keysquare";
this.radioButton2.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.Controls.Add(this.rdbDynamic);
this.panel1.Controls.Add(this.rdbStatic);
this.panel1.Controls.Add(this.label16);
this.panel1.Controls.Add(this.cmbNumberOfThreads);
this.panel1.Controls.Add(this.txtKeyword);
this.panel1.Controls.Add(this.cmdLongWay);
this.panel1.Controls.Add(this.cmdRandom);
this.panel1.Controls.Add(this.label15);
this.panel1.Controls.Add(this.label11);
this.panel1.Controls.Add(this.label6);
this.panel1.Controls.Add(this.label10);
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label9);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label8);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.label7);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.txtKey25);
this.panel1.Controls.Add(this.txtKey20);
this.panel1.Controls.Add(this.txtKey15);
this.panel1.Controls.Add(this.txtKey10);
this.panel1.Controls.Add(this.txtKey5);
this.panel1.Controls.Add(this.txtKey24);
this.panel1.Controls.Add(this.txtKey19);
this.panel1.Controls.Add(this.txtKey14);
this.panel1.Controls.Add(this.txtKey9);
this.panel1.Controls.Add(this.txtKey4);
this.panel1.Controls.Add(this.txtKey23);
this.panel1.Controls.Add(this.txtKey18);
this.panel1.Controls.Add(this.txtKey13);
this.panel1.Controls.Add(this.txtKey8);
this.panel1.Controls.Add(this.txtKey3);
this.panel1.Controls.Add(this.txtKey22);
this.panel1.Controls.Add(this.txtKey17);
this.panel1.Controls.Add(this.txtKey12);
this.panel1.Controls.Add(this.txtKey7);
this.panel1.Controls.Add(this.txtKey2);
this.panel1.Controls.Add(this.txtKey21);
this.panel1.Controls.Add(this.txtKey16);
this.panel1.Controls.Add(this.txtKey11);
this.panel1.Controls.Add(this.txtKey6);
this.panel1.Controls.Add(this.txtKey1);
this.panel1.Location = new System.Drawing.Point(740, 25);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(191, 507);
this.panel1.TabIndex = 7;
//
// rdbDynamic
//
this.rdbDynamic.AutoSize = true;
this.rdbDynamic.Location = new System.Drawing.Point(38, 197);
this.rdbDynamic.Name = "rdbDynamic";
this.rdbDynamic.Size = new System.Drawing.Size(119, 17);
this.rdbDynamic.TabIndex = 29;
this.rdbDynamic.Text = "Dynamic Keysquare";
this.rdbDynamic.UseVisualStyleBackColor = true;
this.rdbDynamic.CheckedChanged += new System.EventHandler(this.rdbDynamic_CheckedChanged);
//
// rdbStatic
//
this.rdbStatic.AutoSize = true;
this.rdbStatic.Location = new System.Drawing.Point(38, 219);
this.rdbStatic.Name = "rdbStatic";
this.rdbStatic.Size = new System.Drawing.Size(105, 17);
this.rdbStatic.TabIndex = 28;
this.rdbStatic.Text = "Static Keysquare";
this.rdbStatic.UseVisualStyleBackColor = true;
this.rdbStatic.CheckedChanged += new System.EventHandler(this.rdbStatic_CheckedChanged);
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(23, 420);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(94, 13);
this.label16.TabIndex = 27;
this.label16.Text = "Number of threads";
//
// cmbNumberOfThreads
//
this.cmbNumberOfThreads.FormattingEnabled = true;
this.cmbNumberOfThreads.Items.AddRange(new object[] {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"});
this.cmbNumberOfThreads.Location = new System.Drawing.Point(123, 417);
this.cmbNumberOfThreads.Name = "cmbNumberOfThreads";
this.cmbNumberOfThreads.Size = new System.Drawing.Size(40, 21);
this.cmbNumberOfThreads.TabIndex = 26;
this.cmbNumberOfThreads.Text = "1";
//
// txtKeyword
//
this.txtKeyword.Location = new System.Drawing.Point(26, 444);
this.txtKeyword.Name = "txtKeyword";
this.txtKeyword.Size = new System.Drawing.Size(137, 20);
this.txtKeyword.TabIndex = 25;
//
// cmdLongWay
//
this.cmdLongWay.Location = new System.Drawing.Point(24, 470);
this.cmdLongWay.Name = "cmdLongWay";
this.cmdLongWay.Size = new System.Drawing.Size(138, 23);
this.cmdLongWay.TabIndex = 11;
this.cmdLongWay.Text = "The Long Way";
this.cmdLongWay.UseVisualStyleBackColor = true;
this.cmdLongWay.Click += new System.EventHandler(this.cmdLongWay_Click);
//
// cmdRandom
//
this.cmdRandom.Location = new System.Drawing.Point(22, 242);
this.cmdRandom.Name = "cmdRandom";
this.cmdRandom.Size = new System.Drawing.Size(138, 23);
this.cmdRandom.TabIndex = 10;
this.cmdRandom.Text = "Random Letters";
this.cmdRandom.UseVisualStyleBackColor = true;
this.cmdRandom.Click += new System.EventHandler(this.cmdRandom_Click);
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(3, 181);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(186, 13);
this.label15.TabIndex = 9;
this.label15.Text = "Remember: Row first, Column Second";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label11.Location = new System.Drawing.Point(22, 139);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(17, 16);
this.label11.TabIndex = 1;
this.label11.Text = "X";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(143, 16);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(17, 16);
this.label6.TabIndex = 1;
this.label6.Text = "X";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label10.Location = new System.Drawing.Point(21, 113);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(19, 16);
this.label10.TabIndex = 1;
this.label10.Text = "G";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(119, 16);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(19, 16);
this.label5.TabIndex = 1;
this.label5.Text = "G";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.Location = new System.Drawing.Point(22, 88);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(17, 16);
this.label9.TabIndex = 1;
this.label9.Text = "F";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(95, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(17, 16);
this.label4.TabIndex = 1;
this.label4.Text = "F";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(22, 62);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(19, 16);
this.label8.TabIndex = 1;
this.label8.Text = "D";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(69, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(19, 16);
this.label3.TabIndex = 1;
this.label3.Text = "D";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(22, 39);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(18, 16);
this.label7.TabIndex = 1;
this.label7.Text = "A";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(45, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(18, 16);
this.label2.TabIndex = 1;
this.label2.Text = "A";
//
// txtKey25
//
this.txtKey25.Location = new System.Drawing.Point(144, 138);
this.txtKey25.MaxLength = 1;
this.txtKey25.Name = "txtKey25";
this.txtKey25.Size = new System.Drawing.Size(19, 20);
this.txtKey25.TabIndex = 24;
this.txtKey25.Text = "Z";
this.txtKey25.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey20
//
this.txtKey20.Location = new System.Drawing.Point(144, 112);
this.txtKey20.MaxLength = 1;
this.txtKey20.Name = "txtKey20";
this.txtKey20.Size = new System.Drawing.Size(19, 20);
this.txtKey20.TabIndex = 19;
this.txtKey20.Text = "U";
this.txtKey20.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey15
//
this.txtKey15.Location = new System.Drawing.Point(144, 87);
this.txtKey15.MaxLength = 1;
this.txtKey15.Name = "txtKey15";
this.txtKey15.Size = new System.Drawing.Size(19, 20);
this.txtKey15.TabIndex = 14;
this.txtKey15.Text = "P";
this.txtKey15.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey10
//
this.txtKey10.Location = new System.Drawing.Point(144, 61);
this.txtKey10.MaxLength = 1;
this.txtKey10.Name = "txtKey10";
this.txtKey10.Size = new System.Drawing.Size(19, 20);
this.txtKey10.TabIndex = 9;
this.txtKey10.Text = "K";
this.txtKey10.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey5
//
this.txtKey5.Location = new System.Drawing.Point(144, 35);
this.txtKey5.MaxLength = 1;
this.txtKey5.Name = "txtKey5";
this.txtKey5.Size = new System.Drawing.Size(19, 20);
this.txtKey5.TabIndex = 4;
this.txtKey5.Text = "E";
this.txtKey5.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey24
//
this.txtKey24.Location = new System.Drawing.Point(119, 138);
this.txtKey24.MaxLength = 1;
this.txtKey24.Name = "txtKey24";
this.txtKey24.Size = new System.Drawing.Size(19, 20);
this.txtKey24.TabIndex = 23;
this.txtKey24.Text = "Y";
this.txtKey24.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey19
//
this.txtKey19.Location = new System.Drawing.Point(119, 112);
this.txtKey19.MaxLength = 1;
this.txtKey19.Name = "txtKey19";
this.txtKey19.Size = new System.Drawing.Size(19, 20);
this.txtKey19.TabIndex = 18;
this.txtKey19.Text = "T";
this.txtKey19.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey14
//
this.txtKey14.Location = new System.Drawing.Point(119, 87);
this.txtKey14.MaxLength = 1;
this.txtKey14.Name = "txtKey14";
this.txtKey14.Size = new System.Drawing.Size(19, 20);
this.txtKey14.TabIndex = 13;
this.txtKey14.Text = "O";
this.txtKey14.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey9
//
this.txtKey9.Location = new System.Drawing.Point(119, 61);
this.txtKey9.MaxLength = 1;
this.txtKey9.Name = "txtKey9";
this.txtKey9.Size = new System.Drawing.Size(19, 20);
this.txtKey9.TabIndex = 8;
this.txtKey9.Text = "I";
this.txtKey9.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey4
//
this.txtKey4.Location = new System.Drawing.Point(119, 35);
this.txtKey4.MaxLength = 1;
this.txtKey4.Name = "txtKey4";
this.txtKey4.Size = new System.Drawing.Size(19, 20);
this.txtKey4.TabIndex = 3;
this.txtKey4.Text = "D";
this.txtKey4.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey23
//
this.txtKey23.Location = new System.Drawing.Point(94, 138);
this.txtKey23.MaxLength = 1;
this.txtKey23.Name = "txtKey23";
this.txtKey23.Size = new System.Drawing.Size(19, 20);
this.txtKey23.TabIndex = 22;
this.txtKey23.Text = "X";
this.txtKey23.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey18
//
this.txtKey18.Location = new System.Drawing.Point(94, 112);
this.txtKey18.MaxLength = 1;
this.txtKey18.Name = "txtKey18";
this.txtKey18.Size = new System.Drawing.Size(19, 20);
this.txtKey18.TabIndex = 17;
this.txtKey18.Text = "S";
this.txtKey18.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey13
//
this.txtKey13.Location = new System.Drawing.Point(94, 87);
this.txtKey13.MaxLength = 1;
this.txtKey13.Name = "txtKey13";
this.txtKey13.Size = new System.Drawing.Size(19, 20);
this.txtKey13.TabIndex = 12;
this.txtKey13.Text = "N";
this.txtKey13.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey8
//
this.txtKey8.Location = new System.Drawing.Point(94, 61);
this.txtKey8.MaxLength = 1;
this.txtKey8.Name = "txtKey8";
this.txtKey8.Size = new System.Drawing.Size(19, 20);
this.txtKey8.TabIndex = 7;
this.txtKey8.Text = "H";
this.txtKey8.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey3
//
this.txtKey3.Location = new System.Drawing.Point(94, 35);
this.txtKey3.MaxLength = 1;
this.txtKey3.Name = "txtKey3";
this.txtKey3.Size = new System.Drawing.Size(19, 20);
this.txtKey3.TabIndex = 2;
this.txtKey3.Text = "C";
this.txtKey3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey22
//
this.txtKey22.Location = new System.Drawing.Point(69, 138);
this.txtKey22.MaxLength = 1;
this.txtKey22.Name = "txtKey22";
this.txtKey22.Size = new System.Drawing.Size(19, 20);
this.txtKey22.TabIndex = 21;
this.txtKey22.Text = "W";
this.txtKey22.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey17
//
this.txtKey17.Location = new System.Drawing.Point(69, 112);
this.txtKey17.MaxLength = 1;
this.txtKey17.Name = "txtKey17";
this.txtKey17.Size = new System.Drawing.Size(19, 20);
this.txtKey17.TabIndex = 16;
this.txtKey17.Text = "R";
this.txtKey17.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey12
//
this.txtKey12.Location = new System.Drawing.Point(69, 87);
this.txtKey12.MaxLength = 1;
this.txtKey12.Name = "txtKey12";
this.txtKey12.Size = new System.Drawing.Size(19, 20);
this.txtKey12.TabIndex = 11;
this.txtKey12.Text = "M";
this.txtKey12.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey7
//
this.txtKey7.Location = new System.Drawing.Point(69, 61);
this.txtKey7.MaxLength = 1;
this.txtKey7.Name = "txtKey7";
this.txtKey7.Size = new System.Drawing.Size(19, 20);
this.txtKey7.TabIndex = 6;
this.txtKey7.Text = "G";
this.txtKey7.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey2
//
this.txtKey2.Location = new System.Drawing.Point(69, 35);
this.txtKey2.MaxLength = 1;
this.txtKey2.Name = "txtKey2";
this.txtKey2.Size = new System.Drawing.Size(19, 20);
this.txtKey2.TabIndex = 1;
this.txtKey2.Text = "B";
this.txtKey2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey21
//
this.txtKey21.Location = new System.Drawing.Point(44, 138);
this.txtKey21.MaxLength = 1;
this.txtKey21.Name = "txtKey21";
this.txtKey21.Size = new System.Drawing.Size(19, 20);
this.txtKey21.TabIndex = 20;
this.txtKey21.Text = "V";
this.txtKey21.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey16
//
this.txtKey16.Location = new System.Drawing.Point(44, 112);
this.txtKey16.MaxLength = 1;
this.txtKey16.Name = "txtKey16";
this.txtKey16.Size = new System.Drawing.Size(19, 20);
this.txtKey16.TabIndex = 15;
this.txtKey16.Text = "Q";
this.txtKey16.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey11
//
this.txtKey11.Location = new System.Drawing.Point(44, 87);
this.txtKey11.MaxLength = 1;
this.txtKey11.Name = "txtKey11";
this.txtKey11.Size = new System.Drawing.Size(19, 20);
this.txtKey11.TabIndex = 10;
this.txtKey11.Text = "L";
this.txtKey11.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey6
//
this.txtKey6.Location = new System.Drawing.Point(44, 61);
this.txtKey6.MaxLength = 1;
this.txtKey6.Name = "txtKey6";
this.txtKey6.Size = new System.Drawing.Size(19, 20);
this.txtKey6.TabIndex = 5;
this.txtKey6.Text = "F";
this.txtKey6.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// txtKey1
//
this.txtKey1.Location = new System.Drawing.Point(44, 35);
this.txtKey1.MaxLength = 1;
this.txtKey1.Name = "txtKey1";
this.txtKey1.Size = new System.Drawing.Size(19, 20);
this.txtKey1.TabIndex = 0;
this.txtKey1.Text = "A";
this.txtKey1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(737, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(97, 13);
this.label1.TabIndex = 8;
this.label1.Text = "Custom KeySquare";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(31, 5);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(53, 13);
this.label12.TabIndex = 8;
this.label12.Text = "Keywords";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(31, 80);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(42, 13);
this.label13.TabIndex = 8;
this.label13.Text = "Original";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(31, 190);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(44, 13);
this.label14.TabIndex = 8;
this.label14.Text = "Outputs";
//
// txtOutput
//
this.txtOutput.Location = new System.Drawing.Point(34, 206);
this.txtOutput.Name = "txtOutput";
this.txtOutput.Size = new System.Drawing.Size(700, 326);
this.txtOutput.TabIndex = 9;
this.txtOutput.Text = "";
//
// cmdClear
//
this.cmdClear.Location = new System.Drawing.Point(34, 538);
this.cmdClear.Name = "cmdClear";
this.cmdClear.Size = new System.Drawing.Size(126, 21);
this.cmdClear.TabIndex = 10;
this.cmdClear.Text = "Clear Output Window";
this.cmdClear.UseVisualStyleBackColor = true;
this.cmdClear.Click += new System.EventHandler(this.cmdClear_Click);
//
// cmdSaveToFile
//
this.cmdSaveToFile.Location = new System.Drawing.Point(166, 538);
this.cmdSaveToFile.Name = "cmdSaveToFile";
this.cmdSaveToFile.Size = new System.Drawing.Size(126, 21);
this.cmdSaveToFile.TabIndex = 11;
this.cmdSaveToFile.Text = "Save Output to File";
this.cmdSaveToFile.UseVisualStyleBackColor = true;
this.cmdSaveToFile.Click += new System.EventHandler(this.cmdSaveToFile_Click);
//
// rtbTreeComposition
//
this.rtbTreeComposition.AutoSize = true;
this.rtbTreeComposition.Location = new System.Drawing.Point(377, 166);
this.rtbTreeComposition.Name = "rtbTreeComposition";
this.rtbTreeComposition.Size = new System.Drawing.Size(91, 17);
this.rtbTreeComposition.TabIndex = 12;
this.rtbTreeComposition.TabStop = true;
this.rtbTreeComposition.Text = "Find Pair Tree";
this.rtbTreeComposition.UseVisualStyleBackColor = true;
//
// Decoder
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(981, 571);
this.Controls.Add(this.rtbTreeComposition);
this.Controls.Add(this.cmdSaveToFile);
this.Controls.Add(this.cmdClear);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.label14);
this.Controls.Add(this.label13);
this.Controls.Add(this.label12);
this.Controls.Add(this.label1);
this.Controls.Add(this.panel1);
this.Controls.Add(this.radioButton2);
this.Controls.Add(this.radioButton1);
this.Controls.Add(this.cmdMenu);
this.Controls.Add(this.txtKeywords);
this.Controls.Add(this.decode);
this.Controls.Add(this.txtInput);
this.Name = "Decoder";
this.Text = "ADFGX Decoder";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtInput;
private System.Windows.Forms.Button decode;
private System.Windows.Forms.TextBox txtKeywords;
private System.Windows.Forms.Button cmdMenu;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtKey25;
private System.Windows.Forms.TextBox txtKey20;
private System.Windows.Forms.TextBox txtKey15;
private System.Windows.Forms.TextBox txtKey10;
private System.Windows.Forms.TextBox txtKey5;
private System.Windows.Forms.TextBox txtKey24;
private System.Windows.Forms.TextBox txtKey19;
private System.Windows.Forms.TextBox txtKey14;
private System.Windows.Forms.TextBox txtKey9;
private System.Windows.Forms.TextBox txtKey4;
private System.Windows.Forms.TextBox txtKey23;
private System.Windows.Forms.TextBox txtKey18;
private System.Windows.Forms.TextBox txtKey13;
private System.Windows.Forms.TextBox txtKey8;
private System.Windows.Forms.TextBox txtKey3;
private System.Windows.Forms.TextBox txtKey22;
private System.Windows.Forms.TextBox txtKey17;
private System.Windows.Forms.TextBox txtKey12;
private System.Windows.Forms.TextBox txtKey7;
private System.Windows.Forms.TextBox txtKey2;
private System.Windows.Forms.TextBox txtKey21;
private System.Windows.Forms.TextBox txtKey16;
private System.Windows.Forms.TextBox txtKey11;
private System.Windows.Forms.TextBox txtKey6;
private System.Windows.Forms.TextBox txtKey1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Button cmdRandom;
private System.Windows.Forms.Button cmdLongWay;
private System.Windows.Forms.TextBox txtKeyword;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.ComboBox cmbNumberOfThreads;
private System.Windows.Forms.RadioButton rdbDynamic;
private System.Windows.Forms.RadioButton rdbStatic;
private System.Windows.Forms.RichTextBox txtOutput;
private System.Windows.Forms.Button cmdClear;
private System.Windows.Forms.Button cmdSaveToFile;
private System.Windows.Forms.RadioButton rtbTreeComposition;
}
}
|
gpl-3.0
|
kevL/0xC_kL
|
src/Ruleset/StatString.cpp
|
5173
|
/*
* Copyright 2010-2020 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StatString.h"
//#include <vector>
namespace OpenXcom
{
/**
* Creates a blank StatString.
*/
StatString::StatString()
{}
/**
* Cleans up the extra StatString.
*/
StatString::~StatString()
{}
/**
* Loads the StatString from a YAML file.
* @param node YAML node.
*/
void StatString::load(const YAML::Node &node)
{
std::string conditionNames[] =
{
"psiStrength",
"psiSkill",
"bravery",
"strength",
"firing",
"reactions",
"stamina",
"tu",
"health",
"throwing"
};
_stringToBeAddedIfAllConditionsAreMet = node["string"].as<std::string>(_stringToBeAddedIfAllConditionsAreMet);
for (size_t
i = 0;
i < sizeof(conditionNames) / sizeof(conditionNames[0]);
i++)
{
if (node[conditionNames[i]])
_conditions.push_back(getCondition(conditionNames[i], node));
}
}
/**
* Generates a condition from YAML.
* @param conditionName Stat name of the condition.
* @param node YAML node.
* @return New StatStringCondition.
*/
StatStringCondition* StatString::getCondition(
const std::string& conditionName,
const YAML::Node& node) const
{
// These are the defaults from xcomutil
int
minValue = 0,
maxValue = 255;
if (node[conditionName][0])
minValue = node[conditionName][0].as<int>(minValue);
if (node[conditionName][1])
maxValue = node[conditionName][1].as<int>(maxValue);
StatStringCondition* thisCondition = new StatStringCondition(
conditionName,
minValue,
maxValue);
return thisCondition;
}
/**
* Gets the conditions associated with this StatString.
* @return List of StatStringConditions.
*/
const std::vector<StatStringCondition*> StatString::getConditions() const
{
return _conditions;
}
/**
* Gets the string to add to a name for this StatString.
* @return StatString... string.
*/
std::string StatString::getString() const
{
return _stringToBeAddedIfAllConditionsAreMet;
}
/**
* Calculates the list of StatStrings that apply to certain unit stats.
* @param currentStats Unit stats.
* @param statStrings List of statString rules.
* @param psiStrengthEval Are psi stats available?
* @return Resulting string of all valid StatStrings.
*/
std::wstring StatString::calcStatString( // static.
UnitStats& currentStats,
const std::vector<StatString*>& statStrings,
bool psiStrengthEval)
{
size_t conditionsMet;
int
minVal,
maxVal;
std::string conditionName, string;
std::wstring
ws,
statString;
bool continueCalc = true;
std::map<std::string, int> currentStatsMap = getCurrentStats(currentStats);
for (std::vector<StatString*>::const_iterator
i1 = statStrings.begin();
i1 != statStrings.end()
&& continueCalc;
++i1)
{
string = (*i1)->getString();
const std::vector<StatStringCondition*> conditions = (*i1)->getConditions();
conditionsMet = 0;
for (std::vector<StatStringCondition*>::const_iterator
i2 = conditions.begin();
i2 != conditions.end()
&& continueCalc;
++i2)
{
conditionName = (*i2)->getConditionName();
minVal = (*i2)->getMinVal();
maxVal = (*i2)->getMaxVal();
if (currentStatsMap.find(conditionName) != currentStatsMap.end())
{
if (currentStatsMap[conditionName] >= minVal
&& currentStatsMap[conditionName] <= maxVal
&& (conditionName != "psiStrength"
|| currentStats.psiSkill > 0
|| psiStrengthEval))
{
conditionsMet++;
}
if (conditionsMet == conditions.size())
{
ws.assign(string.begin(), string.end());
statString = statString + ws;
if (ws.length() > 1)
continueCalc = false;
}
}
}
}
return statString;
}
/**
* Get a map associating stat names to unit stats.
* @param currentStats Unit stats to use.
* @return Map of unit stats.
*/
std::map<std::string, int> StatString::getCurrentStats(UnitStats& currentStats) // static.
{
std::map<std::string, int> currentStatsMap;
currentStatsMap["psiStrength"] = currentStats.psiStrength;
currentStatsMap["psiSkill"] = currentStats.psiSkill;
currentStatsMap["bravery"] = currentStats.bravery;
currentStatsMap["strength"] = currentStats.strength;
currentStatsMap["firing"] = currentStats.firing;
currentStatsMap["reactions"] = currentStats.reactions;
currentStatsMap["stamina"] = currentStats.stamina;
currentStatsMap["tu"] = currentStats.tu;
currentStatsMap["health"] = currentStats.health;
currentStatsMap["throwing"] = currentStats.throwing;
return currentStatsMap;
}
}
|
gpl-3.0
|
MECTsrl/ATCMcontrol_Engineering
|
src/COM/softing/fc/CE/CEWatchView/CeWatchList.cpp
|
76454
|
#include "stdafx.h"
#include "resource.h"
#include "CeWatchList.h"
#include "CeWatchSheetInsVar.h"
#include "PageInsVarTree.h"
#include "PageInsVarList.h"
#include "CeWatchBackEnd.h"
#include "CeSymbol.h"
#include "CeWatchEdit.h"
#include "fc_todebug\fc_assert.h"
#include "dragitem.h"
#include <afxadv.h>
IMPLEMENT_SERIAL (CWatchExpressionDragItem, CObject, CB_FORMAT_4CWATCHEXPR_VERSION)
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CCeWatchList
//*****************************************************************************
CCeWatchList::CCeWatchList()
//*****************************************************************************
{
m_nColumns = 0;
m_xIndent = -1;
m_pEditContainer = NULL;
m_RootVar.SetName("Root");
m_pBackEnd = NULL;
m_pRootSymbol = NULL; // 10.10.06 SIS
m_pDragImage = NULL;
m_iSrcItem = -1;
m_pDropTarget = new CCeWatchDropTarget;
m_uiWatchExpressionCBFormat = RegisterClipboardFormat (CB_FORMAT_4CWATCHEXPR);
}
//*****************************************************************************
CCeWatchList::~CCeWatchList()
//*****************************************************************************
{
if (m_pEditContainer != NULL)
delete m_pEditContainer;
if (m_pDropTarget != NULL)
delete m_pDropTarget;
// 10.10.06 SIS >>
if(m_pRootSymbol)
{
delete m_pRootSymbol;
}
// 10.10.06 SIS <<
SetBackEnd(NULL);
}
//*****************************************************************************
void CCeWatchList::SetBackEnd(CCeWatchBackEnd* pBackEnd)
//*****************************************************************************
{
m_pBackEnd = pBackEnd;
// 10.10.06 SIS >>
if (m_pBackEnd != NULL)
{
LoadSymbols();
}
// 10.10.06 SIS <<
UpdateConnections();
}
// 10.10.06 SIS >>
BOOL CCeWatchList::LoadSymbols()
{
if(!m_pBackEnd)
{
return FALSE;
}
if(m_pRootSymbol)
{
delete m_pRootSymbol;
}
CWaitCursor wait; // display wait cursor
m_pRootSymbol = new CCeSymbol(true);
if(!m_pRootSymbol->Load(m_pBackEnd->GetDebugInfo()))
{
delete m_pRootSymbol;
m_pRootSymbol = NULL;
return FALSE;
}
return TRUE;
}
// 10.10.06 SIS <<
BEGIN_MESSAGE_MAP(CCeWatchList, CListCtrl)
//{{AFX_MSG_MAP(CCeWatchList)
ON_MESSAGE(WM_CEWATCH_ENDEDIT, OnEndLabelEdit)
ON_MESSAGE(WM_CEWATCH_UPDATECONNECTIONS, OnUpdateConnections)
ON_WM_CHAR()
ON_NOTIFY_REFLECT(NM_CLICK, OnClick)
ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemChanged)
ON_WM_KEYUP()
ON_WM_CONTEXTMENU()
ON_COMMAND(IDM_REMOVE_ALL_VARIABLES, OnRemoveAllVariables)
ON_COMMAND(IDM_REMOVE_SELECTED_VARIABLES, OnRemoveSelectedVariables)
ON_COMMAND(IDM_ADD_VARIABLE_FROM_LIST, OnAddVariableFromList)
ON_COMMAND(IDM_ADD_VARIABLE, OnAddVariable)
ON_WM_VSCROLL()
ON_WM_SIZE()
ON_COMMAND(IDM_LOAD_WATCHES, OnLoadWatches)
ON_COMMAND(IDM_STORE_WATCHES, OnStoreWatches)
ON_NOTIFY_REFLECT(LVN_DELETEITEM, OnDeleteItem)
ON_NOTIFY_REFLECT(LVN_BEGINDRAG, OnBeginDrag)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
ON_NOTIFY_REFLECT(LVN_BEGINLABELEDIT, OnBeginLabelEdit)
ON_COMMAND(IDM_EDIT_FORMAT, OnEditFormat)
ON_COMMAND(IDM_EDIT_NAME, OnEditName)
ON_COMMAND(IDM_EDIT_VALUE, OnEditValue)
ON_COMMAND(IDM_DEC_RANGE, OnDecRange)
ON_COMMAND(IDM_INC_RANGE, OnIncRange)
ON_WM_MOUSEWHEEL()
ON_WM_SETFOCUS()
ON_WM_KILLFOCUS()
ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblClick)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//*****************************************************************************
void CCeWatchList::Init()
//*****************************************************************************
{
// create header
CString strHeader;
m_nColumns = 0;
for (int ii = 0; ii < CEWATCH_NCOLUMNS; ii++)
{
strHeader.LoadString(IDS_HEADER_NAME_TYPICAL + ii);
int w = GetStringWidth(strHeader);
strHeader.LoadString(IDS_HEADER_NAME + ii);
m_HeaderWidth[ii] = GetStringWidth(strHeader) + 4;
w = (w > m_HeaderWidth[ii] ? w : m_HeaderWidth[ii]) + GetStringWidth("WW");
InsertColumn(ii, strHeader, LVCFMT_LEFT, w, -1);
m_nColumns++;
}
// attach image list
VERIFY(m_ImageList.Create(IDB_VAR_STATE, 16, 0, RGB(255, 0, 255)));
m_ImageList.SetBkColor(GetSysColor(COLOR_WINDOW));
SetImageList(&m_ImageList, LVSIL_SMALL);
//@@@@@@@@@@@@@@@@
// Load("d:\\4control\\bin\\demo\\IntelligentLightsSimple\\IntelligentLightsSimple.4cw");
//@@@@@@@@@@@@@@@@
// register drop target (drag and drop from ST-editor)
ASSERT(m_pDropTarget != NULL);
if (m_pDropTarget != NULL)
m_pDropTarget->Register(this);
}
//*****************************************************************************
bool CCeWatchList::Load(LPCTSTR strFileName)
//*****************************************************************************
{
DeleteAllVar();
bool rv = false;
ASSERT(AfxIsValidString(strFileName));
ASSERT(strlen(strFileName) > 0);
CArray<CString*, CString*> strItemData;
if (strlen(strFileName) > 0)
{
CStdioFile file;
if (file.Open (strFileName, CFile::modeRead))
{
CString str;
if (file.ReadString(str))
{
if (str == CEWATCH_FILE_VERSION)
{
file.ReadString(str);
int nCount = atoi(str);
if ((nCount > 0) || (str == "0"))
{
strItemData.SetSize(nCount);
for (int ii = 0; ii < nCount; ii++)
{
CString* pStr = new CString();
file.ReadString(*pStr);
strItemData.SetAt(ii, pStr);
}
rv = m_RootVar.ReadData(file);
}
}
else {
//Version conflict.
CString strMessage;
strMessage.Format(IDS_ERROR_VERSION,strFileName,str,CEWATCH_FILE_VERSION);
::AfxMessageBox(strMessage,MB_OK);
}
}
file.Close();
}
}
if (rv)
{
for (int ii = 0; ii < m_RootVar.GetChildrenCount(); ii++)
InsertVarItem(m_RootVar.GetChild(ii), -1, &strItemData);
}
for (int ii = 0; ii < strItemData.GetSize(); ii++)
{
if (strItemData.GetAt(ii) != NULL)
delete strItemData.GetAt(ii);
}
strItemData.RemoveAll();
UpdateConnections();
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
return rv;
}
//*****************************************************************************
bool CCeWatchList::Store(LPCTSTR strFileName)
//*****************************************************************************
{
// adjust different orders of the visual elements and
// the internal structure
CCeWatchElement* pVar = NULL;
int count = 0;
for (int ii = 0; ii < GetItemCount(); ii++)
{
pVar = GetVar(ii);
if (pVar->GetLevel() == 1)
{
m_RootVar.SetChild(count, pVar);
count++;
}
}
ASSERT(count == m_RootVar.GetChildrenCount());
// store data
ASSERT(AfxIsValidString(strFileName));
ASSERT(strlen(strFileName) > 0);
if (strlen(strFileName) > 0)
{
CStdioFile file;
CString str;
if (file.Open (strFileName, CFile::modeCreate | CFile::modeWrite))
{
file.WriteString(CEWATCH_FILE_VERSION);
file.WriteString("\n");
// store list item data
str.Format("%d\n", GetItemCount());
file.WriteString(str);
for (int ii = 0; ii < GetItemCount(); ii++)
{
str.Format("%d;", (int)IsExpanded(ii));
str += GetWatchIndices(ii)->AsString() + "\n";
file.WriteString(str);
}
// store watch element data
bool rv = m_RootVar.WriteData(file);
file.Close();
return rv;
}
}
return false;
}
// SIS: save and load in XML
bool CCeWatchList::SaveToNode(CXMLNode& rtNode, CXMLDocument& rtDocument)
{
// save expand information in watch elements
SaveExpandInfo();
// run over all items
int iItemCount = GetItemCount();
CCeDisplayElement* pDisplayElement;
CCeWatchElement* pWatchElement;
CString strIndexRange; // 15.12.05 SIS
for (int iItem = 0; iItem < iItemCount; iItem++)
{
pDisplayElement = GetDisplayElement(iItem);
ASSERT(pDisplayElement);
if(pDisplayElement)
{
pWatchElement = pDisplayElement->GetWatchElement();
ASSERT(pWatchElement);
if(pWatchElement && pWatchElement->GetLevel() == 1)
{
CXMLNode tNodeNew;
if(rtDocument.CreateNode(tNodeNew, CEWATCH_XMLTAG_VARNODE))
{
// 15.12.05 SIS >>
strIndexRange = pDisplayElement->GetWatchIndices().AsString(TRUE);
if(pWatchElement->SaveToNode(tNodeNew, rtDocument,strIndexRange))
{
rtNode.AppendChild(tNodeNew);
}
// 15.12.05 SIS <<
}
}
}
}
return true;
}
//------------------------------------------------------------------*
/**
* save expand info.
*
* save expand info in watch items.
*
* @param -
* @return -
* @exception -
* @see -
*/
void CCeWatchList::SaveExpandInfo()
{
// run over all items
int iItemCount = GetItemCount();
CCeDisplayElement* pDisplayElement;
for (int iItem = 0; iItem < iItemCount; iItem++)
{
pDisplayElement = GetDisplayElement(iItem);
ASSERT(pDisplayElement);
if(pDisplayElement)
{
pDisplayElement->SaveExpandInfo();
}
}
}
bool CCeWatchList::LoadFromNode(CXMLNode& rtNode)
{
bool bReturn(false);
DeleteAllVar();
bReturn = m_RootVar.LoadFromNode(rtNode, m_pRootSymbol); // 10.10.06 SIS
if(bReturn)
{
for (int ii = 0; ii < m_RootVar.GetChildrenCount(); ii++)
{
AddVarItem(m_RootVar.GetChild(ii));
}
}
UpdateConnections();
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
return bReturn;
}
//*****************************************************************************
int CCeWatchList::InsertVarItem(CCeWatchElement* pVar, int index/*=-1*/, CArray<CString*, CString*>* pItemData/*=NULL*/, bool bEnsureVisible /*=false*/)
//*****************************************************************************
{
LV_ITEM lvItem;
lvItem.mask = LVIF_PARAM ;
lvItem.iSubItem = 0;
if (index >= 0)
lvItem.iItem = index;
else
lvItem.iItem = GetItemCount();
CCeDisplayElement* pDisplayElement = new CCeDisplayElement();
pDisplayElement->SetWatchElement(pVar);
if (lvItem.iItem > 0)
pDisplayElement->SetVerticalLineMask(GetDisplayElement(lvItem.iItem-1)->GetVerticalLineMask());
int iIndexMin, iIndexMax;
if (pVar->GetType().IsArray())
{
iIndexMin = pVar->GetType().GetArrayLowerBound();
iIndexMax = pVar->GetType().GetArrayUpperBound();
// 15.12.05 SIS >>
CString strIndexRange = pVar->GetIndexRange();
if(!strIndexRange.IsEmpty())
{
pDisplayElement->GetWatchIndices().Create(strIndexRange, iIndexMin, iIndexMax);
}
else
{
// #2149 27.10.04 SIS >>
// use new define CEWATCH_STD_ARRAY_LEN
pDisplayElement->GetWatchIndices().Create(iIndexMin, min(iIndexMax, iIndexMin + CEWATCH_STD_ARRAY_LEN - 1), iIndexMin, iIndexMax);
// #2149 27.10.04 SIS <<
}
// 15.12.05 SIS <<
}
if (pItemData != NULL)
{
if (lvItem.iItem < pItemData->GetSize())
{
CString* pStr = pItemData->GetAt(lvItem.iItem);
int iLen = pStr->GetLength();
if (pStr != NULL && iLen > 0)
{
int i1 = pStr->Find(';');
ASSERT(i1 >= 0);
if (i1 >= 0)
{
CString s1, s2;
s1 = pStr->Left(i1);
s2 = pStr->Mid(i1+1);
if (s1.GetLength() > 0)
pDisplayElement->SetExpanded(pStr->GetAt(0) != '0');
if (s2.GetLength() > 0 && pVar->GetType().IsArray())
pDisplayElement->GetWatchIndices().Create(s2, iIndexMin, iIndexMax);
}
}
}
}
lvItem.lParam = (LPARAM)pDisplayElement;
int iNewIten = InsertItem(&lvItem);
UpdateVertLineMasks(lvItem.iItem);
if (bEnsureVisible)
EnsureVisible(iNewIten, FALSE);
int count = 1;
if (IsExpanded(lvItem.iItem))
{
long jj;
if (pVar->GetType().IsArray())
{
CCeWatchIndices* pI = GetWatchIndices(lvItem.iItem);
ASSERT(pI != NULL);
long iIndex;
while (pI->GetNextIndex(iIndex, count == 1))
{
jj = iIndex - pI->GetMinIndex();
ASSERT(jj >= 0 && jj < pVar->GetChildrenCount());
count += InsertVarItem(pVar->GetChild(jj), lvItem.iItem + count, pItemData);
}
}
else
{
for (jj = 0; jj < pVar->GetChildrenCount(); jj++)
{
count += InsertVarItem(pVar->GetChild(jj), lvItem.iItem + count, pItemData);
}
}
}
return count;
}
//*****************************************************************************
int CCeWatchList::AddVarItem(CCeWatchElement* pVar)
//*****************************************************************************
{
// 10.10.06 SIS >>
if(pVar == NULL)
{
return -1;
}
// 10.10.06 SIS <<
LV_ITEM lvItem;
lvItem.mask = LVIF_PARAM ;
lvItem.iSubItem = 0;
lvItem.iItem = GetItemCount();
CCeDisplayElement* pDisplayElement = new CCeDisplayElement();
pDisplayElement->SetWatchElement(pVar);
if (lvItem.iItem > 0)
{
pDisplayElement->SetVerticalLineMask(GetDisplayElement(lvItem.iItem-1)->GetVerticalLineMask());
}
int iIndexMin, iIndexMax;
if (pVar->GetType().IsArray())
{
iIndexMin = pVar->GetType().GetArrayLowerBound();
iIndexMax = pVar->GetType().GetArrayUpperBound();
// 15.12.05 SIS >>
CString strIndexRange = pVar->GetIndexRange();
if(!strIndexRange.IsEmpty())
{
pDisplayElement->GetWatchIndices().Create(strIndexRange, iIndexMin, iIndexMax);
}
else
{
pDisplayElement->GetWatchIndices().Create(iIndexMin, min(iIndexMax, iIndexMin + 4), iIndexMin, iIndexMax);
}
// 15.12.05 SIS <<
}
pDisplayElement->SetExpanded(pVar->GetInitExpanded());
// if (s2.GetLength() > 0 && pVar->GetType().IsArray())
// pDisplayElement->GetWatchIndices().Create(s2, iIndexMin, iIndexMax);
lvItem.lParam = (LPARAM)pDisplayElement;
int iNewIten = InsertItem(&lvItem);
UpdateVertLineMasks(lvItem.iItem);
int count = 1;
if (IsExpanded(lvItem.iItem))
{
long jj;
if (pVar->GetType().IsArray())
{
CCeWatchIndices* pI = GetWatchIndices(lvItem.iItem);
ASSERT(pI != NULL);
long iIndex;
while (pI->GetNextIndex(iIndex, count == 1))
{
jj = iIndex - pI->GetMinIndex();
ASSERT(jj >= 0 && jj < pVar->GetChildrenCount());
// 10.10.06 SIS >>
if(jj >= pVar->GetChildrenCount())
{
break;
}
// 10.10.06 SIS <<
count += AddVarItem(pVar->GetChild(jj));
}
}
else
{
for (jj = 0; jj < pVar->GetChildrenCount(); jj++)
{
count += AddVarItem(pVar->GetChild(jj));
}
}
}
return count;
}
//*****************************************************************************
bool CCeWatchList::MoveVarItem(
int SrcItem,
int DestItem)
// Moves item SrcItem and all child items to DestItem
//*****************************************************************************
{
CCeWatchElement* pVar = GetVar(SrcItem);
CCeWatchElement* pChildVar = NULL;
int ii;
ASSERT(pVar != NULL);
if (pVar != NULL)
{
// save data of list elements
unsigned iParentLevel = pVar->GetLevel();
CArray<CCeDisplayElement*, CCeDisplayElement*> ItemDataArray;
ItemDataArray.Add(GetDisplayElement(SrcItem));
for (ii = SrcItem + 1; (ii < GetItemCount()) && (GetVar(ii)->GetLevel() > iParentLevel); ii++)
ItemDataArray.Add(GetDisplayElement(ii));
ASSERT(DestItem < SrcItem || DestItem >= SrcItem + ItemDataArray.GetSize());
if (DestItem < SrcItem || DestItem >= SrcItem + ItemDataArray.GetSize())
{
// delete source items
for (int ii = 0; ii < ItemDataArray.GetSize(); ii++)
{
SetItemData(SrcItem, NULL);
DeleteItem(SrcItem);
}
if (DestItem > SrcItem)
DestItem -= ItemDataArray.GetSize();
// insert new items
LV_ITEM lvItem;
lvItem.mask = LVIF_PARAM ;
lvItem.iSubItem = 0;
if (DestItem >= 0 && DestItem < GetItemCount())
lvItem.iItem = DestItem;
else
lvItem.iItem = GetItemCount();
for (ii = 0; ii < ItemDataArray.GetSize(); ii++)
{
lvItem.lParam = (LPARAM)ItemDataArray.GetAt(ii);;
InsertItem(&lvItem);
lvItem.iItem++;
}
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// CCeWatchList message handlers
//*****************************************************************************
void CCeWatchList::DeleteSubTree(int iItem)
//*****************************************************************************
{
CCeWatchElement* pVarParent = GetVar(iItem);
ASSERT(IsValidWatchElement(pVarParent));
if (pVarParent != NULL)
{
if (IsExpanded(iItem))
{
unsigned iParentLevel = pVarParent->GetLevel();
int iChildItemMax = iItem + 1;
while (iChildItemMax < GetItemCount())
{
CCeWatchElement* pVarChild = GetVar(iChildItemMax);
ASSERT(IsValidWatchElement(pVarChild));
if (pVarChild->GetLevel() <= iParentLevel)
break;
SetExpanded(iChildItemMax, false);
iChildItemMax++;
}
iChildItemMax--;
for (int ii = iChildItemMax; ii > iItem; ii--)
DeleteItem(ii);
SetExpanded(iItem, false);
RedrawItems(iItem, iItem);
}
}
}
//*****************************************************************************
void CCeWatchList::InsertSubTree(int iItem)
//*****************************************************************************
{
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(IsValidWatchElement(pVar));
if (pVar != NULL && pVar->GetChildrenCount() > 0)
{
if (!IsExpanded(iItem))
{
int count = 0;
long jj;
// insert array (may be a subset)
if (pVar->GetType().IsArray())
{
CCeWatchIndices* pI = GetWatchIndices(iItem);
long iIndex;
long lCount = pI->GetMaxIndex()-pI->GetMinIndex() + 1;
// 10.10.06 SIS >>
// if child count changed -> delete old children and insert new ones
if(lCount != pVar->GetChildrenCount())
{
pVar->DeleteAllChildren();
if(m_pRootSymbol)
{
CCeSymbol* pSymbol = m_pRootSymbol->FindChildRecursive(pVar->GetName());
if(pSymbol && CCeWatchElement::IsVarKindVisible(pSymbol->GetType().GetVarKind()))
{
pVar->AddChildren(pSymbol);
}
}
}
// 10.10.06 SIS <<
while (pI->GetNextIndex(iIndex, count == 0))
{
jj = iIndex - pI->GetMinIndex();
ASSERT(jj >= 0 && jj < pVar->GetChildrenCount());
count += InsertVarItem(pVar->GetChild(jj), iItem + 1 + count);
}
}
// insert structure (all elements)
else
{
for (jj = 0; jj < pVar->GetChildrenCount(); jj++)
{
count+= InsertVarItem(pVar->GetChild(jj), iItem + 1 + count);
}
}
SetExpanded(iItem, true);
RedrawItems(iItem, iItem);
}
}
}
//*****************************************************************************
void CCeWatchList::ToggleSubTree(int iItem)
//*****************************************************************************
{
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(IsValidWatchElement(pVar));
if (pVar != NULL && pVar->GetChildrenCount() > 0)
{
if (IsExpanded(iItem))
DeleteSubTree(iItem);
else
InsertSubTree(iItem);
}
}
//*****************************************************************************
CCeWatchElement* CCeWatchList::GetVar(int iItem)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
ASSERT(IsValidDisplayElement(pDisplayElement));
return pDisplayElement != NULL ? pDisplayElement->GetWatchElement() : NULL;
}
//*****************************************************************************
unsigned long CCeWatchList::GetVertLineMask(int iItem)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
return pDisplayElement != NULL ? pDisplayElement->GetVerticalLineMask() : 0;
}
//*****************************************************************************
CString CCeWatchList::GetFormat(int iItem)
//*****************************************************************************
{
CCeWatchElement* pVar = GetVar(iItem);
return pVar != NULL ? pVar->GetFormat() : CString("");
}
//*****************************************************************************
LONG CCeWatchList::GetExpressionHandle(int iItem)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
return pDisplayElement != NULL ? pDisplayElement->GetExpressionHandle() : -1;
}
//*****************************************************************************
CCeWatchIndices* CCeWatchList::GetWatchIndices(int iItem)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
return pDisplayElement != NULL ? &(pDisplayElement->GetWatchIndices()) : NULL;
}
//*****************************************************************************
bool CCeWatchList::IsExpanded(int iItem)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
return pDisplayElement != NULL ? pDisplayElement->IsExpanded() : false;
}
//*****************************************************************************
void CCeWatchList::SetExpanded(int iItem, bool bExpanded)
//*****************************************************************************
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
ASSERT(pDisplayElement != NULL);
if (pDisplayElement != NULL)
pDisplayElement->SetExpanded(bExpanded);
}
//*****************************************************************************
CCeDisplayElement* CCeWatchList::GetDisplayElement(int iItem)
//*****************************************************************************
{
ASSERT(iItem >= 0 && iItem < GetItemCount());
if (iItem >= 0 && iItem < GetItemCount())
return (CCeDisplayElement*)GetItemData(iItem);
else
return NULL;
}
//*****************************************************************************
CCeDisplayElement* CCeWatchList::GetSelectedDisplayElement()
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
return GetDisplayElement(iItem);
else
return NULL;
}
//*****************************************************************************
void CCeWatchList::GetSelectedDisplayElements (CArray<CCeDisplayElement *, CCeDisplayElement *> &displays)
//*****************************************************************************
{
POSITION pPosition;
displays.RemoveAll ();
pPosition = GetFirstSelectedItemPosition ();
while (pPosition != NULL)
{
int iItem;
CCeDisplayElement *pDisplay;
iItem = GetNextSelectedItem (pPosition);
pDisplay = GetDisplayElement (iItem);
if (pDisplay != NULL)
displays.Add (GetDisplayElement (iItem));
};
}
//*****************************************************************************
CCeWatchElement* CCeWatchList::GetSelectedVar()
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
return GetVar(iItem);
else
return NULL;
}
//*****************************************************************************
int CCeWatchList::GetSelectedItem()
//*****************************************************************************
{
if ( GetSelectedCount() == 1)
{
POSITION pos = GetFirstSelectedItemPosition();
ASSERT(pos != NULL);
return GetNextSelectedItem(pos);
}
return -1;
}
// 15.12.05 SIS >>
//*****************************************************************************
int CCeWatchList::GetNextInsertPos(int iItemStart)
//*****************************************************************************
{
if(iItemStart == -1)
{
return iItemStart; // insert as last
}
int iItemCount = GetItemCount();
CCeDisplayElement* pDisplayElement;
CCeWatchElement* pWatchElement;
for(int iItem = iItemStart; iItem < iItemCount; ++iItem)
{
pDisplayElement = GetDisplayElement(iItem);
pWatchElement = pDisplayElement->GetWatchElement();
if(pWatchElement && pWatchElement->GetLevel() <= 1)
{
break;
}
}
return iItem;
}
// 15.12.05 SIS <<
//*****************************************************************************
bool CCeWatchList::DeleteVar(int iItem)
//*****************************************************************************
{
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(pVar != NULL);
if (pVar != NULL)
{
CCeWatchElement* pVarParent = pVar->GetParent();
ASSERT(pVarParent != NULL);
if (pVarParent != NULL)
{
// only objects wich are directly below the root object
// can be deleted
if (pVarParent->GetParent() == NULL)
{
DeleteSubTree(iItem);
DeleteItem(iItem);
pVarParent->DeleteChild(pVar);
if(GetItemCount() > iItem)
{
SetItemState(iItem, LVIS_SELECTED, LVIS_SELECTED);
}
else if(iItem > 0)
{
SetItemState(iItem-1, LVIS_SELECTED, LVIS_SELECTED);
}
return true;
}
}
}
return false;
}
//*****************************************************************************
bool CCeWatchList::DeleteSelectedVar()
//*****************************************************************************
{
bool rv = false;
CCeWatchElement* pVar = NULL;
CList<int, int> tDeleteList;
int iItem;
// collect all selected items in reverse order
POSITION pos = GetFirstSelectedItemPosition();
while(pos)
{
iItem = GetNextSelectedItem(pos);
tDeleteList.AddHead(iItem);
}
// delete items
POSITION listpos = tDeleteList.GetHeadPosition();
while(listpos)
{
iItem = tDeleteList.GetNext(listpos);
rv |= DeleteVar(iItem);
}
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
return rv;
}
//*****************************************************************************
bool CCeWatchList::DeleteAllVar()
//*****************************************************************************
{
DeleteAllItems();
bool rv = m_RootVar.DeleteAllChildren();
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
return rv;
}
//*****************************************************************************
void CCeWatchList::OnClick(NMHDR* pNMHDR, LRESULT* pResult)
//*****************************************************************************
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
if (pNMListView->iItem >= 0)
{
bool bUpdateConn = false;
CCeWatchElement* pVar = GetVar(pNMListView->iItem);
if (pVar != NULL)
{
if (pVar->GetChildrenCount() > 0)
{
// Hit Test of the "+" or "-" chararcter
CRect LabelRect;
GetItemRect(pNMListView->iItem, LabelRect, LVIR_LABEL);
int xmin = LabelRect.left + (pVar->GetLevel()-1) * m_xIndent;
int xmax = xmin + m_xIndent;
if (pNMListView->ptAction.x >= xmin && pNMListView->ptAction.x <= xmax)
{
ToggleSubTree(pNMListView->iItem);
bUpdateConn = true;
}
}
}
// not very nice, but the only way I found to check
// for scrolling caused by a click into the last line
if (pNMListView->iItem == GetTopIndex() + GetCountPerPage())
bUpdateConn = true;
if (bUpdateConn)
UpdateConnections();
}
*pResult = 0;
}
//*****************************************************************************
void CCeWatchList::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult)
//*****************************************************************************
{
//NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
//if (pNMListView->iItem >= 0 && (pNMListView->uNewState & LVIS_SELECTED))
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
//else
// GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
*pResult = 0;
}
//*****************************************************************************
bool CCeWatchList::IncRange(bool bDec)
//*****************************************************************************
{
if (CheckIncRange(bDec))
{
int iItem = GetSelectedItem();
GetWatchIndices(iItem)->Inc(bDec);
RedrawItems(iItem, iItem);
if (IsExpanded(iItem))
{
DeleteSubTree(iItem);
InsertSubTree(iItem);
UpdateConnections();
}
return true;
}
return false;
}
//*****************************************************************************
bool CCeWatchList::ExpandTree(bool bCollapse)
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
{
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(pVar != NULL);
if (pVar != NULL && pVar->GetChildrenCount() > 0)
{
if (( IsExpanded(iItem) && bCollapse) ||
(!IsExpanded(iItem) && !bCollapse))
{
ToggleSubTree(iItem);
UpdateConnections();
return true;
}
}
}
return false;
}
//*****************************************************************************
void CCeWatchList::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
//*****************************************************************************
{
if (nChar == '*' || nChar == '_')
{
if (IncRange(nChar == '_'))
return;
}
else if (nChar == '+' || nChar == '-')
{
if (ExpandTree(nChar == '-'))
return;
}
CListCtrl::OnChar(nChar, nRepCnt, nFlags);
}
//*****************************************************************************
void CCeWatchList::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
//*****************************************************************************
{
switch (nChar)
{
case VK_DELETE:
OnRemoveSelectedVariables();
UpdateConnections();
break;
case VK_INSERT:
OnAddVariable();
UpdateConnections();
break;
case VK_NEXT:
case VK_PRIOR:
case VK_UP:
case VK_DOWN:
UpdateConnections();
break;
}
CListCtrl::OnKeyUp(nChar, nRepCnt, nFlags);
}
//*****************************************************************************
void CCeWatchList::OnContextMenu(CWnd* pWnd, CPoint point)
//*****************************************************************************
{
CMenu menu;
if (!menu.LoadMenu (IDR_WATCH_POPUP))
return ;
// SHIFT_F10 15.12.04 SIS >>
// use center point if not specified (SHIFT + F10)
if(point.x == -1 && point.y == -1)
{
CRect rect;
GetClientRect(rect);
ClientToScreen(rect);
point = rect.CenterPoint();
}
// SHIFT_F10 15.12.04 SIS <<
CMenu *pPopup = menu.GetSubMenu (0);
ASSERT (pPopup != NULL);
int iSelectedItems = GetSelectedCount();
// 15.12.05 SIS >>
// bool bInsert = CheckVariableInsert();
pPopup->EnableMenuItem (IDM_ADD_VARIABLE, MF_ENABLED);
pPopup->EnableMenuItem (IDM_ADD_VARIABLE_FROM_LIST, MF_ENABLED);
// 15.12.05 SIS <<
pPopup->EnableMenuItem (IDM_REMOVE_SELECTED_VARIABLES, CheckVariableDelete() ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_REMOVE_ALL_VARIABLES, GetItemCount() > 0 ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_EDIT_NAME, CheckNameEdit() ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_EDIT_VALUE, CheckValueEdit() ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_EDIT_FORMAT, CheckFormatEdit() ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_INC_RANGE, CheckIncRange(false) ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_DEC_RANGE, CheckIncRange(true) ? MF_ENABLED : MF_GRAYED);
pPopup->EnableMenuItem (IDM_LOAD_WATCHES, MF_ENABLED);
pPopup->EnableMenuItem (IDM_STORE_WATCHES, MF_ENABLED);
::TrackPopupMenu (pPopup->m_hMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, 0, m_hWnd, NULL);
}
//*****************************************************************************
void CCeWatchList::OnRemoveAllVariables()
//*****************************************************************************
{
DeleteAllVar();
}
//*****************************************************************************
void CCeWatchList::OnRemoveSelectedVariables()
//*****************************************************************************
{
DeleteSelectedVar();
}
//*****************************************************************************
void CCeWatchList::OnBeginLabelEdit(NMHDR* pNMHDR, LRESULT* pResult)
//*****************************************************************************
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
*pResult = 1;
POINT pt;
::GetCursorPos(&pt);
ScreenToClient(&pt);
BeginLabelEdit(pDispInfo->item.iItem, pt.x);
}
//*****************************************************************************
bool CCeWatchList::GetEditRect(int iItem, int iEditType, CRect& rect)
//*****************************************************************************
{
if (iItem >= 0)
{
GetItemRect(iItem, rect, LVIR_LABEL);
rect.bottom--;
if (iEditType == CEWATCH_EDITTYPE_NAME)
{
const CCeWatchElement* pVar = GetVar(iItem);
ASSERT(pVar != NULL);
if (pVar != NULL)
rect.left += (int)pVar->GetLevel() * m_xIndent;
else
return false;
}
else if (iEditType == CEWATCH_EDITTYPE_VALUE)
{
rect.left = rect.right + GetColumnWidth(1);
rect.right = rect.left + GetColumnWidth(2);
}
else if (iEditType == CEWATCH_EDITTYPE_FORMAT)
{
rect.left = rect.right + GetColumnWidth(1) + GetColumnWidth(2) + GetColumnWidth(3) + GetColumnWidth(4);
rect.right = rect.left + GetColumnWidth(5);
}
else
{
return false;
}
rect.left++;
return true;
}
return false;
}
//*****************************************************************************
void CCeWatchList::BeginLabelEdit(int iItem, int xPos)
//*****************************************************************************
{
if (m_pBackEnd != NULL && iItem >= 0)
{
ASSERT(m_pEditContainer == NULL);
CCeDisplayElement* pDisplay = GetDisplayElement(iItem);
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(pVar != NULL);
if (pVar != NULL)
{
CRect EditRectName, EditRectValue, EditRectFormat;
GetEditRect(iItem, CEWATCH_EDITTYPE_NAME, EditRectName);
GetEditRect(iItem, CEWATCH_EDITTYPE_VALUE, EditRectValue);
GetEditRect(iItem, CEWATCH_EDITTYPE_FORMAT, EditRectFormat);
// edit name of top level elements or range of arrays
if (xPos > EditRectName.left && xPos < EditRectName.right)
{
// 10.10.06 SIS >>
// check, if type has changed
if(m_pRootSymbol)
{
CCeSymbol* pSymbol = m_pRootSymbol->FindChildRecursive(pVar->GetName());
if(pSymbol)
{
if(pVar->GetType().GetName().CompareNoCase(pSymbol->GetType().GetName()) != 0)
{
pVar->SetType(pSymbol->GetType());
if(pVar->GetType().IsArray())
{
pVar->CheckArrayIndices();
}
else
{
CCeWatchElement* pNew = new CCeWatchElement(pSymbol);
InsertVariable(pNew, iItem);
DeleteVar(iItem + 1);
UpdateConnections();
}
UpdateConnections();
return; // type has changed, do not edit
}
}
}
// 10.10.06 SIS <<
if (pVar->GetLevel() == 1 || pVar->GetType().IsArray())
{
m_pEditContainer = new CCeWatchEditContainer(iItem, CEWATCH_EDITTYPE_NAME, GetDisplayElement(iItem));
m_pEditContainer->Create(EditRectName, this, 1);
}
}
// change value of variable
else if (xPos > EditRectValue.left && xPos < EditRectValue.right)
{
if (pVar->GetType().IsSimpleType() && pVar->IsConnected())
{
m_pEditContainer = new CCeWatchEditContainer(iItem, CEWATCH_EDITTYPE_VALUE, GetDisplayElement(iItem));
m_pEditContainer->Create(EditRectValue, this, 1);
}
}
// change format of variable
else if (xPos > EditRectFormat.left && xPos < EditRectFormat.right)
{
if (pVar->GetType().IsSimpleType())
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
ASSERT(pDisplayElement != NULL);
if (pDisplayElement != NULL)
{
m_pEditContainer = new CCeWatchEditContainer(iItem, CEWATCH_EDITTYPE_FORMAT, GetDisplayElement(iItem));
m_pEditContainer->Create(EditRectFormat, this, 1);
}
}
}
}
}
}
//*****************************************************************************
void CCeWatchList::EndLabelEdit(WPARAM wParam /*=IDOK*/)
//*****************************************************************************
{
if (m_pBackEnd != NULL)
{
if (m_pEditContainer != NULL)
{
if (m_pEditContainer->IsVisible())
{
if (wParam == IDOK)
{
if (m_pEditContainer->GetEditType() == CEWATCH_EDITTYPE_NAME)
{
if (!EndNameEdit())
return;
}
else if (m_pEditContainer->GetEditType() == CEWATCH_EDITTYPE_VALUE)
{
if (!EndValueEdit())
return;
}
else if (m_pEditContainer->GetEditType() == CEWATCH_EDITTYPE_FORMAT)
{
if (!EndFormatEdit())
return;
}
UpdateConnections();
}
}
delete m_pEditContainer;
m_pEditContainer = NULL;
SetFocus();
}
}
}
//*****************************************************************************
bool CCeWatchList::EndNameEdit()
//*****************************************************************************
{
ASSERT(m_pEditContainer != NULL);
ASSERT(m_pBackEnd != NULL);
int iEditItem = m_pEditContainer->GetEditItem();
ASSERT(iEditItem >= 0 && iEditItem < GetItemCount());
if (iEditItem >= 0 && iEditItem < GetItemCount())
{
CCeWatchElement* pVar = GetVar(iEditItem);
ASSERT(pVar != NULL);
if (pVar != NULL && m_pBackEnd != NULL)
{
CString str;
m_pEditContainer->GetText(str);
int iSep = str.Find(',');
CString strName, strRange;
if (iSep > 0)
{
strName = str.Left(iSep);
strRange = str.Mid(iSep + 1);
}
else
{
strName = str;
}
strName.TrimLeft();
strName.TrimRight();
if (pVar->GetLevel() == 1)
{
// 10.10.06 SIS >>
if (pVar->GetType().IsArray())
{
if (strRange != GetWatchIndices(iEditItem)->AsString())
{
if (!GetWatchIndices(iEditItem)->Create(strRange, pVar->GetType().GetArrayLowerBound(), pVar->GetType().GetArrayUpperBound()))
{
m_pEditContainer->IgnoreFocus(true);
ErrorMsg(IDS_ERROR_ARRAYINDEX);
m_pEditContainer->IgnoreFocus(false);
return true;
}
}
}
BOOL bInserted = FALSE;
if(m_pRootSymbol && m_pBackEnd)
{
CString strText;
CCeWatchType type;
if(m_pBackEnd->GetTypeAndText(strName, type, strText))
{
bool bExpanded = IsExpanded(iEditItem);
CCeSymbol* pSymbol = m_pRootSymbol->FindChildRecursive(strText);
if(pSymbol && CCeWatchElement::IsVarKindVisible(pSymbol->GetType().GetVarKind()))
{
CCeWatchElement* pNew = new CCeWatchElement(pSymbol);
pNew->SetIndexRange(strRange);
pNew->SetName(strName);
InsertVariable(pNew, iEditItem);
bInserted = TRUE;
DeleteVar(iEditItem + 1);
if(bExpanded)
{
InsertSubTree(iEditItem);
}
UpdateConnections();
}
}
}
if(!bInserted)
{
// 10.10.06 SIS <<
CCeWatchElement *pInsertedElement=NULL;
InsertExpression(str, pInsertedElement, iEditItem);
if (pInsertedElement != NULL)
{
pVar = pInsertedElement;
}
DeleteVar(iEditItem + 1);
}
}
if (pVar->GetType().IsArray())
{
if (strRange != GetWatchIndices(iEditItem)->AsString())
{
if (GetWatchIndices(iEditItem)->Create(strRange, pVar->GetType().GetArrayLowerBound(), pVar->GetType().GetArrayUpperBound()))
{
if (IsExpanded(iEditItem))
{
DeleteSubTree(iEditItem);
InsertSubTree(iEditItem);
}
}
else
{
m_pEditContainer->IgnoreFocus(true);
ErrorMsg(IDS_ERROR_ARRAYINDEX);
m_pEditContainer->IgnoreFocus(false);
return true; // 10.10.06 SIS: return true to close edit control
}
}
}
}
}
return true;
}
//*****************************************************************************
bool CCeWatchList::EndValueEdit()
//*****************************************************************************
{
ASSERT(m_pEditContainer != NULL);
ASSERT(m_pBackEnd != NULL);
int iEditItem = m_pEditContainer->GetEditItem();
ASSERT(iEditItem >= 0 && iEditItem < GetItemCount());
if (iEditItem >= 0 && iEditItem < GetItemCount())
{
CCeWatchElement* pVar = GetVar(iEditItem);
CCeDisplayElement* pDisplay = GetDisplayElement(iEditItem);
ASSERT(pVar != NULL);
ASSERT(m_pBackEnd != NULL);
if (pVar != NULL && m_pBackEnd != NULL && pVar->IsConnected())
{
CString str;
m_pEditContainer->GetText(str);
int IdsError = 0;
if (!CCeWatchBackEnd::IsValidValue(pVar, str))
IdsError = IDS_ERROR_INVALID_WRITE_EXPR;
else if (!m_pBackEnd->WriteVar(pVar, str))
IdsError = IDS_ERROR_WRITE_FAILED;
if (IdsError == 0)
{
pVar->AddToHistory(str);
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
}
else
{
m_pEditContainer->IgnoreFocus(true);
ErrorMsg(IdsError);
// m_pEditWnd->SetFocus();
// m_pEditWnd->SetSel(0, -1);
m_pEditContainer->IgnoreFocus(false);
return false;
}
}
}
return true;
}
//*****************************************************************************
bool CCeWatchList::EndFormatEdit()
//*****************************************************************************
{
ASSERT(m_pEditContainer != NULL);
ASSERT(m_pBackEnd != NULL);
int iEditItem = m_pEditContainer->GetEditItem();
ASSERT(iEditItem >= 0 && iEditItem < GetItemCount());
if (iEditItem >= 0 && iEditItem < GetItemCount())
{
CCeWatchElement* pVar = GetVar(iEditItem);
ASSERT(pVar != NULL);
if (pVar != NULL)
{
int iTop = GetTopIndex();
int iBottom = iTop + GetCountPerPage();
iBottom = min(iBottom, GetItemCount());
for (int iItem = iTop; iItem < iBottom; iItem++)
{
CCeWatchElement* pVar2 = GetVar(iItem);
if (pVar2 == pVar)
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
if (pDisplayElement != NULL && pDisplayElement->GetExpressionHandle() >= 0)
{
CString str;
m_pEditContainer->GetText(str);
if (!m_pBackEnd->SetFormat(pDisplayElement->GetExpressionHandle(), str))
{
m_pEditContainer->IgnoreFocus(true);
ErrorMsg(IDS_ERROR_INVALID_FORMAT_EXPR);
m_pEditContainer->IgnoreFocus(false);
return false;
}
}
}
}
}
}
return true;
}
//*****************************************************************************
LRESULT CCeWatchList::OnEndLabelEdit(
WPARAM wParam,
LPARAM lParam)
//*****************************************************************************
{
EndLabelEdit(wParam);
return 0;
}
//*****************************************************************************
void CCeWatchList::OnAddVariableFromList()
//*****************************************************************************
{
if (m_pBackEnd != NULL)
{
CCeSymbol SymbolTable(true);
CWaitCursor wait; // display wait cursor
if (SymbolTable.Load(m_pBackEnd->GetDebugInfo()))
{
CCeWatchSheetInsVar m_Sheet(IDS_INSERTVARIABLE, this);
CPageInsVarTree m_VarTree(this, &m_Sheet, &SymbolTable);
CPageInsVarList m_VarList(this, &m_Sheet, &SymbolTable);
m_Sheet.AddPage(&m_VarTree);
m_Sheet.AddPage(&m_VarList);
m_Sheet.DoModal();
}
else
{
ErrorMsg(IDS_ERROR_LOADSYMBOLS);
}
}
SetFocus(); // SIS 27.1.05: set focus back to dialog after inserting
}
//*****************************************************************************
void CCeWatchList::OnAddVariable()
//*****************************************************************************
{
// 15.12.05 SIS >>
// removed CheckVariableInsert() call
// insert position is calculated correctly now
// 15.12.05 SIS <<
CCeWatchElement* pVar = m_RootVar.AddChild("New Variable", CCeWatchType());
int iItem = GetSelectedItem();
iItem = GetNextInsertPos(iItem); // 15.12.05 SIS
InsertVarItem(pVar, iItem, NULL, true);
UpdateConnections();
if (iItem < 0)
iItem = GetItemCount() - 1;
if (iItem >= 0)
{
CRect r;
GetItemRect(iItem, r, LVIR_LABEL);
BeginLabelEdit(iItem, r.right - 1);
}
}
//*****************************************************************************
int CCeWatchList::InsertExpression(LPCTSTR pstrName, CCeWatchElement *&pInsertedElement, int iItem /*=-1*/)
//*****************************************************************************
{
CWaitCursor wait; // display wait cursor
CCeWatchElement* pVar = NULL;
int iCount;
CCeWatchType type;
CString strText;
pInsertedElement = NULL;
if (!m_pBackEnd->GetTypeAndText(pstrName, type, strText))
type.Set(CEWATCH_BASETYPE_SIMPLE, "???");
else
pstrName = strText;
pVar = new CCeWatchElement(pstrName, type);
iCount = InsertVariable (pVar, iItem);
if (iCount == 0)
return (0);
pInsertedElement = pVar;
return (iCount);
}
//*****************************************************************************
int CCeWatchList::InsertExpressionWithStructInfo(LPCTSTR pstrName, CCeWatchElement *&pInsertedElement, int iItem /*=-1*/)
//*****************************************************************************
{
CWaitCursor wait; // display wait cursor
CCeWatchElement* pVar = NULL;
int iCount = 0;
CCeWatchType type;
CString strText;
CString strId;
CString strIdPath(pstrName);
if (m_pBackEnd != NULL)
{
CCeSymbol SymbolTable(true);
CWaitCursor wait; // display wait cursor
if (SymbolTable.Load(m_pBackEnd->GetDebugInfo()))
{
CCeSymbol* pChild = NULL;
pChild = SymbolTable.FindChild(strIdPath);
if(pChild)
{
iCount = InsertVariable(pChild, iItem);
UpdateConnections();
}
else
{
InsertExpression(pstrName, pInsertedElement);
}
}
else
{
ErrorMsg(IDS_ERROR_LOADSYMBOLS);
}
}
return iCount;
}
BOOL CCeWatchList::StripId(CString& rstrIdPath, CString& rstrId)
{
if(rstrIdPath.IsEmpty())
{
return FALSE;
}
int iFound;
CString strPathTmp(rstrIdPath);
iFound = strPathTmp.Find(_T('.'));
if(iFound >= 0)
{
rstrId = strPathTmp.Left(iFound);
rstrIdPath = strPathTmp.Mid(iFound + 1);
}
else
{
rstrId = rstrIdPath;
rstrIdPath.Empty();
}
return TRUE;
}
//*****************************************************************************
int CCeWatchList::InsertVariable(CCeSymbol *pSymbol, int iItem /*=-1*/)
//*****************************************************************************
{
if (pSymbol != NULL && CCeWatchElement::IsVarKindVisible(pSymbol->GetType().GetVarKind()) &&
pSymbol->GetType().GetName().CompareNoCase(_T("Unknown")) != 0)
return InsertVariable(new CCeWatchElement(pSymbol), iItem);
else
{
::MessageBeep(MB_ICONEXCLAMATION);
return 0;
}
}
////*****************************************************************************
//bool CCeWatchList::IsVarKindVisible(ECeWatchVarKind varKind)
////*****************************************************************************
//{
// switch(varKind)
// {
// case Var:
// case VarInput:
// case VarOutput:
// case VarGlobal:
// return true;
// }
// return false;
//}
//*****************************************************************************
int CCeWatchList::InsertVariable(CCeWatchElement *pVar, int iItem /*=-1*/)
//*****************************************************************************
{
ASSERT(IsValidWatchElement(pVar));
if (pVar != NULL)
{
int iCount;
m_RootVar.AddChild(pVar);
// 15.12.05 SIS >>
// determine correct insert position
if (iItem < 0)
{
iItem = GetSelectedItem();
iItem = GetNextInsertPos(iItem);
}
// 15.12.05 SIS <<
if (iItem < 0)
iItem = GetItemCount();
iCount = InsertVarItem(pVar, iItem, NULL, true);
UpdateConnections();
GetParent()->PostMessage(WM_CEWATCH_VARLISTCHANGED, 0, NULL);
return (iCount);
}
return 0;
}
//*****************************************************************************
bool CCeWatchList::CheckVariableInsert()
//*****************************************************************************
{
if (m_pBackEnd != NULL)
{
int SelCount = GetSelectedCount();
if (SelCount > 1) // don't know where
return false;
else if (SelCount == 0) // insert at the end of list
return true;
else if (SelCount == 1) // insert above the currently selected variable
{
// selected item must be a top level variable
int iItem = GetSelectedItem();
ASSERT(iItem >= 0);
if (iItem >= 0)
{
CCeWatchElement* pVar = GetVar(iItem);
ASSERT(pVar != NULL);
if (pVar != NULL)
{
if (pVar->GetLevel() == 1)
return true;
}
}
}
}
return false;
}
//*****************************************************************************
bool CCeWatchList::CheckVariableDelete()
//*****************************************************************************
{
if (GetSelectedCount() > 0)
{
CCeWatchElement* pVar = NULL;
for (int ii = GetItemCount(); ii >= 0; ii--)
{
if ( GetItemState(ii, LVIS_SELECTED))
{
pVar = GetVar(ii);
if (pVar != NULL && pVar->GetLevel() == 1)
return true;
}
}
}
return false;
}
//*****************************************************************************
bool CCeWatchList::CheckValueEdit()
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
{
CCeDisplayElement* pDisplay = GetDisplayElement(iItem);
if (pDisplay != NULL)
{
CCeWatchElement* pVar = pDisplay->GetWatchElement();
return (pVar != NULL) && pVar->IsConnected() && pVar->GetType().IsSimpleType();
}
}
return false;
}
//*****************************************************************************
bool CCeWatchList::CheckFormatEdit()
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
{
CCeWatchElement* pVar = GetVar(iItem);
return (pVar != NULL) && pVar->GetType().IsSimpleType();
}
return false;
}
//*****************************************************************************
bool CCeWatchList::CheckNameEdit()
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
{
CCeWatchElement* pVar = GetVar(iItem);
return (pVar != NULL) && ((pVar->GetLevel() == 1) || pVar->GetType().IsArray());
}
return false;
}
//*****************************************************************************
bool CCeWatchList::CheckIncRange(bool bDec)
//*****************************************************************************
{
int iItem = GetSelectedItem();
if (iItem >= 0)
{
CCeWatchElement* pVar = GetVar(iItem);
return (pVar != NULL) && (pVar->GetType().IsArray());
}
return false;
}
//*****************************************************************************
void CCeWatchList::UpdateConnections()
//*****************************************************************************
{
if (IsWindow(GetSafeHwnd()))
PostMessage(WM_CEWATCH_UPDATECONNECTIONS, 0, NULL);
}
//*****************************************************************************
void CCeWatchList::OnForceResubscribe()
//*****************************************************************************
{
LoadSymbols(); // 10.10.06 SIS
if (IsWindow(GetSafeHwnd()))
PostMessage(WM_CEWATCH_UPDATECONNECTIONS, 1, NULL);
}
//*****************************************************************************
LRESULT CCeWatchList::OnUpdateConnections(
WPARAM wParam,
LPARAM lParam)
//*****************************************************************************
{
BOOL bResubscribe = (BOOL)wParam;
int iTop = GetTopIndex();
int iBottom = iTop + GetCountPerPage() + 1;
iBottom = min(iBottom, GetItemCount());
for (int iItem = 0; iItem < GetItemCount(); iItem++)
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
ASSERT(IsValidDisplayElement(pDisplayElement));
if (pDisplayElement != NULL && pDisplayElement->GetWatchElement() != NULL)
{
CCeWatchElement* pVar = pDisplayElement->GetWatchElement();
if (pVar->GetChildrenCount() == 0 && pVar->GetType().IsSimpleType())
{
if (m_pBackEnd == NULL)
{
pDisplayElement->SetExpressionHandle(-1);
RedrawItems(iItem, iItem);
}
else
{
bool bConnect = (iItem >= iTop && iItem <= iBottom);
if (bResubscribe && bConnect && pDisplayElement->GetExpressionHandle() != -1)
{
m_pBackEnd->RemoveVar(pDisplayElement->GetExpressionHandle());
pDisplayElement->SetExpressionHandle(-1);
}
if (bConnect && pDisplayElement->GetExpressionHandle() == -1)
{
CString strExpr = pVar->GetName();
if (pVar->GetFormat().GetLength() > 0)
strExpr += ", " + pVar->GetFormat();
pDisplayElement->SetExpressionHandle(m_pBackEnd->AddExpression(strExpr, pDisplayElement));
RedrawItems(iItem, iItem);
}
else if (!bConnect && pDisplayElement->GetExpressionHandle() >= 0)
{
m_pBackEnd->RemoveVar(pDisplayElement->GetExpressionHandle());
pDisplayElement->SetExpressionHandle(-1);
RedrawItems(iItem, iItem);
}
}
}
}
}
return 0;
}
//*****************************************************************************
void CCeWatchList::Deactivate()
//*****************************************************************************
{
if(m_pBackEnd == NULL)
{
return;
}
int iItemCount = GetItemCount();
for (int iItem = 0; iItem < iItemCount; iItem++)
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(iItem);
ASSERT(IsValidDisplayElement(pDisplayElement));
if (pDisplayElement != NULL && pDisplayElement->GetWatchElement() != NULL)
{
CCeWatchElement* pVar = pDisplayElement->GetWatchElement();
if (pVar->GetChildrenCount() == 0 && pVar->GetType().IsSimpleType())
{
if (pDisplayElement->GetExpressionHandle() != -1)
{
m_pBackEnd->RemoveVar(pDisplayElement->GetExpressionHandle());
pDisplayElement->SetExpressionHandle(-1);
RedrawItems(iItem, iItem);
}
}
}
}
}
////*****************************************************************************
//void CCeWatchList::Activate()
////*****************************************************************************
//{
// UpdateConnections();
//}
//*****************************************************************************
void CCeWatchList::UpdateItem(CCeDisplayElement *pDisplayElement)
//*****************************************************************************
{
ASSERT(m_pBackEnd != NULL);
if (IsWindow(GetSafeHwnd()) && m_pBackEnd != NULL)
{
ASSERT(pDisplayElement != NULL && pDisplayElement->GetWatchElement() != NULL);
if (pDisplayElement != NULL && pDisplayElement->GetWatchElement() != NULL)
{
ASSERT(IsValidDisplayElement(pDisplayElement));
m_pBackEnd->UpdateVar(pDisplayElement->GetExpressionHandle(), pDisplayElement->GetWatchElement());
pDisplayElement->GetWatchElement()->SetFormat(m_pBackEnd->GetFormat(pDisplayElement->GetExpressionHandle()));
int iTop = GetTopIndex();
int iBottom = iTop + GetCountPerPage() + 1;
iBottom = min(iBottom, GetItemCount());
for (int iItem = iTop; iItem < iBottom; iItem++)
{
if (pDisplayElement == GetDisplayElement(iItem))
{
CRect r1, r2;;
GetItemRect(iItem, r1, LVIR_ICON);
GetItemRect(iItem, r2, LVIR_BOUNDS);
r2.left += GetColumnWidth(0) + GetColumnWidth(1);
InvalidateRect(r1, FALSE);
InvalidateRect(r2, FALSE);
}
}
}
}
}
//*****************************************************************************
BOOL CCeWatchList::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
//*****************************************************************************
{
BOOL bResult = CListCtrl::OnMouseWheel(nFlags, zDelta, pt);
UpdateConnections();
return bResult;
}
//*****************************************************************************
void CCeWatchList::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
//*****************************************************************************
{
CListCtrl::OnVScroll(nSBCode, nPos, pScrollBar);
UpdateConnections();
}
//*****************************************************************************
void CCeWatchList::OnSize(UINT nType, int cx, int cy)
//*****************************************************************************
{
CListCtrl::OnSize(nType, cx, cy);
UpdateConnections();
}
//*****************************************************************************
void CCeWatchList::OnLoadWatches()
//*****************************************************************************
{
GetParent()->PostMessage(WM_CEWATCH_LOADLIST, 0, NULL);
}
//*****************************************************************************
void CCeWatchList::OnStoreWatches()
//*****************************************************************************
{
GetParent()->PostMessage(WM_CEWATCH_STORELIST, 0, NULL);
}
//*****************************************************************************
void CCeWatchList::OnDeleteItem(NMHDR* pNMHDR, LRESULT* pResult)
//*****************************************************************************
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
if (pNMListView->iItem >= 0)
{
CCeDisplayElement* pDisplayElement = GetDisplayElement(pNMListView->iItem);
if (pDisplayElement != NULL)
{
SetItemData(pNMListView->iItem, NULL);
if (pDisplayElement->GetExpressionHandle() >= 0 && m_pBackEnd != NULL)
{
m_pBackEnd->RemoveVar(pDisplayElement->GetExpressionHandle());
}
pDisplayElement->SetWatchElement(NULL);
delete pDisplayElement;
}
}
*pResult = 0;
}
//*****************************************************************************
void CCeWatchList::OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult)
//*****************************************************************************
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
ASSERT(m_pDragImage == NULL);
*pResult = 1;
if (m_pEditContainer == NULL && m_pDragImage == NULL)
{
CCeWatchElement* pVar = GetVar(pNMListView->iItem);
if (pVar->GetLevel() == 1)
{
CPoint ptImage;
m_iSrcItem = pNMListView->iItem;
m_pDragImage = CreateDragImage(pNMListView->iItem, &ptImage);
if (m_pDragImage != NULL)
{
m_pDragImage->BeginDrag(0, CPoint(8, 8));
m_pDragImage->DragShowNolock(TRUE);
SetCapture();
*pResult = 0;
}
}
}
}
//*****************************************************************************
void CCeWatchList::OnMouseMove(UINT nFlags, CPoint point)
//*****************************************************************************
{
if (m_pDragImage != NULL)
{
POINT pt = point;
ClientToScreen(&pt);
m_pDragImage->DragMove(pt);
int iDestItem;
if (GetDropTarget(point, iDestItem, m_iSrcItem))
SetCursor(LoadCursor(NULL, IDC_ARROW));
else
SetCursor(LoadCursor(NULL, IDC_NO));
}
CListCtrl::OnMouseMove(nFlags, point);
}
//*****************************************************************************
void CCeWatchList::OnLButtonUp(UINT nFlags, CPoint point)
//*****************************************************************************
{
if (m_pDragImage != NULL)
{
m_pDragImage->EndDrag();
delete m_pDragImage;
m_pDragImage = NULL;
ReleaseCapture();
int iDestItem;
if (GetDropTarget(point, iDestItem, m_iSrcItem))
{
MoveVarItem(m_iSrcItem, iDestItem);
// UpdateConnections();
}
m_iSrcItem = -1;
}
CListCtrl::OnLButtonUp(nFlags, point);
}
//*****************************************************************************
bool CCeWatchList::GetDropTarget(CPoint point, int &iDestItem, int iSrcItem/*=-1*/)
//*****************************************************************************
{
CRect rHeader, rClient;
GetHeaderCtrl()->GetWindowRect(rHeader);
GetClientRect(rClient);
rClient.top += rHeader.Height();
iDestItem = -1;
if (rClient.PtInRect(point))
{
iDestItem = HitTest(point);
if (iDestItem >= 0)
{
if ((iSrcItem < 0) || (iSrcItem != iDestItem && iSrcItem+1 != iDestItem))
{
CCeWatchElement* pVar = GetVar(iDestItem);
if (pVar != NULL && pVar->GetLevel() == 1)
return true;
}
}
else
{
if ((iSrcItem < 0) || (iSrcItem != GetItemCount() - 1))
{
iDestItem = GetItemCount();
return true; // dropping ok at the end of the list
}
}
}
return false;
}
//*****************************************************************************
CImageList* CCeWatchList::CreateDragImage(int item, LPPOINT lpPoint)
//*****************************************************************************
{
CImageList *iList = new CImageList; // create a new image-list
CRect rc;
GetItemRect(item, &rc, LVIR_BOUNDS); // get the complete row
rc.OffsetRect(-rc.left, -rc.top); // make it (0, 0)-aligned
rc.right = GetColumnWidth(0); // just want the 1st columne
// iList->Create(rc.Width(), rc.Height(), ILC_COLOR24 | ILC_MASK, 1, 1);
iList->Create(rc.Width(), rc.Height(), ILC_COLOR24, 1, 1);
CDC *pDC = GetDC(); // get device-context
if (pDC)
{
CBitmap drawMap, maskMap;
// create a memory-dc for the image and attach a bitmap to it
CDC drawDC;
drawDC.CreateCompatibleDC(pDC);
CFont* pOldFont = drawDC.SelectObject(GetFont());
drawMap.CreateCompatibleBitmap(pDC, rc.Width(), rc.Height());
CBitmap *old = drawDC.SelectObject(&drawMap);
// erase the background and draw the item into the device context
// drawDC.FillSolidRect(rc, GetSysColor(COLOR_WINDOW));
DRAWITEMSTRUCT dis;
dis.hDC = drawDC.m_hDC; // device-context to draw in
dis.rcItem = rc; // the item rectangle
dis.itemID = item; // the item's id
dis.itemState = ODS_DEFAULT; // or ODS_SELECTED
DrawItem(&dis); // draw item into the dc
drawDC.MoveTo(rc.left, rc.top);
drawDC.LineTo(rc.right-1, rc.top);
drawDC.LineTo(rc.right-1, rc.bottom-1);
drawDC.LineTo(rc.left, rc.bottom-1);
drawDC.LineTo(rc.left, rc.top);
drawDC.SelectObject(old); // switch back to old bitmap
drawDC.SelectObject(pOldFont);
// create a memory-dc for the mask and attach a bitmap to it. to make
// the bitmap just one bit depth, we make it compatible to the memory-
// dc instead of the screen-dc as above
#ifdef CE_WITHMASK
CDC maskDC;
maskDC.CreateCompatibleDC(pDC);
maskMap.CreateCompatibleBitmap(&maskDC, rc.Width(), rc.Height());
pOldFont = maskDC.SelectObject(GetFont());
old = maskDC.SelectObject(&maskMap);
// erase the background and draw the item into the device context
// maskDC.FillSolidRect(rc, GetSysColor(COLOR_WINDOW));
dis.hDC = maskDC.m_hDC; // device-context to draw in
dis.rcItem = rc; // the item rectangle
dis.itemID = item; // the item's id
dis.itemState = ODS_DEFAULT; // or ODS_SELECTED
DrawItem(&dis); // draw into the dc
maskDC.MoveTo(rc.left, rc.top);
maskDC.LineTo(rc.right-1, rc.top);
maskDC.LineTo(rc.right-1, rc.bottom-1);
maskDC.LineTo(rc.left, rc.bottom-1);
maskDC.LineTo(rc.left, rc.top);
maskDC.SelectObject(pOldFont);
maskDC.SelectObject(old); // switch back to old bitmap
#endif
// add the image (and mask) to the image-list
iList->Add(&drawMap, &maskMap);
ReleaseDC(pDC);
}
return iList;
}
//*****************************************************************************
void CCeWatchList::ErrorMsg(unsigned IdsMsg)
//*****************************************************************************
{
CString strMessage;
strMessage.LoadString(IdsMsg);
::AfxMessageBox(strMessage, MB_ICONSTOP);
}
//*****************************************************************************
BOOL CCeWatchList::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
//*****************************************************************************
{
HD_NOTIFY *pHDN = (HD_NOTIFY*)lParam;
if (pHDN->hdr.hwndFrom == GetHeaderCtrl()->m_hWnd)
{
if (pHDN->hdr.code == HDN_DIVIDERDBLCLICKW || pHDN->hdr.code == HDN_DIVIDERDBLCLICKA)
{
ASSERT(pHDN->iItem < CEWATCH_NCOLUMNS);
if (pHDN->iItem < CEWATCH_NCOLUMNS)
{
int MaxTextWidth = 0;
int TextWidth = 0;
CString str;
CRect IconRect;
if (GetItemCount() > 0)
GetItemRect(0, IconRect, LVIR_ICON);
// calculate max. width of selected column
for (int ii = 0; ii < GetItemCount(); ii++)
{
TextWidth = 0;
CCeWatchElement* pVar = GetVar(ii);
CCeDisplayElement* pDisplayElement = GetDisplayElement(ii);
switch (pHDN->iItem)
{
case 0:
if (pVar->GetLevel() == 1)
str = pVar->GetName();
else
str = pVar->GetShortName();
if (pVar->GetType().IsArray())
str += ", [" + GetWatchIndices(ii)->AsString() + "]";
TextWidth = (IconRect.Width() + 1) + pVar->GetLevel() * m_xIndent + 2;
break;
case 1:
str = pVar->GetType().GetName();
break;
case 2:
str = pVar->GetValue();
break;
case 3:
str = pVar->GetTime();
break;
case 4:
str = pVar->GetQualityText();
break;
}
TextWidth += GetStringWidth(str);
MaxTextWidth = max(TextWidth, MaxTextWidth);
}
int BestWidth = max(MaxTextWidth, m_HeaderWidth[pHDN->iItem]);
SetColumnWidth(pHDN->iItem, BestWidth + 8);
*pResult = TRUE;
return TRUE;
}
}
}
return CListCtrl::OnNotify(wParam, lParam, pResult);
}
//*****************************************************************************
void CCeWatchList::OnEditFormat()
//*****************************************************************************
{
int iItem = GetSelectedItem();
CRect r;
if (GetEditRect(iItem, CEWATCH_EDITTYPE_FORMAT, r))
BeginLabelEdit(iItem, r.right-1);
}
//*****************************************************************************
void CCeWatchList::OnEditName()
//*****************************************************************************
{
int iItem = GetSelectedItem();
CRect r;
if (GetEditRect(iItem, CEWATCH_EDITTYPE_NAME, r))
BeginLabelEdit(iItem, r.right-1);
}
//*****************************************************************************
void CCeWatchList::OnEditValue()
//*****************************************************************************
{
int iItem = GetSelectedItem();
CRect r;
if (GetEditRect(iItem, CEWATCH_EDITTYPE_VALUE, r))
BeginLabelEdit(iItem, r.right-1);
}
//*****************************************************************************
void CCeWatchList::OnDecRange()
//*****************************************************************************
{
IncRange(true);
}
//*****************************************************************************
void CCeWatchList::OnIncRange()
//*****************************************************************************
{
IncRange(false);
}
//*****************************************************************************
DROPEFFECT CCeWatchList::OnDragEnter (COleDataObject *pDataObject, DWORD dwKeyState, CPoint point)
//*****************************************************************************
{
if (pDataObject->IsDataAvailable(m_uiWatchExpressionCBFormat))
return DROPEFFECT_COPY;
else
return DROPEFFECT_NONE;
}
//*****************************************************************************
DROPEFFECT CCeWatchList::OnDragOver (COleDataObject *pDataObject, DWORD dwKeyState, CPoint point)
//*****************************************************************************
{
if (pDataObject->IsDataAvailable(m_uiWatchExpressionCBFormat))
{
int iDestItem;
if (GetDropTarget(point, iDestItem))
return DROPEFFECT_COPY;
}
return DROPEFFECT_NONE;
}
//*****************************************************************************
BOOL CCeWatchList::OnDrop (COleDataObject *pDataObject, DROPEFFECT dropEffect, CPoint point)
//*****************************************************************************
{
if (pDataObject->IsDataAvailable(m_uiWatchExpressionCBFormat))
{
int iDestItem;
if (GetDropTarget(point, iDestItem))
{
HGLOBAL hGlobal = pDataObject->GetGlobalData (m_uiWatchExpressionCBFormat);
if (hGlobal != NULL)
{
CSharedFile file;
CArchive ar (&file, CArchive::load);
CWatchExpressionDragItem dragItem;
CCeWatchElement *pInsertedElement=NULL;
file.SetHandle (hGlobal, FALSE);
dragItem.Serialize (ar);
ar.Close ();
file.Detach ();
//InsertExpression(m_pBackEnd->ScopeExpression(dragItem.GetExpression(), dragItem.GetScope()), pInsertedElement, iDestItem);
InsertExpressionWithStructInfo(m_pBackEnd->ScopeExpression(dragItem.GetExpression(), dragItem.GetScope()), pInsertedElement, iDestItem);
return TRUE;
}
}
}
return FALSE;
}
//*****************************************************************************
DROPEFFECT CCeWatchDropTarget::OnDragEnter (CWnd *pWnd, COleDataObject *pDataObject, DWORD dwKeyState, CPoint point)
//*****************************************************************************
{
CCeWatchList* pWatchList = dynamic_cast<CCeWatchList *> (pWnd);
if (pWatchList == NULL)
return FALSE;
return (pWatchList->OnDragEnter (pDataObject, dwKeyState, point));
}
//*****************************************************************************
DROPEFFECT CCeWatchDropTarget::OnDragOver (CWnd *pWnd, COleDataObject *pDataObject, DWORD dwKeyState, CPoint point)
//*****************************************************************************
{
CCeWatchList* pWatchList = dynamic_cast<CCeWatchList *> (pWnd);
if (pWatchList == NULL)
return FALSE;
return (pWatchList->OnDragOver (pDataObject, dwKeyState, point));
}
//*****************************************************************************
BOOL CCeWatchDropTarget::OnDrop (CWnd *pWnd, COleDataObject *pDataObject, DROPEFFECT dropEffect, CPoint point)
//*****************************************************************************
{
CCeWatchList* pWatchList = dynamic_cast<CCeWatchList *> (pWnd);
if (pWatchList == NULL)
return FALSE;
return (pWatchList->OnDrop (pDataObject, dropEffect, point));
}
void CCeWatchList::OnSetFocus(CWnd* pOldWnd)
{
// SHIFT_F10 14.12.04 SIS >>
// select first item, if none selected
if(GetSelectedItem() == -1 && GetItemCount() > 0)
{
SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
}
// SHIFT_F10 14.12.04 SIS <<
CListCtrl::OnSetFocus(pOldWnd);
RefreshWindow();
}
void CCeWatchList::OnKillFocus(CWnd* pNewWnd)
{
CListCtrl::OnKillFocus(pNewWnd);
RefreshWindow();
}
//*****************************************************************************
void CCeWatchList::RefreshWindow()
//*****************************************************************************
{
CRect rItems(0,0,0,0);
CRect rBottom, rRight;
GetClientRect(rBottom);
rRight = rBottom;
rBottom.top = rItems.bottom + 1;
rRight.left = rItems.right + 1;
if (GetItemCount() > 0)
{
int iTop = GetTopIndex();
int iBottom = iTop + GetCountPerPage();
iBottom = min(iBottom, GetItemCount()-1);
CRect r1, r2;
GetItemRect(iTop, r1, LVIR_BOUNDS);
GetItemRect(iBottom, r2, LVIR_BOUNDS);
rItems.UnionRect(&r1, &r2);
InvalidateRect(rItems, FALSE);
}
InvalidateRect(rBottom, TRUE);
InvalidateRect(rRight, TRUE);
}
void CCeWatchList::OnDblClick(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
CString str;
BSTR sVal = NULL;
HRESULT hr = S_OK;
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
*pResult = 0;
if(pNMListView->iItem < 0 || pNMListView->iSubItem != CEWATCH_SUBITEM_VALUE ) {
//something wrong
return;
}
CCeWatchElement* pVar = GetVar(pNMListView->iItem);
if (pVar == NULL || m_pBackEnd == NULL || !pVar->IsConnected()) {
//var is not there or backend not there or variable is not
//connected
return;
}
const CCeWatchType type = pVar->GetType();
if(type.IsSimpleType() && type.GetIECType() == BL_BOOL) {
//Toggle if it is a simple type and IEC datatype == BOOL
VARIANT va;
str = pVar->GetValue();
if(str.IsEmpty()) {
return;
}
::VariantInit(&va);
sVal = str.AllocSysString();
hr = BL_StringToVariant(sVal, (BL_IEC_TYP)type.GetIECType(), NULL, BL_USE_IEC_FORMAT, &va);
FC_FREE_BSTR(sVal);
if(FAILED(hr)) {
return;
}
sVal = ::SysAllocStringLen(NULL,10);
//toggle the value
va.boolVal = (va.boolVal == VARIANT_TRUE) ? VARIANT_FALSE : VARIANT_TRUE;
hr = BL_VariantToString (&va, BL_BOOL, NULL, BL_USE_WINDOWS_FORMAT, sVal, ::SysStringLen(sVal));
if (FAILED (hr)) {
FC_FREE_BSTR(sVal);
return;
}
str = sVal;
FC_FREE_BSTR(sVal);
m_pBackEnd->WriteVar(pVar,str);
}
}
|
gpl-3.0
|
levlab-atomchip/bfieldsim
|
bfieldsim/chips/atomchip_v4.py
|
10584
|
# -*- coding: utf-8 -*-
"""
Created on 2013-07-12
@author: Will
"""
from acwires import HWire, VWire, NWire, HThinWire, VThinWire
#from AtomChip import *
n=5 #number of subwires
I_central = -2.5
I_GU1 = 0
I_GU2 = 0.5
I_GU3 = 0
I_GU4 = 0.5
I_GU5 = 0
I_GL1 = 0
I_GL2 = 0.5
I_GL3 = 0
I_GL4 = 0.5
I_GL5 = 0
I_XBias = 3 #positive is field towards BECy
I_YBias = 0
I_ZBias = 0
I_Macro_Bias_1 = 27
I_Macro_Bias_2 = 27
I_Macro_Central = 0
I_Macro_Axial_1 = 0
I_Macro_Axial_2 = 0
I_Macro_Dimple = 0
# Field Calibration
# Taken from ACM Science Chamber Field Calibrations on wiki
xbiascal = 1054e-7 #T/A
xgradcal = 0.06211e-2 #T/Am
ybiascal = 223.67e-7 #T/A
zbiascal = 1039.7e-7 #T/A
# Bias fields
B_xbias = I_XBias * xbiascal # T
B_ybias = I_YBias * ybiascal # T
B_zbias = I_ZBias * zbiascal # T
# Height Targeting bias selection
# height_target = 500e-6
# B_ybias = 2e-3*I_central*1e-4 / height_target
print("By Bias: %2.2f G"%(B_ybias*1e4))
# Define chip geometry
mww = 100e-6
mwh = 5e-6
mwz = 0
macro_left_H = -2.5e-2
macro_left_ax1 = -0.685e-2
macro_left_ax2 = 0.565e-2
macro_left_dimple = -0.0595e-2
macro_length_H = 5e-2
macro_length_V = 0.119e-2
macro_bottom_H = -0.16e-2
macro_bottom_V = -0.281e-2
macro_height_H = 0.09e-2
macro_height_V = 0.1e-2
macro_low_bias1 = 0.17e-2
macro_low_bias2 = -0.33e-2
macro_low_central = -0.0785e-2
macro_low_V = -2.5e-2
macro_width_H = 0.157e-2
macro_width_V = 3e-2
## Wire definition
# Horizontal Wires
hwires = []
vwires = []
nwires = []
#(name, length, width, height, current, xl, y0, z0, subwires = 1):
hwires.append(HWire('WG', # name
13.6e-3, # length / m
mww, # width / m
mwh, # height / m
I_central, # current / A
-6.8e-3, # xl / m
0, # y0 / m
mwz,
n)) # z0 / m
vwires.append(VWire('GU1', # name
3.3e-3, # length / m
mww, # width / m
mwh, # height / m
I_GU1, # current / A
-3e-3, # x0 / m
0, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GU2', # name
3.8e-3, # length / m
mww, # width / m
mwh, # height / m
I_GU2, # current / A
-1e-3, # x0 / m
0, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GU3', # name
4.4e-3, # length / m
mww, # width / m
mwh, # height / m
I_GU3, # current / A
0e-6, # x0 / m
0, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GU4', # name
4.4e-3, # length / m
mww, # width / m
mwh, # height / m
I_GU4, # current / A
1e-3, # x0 / m
0, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GU5', # name
3.8e-3, # length / m
mww, # width / m
mwh, # height / m
I_GU5, # current / A
3e-3, # x0 / m
0, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GL1', # name
5e-3, # length / m
mww, # width / m
mwh, # height / m
I_GL1, # current / A
-3e-3, # x0 / m
-5e-3, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GL2', # name
5e-3, # length / m
mww, # width / m
mwh, # height / m
I_GL2, # current / A
-1e-3, # x0 / m
-5e-3, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GL3', # name
5e-3, # length / m
mww, # width / m
mwh, # height / m
I_GL3, # current / A
0, # x0 / m
-5e-3, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GL4', # name
5e-3, # length / m
mww, # width / m
mwh, # height / m
I_GL4, # current / A
1e-3, # x0 / m
-5e-3, # yd / m
mwz,
n)) # z0 / m
vwires.append(VWire('GL5', # name
5e-3, # length / m
mww, # width / m
mwh, # height / m
I_GL5, # current / A
3e-3, # x0 / m
-5e-3, # yd / m
mwz,
n)) # z0 / m
hwires.append(HWire('MacroBias1', # name
macro_length_H, # length / m
macro_width_H, # width / m
macro_bottom_H, # height / m
I_Macro_Bias_1, # current / A
macro_left_H, # xl / m
macro_low_bias1, # y0 / m
macro_bottom_H,
n)) # z0 / m
hwires.append(HWire('MacroBias2', # name
macro_length_H, # length / m
macro_width_H, # width / m
macro_bottom_H, # height / m
I_Macro_Bias_2, # current / A
macro_left_H, # xl / m
macro_low_bias2, # y0 / m
macro_bottom_H,
n)) # z0 / m
hwires.append(HWire('MacroCentral', # name
macro_length_H, # length / m
macro_width_H, # width / m
macro_bottom_H, # height / m
I_Macro_Central, # current / A
macro_left_H, # xl / m
macro_low_central, # y0 / m
macro_bottom_H,
n)) # z0 / m
vwires.append(VWire('MacroAxial1', # name
macro_length_V, # length / m
macro_width_V, # width / m
macro_height_V, # height / m
I_Macro_Axial_1, # current / A
macro_left_ax1, # x0 / m
macro_low_V, # yd / m
macro_bottom_V,
n)) # z0 / m
vwires.append(VWire('MacroAxial2', # name
macro_length_V, # length / m
macro_width_V, # width / m
macro_height_V, # height / m
I_Macro_Axial_2, # current / A
macro_left_ax2, # x0 / m
macro_low_V, # yd / m
macro_bottom_V,
n)) # z0 / m
vwires.append(VWire('MacroDimple', # name
macro_length_V, # length / m
macro_width_V, # width / m
macro_height_V, # height / m
I_Macro_Dimple, # current / A
macro_left_dimple, # x0 / m
macro_low_V, # yd / m
macro_bottom_V,
n)) # z0 / m
allwires = hwires + vwires + nwires
atomchip_v4 = {'wirespecs' : allwires,
'B_xbias' : B_xbias,
'B_ybias' : B_ybias,
'B_zbias' : B_zbias}
#
if __name__ == '__main__':
import bfsimulator
b_f_sim = bfsimulator.BFieldSimulator()
b_f_sim.set_chip(atomchip_v4)
b_f_sim.calc_trap_height()
b_f_sim.plot_z()
# b_f_sim.zoom(1.5, [0,0,b_f_sim.z_trap])
# b_f_sim.calc_xy()
# b_f_sim.plot_xy()
sim_results = b_f_sim.find_trap_freq()
print 'x_trap : %2.0f um \ny_trap : %2.0f um \nz_trap : %2.0f um'%(b_f_sim.x_trap*1e6, b_f_sim.y_trap*1e6, b_f_sim.z_trap*1e6)
print 'f_long : %2.0f Hz \nf_trans : %2.0f Hz \nf_z : %2.0f Hz'%(sim_results['f_long'], sim_results['f_trans'], sim_results['f_z'])
# b_f_sim.set_chip(atomchip_v3)
b_f_sim.plot_xy()
# b_f_sim.calc_xy()
# b_f_sim.plot_xy_coupling()
|
gpl-3.0
|
iskandar1023/substratum
|
app/src/main/java/projekt/substratum/adapters/tabs/overlays/VariantAdapter.java
|
7267
|
/*
* Copyright (c) 2016-2017 Projekt Substratum
* This file is part of Substratum.
*
* Substratum 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.
*
* Substratum 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 Substratum. If not, see <http://www.gnu.org/licenses/>.
*/
package projekt.substratum.adapters.tabs.overlays;
import android.content.Context;
import android.content.res.ColorStateList;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.util.List;
import projekt.substratum.R;
import projekt.substratum.common.Packages;
import projekt.substratum.databinding.TabOverlaysPreviewItemBinding;
public class VariantAdapter extends ArrayAdapter<VariantItem> {
private final Context context;
public VariantAdapter(Context context,
List<VariantItem> variantItemArrayList) {
super(context, R.layout.tab_overlays_preview_item, variantItemArrayList);
this.context = context;
}
@Override
public View getDropDownView(int position,
View convertView,
@NonNull ViewGroup parent) {
return this.getCustomView(position);
}
@NonNull
@Override
public View getView(int position,
View convertView,
@NonNull ViewGroup parent) {
return this.getCustomView(position);
}
private View getCustomView(int position) {
LayoutInflater inflater = LayoutInflater.from(context);
TabOverlaysPreviewItemBinding binding = DataBindingUtil.
inflate(inflater, R.layout.tab_overlays_preview_item, null, false);
VariantItem item = this.getItem(position);
if (item != null) {
try {
// First check if our model contains a saved color value
if (item.isDefaultOption()) {
if (item.getVariantName() != null) {
binding.variantName.setText(item.getVariantName().replace("_", " "));
binding.variantHex.setVisibility(View.GONE);
}
} else if (item.getColor() == 0) {
if (item.getVariantName() != null) {
binding.variantName.setText(item.getVariantName().replace("_", " "));
if (item.getVariantHex().contains(":color")) {
// Uh oh, we hit a package dependent resource pointer!
String workingValue = item.getVariantHex();
// First, we have to strip out the reference pointers (public/private)
if (workingValue.startsWith("@*")) {
workingValue = workingValue.substring(2);
} else if (workingValue.startsWith("@")) {
workingValue = workingValue.substring(1);
}
// Now check the package name
String workingPackage = workingValue.split(":")[0];
String workingColor = workingValue.split("/")[1];
int color = Packages.getColorResource(
this.getContext(), workingPackage, workingColor);
if (color != 0) {
item.setColor(color);
ColorStateList csl = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
color,
color
}
);
binding.variantHex.setImageTintList(csl);
binding.variantHex.setVisibility(View.VISIBLE);
} else {
binding.variantName.setText(item.getVariantName());
binding.variantHex.setVisibility(View.GONE);
}
} else {
int color = Color.parseColor(item.getVariantHex());
item.setColor(color);
ColorStateList csl = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
color,
color
}
);
binding.variantHex.setImageTintList(csl);
binding.variantHex.setVisibility(View.VISIBLE);
}
} else {
binding.variantHex.setVisibility(View.INVISIBLE);
}
} else {
if (item.getVariantName() != null) {
binding.variantName.setText(item.getVariantName().replace("_", " "));
}
// We now know that the color is not 0 which is the hardcoded null set for int
int color = item.getColor();
ColorStateList csl = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
color,
color
}
);
binding.variantHex.setImageTintList(csl);
binding.variantHex.setVisibility(View.VISIBLE);
}
} catch (IllegalArgumentException iae) {
binding.variantHex.setVisibility(View.INVISIBLE);
}
} else {
binding.variantHex.setVisibility(View.INVISIBLE);
}
binding.setOverlayColorPreviewItem(item);
binding.executePendingBindings();
return binding.getRoot();
}
}
|
gpl-3.0
|
StarTux/LinkPortal
|
src/main/java/com/winthier/linkportal/LinkPortals.java
|
1987
|
package com.winthier.linkportal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
final class LinkPortals {
private LinkPortalPlugin plugin;
private final PortalStorage storage;
private List<Portal> portals = null;
LinkPortals(final LinkPortalPlugin plugin) {
this.plugin = plugin;
this.storage = new PortalStorage(plugin);
}
public List<Portal> getPortals() {
if (portals == null) {
portals = new LinkedList<>();
portals.addAll(storage.getPortals());
}
return portals;
}
public void addPortal(Portal portal) {
for (Iterator<Portal> it = getPortals().iterator(); it.hasNext();) {
Portal po = it.next();
if (po.signLocationEquals(portal)) {
it.remove();
}
}
getPortals().add(portal);
}
public void removePortal(Portal portal) {
getPortals().remove(portal);
}
public void savePortals() {
if (portals == null) return;
storage.setPortals(portals);
storage.save();
}
public void reload() {
portals = null;
storage.reload();
}
public Portal portalWithSign(Sign sign) {
final Block block = sign.getBlock();
final String worldName = block.getWorld().getName();
int x = block.getX();
int y = block.getY();
int z = block.getZ();
for (Portal portal: getPortals()) {
if (portal.signLocationEquals(worldName, x, y, z)) return portal;
}
return null;
}
public List<Portal> ringOfPortal(Portal portal) {
List<Portal> result = new ArrayList<>();
for (Portal entry: getPortals()) {
if (entry.ownerAndRingEquals(portal)) {
result.add(entry);
}
}
return result;
}
}
|
gpl-3.0
|
rakvat/black_colorful_pages
|
bottom.php
|
365
|
<table width="100%"><tr><td style="padding-left: 10px" align="left">
<a class="none" border="0" href="#top"><img src="TEX/up.png" alt="top" border="0"/></a>
</td>
<td align="right">
<a class="imprint" href=<?php echo "imprint.php?lang=".$lang; ?>><?php echo $l_impressum[$lang]; ?></a></div>
</td></tr></table>
</div> <!-- /container -->
</center>
</body>
</html>
|
gpl-3.0
|
eXistence/fhDOOM
|
neo/d3xp/anim/Anim_Testmodel.cpp
|
27052
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code 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.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*
=============================================================================
MODEL TESTING
Model viewing can begin with either "testmodel <modelname>"
The names must be the full pathname after the basedir, like
"models/weapons/v_launch/tris.md3" or "players/male/tris.md3"
Extension will default to ".ase" if not specified.
Testmodel will create a fake entity 100 units in front of the current view
position, directly facing the viewer. It will remain immobile, so you can
move around it to view it from different angles.
g_testModelRotate
g_testModelAnimate
g_testModelBlend
=============================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
CLASS_DECLARATION( idAnimatedEntity, idTestModel )
EVENT( EV_FootstepLeft, idTestModel::Event_Footstep )
EVENT( EV_FootstepRight, idTestModel::Event_Footstep )
END_CLASS
/*
================
idTestModel::idTestModel
================
*/
idTestModel::idTestModel() {
head = NULL;
headAnimator = NULL;
anim = 0;
headAnim = 0;
starttime = 0;
animtime = 0;
mode = 0;
frame = 0;
}
/*
================
idTestModel::Save
================
*/
void idTestModel::Save( idSaveGame *savefile ) {
}
/*
================
idTestModel::Restore
================
*/
void idTestModel::Restore( idRestoreGame *savefile ) {
// FIXME: one day we may actually want to save/restore test models, but for now we'll just delete them
delete this;
}
/*
================
idTestModel::Spawn
================
*/
void idTestModel::Spawn( void ) {
idVec3 size;
idBounds bounds;
const char *headModel;
jointHandle_t joint;
idStr jointName;
idVec3 origin, modelOffset;
idMat3 axis;
const idKeyValue *kv;
copyJoints_t copyJoint;
if ( renderEntity.hModel && renderEntity.hModel->IsDefaultModel() && !animator.ModelDef() ) {
gameLocal.Warning( "Unable to create testmodel for '%s' : model defaulted", spawnArgs.GetString( "model" ) );
PostEventMS( &EV_Remove, 0 );
return;
}
mode = g_testModelAnimate.GetInteger();
animator.RemoveOriginOffset( g_testModelAnimate.GetInteger() == 1 );
physicsObj.SetSelf( this );
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
if ( spawnArgs.GetVector( "mins", NULL, bounds[0] ) ) {
spawnArgs.GetVector( "maxs", NULL, bounds[1] );
physicsObj.SetClipBox( bounds, 1.0f );
physicsObj.SetContents( 0 );
} else if ( spawnArgs.GetVector( "size", NULL, size ) ) {
bounds[ 0 ].Set( size.x * -0.5f, size.y * -0.5f, 0.0f );
bounds[ 1 ].Set( size.x * 0.5f, size.y * 0.5f, size.z );
physicsObj.SetClipBox( bounds, 1.0f );
physicsObj.SetContents( 0 );
}
spawnArgs.GetVector( "offsetModel", "0 0 0", modelOffset );
// add the head model if it has one
headModel = spawnArgs.GetString( "def_head", "" );
if ( headModel[ 0 ] ) {
jointName = spawnArgs.GetString( "head_joint" );
joint = animator.GetJointHandle( jointName );
if ( joint == INVALID_JOINT ) {
gameLocal.Warning( "Joint '%s' not found for 'head_joint'", jointName.c_str() );
} else {
// copy any sounds in case we have frame commands on the head
idDict args;
const idKeyValue *sndKV = spawnArgs.MatchPrefix( "snd_", NULL );
while( sndKV ) {
args.Set( sndKV->GetKey(), sndKV->GetValue() );
sndKV = spawnArgs.MatchPrefix( "snd_", sndKV );
}
head = gameLocal.SpawnEntityType( idAnimatedEntity::Type, &args );
animator.GetJointTransform( joint, gameLocal.time, origin, axis );
origin = GetPhysics()->GetOrigin() + ( origin + modelOffset ) * GetPhysics()->GetAxis();
head.GetEntity()->SetModel( headModel );
head.GetEntity()->SetOrigin( origin );
head.GetEntity()->SetAxis( GetPhysics()->GetAxis() );
head.GetEntity()->BindToJoint( this, animator.GetJointName( joint ), true );
headAnimator = head.GetEntity()->GetAnimator();
// set up the list of joints to copy to the head
for( kv = spawnArgs.MatchPrefix( "copy_joint", NULL ); kv != NULL; kv = spawnArgs.MatchPrefix( "copy_joint", kv ) ) {
jointName = kv->GetKey();
if ( jointName.StripLeadingOnce( "copy_joint_world " ) ) {
copyJoint.mod = JOINTMOD_WORLD_OVERRIDE;
} else {
jointName.StripLeadingOnce( "copy_joint " );
copyJoint.mod = JOINTMOD_LOCAL_OVERRIDE;
}
copyJoint.from = animator.GetJointHandle( jointName );
if ( copyJoint.from == INVALID_JOINT ) {
gameLocal.Warning( "Unknown copy_joint '%s'", jointName.c_str() );
continue;
}
copyJoint.to = headAnimator->GetJointHandle( jointName );
if ( copyJoint.to == INVALID_JOINT ) {
gameLocal.Warning( "Unknown copy_joint '%s' on head", jointName.c_str() );
continue;
}
copyJoints.Append( copyJoint );
}
}
}
// start any shader effects based off of the spawn time
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time );
SetPhysics( &physicsObj );
gameLocal.Printf( "Added testmodel at origin = '%s', angles = '%s'\n", GetPhysics()->GetOrigin().ToString(), GetPhysics()->GetAxis().ToAngles().ToString() );
BecomeActive( TH_THINK );
}
/*
================
idTestModel::~idTestModel
================
*/
idTestModel::~idTestModel() {
StopSound( SND_CHANNEL_ANY, false );
if ( renderEntity.hModel ) {
gameLocal.Printf( "Removing testmodel %s\n", renderEntity.hModel->Name() );
} else {
gameLocal.Printf( "Removing testmodel\n" );
}
if ( gameLocal.testmodel == this ) {
gameLocal.testmodel = NULL;
}
if ( head.GetEntity() ) {
head.GetEntity()->StopSound( SND_CHANNEL_ANY, false );
head.GetEntity()->PostEventMS( &EV_Remove, 0 );
}
}
/*
===============
idTestModel::Event_Footstep
===============
*/
void idTestModel::Event_Footstep( void ) {
StartSound( "snd_footstep", SND_CHANNEL_BODY, 0, false, NULL );
}
/*
================
idTestModel::ShouldConstructScriptObjectAtSpawn
Called during idEntity::Spawn to see if it should construct the script object or not.
Overridden by subclasses that need to spawn the script object themselves.
================
*/
bool idTestModel::ShouldConstructScriptObjectAtSpawn( void ) const {
return false;
}
/*
================
idTestModel::Think
================
*/
void idTestModel::Think( void ) {
idVec3 pos;
idMat3 axis;
idAngles ang;
int i;
if ( thinkFlags & TH_THINK ) {
if ( anim && ( gameLocal.testmodel == this ) && ( mode != g_testModelAnimate.GetInteger() ) ) {
StopSound( SND_CHANNEL_ANY, false );
if ( head.GetEntity() ) {
head.GetEntity()->StopSound( SND_CHANNEL_ANY, false );
}
switch( g_testModelAnimate.GetInteger() ) {
default:
case 0:
// cycle anim with origin reset
if ( animator.NumFrames( anim ) <= 1 ) {
// single frame animations end immediately, so just cycle it since it's the same result
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
} else {
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnimator->AnimLength( headAnim ) > animator.AnimLength( anim ) ) {
// loop the body anim when the head anim is longer
animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( -1 );
}
}
}
animator.RemoveOriginOffset( false );
break;
case 1:
// cycle anim with fixed origin
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( true );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 2:
// cycle anim with continuous origin
animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 3:
// frame by frame with continuous origin
animator.SetFrame( ANIMCHANNEL_ALL, anim, frame, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->SetFrame( ANIMCHANNEL_ALL, headAnim, frame, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 4:
// play anim once
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( false );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
case 5:
// frame by frame with fixed origin
animator.SetFrame( ANIMCHANNEL_ALL, anim, frame, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
animator.RemoveOriginOffset( true );
if ( headAnim ) {
headAnimator->SetFrame( ANIMCHANNEL_ALL, headAnim, frame, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
}
break;
}
mode = g_testModelAnimate.GetInteger();
}
if ( ( mode == 0 ) && ( gameLocal.time >= starttime + animtime ) ) {
starttime = gameLocal.time;
StopSound( SND_CHANNEL_ANY, false );
animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnim ) {
headAnimator->PlayAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, FRAME2MS( g_testModelBlend.GetInteger() ) );
if ( headAnimator->AnimLength( headAnim ) > animator.AnimLength( anim ) ) {
// loop the body anim when the head anim is longer
animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( -1 );
}
}
}
if ( headAnimator ) {
// copy the animation from the body to the head
for( i = 0; i < copyJoints.Num(); i++ ) {
if ( copyJoints[ i ].mod == JOINTMOD_WORLD_OVERRIDE ) {
idMat3 mat = head.GetEntity()->GetPhysics()->GetAxis().Transpose();
GetJointWorldTransform( copyJoints[ i ].from, gameLocal.time, pos, axis );
pos -= head.GetEntity()->GetPhysics()->GetOrigin();
headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos * mat );
headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis * mat );
} else {
animator.GetJointLocalTransform( copyJoints[ i ].from, gameLocal.time, pos, axis );
headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos );
headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis );
}
}
}
// update rotation
RunPhysics();
physicsObj.GetAngles( ang );
physicsObj.SetAngularExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, ang, idAngles( 0, g_testModelRotate.GetFloat() * 360.0f / 60.0f, 0 ), ang_zero );
idClipModel *clip = physicsObj.GetClipModel();
if ( clip && animator.ModelDef() ) {
idVec3 neworigin;
idMat3 axis;
jointHandle_t joint;
joint = animator.GetJointHandle( "origin" );
animator.GetJointTransform( joint, gameLocal.time, neworigin, axis );
neworigin = ( ( neworigin - animator.ModelDef()->GetVisualOffset() ) * physicsObj.GetAxis() ) + GetPhysics()->GetOrigin();
clip->Link( gameLocal.clip, this, 0, neworigin, clip->GetAxis() );
}
}
UpdateAnimation();
Present();
if ( ( gameLocal.testmodel == this ) && g_showTestModelFrame.GetInteger() && anim ) {
gameLocal.Printf( "^5 Anim: ^7%s ^5Frame: ^7%d/%d Time: %.3f\n", animator.AnimFullName( anim ), animator.CurrentAnim( ANIMCHANNEL_ALL )->GetFrameNumber( gameLocal.time ),
animator.CurrentAnim( ANIMCHANNEL_ALL )->NumFrames(), MS2SEC( gameLocal.time - animator.CurrentAnim( ANIMCHANNEL_ALL )->GetStartTime() ) );
if ( headAnim ) {
gameLocal.Printf( "^5 Head: ^7%s ^5Frame: ^7%d/%d Time: %.3f\n\n", headAnimator->AnimFullName( headAnim ), headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetFrameNumber( gameLocal.time ),
headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->NumFrames(), MS2SEC( gameLocal.time - headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetStartTime() ) );
} else {
gameLocal.Printf( "\n\n" );
}
}
}
/*
================
idTestModel::NextAnim
================
*/
void idTestModel::NextAnim( const idCmdArgs &args ) {
if ( !animator.NumAnims() ) {
return;
}
anim++;
if ( anim >= animator.NumAnims() ) {
// anim 0 is no anim
anim = 1;
}
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
animname = animator.AnimFullName( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
if ( headAnim ) {
gameLocal.Printf( "head '%s', %d.%03d seconds, %d frames\n", headAnimator->AnimFullName( headAnim ), headAnimator->AnimLength( headAnim ) / 1000, headAnimator->AnimLength( headAnim ) % 1000, headAnimator->NumFrames( headAnim ) );
}
// reset the anim
mode = -1;
frame = 1;
}
/*
================
idTestModel::PrevAnim
================
*/
void idTestModel::PrevAnim( const idCmdArgs &args ) {
if ( !animator.NumAnims() ) {
return;
}
headAnim = 0;
anim--;
if ( anim < 0 ) {
anim = animator.NumAnims() - 1;
}
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
animname = animator.AnimFullName( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
if ( headAnim ) {
gameLocal.Printf( "head '%s', %d.%03d seconds, %d frames\n", headAnimator->AnimFullName( headAnim ), headAnimator->AnimLength( headAnim ) / 1000, headAnimator->AnimLength( headAnim ) % 1000, headAnimator->NumFrames( headAnim ) );
}
// reset the anim
mode = -1;
frame = 1;
}
/*
================
idTestModel::NextFrame
================
*/
void idTestModel::NextFrame( const idCmdArgs &args ) {
if ( !anim || ( ( g_testModelAnimate.GetInteger() != 3 ) && ( g_testModelAnimate.GetInteger() != 5 ) ) ) {
return;
}
frame++;
if ( frame > animator.NumFrames( anim ) ) {
frame = 1;
}
gameLocal.Printf( "^5 Anim: ^7%s\n^5Frame: ^7%d/%d\n\n", animator.AnimFullName( anim ), frame, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
================
idTestModel::PrevFrame
================
*/
void idTestModel::PrevFrame( const idCmdArgs &args ) {
if ( !anim || ( ( g_testModelAnimate.GetInteger() != 3 ) && ( g_testModelAnimate.GetInteger() != 5 ) ) ) {
return;
}
frame--;
if ( frame < 1 ) {
frame = animator.NumFrames( anim );
}
gameLocal.Printf( "^5 Anim: ^7%s\n^5Frame: ^7%d/%d\n\n", animator.AnimFullName( anim ), frame, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
================
idTestModel::TestAnim
================
*/
void idTestModel::TestAnim( const idCmdArgs &args ) {
idStr name;
int animNum;
const idAnim *newanim;
if ( args.Argc() < 2 ) {
gameLocal.Printf( "usage: testanim <animname>\n" );
return;
}
newanim = NULL;
name = args.Argv( 1 );
#if 0
if ( strstr( name, ".ma" ) || strstr( name, ".mb" ) ) {
const idMD5Anim *md5anims[ ANIM_MaxSyncedAnims ];
idModelExport exporter;
exporter.ExportAnim( name );
name.SetFileExtension( MD5_ANIM_EXT );
md5anims[ 0 ] = animationLib.GetAnim( name );
if ( md5anims[ 0 ] ) {
customAnim.SetAnim( animator.ModelDef(), name, name, 1, md5anims );
newanim = &customAnim;
}
} else {
animNum = animator.GetAnim( name );
}
#else
animNum = animator.GetAnim( name );
#endif
if ( !animNum ) {
gameLocal.Printf( "Animation '%s' not found.\n", name.c_str() );
return;
}
anim = animNum;
starttime = gameLocal.time;
animtime = animator.AnimLength( anim );
headAnim = 0;
if ( headAnimator ) {
headAnimator->ClearAllAnims( gameLocal.time, 0 );
headAnim = headAnimator->GetAnim( animname );
if ( !headAnim ) {
headAnim = headAnimator->GetAnim( "idle" );
if ( !headAnim ) {
gameLocal.Printf( "Missing 'idle' anim for head.\n" );
}
}
if ( headAnim && ( headAnimator->AnimLength( headAnim ) > animtime ) ) {
animtime = headAnimator->AnimLength( headAnim );
}
}
animname = name;
gameLocal.Printf( "anim '%s', %d.%03d seconds, %d frames\n", animname.c_str(), animator.AnimLength( anim ) / 1000, animator.AnimLength( anim ) % 1000, animator.NumFrames( anim ) );
// reset the anim
mode = -1;
}
/*
=====================
idTestModel::BlendAnim
=====================
*/
void idTestModel::BlendAnim( const idCmdArgs &args ) {
int anim1;
int anim2;
if ( args.Argc() < 4 ) {
gameLocal.Printf( "usage: testblend <anim1> <anim2> <frames>\n" );
return;
}
anim1 = gameLocal.testmodel->animator.GetAnim( args.Argv( 1 ) );
if ( !anim1 ) {
gameLocal.Printf( "Animation '%s' not found.\n", args.Argv( 1 ) );
return;
}
anim2 = gameLocal.testmodel->animator.GetAnim( args.Argv( 2 ) );
if ( !anim2 ) {
gameLocal.Printf( "Animation '%s' not found.\n", args.Argv( 2 ) );
return;
}
animname = args.Argv( 2 );
animator.CycleAnim( ANIMCHANNEL_ALL, anim1, gameLocal.time, 0 );
animator.CycleAnim( ANIMCHANNEL_ALL, anim2, gameLocal.time, FRAME2MS( atoi( args.Argv( 3 ) ) ) );
anim = anim2;
headAnim = 0;
}
/***********************************************************************
Testmodel console commands
***********************************************************************/
/*
=================
idTestModel::KeepTestModel_f
Makes the current test model permanent, allowing you to place
multiple test models
=================
*/
void idTestModel::KeepTestModel_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No active testModel.\n" );
return;
}
gameLocal.Printf( "modelDef %p kept\n", gameLocal.testmodel->renderEntity.hModel );
gameLocal.testmodel = NULL;
}
/*
=================
idTestModel::TestSkin_f
Sets a skin on an existing testModel
=================
*/
void idTestModel::TestSkin_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( !gameLocal.testmodel ) {
common->Printf( "No active testModel\n" );
return;
}
if ( args.Argc() < 2 ) {
common->Printf( "removing testSkin.\n" );
gameLocal.testmodel->SetSkin( NULL );
return;
}
name = args.Argv( 1 );
gameLocal.testmodel->SetSkin( declManager->FindSkin( name ) );
}
/*
=================
idTestModel::TestShaderParm_f
Sets a shaderParm on an existing testModel
=================
*/
void idTestModel::TestShaderParm_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( !gameLocal.testmodel ) {
common->Printf( "No active testModel\n" );
return;
}
if ( args.Argc() != 3 ) {
common->Printf( "USAGE: testShaderParm <parmNum> <float | \"time\">\n" );
return;
}
int parm = atoi( args.Argv( 1 ) );
if ( parm < 0 || parm >= MAX_ENTITY_SHADER_PARMS ) {
common->Printf( "parmNum %i out of range\n", parm );
return;
}
float value;
if ( !idStr::Icmp( args.Argv( 2 ), "time" ) ) {
value = gameLocal.time * -0.001;
} else {
value = atof( args.Argv( 2 ) );
}
gameLocal.testmodel->SetShaderParm( parm, value );
}
/*
=================
idTestModel::TestModel_f
Creates a static modelDef in front of the current position, which
can then be moved around
=================
*/
void idTestModel::TestModel_f( const idCmdArgs &args ) {
idVec3 offset;
idStr name;
idPlayer * player;
const idDict * entityDef;
idDict dict;
player = gameLocal.GetLocalPlayer();
if ( !player || !gameLocal.CheatsOk() ) {
return;
}
// delete the testModel if active
if ( gameLocal.testmodel ) {
delete gameLocal.testmodel;
gameLocal.testmodel = NULL;
}
if ( args.Argc() < 2 ) {
return;
}
name = args.Argv( 1 );
entityDef = gameLocal.FindEntityDefDict( name, false );
if ( entityDef ) {
dict = *entityDef;
} else {
if ( declManager->FindType( DECL_MODELDEF, name, false ) ) {
dict.Set( "model", name );
} else {
// allow map models with underscore prefixes to be tested during development
// without appending an ase
if ( name[ 0 ] != '_' ) {
name.DefaultFileExtension( ".ase" );
}
#ifndef _D3XP
// Maya ascii format is supported natively now
if ( strstr( name, ".ma" ) || strstr( name, ".mb" ) ) {
idModelExport exporter;
exporter.ExportModel( name );
name.SetFileExtension( MD5_MESH_EXT );
}
#endif
if ( !renderModelManager->CheckModel( name ) ) {
gameLocal.Printf( "Can't register model\n" );
return;
}
dict.Set( "model", name );
}
}
offset = player->GetPhysics()->GetOrigin() + player->viewAngles.ToForward() * 100.0f;
dict.Set( "origin", offset.ToString() );
dict.Set( "angle", va( "%f", player->viewAngles.yaw + 180.0f ) );
gameLocal.testmodel = ( idTestModel * )gameLocal.SpawnEntityType( idTestModel::Type, &dict );
gameLocal.testmodel->renderEntity.shaderParms[SHADERPARM_TIMEOFFSET] = -MS2SEC( gameLocal.time );
}
/*
=====================
idTestModel::ArgCompletion_TestModel
=====================
*/
void idTestModel::ArgCompletion_TestModel( const idCmdArgs &args, void(*callback)( const char *s ) ) {
int i, num;
num = declManager->GetNumDecls( DECL_ENTITYDEF );
for ( i = 0; i < num; i++ ) {
callback( idStr( args.Argv( 0 ) ) + " " + declManager->DeclByIndex( DECL_ENTITYDEF, i , false )->GetName() );
}
num = declManager->GetNumDecls( DECL_MODELDEF );
for ( i = 0; i < num; i++ ) {
callback( idStr( args.Argv( 0 ) ) + " " + declManager->DeclByIndex( DECL_MODELDEF, i , false )->GetName() );
}
cmdSystem->ArgCompletion_FolderExtension( args, callback, "models/", false, ".lwo", ".ase", ".md5mesh", ".ma", ".mb", NULL );
}
/*
=====================
idTestModel::TestParticleStopTime_f
=====================
*/
void idTestModel::TestParticleStopTime_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->renderEntity.shaderParms[SHADERPARM_PARTICLE_STOPTIME] = MS2SEC( gameLocal.time );
gameLocal.testmodel->UpdateVisuals();
}
/*
=====================
idTestModel::TestAnim_f
=====================
*/
void idTestModel::TestAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->TestAnim( args );
}
/*
=====================
idTestModel::ArgCompletion_TestAnim
=====================
*/
void idTestModel::ArgCompletion_TestAnim( const idCmdArgs &args, void(*callback)( const char *s ) ) {
if ( gameLocal.testmodel ) {
idAnimator *animator = gameLocal.testmodel->GetAnimator();
for( int i = 0; i < animator->NumAnims(); i++ ) {
callback( va( "%s %s", args.Argv( 0 ), animator->AnimFullName( i ) ) );
}
}
}
/*
=====================
idTestModel::TestBlend_f
=====================
*/
void idTestModel::TestBlend_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->BlendAnim( args );
}
/*
=====================
idTestModel::TestModelNextAnim_f
=====================
*/
void idTestModel::TestModelNextAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->NextAnim( args );
}
/*
=====================
idTestModel::TestModelPrevAnim_f
=====================
*/
void idTestModel::TestModelPrevAnim_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->PrevAnim( args );
}
/*
=====================
idTestModel::TestModelNextFrame_f
=====================
*/
void idTestModel::TestModelNextFrame_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->NextFrame( args );
}
/*
=====================
idTestModel::TestModelPrevFrame_f
=====================
*/
void idTestModel::TestModelPrevFrame_f( const idCmdArgs &args ) {
if ( !gameLocal.testmodel ) {
gameLocal.Printf( "No testModel active.\n" );
return;
}
gameLocal.testmodel->PrevFrame( args );
}
|
gpl-3.0
|
georgetye/openemr
|
portal/messaging/handle_note.php
|
3696
|
<?php
/**
*
* Copyright (C) 2016-2017 Jerry Padgett <sjpadgett@gmail.com>
*
* LICENSE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package OpenEMR
* @author Jerry Padgett <sjpadgett@gmail.com>
* @link http://www.open-emr.org
*/
session_start();
if( isset( $_SESSION['pid'] ) && isset( $_SESSION['patient_portal_onsite_two'] ) ){
$owner = $_SESSION['pid'];
$ignoreAuth = true;
$fake_register_globals=false;
$sanitize_all_escapes=true;
require_once ( dirname( __FILE__ ) . "/../../interface/globals.php" );
} else{
session_destroy();
$ignoreAuth = false;
$sanitize_all_escapes = true;
$fake_register_globals = false;
require_once ( dirname( __FILE__ ) . "/../../interface/globals.php" );
if( ! isset( $_SESSION['authUserID'] ) ){
$landingpage = "index.php";
header( 'Location: ' . $landingpage );
exit();
}
}
require_once (dirname( __FILE__ ) . "/../lib/portal_mail.inc");
require_once("$srcdir/pnotes.inc");
$task = $_POST ['task'];
if (! $task)
return 'no task';
$noteid = $_POST ['noteid'] ? $_POST ['noteid'] : 0;
$reply_noteid = $_POST ['replyid'] ? $_POST ['replyid'] : 0;
$owner = isset($_POST ['owner']) ? $_POST ['owner'] : $_SESSION ['pid'];
$note = $_POST ['inputBody'];
$title = $_POST ['title'];
$sid=(int)$_POST ['sender_id'];
$sn=$_POST ['sender_name'];
$rid=(int)$_POST ['recipient_id'];
$rn=$_POST ['recipient_name'];
$header = '';
switch ($task) {
case "forward" :
{
addPnote($rid, $note,1,1,$title ,$sn,'','New');
updatePortalMailMessageStatus ( $noteid, 'Forwarded' );
echo 'ok';
}
break;
case "add" :
{
// each user has their own copy of message
sendMail ( $owner, $note, $title, $header, $noteid,$sid,$sn,$rid,$rn,'New' );
sendMail ( $rid, $note, $title, $header, $noteid,$sid,$sn,$rid,$rn,'New',$reply_noteid );
echo 'ok';
}
break;
case "reply" :
{
sendMail ( $owner, $note, $title, $header, $noteid,$sid,$sn,$rid,$rn,'Reply','' );
sendMail ( $rid, $note, $title, $header, $noteid,$sid,$sn,$rid,$rn,'New',$reply_noteid );
echo 'ok';
}
break;
case "delete" :
{
updatePortalMailMessageStatus ( $noteid, 'Delete' );
echo 'ok';
}
break;
case "setread" :
{
if ($noteid > 0) {
updatePortalMailMessageStatus ( $noteid, 'Read' );
echo 'ok';
} else
echo 'missing note id';
}
break;
case "getinbox" :
{
if ($owner) {
$result = getMails($owner,'inbox','','');
echo json_encode($result);
} else
echo 'error';
}
break;
case "getsent" :
{
if ($owner) {
$result = getMails($owner,'sent','','');
echo json_encode($result);
} else
echo 'error';
}
break;
case "getall" :
{
if ($owner) {
$result = getMails($owner,'all','','');
echo json_encode($result);
} else
echo 'error';
}
break;
case "getdeleted" :
{
if ($owner) {
$result = getMails($owner,'deleted','','');
echo json_encode($result);
} else
echo 'error';
}
break;
}
if(isset($_REQUEST["submit"]))
header("Location: {$_REQUEST["submit"]}");
?>
|
gpl-3.0
|
akiyamiyamoto/Tutorial
|
geant4/LC/LC3/LC3a/examples/SiD_Markus.py
|
7744
|
#
#
import os, time, logging, DDG4
from DDG4 import OutputLevel as Output
from SystemOfUnits import *
#
global geant4
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
#
"""
dd4hep simulation example setup using the python configuration
@author M.Frank
@version 1.0
"""
def setupWorker():
k = DDG4.Kernel()
kernel = k.worker()
print 'PYTHON: +++ Creating Geant4 worker thread ....'
# Configure Run actions
run1 = DDG4.RunAction(kernel,'Geant4TestRunAction/RunInit')
run1.Property_int = 12345
run1.Property_double = -5e15*keV
run1.Property_string = 'Startrun: Hello_2'
logging.info("%s %f %d",run1.Property_string, run1.Property_double, run1.Property_int)
run1.enableUI()
kernel.registerGlobalAction(run1)
kernel.runAction().adopt(run1)
# Configure Event actions
prt = DDG4.EventAction(kernel,'Geant4ParticlePrint/ParticlePrint')
prt.OutputLevel = Output.DEBUG
prt.OutputType = 3 # Print both: table and tree
kernel.eventAction().adopt(prt)
# Configure Event actions
prt = DDG4.EventAction(kernel,'Geant4SurfaceTest/SurfaceTest')
prt.OutputLevel = Output.INFO
kernel.eventAction().adopt(prt)
# Configure I/O
evt_lcio = geant4.setupLCIOOutput('LcioOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
evt_lcio.OutputLevel = Output.DEBUG
#evt_root = geant4.setupROOTOutput('RootOutput','CLICSiD_'+time.strftime('%Y-%m-%d_%H-%M'))
#generator_output_level = Output.INFO
gen = DDG4.GeneratorAction(kernel,"Geant4GeneratorActionInit/GenerationInit")
kernel.generatorAction().adopt(gen)
#VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
"""
Generation of isotrope tracks of a given multiplicity with overlay:
"""
# First particle generator: pi+
gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropPi+");
gen.Particle = 'pi+'
gen.Energy = 100 * GeV
gen.Multiplicity = 2
gen.Mask = 1
gen.OutputLevel = Output.DEBUG
gen.PhiMin = 0
gen.PhiMax = 0
gen.ThetaMin = 1.61
gen.ThetaMax = 1.61
kernel.generatorAction().adopt(gen)
# Install vertex smearing for this interaction
gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearPi+");
gen.Mask = 1
gen.Offset = (20*mm, 10*mm, 10*mm, 0*ns)
gen.Sigma = (4*mm, 1*mm, 1*mm, 0*ns)
kernel.generatorAction().adopt(gen)
"""
# Second particle generator: e-
gen = DDG4.GeneratorAction(kernel,"Geant4IsotropeGenerator/IsotropE-");
gen.Particle = 'e-'
gen.Energy = 25 * GeV
gen.Multiplicity = 3
gen.Mask = 2
gen.OutputLevel = Output.DEBUG
kernel.generatorAction().adopt(gen)
# Install vertex smearing for this interaction
gen = DDG4.GeneratorAction(kernel,"Geant4InteractionVertexSmear/SmearE-");
gen.Mask = 2
gen.Offset = (-20*mm, -10*mm, -10*mm, 0*ns)
gen.Sigma = (12*mm, 8*mm, 8*mm, 0*ns)
kernel.generatorAction().adopt(gen)
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"""
# Merge all existing interaction records
gen = DDG4.GeneratorAction(kernel,"Geant4InteractionMerger/InteractionMerger")
gen.OutputLevel = 4 #generator_output_level
gen.enableUI()
kernel.generatorAction().adopt(gen)
# Finally generate Geant4 primaries
gen = DDG4.GeneratorAction(kernel,"Geant4PrimaryHandler/PrimaryHandler")
gen.OutputLevel = Output.DEBUG #generator_output_level
gen.enableUI()
kernel.generatorAction().adopt(gen)
# And handle the simulation particles.
part = DDG4.GeneratorAction(kernel,"Geant4ParticleHandler/ParticleHandler")
kernel.generatorAction().adopt(part)
#part.SaveProcesses = ['conv','Decay']
part.SaveProcesses = ['Decay']
part.MinimalKineticEnergy = 100*MeV
part.OutputLevel = Output.DEBUG # generator_output_level
part.enableUI()
user = DDG4.Action(kernel,"Geant4TCUserParticleHandler/UserParticleHandler")
user.TrackingVolume_Zmax = DDG4.EcalEndcap_zmin
user.TrackingVolume_Rmax = DDG4.EcalBarrel_rmin
user.enableUI()
part.adopt(user)
logging.info('PYTHON: +++ Geant4 worker thread configured successfully....')
return 1
def setupMaster():
logging.info('PYTHON: +++ Setting up master thread.....')
return 1
def setupSensitives():
global geant4
# First the tracking detectors
seq,act = geant4.setupTracker('SiVertexBarrel')
act.OutputLevel = Output.ERROR
act.CollectSingleDeposits = False
seq,act = geant4.setupTracker('SiVertexEndcap')
act.OutputLevel = Output.ERROR
act.CollectSingleDeposits = False
logging.info('PYTHON: +++ Setting up Geant4 sensitive detectors for worker thread.....')
return 1
def dummy_sd():
logging.info('PYTHON: +++ Setting up DUMMY Geant4 sensitive detectors for worker thread.....')
return 1
def dummy_geom():
logging.info('PYTHON: +++ Setting up DUMMY Geant4 geometry for worker thread.....')
return 1
def run():
global geant4
kernel = DDG4.Kernel()
description = kernel.detectorDescription()
install_dir = os.environ['DD4hepINSTALL']
kernel.loadGeometry("file:"+install_dir+"/DDDetectors/compact/SiD_Markus.xml")
DDG4.importConstants(description)
DDG4.Core.setPrintLevel(Output.DEBUG)
DDG4.Core.setPrintFormat("%-32s %6s %s")
kernel.NumberOfThreads = 1
geant4 = DDG4.Geant4(kernel,tracker='Geant4TrackerWeightedAction')
geant4.printDetectors()
# Configure UI
geant4.setupCshUI()
# Geant4 user initialization action
geant4.addUserInitialization(worker=setupWorker, master=setupMaster)
# Configure G4 geometry setup
seq,act = geant4.addDetectorConstruction("Geant4DetectorGeometryConstruction/ConstructGeo")
# Configure G4 magnetic field tracking
self.setupTrackingFieldMT()
seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/DummyDet",
geometry=dummy_geom,
sensitives=dummy_sd)
# Configure G4 sensitive detectors
seq,act = geant4.addDetectorConstruction("Geant4PythonDetectorConstruction/SetupSD",
sensitives=setupSensitives)
# Configure G4 sensitive detectors
seq,act = geant4.addDetectorConstruction("Geant4DetectorSensitivesConstruction/ConstructSD",
allow_threads=True)
# Setup random generator
rndm = DDG4.Action(kernel,'Geant4Random/Random')
rndm.Seed = 987654321
rndm.initialize()
# Setup global filters fur use in sensntive detectors
f1 = DDG4.Filter(kernel,'GeantinoRejectFilter/GeantinoRejector')
kernel.registerGlobalFilter(f1)
#seq,act = geant4.setupTracker('SiTrackerBarrel')
#seq,act = geant4.setupTracker('SiTrackerEndcap')
#seq,act = geant4.setupTracker('SiTrackerForward')
# Now the calorimeters
#seq,act = geant4.setupCalorimeter('EcalBarrel')
#seq,act = geant4.setupCalorimeter('EcalEndcap')
#seq,act = geant4.setupCalorimeter('HcalBarrel')
#seq,act = geant4.setupCalorimeter('HcalEndcap')
#seq,act = geant4.setupCalorimeter('HcalPlug')
#seq,act = geant4.setupCalorimeter('MuonBarrel')
#seq,act = geant4.setupCalorimeter('MuonEndcap')
#seq,act = geant4.setupCalorimeter('LumiCal')
#seq,act = geant4.setupCalorimeter('BeamCal')
# Now build the physics list:
seq = geant4.setupPhysics('QGSP_BERT')
phys = DDG4.PhysicsList(geant4.master(),'Geant4PhysicsList/MyPhysics')
part = DDG4.Action(geant4.master(),'Geant4ExtraParticles/extraparts')
part.pdgfile = 'checkout/DDG4/examples/particle.tbl'
phys.adoptPhysicsConstructor(part.get())
seq.add(phys)
geant4.run()
#kernel.configure()
#kernel.initialize()
#DDG4.setPrintLevel(Output.DEBUG)
#kernel.run()
#kernel.terminate()
return 1
if __name__ == "__main__":
import sys
logging.info('Arguments: %s',str(sys.argv))
run()
|
gpl-3.0
|
vially/googlemusic-xbmc
|
resources/Lib/playsong.py
|
4654
|
import api
import utils
import xbmc
from storage import storage
class PlaySong:
def __init__(self):
self.api = api.Api()
def play(self, params):
song_id = params.pop('song_id')
if song_id[0] == 't': song_id = song_id.capitalize()
params = self.__getSongStreamUrl(song_id, params)
url = params.pop('url')
title = params.get('title')
utils.log("Song: %s - %r " % (title, url))
li = utils.createItem(title, params.pop('albumart'), params.pop('artistart'))
li.setInfo(type='music', infoLabels=params)
li.setPath(url)
utils.setResolvedUrl(li)
self.__incrementSongPlayCount(song_id)
if utils.addon.getSettingBool("prefetch"):
try:
self.__prefetchUrl()
except Exception as ex:
utils.log("ERROR trying to fetch url: " + repr(ex))
def __incrementSongPlayCount(self, song_id):
xbmc.sleep(5000)
self.api.incrementSongPlayCount(song_id)
def __getSongStreamUrl(self, song_id, params):
# try to fetch from memory first
params['url'] = utils.get_mem_cache(song_id)
# if no metadata
if 'title' not in params:
song = storage.getSong(song_id)
if not song:
# fetch from web
song = self.api.getTrack(song_id)
params['title'] = song['title']
params['artist'] = song['artist']
params['albumart'] = song['albumart']
params['artistart'] = song['artistart']
params['tracknumber'] = song['tracknumber']
params['album'] = song['album']
params['year'] = song['year']
params['rating'] = song['rating']
# check if not expired before returning
if params['url']:
import time
if int(utils.paramsToDict(params['url']).get('expire', 0)) < time.time():
params['url'] = ''
if not params['url']:
# try to fetch from web
params['url'] = self.api.getSongStreamUrl(song_id, session_token=params.pop('sessiontoken', None),
wentry_id=params.pop('wentryid', None))
return params
def __prefetchUrl(self):
import json
jsonGetPlaylistPos = '{"jsonrpc":"2.0", "method":"Player.GetProperties", "params":{"playerid":0,"properties":["playlistid","position","percentage"]},"id":1}'
jsonGetPlaylistItems = '{"jsonrpc":"2.0", "method":"Playlist.GetItems", "params":{"playlistid":0,"properties":["file","duration"]}, "id":1}'
# get song position in playlist
playerProperties = json.loads(xbmc.executeJSONRPC(jsonGetPlaylistPos))
while 'result' not in playerProperties or playerProperties['result']['percentage'] > 5:
# wait for song playing and playlist ready
xbmc.sleep(1000)
playerProperties = json.loads(xbmc.executeJSONRPC(jsonGetPlaylistPos))
position = playerProperties['result']['position']
utils.log("position:" + str(position) + " percentage:" + str(playerProperties['result']['percentage']))
# get next song id and fetch url
playlistItems = json.loads(xbmc.executeJSONRPC(jsonGetPlaylistItems))
# utils.log("playlistItems:: "+repr(playlistItems))
if 'items' not in playlistItems['result']:
utils.log("empty playlist")
return
if position + 1 >= len(playlistItems['result']['items']):
utils.log("playlist end:: position " + repr(position) + " size " + repr(len(playlistItems['result']['items'])))
return
song_id_next = utils.paramsToDict(playlistItems['result']['items'][position + 1]['file']).get("song_id")
stream_url = self.api.getSongStreamUrl(song_id_next)
utils.set_mem_cache(song_id_next, stream_url)
# stream url expires in 1 minute, refetch to always have a valid one
while True:
xbmc.sleep(50000)
# test if music changed
playerProperties = json.loads(xbmc.executeJSONRPC(jsonGetPlaylistPos))
utils.log("playerProperties:: " + repr(playerProperties))
if 'result' not in playerProperties or position != playerProperties['result']['position']:
utils.log("ending:: position " + repr(position) + " " + repr(playerProperties))
break
# before the stream url expires we fetch it again
stream_url = self.api.getSongStreamUrl(song_id_next)
utils.set_mem_cache(song_id_next, stream_url)
|
gpl-3.0
|
Cestra/Cestra
|
game/src/org/cestra/game/world/World.java
|
75220
|
package org.cestra.game.world;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.cestra.client.Account;
import org.cestra.client.Player;
import org.cestra.client.other.Stats;
import org.cestra.command.server.Commandes;
import org.cestra.command.server.Groupes;
import org.cestra.common.Formulas;
import org.cestra.common.SocketManager;
import org.cestra.db.Database;
import org.cestra.entity.Collector;
import org.cestra.entity.Dragodinde;
import org.cestra.entity.Pet;
import org.cestra.entity.PetEntry;
import org.cestra.entity.Prism;
import org.cestra.entity.monster.Monster;
import org.cestra.entity.npc.NpcAnswer;
import org.cestra.entity.npc.NpcQuestion;
import org.cestra.entity.npc.NpcTemplate;
import org.cestra.fight.spells.Spell;
import org.cestra.fight.spells.SpellEffect;
import org.cestra.game.GameClient;
import org.cestra.hdv.Hdv;
import org.cestra.hdv.HdvEntry;
import org.cestra.job.Job;
import org.cestra.job.maging.Rune;
import org.cestra.kernel.Boutique;
import org.cestra.kernel.Config;
import org.cestra.kernel.Console;
import org.cestra.kernel.Constant;
import org.cestra.kernel.Main;
import org.cestra.map.InteractiveObject;
import org.cestra.map.MountPark;
import org.cestra.map.SchemaFight;
import org.cestra.map.laby.Dc;
import org.cestra.map.laby.Toror;
import org.cestra.object.ObjectSet;
import org.cestra.object.ObjectTemplate;
import org.cestra.object.entity.Fragment;
import org.cestra.object.entity.SoulStone;
import org.cestra.other.Animation;
import org.cestra.other.Dopeul;
import org.cestra.other.Guild;
import org.cestra.other.House;
import org.cestra.other.Trunk;
import org.cestra.other.Tutorial;
import org.cestra.quest.Quest;
import org.cestra.quest.Quest_Etape;
public class World {
private static Map<Integer, Account> Comptes;
private static Map<String, Integer> ComptebyName;
private static Map<Integer, Player> Persos;
private static Map<Short, org.cestra.map.Map> Maps;
private static Map<Short, SchemaFight> SchemaFights;
private static Map<Integer, org.cestra.object.Object> Objets;
private static Map<Integer, ExpLevel> ExpLevels;
private static Map<Integer, Spell> Sorts;
private static Map<Integer, ObjectTemplate> ObjTemplates;
private static Map<Integer, Monster> MobTemplates;
private static Map<Integer, NpcTemplate> NPCTemplates;
private static Map<Integer, NpcQuestion> NPCQuestions;
private static Map<Integer, NpcAnswer> NpcAnswer;
private static Map<Integer, InteractiveObject.InteractiveObjectTemplate> IOTemplate;
private static Map<Integer, Dragodinde> Dragodindes;
private static Map<Integer, SuperArea> SuperAreas;
private static Map<Integer, Area> Areas;
private static Map<Integer, SubArea> SubAreas;
private static Map<Integer, Job> Jobs;
private static Map<Integer, ArrayList<Couple<Integer, Integer>>> Crafts;
private static Map<Integer, ObjectSet> ItemSets;
private static Map<Integer, Guild> Guildes;
private static Map<Integer, Hdv> Hdvs;
private static Map<Integer, Map<Integer, ArrayList<HdvEntry>>> hdvsItems;
private static Map<Integer, Player> Married;
private static Map<Integer, Animation> Animations;
private static Map<Short, MountPark> MountPark;
private static Map<Integer, Trunk> Trunks;
private static Map<Integer, Collector> Collectors;
private static Map<Integer, House> Houses;
private static Map<Short, Collection<Integer>> Seller;
private static StringBuilder Challenges;
private static Map<Integer, Prism> Prismes;
private static Map<Integer, Map<String, String>> fullmorphs;
private static Map<Integer, Pet> Pets;
private static Map<Integer, PetEntry> PetsEntry;
private static Map<String, Map<String, String>> mobGroupFix;
private static Map<Integer, Map<String, Map<String, Integer>>> extraMonstre;
private static Map<Integer, org.cestra.map.Map> extraMonstreOnMap;
private static Map<Integer, Tutorial> Tutorial;
private static int nextHdvID;
private static int nextHdvItemID;
private static int nextLigneID;
private static int nextObjetID;
static {
World.Comptes = new TreeMap<Integer, Account>();
World.ComptebyName = new TreeMap<String, Integer>();
World.Persos = new TreeMap<Integer, Player>();
World.Maps = new TreeMap<Short, org.cestra.map.Map>();
World.SchemaFights = new TreeMap<Short, SchemaFight>();
World.Objets = new TreeMap<Integer, org.cestra.object.Object>();
World.ExpLevels = new TreeMap<Integer, ExpLevel>();
World.Sorts = new TreeMap<Integer, Spell>();
World.ObjTemplates = new TreeMap<Integer, ObjectTemplate>();
World.MobTemplates = new TreeMap<Integer, Monster>();
World.NPCTemplates = new TreeMap<Integer, NpcTemplate>();
World.NPCQuestions = new TreeMap<Integer, NpcQuestion>();
World.NpcAnswer = new TreeMap<Integer, NpcAnswer>();
World.IOTemplate = new TreeMap<Integer, InteractiveObject.InteractiveObjectTemplate>();
World.Dragodindes = new TreeMap<Integer, Dragodinde>();
World.SuperAreas = new TreeMap<Integer, SuperArea>();
World.Areas = new TreeMap<Integer, Area>();
World.SubAreas = new TreeMap<Integer, SubArea>();
World.Jobs = new TreeMap<Integer, Job>();
World.Crafts = new TreeMap<Integer, ArrayList<Couple<Integer, Integer>>>();
World.ItemSets = new TreeMap<Integer, ObjectSet>();
World.Guildes = new TreeMap<Integer, Guild>();
World.Hdvs = new TreeMap<Integer, Hdv>();
World.hdvsItems = new HashMap<Integer, Map<Integer, ArrayList<HdvEntry>>>();
World.Married = new TreeMap<Integer, Player>();
World.Animations = new TreeMap<Integer, Animation>();
World.MountPark = new TreeMap<Short, MountPark>();
World.Trunks = new TreeMap<Integer, Trunk>();
World.Collectors = new TreeMap<Integer, Collector>();
World.Houses = new TreeMap<Integer, House>();
World.Seller = new TreeMap<Short, Collection<Integer>>();
World.Challenges = new StringBuilder();
World.Prismes = new TreeMap<Integer, Prism>();
World.fullmorphs = new HashMap<Integer, Map<String, String>>();
World.Pets = new TreeMap<Integer, Pet>();
World.PetsEntry = new TreeMap<Integer, PetEntry>();
World.mobGroupFix = new HashMap<String, Map<String, String>>();
World.extraMonstre = new TreeMap<Integer, Map<String, Map<String, Integer>>>();
World.extraMonstreOnMap = new TreeMap<Integer, org.cestra.map.Map>();
World.Tutorial = new TreeMap<Integer, Tutorial>();
}
public static Map<Integer, Account> getAccounts() {
return World.Comptes;
}
public static Map<Integer, Account> getAccountsByIp(final String Ip) {
final Map<Integer, Account> newAccounts = new TreeMap<Integer, Account>();
for (final Map.Entry<Integer, Account> entry : World.Comptes.entrySet()) {
if (entry.getValue().getLastIP().equalsIgnoreCase(Ip)) {
newAccounts.put(newAccounts.size(), entry.getValue());
}
}
return newAccounts;
}
public static Map<String, Integer> getAccountsByName() {
return World.ComptebyName;
}
public static Map<Integer, Player> getPlayers() {
return World.Persos;
}
public static Map<Short, org.cestra.map.Map> getMaps() {
return World.Maps;
}
public static Map<Integer, org.cestra.object.Object> getObjects() {
return World.Objets;
}
public static Map<Integer, ExpLevel> getExpLevels() {
return World.ExpLevels;
}
public static Map<Integer, Spell> getSpells() {
return World.Sorts;
}
public static Map<Integer, ObjectTemplate> getObjectsTemplates() {
return World.ObjTemplates;
}
public static Map<Integer, Monster> getMobsTemplates() {
return World.MobTemplates;
}
public static Map<Integer, NpcTemplate> getNpcTemplates() {
return World.NPCTemplates;
}
public static Map<Integer, NpcQuestion> getNpcQuestions() {
return World.NPCQuestions;
}
public static Map<Integer, NpcAnswer> getNpcAnswer() {
return World.NpcAnswer;
}
public static Map<Integer, InteractiveObject.InteractiveObjectTemplate> getIOTemplates() {
return World.IOTemplate;
}
public static Map<Integer, Dragodinde> getMounts() {
return World.Dragodindes;
}
public static Map<Integer, SuperArea> getSuperAreas() {
return World.SuperAreas;
}
public static Map<Integer, Area> getAreas() {
return World.Areas;
}
public static Map<Integer, SubArea> getSubAreas() {
return World.SubAreas;
}
public static Map<Integer, Job> getJobs() {
return World.Jobs;
}
public static Map<Integer, ArrayList<Couple<Integer, Integer>>> getCrafts() {
return World.Crafts;
}
public static Map<Integer, ObjectSet> getItemSets() {
return World.ItemSets;
}
public static Map<Integer, Guild> getGuilds() {
return World.Guildes;
}
public static Map<Integer, Hdv> getHdvs() {
return World.Hdvs;
}
public static Map<Integer, Map<Integer, ArrayList<HdvEntry>>> getHdvsItems() {
return World.hdvsItems;
}
public static Map<Integer, Player> getMarried() {
return World.Married;
}
public static Map<Integer, Animation> getAnimations() {
return World.Animations;
}
public static Map<Short, MountPark> getMountparks() {
return World.MountPark;
}
public static Map<Integer, Trunk> getTrunks() {
return World.Trunks;
}
public static Map<Integer, Collector> getCollectors() {
return World.Collectors;
}
public static Map<Integer, House> getHouses() {
return World.Houses;
}
public static Map<Short, Collection<Integer>> getSellers() {
return World.Seller;
}
public static StringBuilder getChallenges() {
return World.Challenges;
}
public static Map<Integer, Prism> getPrisms() {
return World.Prismes;
}
public static Map<Integer, Map<String, String>> getFullmorphs() {
return World.fullmorphs;
}
public static Map<Integer, Pet> getPets() {
return World.Pets;
}
public static Map<Integer, PetEntry> getPetsEntry() {
return World.PetsEntry;
}
public static Map<String, Map<String, String>> getMobGroupFix() {
return World.mobGroupFix;
}
public static Map<Integer, Map<String, Map<String, Integer>>> getExtraMonsters() {
return World.extraMonstre;
}
public static Map<Integer, org.cestra.map.Map> getExtraMonstersOnMap() {
return World.extraMonstreOnMap;
}
public static Map<Integer, Tutorial> getTutorials() {
return World.Tutorial;
}
public static void createWorld() {
final long time = System.currentTimeMillis();
Console.println("Creation of the world :", Console.Color.YELLOW);
Database.getStatique().getCommandeData().load();
Console.println("- Loading " + Commandes.size() + " Commands of Administrators.", Console.Color.GAME);
Database.getStatique().getGroupeData().load();
Console.println("- Loading " + Groupes.size() + " Groups of Administrators.", Console.Color.GAME);
Database.getStatique().getFull_morphData().load();
Console.println("- Loading " + getFullmorphs().size() + " Complete transformations.",Console.Color.GAME);
Database.getStatique().getExtra_monsterData().load();
Console.println("- Loading " + getExtraMonsters().size() + " Extra monsters.", Console.Color.GAME);
Database.getStatique().getExperienceData().load();
Console.println("- Loading " + World.ExpLevels.size() + " Levels.", Console.Color.GAME);
Database.getStatique().getSortData().load();
Console.println("- Loading " + World.Sorts.size() + " Spells.", Console.Color.GAME);
Database.getStatique().getMonsterData().load();
Console.println("- Loading " + World.MobTemplates.size() + " Monstres.", Console.Color.GAME);
Database.getStatique().getItem_templateData().load();
Console.println("- Loading " + World.ObjTemplates.size() + " Object templates.", Console.Color.GAME);
Console.println("- Loading " + Boutique.items.size() + " Shop items.", Console.Color.GAME);
Database.getStatique().getItemData().load();
Console.println("- Loading " + World.Objets.size() + " Objects.", Console.Color.GAME);
Database.getStatique().getNpc_templateData().load();
Console.println("- Loading " + World.NPCTemplates.size() + " NPC Templates.", Console.Color.GAME);
Database.getStatique().getNpc_questionData().load();
Console.println("- Loading " + getNpcQuestions().size() + " NPC questions.", Console.Color.GAME);
Database.getStatique().getNpc_reponses_actionData().load();
Console.println("- Loading " + getNpcAnswer().size() + " NPC responses.", Console.Color.GAME);
Database.getStatique().getQuest_objectifData().load();
Database.getStatique().getQuest_etapeData().load();
Console.println("- Loading " + Quest_Etape.getQuestEtapeList().size() + " Quest steps.",Console.Color.GAME);
Database.getStatique().getQuest_dataData().load();
Console.println("- Loading " + Quest.getQuestDataList().size() + " Quest.", Console.Color.GAME);
Database.getStatique().getNpc_templateData().loadQuest();
Console.println("- Added quests on NPC templates.", Console.Color.GAME);
final int numero = Database.getGame().getPrismeData().load();
Console.println("- Loading " + numero + " Prismatic.", Console.Color.GAME);
Database.getStatique().getArea_dataData().load();
Database.getGame().getArea_dataData().load();
Console.println("- Loading " + World.Areas.size() + " Areas.", Console.Color.GAME);
Database.getStatique().getSubarea_dataData().load();
Database.getGame().getSubarea_dataData().load();
Console.println("- Loading " + getSubAreas().size() + " Sub-areas.", Console.Color.GAME);
Database.getStatique().getInteractive_objects_dataData().load();
Console.println("- Loading " + World.IOTemplate.size() + " Interactive object templates.",Console.Color.GAME);
Database.getStatique().getCraftData().load();
Console.println("- Loading " + World.Crafts.size() + " Object Recipes.", Console.Color.GAME);
Database.getStatique().getJobs_dataData().load();
Console.println("- Loading " + World.Jobs.size() + " Jobs.", Console.Color.GAME);
Database.getStatique().getItemsetData().load();
Console.println("- Loading " + World.ItemSets.size() + " Item-Sets.", Console.Color.GAME);
Database.getStatique().getMapData().load();
Console.println("- Loading " + World.Maps.size() + " Maps.", Console.Color.GAME);
Database.getStatique().getSchemafightData().load();
Console.println("- Loading " + World.SchemaFights.size() + " schemafights.", Console.Color.GAME);
int nbr = Database.getStatique().getScripted_cellData().load();
Console.println("- Loading " + nbr + " Triggers.", Console.Color.GAME);
nbr = Database.getStatique().getEndfight_actionData().load();
Console.println("- Loading " + nbr + " endfight action.", Console.Color.GAME);
nbr = Database.getStatique().getNpcData().load();
Console.println("- Loading " + nbr + " NPCs.", Console.Color.GAME);
nbr = Database.getStatique().getObjectsactionData().load();
Console.println("- Loading " + nbr + " Object actions.", Console.Color.GAME);
Database.getStatique().getDropData().load();
Console.println("- Loading drops.", Console.Color.GAME);
Database.getStatique().getAnimationData().load();
Console.println("- Loading " + World.Animations.size() + " animations.", Console.Color.GAME);
Database.getStatique().getServerData().loggedZero();
Console.println("- Disconnecting all characters from the server. Server-ID: " + Main.serverId + ".", Console.Color.GAME);
Database.getStatique().getAccountData().load();
Console.println("- Loading " + World.Comptes.size() + " Accounts.", Console.Color.GAME);
Database.getStatique().getPlayerData().load();
Console.println("- Loading " + World.Persos.size() + " Characters.", Console.Color.GAME);
Database.getGame().getGuildData().load();
Console.println("- Loading " + getGuilds().size() + " Guilds.", Console.Color.GAME);
Database.getGame().getGuild_memberData().load();
Console.println("- Loading Guild Members.", Console.Color.GAME);
nbr = Database.getStatique().getPets_dataData().load();
Console.println("- Loading " + nbr + " Pets.", Console.Color.GAME);
nbr = Database.getStatique().getPetData().load();
Console.println("- Loading " + nbr + " Entries of Pets.", Console.Color.GAME);
Database.getStatique().getMounts_dataData().load();
Console.println("- Loading " + World.Dragodindes.size() + " Mounts.", Console.Color.GAME);
Database.getStatique().getTutorielData().load();
Console.println("- Loading " + World.Tutorial.size() + " Tutorials.", Console.Color.GAME);
Database.getStatique().getMountpark_dataData().load();
nbr = Database.getGame().getMountpark_dataData().load();
Console.println("- Loading " + nbr + " Mountpark.", Console.Color.GAME);
nbr = Database.getGame().getPercepteurData().load();
Console.println("- Loading " + nbr + " Perceptor.", Console.Color.GAME);
Database.getStatique().getHouseData().load();
nbr = Database.getGame().getHouseData().load();
Console.println("- Loading " + nbr + " Houses.", Console.Color.GAME);
Database.getStatique().getCoffreData().load();
nbr = Database.getGame().getCoffreData().load();
Console.println("- Loading " + nbr + " Chests.", Console.Color.GAME);
nbr = Database.getStatique().getZaapData().load();
Console.println("- Loading " + nbr + " Zaaps.", Console.Color.GAME);
nbr = Database.getStatique().getZaapiData().load();
Console.println("- Loading " + nbr + " Zaapis.", Console.Color.GAME);
Database.getStatique().getChallengeData().load();
Console.println("- Loading " + World.Challenges.toString().split(";").length + " Challenges.",Console.Color.GAME);
Database.getStatique().getHdvData().load();
Console.println("- Loading " + getHdvs().size() + " Auction Houses.", Console.Color.GAME);
Database.getGame().getHdvs_itemData().load();
Console.println("- Loading items Auction Houses.", Console.Color.GAME);
Database.getStatique().getDonjonData().load();
Console.println("- Loading " + Dopeul.getDonjons().size() + " Dungeons.", Console.Color.GAME);
try {
loadExtraMonster();
Console.println("- Added extra-monsters on maps.", Console.Color.GAME);
}
catch (Exception e) {
e.printStackTrace();
Console.println("Error while adding extra-monsters on maps: " + e.getMessage(),
Console.Color.ERROR);
}
try {
loadMonsterOnMap();
Console.println("- Adding Monsters to Maps.", Console.Color.GAME);
}
catch (Exception e) {
e.printStackTrace();
Console.println("Error adding monsters to maps: " + e.getMessage(),
Console.Color.ERROR);
}
Database.getStatique().getRuneData().load();
Console.println("- Loading " + Rune.runes.size() + " Runes.", Console.Color.GAME);
World.nextObjetID = Database.getStatique().getItemData().getNextObjetID();
Console.println("- Chargement des bandits de Cania.", Console.Color.GAME);
Database.getGame().getBanditData().load();
Console.println("- Initialization of the DRAGON PIG labyrinth.", Console.Color.GAME);
Dc.initialize();
Console.println("- Initialization of the MINOTOROR labyrinth.", Console.Color.GAME);
Toror.initialize();
Boutique.initPacket();
Database.getStatique().getServerData().updateTime(time);
System.out.println("The server has finished loading : "
+ new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss", Locale.FRANCE).format(new Date()) + "\n"
+ "The server was loaded in "
+ new SimpleDateFormat("mm", Locale.FRANCE).format(System.currentTimeMillis() - time) + " minutes and "
+ new SimpleDateFormat("ss", Locale.FRANCE).format(System.currentTimeMillis() - time) + " seconds.");
}
public static void addExtraMonster(final int idMob, final String superArea, final String subArea,
final int chances) {
final Map<String, Map<String, Integer>> map = new TreeMap<String, Map<String, Integer>>();
final Map<String, Integer> _map = new HashMap<String, Integer>();
_map.put(subArea, chances);
map.put(superArea, _map);
World.extraMonstre.put(idMob, map);
}
public static Map<Integer, org.cestra.map.Map> getExtraMonsterOnMap() {
return World.extraMonstreOnMap;
}
public static void loadExtraMonster() {
final ArrayList<org.cestra.map.Map> mapPossible = new ArrayList<org.cestra.map.Map>();
for (final Map.Entry<Integer, Map<String, Map<String, Integer>>> i : World.extraMonstre.entrySet()) {
Map<String, Map<String, Integer>> map = new TreeMap<String, Map<String, Integer>>();
map = i.getValue();
for (final Map.Entry<String, Map<String, Integer>> areaChances : map.entrySet()) {
Integer chances = null;
for (final Map.Entry<String, Integer> _e : areaChances.getValue().entrySet()) {
final Integer _c = _e.getValue();
if (_c != null && _c != -1) {
chances = _c;
}
}
if (!areaChances.getKey().equals("")) {
String[] split;
for (int length = (split = areaChances.getKey().split(",")).length, j = 0; j < length; ++j) {
final String ar = split[j];
final Area Area = World.Areas.get(Integer.parseInt(ar));
for (final org.cestra.map.Map Map : Area.getMaps()) {
if (Map == null) {
continue;
}
if (Map.haveMobFix()) {
continue;
}
if (!Map.isPossibleToPutMonster()) {
continue;
}
if (chances != null) {
Map.addMobExtra(i.getKey(), chances);
} else {
if (mapPossible.contains(Map)) {
continue;
}
mapPossible.add(Map);
}
}
}
}
if (!areaChances.getValue().equals("")) {
for (final Map.Entry<String, Integer> area : areaChances.getValue().entrySet()) {
final String areas = area.getKey();
String[] split2;
for (int length2 = (split2 = areas.split(",")).length, k = 0; k < length2; ++k) {
final String sub = split2[k];
SubArea subArea = null;
try {
subArea = World.SubAreas.get(Integer.parseInt(sub));
} catch (Exception e) {
e.printStackTrace();
}
if (subArea != null) {
for (final org.cestra.map.Map Map2 : subArea.getMaps()) {
if (Map2 != null) {
if (Map2.equals("")) {
continue;
}
if (Map2.haveMobFix()) {
continue;
}
if (!Map2.isPossibleToPutMonster()) {
continue;
}
if (chances != null) {
Map2.addMobExtra(i.getKey(), chances);
}
if (mapPossible.contains(Map2)) {
continue;
}
mapPossible.add(Map2);
}
}
}
}
}
}
}
if (mapPossible.size() <= 0) {
Console.println("#1# Erreur extraMonster : " + i.getKey(), Console.Color.ERROR);
mapPossible.clear();
} else {
org.cestra.map.Map aleaMap = null;
if (mapPossible.size() == 1) {
aleaMap = mapPossible.get(0);
} else {
aleaMap = mapPossible.get(Formulas.getRandomValue(0, mapPossible.size() - 1));
}
if (aleaMap == null) {
Console.println("#2# Erreur extraMonster : " + i.getKey(), Console.Color.ERROR);
mapPossible.clear();
} else {
if (getMonstre(i.getKey()) == null) {
Console.println("#3# Erreur extraMonster : " + i.getKey(), Console.Color.ERROR);
}
if (aleaMap.loadExtraMonsterOnMap(i.getKey())) {
World.extraMonstreOnMap.put(i.getKey(), aleaMap);
} else {
Console.println("#4# Erreur extraMonster : " + i.getKey(), Console.Color.ERROR);
}
mapPossible.clear();
}
}
}
}
public static Map<String, String> getGroupFix(final int map, final int cell) {
return World.mobGroupFix.get(String.valueOf(map) + ";" + cell);
}
public static void addGroupFix(final String str, final String mob, final int Time) {
World.mobGroupFix.put(str, new HashMap<String, String>());
World.mobGroupFix.get(str).put("groupData", mob);
World.mobGroupFix.get(str).put("timer", new StringBuilder(String.valueOf(Time)).toString());
}
public static Collection<SubArea> getAllSubArea() {
return World.SubAreas.values();
}
public static void loadMonsterOnMap() {
for (final org.cestra.map.Map i : World.Maps.values()) {
if (i == null) {
continue;
}
i.loadMonsterOnMap();
}
}
public static Area getArea(final int areaID) {
return World.Areas.get(areaID);
}
public static SuperArea getSuperArea(final int areaID) {
return World.SuperAreas.get(areaID);
}
public static SubArea getSubArea(final int areaID) {
return World.SubAreas.get(areaID);
}
public static void addArea(final Area area) {
World.Areas.put(area.get_id(), area);
}
public static void addSuperArea(final SuperArea SA) {
World.SuperAreas.put(SA.get_id(), SA);
}
public static void addSubArea(final SubArea SA) {
World.SubAreas.put(SA.getId(), SA);
}
public static String getSousZoneStateString() {
String str = "";
boolean first = false;
for (final SubArea subarea : World.SubAreas.values()) {
if (!subarea.getConquistable()) {
continue;
}
if (first) {
str = String.valueOf(str) + "|";
}
str = String.valueOf(str) + subarea.getId() + ";" + subarea.getAlignement();
first = true;
}
return str;
}
public static void addNpcAnswer(final NpcAnswer rep) {
World.NpcAnswer.put(rep.getId(), rep);
}
public static NpcAnswer getNpcAnswer(final int guid) {
return World.NpcAnswer.get(guid);
}
public static double getBalanceArea(final Area area, final int alignement) {
int cant = 0;
for (final SubArea subarea : World.SubAreas.values()) {
if (subarea.getArea() == area && subarea.getAlignement() == alignement) {
++cant;
}
}
if (cant == 0) {
return 0.0;
}
return Math.rint(1000 * cant / area.getSubAreas().size() / 10);
}
public static double getBalanceWorld(final int alignement) {
int cant = 0;
for (final SubArea subarea : World.SubAreas.values()) {
if (subarea.getAlignement() == alignement) {
++cant;
}
}
if (cant == 0) {
return 0.0;
}
return Math.rint(10 * cant / 4 / 10);
}
public static int getExpLevelSize() {
return World.ExpLevels.size();
}
public static void addExpLevel(final int lvl, final ExpLevel exp) {
World.ExpLevels.put(lvl, exp);
}
public static Account getCompte(final int guid) {
return World.Comptes.get(guid);
}
public static void addNPCQuestion(final NpcQuestion quest) {
World.NPCQuestions.put(quest.getId(), quest);
}
public static NpcQuestion getNPCQuestion(final int guid) {
return World.NPCQuestions.get(guid);
}
public static NpcTemplate getNPCTemplate(final int guid) {
return World.NPCTemplates.get(guid);
}
public static void addNpcTemplate(final NpcTemplate temp) {
World.NPCTemplates.put(temp.get_id(), temp);
}
public static org.cestra.map.Map getMap(final short id) {
return World.Maps.get(id);
}
public static void addMap(final org.cestra.map.Map map) {
if (!World.Maps.containsKey(map.getId())) {
World.Maps.put(map.getId(), map);
}
}
public static void delMap(final org.cestra.map.Map map) {
if (World.Maps.containsKey(map.getId())) {
World.Maps.remove(map.getId());
}
}
public static Account getCompteByName(final String name) {
return (World.ComptebyName.get(name.toLowerCase()) != null)
? World.Comptes.get(World.ComptebyName.get(name.toLowerCase())) : null;
}
public static Player getPersonnage(final int guid) {
return World.Persos.get(guid);
}
public static void addAccount(final Account compte) {
World.Comptes.put(compte.getGuid(), compte);
World.ComptebyName.put(compte.getName().toLowerCase(), compte.getGuid());
}
public static void addAccountbyName(final Account compte) {
World.ComptebyName.put(compte.getName(), compte.getGuid());
}
public static void addPersonnage(final Player perso) {
World.Persos.put(perso.getId(), perso);
}
public static Player getPersoByName(final String name) {
final ArrayList<Player> Ps = new ArrayList<Player>();
Ps.addAll(World.Persos.values());
for (final Player P : Ps) {
if (P.getName().equalsIgnoreCase(name)) {
return P;
}
}
return null;
}
public static void deletePerso(final Player perso) {
if (perso.get_guild() != null) {
if (perso.get_guild().getMembers().size() <= 1) {
removeGuild(perso.get_guild().getId());
} else if (perso.getGuildMember().getRank() == 1) {
final int curMaxRight = 0;
Player Meneur = null;
for (final Player newMeneur : perso.get_guild().getMembers()) {
if (newMeneur == perso) {
continue;
}
if (newMeneur.getGuildMember().getRights() >= curMaxRight) {
continue;
}
Meneur = newMeneur;
}
perso.get_guild().removeMember(perso);
Meneur.getGuildMember().setRank(1);
} else {
perso.get_guild().removeMember(perso);
}
}
perso.remove();
unloadPerso(perso.getId());
World.Persos.remove(perso.getId());
}
public static void unloadPerso(final Player perso) {
unloadPerso(perso.getId());
World.Persos.remove(perso.getId());
}
public static long getPersoXpMin(int _lvl) {
if (_lvl > getExpLevelSize()) {
_lvl = getExpLevelSize();
}
if (_lvl < 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl).perso;
}
public static long getPersoXpMax(int _lvl) {
if (_lvl >= getExpLevelSize()) {
_lvl = getExpLevelSize() - 1;
}
if (_lvl <= 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl + 1).perso;
}
public static long getTourmenteursXpMin(int _lvl) {
if (_lvl > getExpLevelSize()) {
_lvl = getExpLevelSize();
}
if (_lvl < 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl).tourmenteurs;
}
public static long getTourmenteursXpMax(int _lvl) {
if (_lvl >= getExpLevelSize()) {
_lvl = getExpLevelSize() - 1;
}
if (_lvl <= 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl + 1).tourmenteurs;
}
public static long getBanditsXpMin(int _lvl) {
if (_lvl > getExpLevelSize()) {
_lvl = getExpLevelSize();
}
if (_lvl < 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl).bandits;
}
public static long getBanditsXpMax(int _lvl) {
if (_lvl >= getExpLevelSize()) {
_lvl = getExpLevelSize() - 1;
}
if (_lvl <= 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl + 1).bandits;
}
public static void addSort(final Spell sort) {
World.Sorts.put(sort.getSpellID(), sort);
}
public static Spell getSort(final int id) {
return World.Sorts.get(id);
}
public static Spell delSort(final int id) {
return World.Sorts.remove(id);
}
public static void addObjTemplate(final ObjectTemplate obj) {
World.ObjTemplates.put(obj.getId(), obj);
}
public static ObjectTemplate getObjTemplate(final int id) {
return World.ObjTemplates.get(id);
}
public static boolean updateMapPlaces(final SchemaFight obj, final int id) {
return Database.getStatique().getMapData().updatePlaces(obj, id);
}
public static void editSchema(final SchemaFight obj, final short id) {
obj.setId(id);
}
public static boolean newSchemaFight(final SchemaFight obj) {
final boolean sql = Database.getStatique().getSchemafightData().add(obj);
if (sql) {
addSchemaFight(obj);
}
return sql;
}
public static boolean delSchemaFight(final SchemaFight obj) {
final boolean sql = Database.getStatique().getSchemafightData().delete(obj);
if (sql) {
World.SchemaFights.remove(obj.getId());
}
return sql;
}
public static void addSchemaFight(final SchemaFight obj) {
World.SchemaFights.put(obj.getId(), obj);
}
public static SchemaFight getSchemaFight(final int id) {
for (final Map.Entry<Short, SchemaFight> entry : World.SchemaFights.entrySet()) {
final Short tmp = entry.getKey();
if (tmp == id) {
return entry.getValue();
}
}
return null;
}
public static SchemaFight getSchemaFight(final String places) {
for (final Map.Entry<Short, SchemaFight> entry : World.SchemaFights.entrySet()) {
final SchemaFight tmp = entry.getValue();
if (tmp.getPlacesStr().equals(places)) {
return tmp;
}
}
return null;
}
public static Map<Short, SchemaFight> getSchemaFights() {
return World.SchemaFights;
}
public static synchronized int getNewItemGuid() {
return ++World.nextObjetID;
}
public static void addMobTemplate(final int id, final Monster mob) {
World.MobTemplates.put(id, mob);
}
public static Monster getMonstre(final int id) {
return World.MobTemplates.get(id);
}
public static Collection<Monster> getMonstres() {
return World.MobTemplates.values();
}
public static List<Player> getOnlinePersos() {
final List<Player> online = new ArrayList<Player>();
for (final Map.Entry<Integer, Player> perso : World.Persos.entrySet()) {
if (perso.getValue() == null) {
continue;
}
if (!perso.getValue().isOnline() || perso.getValue().getGameClient() == null) {
continue;
}
online.add(perso.getValue());
}
return online;
}
public static String getStatOfAlign() {
int ange = 0;
int demon = 0;
int total = 0;
for (final Player i : getPlayers().values()) {
if (i == null) {
continue;
}
if (i.get_align() == 1) {
++ange;
}
if (i.get_align() == 2) {
++demon;
}
++total;
}
ange /= total;
demon /= total;
if (ange > demon) {
return "Les Br\u00e2kmarien sont actuellement en minorit\u00e9, je peux donc te proposer de rejoindre les rangs Br\u00e2kmarien ?";
}
if (demon > ange) {
return "Les Bontarien sont actuellement en minorit\u00e9, je peux donc te proposer de rejoindre les rangs Bontarien ?";
}
if (demon == ange) {
return " Aucune milice est actuellement en minorit\u00e9, je peux donc te proposer de rejoindre al\u00e9atoirement une milice ?";
}
return "Undefined";
}
public static List<org.cestra.map.Map> getAllMaps() {
final List<org.cestra.map.Map> allMap = new ArrayList<org.cestra.map.Map>();
for (final Map.Entry<Short, org.cestra.map.Map> map : World.Maps.entrySet()) {
if (map != null) {
allMap.add(map.getValue());
}
}
return allMap;
}
public static void addObjet(final org.cestra.object.Object item, final boolean saveSQL) {
if (item == null) {
return;
}
World.Objets.put(item.getGuid(), item);
if (saveSQL) {
Database.getStatique().getItemData().saveNew(item);
}
}
public static org.cestra.object.Object getObjet(final int guid) {
return World.Objets.get(guid);
}
public static void removeItem(final int guid) {
World.Objets.remove(guid);
Database.getStatique().getItemData().delete(guid);
}
public static void addIOTemplate(final InteractiveObject.InteractiveObjectTemplate IOT) {
World.IOTemplate.put(IOT.getId(), IOT);
}
public static Dragodinde getDragoByID(final int id) {
return World.Dragodindes.get(id);
}
public static void addDragodinde(final Dragodinde DD) {
World.Dragodindes.put(DD.getId(), DD);
}
public static void removeDragodinde(final int DID) {
World.Dragodindes.remove(DID);
}
public static void addTutorial(final Tutorial tutorial) {
World.Tutorial.put(tutorial.getId(), tutorial);
}
public static Tutorial getTutorial(final int id) {
return World.Tutorial.get(id);
}
public static void RefreshAllMob() {
for (final org.cestra.map.Map map : World.Maps.values()) {
map.refreshSpawns();
}
}
public static ExpLevel getExpLevel(final int lvl) {
return World.ExpLevels.get(lvl);
}
public static InteractiveObject.InteractiveObjectTemplate getIOTemplate(final int id) {
return World.IOTemplate.get(id);
}
public static Job getMetier(final int id) {
return World.Jobs.get(id);
}
public static void addJob(final Job metier) {
World.Jobs.put(metier.getId(), metier);
}
public static void addCraft(final int id, final ArrayList<Couple<Integer, Integer>> m) {
World.Crafts.put(id, m);
}
public static ArrayList<Couple<Integer, Integer>> getCraft(final int i) {
return World.Crafts.get(i);
}
public static void addFullMorph(final int morphID, final String name, final int gfxID, final String spells,
final String[] args) {
if (World.fullmorphs.get(morphID) != null) {
return;
}
World.fullmorphs.put(morphID, new HashMap<String, String>());
World.fullmorphs.get(morphID).put("name", name);
World.fullmorphs.get(morphID).put("gfxid", new StringBuilder(String.valueOf(gfxID)).toString());
World.fullmorphs.get(morphID).put("spells", spells);
if (args != null) {
World.fullmorphs.get(morphID).put("vie", args[0]);
World.fullmorphs.get(morphID).put("pa", args[1]);
World.fullmorphs.get(morphID).put("pm", args[2]);
World.fullmorphs.get(morphID).put("vitalite", args[3]);
World.fullmorphs.get(morphID).put("sagesse", args[4]);
World.fullmorphs.get(morphID).put("terre", args[5]);
World.fullmorphs.get(morphID).put("feu", args[6]);
World.fullmorphs.get(morphID).put("eau", args[7]);
World.fullmorphs.get(morphID).put("air", args[8]);
World.fullmorphs.get(morphID).put("initiative", args[9]);
World.fullmorphs.get(morphID).put("stats", args[10]);
World.fullmorphs.get(morphID).put("donjon", args[11]);
}
}
public static Map<String, String> getFullMorph(final int morphID) {
return World.fullmorphs.get(morphID);
}
public static int getObjectByIngredientForJob(final ArrayList<Integer> list,
final Map<Integer, Integer> ingredients) {
if (list == null) {
return -1;
}
for (final int tID : list) {
final ArrayList<Couple<Integer, Integer>> craft = getCraft(tID);
if (craft == null) {
continue;
}
if (craft.size() != ingredients.size()) {
continue;
}
boolean ok = true;
for (final Couple<Integer, Integer> c : craft) {
if (!(ingredients.get(c.first) + " ").equals(c.second + " ")) {
ok = false;
}
}
if (ok) {
return tID;
}
}
return -1;
}
public static Account getCompteByPseudo(final String p) {
for (final Account C : World.Comptes.values()) {
if (C.getPseudo().equals(p)) {
return C;
}
}
return null;
}
public static void addItemSet(final ObjectSet itemSet) {
World.ItemSets.put(itemSet.getId(), itemSet);
}
public static ObjectSet getItemSet(final int tID) {
return World.ItemSets.get(tID);
}
public static int getItemSetNumber() {
return World.ItemSets.size();
}
public static int getNextIdForMount() {
int max = -101;
for (final int a : World.Dragodindes.keySet()) {
if (a < max) {
max = a;
}
}
return max - 3;
}
public static org.cestra.map.Map getMapByPosAndCont(final int mapX, final int mapY, final int contID) {
for (final org.cestra.map.Map map : World.Maps.values()) {
if (map.getX() == mapX && map.getY() == mapY
&& map.getSubArea().getArea().get_superArea().get_id() == contID) {
return map;
}
}
return null;
}
public static ArrayList<org.cestra.map.Map> getMapByPosInArray(final int mapX, final int mapY) {
final ArrayList<org.cestra.map.Map> i = new ArrayList<org.cestra.map.Map>();
for (final org.cestra.map.Map map : World.Maps.values()) {
if (map.getX() == mapX && map.getY() == mapY) {
i.add(map);
}
}
return i;
}
public static ArrayList<org.cestra.map.Map> getMapByPosInArrayPlayer(final int mapX, final int mapY,
final Player p) {
final ArrayList<org.cestra.map.Map> i = new ArrayList<org.cestra.map.Map>();
for (final org.cestra.map.Map map : World.Maps.values()) {
if (map.getX() == mapX && map.getY() == mapY && map.getSubArea().getArea().get_superArea().get_id() == p
.getCurMap().getSubArea().getArea().get_superArea().get_id()) {
i.add(map);
}
}
return i;
}
public static void addGuild(final Guild g, final boolean save) {
World.Guildes.put(g.getId(), g);
if (save) {
Database.getGame().getGuildData().add(g);
}
}
public static int getNextHighestGuildID() {
if (World.Guildes.isEmpty()) {
return 1;
}
int n = 0;
for (final int x : World.Guildes.keySet()) {
if (n < x) {
n = x;
}
}
return n + 1;
}
public static boolean guildNameIsUsed(final String name) {
for (final Guild g : World.Guildes.values()) {
if (g.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static boolean guildEmblemIsUsed(final String emb) {
for (final Guild g : World.Guildes.values()) {
if (g.getEmblem().equals(emb)) {
return true;
}
}
return false;
}
public static Guild getGuild(final int i) {
return World.Guildes.get(i);
}
public static int getGuildByName(final String name) {
for (final Guild g : World.Guildes.values()) {
if (g.getName().equalsIgnoreCase(name)) {
return g.getId();
}
}
return -1;
}
public static long getGuildXpMax(int _lvl) {
if (_lvl >= 200) {
_lvl = 199;
}
if (_lvl <= 1) {
_lvl = 1;
}
return World.ExpLevels.get(_lvl + 1).guilde;
}
public static void ReassignAccountToChar(final Account C) {
C.getPersos().clear();
Database.getStatique().getPlayerData().loadByAccountId(C.getGuid());
for (final Player P : World.Persos.values()) {
if (P.getAccID() == C.getGuid()) {
P.setAccount(C);
}
}
}
public static int getZaapCellIdByMapId(final short i) {
for (final Map.Entry<Integer, Integer> zaap : Constant.ZAAPS.entrySet()) {
if (zaap.getKey() == i) {
return zaap.getValue();
}
}
return -1;
}
public static int getEncloCellIdByMapId(final short i) {
if (getMap(i).getMountPark() != null && getMap(i).getMountPark().getCell() > 0) {
return getMap(i).getMountPark().getCell();
}
return -1;
}
public static void delDragoByID(final int getId) {
World.Dragodindes.remove(getId);
}
public static void removeGuild(final int id) {
House.removeHouseGuild(id);
org.cestra.map.Map.removeMountPark(id);
Collector.removeCollector(id);
World.Guildes.remove(id);
Database.getGame().getGuild_memberData().deleteAll(id);
Database.getGame().getGuildData().delete(id);
}
public static boolean ipIsUsed(final String ip) {
for (final Account c : World.Comptes.values()) {
if (c.getCurIP().compareTo(ip) == 0) {
return true;
}
}
return false;
}
public static int ipIsUsed2(final String ip) {
int i = 0;
for (final Account c : World.Comptes.values()) {
if (c.getCurIP().compareTo(ip) == 0) {
++i;
}
}
return i;
}
public static boolean ipIsUsed3(final Account acc, final String ip) {
final Player perso = acc.getCurPerso();
for (final Account c : World.Comptes.values()) {
if (c.getCurIP().compareTo(ip) == 0 && c != null) {
if (acc == null) {
continue;
}
final Player persoC = c.getCurPerso();
if (persoC.getGroupe() != null && perso.getGroupe() == null) {
return true;
}
if (persoC.getGroupe() == null && perso.getGroupe() != null) {
return true;
}
continue;
}
}
return false;
}
public static void unloadPerso(final int g) {
Player toRem = World.Persos.get(g);
synchronized (toRem.getItems()) {
if (!toRem.getItems().isEmpty()) {
for (final Map.Entry<Integer, org.cestra.object.Object> curObj : toRem.getItems().entrySet()) {
World.Objets.remove(curObj.getKey());
}
}
}
// monitorexit(toRem.getItems())
toRem = null;
}
public static org.cestra.object.Object newObjet(final int Guid, final int template, final int qua, final int pos,
final String strStats, final int puit) {
if (getObjTemplate(template) == null) {
Console.println("Erreur items. Template " + template + " inexistant.", Console.Color.ERROR);
return null;
}
if (template == 8378) {
return new Fragment(Guid, strStats);
}
if (getObjTemplate(template).getType() == 85) {
return new SoulStone(Guid, qua, template, pos, strStats);
}
if (getObjTemplate(template).getType() == 24) {
if (!Constant.isCertificatDopeuls(getObjTemplate(template).getId())) {
if (getObjTemplate(template).getId() != 6653) {
return new org.cestra.object.Object(Guid, template, qua, pos, strStats, 0);
}
}
try {
final Map<Integer, String> txtStat = new TreeMap<Integer, String>();
txtStat.put(805, new StringBuilder(String.valueOf(strStats.substring(3))).toString());
return new org.cestra.object.Object(Guid, template, qua, -1, new Stats(false, null),
new ArrayList<SpellEffect>(), new TreeMap<Integer, Integer>(), txtStat, puit);
} catch (Exception e) {
e.printStackTrace();
return new org.cestra.object.Object(Guid, template, qua, pos, strStats, 0);
}
}
return new org.cestra.object.Object(Guid, template, qua, pos, strStats, 0);
}
public static Map<Integer, Integer> getChangeHdv() {
final Map<Integer, Integer> changeHdv = new HashMap<Integer, Integer>();
changeHdv.put(8753, 8759);
changeHdv.put(4607, 4271);
changeHdv.put(4622, 4216);
changeHdv.put(4627, 4232);
changeHdv.put(5112, 4178);
changeHdv.put(4562, 4183);
changeHdv.put(8754, 8760);
changeHdv.put(5317, 4098);
changeHdv.put(4615, 4247);
changeHdv.put(4646, 4262);
changeHdv.put(8756, 8757);
changeHdv.put(4618, 4174);
changeHdv.put(4588, 4172);
changeHdv.put(8482, 10129);
changeHdv.put(4595, 4287);
changeHdv.put(4630, 2221);
changeHdv.put(5311, 4179);
changeHdv.put(4629, 4299);
return changeHdv;
}
public static int changeHdv(int map) {
final Map<Integer, Integer> changeHdv = getChangeHdv();
if (changeHdv.containsKey(map)) {
map = changeHdv.get(map);
}
return map;
}
public static Hdv getHdv(final int map) {
return World.Hdvs.get(changeHdv(map));
}
public static synchronized int getNextHdvID() {
return ++World.nextHdvID;
}
public static synchronized void setNextHdvID(final int id) {
World.nextHdvID = id;
}
public static synchronized int getNextHdvItemID() {
return ++World.nextHdvItemID;
}
public static synchronized void setNextHdvItemID(final int id) {
World.nextHdvItemID = id;
}
public static synchronized int getNextLigneID() {
return ++World.nextLigneID;
}
public static synchronized void setNextLigneID(final int id) {
World.nextLigneID = id;
}
public static void addHdvItem(final int compteID, final int hdvID, final HdvEntry toAdd) {
if (World.hdvsItems.get(compteID) == null) {
World.hdvsItems.put(compteID, new HashMap<Integer, ArrayList<HdvEntry>>());
}
if (World.hdvsItems.get(compteID).get(hdvID) == null) {
World.hdvsItems.get(compteID).put(hdvID, new ArrayList<HdvEntry>());
}
World.hdvsItems.get(compteID).get(hdvID).add(toAdd);
}
public static void removeHdvItem(final int compteID, final int hdvID, final HdvEntry toDel) {
World.hdvsItems.get(compteID).get(hdvID).remove(toDel);
}
public static int getHdvNumber() {
return World.Hdvs.size();
}
public static int getHdvObjetsNumber() {
int size = 0;
for (final Map<Integer, ArrayList<HdvEntry>> curCompte : World.hdvsItems.values()) {
for (final ArrayList<HdvEntry> curHdv : curCompte.values()) {
size += curHdv.size();
}
}
return size;
}
public static void addHdv(final Hdv toAdd) {
World.Hdvs.put(toAdd.getHdvId(), toAdd);
}
public static Map<Integer, ArrayList<HdvEntry>> getMyItems(final int compteID) {
if (World.hdvsItems.get(compteID) == null) {
World.hdvsItems.put(compteID, new HashMap<Integer, ArrayList<HdvEntry>>());
}
return World.hdvsItems.get(compteID);
}
public static Collection<ObjectTemplate> getObjTemplates() {
return World.ObjTemplates.values();
}
public static Player getMarried(final int ordre) {
return World.Married.get(ordre);
}
public static void AddMarried(final int ordre, final Player perso) {
World.Married.remove(ordre);
World.Married.put(ordre, perso);
}
public static void PriestRequest(final Player perso, final org.cestra.map.Map Map, final int IdPretre) {
final Player Homme = World.Married.get(0);
final Player Femme = World.Married.get(1);
if (Homme.getWife() != 0) {
SocketManager.GAME_SEND_MESSAGE_TO_MAP(Map,
String.valueOf(Homme.getName()) + " est d\u00e9j\u00e0 marier !",
Config.getInstance().colorMessage);
return;
}
if (Femme.getWife() != 0) {
SocketManager.GAME_SEND_MESSAGE_TO_MAP(Map,
String.valueOf(Femme.getName()) + " est d\u00e9j\u00e0 marier !",
Config.getInstance().colorMessage);
return;
}
SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(perso.getCurMap(), "", -1, "Pr\u00eatre",
String.valueOf(perso.getName()) + " acceptez-vous d'\u00e9pouser "
+ getMarried((perso.getSexe() != 1) ? 1 : 0).getName() + " ?");
SocketManager.GAME_SEND_WEDDING(Map, 617, (Homme == perso) ? Homme.getId() : Femme.getId(),
(Homme == perso) ? Femme.getId() : Homme.getId(), IdPretre);
}
public static void Wedding(final Player Homme, final Player Femme, final int isOK) {
if (isOK > 0) {
SocketManager.GAME_SEND_cMK_PACKET_TO_MAP(Homme.getCurMap(), "", -1, "Pr\u00eatre", "Je d\u00e9clare "
+ Homme.getName() + " et " + Femme.getName() + " unis par les liens sacr\u00e9s du mariage.");
Homme.MarryTo(Femme);
Femme.MarryTo(Homme);
} else {
SocketManager.GAME_SEND_Im_PACKET_TO_MAP(Homme.getCurMap(),
"048;" + Homme.getName() + "~" + Femme.getName());
}
World.Married.get(0).setisOK(0);
World.Married.get(1).setisOK(0);
World.Married.clear();
}
public static Animation getAnimation(final int AnimationId) {
return World.Animations.get(AnimationId);
}
public static void addAnimation(final Animation animation) {
World.Animations.put(animation.getId(), animation);
}
public static void addHouse(final House house) {
World.Houses.put(house.getId(), house);
}
public static House getHouse(final int id) {
return World.Houses.get(id);
}
public static void addCollector(final Collector Collector) {
World.Collectors.put(Collector.getId(), Collector);
}
public static Collector getCollector(final int CollectorID) {
return World.Collectors.get(CollectorID);
}
public static void addTrunk(final Trunk trunk) {
World.Trunks.put(trunk.getId(), trunk);
}
public static Trunk getTrunk(final int id) {
return World.Trunks.get(id);
}
public static void addMountPark(final MountPark mp) {
World.MountPark.put(mp.getMap().getId(), mp);
}
public static Map<Short, MountPark> getMountPark() {
return World.MountPark;
}
public static String parseMPtoGuild(final int GuildID) {
final Guild G = getGuild(GuildID);
final byte enclosMax = (byte) Math.floor(G.getLvl() / 10);
final StringBuilder packet = new StringBuilder();
packet.append(enclosMax);
for (final Map.Entry<Short, MountPark> mp : World.MountPark.entrySet()) {
if (mp.getValue().getGuild() != null && mp.getValue().getGuild().getId() == GuildID) {
packet.append("|").append(mp.getValue().getMap().getId()).append(";").append(mp.getValue().getSize())
.append(";").append(mp.getValue().getMaxObject());
if (mp.getValue().getListOfRaising().size() <= 0) {
continue;
}
packet.append(";");
boolean primero = false;
for (final Integer id : mp.getValue().getListOfRaising()) {
final Dragodinde dd = getDragoByID(id);
if (dd != null) {
if (primero) {
packet.append(",");
}
packet.append(String.valueOf(dd.getColor()) + "," + dd.getName() + ",");
if (getPersonnage(dd.getPerso()) == null) {
packet.append("Sans maitre");
} else {
packet.append(getPersonnage(dd.getPerso()).getName());
}
primero = true;
}
}
}
}
return packet.toString();
}
public static int totalMPGuild(final int GuildID) {
int i = 0;
for (final Map.Entry<Short, MountPark> mp : World.MountPark.entrySet()) {
if (mp.getValue().getGuild() != null && mp.getValue().getGuild().getId() == GuildID) {
++i;
}
}
return i;
}
public static void addChallenge(final String chal) {
if (!World.Challenges.toString().isEmpty()) {
World.Challenges.append(";");
}
World.Challenges.append(chal);
}
public static synchronized void addPrisme(final Prism Prisme) {
World.Prismes.put(Prisme.getId(), Prisme);
}
public static Prism getPrisme(final int id) {
return World.Prismes.get(id);
}
public static void removePrisme(final int id) {
World.Prismes.remove(id);
}
public static Collection<Prism> AllPrisme() {
if (World.Prismes.size() > 0) {
return World.Prismes.values();
}
return null;
}
public static String PrismesGeoposition(final int alignement) {
String str = "";
boolean first = false;
int subareas = 0;
for (final SubArea subarea : World.SubAreas.values()) {
if (!subarea.getConquistable()) {
continue;
}
if (first) {
str = String.valueOf(str) + ";";
}
str = String.valueOf(str) + subarea.getId() + ","
+ ((subarea.getAlignement() == 0) ? -1 : subarea.getAlignement()) + ",0,";
if (getPrisme(subarea.getPrismId()) == null) {
str = String.valueOf(str) + "0,1";
} else {
str = String.valueOf(str) + ((subarea.getPrismId() == 0) ? 0 : getPrisme(subarea.getPrismId()).getMap())
+ ",1";
}
first = true;
++subareas;
}
if (alignement == 1) {
str = String.valueOf(str) + "|" + Area._bontas;
} else if (alignement == 2) {
str = String.valueOf(str) + "|" + Area._brakmars;
}
str = String.valueOf(str) + "|" + World.Areas.size() + "|";
first = false;
for (final Area area : World.Areas.values()) {
if (area.getalignement() == 0) {
continue;
}
if (first) {
str = String.valueOf(str) + ";";
}
str = String.valueOf(str) + area.get_id() + "," + area.getalignement() + ",1,"
+ ((area.getPrismeID() != 0) ? 1 : 0);
first = true;
}
if (alignement == 1) {
str = String.valueOf(Area._bontas) + "|" + subareas + "|" + (subareas - (SubArea.bontas + SubArea.brakmars))
+ "|" + str;
} else if (alignement == 2) {
str = String.valueOf(Area._brakmars) + "|" + subareas + "|"
+ (subareas - (SubArea.bontas + SubArea.brakmars)) + "|" + str;
}
return str;
}
public static void showPrismes(final Player perso) {
for (final SubArea subarea : World.SubAreas.values()) {
if (subarea.getAlignement() == 0) {
continue;
}
SocketManager.GAME_SEND_am_ALIGN_PACKET_TO_SUBAREA(perso,
String.valueOf(subarea.getId()) + "|" + subarea.getAlignement() + "|1");
}
}
public static synchronized int getNextIDPrisme() {
int max = -102;
for (final int a : World.Prismes.keySet()) {
if (a < max) {
max = a;
}
}
return max - 3;
}
public static void addPets(final Pet pets) {
World.Pets.put(pets.getTemplateId(), pets);
}
public static Pet getPets(final int Tid) {
return World.Pets.get(Tid);
}
public static void addPetsEntry(final PetEntry pets) {
World.PetsEntry.put(pets.getObjectId(), pets);
}
public static PetEntry getPetsEntry(final int guid) {
return World.PetsEntry.get(guid);
}
public static PetEntry removePetsEntry(final int guid) {
return World.PetsEntry.remove(guid);
}
public static String getChallengeFromConditions(final boolean sevEnn, final boolean sevAll, final boolean bothSex,
final boolean EvenEnn, final boolean MoreEnn, final boolean hasCaw, final boolean hasChaf,
final boolean hasRoul, final boolean hasArak, final int isBoss, final boolean ecartLvlPlayer,
final boolean hasArround, final boolean hasDisciple, final boolean isSolo) {
final StringBuilder toReturn = new StringBuilder();
boolean isFirst = true;
boolean isGood = false;
int cond = 0;
String[] split;
for (int length = (split = World.Challenges.toString().split(";")).length, i = 0; i < length; ++i) {
final String chal = split[i];
if (!isFirst && isGood) {
toReturn.append(";");
}
isGood = true;
final int id = Integer.parseInt(chal.split(",")[0]);
cond = Integer.parseInt(chal.split(",")[4]);
if ((cond & 0x1) == 0x1 && !sevEnn) {
isGood = false;
}
if ((cond >> 1 & 0x1) == 0x1 && !sevAll) {
isGood = false;
}
if ((cond >> 2 & 0x1) == 0x1 && !bothSex) {
isGood = false;
}
if ((cond >> 3 & 0x1) == 0x1 && !EvenEnn) {
isGood = false;
}
if ((cond >> 4 & 0x1) == 0x1 && !MoreEnn) {
isGood = false;
}
if (!hasCaw && id == 7) {
isGood = false;
}
if (!hasChaf && id == 12) {
isGood = false;
}
if (!hasRoul && id == 14) {
isGood = false;
}
if (!hasArak && id == 15) {
isGood = false;
}
if (!ecartLvlPlayer && id == 48) {
isGood = false;
}
if (isBoss != -1 && id == 5) {
isGood = false;
}
if (!hasArround && id == 36) {
isGood = false;
}
if (!hasDisciple && id == 19) {
isGood = false;
}
switch (id) {
case 44:
case 45:
case 46:
case 47: {
if (isSolo) {
isGood = false;
break;
}
break;
}
}
Label_0879: {
switch (isBoss) {
case 1045: {
switch (id) {
case 1:
case 2:
case 8:
case 37: {
isGood = false;
break;
}
}
break;
}
case 1072:
case 1085:
case 1086:
case 1087: {
switch (id) {
case 20:
case 36: {
isGood = false;
break;
}
}
break;
}
case 1071: {
switch (id) {
case 9:
case 17:
case 22:
case 47: {
isGood = false;
break;
}
}
break;
}
case 780: {
switch (id) {
case 3:
case 4:
case 25:
case 31:
case 32:
case 34:
case 35: {
isGood = false;
break;
}
}
break;
}
case 113: {
switch (id) {
case 7:
case 12:
case 15:
case 41: {
isGood = false;
break;
}
}
break;
}
case 612: {
switch (id) {
case 20:
case 37: {
isGood = false;
break;
}
}
break;
}
case 478:
case 568:
case 940: {
switch (id) {
case 20: {
isGood = false;
break;
}
}
break;
}
case 1188: {
switch (id) {
case 20:
case 44:
case 46: {
isGood = false;
break;
}
}
break;
}
case 865:
case 866: {
switch (id) {
case 31:
case 32: {
isGood = false;
break Label_0879;
}
}
break;
}
}
}
if (isGood) {
toReturn.append(chal);
}
isFirst = false;
}
return toReturn.toString();
}
public static void verifyClone(final Player p) {
if (p.getCurCell() != null && p.get_fight() == null && p.getCurCell().getCharacters().containsKey(p.getId())) {
p.getCurCell().removeCharacter(p.getId());
Database.getStatique().getPlayerData().update(p, true);
}
if (p.isOnline()) {
Database.getStatique().getPlayerData().update(p, true);
}
}
public static ArrayList<String> getRandomChallenge(final int nombreChal, final String challenges) {
final String MovingChals = ";1;2;8;36;37;39;40;";
boolean hasMovingChal = false;
final String TargetChals = ";3;4;10;25;31;32;34;35;38;42;";
boolean hasTargetChal = false;
final String SpellChals = ";5;6;9;11;19;20;24;41;";
boolean hasSpellChal = false;
final String KillerChals = ";28;29;30;44;45;46;48;";
boolean hasKillerChal = false;
final String HealChals = ";18;43;";
boolean hasHealChal = false;
int compteur = 0;
int i = 0;
final ArrayList<String> toReturn = new ArrayList<String>();
String chal = new String();
while (compteur < 100 && toReturn.size() < nombreChal) {
++compteur;
i = Formulas.getRandomValue(1, challenges.split(";").length);
chal = challenges.split(";")[i - 1];
if (!toReturn.contains(chal)) {
if (MovingChals.contains(";" + chal.split(",")[0] + ";")) {
if (!hasMovingChal) {
hasMovingChal = true;
toReturn.add(chal);
continue;
}
continue;
} else if (TargetChals.contains(";" + chal.split(",")[0] + ";")) {
if (!hasTargetChal) {
hasTargetChal = true;
toReturn.add(chal);
continue;
}
continue;
} else if (SpellChals.contains(";" + chal.split(",")[0] + ";")) {
if (!hasSpellChal) {
hasSpellChal = true;
toReturn.add(chal);
continue;
}
continue;
} else if (KillerChals.contains(";" + chal.split(",")[0] + ";")) {
if (!hasKillerChal) {
hasKillerChal = true;
toReturn.add(chal);
continue;
}
continue;
} else if (HealChals.contains(";" + chal.split(",")[0] + ";")) {
if (!hasHealChal) {
hasHealChal = true;
toReturn.add(chal);
continue;
}
continue;
} else {
toReturn.add(chal);
}
}
++compteur;
}
return toReturn;
}
public static Collector getCollectorById(final int id) {
return getCollectors().get(id);
}
public static Collector getCollectorByMap(final int id) {
for (final Map.Entry<Integer, Collector> Collector : getCollectors().entrySet()) {
final org.cestra.map.Map map = getMap(Collector.getValue().getMap());
if (map.getId() == id) {
return Collector.getValue();
}
}
return null;
}
public static List<Player> getPersonnageOnSameMap(final int IDmap) {
final List<Player> present = new ArrayList<Player>();
for (final Map.Entry<Integer, Player> perso : World.Persos.entrySet()) {
if (perso.getValue().getCurMap().getId() == IDmap) {
present.add(perso.getValue());
}
}
return present;
}
public static void reloadPlayerGroup() {
for (final GameClient client : Main.gameServer.getClients().values()) {
if (client == null) {
continue;
}
if (client.getPersonnage() == null) {
continue;
}
Database.getStatique().getPlayerData().reloadGroup(client.getPersonnage());
}
}
public static void reloadDrops() {
Database.getStatique().getDropData().reload();
}
public static void reloadEndFightActions() {
Database.getStatique().getEndfight_actionData().reload();
}
public static void reloadNpcs() {
Database.getStatique().getNpc_templateData().reload();
World.NPCQuestions.clear();
Database.getStatique().getNpc_questionData().load();
World.NpcAnswer.clear();
Database.getStatique().getNpc_reponses_actionData().load();
}
public static void reloadHouses() {
World.Houses.clear();
Database.getStatique().getHouseData().load();
Database.getGame().getHouseData().load();
}
public static void reloadTrunks() {
World.Trunks.clear();
Database.getStatique().getCoffreData().load();
Database.getGame().getCoffreData().load();
}
public static void reloadMaps() {
Database.getStatique().getMapData().reload();
}
public static void reloadMountParks(final int i) {
Database.getStatique().getMountpark_dataData().reload(i);
Database.getGame().getMountpark_dataData().reload(i);
}
public static void reloadMonsters() {
Database.getStatique().getMonsterData().reload();
}
public static void reloadQuests() {
Database.getStatique().getQuest_dataData().load();
}
public static void reloadObjectsActions() {
Database.getStatique().getObjectsactionData().reload();
}
public static void reloadSpells() {
Database.getStatique().getSortData().load();
}
public static void reloadItems() {
Database.getStatique().getItem_templateData().load();
}
public static void addSeller(final Player player) {
synchronized (player.getStoreItems()) {
if (player.getStoreItems().isEmpty()) {
// monitorexit(player.getStoreItems())
return;
}
}
// monitorexit(player.getStoreItems())
final short map = player.getCurMap().getId();
if (World.Seller.get(map) == null) {
final ArrayList<Integer> players = new ArrayList<Integer>();
players.add(player.getId());
World.Seller.put(map, players);
} else {
final ArrayList<Integer> players = new ArrayList<Integer>();
players.add(player.getId());
players.addAll(World.Seller.get(map));
World.Seller.remove(map);
World.Seller.put(map, players);
}
}
public static Collection<Integer> getSeller(final short map) {
return World.Seller.get(map);
}
public static void removeSeller(final int player, final short map) {
World.Seller.get(map).remove(player);
}
public static double getPwrPerEffet(final int effect) {
double r = 0.0;
switch (effect) {
case 111: {
r = 100.0;
break;
}
case 78: {
r = 90.0;
break;
}
case 110: {
r = 0.25;
break;
}
case 114: {
r = 100.0;
break;
}
case 115: {
r = 30.0;
break;
}
case 117: {
r = 51.0;
break;
}
case 118: {
r = 1.0;
break;
}
case 119: {
r = 1.0;
break;
}
case 120: {
r = 100.0;
break;
}
case 112: {
r = 20.0;
break;
}
case 122: {
r = 1.0;
break;
}
case 123: {
r = 1.0;
break;
}
case 124: {
r = 3.0;
break;
}
case 125: {
r = 0.25;
break;
}
case 126: {
r = 1.0;
break;
}
case 128: {
r = 90.0;
break;
}
case 138: {
r = 2.0;
break;
}
case 142: {
r = 2.0;
break;
}
case 158: {
r = 0.25;
break;
}
case 160: {
r = 1.0;
break;
}
case 161: {
r = 1.0;
break;
}
case 174: {
r = 0.1;
break;
}
case 176: {
r = 3.0;
break;
}
case 178: {
r = 20.0;
break;
}
case 182: {
r = 30.0;
break;
}
case 210: {
r = 6.0;
break;
}
case 211: {
r = 6.0;
break;
}
case 212: {
r = 6.0;
break;
}
case 213: {
r = 6.0;
break;
}
case 214: {
r = 6.0;
break;
}
case 225: {
r = 15.0;
break;
}
case 226: {
r = 2.0;
break;
}
case 240: {
r = 2.0;
break;
}
case 241: {
r = 2.0;
break;
}
case 242: {
r = 2.0;
break;
}
case 243: {
r = 2.0;
break;
}
case 244: {
r = 2.0;
break;
}
case 250: {
r = 6.0;
break;
}
case 251: {
r = 6.0;
break;
}
case 252: {
r = 6.0;
break;
}
case 253: {
r = 6.0;
break;
}
case 254: {
r = 6.0;
break;
}
case 260: {
r = 2.0;
break;
}
case 261: {
r = 2.0;
break;
}
case 262: {
r = 2.0;
break;
}
case 263: {
r = 2.0;
break;
}
case 264: {
r = 2.0;
break;
}
}
return r;
}
public static double getOverPerEffet(final int effect) {
double r = 0.0;
switch (effect) {
case 111: {
r = 0.0;
break;
}
case 78: {
r = 404.0;
break;
}
case 110: {
r = 404.0;
break;
}
case 114: {
r = 0.0;
break;
}
case 115: {
r = 3.0;
break;
}
case 117: {
r = 0.0;
break;
}
case 118: {
r = 101.0;
break;
}
case 119: {
r = 101.0;
break;
}
case 120: {
r = 0.0;
break;
}
case 112: {
r = 5.0;
break;
}
case 122: {
r = 0.0;
break;
}
case 123: {
r = 101.0;
break;
}
case 124: {
r = 33.0;
break;
}
case 125: {
r = 404.0;
break;
}
case 126: {
r = 101.0;
break;
}
case 128: {
r = 0.0;
break;
}
case 138: {
r = 50.0;
break;
}
case 142: {
r = 50.0;
break;
}
case 158: {
r = 404.0;
break;
}
case 160: {
r = 0.0;
break;
}
case 161: {
r = 0.0;
break;
}
case 174: {
r = 1010.0;
break;
}
case 176: {
r = 33.0;
break;
}
case 178: {
r = 5.0;
break;
}
case 182: {
r = 3.0;
break;
}
case 210: {
r = 16.0;
break;
}
case 211: {
r = 16.0;
break;
}
case 212: {
r = 16.0;
break;
}
case 213: {
r = 16.0;
break;
}
case 214: {
r = 16.0;
break;
}
case 225: {
r = 6.0;
break;
}
case 226: {
r = 50.0;
break;
}
case 240: {
r = 50.0;
break;
}
case 241: {
r = 50.0;
break;
}
case 242: {
r = 50.0;
break;
}
case 243: {
r = 50.0;
break;
}
case 244: {
r = 50.0;
break;
}
case 250: {
r = 16.0;
break;
}
case 251: {
r = 16.0;
break;
}
case 252: {
r = 16.0;
break;
}
case 253: {
r = 16.0;
break;
}
case 254: {
r = 16.0;
break;
}
case 260: {
r = 50.0;
break;
}
case 261: {
r = 50.0;
break;
}
case 262: {
r = 50.0;
break;
}
case 263: {
r = 50.0;
break;
}
case 264: {
r = 50.0;
break;
}
}
return r;
}
public static double getTauxObtentionIntermediaire(final double bonus, final boolean b1, final boolean b2) {
double taux = bonus;
if (b1) {
if (bonus == 100.0) {
taux += 2.0 * getTauxObtentionIntermediaire(30.0, true, b2);
}
if (bonus == 30.0) {
taux += 2.0 * getTauxObtentionIntermediaire(10.0, !b2, b2);
}
if (bonus == 10.0) {
taux += 2.0 * getTauxObtentionIntermediaire(3.0, b2, b2);
} else if (bonus == 3.0) {
taux += 2.0 * getTauxObtentionIntermediaire(1.0, false, b2);
}
}
return taux;
}
public static int getMetierByMaging(final int idMaging) {
int mId = -1;
switch (idMaging) {
case 43: {
mId = 17;
break;
}
case 44: {
mId = 11;
break;
}
case 45: {
mId = 14;
break;
}
case 46: {
mId = 20;
break;
}
case 47: {
mId = 31;
break;
}
case 48: {
mId = 13;
break;
}
case 49: {
mId = 19;
break;
}
case 50: {
mId = 18;
break;
}
case 62: {
mId = 15;
break;
}
case 63: {
mId = 16;
break;
}
case 64: {
mId = 27;
break;
}
}
return mId;
}
public static int getTempleByClasse(final int classe) {
int temple = -1;
switch (classe) {
case 1: {
temple = 1554;
break;
}
case 2: {
temple = 1546;
break;
}
case 3: {
temple = 1470;
break;
}
case 4: {
temple = 6926;
break;
}
case 5: {
temple = 1469;
break;
}
case 6: {
temple = 1544;
break;
}
case 7: {
temple = 6928;
break;
}
case 8: {
temple = 1549;
break;
}
case 9: {
temple = 1558;
break;
}
case 10: {
temple = 1466;
break;
}
case 11: {
temple = 6949;
break;
}
case 12: {
temple = 8490;
break;
}
}
return temple;
}
public static class Drop {
private int template;
private int prospection;
private float taux;
private int max;
private int level;
private int action;
private int max_combat;
private String condition;
public Drop(final int template, final int prospection, final float taux, final int max, final int max_combat,
final int level, final int action, final String condition) {
this.template = template;
this.prospection = prospection;
this.taux = taux;
this.max = max;
this.setMax_combat(max_combat);
this.level = level;
this.action = action;
this.condition = condition;
}
public int getTemplateId() {
return this.template;
}
public int getProspection() {
return this.prospection;
}
public float getTaux() {
return this.taux;
}
public void setMax(final int max) {
this.max = max;
}
public int getMax() {
return this.max;
}
public int getLevel() {
return this.level;
}
public int getAction() {
return this.action;
}
public String getCondition() {
return this.condition;
}
public int getMax_combat() {
return this.max_combat;
}
public void setMax_combat(final int max_combat) {
this.max_combat = max_combat;
}
}
public static class SuperArea {
private int _id;
private ArrayList<Area> _areas;
public SuperArea(final int a_id) {
this._areas = new ArrayList<Area>();
this._id = a_id;
}
public void addArea(final Area A) {
this._areas.add(A);
}
public int get_id() {
return this._id;
}
}
public static class Area {
private int _id;
private SuperArea _superArea;
private String _name;
private ArrayList<SubArea> _subAreas;
private int _alignement;
public static int _bontas;
public static int _brakmars;
private int _Prisme;
static {
Area._bontas = 0;
Area._brakmars = 0;
}
public Area(final int id, final int superArea, final String nom) {
this._subAreas = new ArrayList<SubArea>();
this._Prisme = 0;
this._id = id;
this._name = nom;
this._superArea = World.getSuperArea(superArea);
if (this._superArea == null) {
World.addSuperArea(this._superArea = new SuperArea(superArea));
}
this._alignement = 0;
this._Prisme = 0;
}
public String get_name() {
return this._name;
}
public int get_id() {
return this._id;
}
public int getalignement() {
return this._alignement;
}
public int getPrismeID() {
return this._Prisme;
}
public void setPrismeID(final int Prisme) {
this._Prisme = Prisme;
}
public void setalignement(final int alignement) {
if (this._alignement == 1 && alignement == -1) {
--Area._bontas;
} else if (this._alignement == 2 && alignement == -1) {
--Area._brakmars;
} else if (this._alignement == -1 && alignement == 1) {
++Area._bontas;
} else if (this._alignement == -1 && alignement == 2) {
++Area._brakmars;
}
this._alignement = alignement;
}
public SuperArea get_superArea() {
return this._superArea;
}
public void addSubArea(final SubArea sa) {
this._subAreas.add(sa);
}
public ArrayList<SubArea> getSubAreas() {
return this._subAreas;
}
public ArrayList<org.cestra.map.Map> getMaps() {
final ArrayList<org.cestra.map.Map> maps = new ArrayList<org.cestra.map.Map>();
for (final SubArea SA : this._subAreas) {
maps.addAll(SA.getMaps());
}
return maps;
}
}
public static class SubArea {
private int id;
private Area area;
private int alignement;
private String name;
private ArrayList<org.cestra.map.Map> maps;
private boolean conquistable;
private int prism;
public static int bontas;
public static int brakmars;
static {
SubArea.bontas = 0;
SubArea.brakmars = 0;
}
public SubArea(final int id, final int area, final String name) {
this.maps = new ArrayList<org.cestra.map.Map>();
this.id = id;
this.name = name;
this.area = World.getArea(area);
}
public void setConquistable(final int conquistable) {
this.conquistable = (conquistable == 0);
}
public int getId() {
return this.id;
}
public Area getArea() {
return this.area;
}
public int getAlignement() {
return this.alignement;
}
public void setAlignement(final int alignement) {
if (this.alignement == 1 && alignement == -1) {
--SubArea.bontas;
} else if (this.alignement == 2 && alignement == -1) {
--SubArea.brakmars;
} else if (this.alignement == -1 && alignement == 1) {
++SubArea.bontas;
} else if (this.alignement == -1 && alignement == 2) {
++SubArea.brakmars;
}
this.alignement = alignement;
}
public String getName() {
return this.name;
}
public ArrayList<org.cestra.map.Map> getMaps() {
return this.maps;
}
public void addMap(final org.cestra.map.Map Map) {
this.maps.add(Map);
}
public boolean getConquistable() {
return this.conquistable;
}
public int getPrismId() {
return this.prism;
}
public void setPrismId(final int prism) {
this.prism = prism;
}
}
public static class Couple<L, R> {
public L first;
public R second;
public Couple(final L s, final R i) {
this.first = s;
this.second = i;
}
}
public static class ExpLevel {
public long perso;
public int metier;
public int dinde;
public int pvp;
public long guilde;
public long tourmenteurs;
public long bandits;
public ExpLevel(final long c, final int m, final int d, final int p, final long t, final long b) {
this.perso = c;
this.metier = m;
this.dinde = d;
this.pvp = p;
this.guilde = this.perso * 10L;
this.tourmenteurs = t;
this.bandits = b;
}
}
}
|
gpl-3.0
|
electricpandafishstudios/Spoon
|
game/modules/tome-1.4.1/data/zones/ancient-elven-ruins/zone.lua
|
2784
|
-- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2016 Nicolas Casalini
--
-- 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/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return {
name = "Elven Ruins",
level_range = {33,42},
level_scheme = "player",
max_level = 3,
decay = {300, 800},
actor_adjust_level = function(zone, level, e) return zone.base_level + e:getRankLevelAdjust() + level.level-1 + rng.range(-1,2) end,
width = 30, height = 30,
-- all_remembered = true,
-- all_lited = true,
persistent = "zone",
ambient_music = {"Anne_van_Schothorst_-_Passed_Tense.ogg", "weather/dungeon_base.ogg"},
min_material_level = 3,
max_material_level = 4,
generator = {
map = {
class = "engine.generator.map.TileSet",
tileset = {"3x3/base", "3x3/tunnel", "3x3/windy_tunnel"},
tunnel_chance = 100,
['.'] = "OLD_FLOOR",
['#'] = {"OLD_WALL","WALL","WALL","WALL","WALL"},
['+'] = "DOOR",
["'"] = "DOOR",
up = "UP",
down = "DOWN",
},
actor = {
class = "mod.class.generator.actor.Random",
nb_npc = {20, 20},
guardian = "GREATER_MUMMY_LORD",
},
object = {
class = "engine.generator.object.Random",
nb_object = {6, 9},
},
trap = {
class = "engine.generator.trap.Random",
nb_trap = {0, 0},
},
},
levels =
{
[1] = {
generator = { map = {
up = "UP_WILDERNESS",
}, },
},
[3] = {
width = 100, height = 100,
generator = {
map = {
tileset = {"5x5/base", "5x5/tunnel", "5x5/windy_tunnel", "5x5/crypt"},
start_tiles = {{tile="LONG_TUNNEL_82", x=8, y=0}},
tunnel_chance = 60,
force_last_stair = true,
down = "QUICK_EXIT",
},
actor = {
nb_npc = {20*3, 25*3},
},
object = {
nb_object = {6*3, 9*3},
},
trap = {
nb_trap = {0, 0},
},
},
},
},
post_process = function(level)
-- Place a lore note on each level
game:placeRandomLoreObject("NOTE"..level.level)
game.state:makeAmbientSounds(level, {
dungeon2={ chance=250, volume_mod=1, pitch=1, random_pos={rad=10}, files={"ambient/dungeon/dungeon1","ambient/dungeon/dungeon2","ambient/dungeon/dungeon3","ambient/dungeon/dungeon4","ambient/dungeon/dungeon5"}},
})
end,
}
|
gpl-3.0
|
fatedier/faframe
|
src/public/FaBaseTime.cpp
|
2789
|
/*************************************************************************
*
* Copyright (c) 2014, FateDier All rights reserved。
* 文件名称: FaBaseTime.cpp
* 描述: 日期时间相关的基类
* @author: 王成龙 <fatedier@gmail.com>
*
*************************************************************************/
#include "FaBaseTime.h"
int FaBaseTime::m_nMonthDayC[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int FaBaseTime::m_nMonthDayS[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/**构造及析构函数**/
//构造初始字符串
FaBaseTime::FaBaseTime()
{
m_strDateTime = "";
}
//根据字符串构造时间对象
FaBaseTime::FaBaseTime(const char* sDateTime)
{
m_strDateTime = sDateTime;
}
//根据字符串构造时间对象
FaBaseTime::FaBaseTime(const string& strDateTime)
{
m_strDateTime = strDateTime;
}
FaBaseTime::~FaBaseTime()
{
}
/**常用函数**/
//判断是否是闰年
bool FaBaseTime::isLeapYear(int year) const
{
if (year%100 == 0)
{
return (year%400 == 0);
}
else
{
return (year%4 == 0);
}
}
//获取指定年月的最后一天
int FaBaseTime::getLastDayOfMonth(int year, int month) const
{
//闰年
if (this->isLeapYear(year))
{
return m_nMonthDayS[month-1];
}
//非闰年
else
{
return m_nMonthDayC[month-1];
}
}
//返回日期时间字符串
string FaBaseTime::toString() const
{
return m_strDateTime;
}
/**内部调用函数**/
//检查8位字符的日期格式是否正确
void FaBaseTime::verifyDate(const string& strDate)
{
int year = atoi(strDate.substr(0, 4).c_str());
int month = atoi(strDate.substr(4, 2).c_str());
int day = atoi(strDate.substr(6, 2).c_str());
if (year <= 0 || year > 9999)
{
throw FaException(ERROR_TIME, "年份错误!");
}
if (month <= 0 || month > 12)
{
throw FaException(ERROR_TIME, "月份错误!");
}
if (day <= 0 || day > this->getLastDayOfMonth(year, month))
{
throw FaException(ERROR_TIME, "日(day)错误!");
}
}
//检查6位字符的时间格式是否正确
void FaBaseTime::verifyTime(const string& strTime)
{
int hour = atoi(strTime.substr(0, 2).c_str());
int minute = atoi(strTime.substr(2, 2).c_str());
int second = atoi(strTime.substr(4, 2).c_str());
if (hour < 0 || hour > 23)
{
throw FaException(ERROR_TIME, "小时错误!");
}
if (minute < 0 || minute > 59)
{
throw FaException(ERROR_TIME, "分钟错误!");
}
if (second < 0 || second > 59)
{
throw FaException(ERROR_TIME, "秒错误!");
}
}
|
gpl-3.0
|
Mtk112/CaloriesWatcher
|
app/src/main/java/Fragments/MetawearFragment.java
|
5750
|
package Fragments;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.example.miikka.calorieswatcher.R;
import com.mbientlab.metawear.MetaWearBoard;
import com.mbientlab.metawear.android.BtleService;
import com.mbientlab.metawear.module.AccelerometerBmi160;
import bolts.Continuation;
import bolts.Task;
/**
* Fragment builds connections to external sensor and starts monitoring time stood still
*/
public class MetawearFragment extends Fragment implements ServiceConnection, View.OnClickListener{
private final String MW_MAC_ADDRESS= "C1:A8:34:4D:BF:8E";
private MetaWearBoard board;
private AccelerometerBmi160 accelerometerBmi160;
final AccelerometerBmi160.SignificantMotionDataProducer significantMotion =
accelerometerBmi160.motion(AccelerometerBmi160.SignificantMotionDataProducer.class);
private Handler handler = new Handler();
Button button;
EditText editText;
int timer;
private BtleService.LocalBinder serviceBinder;
public MetawearFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_metawear, container, false);
getContext().getApplicationContext().bindService(new Intent(getContext(), BtleService.class),
this, Context.BIND_AUTO_CREATE);
editText = (EditText)v.findViewById(R.id.metawearEditText);
button = (Button)v.findViewById(R.id.startMetawear);
button.setOnClickListener(this);
return v;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceBinder = (BtleService.LocalBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
@Override
public void onDestroy(){
super.onDestroy();
getContext().getApplicationContext().unbindService(this);
}
/**
*connects to the metawear board
*/
public void retrieveBoard() {
final BluetoothManager btManager=
(BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
final BluetoothDevice remoteDevice=
btManager.getAdapter().getRemoteDevice(MW_MAC_ADDRESS);
// Create a MetaWear board object for the Bluetooth Device
board= serviceBinder.getMetaWearBoard(remoteDevice);
board.connectAsync().continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) throws Exception {
if (task.isFaulted()) {
Log.i("MainActivity", "Failed to connect");
} else {
Log.i("MainActivity", "Connected");
}
return null;
}
});
board.disconnectAsync().continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) throws Exception {
Log.i("MainActivity", "Disconnected");
return null;
}
});
board.onUnexpectedDisconnect(new MetaWearBoard.UnexpectedDisconnectHandler() {
@Override
public void disconnected(int status) {
Log.i("MainActivity", "Unexpectedly lost connection: " + status);
}
});
Log.i("MainActivity", "board model = " + board.getModel());
}
/**
*reads and parses the user set timer for standing still
*/
@Override
public void onClick(View view) {
switch (view.getId()){
case(R.id.startMetawear):
timer = Integer.parseInt(editText.getText().toString());
timer =timer*1000;
handler.postDelayed(runnable,timer);
break;
}
}
/**
*Should start the async task for monitoring the movement of the metawear sensor
* Not working yet.
*
*/
private Runnable runnable = new Runnable() {
@Override
public void run() {
/*significantMotion.configure()
.proofTime(AccelerometerBmi160.ProofTime.PT_1_S)
.skipTime(AccelerometerBmi160.SkipTime.ST_1_5_S)
.commit();
significantMotion.addRouteAsync(new RouteBuilder() {
@Override
public void configure(RouteComponent source) {
source.stream(new Subscriber() {
@Override
public void apply(Data data, Object... env) {
actual.set(data.bytes()[0]); }
});
}
}).continueWith(new Continuation<Route, Object>() {
@Override
public Void then(Task<Route> task)throws Exception{
significantMotion.start();
accelerometerBmi160.start();
return null;
}
});*/
handler.postDelayed(runnable,timer);
}
};
}
|
gpl-3.0
|
podondra/bt-spectraldl
|
notebooks/spectraldl/preprocessing.py
|
1684
|
import numpy as np
import imblearn.over_sampling
import sklearn.preprocessing
import astropy.convolution
START = 6519
END = 6732
def air2vacuum(air_waves):
'''Convert air wavelengths to vacuum wavelengths'''
# http://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion
vac_waves = np.zeros_like(air_waves)
for idx, wave in enumerate(air_waves):
s = (10 ** 4) / wave
n = 1 + 0.00008336624212083 + 0.02408926869968 / (130.1065924522 \
- s ** 2) + 0.0001599740894897 / (38.92568793293 - s ** 2)
vac_waves[idx] = wave * n
return vac_waves
def convolve_spectrum(fluxes, stddev=7):
'''Convolve spectrum with Gaussian 1D kernel.'''
kernel = astropy.convolution.Gaussian1DKernel(stddev=stddev)
return astropy.convolution.convolve(fluxes, kernel, boundary='extend')
def resample_spectrum(waves, fluxes, space=np.linspace(START, END, 140)):
return np.interp(space, waves, fluxes)
def smote_over_sample(X, y, *, n_classes=3):
'''Oversample the dataset
so that all classes has the same number of samples.'''
X_ = np.copy(X)
y_ = np.copy(y)
smote = imblearn.over_sampling.SMOTE()
for _ in range(n_classes - 1):
X_, y_ = smote.fit_sample(X_, y_)
return X_, y_
def scale_samples(X):
'''Scale each sample to have zero mean and unit sample.'''
return sklearn.preprocessing.scale(X, axis=1)
def scale_features(X_train, X_validation,
scaler=sklearn.preprocessing.StandardScaler()):
'''Fit scaler on X_train and tranform both X_train and X_validation.'''
X_tr = scaler.fit_transform(X_train)
X_val = scaler.transform(X_validation)
return X_tr, X_val
|
gpl-3.0
|
NikNitro/Python-iBeacon-Scan
|
sympy/geometry/ellipse.py
|
41821
|
"""Elliptical geometrical entities.
Contains
* Ellipse
* Circle
"""
from __future__ import division, print_function
from sympy.core import S, pi, sympify
from sympy.core.logic import fuzzy_bool
from sympy.core.numbers import Rational, oo
from sympy.core.compatibility import range
from sympy.core.symbol import Dummy
from sympy.simplify import simplify, trigsimp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.geometry.exceptions import GeometryError
from sympy.polys import DomainError, Poly, PolynomialError
from sympy.polys.polyutils import _not_a_coeff, _nsort
from sympy.solvers import solve
from sympy.utilities.iterables import uniq
from sympy.utilities.misc import filldedent
from sympy.utilities.decorator import doctest_depends_on
from .entity import GeometryEntity, GeometrySet
from .point import Point
from .line import Line, LinearEntity
from .util import _symbol, idiff
import random
class Ellipse(GeometrySet):
"""An elliptical GeometryEntity.
Parameters
==========
center : Point, optional
Default value is Point(0, 0)
hradius : number or SymPy expression, optional
vradius : number or SymPy expression, optional
eccentricity : number or SymPy expression, optional
Two of `hradius`, `vradius` and `eccentricity` must be supplied to
create an Ellipse. The third is derived from the two supplied.
Attributes
==========
center
hradius
vradius
area
circumference
eccentricity
periapsis
apoapsis
focus_distance
foci
Raises
======
GeometryError
When `hradius`, `vradius` and `eccentricity` are incorrectly supplied
as parameters.
TypeError
When `center` is not a Point.
See Also
========
Circle
Notes
-----
Constructed from a center and two radii, the first being the horizontal
radius (along the x-axis) and the second being the vertical radius (along
the y-axis).
When symbolic value for hradius and vradius are used, any calculation that
refers to the foci or the major or minor axis will assume that the ellipse
has its major radius on the x-axis. If this is not true then a manual
rotation is necessary.
Examples
========
>>> from sympy import Ellipse, Point, Rational
>>> e1 = Ellipse(Point(0, 0), 5, 1)
>>> e1.hradius, e1.vradius
(5, 1)
>>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5))
>>> e2
Ellipse(Point2D(3, 1), 3, 9/5)
Plotting:
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
>>> from sympy import Circle, Segment
>>> c1 = Circle(Point(0,0), 1)
>>> Plot(c1) # doctest: +SKIP
[0]: cos(t), sin(t), 'mode=parametric'
>>> p = Plot() # doctest: +SKIP
>>> p[0] = c1 # doctest: +SKIP
>>> radius = Segment(c1.center, c1.random_point())
>>> p[1] = radius # doctest: +SKIP
>>> p # doctest: +SKIP
[0]: cos(t), sin(t), 'mode=parametric'
[1]: t*cos(1.546086215036205357975518382),
t*sin(1.546086215036205357975518382), 'mode=parametric'
"""
def __contains__(self, o):
if isinstance(o, Point):
x = Dummy('x', real=True)
y = Dummy('y', real=True)
res = self.equation(x, y).subs({x: o.x, y: o.y})
return trigsimp(simplify(res)) is S.Zero
elif isinstance(o, Ellipse):
return self == o
return False
def __eq__(self, o):
"""Is the other GeometryEntity the same as this ellipse?"""
return isinstance(o, Ellipse) and (self.center == o.center and
self.hradius == o.hradius and
self.vradius == o.vradius)
def __hash__(self):
return super(Ellipse, self).__hash__()
def __new__(
cls, center=None, hradius=None, vradius=None, eccentricity=None,
**kwargs):
hradius = sympify(hradius)
vradius = sympify(vradius)
eccentricity = sympify(eccentricity)
if center is None:
center = Point(0, 0)
else:
center = Point(center, dim=2)
if len(center) != 2:
raise ValueError('The center of "{0}" must be a two dimensional point'.format(cls))
if len(list(filter(None, (hradius, vradius, eccentricity)))) != 2:
raise ValueError('Exactly two arguments of "hradius", '
'"vradius", and "eccentricity" must not be None."')
if eccentricity is not None:
if hradius is None:
hradius = vradius / sqrt(1 - eccentricity**2)
elif vradius is None:
vradius = hradius * sqrt(1 - eccentricity**2)
if hradius == vradius:
return Circle(center, hradius, **kwargs)
return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs)
def _do_ellipse_intersection(self, o):
"""The intersection of an ellipse with another ellipse or a circle.
Private helper method for `intersection`.
"""
x = Dummy('x', real=True)
y = Dummy('y', real=True)
seq = self.equation(x, y)
oeq = o.equation(x, y)
# TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain
result = solve([seq, oeq], x, y)
return [Point(*r) for r in list(uniq(result))]
def _do_line_intersection(self, o):
"""
Find the intersection of a LinearEntity and the ellipse.
All LinearEntities are treated as a line and filtered at
the end to see that they lie in o.
"""
hr_sq = self.hradius ** 2
vr_sq = self.vradius ** 2
lp = o.points
ldir = lp[1] - lp[0]
diff = lp[0] - self.center
mdir = Point(ldir.x/hr_sq, ldir.y/vr_sq)
mdiff = Point(diff.x/hr_sq, diff.y/vr_sq)
a = ldir.dot(mdir)
b = ldir.dot(mdiff)
c = diff.dot(mdiff) - 1
det = simplify(b*b - a*c)
result = []
if det == 0:
t = -b / a
result.append(lp[0] + (lp[1] - lp[0]) * t)
# Definite and potential symbolic intersections are allowed.
elif (det > 0) != False:
root = sqrt(det)
t_a = (-b - root) / a
t_b = (-b + root) / a
result.append( lp[0] + (lp[1] - lp[0]) * t_a )
result.append( lp[0] + (lp[1] - lp[0]) * t_b )
return [r for r in result if r in o]
def _svg(self, scale_factor=1., fill_color="#66cc99"):
"""Returns SVG ellipse element for the Ellipse.
Parameters
==========
scale_factor : float
Multiplication factor for the SVG stroke-width. Default is 1.
fill_color : str, optional
Hex string for fill color. Default is "#66cc99".
"""
from sympy.core.evalf import N
c = N(self.center)
h, v = N(self.hradius), N(self.vradius)
return (
'<ellipse fill="{1}" stroke="#555555" '
'stroke-width="{0}" opacity="0.6" cx="{2}" cy="{3}" rx="{4}" ry="{5}"/>'
).format(2. * scale_factor, fill_color, c.x, c.y, h, v)
@property
def ambient_dimension(self):
return 2
@property
def apoapsis(self):
"""The apoapsis of the ellipse.
The greatest distance between the focus and the contour.
Returns
=======
apoapsis : number
See Also
========
periapsis : Returns shortest distance between foci and contour
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.apoapsis
2*sqrt(2) + 3
"""
return self.major * (1 + self.eccentricity)
def arbitrary_point(self, parameter='t'):
"""A parameterized point on the ellipse.
Parameters
==========
parameter : str, optional
Default value is 't'.
Returns
=======
arbitrary_point : Point
Raises
======
ValueError
When `parameter` already appears in the functions.
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(0, 0), 3, 2)
>>> e1.arbitrary_point()
Point2D(3*cos(t), 2*sin(t))
"""
t = _symbol(parameter)
if t.name in (f.name for f in self.free_symbols):
raise ValueError(filldedent('Symbol %s already appears in object '
'and cannot be used as a parameter.' % t.name))
return Point(self.center.x + self.hradius*cos(t),
self.center.y + self.vradius*sin(t))
@property
def area(self):
"""The area of the ellipse.
Returns
=======
area : number
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.area
3*pi
"""
return simplify(S.Pi * self.hradius * self.vradius)
@property
def bounds(self):
"""Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
rectangle for the geometric figure.
"""
h, v = self.hradius, self.vradius
return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v)
@property
def center(self):
"""The center of the ellipse.
Returns
=======
center : number
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.center
Point2D(0, 0)
"""
return self.args[0]
@property
def circumference(self):
"""The circumference of the ellipse.
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.circumference
12*Integral(sqrt((-8*_x**2/9 + 1)/(-_x**2 + 1)), (_x, 0, 1))
"""
from sympy import Integral
if self.eccentricity == 1:
return 2*pi*self.hradius
else:
x = Dummy('x', real=True)
return 4*self.major*Integral(
sqrt((1 - (self.eccentricity*x)**2)/(1 - x**2)), (x, 0, 1))
@property
def eccentricity(self):
"""The eccentricity of the ellipse.
Returns
=======
eccentricity : number
Examples
========
>>> from sympy import Point, Ellipse, sqrt
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, sqrt(2))
>>> e1.eccentricity
sqrt(7)/3
"""
return self.focus_distance / self.major
def encloses_point(self, p):
"""
Return True if p is enclosed by (is inside of) self.
Notes
-----
Being on the border of self is considered False.
Parameters
==========
p : Point
Returns
=======
encloses_point : True, False or None
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Ellipse, S
>>> from sympy.abc import t
>>> e = Ellipse((0, 0), 3, 2)
>>> e.encloses_point((0, 0))
True
>>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half))
False
>>> e.encloses_point((4, 0))
False
"""
p = Point(p, dim=2)
if p in self:
return False
if len(self.foci) == 2:
# if the combined distance from the foci to p (h1 + h2) is less
# than the combined distance from the foci to the minor axis
# (which is the same as the major axis length) then p is inside
# the ellipse
h1, h2 = [f.distance(p) for f in self.foci]
test = 2*self.major - (h1 + h2)
else:
test = self.radius - self.center.distance(p)
return fuzzy_bool(test.is_positive)
def equation(self, x='x', y='y'):
"""The equation of the ellipse.
Parameters
==========
x : str, optional
Label for the x-axis. Default value is 'x'.
y : str, optional
Label for the y-axis. Default value is 'y'.
Returns
=======
equation : sympy expression
See Also
========
arbitrary_point : Returns parameterized point on ellipse
Examples
========
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(1, 0), 3, 2)
>>> e1.equation()
y**2/4 + (x/3 - 1/3)**2 - 1
"""
x = _symbol(x)
y = _symbol(y)
t1 = ((x - self.center.x) / self.hradius)**2
t2 = ((y - self.center.y) / self.vradius)**2
return t1 + t2 - 1
def evolute(self, x='x', y='y'):
"""The equation of evolute of the ellipse.
Parameters
==========
x : str, optional
Label for the x-axis. Default value is 'x'.
y : str, optional
Label for the y-axis. Default value is 'y'.
Returns
=======
equation : sympy expression
Examples
========
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(1, 0), 3, 2)
>>> e1.evolute()
2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3)
"""
if len(self.args) != 3:
raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.')
x = _symbol(x)
y = _symbol(y)
t1 = (self.hradius*(x - self.center.x))**Rational(2, 3)
t2 = (self.vradius*(y - self.center.y))**Rational(2, 3)
return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3)
@property
def foci(self):
"""The foci of the ellipse.
Notes
-----
The foci can only be calculated if the major/minor axes are known.
Raises
======
ValueError
When the major and minor axis cannot be determined.
See Also
========
sympy.geometry.point.Point
focus_distance : Returns the distance between focus and center
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.foci
(Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0))
"""
c = self.center
hr, vr = self.hradius, self.vradius
if hr == vr:
return (c, c)
# calculate focus distance manually, since focus_distance calls this
# routine
fd = sqrt(self.major**2 - self.minor**2)
if hr == self.minor:
# foci on the y-axis
return (c + Point(0, -fd), c + Point(0, fd))
elif hr == self.major:
# foci on the x-axis
return (c + Point(-fd, 0), c + Point(fd, 0))
@property
def focus_distance(self):
"""The focal distance of the ellipse.
The distance between the center and one focus.
Returns
=======
focus_distance : number
See Also
========
foci
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.focus_distance
2*sqrt(2)
"""
return Point.distance(self.center, self.foci[0])
@property
def hradius(self):
"""The horizontal radius of the ellipse.
Returns
=======
hradius : number
See Also
========
vradius, major, minor
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.hradius
3
"""
return self.args[1]
def intersection(self, o):
"""The intersection of this ellipse and another geometrical entity
`o`.
Parameters
==========
o : GeometryEntity
Returns
=======
intersection : list of GeometryEntity objects
Notes
-----
Currently supports intersections with Point, Line, Segment, Ray,
Circle and Ellipse types.
See Also
========
sympy.geometry.entity.GeometryEntity
Examples
========
>>> from sympy import Ellipse, Point, Line, sqrt
>>> e = Ellipse(Point(0, 0), 5, 7)
>>> e.intersection(Point(0, 0))
[]
>>> e.intersection(Point(5, 0))
[Point2D(5, 0)]
>>> e.intersection(Line(Point(0,0), Point(0, 1)))
[Point2D(0, -7), Point2D(0, 7)]
>>> e.intersection(Line(Point(5,0), Point(5, 1)))
[Point2D(5, 0)]
>>> e.intersection(Line(Point(6,0), Point(6, 1)))
[]
>>> e = Ellipse(Point(-1, 0), 4, 3)
>>> e.intersection(Ellipse(Point(1, 0), 4, 3))
[Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)]
>>> e.intersection(Ellipse(Point(5, 0), 4, 3))
[Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)]
>>> e.intersection(Ellipse(Point(100500, 0), 4, 3))
[]
>>> e.intersection(Ellipse(Point(0, 0), 3, 4))
[Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175), Point2D(3, 0)]
>>> e.intersection(Ellipse(Point(-1, 0), 3, 4))
[Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)]
"""
if isinstance(o, Point):
if o in self:
return [o]
else:
return []
elif isinstance(o, LinearEntity):
# LinearEntity may be a ray/segment, so check the points
# of intersection for coincidence first
return self._do_line_intersection(o)
elif isinstance(o, Ellipse):
if o == self:
return self
else:
return self._do_ellipse_intersection(o)
return o.intersection(self)
def is_tangent(self, o):
"""Is `o` tangent to the ellipse?
Parameters
==========
o : GeometryEntity
An Ellipse, LinearEntity or Polygon
Raises
======
NotImplementedError
When the wrong type of argument is supplied.
Returns
=======
is_tangent: boolean
True if o is tangent to the ellipse, False otherwise.
See Also
========
tangent_lines
Examples
========
>>> from sympy import Point, Ellipse, Line
>>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3)
>>> e1 = Ellipse(p0, 3, 2)
>>> l1 = Line(p1, p2)
>>> e1.is_tangent(l1)
True
"""
inter = None
if isinstance(o, Ellipse):
inter = self.intersection(o)
if isinstance(inter, Ellipse):
return False
return (inter is not None and len(inter) == 1
and isinstance(inter[0], Point))
elif isinstance(o, LinearEntity):
inter = self._do_line_intersection(o)
if inter is not None and len(inter) == 1:
return inter[0] in o
else:
return False
elif isinstance(o, Polygon):
c = 0
for seg in o.sides:
inter = self._do_line_intersection(seg)
c += len([True for point in inter if point in seg])
return c == 1
else:
raise NotImplementedError("Unknown argument type")
@property
def major(self):
"""Longer axis of the ellipse (if it can be determined) else hradius.
Returns
=======
major : number or expression
See Also
========
hradius, vradius, minor
Examples
========
>>> from sympy import Point, Ellipse, Symbol
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.major
3
>>> a = Symbol('a')
>>> b = Symbol('b')
>>> Ellipse(p1, a, b).major
a
>>> Ellipse(p1, b, a).major
b
>>> m = Symbol('m')
>>> M = m + 1
>>> Ellipse(p1, m, M).major
m + 1
"""
ab = self.args[1:3]
if len(ab) == 1:
return ab[0]
a, b = ab
o = b - a < 0
if o == True:
return a
elif o == False:
return b
return self.hradius
@property
def minor(self):
"""Shorter axis of the ellipse (if it can be determined) else vradius.
Returns
=======
minor : number or expression
See Also
========
hradius, vradius, major
Examples
========
>>> from sympy import Point, Ellipse, Symbol
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.minor
1
>>> a = Symbol('a')
>>> b = Symbol('b')
>>> Ellipse(p1, a, b).minor
b
>>> Ellipse(p1, b, a).minor
a
>>> m = Symbol('m')
>>> M = m + 1
>>> Ellipse(p1, m, M).minor
m
"""
ab = self.args[1:3]
if len(ab) == 1:
return ab[0]
a, b = ab
o = a - b < 0
if o == True:
return a
elif o == False:
return b
return self.vradius
def normal_lines(self, p, prec=None):
"""Normal lines between `p` and the ellipse.
Parameters
==========
p : Point
Returns
=======
normal_lines : list with 1, 2 or 4 Lines
Examples
========
>>> from sympy import Line, Point, Ellipse
>>> e = Ellipse((0, 0), 2, 3)
>>> c = e.center
>>> e.normal_lines(c + Point(1, 0))
[Line2D(Point2D(0, 0), Point2D(1, 0))]
>>> e.normal_lines(c)
[Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))]
Off-axis points require the solution of a quartic equation. This
often leads to very large expressions that may be of little practical
use. An approximate solution of `prec` digits can be obtained by
passing in the desired value:
>>> e.normal_lines((3, 3), prec=2)
[Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)),
Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))]
Whereas the above solution has an operation count of 12, the exact
solution has an operation count of 2020.
"""
p = Point(p, dim=2)
# XXX change True to something like self.angle == 0 if the arbitrarily
# rotated ellipse is introduced.
# https://github.com/sympy/sympy/issues/2815)
if True:
rv = []
if p.x == self.center.x:
rv.append(Line(self.center, slope=oo))
if p.y == self.center.y:
rv.append(Line(self.center, slope=0))
if rv:
# at these special orientations of p either 1 or 2 normals
# exist and we are done
return rv
# find the 4 normal points and construct lines through them with
# the corresponding slope
x, y = Dummy('x', real=True), Dummy('y', real=True)
eq = self.equation(x, y)
dydx = idiff(eq, y, x)
norm = -1/dydx
slope = Line(p, (x, y)).slope
seq = slope - norm
# TODO: Replace solve with solveset, when this line is tested
yis = solve(seq, y)[0]
xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
if len(xeq.free_symbols) == 1:
try:
# this is so much faster, it's worth a try
xsol = Poly(xeq, x).real_roots()
except (DomainError, PolynomialError, NotImplementedError):
# TODO: Replace solve with solveset, when these lines are tested
xsol = _nsort(solve(xeq, x), separated=True)[0]
points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol]
else:
raise NotImplementedError(
'intersections for the general ellipse are not supported')
slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
if prec is not None:
points = [pt.n(prec) for pt in points]
slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes]
return [Line(pt, slope=s) for pt,s in zip(points, slopes)]
@property
def periapsis(self):
"""The periapsis of the ellipse.
The shortest distance between the focus and the contour.
Returns
=======
periapsis : number
See Also
========
apoapsis : Returns greatest distance between focus and contour
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.periapsis
-2*sqrt(2) + 3
"""
return self.major * (1 - self.eccentricity)
def plot_interval(self, parameter='t'):
"""The plot interval for the default geometric plot of the Ellipse.
Parameters
==========
parameter : str, optional
Default value is 't'.
Returns
=======
plot_interval : list
[parameter, lower_bound, upper_bound]
Examples
========
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(0, 0), 3, 2)
>>> e1.plot_interval()
[t, -pi, pi]
"""
t = _symbol(parameter)
return [t, -S.Pi, S.Pi]
def random_point(self, seed=None):
"""A random point on the ellipse.
Returns
=======
point : Point
See Also
========
sympy.geometry.point.Point
arbitrary_point : Returns parameterized point on ellipse
Notes
-----
A random point may not appear to be on the ellipse, ie, `p in e` may
return False. This is because the coordinates of the point will be
floating point values, and when these values are substituted into the
equation for the ellipse the result may not be zero because of floating
point rounding error.
Examples
========
>>> from sympy import Point, Ellipse, Segment
>>> e1 = Ellipse(Point(0, 0), 3, 2)
>>> e1.random_point() # gives some random point
Point2D(...)
>>> p1 = e1.random_point(seed=0); p1.n(2)
Point2D(2.1, 1.4)
The random_point method assures that the point will test as being
in the ellipse:
>>> p1 in e1
True
Notes
=====
An arbitrary_point with a random value of t substituted into it may
not test as being on the ellipse because the expression tested that
a point is on the ellipse doesn't simplify to zero and doesn't evaluate
exactly to zero:
>>> from sympy.abc import t
>>> e1.arbitrary_point(t)
Point2D(3*cos(t), 2*sin(t))
>>> p2 = _.subs(t, 0.1)
>>> p2 in e1
False
Note that arbitrary_point routine does not take this approach. A value
for cos(t) and sin(t) (not t) is substituted into the arbitrary point.
There is a small chance that this will give a point that will not
test as being in the ellipse, so the process is repeated (up to 10
times) until a valid point is obtained.
"""
from sympy import sin, cos, Rational
t = _symbol('t')
x, y = self.arbitrary_point(t).args
# get a random value in [-1, 1) corresponding to cos(t)
# and confirm that it will test as being in the ellipse
if seed is not None:
rng = random.Random(seed)
else:
rng = random
for i in range(10): # should be enough?
# simplify this now or else the Float will turn s into a Float
c = 2*Rational(rng.random()) - 1
s = sqrt(1 - c**2)
p1 = Point(x.subs(cos(t), c), y.subs(sin(t), s))
if p1 in self:
return p1
raise GeometryError(
'Having problems generating a point in the ellipse.')
def reflect(self, line):
"""Override GeometryEntity.reflect since the radius
is not a GeometryEntity.
Examples
========
>>> from sympy import Circle, Line
>>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
Circle(Point2D(1, 0), -1)
>>> from sympy import Ellipse, Line, Point
>>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0)))
Traceback (most recent call last):
...
NotImplementedError:
General Ellipse is not supported but the equation of the reflected
Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 +
37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1
Notes
=====
Until the general ellipse (with no axis parallel to the x-axis) is
supported a NotImplemented error is raised and the equation whose
zeros define the rotated ellipse is given.
"""
from .util import _uniquely_named_symbol
if line.slope in (0, oo):
c = self.center
c = c.reflect(line)
return self.func(c, -self.hradius, self.vradius)
else:
x, y = [_uniquely_named_symbol(name, self, line) for name in 'xy']
expr = self.equation(x, y)
p = Point(x, y).reflect(line)
result = expr.subs(zip((x, y), p.args
), simultaneous=True)
raise NotImplementedError(filldedent(
'General Ellipse is not supported but the equation '
'of the reflected Ellipse is given by the zeros of: ' +
"f(%s, %s) = %s" % (str(x), str(y), str(result))))
def rotate(self, angle=0, pt=None):
"""Rotate ``angle`` radians counterclockwise about Point ``pt``.
Note: since the general ellipse is not supported, only rotations that
are integer multiples of pi/2 are allowed.
Examples
========
>>> from sympy import Ellipse, pi
>>> Ellipse((1, 0), 2, 1).rotate(pi/2)
Ellipse(Point2D(0, 1), 1, 2)
>>> Ellipse((1, 0), 2, 1).rotate(pi)
Ellipse(Point2D(-1, 0), 2, 1)
"""
if self.hradius == self.vradius:
return self.func(self.center.rotate(angle, pt), self.hradius)
if (angle/S.Pi).is_integer:
return super(Ellipse, self).rotate(angle, pt)
if (2*angle/S.Pi).is_integer:
return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius)
# XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes
raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.')
def scale(self, x=1, y=1, pt=None):
"""Override GeometryEntity.scale since it is the major and minor
axes which must be scaled and they are not GeometryEntities.
Examples
========
>>> from sympy import Ellipse
>>> Ellipse((0, 0), 2, 1).scale(2, 4)
Circle(Point2D(0, 0), 4)
>>> Ellipse((0, 0), 2, 1).scale(2)
Ellipse(Point2D(0, 0), 4, 1)
"""
c = self.center
if pt:
pt = Point(pt, dim=2)
return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
h = self.hradius
v = self.vradius
return self.func(c.scale(x, y), hradius=h*x, vradius=v*y)
@doctest_depends_on(modules=('pyglet',))
def tangent_lines(self, p):
"""Tangent lines between `p` and the ellipse.
If `p` is on the ellipse, returns the tangent line through point `p`.
Otherwise, returns the tangent line(s) from `p` to the ellipse, or
None if no tangent line is possible (e.g., `p` inside ellipse).
Parameters
==========
p : Point
Returns
=======
tangent_lines : list with 1 or 2 Lines
Raises
======
NotImplementedError
Can only find tangent lines for a point, `p`, on the ellipse.
See Also
========
sympy.geometry.point.Point, sympy.geometry.line.Line
Examples
========
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(0, 0), 3, 2)
>>> e1.tangent_lines(Point(3, 0))
[Line2D(Point2D(3, 0), Point2D(3, -12))]
>>> # This will plot an ellipse together with a tangent line.
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
>>> from sympy import Point, Ellipse
>>> e = Ellipse(Point(0,0), 3, 2)
>>> t = e.tangent_lines(e.random_point())
>>> p = Plot()
>>> p[0] = e # doctest: +SKIP
>>> p[1] = t # doctest: +SKIP
"""
p = Point(p, dim=2)
if self.encloses_point(p):
return []
if p in self:
delta = self.center - p
rise = (self.vradius ** 2)*delta.x
run = -(self.hradius ** 2)*delta.y
p2 = Point(simplify(p.x + run),
simplify(p.y + rise))
return [Line(p, p2)]
else:
if len(self.foci) == 2:
f1, f2 = self.foci
maj = self.hradius
test = (2*maj -
Point.distance(f1, p) -
Point.distance(f2, p))
else:
test = self.radius - Point.distance(self.center, p)
if test.is_number and test.is_positive:
return []
# else p is outside the ellipse or we can't tell. In case of the
# latter, the solutions returned will only be valid if
# the point is not inside the ellipse; if it is, nan will result.
x, y = Dummy('x'), Dummy('y')
eq = self.equation(x, y)
dydx = idiff(eq, y, x)
slope = Line(p, Point(x, y)).slope
# TODO: Replace solve with solveset, when this line is tested
tangent_points = solve([slope - dydx, eq], [x, y])
# handle horizontal and vertical tangent lines
if len(tangent_points) == 1:
assert tangent_points[0][
0] == p.x or tangent_points[0][1] == p.y
return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))]
# others
return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
@property
def vradius(self):
"""The vertical radius of the ellipse.
Returns
=======
vradius : number
See Also
========
hradius, major, minor
Examples
========
>>> from sympy import Point, Ellipse
>>> p1 = Point(0, 0)
>>> e1 = Ellipse(p1, 3, 1)
>>> e1.vradius
1
"""
return self.args[2]
class Circle(Ellipse):
"""A circle in space.
Constructed simply from a center and a radius, or from three
non-collinear points.
Parameters
==========
center : Point
radius : number or sympy expression
points : sequence of three Points
Attributes
==========
radius (synonymous with hradius, vradius, major and minor)
circumference
equation
Raises
======
GeometryError
When trying to construct circle from three collinear points.
When trying to construct circle from incorrect parameters.
See Also
========
Ellipse, sympy.geometry.point.Point
Examples
========
>>> from sympy.geometry import Point, Circle
>>> # a circle constructed from a center and radius
>>> c1 = Circle(Point(0, 0), 5)
>>> c1.hradius, c1.vradius, c1.radius
(5, 5, 5)
>>> # a circle constructed from three points
>>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0))
>>> c2.hradius, c2.vradius, c2.radius, c2.center
(sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2))
"""
def __new__(cls, *args, **kwargs):
c, r = None, None
if len(args) == 3:
args = [Point(a, dim=2) for a in args]
if Point.is_collinear(*args):
raise GeometryError(
"Cannot construct a circle from three collinear points")
from .polygon import Triangle
t = Triangle(*args)
c = t.circumcenter
r = t.circumradius
elif len(args) == 2:
# Assume (center, radius) pair
c = Point(args[0], dim=2)
r = sympify(args[1])
if not (c is None or r is None):
return GeometryEntity.__new__(cls, c, r, **kwargs)
raise GeometryError("Circle.__new__ received unknown arguments")
@property
def circumference(self):
"""The circumference of the circle.
Returns
=======
circumference : number or SymPy expression
Examples
========
>>> from sympy import Point, Circle
>>> c1 = Circle(Point(3, 4), 6)
>>> c1.circumference
12*pi
"""
return 2 * S.Pi * self.radius
def equation(self, x='x', y='y'):
"""The equation of the circle.
Parameters
==========
x : str or Symbol, optional
Default value is 'x'.
y : str or Symbol, optional
Default value is 'y'.
Returns
=======
equation : SymPy expression
Examples
========
>>> from sympy import Point, Circle
>>> c1 = Circle(Point(0, 0), 5)
>>> c1.equation()
x**2 + y**2 - 25
"""
x = _symbol(x)
y = _symbol(y)
t1 = (x - self.center.x)**2
t2 = (y - self.center.y)**2
return t1 + t2 - self.major**2
def intersection(self, o):
"""The intersection of this circle with another geometrical entity.
Parameters
==========
o : GeometryEntity
Returns
=======
intersection : list of GeometryEntities
Examples
========
>>> from sympy import Point, Circle, Line, Ray
>>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0)
>>> p4 = Point(5, 0)
>>> c1 = Circle(p1, 5)
>>> c1.intersection(p2)
[]
>>> c1.intersection(p4)
[Point2D(5, 0)]
>>> c1.intersection(Ray(p1, p2))
[Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)]
>>> c1.intersection(Line(p2, p3))
[]
"""
return Ellipse.intersection(self, o)
@property
def radius(self):
"""The radius of the circle.
Returns
=======
radius : number or sympy expression
See Also
========
Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius
Examples
========
>>> from sympy import Point, Circle
>>> c1 = Circle(Point(3, 4), 6)
>>> c1.radius
6
"""
return self.args[1]
def reflect(self, line):
"""Override GeometryEntity.reflect since the radius
is not a GeometryEntity.
Examples
========
>>> from sympy import Circle, Line
>>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
Circle(Point2D(1, 0), -1)
"""
c = self.center
c = c.reflect(line)
return self.func(c, -self.radius)
def scale(self, x=1, y=1, pt=None):
"""Override GeometryEntity.scale since the radius
is not a GeometryEntity.
Examples
========
>>> from sympy import Circle
>>> Circle((0, 0), 1).scale(2, 2)
Circle(Point2D(0, 0), 2)
>>> Circle((0, 0), 1).scale(2, 4)
Ellipse(Point2D(0, 0), 2, 4)
"""
c = self.center
if pt:
pt = Point(pt, dim=2)
return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
c = c.scale(x, y)
x, y = [abs(i) for i in (x, y)]
if x == y:
return self.func(c, x*self.radius)
h = v = self.radius
return Ellipse(c, hradius=h*x, vradius=v*y)
@property
def vradius(self):
"""
This Ellipse property is an alias for the Circle's radius.
Whereas hradius, major and minor can use Ellipse's conventions,
the vradius does not exist for a circle. It is always a positive
value in order that the Circle, like Polygons, will have an
area that can be positive or negative as determined by the sign
of the hradius.
Examples
========
>>> from sympy import Point, Circle
>>> c1 = Circle(Point(3, 4), 6)
>>> c1.vradius
6
"""
return abs(self.radius)
from .polygon import Polygon
|
gpl-3.0
|
boecker-lab/sirius_frontend
|
sirius_gui/src/main/java/de/unijena/bioinf/sirius/gui/settings/GerneralSettingsPanel.java
|
3563
|
package de.unijena.bioinf.sirius.gui.settings;
/**
* Created by Markus Fleischauer (markus.fleischauer@gmail.com)
* as part of the sirius_frontend
* 07.10.16.
*/
import de.unijena.bioinf.fingerid.db.SearchableDatabases;
import de.unijena.bioinf.sirius.gui.io.FileChooserPanel;
import de.unijena.bioinf.sirius.gui.utils.TwoCloumnPanel;
import org.jdesktop.swingx.JXTitledSeparator;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Properties;
import java.util.Vector;
import static de.unijena.bioinf.sirius.gui.mainframe.MainFrame.MF;
/**
* @author Markus Fleischauer (markus.fleischauer@gmail.com)
*/
public class GerneralSettingsPanel extends TwoCloumnPanel implements SettingsPanel {
private Properties props;
final FileChooserPanel db;
final JComboBox<String> solver;
final SpinnerNumberModel treeTimeout;
public GerneralSettingsPanel(Properties properties) {
super();
this.props = properties;
add(new JXTitledSeparator("ILP solver"));
Vector<String> items = new Vector<>(Arrays.asList("gurobi,cplex,glpk", "gurobi,glpk", "glpk,gurobi", "gurobi", "cplex", "glpk"));
String selected = props.getProperty("de.unijena.bioinf.sirius.treebuilder");
if (!items.contains(selected))
items.add(selected);
solver = new JComboBox<>(items);
solver.setSelectedItem(selected);
solver.setToolTipText("Choose the allowed solvers and in which order they should be checked. Note that glpk is part of Sirius whereas the others not");
add(new JLabel("Allowed solvers:"), solver);
treeTimeout = createTimeoutModel();
add(new JLabel("Tree timeout (seconds):"), new JSpinner(treeTimeout));
add(new JXTitledSeparator("CSI:FingerID"));
String p = props.getProperty("de.unijena.bioinf.sirius.fingerID.cache");
db = new FileChooserPanel(p, JFileChooser.DIRECTORIES_ONLY);
db.setToolTipText("Specify the directory where CSI:FingerID should store the compound candidates.");
add(new JLabel("Database cache:"), db);
}
@Override
public void saveProperties() {
props.setProperty("de.unijena.bioinf.sirius.treebuilder", (String) solver.getSelectedItem());
props.setProperty("de.unijena.bioinf.sirius.treebuilder.timeout", treeTimeout.getNumber().toString());
final Path dir = Paths.get(db.getFilePath());
if (Files.isDirectory(dir)) {
props.setProperty("de.unijena.bioinf.sirius.fingerID.cache", dir.toAbsolutePath().toString());
new SwingWorker<Integer, String>() {
@Override
protected Integer doInBackground() throws Exception {
SearchableDatabases.invalidateCache();
MF.getCsiFingerId().refreshDatabaseCacheDir();
return 1;
}
}.execute();
} else {
LoggerFactory.getLogger(this.getClass()).warn("Specified path is not a directory (" + dir.toString() + "). Directory not Changed!");
}
}
private SpinnerNumberModel createTimeoutModel() {
String seconds = props.getProperty("de.unijena.bioinf.sirius.treebuilder.timeout", "1800");
SpinnerNumberModel model = new SpinnerNumberModel();
model.setValue(Integer.valueOf(seconds));
return model;
}
@Override
public String name() {
return "General";
}
}
|
gpl-3.0
|
SupaHam/SupaCommons
|
commons-bukkit/src/test/java/com/supaham/commons/bukkit/commands/FlagParserTest.java
|
5373
|
package com.supaham.commons.bukkit.commands;
import com.supaham.commons.bukkit.commands.flags.Flag;
import com.supaham.commons.bukkit.commands.flags.FlagParseResult;
import com.supaham.commons.bukkit.commands.flags.FlagParser;
import com.supaham.commons.bukkit.commands.flags.MissingFlagException;
import com.supaham.commons.bukkit.commands.flags.MissingFlagValueException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class FlagParserTest {
private static final String[] NO_ARGS = new String[0];
private FlagParser parser;
private Flag FOO_FLAG;
private Flag VAL_FOO_FLAG;
private Flag OPT_BAR_FLAG;
private Flag OPT_VAL_BAR_FLAG;
@Before
public void setUp() throws Exception {
parser = new FlagParser(FlagParser.SHORTHAND_PREFIX, FlagParser.LONGHAND_PREFIX);
FOO_FLAG = new Flag('f', "foo", false, false);
VAL_FOO_FLAG = new Flag('f', "foo", false, true);
OPT_BAR_FLAG = new Flag('b', "bar", true, false);
OPT_VAL_BAR_FLAG = new Flag('b', "bar", true, true);
}
@Test
public void testEmpty() throws Exception {
FlagParseResult result = parser.parse(NO_ARGS);
Assert.assertNotNull(result);
}
@Test
public void testNoFlags() throws Exception {
String[] args = {"some", "args"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 2);
Assert.assertEquals("some", result.getArgs()[0]);
Assert.assertEquals("args", result.getArgs()[1]);
}
@Test
public void testFooFlag() throws Exception {
parser.add(FOO_FLAG);
String[] args = {"-f"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 0);
}
@Test
public void testFooFlagWithNormalArg() throws Exception {
parser.add(FOO_FLAG);
String[] args = {"-f", "foo"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("foo", result.getArgs()[0]);
}
@Test
public void testFooValueFlag() throws Exception {
parser.add(VAL_FOO_FLAG);
String[] args = {"-f", "foo"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 0);
}
@Test
public void testFooValueFlagWithNormalArg() throws Exception {
parser.add(VAL_FOO_FLAG);
String[] args = {"-f", "foo", "bar"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("bar", result.getArgs()[0]);
}
@Test
public void testOptionalBarFlagAbsent() throws Exception {
parser.add(OPT_BAR_FLAG);
String[] args = {"bar"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("bar", result.getArgs()[0]);
}
@Test
public void testOptionalBarFlagPresent() throws Exception {
parser.add(OPT_BAR_FLAG);
String[] args = {"-b", "bar"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("bar", result.getArgs()[0]);
}
@Test
public void testOptionalBarValueFlagAbsent() throws Exception {
parser.add(OPT_VAL_BAR_FLAG);
String[] args = {"bar"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("bar", result.getArgs()[0]);
}
@Test
public void testOptionalBarValueFlagPresent() throws Exception {
parser.add(OPT_VAL_BAR_FLAG);
String[] args = {"-b", "bar"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 0);
Assert.assertEquals("bar", result.get('b'));
}
@Test
public void testOptionalBarValueFlagPresentWithNormalArg() throws Exception {
parser.add(OPT_VAL_BAR_FLAG);
String[] args = {"-b", "bar", "foo"};
FlagParseResult result = parser.parse(args);
Assert.assertNotNull(result);
Assert.assertTrue(result.getArgs().length == 1);
Assert.assertEquals("bar", result.get('b'));
Assert.assertEquals("foo", result.getArgs()[0]);
}
@Test(expected = Exception.class)
public void testNullArgs() throws Exception {
parser.parse(null);
}
@Test(expected = MissingFlagException.class)
public void testMissingFlag() throws Exception {
parser.add(FOO_FLAG);
FlagParseResult parse = parser.parse(NO_ARGS);
}
@Test(expected = MissingFlagException.class)
public void testMissingFlagForValueFlag() throws Exception {
parser.add(VAL_FOO_FLAG);
FlagParseResult parse = parser.parse(NO_ARGS);
}
@Test(expected = MissingFlagValueException.class)
public void testMissingFlagValue() throws Exception {
parser.add(VAL_FOO_FLAG);
String[] args = {"-f"};
FlagParseResult parse = parser.parse(args);
}
@Test(expected = MissingFlagValueException.class)
public void testMissingOptionalFlagValue() throws Exception {
parser.add(OPT_VAL_BAR_FLAG);
String[] args = {"-b"};
FlagParseResult parse = parser.parse(args);
}
}
|
gpl-3.0
|
farert/farert
|
db/scripts/jrfare_f.py
|
1302
|
#!python3.0.1
# -*- coding: utf-8 -*-
# f: JR北海道幹線
import sys
def fare(km):
if km < 40: # 1 to 3km
return 160
if km < 70: # 4 to 6km
return 200
if km < 101: # 7 to 10km
return 210
if (6000 < km): # 600km越えは40キロ刻み
c_km = (km - 1) // 400 * 400 + 200
elif (1000 < km) : # 100.1-600kmは20キロ刻み
c_km = (km - 1) // 200 * 200 + 100
elif (500 < km) : # 50.1-100kmは10キロ刻み
c_km = (km - 1) // 100 * 100 + 50
elif (100 < km) : # 10.1-50kmは5キロ刻み
c_km = (km - 1) // 50 * 50 + 30
else:
assert(False)
if (6000 < c_km):
fare = 1785 * 2000 + 1620 * 1000 + 1285 * 3000 + 705 * (c_km - 6000)
elif (3000 < c_km) :
fare = 1785 * 2000 + 1620 * 1000 + 1285 * (c_km - 3000)
elif 2000 < c_km :
fare = 1785 * 2000 + 1620 * (c_km - 2000)
else :
fare = 1785 * c_km
if (c_km <= 1000) : # 100km以下は切り上げ
# 1の位を切り上げ
fare = (fare + 9999) // 10000 * 10
else: # 100㎞越えは四捨五入
fare = (fare + 50000) // 100000 * 100
fare = fare + ((fare // 10 // 2) + 5) // 10 * 10 # tax = +5%, 四捨五入
return fare
yen_b = -1
for k in range(0, 35000):
yen = fare(k)
if yen_b != yen:
print("{0}\t{1}".format((k + 9)//10, yen))
yen_b = yen
|
gpl-3.0
|
romw/boincsentinels
|
bslclient/src/RPCSyncProjectStatistics.cpp
|
4566
|
// BOINC Sentinels.
// https://projects.romwnet.org/boincsentinels
// Copyright (C) 2009-2014 Rom Walton
//
// BOINC Sentinels 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.
//
// BOINC Sentinels 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 BOINC Sentinels. If not, see <http://www.gnu.org/licenses/>.
//
#include "stdwx.h"
#include "Instance.h"
#include "bslxml/bslXMLTypes.h"
#include "bslcommon/bslCommonTypes.h"
#include "bslclient/bslClient.h"
#include "ClientStateEvents.h"
#include "ClientStateTypes.h"
#include "ClientState.h"
#include "EventManager.h"
#include "RPCProtocol.h"
#include "RPCSyncProjectStatistics.h"
#define BSLXMLTAGHASH_PROJECTGROUPING \
0x97f08fa2
#define BSLXMLTAGHASH_MASTERURL \
0xda55ae25
IMPLEMENT_DYNAMIC_CLASS(CRPCSyncProjectStatistics, CRPCProtocol);
CRPCSyncProjectStatistics::CRPCSyncProjectStatistics():
CRPCProtocol(wxT("get_statistics"), sizeof(wxT("get_statistics")))
{
}
CRPCSyncProjectStatistics::~CRPCSyncProjectStatistics()
{
}
BSLERRCODE CRPCSyncProjectStatistics::ParseResponse(CHost* pHost, wxString& strResponse)
{
BSLERRCODE rc = BSLERR_SUCCESS;
CBSLXMLDocumentEx oDocument;
CBSLXMLElementEx oElement;
CBSLProjectStatistic bslProjectStatistic, bslProjectStatisticData;
CProject* pProject = NULL;
CProjectStatistic* pProjectStatistic = NULL;
std::vector<BSLHANDLE> oBulkAdd;
std::vector<BSLHANDLE> oBulkUpdate;
oDocument.SetDocument(strResponse);
oBulkAdd.reserve(GetEventManager()->GetOptimialQueueSize());
oBulkUpdate.reserve(GetEventManager()->GetOptimialQueueSize());
while (BSLXMLERR_SUCCESS == oDocument.GetNextElement(oElement))
{
if (BSLXMLTAGHASH_PROJECTGROUPING == oElement.GetNameHash())
{
while (BSLXMLERR_SUCCESS == oDocument.GetNextElement(oElement))
{
if (BSLXMLTAGHASH_PROJECTGROUPING == oElement.GetNameHash()) break;
if (BSLXMLTAGHASH_MASTERURL == oElement.GetNameHash())
{
pHost->FindProject(oElement.GetValueHash(), &pProject);
}
else if ((BSLXMLTAGHASH_PROJECTSTATISTIC == oElement.GetNameHash()) && pProject)
{
bslProjectStatistic.Clear();
// Parse data
bslProjectStatistic.ParseEx(oDocument);
// Setup known handles
bslProjectStatistic.SetHostHandle(pHost);
bslProjectStatistic.SetProjectHandle(pProject);
// Update existing record if it already exists
if (BSLERR_SUCCESS == pProject->FindProjectStatistic(bslProjectStatistic.GetTimestamp(), &pProjectStatistic, &bslProjectStatisticData))
{
// Add missing handles
bslProjectStatistic.SetProjectStatisticHandle(bslProjectStatisticData.GetProjectStatisticHandle());
bslProjectStatistic.SetData(bslProjectStatisticData.GetData());
// Only update if something has changed
if (BSLERR_SUCCESS == pProjectStatistic->Update(bslProjectStatistic))
{
oBulkUpdate.push_back(pProjectStatistic->GetProjectStatisticHandle());
}
}
else
{
pProjectStatistic = new CProjectStatistic(bslProjectStatistic);
pProject->AddProjectStatistic(pProjectStatistic);
oBulkAdd.push_back(pProjectStatistic->GetProjectStatisticHandle());
}
}
else if (!pProject)
{
rc = BSLERR_OBJECT_NOT_FOUND;
}
}
}
}
GetEventManager()->FireBulkEvent(wxEVT_BSLPROJECTSTATISTIC_BULKADD, pHost, oBulkAdd);
GetEventManager()->FireBulkEvent(wxEVT_BSLPROJECTSTATISTIC_BULKUPDATE, pHost, oBulkUpdate);
return rc;
}
|
gpl-3.0
|
xPJS811x/xmlsae
|
src/control/RichStatement.java
|
1061
|
package control;
import java.sql.SQLException;
import java.util.List;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.codecs.Codec;
import org.owasp.esapi.codecs.MySQLCodec;
import org.owasp.esapi.codecs.MySQLCodec.Mode;
public class RichStatement {
private static Codec codec;
private String query;
private List<String> params;
static {
codec = new MySQLCodec(Mode.STANDARD);
}
public RichStatement(String query) throws SQLException {
this.query = query;
this.params = new java.util.ArrayList<>();
}
public void setRaw(String raw) throws SQLException {
params.add(ESAPI.encoder().encodeForSQL(codec, raw));
}
public void setString(String val) throws SQLException {
params.add('"' + ESAPI.encoder().encodeForSQL(codec, val) + '"');
}
public void executeUpdate() throws SQLException {
for (String param : params) {
query = query.replaceFirst("\\?", param);
}
System.out.println(query);
DatabaseActor.getConnection().newPreparedStatement(query).executeUpdate();
}
}
|
gpl-3.0
|
mclintprojects/ideabag2
|
android/xamarin.android/ProgrammingIdeas/Activities/IdeaListActivity.cs
|
5922
|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using ProgrammingIdeas.Adapters;
using ProgrammingIdeas.Helpers;
using System.Collections.Generic;
using System.Linq;
using PopupMenu = Android.Support.V7.Widget.PopupMenu;
namespace ProgrammingIdeas.Activities
{
[Activity(Label = "ItemActivity", Theme = "@style/AppTheme")]
public class IdeaListActivity : BaseActivity, PopupMenu.IOnMenuItemClickListener
{
private RecyclerView recyclerView;
private RecyclerView.LayoutManager manager;
private IdeaListAdapter adapter;
private List<Category> allCategories = new List<Category>();
private List<Idea> ideasList;
private ProgressBar progressBar;
public override int LayoutResource => Resource.Layout.idealistactivity;
public override bool HomeAsUpEnabled => true;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
manager = new LinearLayoutManager(this);
recyclerView = FindViewById<RecyclerView>(Resource.Id.itemRecyclerView);
progressBar = FindViewById<ProgressBar>(Resource.Id.completedIdeasBar);
allCategories = Global.Categories;
progressBar.Max = allCategories[Global.CategoryScrollPosition].Items.Count;
SetupUI();
}
protected override void OnResume()
{
base.OnResume();
if (Global.RefreshBookmarks)
adapter.RefreshBookmarks();
adapter?.NotifyDataSetChanged(); // Highlights the last clicked idea
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.idea_list_menu, menu);
return base.OnCreateOptionsMenu(menu);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.sortIdeas:
var sortAnchor = FindViewById(Resource.Id.sortIdeas);
ShowSortPopup(sortAnchor);
return true;
}
return base.OnOptionsItemSelected(item);
}
private void ShowSortPopup(View sortAnchor)
{
var popup = new PopupMenu(this, sortAnchor);
popup.MenuInflater.Inflate(Resource.Menu.idea_sort_menu, popup.Menu);
popup.SetOnMenuItemClickListener(this);
popup.Show();
}
private void ShowProgress()
{
var completedCount = allCategories[Global.CategoryScrollPosition].Items.FindAll(x => x.State == Status.Done).Count;
progressBar.Progress = 0;
progressBar.IncrementProgressBy(completedCount);
}
private void SetupUI()
{
var title = Global.Categories[Global.CategoryScrollPosition].CategoryLbl;
ideasList = Global.Categories[Global.CategoryScrollPosition].Items;
Title = title;
recyclerView.SetLayoutManager(manager);
adapter = new IdeaListAdapter(ideasList);
adapter.ItemClick -= OnItemClick;
adapter.ItemClick += OnItemClick;
recyclerView.SetAdapter(adapter);
manager.ScrollToPosition(Global.IdeaScrollPosition);
adapter.StateClicked -= Adapter_StateClicked;
adapter.StateClicked += Adapter_StateClicked;
ShowProgress();
}
private void Adapter_StateClicked(string title, string state, int adapterPos)
{
if (ideasList != null && ideasList.Count != 0)
{
var changedItem = ideasList.ElementAt(adapterPos);
if (changedItem != null)
{
changedItem.State = state;
adapter.NotifyItemChanged(adapterPos);
ShowProgress();
}
}
}
protected override void OnPause()
{
DBSerializer.SerializeDBAsync(Global.IDEAS_PATH, allCategories);
base.OnPause();
}
protected override void OnDestroy()
{
base.OnDestroy();
// Resets position back to zero so the highlight shows at the top of the list anything we enter
Global.IdeaScrollPosition = 0;
}
private void OnItemClick(int position)
{
Global.IdeaScrollPosition = position;
StartActivity(new Intent(this, typeof(IdeaDetailsActivity)));
OverridePendingTransition(Resource.Animation.push_left_in, Resource.Animation.push_left_out);
}
public bool OnMenuItemClick(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.sortByName:
var sortedList = ideasList.OrderBy(x => x.Title).ToList();
ideasList.Clear();
ideasList.AddRange(sortedList);
adapter.NotifyDataSetChanged();
return true;
case Resource.Id.sortByDifficulty:
var sortedDiffList = ideasList.OrderBy(x => x.GetDifficultyId()).ToList();
ideasList.Clear();
ideasList.AddRange(sortedDiffList);
adapter.NotifyDataSetChanged();
return true;
case Resource.Id.sortByStatus:
var sortedStatusList = ideasList.OrderBy(x => x.GetStatusId()).ToList();
ideasList.Clear();
ideasList.AddRange(sortedStatusList);
adapter.NotifyDataSetChanged();
return true;
default:
return true;
}
}
}
}
|
gpl-3.0
|
eater2/oms
|
src/test/java/com/marek/utils/others/SolutionTest.java
|
940
|
package com.marek.utils.others;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
/**
* Created by marek.papis on 04.08.2016.
*/
public class SolutionTest {
private Solution solution = new Solution();
@Test
public void testGDC1() {
int[] arr = new int[]{1,2,33,4,2,1};
//int[] arr = new int[]{1,1};
int counter = 0;
Map m = new HashMap<Integer,Integer>();
for(int i : arr){
if(m.containsKey(i) )
m.put(i,(Integer)m.get(i)+1);
else
m.put(i,1);
//if((Integer)m.get(i) >=2)
// counter++;
}
for(Object k: m.values())
{
if((Integer)k>=2)
counter++;
}
System.out.println(m);
System.out.println(counter);
}
}
|
gpl-3.0
|
tvesalainen/util
|
util/src/main/java/org/vesalainen/util/Lists.java
|
12728
|
/*
* Copyright (C) 2016 Timo Vesalainen <timo.vesalainen@iki.fi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.util;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
/**
* @deprecated Renamed to CollectionHelp
* CollectionHelp class contains methods to construct often used lists
* @author Timo Vesalainen <timo.vesalainen@iki.fi>
*/
public class Lists
{
private static final ThreadLocal<Locale> threadLocale = new ThreadLocal<>();
private static final ThreadLocal<String> threadFormat = new ThreadLocal<>();
/**
* Set Format string and locale for calling thread. List items are formatted
* using these. It is good practice to call removeFormat after use.
* @param locale
* @see #removeFormat()
* @see java.lang.String#format(java.util.Locale, java.lang.String, java.lang.Object...)
*/
public static final void setFormat(String format, Locale locale)
{
threadFormat.set(format);
threadLocale.set(locale);
}
/**
* Remove format and locale set in setFormat method.
* @see #setFormat(java.lang.String, java.util.Locale)
*/
public static final void removeFormat()
{
threadFormat.remove();
threadLocale.remove();
}
private static String format(Object ob)
{
String format = threadFormat.get();
Locale locale = threadLocale.get();
if (format != null && locale != null)
{
return String.format(locale, format, ob);
}
else
{
return ob.toString();
}
}
/**
* Creates a list that is populated with items
* @param <T>
* @param items
* @return
*/
public static final <T> List<T> create(T... items)
{
List<T> list = new ArrayList<>();
Collections.addAll(list, items);
return list;
}
/**
* @deprecated Replace with Collections.addAll
* Populates collection with items
* @param <T>
* @param collection
* @param items
* @see java.util.Collections#addAll(java.util.Collection, java.lang.Object...)
*/
public static final <T> void populate(Collection<T> collection, T... items)
{
Collections.addAll(collection, items);
}
/**
* Removes items from collection
* @param <T>
* @param collection
* @param items
*/
public static final <T> void remove(Collection<T> collection, T... items)
{
for (T t : items)
{
collection.remove(t);
}
}
/**
* Returns collection items delimited
* @param delim
* @param collection
* @return
* @deprecated Use java.util.stream.Collectors.joining
* @see java.util.stream.Collectors#joining(java.lang.CharSequence)
*/
public static final String print(String delim, Collection<?> collection)
{
return print(null, delim, null, null, null, collection);
}
/**
* Returns collection items delimited with given strings. If any of delimiters
* is null, it is ignored.
* @param start Start
* @param delim Delimiter
* @param quotStart Start of quotation
* @param quotEnd End of quotation
* @param end End
* @param collection
* @return
* @deprecated Use java.util.stream.Collectors.joining
* @see java.util.stream.Collectors#joining(java.lang.CharSequence, java.lang.CharSequence, java.lang.CharSequence)
*/
public static final String print(String start, String delim, String quotStart, String quotEnd, String end, Collection<?> collection)
{
try
{
StringBuilder out = new StringBuilder();
print(out, start, delim, quotStart, quotEnd, end, collection);
return out.toString();
}
catch (IOException ex)
{
throw new IllegalArgumentException(ex);
}
}
/**
*
* @param out
* @param start
* @param delim
* @param quotStart
* @param quotEnd
* @param end
* @param collection
* @throws IOException
*/
public static final void print(Appendable out, String start, String delim, String quotStart, String quotEnd, String end, Collection<?> collection) throws IOException
{
append(start, out);
boolean first = true;
for (Object ob : collection)
{
if (!first)
{
append(delim, out);
}
else
{
first=false;
}
append(quotStart, out);
out.append(format(ob));
append(quotEnd, out);
}
append(end, out);
}
/**
* Returns array items delimited
* @param delim
* @param array
* @return
*/
public static final String print(String delim, Object... array)
{
return print(null, delim, null, null, null, array);
}
/**
* Returns array items delimited with given strings. If any of delimiters
* is null, it is ignored.
* @param start
* @param delim
* @param quotStart
* @param quotEnd
* @param end
* @param array
* @return
*/
public static final String print(String start, String delim, String quotStart, String quotEnd, String end, Object... array)
{
try
{
StringBuilder out = new StringBuilder();
print(out, start, delim, quotStart, quotEnd, end, array);
return out.toString();
}
catch (IOException ex)
{
throw new IllegalArgumentException(ex);
}
}
public static final void print(Appendable out, String start, String delim, String quotStart, String quotEnd, String end, Object... array) throws IOException
{
append(start, out);
boolean first = true;
for (Object ob : array)
{
if (!first)
{
append(delim, out);
}
else
{
first=false;
}
append(quotStart, out);
out.append(format(ob));
append(quotEnd, out);
}
append(end, out);
}
private static void append(String str, Appendable out) throws IOException
{
if (str != null)
{
out.append(str);
}
}
/**
* Returns true if list has equal items as array in same order.
* @param <T>
* @param list
* @param array
* @return
*/
public static <T> boolean equals(List<T> list, T... array)
{
if (list.size() != array.length)
{
return false;
}
int len = array.length;
for (int ii=0;ii<len;ii++)
{
if (!Objects.equals(list.get(ii), array[ii]))
{
return false;
}
}
return true;
}
/**
* Adds array members to list
* @param <T>
* @param list
* @param array
*/
public static <T> Collection<T> addAll(Collection<T> list, T... array)
{
for (T item : array)
{
list.add(item);
}
return list;
}
/**
* Add arrays members to list starting at index.
* <p>
* If list contains a,b,c,d and array 1,2,3. After addAll(2, list, array)
* list contains a,b,1,2,3,c,d
* @param <T>
* @param index
* @param list
* @param array
*/
public static <T> List<T> addAll(int index, List<T> list, T... array)
{
for (T item : array)
{
list.add(index++, item);
}
return list;
}
/**
* Converts Collection to array.
* @param <T>
* @param col
* @param cls
* @return
* @see java.util.Collection#toArray(T[])
*/
public static <T> T[] toArray(Collection<T> col, Class<T> cls)
{
T[] arr = (T[]) Array.newInstance(cls, col.size());
return col.toArray(arr);
}
/**
* Sort list using quick-sort algorithm using ForkJoinPool.
* <p>Note! This is experimental and is slower than other sorting methods!
* @param <T>
* @param list
* @param comparator
*/
public static final <T> void parallelQuickSort(List<T> list, Comparator<T> comparator)
{
ForkJoinPool pool = new ForkJoinPool();
QuickSorter sorter = new QuickSorter(list, 0, list.size()-1, comparator);
pool.invoke(sorter);
}
/**
* Sort list using quick-sort algorithm
* <p>Needs a big list to have any benefit to ArrayList.sort!
* @param <T>
* @param list
* @param comparator
* @see java.util.ArrayList#sort(java.util.Comparator)
*/
public static final <T> void quickSort(List<T> list, Comparator<T> comparator)
{
quickSort(list, 0, list.size()-1, comparator);
}
private static <T> void quickSort(List<T> list, int lo, int hi, Comparator<T> comparator)
{
if (lo < hi)
{
int p = partition(list, lo, hi, comparator);
quickSort(list, lo, p, comparator);
quickSort(list, p+1, hi, comparator);
}
}
private static <T> int partition(List<T> list, int lo, int hi, Comparator<T> comparator)
{
T pivot = list.get(lo);
int i = lo-1;
int j = hi+1;
while (true)
{
do
{
i++;
} while (compare(list.get(i), pivot, comparator) < 0);
do
{
j--;
} while (compare(list.get(j), pivot, comparator) > 0);
if (i >= j)
{
return j;
}
T swap = list.get(i);
list.set(i, list.get(j));
list.set(j, swap);
}
}
private static <T> int compare(T o1, T o2, Comparator<T> comparator)
{
if (comparator != null)
{
return comparator.compare(o1, o2);
}
else
{
return ((Comparable)o1).compareTo(o2);
}
}
private static class QuickSorter<T> extends RecursiveAction
{
private List<T> list;
private int lo;
private int hi;
private Comparator<T> comparator;
public QuickSorter(List<T> list, int lo, int hi, Comparator<T> comparator)
{
this.list = list;
this.lo = lo;
this.hi = hi;
this.comparator = comparator;
}
@Override
protected void compute()
{
if (lo < hi)
{
int p = partition(list, lo, hi, comparator);
List<ForkJoinTask> tasks = new ArrayList<>();
if (p-lo > 50)
{
tasks.add(new QuickSorter(list, lo, p, comparator));
}
else
{
quickSort(list, lo, p, comparator);
}
if (hi-p+1 > 50)
{
tasks.add(new QuickSorter(list, p+1, hi, comparator));
}
else
{
quickSort(list, p+1, hi, comparator);
}
invokeAll(tasks);
}
}
}
}
|
gpl-3.0
|
rukzuk/rukzuk
|
app/sets/rukzuk/rz_core/modules/rz_grid/assets/notlive/editMode.js
|
17050
|
define([
'jquery',
'CMS',
'rz_root/notlive/js/baseJsModule',
'rz_root/notlive/js/cssHelper',
'rz_root/notlive/js/breakpointHelper',
'rz_grid/notlive/gridHelper',
], function ($, CMS, JsModule, cssHelper, bpHelper, gridHelper) {
/**
* Returns a form value for a given breakpoint id respecting the
* inheritance logic of the formValues
*/
var getFormValue = bpHelper.getFormValue;
/**
* get definition of the grid for the current resolution
*/
var getGridDefinitionForCurrentResolution = function (unitData) {
var currentBreakpointId = CMS.getCurrentResolution();
return String(getFormValue(unitData, 'cssGridDefinition', currentBreakpointId));
};
/**
* set definition of the grid for the current resolution
*/
var setGridDefinitionForCurrentResolution = function (unitData, newGridDefinition) {
var currentBreakpointId = CMS.getCurrentResolution();
var gridDefinition = unitData.formValues.cssGridDefinition.value;
gridDefinition[currentBreakpointId] = newGridDefinition;
CMS.set(unitData.id, 'cssGridDefinition', gridDefinition);
};
/**
* enable visual interface; only if user has editing rights
*/
var enableVisualInterface = function (unitId, selectedUnitId) {
if (CMS.get(unitId).formValues.gridSize.editable) {
enableMarginMarker(unitId);
enableDrag(unitId, selectedUnitId);
}
};
/**
* disable visual interface
*/
var disableVisualInterface = function (unitId) {
disableDrag();
disableHeightDrag();
disableMarginMarker(unitId);
disableGridRaster(unitId);
};
// resize handles
var $resizeMarginLeft;
var $resizeMarginRight;
var $resizeWidth;
var $resizeHeight;
var $uiBlocker;
var $uiBlockerResizeHeight;
/**
* enable visual margin markers
*/
var enableMarginMarker = function (unitId) {
disableMarginMarker(unitId);
// inject margin marker
$('#' + unitId + ' > .gridElements > div').append('<span class="marker markerLeft"></span><span class="marker markerCenter"></span><span class="marker markerRight"></span>');
};
/**
* disable visual margin markers
*/
var disableMarginMarker = function (unitId) {
// remove margin marker
$('#' + unitId + ' > .gridElements > div > .marker').remove();
};
/**
* enable visual grid raster
*/
var enableGridRaster = function (unitId) {
disableGridRaster(unitId);
var formValues = CMS.get(unitId).formValues;
if (!formValues.gridSize.editable) {
return;
}
var gridRasterHtml = '<span class="gridRaster">';
for (var i = 0; i < formValues.gridSize.value; i++) {
gridRasterHtml += '<div></div>';
}
gridRasterHtml += '</span>';
// inject grid raster
$('#' + unitId).append(gridRasterHtml);
};
/**
* disable visual grid raster
*/
var disableGridRaster = function (unitId) {
// remove grid raster
$('#' + unitId + ' > .gridRaster').remove();
};
/**
* enable visual resize
*/
var enableDrag = function (unitId, selectedUnitId) {
disableDrag();
var unitData;
var gridDefinitionHelper;
var triggerWidth;
var windowWidth;
var activeColumnIndex;
$resizeMarginLeft = $('<span class="resizeMarginLeft"></span>');
$resizeMarginRight = $('<span class="resizeMarginRight"></span>');
$resizeWidth = $('<span class="resizeWidth"></span>');
$uiBlocker = $('<div class="uiBlocker"></div>');
var startDrag = function () {
unitData = CMS.get(unitId);
var gridDefinition = getGridDefinitionForCurrentResolution(unitData);
var gridSize = unitData.formValues.gridSize.value;
triggerWidth = $('#' + unitId).width() / gridSize;
windowWidth = $(window).width();
gridDefinitionHelper = gridHelper.create(gridDefinition, gridSize);
var $activeColumn = $(this).parent().parent();
activeColumnIndex = $('#' + unitId + ' > .gridElements > div').index($activeColumn);
$('body').append($uiBlocker);
};
var doDrag = function (what, deltaX) {
var delta = Math.round(deltaX / triggerWidth);
var dirty;
switch (what) {
case 'columnSize':
dirty = gridDefinitionHelper.dragColumnSize(activeColumnIndex, delta);
break;
case 'marginLeft':
dirty = gridDefinitionHelper.dragColumnMarginLeft(activeColumnIndex, delta);
break;
case 'marginRight':
dirty = gridDefinitionHelper.dragColumnMarginRight(activeColumnIndex, delta);
break;
}
if (dirty) {
setGridDefinitionForCurrentResolution(unitData, gridDefinitionHelper.serializeGridDefinition());
cssHelper.refreshCSS(unitId);
}
};
var endDrag = function () {
gridDefinitionHelper = null;
$uiBlocker.detach();
};
// drag for resizing column width
$resizeWidth
.drag('start', startDrag)
.drag(function (ev, dd) {
// increase deltaX when mouse is leaving the screen to allow grid elements to flow into next row
var deltaX = dd.deltaX;
if (dd.offsetX > windowWidth) {
deltaX += triggerWidth;
}
doDrag('columnSize', deltaX);
})
.drag('end', endDrag);
// drag for resizing offset left
$resizeMarginLeft
.drag('start', startDrag)
.drag(function (ev, dd) {
doDrag('marginLeft', dd.deltaX);
})
.drag('end', endDrag);
// drag for resizing offset right
$resizeMarginRight
.drag('start', startDrag)
.drag(function (ev, dd) {
doDrag('marginRight', dd.deltaX);
})
.drag('end', endDrag);
// inject resize handles
var $selectedUnitId = $('#' + selectedUnitId);
$selectedUnitId.find('~ .markerRight').append($resizeWidth);
$selectedUnitId.find('~ .markerCenter').append($resizeMarginLeft).append($resizeMarginRight);
};
/**
* enable visual height resize of whole grid
*/
var enableResizeHeight = function (unitId) {
disableHeightDrag();
var triggerHeight;
var minHeight;
$resizeHeight = $('<span class="resizeHeight"></span>');
$uiBlockerResizeHeight = $('<div class="uiBlocker uiBlockerResizeHeight"></div>');
var startDrag = function () {
var $unit = $('#' + unitId);
var unitHeight = $unit.height();
var unitWidth = $unit.width();
triggerHeight = unitWidth / 100;
minHeight = Math.round(unitHeight / unitWidth * 100);
$('body').append($uiBlockerResizeHeight);
};
var doDrag = function (deltaY, dd) {
var delta = Math.round(deltaY / triggerHeight);
CMS.set(unitId, 'cssMinHeight', (minHeight + delta) + '%');
cssHelper.refreshCSS(unitId);
};
var endDrag = function () {
$uiBlockerResizeHeight.detach();
};
// drag for resizing height
$resizeHeight
.drag('start', startDrag)
.drag(function (ev, dd) {
doDrag(dd.deltaY, dd);
})
.drag('end', endDrag);
// inject resize handles
$('#' + unitId).append($resizeHeight);
};
/**
* remove elements of height drag
*/
var disableHeightDrag = function () {
if ($resizeHeight) {
$resizeHeight.remove();
}
if ($uiBlockerResizeHeight) {
$uiBlockerResizeHeight.remove();
}
};
/**
* remove resize handles and listeners
*/
var disableDrag = function () {
if ($resizeMarginLeft) {
$resizeMarginLeft.remove();
}
if ($resizeMarginRight) {
$resizeMarginRight.remove();
}
if ($resizeWidth) {
$resizeWidth.remove();
}
if ($uiBlocker) {
$uiBlocker.remove();
}
};
/**
* Sync grid definition with child units for all resolutions
* Corrects the grid settings (column config) for changes of units (move, delete, add)
* Units will keep their settings if moved, added or removed
*
* @param {string} unitId - id of the grid
* @param {array} [childUnits] - list of unitIds of direct children (non recursive)
*/
var syncColumnsWithUnits = function (unitId, childUnits) {
var unitData = CMS.get(unitId);
if (!childUnits) {
childUnits = filterForRegularUnits(unitData.children);
}
var childUnitsInDom = [];
$('#' + unitId + ' > div > div > .isModule').each(function () {
childUnitsInDom.push(this.id);
});
var gridSize = unitData.formValues.gridSize.value;
var gridDefinitions = unitData.formValues.cssGridDefinition.value;
// for all resolutions
for (var resId in gridDefinitions) {
if (resId == 'type') {
continue;
}
var gridDefinition = gridDefinitions[resId].replace(/\n/g, ' ');
var gridDefinitionArray = gridDefinition.split(' ');
var columnTable = {};
/*jshint -W083 */
childUnitsInDom.forEach(function (childId, index) {
columnTable[childId] = gridDefinitionArray[index];
});
var newGridDefinition = '';
var lastChildWidth = gridSize;
for (var i = 0; i < childUnits.length; i++) {
var childId = childUnits[i];
if (columnTable[childId]) {
newGridDefinition = newGridDefinition + columnTable[childId] + ' ';
lastChildWidth = columnTable[childId];
} else {
newGridDefinition = newGridDefinition + lastChildWidth + ' ';
}
}
var gridDefinitionHelper = gridHelper.create(newGridDefinition, gridSize);
gridDefinitions[resId] = gridDefinitionHelper.serializeGridDefinition();
}
CMS.set(unitId, 'cssGridDefinition', gridDefinitions);
};
var isResolutionResetChange = function (key, config) {
return (config.key == key && !config.newValue[CMS.getCurrentResolution()]);
};
/**
* Fixes the gridDefinition if number of columns in gridDefinition is not equal to the number of child units.
* @param {string} unitId - id of the grid
*/
var fixGridDefinitionLength = function (unitId) {
var unitData = CMS.get(unitId);
var childUnits = filterForRegularUnits(unitData.children);
var gridSize = unitData.formValues.gridSize.value;
var gridDefinition = getGridDefinitionForCurrentResolution(unitData).replace(/\n/g, ' ');
var gridDefinitionArray = gridDefinition.split(' ');
if (childUnits.length != gridDefinitionArray.length) {
// rebuild gridDefinition
var newGridDefinition = '';
var j = 0;
for (var i = 1; i <= childUnits.length; i++) {
newGridDefinition = newGridDefinition + gridDefinitionArray[j] + ' ';
j++;
if (j == gridDefinitionArray.length) {
j = 0;
}
}
var gridDefinitionHelper = gridHelper.create(newGridDefinition, gridSize);
setGridDefinitionForCurrentResolution(unitData, gridDefinitionHelper.serializeGridDefinition());
}
};
/**
* Non recursive filter for regular (i. e. non-extension) units
* @param {array} unitIds - array of unit ids (string)
* @returns {array} - array of unitIs of units which are not based on an extension module (i.e. non-extension units)
*/
var filterForRegularUnits = function (unitIds) {
unitIds = unitIds || [];
return unitIds.filter(function (unitId) { return !CMS.getModule(CMS.get(unitId).moduleId).extensionModule; });
};
return JsModule.extend({
/** @protected */
onFormValueChange: function (eventData) {
// always validate grid definition & add/remove column buttons
if (['cssGridDefinition', 'gridSize'].indexOf(eventData.key) != -1) {
var unitId = eventData.unitId;
if (!isResolutionResetChange('cssGridDefinition', eventData)) {
var unitData = CMS.get(unitId);
var gridSize = unitData.formValues.gridSize.value;
var gridDefinition = getGridDefinitionForCurrentResolution(unitData);
var gridDefinitionHelper = gridHelper.create(gridDefinition, gridSize);
setGridDefinitionForCurrentResolution(unitData, gridDefinitionHelper.serializeGridDefinition());
}
syncColumnsWithUnits(unitId);
cssHelper.refreshCSS(unitId);
enableDrag(unitId);
if (eventData.key == 'gridSize') {
CMS.preventRendering(unitId);
enableGridRaster(unitId);
}
}
},
/** @protected */
onResolutionChange: function () {
var selectedUnit = CMS.getSelected(false);
if (selectedUnit.moduleId == 'rz_grid') {
enableDrag(selectedUnit.id);
}
},
/** @protected */
onUnitSelect: function (config) {
enableGridRaster(config.unitId);
enableMarginMarker(config.unitId);
enableResizeHeight(config.unitId);
},
/** @protected */
onUnitDeselect: function (config) {
disableVisualInterface(config.unitId);
},
/** @protected */
initUnit: function (gridUnitId) {
var selectedUnit = CMS.getSelected(false);
if (selectedUnit && selectedUnit.parentUnitId == gridUnitId) {
enableVisualInterface(gridUnitId, selectedUnit.id);
enableGridRaster(gridUnitId);
fixGridDefinitionLength(gridUnitId);
}
if (selectedUnit && selectedUnit.id === gridUnitId) {
enableGridRaster(gridUnitId);
enableMarginMarker(gridUnitId);
enableResizeHeight(gridUnitId);
fixGridDefinitionLength(gridUnitId);
}
// disable grid raster & visual interface if selected unit is a child of the grid
CMS.on('unitDeselect', function (config) {
var unitData = CMS.get(config.unitId, false);
if (unitData && unitData.parentUnitId == gridUnitId) {
disableVisualInterface(gridUnitId, config.unitId);
}
});
// enable grid raster & visual interface if selected unit is a child of the grid
CMS.on('unitSelect', function (config) {
var unitData = CMS.get(config.unitId, false);
if (unitData && unitData.parentUnitId == gridUnitId) {
enableVisualInterface(gridUnitId, config.unitId);
fixGridDefinitionLength(gridUnitId);
if (unitData.moduleId != 'rz_grid') {
enableGridRaster(gridUnitId);
}
}
});
// add listeners for children unit syncing
CMS.on('beforeMoveUnit', function (eventData) {
if (eventData.parentUnitId == gridUnitId) {
syncColumnsWithUnits(gridUnitId);
}
});
CMS.on('beforeRemoveUnit', function (removeUnitId) {
var removeUnitData = CMS.get(removeUnitId, false);
if (removeUnitData && removeUnitData.parentUnitId == gridUnitId) {
var parentUnitData = CMS.get(removeUnitData.parentUnitId, false);
var childUnits = parentUnitData.children;
childUnits.splice(childUnits.indexOf(removeUnitId), 1);
syncColumnsWithUnits(gridUnitId, filterForRegularUnits(childUnits));
}
});
CMS.on('beforeInsertUnit', function (eventData) {
if (eventData.parentUnitId == gridUnitId) {
syncColumnsWithUnits(gridUnitId);
}
});
}
});
});
|
gpl-3.0
|
gom3s/math4Kids
|
src/components/app/QuestionBasic.js
|
564
|
import { connect } from 'react-redux'
import React, { Component } from 'react';
class QuestionBasic extends Component {
render() {
return (
<div className="task" style={{ fontSize: '40px', padding: '15px'}}>
{ this.props.a } { this.props.operator } { this.props.b } =
</div>
)
}
}
const mapStateToProps = (state) => {
return {
a: state.math.a,
b: state.math.b,
operator: state.math.operator
}
}
export default connect(
mapStateToProps,
null
)(QuestionBasic)
|
gpl-3.0
|
ftisunpar/BlueTape
|
vendor/google/apiclient-services/src/Google/Service/Monitoring/Resource/ProjectsGroups.php
|
5815
|
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "groups" collection of methods.
* Typical usage is:
* <code>
* $monitoringService = new Google_Service_Monitoring(...);
* $groups = $monitoringService->groups;
* </code>
*/
class Google_Service_Monitoring_Resource_ProjectsGroups extends Google_Service_Resource
{
/**
* Creates a new group. (groups.create)
*
* @param string $name Required. The project in which to create the group. The
* format is: projects/[PROJECT_ID_OR_NUMBER]
* @param Google_Service_Monitoring_Group $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool validateOnly If true, validate this request but do not create
* the group.
* @return Google_Service_Monitoring_Group
*/
public function create($name, Google_Service_Monitoring_Group $postBody, $optParams = array())
{
$params = array('name' => $name, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Monitoring_Group");
}
/**
* Deletes an existing group. (groups.delete)
*
* @param string $name Required. The group to delete. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID]
* @param array $optParams Optional parameters.
*
* @opt_param bool recursive If this field is true, then the request means to
* delete a group with all its descendants. Otherwise, the request means to
* delete a group only when it has no descendants. The default value is false.
* @return Google_Service_Monitoring_MonitoringEmpty
*/
public function delete($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Monitoring_MonitoringEmpty");
}
/**
* Gets a single group. (groups.get)
*
* @param string $name Required. The group to retrieve. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID]
* @param array $optParams Optional parameters.
* @return Google_Service_Monitoring_Group
*/
public function get($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Monitoring_Group");
}
/**
* Lists the existing groups. (groups.listProjectsGroups)
*
* @param string $name Required. The project whose groups are to be listed. The
* format is: projects/[PROJECT_ID_OR_NUMBER]
* @param array $optParams Optional parameters.
*
* @opt_param string ancestorsOfGroup A group name. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Returns groups that are
* ancestors of the specified group. The groups are returned in order, starting
* with the immediate parent and ending with the most distant ancestor. If the
* specified group has no immediate parent, the results are empty.
* @opt_param string descendantsOfGroup A group name. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Returns the descendants of
* the specified group. This is a superset of the results returned by the
* children_of_group filter, and includes children-of-children, and so forth.
* @opt_param string childrenOfGroup A group name. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Returns groups whose
* parent_name field contains the group name. If no groups have this parent, the
* results are empty.
* @opt_param int pageSize A positive number that is the maximum number of
* results to return.
* @opt_param string pageToken If this field is not empty then it must contain
* the next_page_token value returned by a previous call to this method. Using
* this field causes the method to return additional results from the previous
* method call.
* @return Google_Service_Monitoring_ListGroupsResponse
*/
public function listProjectsGroups($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Monitoring_ListGroupsResponse");
}
/**
* Updates an existing group. You can change any group attributes except name.
* (groups.update)
*
* @param string $name Output only. The name of this group. The format is:
* projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] When creating a group, this
* field is ignored and a new name is created consisting of the project
* specified in the call to CreateGroup and a unique [GROUP_ID] that is
* generated automatically.
* @param Google_Service_Monitoring_Group $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool validateOnly If true, validate this request but do not update
* the existing group.
* @return Google_Service_Monitoring_Group
*/
public function update($name, Google_Service_Monitoring_Group $postBody, $optParams = array())
{
$params = array('name' => $name, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_Monitoring_Group");
}
}
|
gpl-3.0
|
nimesh158/ARDetection
|
ARToolKitPlus/src/MemoryManager.cpp
|
2479
|
/* ========================================================================
* PROJECT: ARToolKitPlus
* ========================================================================
* This work is based on the original ARToolKit developed by
* Hirokazu Kato
* Mark Billinghurst
* HITLab, University of Washington, Seattle
* http://www.hitl.washington.edu/artoolkit/
*
* Copyright of the derived and new portions of this work
* (C) 2006 Graz University of Technology
*
* This framework 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 framework 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 framework; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For further information please contact
* Dieter Schmalstieg
* <schmalstieg@icg.tu-graz.ac.at>
* Graz University of Technology,
* Institut for Computer Graphics and Vision,
* Inffeldgasse 16a, 8010 Graz, Austria.
* ========================================================================
** @author Daniel Wagner
*
* $Id: MemoryManager.cpp 164 2006-05-02 11:29:10Z daniel $
* @file
* ======================================================================== */
#include <ARToolKitPlus/MemoryManager.h>
#ifndef __APPLE__
#include <malloc.h>
#else
#include <stdlib.h>
#endif
namespace ARToolKitPlus
{
#ifndef _ARTKP_NO_MEMORYMANAGER_
MemoryManager* memManager = NULL;
ARTOOLKITPLUS_API void
setMemoryManager(MemoryManager* nManager)
{
memManager = nManager;
}
ARTOOLKITPLUS_API MemoryManager*
getMemoryManager()
{
return memManager;
}
#endif //_ARTKP_NO_MEMORYMANAGER_
void
artkp_Free(void* rawMemory)
{
if(!rawMemory)
return;
#ifndef _ARTKP_NO_MEMORYMANAGER_
if(memManager)
memManager->releaseMemory(rawMemory);
else
#endif //_ARTKP_NO_MEMORYMANAGER_
::free(rawMemory);
rawMemory = NULL;
}
} // namespace ARToolKitPlus
|
gpl-3.0
|
potty-dzmeia/db4o
|
src/db4oj/core/src/com/db4o/internal/references/HashcodeReferenceSystem.java
|
3725
|
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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 com.db4o.internal.references;
import com.db4o.*;
import com.db4o.foundation.*;
import com.db4o.internal.*;
/**
* @exclude
*/
public class HashcodeReferenceSystem implements ReferenceSystem {
private ObjectReference _hashCodeTree;
private ObjectReference _idTree;
public void addNewReference(ObjectReference ref){
addReference(ref);
}
public void addExistingReference(ObjectReference ref){
addReference(ref);
}
private void addReference(ObjectReference ref){
ref.ref_init();
idAdd(ref);
hashCodeAdd(ref);
}
public void commit() {
// do nothing
}
private void hashCodeAdd(ObjectReference ref){
if (Deploy.debug) {
Object obj = ref.getObject();
if (obj != null) {
ObjectReference existing = referenceForObject(obj);
if (existing != null) {
System.out.println("Duplicate alarm hc_Tree");
}
}
}
if(_hashCodeTree == null){
_hashCodeTree = ref;
return;
}
_hashCodeTree = _hashCodeTree.hc_add(ref);
}
private void idAdd(ObjectReference ref){
if(DTrace.enabled){
DTrace.ID_TREE_ADD.log(ref.getID());
}
if (Deploy.debug) {
ObjectReference existing = referenceForId(ref.getID());
if (existing != null) {
System.out.println("Duplicate alarm id_Tree:" + ref.getID());
}
}
if(_idTree == null){
_idTree = ref;
return;
}
_idTree = _idTree.id_add(ref);
}
public ObjectReference referenceForId(int id){
if(DTrace.enabled){
DTrace.GET_YAPOBJECT.log(id);
}
if(_idTree == null){
return null;
}
if(! ObjectReference.isValidId(id)){
return null;
}
return _idTree.id_find(id);
}
public ObjectReference referenceForObject(Object obj) {
if(_hashCodeTree == null){
return null;
}
return _hashCodeTree.hc_find(obj);
}
public void removeReference(ObjectReference ref) {
if(DTrace.enabled){
DTrace.REFERENCE_REMOVED.log(ref.getID());
}
if(_hashCodeTree != null){
_hashCodeTree = _hashCodeTree.hc_remove(ref);
}
if(_idTree != null){
_idTree = _idTree.id_remove(ref);
}
}
public void rollback() {
// do nothing
}
public void traverseReferences(final Visitor4 visitor) {
if(_hashCodeTree == null){
return;
}
_hashCodeTree.hc_traverse(visitor);
}
@Override
public String toString() {
final BooleanByRef found = new BooleanByRef();
final StringBuffer str = new StringBuffer("HashcodeReferenceSystem {");
traverseReferences(new Visitor4() {
public void visit(Object obj) {
if(found.value){
str.append(", ");
}
ObjectReference ref = (ObjectReference) obj;
str.append(ref.getID());
found.value = true;
}
});
str.append("}");
return str.toString();
}
public void discarded() {
// do nothing
}
}
|
gpl-3.0
|
krbaker/jmfs
|
src/tivo/mfs/inode/InodeIndataOutputStream.java
|
1308
|
package tivo.mfs.inode;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
// through-write, byte-array backed stream.
// ByteArrayOutputStream won't work because it does not write into specific buffer
public class InodeIndataOutputStream extends OutputStream {
private byte[] buf;
private int bufPtr = 0;
private byte[] singleByteBuffer = new byte[1];
public InodeIndataOutputStream( byte[] indata ) {
this.buf = indata;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
int toWrite = Math.min( buf.length - bufPtr, len );
System.arraycopy( b, off, buf, bufPtr, toWrite );
bufPtr += toWrite;
if( toWrite < len )
throw new EOFException( "End of inode" );
}
@Override
public void close() throws IOException {
buf = null;
singleByteBuffer = null;
}
@Override
public void flush() throws IOException {
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(int b) throws IOException {
singleByteBuffer[0] = (byte)b;
write( singleByteBuffer, 0, 1 );
}
@Override
protected void finalize() throws Throwable {
flush();
close();
super.finalize();
}
}
|
gpl-3.0
|
enati/tracker
|
src/org/opensourcephysics/cabrillo/tracker/ThumbnailDialog.java
|
18477
|
/*
* The tracker package defines a set of video/image analysis tools
* built on the Open Source Physics framework by Wolfgang Christian.
*
* Copyright (c) 2015 Douglas Brown
*
* Tracker 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.
*
* Tracker 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 Tracker; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA
* or view the license online at <http://www.gnu.org/copyleft/gpl.html>
*
* For additional Tracker information and documentation, please see
* <http://www.cabrillo.edu/~dbrown/tracker/>.
*/
package org.opensourcephysics.cabrillo.tracker;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.JTextComponent;
import org.opensourcephysics.controls.XML;
import org.opensourcephysics.media.core.VideoFileFilter;
import org.opensourcephysics.media.core.VideoIO;
import org.opensourcephysics.media.core.VideoType;
import org.opensourcephysics.tools.FontSizer;
import java.io.File;
/**
* A dialog for saving thumbnail images of a TrackerPanel.
*
* @author Douglas Brown
*/
public class ThumbnailDialog extends JDialog {
protected static ThumbnailDialog thumbnailDialog; // singleton
protected static String[] viewNames = new String[] {"WholeFrame", "MainView", "VideoOnly"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
protected static String[] formatNames = new String[] {"png", "jpg"}; //$NON-NLS-1$ //$NON-NLS-2$
protected static Dimension defaultSize = new Dimension(320, 240);
protected static VideoFileFilter[] fileFilters = new VideoFileFilter[formatNames.length];
protected static PropertyChangeListener fileChooserListener;
protected static JTextComponent chooserField;
protected static boolean settingsOnly;
// instance fields
protected TrackerPanel trackerPanel;
protected JButton saveAsButton, closeButton;
protected JComponent sizePanel, viewPanel, formatPanel;
protected JComboBox formatDropdown, viewDropdown, sizeDropdown;
protected DefaultComboBoxModel formatModel, viewModel;
protected AffineTransform transform = new AffineTransform();
protected BufferedImage sizedImage;
protected HashMap<Object, Dimension> sizes;
protected Dimension fullSize = new Dimension(), thumbSize;
protected boolean isRefreshing;
protected String savedFilePath;
protected JPanel buttonbar;
/**
* Returns the singleton ThumbnailDialog for a specified TrackerPanel.
*
* @param panel the TrackerPanel
* @param withSaveButton true to include the "Save As" button
* @return the ThumbnailDialog
*/
public static ThumbnailDialog getDialog(TrackerPanel panel, boolean withSaveButton) {
// create singleton if it does not yet exist
if (thumbnailDialog==null) {
thumbnailDialog = new ThumbnailDialog(panel);
fileChooserListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (chooserField!=null) {
VideoFileFilter filter = (VideoFileFilter)e.getNewValue();
final String ext = filter.getDefaultExtension();
Runnable runner = new Runnable() {
public void run() {
String name = XML.stripExtension(chooserField.getText())+"."+ext; //$NON-NLS-1$
chooserField.setText(name);
}
};
SwingUtilities.invokeLater(runner);
}
}
};
// set up file filters
for (int i=0; i<formatNames.length; i++) {
VideoType type = VideoIO.getVideoType(null, formatNames[i]);
for (VideoFileFilter filter: type.getFileFilters()) {
if (filter.getDefaultExtension().equals(formatNames[i])) {
fileFilters[i] = filter;
break;
}
}
}
// set up chooser field
JFileChooser chooser = TrackerIO.getChooser();
String temp = "untitled.tmp"; //$NON-NLS-1$
chooser.setSelectedFile(new File(temp));
chooserField = getTextComponent(chooser, temp);
chooser.setSelectedFile(new File("")); //$NON-NLS-1$
}
settingsOnly = !withSaveButton;
if (thumbnailDialog.trackerPanel != panel) {
thumbnailDialog.trackerPanel = panel;
}
thumbnailDialog.refreshGUI();
return thumbnailDialog;
}
/**
* Saves a thumbnail image of the current frame using the current dropdown choices.
*
* @param filePath the path to the target image file (may be null)
* @return the saved image file, or null if cancelled or failed
*/
public File saveThumbnail(String filePath) {
int i = formatDropdown.getSelectedIndex();
String format = formatNames[i];
if (filePath==null) {
JFileChooser chooser = TrackerIO.getChooser();
chooser.setAcceptAllFileFilterUsed(false);
for (FileFilter filter: chooser.getChoosableFileFilters())
chooser.removeChoosableFileFilter(filter);
for (VideoFileFilter filter: fileFilters) {
chooser.addChoosableFileFilter(filter);
}
chooser.setFileFilter(fileFilters[i]);
chooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, fileChooserListener);
chooser.setDialogTitle(TrackerRes.getString("ThumbnailDialog.Chooser.SaveThumbnail.Title")); //$NON-NLS-1$
String tabName = XML.stripExtension(trackerPanel.getTitle());
chooser.setSelectedFile(new File(tabName+"_thumbnail."+format)); //$NON-NLS-1$
File[] files = TrackerIO.getChooserFiles("save"); //$NON-NLS-1$
chooser.removePropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, fileChooserListener);
if (files==null || files.length==0)
return null;
filePath = files[0].getAbsolutePath();
VideoFileFilter selectedFilter = (VideoFileFilter)chooser.getFileFilter();
String ext = selectedFilter.getDefaultExtension();
setFormat(ext);
if (!selectedFilter.accept(files[0])) {
filePath = XML.stripExtension(filePath)+"."+ext; //$NON-NLS-1$
if (!TrackerIO.canWrite(new File(filePath))) return null;
}
}
if (XML.getExtension(filePath)==null)
filePath = XML.stripExtension(filePath)+"."+format; //$NON-NLS-1$
Dimension size = sizes.get(sizeDropdown.getSelectedItem());
BufferedImage thumb = getThumbnailImage(size);
File thumbnail = VideoIO.writeImageFile(thumb, filePath);
return thumbnail;
}
/**
* Gets a thumbnail image of the TrackerPanel.
*
* @return a BufferedImage
*/
public BufferedImage getThumbnail() {
Dimension size = sizes.get(sizeDropdown.getSelectedItem());
return getThumbnailImage(size);
}
/**
* Sets the image format (filename extension).
*
* @param format "png" or "jpg"
*/
public void setFormat(String format) {
for (int i=0; i<formatNames.length; i++) {
if (format!=null && formatNames[i].equals(format.toLowerCase())) {
formatDropdown.setSelectedIndex(i);
break;
}
}
}
/**
* Gets the image format (filename extension).
*
* @return "png" or "jpg"
*/
public String getFormat() {
return formatNames[formatDropdown.getSelectedIndex()];
}
//_____________________ private constructor and methods ____________________________
/**
* Constructs a ThumbnailDialog.
*
* @param panel a TrackerPanel to supply the images
*/
private ThumbnailDialog(TrackerPanel panel) {
super(panel.getTFrame(), true);
trackerPanel = panel;
setResizable(false);
createGUI();
refreshGUI();
// center dialog on the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dim.width - getBounds().width) / 2;
int y = (dim.height - getBounds().height) / 2;
setLocation(x, y);
}
/**
* Creates the visible components of this dialog.
*/
private void createGUI() {
JPanel contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
Box settingsPanel = Box.createVerticalBox();
settingsPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 0, 2));
contentPane.add(settingsPanel, BorderLayout.CENTER);
JPanel upper = new JPanel(new GridLayout(1, 1));
JPanel lower = new JPanel(new GridLayout(1, 2));
// size panel
sizes = new HashMap<Object, Dimension>();
sizePanel = Box.createVerticalBox();
sizeDropdown = new JComboBox();
sizePanel.add(sizeDropdown);
// view panel
viewPanel = Box.createVerticalBox();
viewModel = new DefaultComboBoxModel();
viewDropdown = new JComboBox(viewModel);
viewPanel.add(viewDropdown);
viewDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange()==ItemEvent.SELECTED) {
if (!isRefreshing)
refreshSizeDropdown();
}
}
});
// format panel
formatPanel = Box.createVerticalBox();
formatModel = new DefaultComboBoxModel();
formatDropdown = new JComboBox(formatModel);
formatPanel.add(formatDropdown);
// assemble
settingsPanel.add(upper);
settingsPanel.add(lower);
upper.add(viewPanel);
lower.add(sizePanel);
lower.add(formatPanel);
// buttons
saveAsButton = new JButton();
saveAsButton.setForeground(new Color(0, 0, 102));
saveAsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
saveThumbnail(null);
}
});
closeButton = new JButton();
closeButton.setForeground(new Color(0, 0, 102));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
firePropertyChange("accepted", null, null); //$NON-NLS-1$
}
});
// buttonbar
buttonbar = new JPanel();
contentPane.add(buttonbar, BorderLayout.SOUTH);
buttonbar.add(saveAsButton);
buttonbar.add(closeButton);
}
/**
* Refreshes the visible components of this dialog.
*/
protected void refreshGUI() {
// refresh strings
String resource = settingsOnly? "ThumbnailDialog.Settings.Title": "ThumbnailDialog.Title"; //$NON-NLS-1$ //$NON-NLS-2$
String title = TrackerRes.getString(resource);
setTitle(title);
// subpanel titled borders
title = TrackerRes.getString("ExportVideoDialog.Subtitle.Size"); //$NON-NLS-1$
Border space = BorderFactory.createEmptyBorder(0, 4, 6, 4);
Border titled = BorderFactory.createTitledBorder(title);
int fontLevel = FontSizer.getLevel();
FontSizer.setFonts(titled, fontLevel);
sizePanel.setBorder(BorderFactory.createCompoundBorder(titled, space));
title = TrackerRes.getString("ThumbnailDialog.Subtitle.Image"); //$NON-NLS-1$
titled = BorderFactory.createTitledBorder(title);
FontSizer.setFonts(titled, fontLevel);
viewPanel.setBorder(BorderFactory.createCompoundBorder(titled, space));
title = TrackerRes.getString("ExportVideoDialog.Subtitle.Format"); //$NON-NLS-1$
titled = BorderFactory.createTitledBorder(title);
FontSizer.setFonts(titled, fontLevel);
formatPanel.setBorder(BorderFactory.createCompoundBorder(titled, space));
// buttons
saveAsButton.setText(TrackerRes.getString("ExportVideoDialog.Button.SaveAs")); //$NON-NLS-1$
if (settingsOnly) {
buttonbar.remove(saveAsButton);
closeButton.setText(TrackerRes.getString("Dialog.Button.OK")); //$NON-NLS-1$
}
else {
buttonbar.add(saveAsButton, 0);
closeButton.setText(TrackerRes.getString("Dialog.Button.Close")); //$NON-NLS-1$
}
// dropdowns
isRefreshing = true;
int index = formatDropdown.getSelectedIndex();
index = Math.max(index, 0);
formatModel.removeAllElements();
for (int i=0; i< formatNames.length; i++) {
String format = TrackerRes.getString("ThumbnailDialog.Format."+formatNames[i].toUpperCase()); //$NON-NLS-1$
formatModel.addElement(format);
}
formatDropdown.setSelectedIndex(index);
int lastIndex = trackerPanel.getVideo()==null? viewNames.length-2: viewNames.length-1;
index = Math.min(viewDropdown.getSelectedIndex(), lastIndex);
index = Math.max(index, 0);
viewModel.removeAllElements();
for (int i=0; i<=lastIndex; i++) {
String view = TrackerRes.getString("ThumbnailDialog.View."+viewNames[i]); //$NON-NLS-1$
viewModel.addElement(view);
}
viewDropdown.setSelectedIndex(index);
isRefreshing = false;
refreshSizeDropdown();
pack();
}
/**
* Refreshes the size dropdown.
*/
private void refreshSizeDropdown() {
isRefreshing = true;
Object selectedItem = sizeDropdown.getSelectedItem();
sizeDropdown.removeAllItems();
sizes.clear();
switch(viewDropdown.getSelectedIndex()) {
case 1: // video and graphics
Rectangle bounds = trackerPanel.getMat().mat;
fullSize.setSize(bounds.getWidth(), bounds.getHeight());
thumbSize = getFullThumbnailSize(fullSize);
break;
case 2: // video only
BufferedImage image = trackerPanel.getVideo().getImage();
fullSize.setSize(image.getWidth(), image.getHeight());
thumbSize = getFullThumbnailSize(fullSize);
break;
default: // entire frame
fullSize.setSize(trackerPanel.getTFrame().getSize());
thumbSize = getFullThumbnailSize(fullSize);
}
// add full-size item
if (isAcceptedDimension(fullSize.width, fullSize.height)) {
String s = fullSize.width+"x"+fullSize.height; //$NON-NLS-1$
sizeDropdown.addItem(s);
sizes.put(s, fullSize);
}
// add half-size item
Dimension dim = new Dimension(fullSize.width/2, fullSize.height/2);
if (dim.width>thumbSize.width && dim.height>thumbSize.height
&& isAcceptedDimension(dim.width, dim.height)) {
String s = dim.width+"x"+dim.height; //$NON-NLS-1$
sizeDropdown.addItem(s);
sizes.put(s, dim);
}
// add "full-thumb-size" item and make it the default
String s = thumbSize.width+"x"+thumbSize.height; //$NON-NLS-1$
Object defaultItem = s;
sizeDropdown.addItem(s);
sizes.put(s, thumbSize);
// add additional sizes if acceptable
double[] factor = new double[] {0.75, 0.5, 0.375, 0.25};
for (int i=0; i<factor.length; i++) {
dim = new Dimension((int)(thumbSize.width*factor[i]), (int)(thumbSize.height*factor[i]));
if (isAcceptedDimension(dim.width, dim.height)) {
s = dim.width+"x"+dim.height; //$NON-NLS-1$
sizeDropdown.addItem(s);
sizes.put(s, dim);
}
}
// select previous or default size
sizeDropdown.setSelectedItem(sizes.keySet().contains(selectedItem)? selectedItem: defaultItem);
isRefreshing = false;
}
/**
* Gets the "full-sized" thumbnail dimension for a specified image size.
*
* @param w the desired width
* @param h the desired height
* @return an acceptable dimension
*/
private Dimension getFullThumbnailSize(Dimension imageSize) {
// determine image resize factor
double widthFactor = defaultSize.getWidth()/imageSize.width;
double heightFactor = defaultSize.getHeight()/imageSize.height;
double factor = Math.min(widthFactor, heightFactor);
// determine default dimensions of thumbnail image
int w = (int)(imageSize.width*factor);
int h = (int)(imageSize.height*factor);
// return default size
return new Dimension(w, h);
}
/**
* Determines if a width and height are acceptable.
* Returns true if height greater than 60 or width greater than 80.
*
* @param w the width
* @param h the height
* @return true if accepted
*/
private boolean isAcceptedDimension(int w, int h) {
if (w>=80 || h>=60) return true;
return false;
}
/**
* Gets an image of a specified size from the TrackerPanel.
* The view dropdown determines which component is rendered.
*
* @param size the size
* @return a BufferedImage
*/
private BufferedImage getThumbnailImage(Dimension size) {
BufferedImage rawImage;
switch(viewDropdown.getSelectedIndex()) {
case 1: // video and graphics
rawImage = trackerPanel.renderMat();
break;
case 2: // video only
rawImage = trackerPanel.getVideo().getImage();
break;
default: // entire frame
TFrame frame = trackerPanel.getTFrame();
rawImage = (BufferedImage)frame.createImage(fullSize.width, fullSize.height);
Graphics2D g2 = rawImage.createGraphics();
frame.paint(g2);
g2.dispose();
}
return getResizedImage(rawImage, size);
}
/**
* Resizes a source image and returns the resized image.
*
* @param source the source image
* @param size the desired size
* @return a BufferedImage
*/
private BufferedImage getResizedImage(BufferedImage source, Dimension size) {
if (size.width==source.getWidth() && size.height==source.getHeight())
return source;
if (sizedImage==null
|| sizedImage.getWidth()!=size.width
|| sizedImage.getHeight()!=size.height) {
sizedImage = new BufferedImage(size.width, size.height, source.getType());
}
Graphics2D g2 = sizedImage.createGraphics();
// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(source, 0, 0, size.width, size.height,
0, 0, source.getWidth(), source.getHeight(), null);
g2.dispose();
return sizedImage;
}
private static JTextComponent getTextComponent(Container c, String toMatch) {
Component[] comps = c.getComponents();
for(int i = 0; i<comps.length; i++) {
if((comps[i] instanceof JTextComponent)&&toMatch.equals(((JTextComponent) comps[i]).getText())) {
return(JTextComponent) comps[i];
}
if(comps[i] instanceof Container) {
JTextComponent tc = getTextComponent((Container) comps[i], toMatch);
if(tc!=null) {
return tc;
}
}
}
return null;
}
}
|
gpl-3.0
|
simon-jouet/Marlin
|
Marlin/src/lcd/menu/menu_ubl.cpp
|
17794
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
//
// Unified Bed Leveling Menus
//
#include "../../inc/MarlinConfigPre.h"
#if HAS_LCD_MENU && ENABLED(AUTO_BED_LEVELING_UBL)
#include "menu.h"
#include "../../module/planner.h"
#include "../../module/configuration_store.h"
#include "../../feature/bedlevel/bedlevel.h"
static int16_t ubl_storage_slot = 0,
custom_hotend_temp = 190,
side_points = 3,
ubl_fillin_amount = 5,
ubl_height_amount = 1,
n_edit_pts = 1,
x_plot = 0,
y_plot = 0;
#if HAS_HEATED_BED
static int16_t custom_bed_temp = 50;
#endif
float mesh_edit_value, mesh_edit_accumulator; // We round mesh_edit_value to 2.5 decimal places. So we keep a
// separate value that doesn't lose precision.
static int16_t ubl_encoderPosition = 0;
static void _lcd_mesh_fine_tune(PGM_P msg) {
ui.defer_status_screen();
if (ubl.encoder_diff) {
ubl_encoderPosition = (ubl.encoder_diff > 0) ? 1 : -1;
ubl.encoder_diff = 0;
mesh_edit_accumulator += float(ubl_encoderPosition) * 0.005f * 0.5f;
mesh_edit_value = mesh_edit_accumulator;
ui.encoderPosition = 0;
ui.refresh(LCDVIEW_CALL_REDRAW_NEXT);
const int32_t rounded = (int32_t)(mesh_edit_value * 1000);
mesh_edit_value = float(rounded - (rounded % 5L)) / 1000;
}
if (ui.should_draw()) {
draw_edit_screen(msg, ftostr43sign(mesh_edit_value));
#if ENABLED(MESH_EDIT_GFX_OVERLAY)
_lcd_zoffset_overlay_gfx(mesh_edit_value);
#endif
}
}
void _lcd_mesh_edit_NOP() {
ui.defer_status_screen();
}
float lcd_mesh_edit() {
ui.goto_screen(_lcd_mesh_edit_NOP);
ui.refresh(LCDVIEW_CALL_REDRAW_NEXT);
_lcd_mesh_fine_tune(PSTR("Mesh Editor"));
return mesh_edit_value;
}
void lcd_mesh_edit_setup(const float &initial) {
mesh_edit_value = mesh_edit_accumulator = initial;
ui.goto_screen(_lcd_mesh_edit_NOP);
}
void _lcd_z_offset_edit() {
_lcd_mesh_fine_tune(PSTR("Z-Offset: "));
}
float lcd_z_offset_edit() {
ui.goto_screen(_lcd_z_offset_edit);
return mesh_edit_value;
}
void lcd_z_offset_edit_setup(const float &initial) {
mesh_edit_value = mesh_edit_accumulator = initial;
ui.goto_screen(_lcd_z_offset_edit);
}
/**
* UBL Build Custom Mesh Command
*/
void _lcd_ubl_build_custom_mesh() {
char ubl_lcd_gcode[20];
queue.inject_P(PSTR("G28"));
#if HAS_HEATED_BED
sprintf_P(ubl_lcd_gcode, PSTR("M190 S%i"), custom_bed_temp);
lcd_enqueue_one_now(ubl_lcd_gcode);
#endif
sprintf_P(ubl_lcd_gcode, PSTR("M109 S%i"), custom_hotend_temp);
lcd_enqueue_one_now(ubl_lcd_gcode);
queue.inject_P(PSTR("G29 P1"));
}
/**
* UBL Custom Mesh submenu
*
* << Build Mesh
* Hotend Temp: ---
* Bed Temp: ---
* Build Custom Mesh
*/
void _lcd_ubl_custom_mesh() {
START_MENU();
MENU_BACK(MSG_UBL_BUILD_MESH_MENU);
MENU_ITEM_EDIT(int3, MSG_UBL_HOTEND_TEMP_CUSTOM, &custom_hotend_temp, EXTRUDE_MINTEMP, (HEATER_0_MAXTEMP - 10));
#if HAS_HEATED_BED
MENU_ITEM_EDIT(int3, MSG_UBL_BED_TEMP_CUSTOM, &custom_bed_temp, BED_MINTEMP, (BED_MAXTEMP - 10));
#endif
MENU_ITEM(function, MSG_UBL_BUILD_CUSTOM_MESH, _lcd_ubl_build_custom_mesh);
END_MENU();
}
/**
* UBL Adjust Mesh Height Command
*/
void _lcd_ubl_adjust_height_cmd() {
char ubl_lcd_gcode[16];
const int ind = ubl_height_amount > 0 ? 9 : 10;
strcpy_P(ubl_lcd_gcode, PSTR("G29 P6 C -"));
sprintf_P(&ubl_lcd_gcode[ind], PSTR(".%i"), ABS(ubl_height_amount));
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Adjust Mesh Height submenu
*
* << Edit Mesh
* Height Amount: ---
* Adjust Mesh Height
* << Info Screen
*/
void _menu_ubl_height_adjust() {
START_MENU();
MENU_BACK(MSG_EDIT_MESH);
MENU_ITEM_EDIT_CALLBACK(int3, MSG_UBL_MESH_HEIGHT_AMOUNT, &ubl_height_amount, -9, 9, _lcd_ubl_adjust_height_cmd);
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
/**
* UBL Edit Mesh submenu
*
* << UBL Tools
* Fine Tune All
* Fine Tune Closest
* - Adjust Mesh Height >>
* << Info Screen
*/
void _lcd_ubl_edit_mesh() {
START_MENU();
MENU_BACK(MSG_UBL_TOOLS);
MENU_ITEM(gcode, MSG_UBL_FINE_TUNE_ALL, PSTR("G29 P4 R999 T"));
MENU_ITEM(gcode, MSG_UBL_FINE_TUNE_CLOSEST, PSTR("G29 P4 T"));
MENU_ITEM(submenu, MSG_UBL_MESH_HEIGHT_ADJUST, _menu_ubl_height_adjust);
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
/**
* UBL Validate Custom Mesh Command
*/
void _lcd_ubl_validate_custom_mesh() {
char ubl_lcd_gcode[24];
const int temp =
#if HAS_HEATED_BED
custom_bed_temp
#else
0
#endif
;
sprintf_P(ubl_lcd_gcode, PSTR("G26 C B%i H%i P"), temp, custom_hotend_temp);
lcd_enqueue_one_now_P(PSTR("G28"));
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Validate Mesh submenu
*
* << UBL Tools
* Mesh Validation with Material 1
* Mesh Validation with Material 2
* Validate Custom Mesh
* << Info Screen
*/
void _lcd_ubl_validate_mesh() {
START_MENU();
MENU_BACK(MSG_UBL_TOOLS);
#if HAS_HEATED_BED
MENU_ITEM(gcode, MSG_UBL_VALIDATE_MESH_M1, PSTR("G28\nG26 C B" STRINGIFY(PREHEAT_1_TEMP_BED) " H" STRINGIFY(PREHEAT_1_TEMP_HOTEND) " P"));
MENU_ITEM(gcode, MSG_UBL_VALIDATE_MESH_M2, PSTR("G28\nG26 C B" STRINGIFY(PREHEAT_2_TEMP_BED) " H" STRINGIFY(PREHEAT_2_TEMP_HOTEND) " P"));
#else
MENU_ITEM(gcode, MSG_UBL_VALIDATE_MESH_M1, PSTR("G28\nG26 C B0 H" STRINGIFY(PREHEAT_1_TEMP_HOTEND) " P"));
MENU_ITEM(gcode, MSG_UBL_VALIDATE_MESH_M2, PSTR("G28\nG26 C B0 H" STRINGIFY(PREHEAT_2_TEMP_HOTEND) " P"));
#endif
MENU_ITEM(function, MSG_UBL_VALIDATE_CUSTOM_MESH, _lcd_ubl_validate_custom_mesh);
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
/**
* UBL Grid Leveling Command
*/
void _lcd_ubl_grid_level_cmd() {
char ubl_lcd_gcode[12];
sprintf_P(ubl_lcd_gcode, PSTR("G29 J%i"), side_points);
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Grid Leveling submenu
*
* << UBL Tools
* Side points: ---
* Level Mesh
*/
void _lcd_ubl_grid_level() {
START_MENU();
MENU_BACK(MSG_UBL_TOOLS);
MENU_ITEM_EDIT(int3, MSG_UBL_SIDE_POINTS, &side_points, 2, 6);
MENU_ITEM(function, MSG_UBL_MESH_LEVEL, _lcd_ubl_grid_level_cmd);
END_MENU();
}
/**
* UBL Mesh Leveling submenu
*
* << UBL Tools
* 3-Point Mesh Leveling
* - Grid Mesh Leveling >>
* << Info Screen
*/
void _lcd_ubl_mesh_leveling() {
START_MENU();
MENU_BACK(MSG_UBL_TOOLS);
MENU_ITEM(gcode, MSG_UBL_3POINT_MESH_LEVELING, PSTR("G29 J0"));
MENU_ITEM(submenu, MSG_UBL_GRID_MESH_LEVELING, _lcd_ubl_grid_level);
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
/**
* UBL Fill-in Amount Mesh Command
*/
void _lcd_ubl_fillin_amount_cmd() {
char ubl_lcd_gcode[18];
sprintf_P(ubl_lcd_gcode, PSTR("G29 P3 R C.%i"), ubl_fillin_amount);
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Fill-in Mesh submenu
*
* << Build Mesh
* Fill-in Amount: ---
* Fill-in Mesh
* Smart Fill-in
* Manual Fill-in
* << Info Screen
*/
void _menu_ubl_fillin() {
START_MENU();
MENU_BACK(MSG_UBL_BUILD_MESH_MENU);
MENU_ITEM_EDIT_CALLBACK(int3, MSG_UBL_FILLIN_AMOUNT, &ubl_fillin_amount, 0, 9, _lcd_ubl_fillin_amount_cmd);
MENU_ITEM(gcode, MSG_UBL_SMART_FILLIN, PSTR("G29 P3 T0"));
MENU_ITEM(gcode, MSG_UBL_MANUAL_FILLIN, PSTR("G29 P2 B T0"));
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
void _lcd_ubl_invalidate() {
ubl.invalidate();
SERIAL_ECHOLNPGM("Mesh invalidated.");
}
/**
* UBL Build Mesh submenu
*
* << UBL Tools
* Build Mesh with Material 1
* Build Mesh with Material 2
* - Build Custom Mesh >>
* Build Cold Mesh
* - Fill-in Mesh >>
* Continue Bed Mesh
* Invalidate All
* Invalidate Closest
* << Info Screen
*/
void _lcd_ubl_build_mesh() {
START_MENU();
MENU_BACK(MSG_UBL_TOOLS);
#if HAS_HEATED_BED
MENU_ITEM(gcode, MSG_UBL_BUILD_MESH_M1, PSTR(
"G28\n"
"M190 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\n"
"M109 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND) "\n"
"G29 P1\n"
"M104 S0\n"
"M140 S0"
));
MENU_ITEM(gcode, MSG_UBL_BUILD_MESH_M2, PSTR(
"G28\n"
"M190 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\n"
"M109 S" STRINGIFY(PREHEAT_2_TEMP_HOTEND) "\n"
"G29 P1\n"
"M104 S0\n"
"M140 S0"
));
#else
MENU_ITEM(gcode, MSG_UBL_BUILD_MESH_M1, PSTR(
"G28\n"
"M109 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND) "\n"
"G29 P1\n"
"M104 S0"
));
MENU_ITEM(gcode, MSG_UBL_BUILD_MESH_M2, PSTR(
"G28\n"
"M109 S" STRINGIFY(PREHEAT_2_TEMP_HOTEND) "\n"
"G29 P1\n"
"M104 S0"
));
#endif
MENU_ITEM(submenu, MSG_UBL_BUILD_CUSTOM_MESH, _lcd_ubl_custom_mesh);
MENU_ITEM(gcode, MSG_UBL_BUILD_COLD_MESH, PSTR("G28\nG29 P1"));
MENU_ITEM(submenu, MSG_UBL_FILLIN_MESH, _menu_ubl_fillin);
MENU_ITEM(gcode, MSG_UBL_CONTINUE_MESH, PSTR("G29 P1 C"));
MENU_ITEM(function, MSG_UBL_INVALIDATE_ALL, _lcd_ubl_invalidate);
MENU_ITEM(gcode, MSG_UBL_INVALIDATE_CLOSEST, PSTR("G29 I"));
MENU_ITEM(function, MSG_WATCH, ui.return_to_status);
END_MENU();
}
/**
* UBL Load Mesh Command
*/
void _lcd_ubl_load_mesh_cmd() {
char ubl_lcd_gcode[25];
sprintf_P(ubl_lcd_gcode, PSTR("G29 L%i"), ubl_storage_slot);
lcd_enqueue_one_now(ubl_lcd_gcode);
sprintf_P(ubl_lcd_gcode, PSTR("M117 " MSG_MESH_LOADED), ubl_storage_slot);
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Save Mesh Command
*/
void _lcd_ubl_save_mesh_cmd() {
char ubl_lcd_gcode[25];
sprintf_P(ubl_lcd_gcode, PSTR("G29 S%i"), ubl_storage_slot);
lcd_enqueue_one_now(ubl_lcd_gcode);
sprintf_P(ubl_lcd_gcode, PSTR("M117 " MSG_MESH_SAVED), ubl_storage_slot);
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL Mesh Storage submenu
*
* << Unified Bed Leveling
* Memory Slot: ---
* Load Bed Mesh
* Save Bed Mesh
*/
void _lcd_ubl_storage_mesh() {
int16_t a = settings.calc_num_meshes();
START_MENU();
MENU_BACK(MSG_UBL_LEVEL_BED);
if (!WITHIN(ubl_storage_slot, 0, a - 1)) {
STATIC_ITEM(MSG_NO_STORAGE);
}
else {
MENU_ITEM_EDIT(int3, MSG_UBL_STORAGE_SLOT, &ubl_storage_slot, 0, a - 1);
MENU_ITEM(function, MSG_UBL_LOAD_MESH, _lcd_ubl_load_mesh_cmd);
MENU_ITEM(function, MSG_UBL_SAVE_MESH, _lcd_ubl_save_mesh_cmd);
}
END_MENU();
}
/**
* UBL LCD "radar" map homing
*/
void _lcd_ubl_output_map_lcd();
void _lcd_ubl_map_homing() {
ui.defer_status_screen();
_lcd_draw_homing();
if (all_axes_homed()) {
ubl.lcd_map_control = true; // Return to the map screen
ui.goto_screen(_lcd_ubl_output_map_lcd);
}
}
/**
* UBL LCD "radar" map point editing
*/
void _lcd_ubl_map_lcd_edit_cmd() {
char ubl_lcd_gcode[50], str[10], str2[10];
dtostrf(pgm_read_float(&ubl._mesh_index_to_xpos[x_plot]), 0, 2, str);
dtostrf(pgm_read_float(&ubl._mesh_index_to_ypos[y_plot]), 0, 2, str2);
snprintf_P(ubl_lcd_gcode, sizeof(ubl_lcd_gcode), PSTR("G29 P4 X%s Y%s R%i"), str, str2, n_edit_pts);
lcd_enqueue_one_now(ubl_lcd_gcode);
}
/**
* UBL LCD Map Movement
*/
void ubl_map_move_to_xy() {
REMEMBER(fr, feedrate_mm_s, MMM_TO_MMS(XY_PROBE_SPEED));
set_destination_from_current(); // sync destination at the start
#if ENABLED(DELTA)
if (current_position[Z_AXIS] > delta_clip_start_height) {
destination[Z_AXIS] = delta_clip_start_height;
prepare_move_to_destination();
}
#endif
destination[X_AXIS] = pgm_read_float(&ubl._mesh_index_to_xpos[x_plot]);
destination[Y_AXIS] = pgm_read_float(&ubl._mesh_index_to_ypos[y_plot]);
prepare_move_to_destination();
}
/**
* UBL LCD "radar" map
*/
void set_current_from_steppers_for_axis(const AxisEnum axis);
void sync_plan_position();
void _lcd_do_nothing() {}
void _lcd_hard_stop() {
const screenFunc_t old_screen = ui.currentScreen;
ui.currentScreen = _lcd_do_nothing;
planner.quick_stop();
ui.currentScreen = old_screen;
set_current_from_steppers_for_axis(ALL_AXES);
sync_plan_position();
}
void _lcd_ubl_output_map_lcd() {
static int16_t step_scaler = 0;
if (ui.use_click()) return _lcd_ubl_map_lcd_edit_cmd();
ui.encoder_direction_normal();
if (ui.encoderPosition) {
step_scaler += int16_t(ui.encoderPosition);
x_plot += step_scaler / (ENCODER_STEPS_PER_MENU_ITEM);
ui.encoderPosition = 0;
ui.refresh(LCDVIEW_REDRAW_NOW);
}
#if IS_KINEMATIC
#define KEEP_LOOPING true // Loop until a valid point is found
#else
#define KEEP_LOOPING false
#endif
do {
// Encoder to the right (++)
if (x_plot >= GRID_MAX_POINTS_X) { x_plot = 0; y_plot++; }
if (y_plot >= GRID_MAX_POINTS_Y) y_plot = 0;
// Encoder to the left (--)
if (x_plot < 0) { x_plot = GRID_MAX_POINTS_X - 1; y_plot--; }
if (y_plot < 0) y_plot = GRID_MAX_POINTS_Y - 1;
#if IS_KINEMATIC
const float x = pgm_read_float(&ubl._mesh_index_to_xpos[x_plot]),
y = pgm_read_float(&ubl._mesh_index_to_ypos[y_plot]);
if (position_is_reachable(x, y)) break; // Found a valid point
x_plot += (step_scaler < 0) ? -1 : 1;
#endif
} while(KEEP_LOOPING);
// Determine number of points to edit
#if IS_KINEMATIC
n_edit_pts = 9; //TODO: Delta accessible edit points
#else
const bool xc = WITHIN(x_plot, 1, GRID_MAX_POINTS_X - 2),
yc = WITHIN(y_plot, 1, GRID_MAX_POINTS_Y - 2);
n_edit_pts = yc ? (xc ? 9 : 6) : (xc ? 6 : 4); // Corners
#endif
// Cleanup
if (ABS(step_scaler) >= ENCODER_STEPS_PER_MENU_ITEM) step_scaler = 0;
if (ui.should_draw()) {
ui.ubl_plot(x_plot, y_plot);
if (planner.movesplanned()) // If the nozzle is already moving, cancel the move.
_lcd_hard_stop();
ubl_map_move_to_xy(); // Move to new location
}
}
/**
* UBL Homing before LCD map
*/
void _lcd_ubl_output_map_lcd_cmd() {
if (!all_axes_known()) {
set_all_unhomed();
queue.inject_P(PSTR("G28"));
}
ui.goto_screen(_lcd_ubl_map_homing);
}
/**
* UBL Output map submenu
*
* << Unified Bed Leveling
* Output for Host
* Output for CSV
* Off Printer Backup
* Output Mesh Map
*/
void _lcd_ubl_output_map() {
START_MENU();
MENU_BACK(MSG_UBL_LEVEL_BED);
MENU_ITEM(gcode, MSG_UBL_OUTPUT_MAP_HOST, PSTR("G29 T0"));
MENU_ITEM(gcode, MSG_UBL_OUTPUT_MAP_CSV, PSTR("G29 T1"));
MENU_ITEM(gcode, MSG_UBL_OUTPUT_MAP_BACKUP, PSTR("G29 S-1"));
MENU_ITEM(function, MSG_UBL_OUTPUT_MAP, _lcd_ubl_output_map_lcd_cmd);
END_MENU();
}
/**
* UBL Tools submenu
*
* << Unified Bed Leveling
* - Build Mesh >>
* - Validate Mesh >>
* - Edit Mesh >>
* - Mesh Leveling >>
*/
void _menu_ubl_tools() {
START_MENU();
MENU_BACK(MSG_UBL_LEVEL_BED);
MENU_ITEM(submenu, MSG_UBL_BUILD_MESH_MENU, _lcd_ubl_build_mesh);
MENU_ITEM(gcode, MSG_UBL_MANUAL_MESH, PSTR("G29 I999\nG29 P2 B T0"));
MENU_ITEM(submenu, MSG_UBL_VALIDATE_MESH_MENU, _lcd_ubl_validate_mesh);
MENU_ITEM(submenu, MSG_EDIT_MESH, _lcd_ubl_edit_mesh);
MENU_ITEM(submenu, MSG_UBL_MESH_LEVELING, _lcd_ubl_mesh_leveling);
END_MENU();
}
/**
* UBL Step-By-Step submenu
*
* << Unified Bed Leveling
* 1 Build Cold Mesh
* 2 Smart Fill-in
* - 3 Validate Mesh >>
* 4 Fine Tune All
* - 5 Validate Mesh >>
* 6 Fine Tune All
* 7 Save Bed Mesh
*/
void _lcd_ubl_step_by_step() {
START_MENU();
MENU_BACK(MSG_UBL_LEVEL_BED);
MENU_ITEM(gcode, "1 " MSG_UBL_BUILD_COLD_MESH, PSTR("G28\nG29 P1"));
MENU_ITEM(gcode, "2 " MSG_UBL_SMART_FILLIN, PSTR("G29 P3 T0"));
MENU_ITEM(submenu, "3 " MSG_UBL_VALIDATE_MESH_MENU, _lcd_ubl_validate_mesh);
MENU_ITEM(gcode, "4 " MSG_UBL_FINE_TUNE_ALL, PSTR("G29 P4 R999 T"));
MENU_ITEM(submenu, "5 " MSG_UBL_VALIDATE_MESH_MENU, _lcd_ubl_validate_mesh);
MENU_ITEM(gcode, "6 " MSG_UBL_FINE_TUNE_ALL, PSTR("G29 P4 R999 T"));
MENU_ITEM(function, "7 " MSG_UBL_SAVE_MESH, _lcd_ubl_save_mesh_cmd);
END_MENU();
}
/**
* UBL System submenu
*
* << Motion
* - Manually Build Mesh >>
* - Activate UBL >>
* - Deactivate UBL >>
* - Step-By-Step UBL >>
* - Mesh Storage >>
* - Output Map >>
* - UBL Tools >>
* - Output UBL Info >>
*/
void _lcd_ubl_level_bed() {
START_MENU();
MENU_BACK(MSG_MOTION);
if (planner.leveling_active)
MENU_ITEM(gcode, MSG_UBL_DEACTIVATE_MESH, PSTR("G29 D"));
else
MENU_ITEM(gcode, MSG_UBL_ACTIVATE_MESH, PSTR("G29 A"));
MENU_ITEM(submenu, MSG_UBL_STEP_BY_STEP_MENU, _lcd_ubl_step_by_step);
MENU_ITEM(function, MSG_UBL_MESH_EDIT, _lcd_ubl_output_map_lcd_cmd);
MENU_ITEM(submenu, MSG_UBL_STORAGE_MESH_MENU, _lcd_ubl_storage_mesh);
MENU_ITEM(submenu, MSG_UBL_OUTPUT_MAP, _lcd_ubl_output_map);
MENU_ITEM(submenu, MSG_UBL_TOOLS, _menu_ubl_tools);
MENU_ITEM(gcode, MSG_UBL_INFO_UBL, PSTR("G29 W"));
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float3, MSG_Z_FADE_HEIGHT, &lcd_z_fade_height, 0, 100, _lcd_set_z_fade_height);
#endif
END_MENU();
}
#endif // HAS_LCD_MENU && AUTO_BED_LEVELING_UBL
|
gpl-3.0
|
ikeman32/vetcoin
|
src/qt/locale/bitcoin_pl.ts
|
116164
|
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Vetcoin</source>
<translation>O Vetcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Vetcoin</b> version</source>
<translation>Wersja <b>Vetcoin</b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Oprogramowanie eksperymentalne.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Prawo autorskie</translation>
</message>
<message>
<location line="+0"/>
<source>The Vetcoin developers</source>
<translation>Deweloperzy Vetcoin</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Książka Adresowa</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Kliknij dwukrotnie, aby edytować adres lub etykietę</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Utwórz nowy adres</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Skopiuj aktualnie wybrany adres do schowka</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nowy Adres</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Vetcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Tutaj znajdują się twoje adresy Vetcoin do odbioru płatności. Możesz nadać oddzielne adresy dla każdego z wysyłających monety, żeby śledzić oddzielnie ich opłaty.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopiuj adres</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Pokaż Kod &QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Vetcoin address</source>
<translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Podpisz wiado&mość</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Usuń zaznaczony adres z listy</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksportuj dane z aktywnej karty do pliku</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Eksportuj</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Vetcoin address</source>
<translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Vetcoin.</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Zweryfikuj wiadomość</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Usuń</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Vetcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Tutaj znajdują się Twoje adresy Vetcoin do wysyłania płatności. Zawsze sprawdzaj ilość i adres odbiorcy przed wysyłką monet.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopiuj &Etykietę</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Edytuj</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Wyślij monety</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportuj książkę adresową</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Plik *.CSV (rozdzielany przecinkami)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Błąd podczas eksportowania</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Błąd zapisu do pliku %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etykieta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(bez etykiety)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Okienko Hasła</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Wpisz hasło</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nowe hasło</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Powtórz nowe hasło</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Wprowadź nowe hasło dla portfela.<br/>Proszę użyć hasła składającego się z <b>10 lub więcej losowych znaków</b> lub <b>ośmiu lub więcej słów</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Zaszyfruj portfel</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ta operacja wymaga hasła do portfela ażeby odblokować portfel.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Odblokuj portfel</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ta operacja wymaga hasła do portfela ażeby odszyfrować portfel.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Odszyfruj portfel</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Zmień hasło</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Podaj stare i nowe hasło do portfela.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Potwierdź szyfrowanie portfela</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Uwaga: Jeśli zaszyfrujesz swój portfel i zgubisz hasło to <b>STRACISZ WSZYSTKIE SWOJE LITECOIN'Y</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Jesteś pewien, że chcesz zaszyfrować swój portfel?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>WAŻNE: Wszystkie wykonane wcześniej kopie pliku portfela powinny być zamienione na nowe, szyfrowane pliki. Z powodów bezpieczeństwa, poprzednie kopie nieszyfrowanych plików portfela staną się bezużyteczne jak tylko zaczniesz korzystać z nowego, szyfrowanego portfela.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Uwaga: Klawisz Caps Lock jest włączony</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Portfel zaszyfrowany</translation>
</message>
<message>
<location line="-56"/>
<source>Vetcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your vetcoins from being stolen by malware infecting your computer.</source>
<translation>Program Vetcoin zamknie się aby dokończyć proces szyfrowania. Pamiętaj, że szyfrowanie portfela nie zabezpiecza w pełni Twoich vetcoinów przed kradzieżą przez wirusy lub trojany mogące zainfekować Twój komputer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Szyfrowanie portfela nie powiodło się</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Szyfrowanie portfela nie powiodło się z powodu wewnętrznego błędu. Twój portfel nie został zaszyfrowany.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Podane hasła nie są takie same.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Odblokowanie portfela nie powiodło się</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Wprowadzone hasło do odszyfrowania portfela jest niepoprawne.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Odszyfrowywanie portfela nie powiodło się</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Hasło portfela zostało pomyślnie zmienione.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Podpisz wiado&mość...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizacja z siecią...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>P&odsumowanie</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Pokazuje ogólny zarys portfela</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcje</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Przeglądaj historię transakcji</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edytuj listę zapisanych adresów i i etykiet</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Pokaż listę adresów do otrzymywania płatności</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Zakończ</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Zamknij program</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Vetcoin</source>
<translation>Pokaż informację o Vetcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>O &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Pokazuje informacje o Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opcje...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Zaszyfruj Portf&el</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Wykonaj kopię zapasową...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Zmień hasło...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importowanie bloków z dysku...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Ponowne indeksowanie bloków na dysku...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Vetcoin address</source>
<translation>Wyślij monety na adres Vetcoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Vetcoin</source>
<translation>Zmienia opcje konfiguracji vetcoina</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Zapasowy portfel w innej lokalizacji</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Zmień hasło użyte do szyfrowania portfela</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Okno debudowania</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Otwórz konsolę debugowania i diagnostyki</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Zweryfikuj wiadomość...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Vetcoin</source>
<translation>Vetcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Portfel</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>Wyślij</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>Odbie&rz</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adresy</translation>
</message>
<message>
<location line="+22"/>
<source>&About Vetcoin</source>
<translation>O Vetcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Pokaż / Ukryj</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Pokazuje lub ukrywa główne okno</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Szyfruj klucze prywatne, które są powiązane z twoim portfelem</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Vetcoin addresses to prove you own them</source>
<translation>Podpisz wiadomości swoim adresem aby udowodnić jego posiadanie</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Vetcoin addresses</source>
<translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Vetcoin.</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Plik</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>P&referencje</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>Pomo&c</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Pasek zakładek</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Vetcoin client</source>
<translation>Vetcoin klient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Vetcoin network</source>
<translation><numerusform>%n aktywne połączenie do sieci Vetcoin</numerusform><numerusform>%n aktywne połączenia do sieci Vetcoin</numerusform><numerusform>%n aktywnych połączeń do sieci Vetcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Przetworzono (w przybliżeniu) %1 z %2 bloków historii transakcji.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Pobrano %1 bloków z historią transakcji.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n godzina</numerusform><numerusform>%n godzin</numerusform><numerusform>%n godzin</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dzień</numerusform><numerusform>%n dni</numerusform><numerusform>%n dni</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n tydzień</numerusform><numerusform>%n tygodni</numerusform><numerusform>%n tygodni</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Ostatni otrzymany blok został wygenerowany %1 temu.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Błąd</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Ostrzeżenie</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informacja</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Transakcja przekracza limit. Możesz wysłać ją płacąc prowizję %1, która zostaje przekazana do węzłów, które ją prześlą i pomoże wspierać sieć Vetcoin. Czy chcesz zapłacić prowizję?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Aktualny</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Łapanie bloków...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Potwierdź prowizję transakcyjną</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transakcja wysłana</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transakcja przychodząca</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Kwota: %2
Typ: %3
Adres: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Obsługa URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Vetcoin address or malformed URI parameters.</source>
<translation>URI nie może zostać przetworzony! Prawdopodobnie błędny adres Vetcoin bądź nieprawidłowe parametry URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portfel jest <b>zaszyfrowany</b> i obecnie <b>niezablokowany</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portfel jest <b>zaszyfrowany</b> i obecnie <b>zablokowany</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Vetcoin can no longer continue safely and will quit.</source>
<translation>Błąd krytyczny. Vetcoin nie może kontynuować bezpiecznie więc zostanie zamknięty.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Sieć Alert</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Edytuj adres</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etykieta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Etykieta skojarzona z tym wpisem w książce adresowej</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Ten adres jest skojarzony z wpisem w książce adresowej. Może być zmodyfikowany jedynie dla adresów wysyłających.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nowy adres odbiorczy</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nowy adres wysyłania</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Edytuj adres odbioru</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Edytuj adres wysyłania</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Wprowadzony adres "%1" już istnieje w książce adresowej.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Vetcoin address.</source>
<translation>Wprowadzony adres "%1" nie jest poprawnym adresem Vetcoin.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nie można było odblokować portfela.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Tworzenie nowego klucza nie powiodło się.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Vetcoin-Qt</source>
<translation>Vetcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>wersja</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Użycie:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>opcje konsoli</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI opcje</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Ustaw Język, na przykład "pl_PL" (domyślnie: systemowy)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Uruchom zminimalizowany</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Pokazuj okno powitalne przy starcie (domyślnie: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opcje</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>Główne</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Płać prowizję za transakcje</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Vetcoin after logging in to the system.</source>
<translation>Automatycznie uruchamia Vetcoin po zalogowaniu do systemu.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Vetcoin on system login</source>
<translation>Uruchamiaj Vetcoin wraz z zalogowaniem do &systemu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Przywróć domyślne wszystkie ustawienia klienta.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Z&resetuj Ustawienia</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Sieć</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Vetcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatycznie otwiera port klienta Vetcoin na routerze. Ta opcja dzieła tylko jeśli twój router wspiera UPnP i jest ono włączone.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapuj port używając &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Vetcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Podłącz się do sieci Vetcoin przez proxy SOCKS (np. gdy łączysz się poprzez Tor'a)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Połącz się przez proxy SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP: </translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Adres IP serwera proxy (np. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port proxy (np. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>Wersja &SOCKS</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS wersja serwera proxy (np. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Okno</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Pokazuj tylko ikonę przy zegarku po zminimalizowaniu okna.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimalizuj do paska przy zegarku zamiast do paska zadań</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimalizuje zamiast zakończyć działanie programu przy zamykaniu okna. Kiedy ta opcja jest włączona, program zakończy działanie po wybieraniu Zamknij w menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimalizuj przy zamknięciu</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Wyświetlanie</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Język &Użytkownika:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Vetcoin.</source>
<translation>Można tu ustawić język interfejsu uzytkownika. Żeby ustawienie przyniosło skutek trzeba uruchomić ponownie Vetcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Jednostka pokazywana przy kwocie:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Wybierz podział jednostki pokazywany w interfejsie oraz podczas wysyłania monet</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Vetcoin addresses in the transaction list or not.</source>
<translation>Pokazuj adresy Vetcoin na liście transakcji.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Wyświetlaj adresy w liście transakcji</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Anuluj</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>Z&astosuj</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>domyślny</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Potwierdź reset ustawień</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Niektóre ustawienia mogą wymagać ponownego uruchomienia klienta, żeby zacząć działać.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Czy chcesz kontynuować?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Ostrzeżenie</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Vetcoin.</source>
<translation>To ustawienie zostanie zastosowane po restarcie Vetcoin</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Adres podanego proxy jest nieprawidłowy</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formularz</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Vetcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Wyświetlana informacja może być nieaktualna. Twój portfel synchronizuje się automatycznie z siecią vetcoin, zaraz po tym jak uzyskano połączenie, ale proces ten nie został jeszcze ukończony.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Niepotwierdzony:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Portfel</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Niedojrzały: </translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Balans wydobycia, który jeszcze nie dojrzał</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Ostatnie transakcje</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Twoje obecne saldo</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Suma transakcji, które nie zostały jeszcze potwierdzone, i które nie zostały wliczone do twojego obecnego salda</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>desynchronizacja</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start vetcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Okno Dialogowe Kodu QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Prośba o płatność</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Kwota:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etykieta:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Wiadomość:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Zapi&sz jako...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Błąd kodowania URI w Kodzie QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Podana ilość jest nieprawidłowa, proszę sprawdzić</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Wynikowy URI jest zbyt długi, spróbuj zmniejszyć tekst etykiety / wiadomości</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Zapisz Kod QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Obraz PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nazwa klienta</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>NIEDOSTĘPNE</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Wersja klienta</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informacje</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Używana wersja OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Czas uruchomienia</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Sieć</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Liczba połączeń</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>W sieci testowej</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Ciąg bloków</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktualna liczba bloków</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Szacowana ilość bloków</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Czas ostatniego bloku</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Otwórz</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Opcje konsoli</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Vetcoin-Qt help message to get a list with possible Vetcoin command-line options.</source>
<translation>Pokaż pomoc Vetcoin-Qt, aby zobaczyć listę wszystkich opcji linii poleceń</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Pokaż</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Data kompilacji</translation>
</message>
<message>
<location line="-104"/>
<source>Vetcoin - Debug window</source>
<translation>Vetcoin - Okno debudowania</translation>
</message>
<message>
<location line="+25"/>
<source>Vetcoin Core</source>
<translation>Rdzeń BitCoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Vetcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Wyczyść konsolę</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Vetcoin RPC console.</source>
<translation>Witam w konsoli Vetcoin RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Użyj strzałek do przewijania historii i <b>Ctrl-L</b> aby wyczyścić ekran</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Wpisz <b>help</b> aby uzyskać listę dostępnych komend</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Wyślij płatność</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Wyślij do wielu odbiorców na raz</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Dodaj Odbio&rce</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Wyczyść wszystkie pola transakcji</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Wyczyść &wszystko</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Potwierdź akcję wysyłania</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Wy&syłka</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> do %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Potwierdź wysyłanie monet</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Czy na pewno chcesz wysłać %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> i </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Adres odbiorcy jest nieprawidłowy, proszę poprawić</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Kwota do zapłacenia musi być większa od 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Kwota przekracza twoje saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Suma przekracza twoje saldo, gdy doliczymy %1 prowizji transakcyjnej.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Znaleziono powtórzony adres, można wysłać tylko raz na każdy adres podczas operacji wysyłania.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Błąd: Tworzenie transakcji zakończone niepowodzeniem!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Błąd: transakcja została odrzucona. Może się to zdarzyć, gdy monety z Twojego portfela zostały już wydane, na przykład gdy używałeś kopii wallet.dat i vetcoiny które tam wydałeś nie zostały jeszcze odjęte z portfela z którego teraz korzystasz.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formularz</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Zapłać dla:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adres, na który wysłasz płatności (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Wprowadź etykietę dla tego adresu by dodać go do książki adresowej</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etykieta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Wybierz adres z książki adresowej</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Wklej adres ze schowka</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Usuń tego odbiorce</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Vetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Wprowadź adres Vetcoin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Podpisy - Podpisz / zweryfikuj wiadomość</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>Podpi&sz Wiadomość</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Możesz podpisywać wiadomości swoimi adresami aby udowodnić, że jesteś ich właścicielem. Uważaj, aby nie podpisywać niczego co wzbudza Twoje podejrzenia, ponieważ ktoś może stosować phishing próbując nakłonić Cię do ich podpisania. Akceptuj i podpisuj tylko w pełni zrozumiałe komunikaty i wiadomości.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Wprowadź adres Vetcoin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Wybierz adres z książki kontaktowej</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Wklej adres ze schowka</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Wprowadź wiadomość, którą chcesz podpisać, tutaj</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Podpis</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopiuje aktualny podpis do schowka systemowego</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Vetcoin address</source>
<translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Podpisz Wiado&mość</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Zresetuj wszystkie pola podpisanej wiadomości</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Wyczyść &wszystko</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Zweryfikuj wiadomość</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Wprowadź adres Vetcoin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Vetcoin address</source>
<translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Vetcoin.</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Zweryfikuj Wiado&mość</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Resetuje wszystkie pola weryfikacji wiadomości</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Vetcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Wprowadź adres Vetcoin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Kliknij "Podpisz Wiadomość" żeby uzyskać podpis</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Vetcoin signature</source>
<translation>Wprowadź podpis Vetcoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Podany adres jest nieprawidłowy.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Proszę sprawdzić adres i spróbować ponownie.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Wprowadzony adres nie odnosi się do klucza.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Odblokowanie portfela zostało anulowane.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Klucz prywatny dla podanego adresu nie jest dostępny</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Podpisanie wiadomości nie powiodło się</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Wiadomość podpisana.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Podpis nie może zostać zdekodowany.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Sprawdź podpis i spróbuj ponownie.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Weryfikacja wiadomości nie powiodła się.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Wiadomość zweryfikowana.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Vetcoin developers</source>
<translation>Deweloperzy Vetcoin</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Otwórz do %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/niezatwierdzone</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 potwierdzeń</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, emitowany przez %n węzeł</numerusform><numerusform>, emitowany przez %n węzły</numerusform><numerusform>, emitowany przez %n węzłów</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Źródło</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Wygenerowano</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Od</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Do</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>własny adres</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etykieta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Przypisy</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>niezaakceptowane</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Prowizja transakcji</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Kwota netto</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Wiadomość</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Komentarz</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID transakcji</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Wygenerowane monety muszą zaczekać 120 bloków zanim będzie można je wydać. Kiedy wygenerowałeś ten blok, został on wyemitowany do sieci, aby dodać go do łańcucha bloków. Jeśli to się nie powiedzie nie zostanie on zaakceptowany i wygenerowanych monet nie będzie można wysyłać. Może się to czasami zdarzyć jeśli inny węzeł wygeneruje blok tuż przed tobą.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informacje debugowania</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transakcja</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Wejścia</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Kwota</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>prawda</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>fałsz</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, nie został jeszcze pomyślnie wyemitowany</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Otwórz dla %n bloku</numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nieznany</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Szczegóły transakcji</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ten panel pokazuje szczegółowy opis transakcji</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Kwota</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Otwórz do %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 potwierdzeń)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Niezatwierdzony (%1 z %2 potwierdzeń)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Zatwierdzony (%1 potwierdzeń)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostał %n blok</numerusform><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostało %n bloków</numerusform><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostało %n bloków</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ten blok nie został odebrany przez jakikolwiek inny węzeł i prawdopodobnie nie zostanie zaakceptowany!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Wygenerowano ale nie zaakceptowano</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Otrzymane przez</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Odebrano od</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Wysłano do</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Płatność do siebie</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Wydobyto</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(brak)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transakcji. Najedź na pole, aby zobaczyć liczbę potwierdzeń.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data i czas odebrania transakcji.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Rodzaj transakcji.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Adres docelowy transakcji.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Kwota usunięta z lub dodana do konta.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Wszystko</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Dzisiaj</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>W tym tygodniu</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>W tym miesiącu</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>W zeszłym miesiącu</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>W tym roku</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Zakres...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Otrzymane przez</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Wysłano do</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Do siebie</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Wydobyto</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Inne</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Wprowadź adres albo etykietę żeby wyszukać</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min suma</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiuj adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopiuj etykietę</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiuj kwotę</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Skopiuj ID transakcji</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edytuj etykietę</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Pokaż szczegóły transakcji</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Eksportuj Dane Transakcyjne</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>CSV (rozdzielany przecinkami)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Potwierdzony</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etykieta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Kwota</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Błąd podczas eksportowania</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Błąd zapisu do pliku %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Zakres:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>do</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Wyślij płatność</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Eksportuj</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Eksportuj dane z aktywnej karty do pliku</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Kopia Zapasowa Portfela</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Dane Portfela (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Nie udało się wykonać kopii zapasowej</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Wystąpił błąd przy zapisywaniu portfela do nowej lokalizacji.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Wykonano Kopię Zapasową</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Dane portfela zostały poprawnie zapisane w nowym miejscu.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Vetcoin version</source>
<translation>Wersja Vetcoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Użycie:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or vetcoind</source>
<translation>Wyślij polecenie do -server lub vetcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Lista poleceń</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Uzyskaj pomoc do polecenia</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opcje:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: vetcoin.conf)</source>
<translation>Wskaż plik konfiguracyjny (domyślnie: vetcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: vetcoind.pid)</source>
<translation>Wskaż plik pid (domyślnie: vetcoin.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Wskaż folder danych</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Ustaw rozmiar w megabajtach cache-u bazy danych (domyślnie: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Nasłuchuj połączeń na <port> (domyślnie: 9333 lub testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Utrzymuj maksymalnie <n> połączeń z peerami (domyślnie: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Podłącz się do węzła aby otrzymać adresy peerów i rozłącz</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Podaj swój publiczny adres</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Próg po którym nastąpi rozłączenie nietrzymających się zasad peerów (domyślnie: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Czas w sekundach, przez jaki nietrzymający się zasad peerzy nie będą mogli ponownie się podłączyć (domyślnie: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Nasłuchuj połączeń JSON-RPC na <port> (domyślnie: 9332 or testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Akceptuj linię poleceń oraz polecenia JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Uruchom w tle jako daemon i przyjmuj polecenia</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Użyj sieci testowej</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Akceptuj połączenia z zewnątrz (domyślnie: 1 jeśli nie ustawiono -proxy lub -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=vetcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Vetcoin Alert" admin@foo.com
</source>
<translation>%s, musisz ustawić rpcpassword w pliku konfiguracyjnym:⏎
%s⏎
Zalecane jest użycie losowego hasła:⏎
rpcuser=vetcoinrpc⏎
rpcpassword=%s⏎
(nie musisz pamiętać tego hasła)⏎
Użytkownik i hasło nie mogą być takie same.⏎
Jeśli plik nie istnieje, utwórz go z uprawnieniami tylko-do-odczytu dla właściciela.⏎
Zalecane jest ustawienie alertnotify aby poinformować o problemach:⏎
na przykład: alertnotify=echo %%s | mail -s "Alarm Vetcoin" admin@foo.com⏎</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu dla IPv6, korzystam z IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Skojarz z podanym adresem. Użyj formatu [host]:port dla IPv6 </translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Vetcoin is probably already running.</source>
<translation>Nie można zablokować folderu danych %s. Vetcoin prawdopodobnie już działa.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Uruchom polecenie przy otrzymaniu odpowiedniego powiadomienia (%s w poleceniu jest podstawiane za komunikat)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Wykonaj polecenie, kiedy transakcja portfela ulegnie zmianie (%s w poleceniu zostanie zastąpione przez TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Ustaw maksymalny rozmiar transakcji o wysokim priorytecie/niskiej prowizji w bajtach (domyślnie: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Ostrzeżenie: -paytxfee jest bardzo duży. To jest prowizja za transakcje, którą płacisz, gdy wysyłasz monety.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Uwaga: Wyświetlone transakcje mogą nie być poprawne! Możliwe, że potrzebujesz aktualizacji bądź inne węzły jej potrzebują</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Vetcoin will not work properly.</source>
<translation>Uwaga: Sprawdź czy data i czas na Twoim komputerze są prawidłowe! Jeśli nie to Vetcoin nie będzie działał prawidłowo.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Ostrzeżenie: błąd odczytu wallet.dat! Wszystkie klucze zostały odczytane, ale może brakować pewnych danych transakcji lub wpisów w książce adresowej lub mogą one być nieprawidłowe.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Ostrzeżenie: Odtworzono dane z uszkodzonego pliku wallet.dat! Oryginalny wallet.dat został zapisany jako wallet.{timestamp}.bak w %s; jeśli twoje saldo lub transakcje są niepoprawne powinieneś odtworzyć kopię zapasową.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Próbuj odzyskać klucze prywatne z uszkodzonego wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Opcje tworzenia bloku:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Łącz tylko do wskazanego węzła</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Wykryto uszkodzoną bazę bloków</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Odkryj własny adres IP (domyślnie: 1 kiedy w trybie nasłuchu i brak -externalip )</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Czy chcesz teraz przebudować bazę bloków?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Błąd inicjowania bloku bazy danych</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Błąd inicjowania środowiska bazy portfela %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Błąd ładowania bazy bloków</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Błąd ładowania bazy bloków</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Błąd: Mało miejsca na dysku!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Błąd: Zablokowany portfel, nie można utworzyć transakcji!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Błąd: błąd systemu:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Próba otwarcia jakiegokolwiek portu nie powiodła się. Użyj -listen=0 jeśli tego chcesz.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Nie udało się odczytać informacji bloku</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Nie udało się odczytać bloku.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Nie udało się zsynchronizować indeksu bloków.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Nie udało się zapisać indeksu bloków.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Nie udało się zapisać informacji bloku</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Nie udało się zapisać bloku</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Nie udało się zapisać do bazy monet</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Nie udało się zapisać indeksu transakcji</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Nie udało się zapisać danych odtwarzających</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Wyszukaj połączenia wykorzystując zapytanie DNS (domyślnie 1 jeśli nie użyto -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generuj monety (domyślnie: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Ile bloków sprawdzić przy starcie (domyślnie: 288, 0 = wszystkie)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Jak dokładna jest weryfikacja bloku (0-4, domyślnie: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Odbuduj indeks łańcucha bloków z obecnych plików blk000??.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ustaw liczbę wątków do odwołań RPC (domyślnie: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Weryfikacja bloków...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Weryfikacja portfela...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importuj bloki z zewnętrznego pliku blk000??.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Ustaw liczbę wątków skryptu weryfikacji (do 16, 0 = auto, <0 = zostawia taką ilość rdzenie wolnych, domyślnie: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Informacja</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Nieprawidłowy adres -tor: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Utrzymuj pełen indeks transakcji (domyślnie: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maksymalny bufor odbioru na połączenie, <n>*1000 bajtów (domyślnie: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maksymalny bufor wysyłu na połączenie, <n>*1000 bajtów (domyślnie: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Akceptuj tylko łańcuch bloków zgodny z wbudowanymi punktami kontrolnymi (domyślnie: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Łącz z węzłami tylko w sieci <net> (IPv4, IPv6 lub Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Poprzedź informacje debugowania znacznikiem czasowym</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Vetcoin Wiki for SSL setup instructions)</source>
<translation>Opcje SSL: (odwiedź Vetcoin Wiki w celu uzyskania instrukcji)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Wybierz używaną wersje socks serwera proxy (4-5, domyślnie:5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Wyślij informację/raport do konsoli zamiast do pliku debug.log.</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Wyślij informację/raport do debuggera.</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Ustaw maksymalny rozmiar bloku w bajtach (domyślnie: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ustaw minimalny rozmiar bloku w bajtach (domyślnie: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Zmniejsz plik debug.log przy starcie programu (domyślnie: 1 jeśli nie użyto -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Wskaż czas oczekiwania bezczynności połączenia w milisekundach (domyślnie: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Błąd systemu:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 1 gdy nasłuchuje)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nazwa użytkownika dla połączeń JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Ostrzeżenie</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Uwaga: Ta wersja jest przestarzała, aktualizacja wymagana!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Musisz przebudować bazę używając parametru -reindex aby zmienić -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat uszkodzony, odtworzenie się nie powiodło</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Hasło do połączeń JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Przyjmuj połączenia JSON-RPC ze wskazanego adresu IP</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Wysyłaj polecenia do węzła działającego na <ip> (domyślnie: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Wykonaj polecenie kiedy najlepszy blok ulegnie zmianie (%s w komendzie zastanie zastąpione przez hash bloku)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Zaktualizuj portfel do najnowszego formatu.</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ustaw rozmiar puli kluczy na <n> (domyślnie: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Przeskanuj blok łańcuchów żeby znaleźć zaginione transakcje portfela</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Użyj OpenSSL (https) do połączeń JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Plik certyfikatu serwera (domyślnie: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Klucz prywatny serwera (domyślnie: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Aceptowalne szyfry (domyślnie: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Ta wiadomość pomocy</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nie można przywiązać %s na tym komputerze (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Łączy przez proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Zezwól -addnode, -seednode i -connect na łączenie się z serwerem DNS</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Wczytywanie adresów...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Błąd ładowania wallet.dat: Uszkodzony portfel</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Vetcoin</source>
<translation>Błąd ładowania wallet.dat: Portfel wymaga nowszej wersji Vetcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Vetcoin to complete</source>
<translation>Portfel wymaga przepisania: zrestartuj Vetcoina żeby ukończyć</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Błąd ładowania wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Nieprawidłowy adres -proxy: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Nieznana sieć w -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Nieznana wersja proxy w -socks: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Nie można uzyskać adresu -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Nie można uzyskać adresu -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Nieprawidłowa kwota dla -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Nieprawidłowa kwota</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Niewystarczające środki</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ładowanie indeksu bloku...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Dodaj węzeł do łączenia się and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Vetcoin is probably already running.</source>
<translation>Nie można przywiązać %s na tym komputerze. Vetcoin prawdopodobnie już działa.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>
</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Wczytywanie portfela...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Nie można dezaktualizować portfela</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Nie można zapisać domyślnego adresu</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ponowne skanowanie...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Wczytywanie zakończone</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Aby użyć opcji %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Błąd</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Musisz ustawić rpcpassword=<hasło> w pliku configuracyjnym:
%s
Jeżeli plik nie istnieje, utwórz go z uprawnieniami właściciela-tylko-do-odczytu.</translation>
</message>
</context>
</TS>
|
gpl-3.0
|
xcalder/openant
|
public/view/position_bottom.php
|
192
|
<?php if(!empty($modules)):?>
<div id="bottom" class="col-sm-12" style="padding: 0">
<?php foreach($modules as $module):?>
<?php echo $module;?>
<?php endforeach;?>
</div>
<?php endif;?>
|
gpl-3.0
|
imapp-pl/golem
|
gnr/customizers/customizer.py
|
1478
|
import os
import subprocess
from PyQt4.QtCore import QSettings
from PyQt4.QtGui import QMessageBox
from golem.core.simpleexccmd import is_windows
class Customizer(object):
def __init__(self, gui, logic):
self.gui = gui
self.logic = logic
self.load_data()
self._setup_connections()
def _setup_connections(self):
pass
def load_data(self):
pass
@staticmethod
def show_file(file_name):
""" Open file with given using specific program that is connected with this file
extension
:param file_name: file that should be opened
"""
if is_windows():
os.startfile(file_name)
else:
opener = "xdg-open"
subprocess.call([opener, file_name])
@staticmethod
def show_error_window(text):
ms_box = QMessageBox(QMessageBox.Critical, "Error", u"{}".format(text))
ms_box.exec_()
ms_box.show()
def save_setting(self, name, value, sync=False):
settings = QSettings(os.path.join(self.logic.dir_manager.root_path, "gui_settings.ini"), QSettings.IniFormat)
settings.setValue(name, value)
if sync:
settings.sync()
def load_setting(self, name, default):
settings = QSettings(os.path.join(self.logic.dir_manager.root_path, "gui_settings.ini"), QSettings.IniFormat)
return settings.value(name, default)
|
gpl-3.0
|
Bobombe/MotorQtOrSFML
|
LD40/Pod.cpp
|
5029
|
#include "Opponent.h"
#include "Pod.h"
#include "Collider.h"
#include "ScreenLevel1.h"
#include "moteur2d.h"
#include <stdlib.h> /* srand, rand */
const int Pod::BASESPEED(100);
const int Pod::BASEACCEL(100);
Pod::Pod(Spaceship * player, Planet::PlanetType podType, bool left, WorldElement * parent) : Sprite(), _podType(podType), _player(player),
_planet(0), _cabCaller(0), _dead(false), _state(STATE_NONE)
{
_weName = "Pod";
setParent(parent);
double baseSpeed = 100;
switch (_podType) {
case Planet::PLANET_PURPLE:
setSprite("./Ressources/cars.png", Vector2d(0, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(0, 0), Vector2d(10, 10), Vector2d(200, 10), this);
break;
case Planet::PLANET_ORANGE:
setSprite("./Ressources/cars.png", Vector2d(20, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(10, 0), Vector2d(10, 10), Vector2d(200, 10), this);
break;
case Planet::PLANET_GREEN:
setSprite("./Ressources/cars.png", Vector2d(40, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(20, 0), Vector2d(10, 10), Vector2d(200, 10), this);
break;
case Planet::PLANET_YELLOW:
setSprite("./Ressources/cars.png", Vector2d(60, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(30, 0), Vector2d(10, 10), Vector2d(200, 10), this);
break;
case Planet::PLANET_WHITE:
setSprite("./Ressources/cars.png", Vector2d(80, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(0, 60), Vector2d(10, 10), Vector2d(200, 10), this);
break;
case Planet::PLANET_BLACK:
setSprite("./Ressources/cars.png", Vector2d(100, 100), Vector2d(20, 30));
setSpeed(Vector2d(0, baseSpeed));
_cabCaller = new Obstacle("./Ressources/palette.png", Vector2d(20, 60), Vector2d(10, 10), Vector2d(200, 10), this);
break;
}
_collider = new Collider(this);
_collider->initRectangular(0, 0, getSize().x, getSize().y);
if (!left) {
setPosition(Vector2d(ScreenLevel1::SIZEX-20, -getAbsoluteSize().y));
_cabCaller->setPosition(Vector2d(-_cabCaller->getSize().x, 10));
} else {
setPosition(Vector2d(0, -getAbsoluteSize().y));
_cabCaller->setPosition(Vector2d(getSize().x, 10));
}
ScreenLevel1 * screen = dynamic_cast<ScreenLevel1*>(parent);
if (screen) {
screen->addCollider(0, _collider);
} else {
std::cout << "Problem in Pod::Pod " << std::endl;
}
}
Pod::~Pod()
{
ScreenLevel1 * screen = dynamic_cast<ScreenLevel1*>(_player->getParent());
if (screen) {
screen->deleteCollider(0, _collider);
} else {
std::cout << "Problem in Pod::~Pod " << std::endl;
}
}
int Pod::update(double seconds)
{
if (_dead) {
if(getAbsolutePosition().x>ScreenLevel1::SIZEX/2-20) {
setSpeed(Vector2d(500, 0));
} else {
setSpeed(Vector2d(-500, 0));
}
}
if (_state == STATE_DOCKING) {
Vector2d speed = _dockPosition+_player->getAbsolutePosition()-getAbsolutePosition();
if (speed.x < 1 && speed.x > -1 && speed.y < 1 && speed.y > -1) {
setParent(_player);
setPosition(_dockPosition);
setSpeed(Vector2d());
} else {
Vector2d unit = speed;
speed*=2;
unit.normalize();
speed+=unit*2;
setSpeed(speed);
}
if (_cabCaller) {
delete _cabCaller;
_cabCaller = 0;
}
} else if (_state == STATE_GOING) {
if (_planet){
Vector2d speed = _planet->getAbsolutePosition()+Vector2d(100, 300)-getAbsolutePosition();
setSpeed(speed);
}
}
Sprite::update(seconds);
if (getAbsolutePosition().y > Moteur2D::getInstance()->getScreenSize().y ||
getAbsolutePosition().x > Moteur2D::getInstance()->getScreenSize().x || getAbsolutePosition().x < -getSize().x) {
delete this;
}
return 0;
}
void Pod::acceptCall()
{
if (_state == STATE_NONE) {
if (_player->getDockPosition(this, _dockPosition)) {
_state = STATE_DOCKING; //State docking
}
}
}
void Pod::handleCollisionWith(WorldElement * weColided, double, int...)
{
Spaceship * ship = dynamic_cast<Spaceship*>(weColided);
if (ship) {
acceptCall();
}
}
int Pod::undock(Planet * planet)
{
int ret = -1;
if (planet->_planetType == _podType) {
ret = 5;
_planet = planet;
setParent(_planet);
_state = STATE_GOING;
}
return ret;
}
|
gpl-3.0
|
wuceyang/smartcms
|
library/Database/DriverType.php
|
83
|
<?php
namespace Library\Database;
class DriverType{
const MYSQL = 'MYSQL';
}
|
gpl-3.0
|
r0mai/metashell
|
lib/data/src/event_category.cpp
|
1346
|
// Metashell - Interactive C++ template metaprogramming shell
// Copyright (C) 2018, Abel Sinkovics (abel@sinkovics.hu)
//
// 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 <metashell/data/event_category.hpp>
#include <iostream>
namespace metashell
{
namespace data
{
std::ostream& operator<<(std::ostream& os_, event_category category_)
{
return os_ << to_string(category_);
}
std::string to_string(event_category category_)
{
switch (category_)
{
case event_category::preprocessor:
return "preprocessor";
case event_category::template_:
return "template";
case event_category::misc:
return "misc";
}
return "unknown category";
}
}
}
|
gpl-3.0
|
xbmcmegapack/plugin.video.megapack.dev
|
resources/lib/menus/home_countries_virgin_islands_us.py
|
1134
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@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/gpl-3.0.html
"""
class Countries_Virgin_islands_us():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
countries=["Virgin Islands, U.S."]))
|
gpl-3.0
|
Mexiswow/FastSocialEngine
|
src/htdocs/adm/index.php
|
204
|
<?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 28.11.13
* Time: 0:15
*/
include '../../engine/engine.inc.php';
include '../../engine/admin_include.php';
$smarty->display('admin/index.tpl');
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.