code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2010 Benny Malengier
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Python classes
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#-------------------------------------------------------------------------
#
# GTK classes
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
_TAB = Gdk.keyval_from_name("Tab")
_ENTER = Gdk.keyval_from_name("Enter")
#-------------------------------------------------------------------------
#
# Gramps classes
#
#-------------------------------------------------------------------------
from .surnamemodel import SurnameModel
from .embeddedlist import EmbeddedList, TEXT_EDIT_COL
from ...ddtargets import DdTargets
from gramps.gen.lib import Surname, NameOriginType
from ...utils import match_primary_mask, no_match_primary_mask
# table for skipping illegal control chars
INVISIBLE = dict.fromkeys(list(range(32)))
#-------------------------------------------------------------------------
#
# SurnameTab
#
#-------------------------------------------------------------------------
class SurnameTab(EmbeddedList):
_HANDLE_COL = 5
_DND_TYPE = DdTargets.SURNAME
_MSG = {
'add' : _('Create and add a new surname'),
'del' : _('Remove the selected surname'),
'edit' : _('Edit the selected surname'),
'up' : _('Move the selected surname upwards'),
'down' : _('Move the selected surname downwards'),
}
#index = column in model. Value =
# (name, sortcol in model, width, markup/text
_column_names = [
(_('Prefix'), 0, 150, TEXT_EDIT_COL, -1, None),
(_('Surname'), 1, -1, TEXT_EDIT_COL, -1, None),
(_('Connector'), 2, 100, TEXT_EDIT_COL, -1, None),
]
_column_combo = (_('Origin'), -1, 150, 3) # name, sort, width, modelcol
_column_toggle = (_('Primary', 'Name'), -1, 80, 4)
def __init__(self, dbstate, uistate, track, name, on_change=None,
top_label='<b>%s</b>' % _("Multiple Surnames") ):
self.obj = name
self.on_change = on_change
self.curr_col = -1
self.curr_cellr = None
self.curr_celle = None
EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'),
SurnameModel, move_buttons=True,
top_label=top_label)
def build_columns(self):
#first the standard text columns with normal method
EmbeddedList.build_columns(self)
# now we add the two special columns
# combobox for type
colno = len(self.columns)
name = self._column_combo[0]
renderer = Gtk.CellRendererCombo()
renderer.set_property('ellipsize', Pango.EllipsizeMode.END)
# set up the comboentry editable
no = NameOriginType()
self.cmborig = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING)
self.cmborigmap = no.get_map().copy()
#sort the keys based on the value
keys = sorted(self.cmborigmap, key=lambda x: glocale.sort_key(self.cmborigmap[x]))
for key in keys:
if key != no.get_custom():
self.cmborig.append(row=[key, self.cmborigmap[key]])
additional = self.dbstate.db.get_origin_types()
if additional:
for type in additional:
if type:
self.cmborig.append(row=[no.get_custom(), type])
renderer.set_property("model", self.cmborig)
renderer.set_property("text-column", 1)
renderer.set_property('editable', not self.dbstate.db.readonly)
renderer.connect('editing_started', self.on_edit_start_cmb, colno)
renderer.connect('edited', self.on_orig_edited, self._column_combo[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, text=self._column_combo[3])
column.set_resizable(True)
column.set_sort_column_id(self._column_combo[1])
column.set_min_width(self._column_combo[2])
column.set_expand(False)
self.columns.append(column)
self.tree.append_column(column)
# toggle box for primary
colno += 1
name = self._column_toggle[0]
renderer = Gtk.CellRendererToggle()
renderer.set_property('activatable', True)
renderer.set_property('radio', True)
renderer.connect( 'toggled', self.on_prim_toggled, self._column_toggle[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, active=self._column_toggle[3])
column.set_resizable(False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
column.set_alignment(0.5)
column.set_sort_column_id(self._column_toggle[1])
column.set_max_width(self._column_toggle[2])
self.columns.append(column)
self.tree.append_column(column)
## def by_value(self, first, second):
## """
## Method for sorting keys based on the values.
## """
## fvalue = self.cmborigmap[first]
## svalue = self.cmborigmap[second]
## return glocale.strcoll(fvalue, svalue)
def setup_editable_col(self):
"""
inherit this and set the variables needed for editable columns
Variable edit_col_funcs needs to be a dictionary from model col_nr to
function to call for
Example:
self.edit_col_funcs ={1: {'edit_start': self.on_edit_start,
'edited': self.on_edited
}}
"""
self.edit_col_funcs = {
0: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
1: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
2: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline}}
def get_data(self):
return self.obj.get_surname_list()
def is_empty(self):
return len(self.model)==0
def _get_surn_from_model(self):
"""
Return new surname_list for storing in the name based on content of
the model
"""
new_list = []
for idx in range(len(self.model)):
node = self.model.get_iter(idx)
surn = self.model.get_value(node, 5)
surn.set_prefix(self.model.get_value(node, 0))
surn.set_surname(self.model.get_value(node, 1))
surn.set_connector(self.model.get_value(node, 2))
surn.get_origintype().set(self.model.get_value(node, 3))
surn.set_primary(self.model.get_value(node, 4))
new_list += [surn]
return new_list
def update(self):
"""
Store the present data in the model to the name object
"""
new_map = self._get_surn_from_model()
self.obj.set_surname_list(new_map)
# update name in previews
if self.on_change:
self.on_change()
def post_rebuild(self, prebuildpath):
"""
Called when data model has changed, in particular necessary when row
order is updated.
@param prebuildpath: path selected before rebuild, None if none
@type prebuildpath: tree path
"""
if self.on_change:
self.on_change()
def column_order(self):
# order of columns for EmbeddedList. Only the text columns here
return ((1, 0), (1, 1), (1, 2))
def add_button_clicked(self, obj):
"""Add button is clicked, add a surname to the person"""
prim = False
if len(self.obj.get_surname_list()) == 0:
prim = True
node = self.model.append(row=['', '', '', str(NameOriginType()), prim,
Surname()])
self.selection.select_iter(node)
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
self.update()
def del_button_clicked(self, obj):
"""
Delete button is clicked. Remove from the model
"""
(model, node) = self.selection.get_selected()
if node:
self.model.remove(node)
self.update()
def on_edit_start(self, cellr, celle, path, colnr):
""" start of editing. Store stuff so we know when editing ends where we
are
"""
self.curr_col = colnr
self.curr_cellr = cellr
self.curr_celle = celle
def on_edit_start_cmb(self, cellr, celle, path, colnr):
"""
An edit starts in the origin type column
This means a cmb has been created as celle, and we can set up the stuff
we want this cmb to contain: autocompletion, stop edit when selection
in the cmb happens.
"""
self.on_edit_start(cellr, celle, path, colnr)
#set up autocomplete
entry = celle.get_child()
entry.set_width_chars(10)
completion = Gtk.EntryCompletion()
completion.set_model(self.cmborig)
completion.set_minimum_key_length(1)
completion.set_text_column(1)
entry.set_completion(completion)
#
celle.connect('changed', self.on_origcmb_change, path, colnr)
def on_edit_start_toggle(self, cellr, celle, path, colnr):
"""
Edit
"""
self.on_edit_start(cellr, celle, path, colnr)
def on_edit_inline(self, cell, path, new_text, colnr):
"""
Edit is happening. The model is updated and the surname objects updated.
colnr must be the column in the model.
"""
node = self.model.get_iter(path)
text = new_text.translate(INVISIBLE).strip()
self.model.set_value(node, colnr, text)
self.update()
def on_orig_edited(self, cellr, path, new_text, colnr):
"""
An edit is finished in the origin type column. For a cmb in an editor,
the model may only be updated when typing is finished, as editing stops
automatically on update of the model.
colnr must be the column in the model.
"""
self.on_edit_inline(cellr, path, new_text, colnr)
def on_origcmb_change(self, cmb, path, colnr):
"""
A selection occured in the cmb of the origin type column. colnr must
be the column in the model.
"""
act = cmb.get_active()
if act == -1:
return
self.on_orig_edited(None, path,
self.cmborig.get_value(
self.cmborig.get_iter((act,)),1),
colnr)
def on_prim_toggled(self, cell, path, colnr):
"""
Primary surname on path is toggled. colnr must be the col
in the model
"""
#obtain current value
node = self.model.get_iter(path)
old_val = self.model.get_value(node, colnr)
for nr in range(len(self.obj.get_surname_list())):
if nr == int(path[0]):
if old_val:
#True remains True
break
else:
#This value becomes True
self.model.set_value(self.model.get_iter((nr,)), colnr, True)
else:
self.model.set_value(self.model.get_iter((nr,)), colnr, False)
self.update()
return
def edit_button_clicked(self, obj):
""" Edit button clicked
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
def key_pressed(self, obj, event):
"""
Handles the key being pressed.
Here we make sure tab moves to next or previous value in row on TAB
"""
if not EmbeddedList.key_pressed(self, obj, event):
if event.type == Gdk.EventType.KEY_PRESS and event.keyval in (_TAB,):
if no_match_primary_mask(event.get_state(),
Gdk.ModifierType.SHIFT_MASK):
return self.next_cell()
elif match_primary_mask(event.get_state(), Gdk.ModifierType.SHIFT_MASK):
return self.prev_cell()
else:
return
else:
return
return True
def next_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
nccol = self.curr_col+1
if nccol < 4:
if self.curr_celle:
self.curr_celle.editing_done()
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[nccol],
focus_cell=None,
start_editing=True)
elif nccol == 4:
#go to next line if there is one
if path < len(self.obj.get_surname_list()):
newpath = Gtk.TreePath((path+1,))
self.curr_celle.editing_done()
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
def prev_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
if self.curr_col > 0:
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[self.curr_col-1],
focus_cell=None,
start_editing=True)
elif self.curr_col == 0:
#go to prev line if there is one
if path > 0:
newpath = Gtk.TreePath((path-1,))
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[-2],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
| Fedik/gramps | gramps/gui/editors/displaytabs/surnametab.py | Python | gpl-2.0 | 16,204 |
<?php defined('WPSS_PATH') or die();?>
<?php $util = new WPSS_Util();?>
<?php $question = new WPSS_Question((int) $_GET['id']);?>
<?php $quiz = new WPSS_Quiz($question->quiz_id);?>
<!-- Admin questions#new -->
<div class="wrap wpss">
<img class="left" src="<?php echo WPSS_URL.'assets/images/wpss_admin.png'?>" />
<h2 class="left"><?php echo $quiz->title;?>, Editing Question</h2>
<div class="clear"></div>
<hr />
<p class="wpss-breadcrumb">
<a href="<?php echo $util->admin_url('','','');?>">Quizzes</a> » <a href="<?php echo $util->admin_url('quiz', 'edit', $quiz->id);?>"><?php echo $quiz->title;?></a> » <a href="<?php echo $util->admin_url('quiz', 'questions_index', $quiz->id);?>">Questions</a> » <a class="current">Edit</a>
</p>
<?php include( WPSS_PATH . "admin/questions/_form.php");?>
</div>
| JohnBueno/cafequill | wp-content/plugins/wordpress-simple-survey/admin/questions/edit.php | PHP | gpl-2.0 | 843 |
<?php
namespace Drutiny\Audit;
use Drutiny\Sandbox\Sandbox;
use Drutiny\Audit\AuditInterface;
/**
*
*/
interface RemediableInterface extends AuditInterface
{
/**
* Attempt to remediate the check after it has failed.
*
* @param Sandbox $sandbox
* @return bool
*/
public function remediate(Sandbox $sandbox);
}
| drutiny/drutiny | src/Audit/RemediableInterface.php | PHP | gpl-2.0 | 336 |
<?php
pb_backupbuddy::$ui->start_metabox( 'BackupBuddy Settings', true, 'width: 100%; max-width: 1200px;' );
$settings_form->display_settings( 'Save Settings' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
/*
REMOVED v3.1.
pb_backupbuddy::$ui->start_metabox( __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ), true, 'width: 100%; max-width: 1200px;' );
//echo '<h3>' . __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ) . '</h3>';
//echo '<br>';
echo '<a href="' . pb_backupbuddy::ajax_url( 'destination_picker' ) . '&action_verb=to%20manage%20files&TB_iframe=1&width=640&height=600" class="thickbox button secondary-button" style="margin-top: 3px;" title="' . __( 'Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '">' . __('Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '</a>';
echo ' ';
_e( 'Add & configure destinations or select a destination to browse & manage its files.', 'it-l10n-backupbuddy' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
*/
?>
<script type="text/javascript">
function pb_backupbuddy_selectdestination( destination_id, destination_title, callback_data ) {
window.location.href = '<?php
if ( is_network_admin() ) {
echo network_admin_url( 'admin.php' );
} else {
echo admin_url( 'admin.php' );
}
?>?page=pb_backupbuddy_backup&custom=remoteclient&destination_id=' + destination_id;
}
</script>
<?php
// Handles thickbox auto-resizing. Keep at bottom of page to avoid issues.
if ( !wp_script_is( 'media-upload' ) ) {
wp_enqueue_script( 'media-upload' );
wp_print_scripts( 'media-upload' );
}
?> | Ransom-Brent/HVAC | wp-content/plugins/backupbuddy/views/settings.php | PHP | gpl-2.0 | 1,947 |
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/Boot/Boot.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <unordered_set>
#include <vector>
#include <zlib.h>
#include "Common/Align.h"
#include "Common/CDUtils.h"
#include "Common/CommonPaths.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Common/File.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "Core/Boot/DolReader.h"
#include "Core/Boot/ElfReader.h"
#include "Core/CommonTitles.h"
#include "Core/Config/SYSCONFSettings.h"
#include "Core/ConfigManager.h"
#include "Core/FifoPlayer/FifoPlayer.h"
#include "Core/HLE/HLE.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI_DeviceIPL.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/VideoInterface.h"
#include "Core/Host.h"
#include "Core/IOS/IOS.h"
#include "Core/PatchEngine.h"
#include "Core/PowerPC/PPCAnalyst.h"
#include "Core/PowerPC/PPCSymbolDB.h"
#include "Core/PowerPC/PowerPC.h"
#include "DiscIO/Enums.h"
#include "DiscIO/Volume.h"
BootParameters::BootParameters(Parameters&& parameters_,
const std::optional<std::string>& savestate_path_)
: parameters(std::move(parameters_)), savestate_path(savestate_path_)
{
}
std::unique_ptr<BootParameters>
BootParameters::GenerateFromFile(const std::string& path,
const std::optional<std::string>& savestate_path)
{
const bool is_drive = cdio_is_cdrom(path);
// Check if the file exist, we may have gotten it from a --elf command line
// that gave an incorrect file name
if (!is_drive && !File::Exists(path))
{
PanicAlertT("The specified file \"%s\" does not exist", path.c_str());
return {};
}
std::string extension;
SplitPath(path, nullptr, nullptr, &extension);
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
static const std::unordered_set<std::string> disc_image_extensions = {
{".gcm", ".iso", ".tgc", ".wbfs", ".ciso", ".gcz", ".dol", ".elf"}};
if (disc_image_extensions.find(extension) != disc_image_extensions.end() || is_drive)
{
std::unique_ptr<DiscIO::Volume> volume = DiscIO::CreateVolumeFromFilename(path);
if (volume)
return std::make_unique<BootParameters>(Disc{path, std::move(volume)}, savestate_path);
if (extension == ".elf")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<ElfReader>(path)},
savestate_path);
}
if (extension == ".dol")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<DolReader>(path)},
savestate_path);
}
if (is_drive)
{
PanicAlertT("Could not read \"%s\". "
"There is no disc in the drive or it is not a GameCube/Wii backup. "
"Please note that Dolphin cannot play games directly from the original "
"GameCube and Wii discs.",
path.c_str());
}
else
{
PanicAlertT("\"%s\" is an invalid GCM/ISO file, or is not a GC/Wii ISO.", path.c_str());
}
return {};
}
if (extension == ".dff")
return std::make_unique<BootParameters>(DFF{path}, savestate_path);
if (extension == ".wad")
return std::make_unique<BootParameters>(DiscIO::WiiWAD{path}, savestate_path);
PanicAlertT("Could not recognize file %s", path.c_str());
return {};
}
BootParameters::IPL::IPL(DiscIO::Region region_) : region(region_)
{
const std::string directory = SConfig::GetInstance().GetDirectoryForRegion(region);
path = SConfig::GetInstance().GetBootROMPath(directory);
}
BootParameters::IPL::IPL(DiscIO::Region region_, Disc&& disc_) : IPL(region_)
{
disc = std::move(disc_);
}
// Inserts a disc into the emulated disc drive and returns a pointer to it.
// The returned pointer must only be used while we are still booting,
// because DVDThread can do whatever it wants to the disc after that.
static const DiscIO::Volume* SetDisc(std::unique_ptr<DiscIO::Volume> volume)
{
const DiscIO::Volume* pointer = volume.get();
DVDInterface::SetDisc(std::move(volume));
return pointer;
}
bool CBoot::DVDRead(const DiscIO::Volume& volume, u64 dvd_offset, u32 output_address, u32 length,
const DiscIO::Partition& partition)
{
std::vector<u8> buffer(length);
if (!volume.Read(dvd_offset, length, buffer.data(), partition))
return false;
Memory::CopyToEmu(output_address, buffer.data(), length);
return true;
}
void CBoot::UpdateDebugger_MapLoaded()
{
Host_NotifyMapLoaded();
}
// Get map file paths for the active title.
bool CBoot::FindMapFile(std::string* existing_map_file, std::string* writable_map_file)
{
const std::string& game_id = SConfig::GetInstance().m_debugger_game_id;
if (writable_map_file)
*writable_map_file = File::GetUserPath(D_MAPS_IDX) + game_id + ".map";
bool found = false;
static const std::string maps_directories[] = {File::GetUserPath(D_MAPS_IDX),
File::GetSysDirectory() + MAPS_DIR DIR_SEP};
for (size_t i = 0; !found && i < ArraySize(maps_directories); ++i)
{
std::string path = maps_directories[i] + game_id + ".map";
if (File::Exists(path))
{
found = true;
if (existing_map_file)
*existing_map_file = path;
}
}
return found;
}
bool CBoot::LoadMapFromFilename()
{
std::string strMapFilename;
bool found = FindMapFile(&strMapFilename, nullptr);
if (found && g_symbolDB.LoadMap(strMapFilename))
{
UpdateDebugger_MapLoaded();
return true;
}
return false;
}
// If ipl.bin is not found, this function does *some* of what BS1 does:
// loading IPL(BS2) and jumping to it.
// It does not initialize the hardware or anything else like BS1 does.
bool CBoot::Load_BS2(const std::string& boot_rom_filename)
{
// CRC32 hashes of the IPL file; including source where known
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385344#pid385344
constexpr u32 USA_v1_0 = 0x6D740AE7;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385334#pid385334
constexpr u32 USA_v1_1 = 0xD5E6FEEA;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385399#pid385399
constexpr u32 USA_v1_2 = 0x86573808;
// GameCubes sold in Brazil have this IPL. Same as USA v1.2 but localized
constexpr u32 BRA_v1_0 = 0x667D0B64;
// Redump
constexpr u32 JAP_v1_0 = 0x6DAC1F2A;
// https://bugs.dolphin-emu.org/issues/8936
constexpr u32 JAP_v1_1 = 0xD235E3F9;
constexpr u32 JAP_v1_2 = 0x8BDABBD4;
// Redump
constexpr u32 PAL_v1_0 = 0x4F319F43;
// https://forums.dolphin-emu.org/Thread-ipl-with-unknown-hash-dd8cab7c-problem-caused-by-my-pal-gamecube-bios?pid=435463#pid435463
constexpr u32 PAL_v1_1 = 0xDD8CAB7C;
// Redump
constexpr u32 PAL_v1_2 = 0xAD1B7F16;
// Load the whole ROM dump
std::string data;
if (!File::ReadFileToString(boot_rom_filename, data))
return false;
// Use zlibs crc32 implementation to compute the hash
u32 ipl_hash = crc32(0L, Z_NULL, 0);
ipl_hash = crc32(ipl_hash, (const Bytef*)data.data(), (u32)data.size());
DiscIO::Region ipl_region;
switch (ipl_hash)
{
case USA_v1_0:
case USA_v1_1:
case USA_v1_2:
case BRA_v1_0:
ipl_region = DiscIO::Region::NTSC_U;
break;
case JAP_v1_0:
case JAP_v1_1:
case JAP_v1_2:
ipl_region = DiscIO::Region::NTSC_J;
break;
case PAL_v1_0:
case PAL_v1_1:
case PAL_v1_2:
ipl_region = DiscIO::Region::PAL;
break;
default:
PanicAlertT("IPL with unknown hash %x", ipl_hash);
ipl_region = DiscIO::Region::Unknown;
break;
}
const DiscIO::Region boot_region = SConfig::GetInstance().m_region;
if (ipl_region != DiscIO::Region::Unknown && boot_region != ipl_region)
PanicAlertT("%s IPL found in %s directory. The disc might not be recognized",
SConfig::GetDirectoryForRegion(ipl_region),
SConfig::GetDirectoryForRegion(boot_region));
// Run the descrambler over the encrypted section containing BS1/BS2
ExpansionInterface::CEXIIPL::Descrambler((u8*)data.data() + 0x100, 0x1AFE00);
// TODO: Execution is supposed to start at 0xFFF00000, not 0x81200000;
// copying the initial boot code to 0x81200000 is a hack.
// For now, HLE the first few instructions and start at 0x81200150
// to work around this.
Memory::CopyToEmu(0x01200000, data.data() + 0x100, 0x700);
Memory::CopyToEmu(0x01300000, data.data() + 0x820, 0x1AFE00);
PowerPC::ppcState.gpr[3] = 0xfff0001f;
PowerPC::ppcState.gpr[4] = 0x00002030;
PowerPC::ppcState.gpr[5] = 0x0000009c;
UReg_MSR& m_MSR = ((UReg_MSR&)PowerPC::ppcState.msr);
m_MSR.FP = 1;
m_MSR.DR = 1;
m_MSR.IR = 1;
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_IBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_IBAT3L] = 0xfff00001;
PowerPC::ppcState.spr[SPR_DBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_DBAT3L] = 0xfff00001;
SetupBAT(/*is_wii*/ false);
PC = 0x81200150;
return true;
}
static void SetDefaultDisc()
{
const SConfig& config = SConfig::GetInstance();
if (!config.m_strDefaultISO.empty())
SetDisc(DiscIO::CreateVolumeFromFilename(config.m_strDefaultISO));
}
static void CopyDefaultExceptionHandlers()
{
constexpr u32 EXCEPTION_HANDLER_ADDRESSES[] = {0x00000100, 0x00000200, 0x00000300, 0x00000400,
0x00000500, 0x00000600, 0x00000700, 0x00000800,
0x00000900, 0x00000C00, 0x00000D00, 0x00000F00,
0x00001300, 0x00001400, 0x00001700};
constexpr u32 RFI_INSTRUCTION = 0x4C000064;
for (const u32 address : EXCEPTION_HANDLER_ADDRESSES)
Memory::Write_U32(RFI_INSTRUCTION, address);
}
// Third boot step after BootManager and Core. See Call schedule in BootManager.cpp
bool CBoot::BootUp(std::unique_ptr<BootParameters> boot)
{
SConfig& config = SConfig::GetInstance();
g_symbolDB.Clear();
// PAL Wii uses NTSC framerate and linecount in 60Hz modes
VideoInterface::Preset(DiscIO::IsNTSC(config.m_region) ||
(config.bWii && Config::Get(Config::SYSCONF_PAL60)));
struct BootTitle
{
BootTitle() : config(SConfig::GetInstance()) {}
bool operator()(BootParameters::Disc& disc) const
{
NOTICE_LOG(BOOT, "Booting from disc: %s", disc.path.c_str());
const DiscIO::Volume* volume = SetDisc(std::move(disc.volume));
if (!volume)
return false;
if (!EmulatedBS2(config.bWii, *volume))
return false;
// Try to load the symbol map if there is one, and then scan it for
// and eventually replace code
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::Executable& executable) const
{
NOTICE_LOG(BOOT, "Booting from executable: %s", executable.path.c_str());
if (!executable.reader->IsValid())
return false;
if (!executable.reader->LoadIntoMemory())
{
PanicAlertT("Failed to load the executable to memory.");
return false;
}
SetDefaultDisc();
SetupMSR();
SetupBAT(config.bWii);
CopyDefaultExceptionHandlers();
if (config.bWii)
{
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_HID4] = 0x82000000;
// Set a value for the SP. It doesn't matter where this points to,
// as long as it is a valid location. This value is taken from a homebrew binary.
PowerPC::ppcState.gpr[1] = 0x8004d4bc;
// Because there is no TMD to get the requested system (IOS) version from,
// we default to IOS58, which is the version used by the Homebrew Channel.
SetupWiiMemory();
IOS::HLE::GetIOS()->BootIOS(Titles::IOS(58));
}
else
{
SetupGCMemory();
}
PC = executable.reader->GetEntryPoint();
if (executable.reader->LoadSymbols() || LoadMapFromFilename())
{
UpdateDebugger_MapLoaded();
HLE::PatchFunctions();
}
return true;
}
bool operator()(const DiscIO::WiiWAD& wad) const
{
SetDefaultDisc();
return Boot_WiiWAD(wad);
}
bool operator()(const BootParameters::NANDTitle& nand_title) const
{
SetDefaultDisc();
return BootNANDTitle(nand_title.id);
}
bool operator()(const BootParameters::IPL& ipl) const
{
NOTICE_LOG(BOOT, "Booting GC IPL: %s", ipl.path.c_str());
if (!File::Exists(ipl.path))
{
if (ipl.disc)
PanicAlertT("Cannot start the game, because the GC IPL could not be found.");
else
PanicAlertT("Cannot find the GC IPL.");
return false;
}
if (!Load_BS2(ipl.path))
return false;
if (ipl.disc)
{
NOTICE_LOG(BOOT, "Inserting disc: %s", ipl.disc->path.c_str());
SetDisc(DiscIO::CreateVolumeFromFilename(ipl.disc->path));
}
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::DFF& dff) const
{
NOTICE_LOG(BOOT, "Booting DFF: %s", dff.dff_path.c_str());
return FifoPlayer::GetInstance().Open(dff.dff_path);
}
private:
const SConfig& config;
};
if (!std::visit(BootTitle(), boot->parameters))
return false;
PatchEngine::LoadPatches();
HLE::PatchFixedFunctions();
return true;
}
BootExecutableReader::BootExecutableReader(const std::string& file_name)
: BootExecutableReader(File::IOFile{file_name, "rb"})
{
}
BootExecutableReader::BootExecutableReader(File::IOFile file)
{
file.Seek(0, SEEK_SET);
m_bytes.resize(file.GetSize());
file.ReadBytes(m_bytes.data(), m_bytes.size());
}
BootExecutableReader::BootExecutableReader(const std::vector<u8>& bytes) : m_bytes(bytes)
{
}
BootExecutableReader::~BootExecutableReader() = default;
void StateFlags::UpdateChecksum()
{
constexpr size_t length_in_bytes = sizeof(StateFlags) - 4;
constexpr size_t num_elements = length_in_bytes / sizeof(u32);
std::array<u32, num_elements> flag_data;
std::memcpy(flag_data.data(), &flags, length_in_bytes);
checksum = std::accumulate(flag_data.cbegin(), flag_data.cend(), 0U);
}
void UpdateStateFlags(std::function<void(StateFlags*)> update_function)
{
const std::string file_path =
Common::GetTitleDataPath(Titles::SYSTEM_MENU, Common::FROM_SESSION_ROOT) + WII_STATE;
File::IOFile file;
StateFlags state;
if (File::Exists(file_path))
{
file.Open(file_path, "r+b");
file.ReadBytes(&state, sizeof(state));
}
else
{
File::CreateFullPath(file_path);
file.Open(file_path, "a+b");
memset(&state, 0, sizeof(state));
}
update_function(&state);
state.UpdateChecksum();
file.Seek(0, SEEK_SET);
file.WriteBytes(&state, sizeof(state));
}
| SeannyM/dolphin | Source/Core/Core/Boot/Boot.cpp | C++ | gpl-2.0 | 15,252 |
<?php
namespace TYPO3\CMS\Extbase\Persistence\Generic;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
/**
* The Query class used to run queries against the database
*
* @api
*/
class Query implements QueryInterface {
/**
* An inner join.
*/
const JCR_JOIN_TYPE_INNER = '{http://www.jcp.org/jcr/1.0}joinTypeInner';
/**
* A left-outer join.
*/
const JCR_JOIN_TYPE_LEFT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeLeftOuter';
/**
* A right-outer join.
*/
const JCR_JOIN_TYPE_RIGHT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeRightOuter';
/**
* Charset of strings in QOM
*/
const CHARSET = 'utf-8';
/**
* @var string
*/
protected $type;
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* @inject
*/
protected $objectManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
* @inject
*/
protected $dataMapper;
/**
* @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
* @inject
*/
protected $persistenceManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory
* @inject
*/
protected $qomFactory;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
*/
protected $source;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface
*/
protected $constraint;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
protected $statement;
/**
* @var int
*/
protected $orderings = array();
/**
* @var int
*/
protected $limit;
/**
* @var int
*/
protected $offset;
/**
* The query settings.
*
* @var QuerySettingsInterface
*/
protected $querySettings;
/**
* Constructs a query object working on the given class name
*
* @param string $type
*/
public function __construct($type) {
$this->type = $type;
}
/**
* Sets the Query Settings. These Query settings must match the settings expected by
* the specific Storage Backend.
*
* @param QuerySettingsInterface $querySettings The Query Settings
* @return void
* @api This method is not part of FLOW3 API
*/
public function setQuerySettings(QuerySettingsInterface $querySettings) {
$this->querySettings = $querySettings;
}
/**
* Returns the Query Settings.
*
* @throws Exception
* @return QuerySettingsInterface $querySettings The Query Settings
* @api This method is not part of FLOW3 API
*/
public function getQuerySettings() {
if (!$this->querySettings instanceof QuerySettingsInterface) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Tried to get the query settings without seting them before.', 1248689115);
}
return $this->querySettings;
}
/**
* Returns the type this query cares for.
*
* @return string
* @api
*/
public function getType() {
return $this->type;
}
/**
* Sets the source to fetch the result from
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source
*/
public function setSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source) {
$this->source = $source;
}
/**
* Returns the selectorn name or an empty string, if the source is not a selector
* TODO This has to be checked at another place
*
* @return string The selector name
*/
protected function getSelectorName() {
$source = $this->getSource();
if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
return $source->getSelectorName();
} else {
return '';
}
}
/**
* Gets the node-tuple source for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface the node-tuple source; non-null
*/
public function getSource() {
if ($this->source === NULL) {
$this->source = $this->qomFactory->selector($this->getType(), $this->dataMapper->convertClassNameToTableName($this->getType()));
}
return $this->source;
}
/**
* Executes the query against the database and returns the result
*
* @param $returnRawQueryResult boolean avoids the object mapping by the persistence
* @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface|array The query result object or an array if $returnRawQueryResult is TRUE
* @api
*/
public function execute($returnRawQueryResult = FALSE) {
if ($returnRawQueryResult === TRUE || $this->getQuerySettings()->getReturnRawQueryResult() === TRUE) {
return $this->persistenceManager->getObjectDataByQuery($this);
} else {
return $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\QueryResultInterface', $this);
}
}
/**
* Sets the property names to order the result by. Expected like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
* where 'foo' and 'bar' are property names.
*
* @param array $orderings The property names to order by
* @return QueryInterface
* @api
*/
public function setOrderings(array $orderings) {
$this->orderings = $orderings;
return $this;
}
/**
* Returns the property names to order the result by. Like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
*
* @return array
* @api
*/
public function getOrderings() {
return $this->orderings;
}
/**
* Sets the maximum size of the result set to limit. Returns $this to allow
* for chaining (fluid interface)
*
* @param integer $limit
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setLimit($limit) {
if (!is_int($limit) || $limit < 1) {
throw new \InvalidArgumentException('The limit must be an integer >= 1', 1245071870);
}
$this->limit = $limit;
return $this;
}
/**
* Resets a previously set maximum size of the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @return QueryInterface
* @api
*/
public function unsetLimit() {
unset($this->limit);
return $this;
}
/**
* Returns the maximum size of the result set to limit.
*
* @return integer
* @api
*/
public function getLimit() {
return $this->limit;
}
/**
* Sets the start offset of the result set to offset. Returns $this to
* allow for chaining (fluid interface)
*
* @param integer $offset
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setOffset($offset) {
if (!is_int($offset) || $offset < 0) {
throw new \InvalidArgumentException('The offset must be a positive integer', 1245071872);
}
$this->offset = $offset;
return $this;
}
/**
* Returns the start offset of the result set.
*
* @return integer
* @api
*/
public function getOffset() {
return $this->offset;
}
/**
* The constraint used to limit the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint
* @return QueryInterface
* @api
*/
public function matching($constraint) {
$this->constraint = $constraint;
return $this;
}
/**
* Sets the statement of this query. If you use this, you will lose the abstraction from a concrete storage
* backend (database).
*
* @param string|\TYPO3\CMS\Core\Database\PreparedStatement $statement The statement
* @param array $parameters An array of parameters. These will be bound to placeholders '?' in the $statement.
* @return QueryInterface
*/
public function statement($statement, array $parameters = array()) {
$this->statement = $this->qomFactory->statement($statement, $parameters);
return $this;
}
/**
* Returns the statement of this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
public function getStatement() {
return $this->statement;
}
/**
* Gets the constraint for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface|NULL the constraint, or null if none
* @api
*/
public function getConstraint() {
return $this->constraint;
}
/**
* Performs a logical conjunction of the given constraints. The method takes one or more contraints and concatenates them with a boolean AND.
* It also scepts a single array of constraints to be concatenated.
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface
* @api
*/
public function logicalAnd($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056288);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_and($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical disjunction of the two given constraints
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface
* @api
*/
public function logicalOr($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056289);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_or($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical negation of the given constraint
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint Constraint to negate
* @throws \RuntimeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface
* @api
*/
public function logicalNot(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint) {
return $this->qomFactory->not($constraint);
}
/**
* Returns an equals criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the equality test should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function equals($propertyName, $operand, $caseSensitive = TRUE) {
if (is_object($operand) || $caseSensitive) {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->propertyValue($propertyName, $this->getSelectorName()),
QueryInterface::OPERATOR_EQUAL_TO,
$operand
);
} else {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->lowerCase($this->qomFactory->propertyValue($propertyName, $this->getSelectorName())),
QueryInterface::OPERATOR_EQUAL_TO,
\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter')->conv_case(\TYPO3\CMS\Extbase\Persistence\Generic\Query::CHARSET, $operand, 'toLower')
);
}
return $comparison;
}
/**
* Returns a like criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the matching should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function like($propertyName, $operand, $caseSensitive = TRUE) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LIKE, $operand);
}
/**
* Returns a "contains" criterion used for matching objects against a query.
* It matches if the multivalued property contains the given operand.
*
* @param string $propertyName The name of the (multivalued) property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function contains($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_CONTAINS, $operand);
}
/**
* Returns an "in" criterion used for matching objects against a query. It
* matches if the property's value is contained in the multivalued operand.
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with, multivalued
* @throws Exception\UnexpectedTypeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function in($propertyName, $operand) {
if (!is_array($operand) && !$operand instanceof \ArrayAccess && !$operand instanceof \Traversable) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('The "in" operator must be given a multivalued operand (array, ArrayAccess, Traversable).', 1264678095);
}
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_IN, $operand);
}
/**
* Returns a less than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN, $operand);
}
/**
* Returns a less or equal than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO, $operand);
}
/**
* Returns a greater than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN, $operand);
}
/**
* Returns a greater than or equal criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO, $operand);
}
/**
* @return void
*/
public function __wakeup() {
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$this->persistenceManager = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\PersistenceManagerInterface');
$this->dataMapper = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapper');
$this->qomFactory = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\QueryObjectModelFactory');
}
/**
* @return array
*/
public function __sleep() {
return array('type', 'source', 'constraint', 'statement', 'orderings', 'limit', 'offset', 'querySettings');
}
/**
* Returns the query result count.
*
* @return integer The query result count
* @api
*/
public function count() {
return $this->execute()->count();
}
/**
* Returns an "isEmpty" criterion used for matching objects against a query.
* It matches if the multivalued property contains no values or is NULL.
*
* @param string $propertyName The name of the multivalued property to compare against
* @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException
* @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException if used on a single-valued property
* @return bool
* @api
*/
public function isEmpty($propertyName) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException(__METHOD__);
}
}
| federicobernardin/labs | typo3/sysext/extbase/Classes/Persistence/Generic/Query.php | PHP | gpl-2.0 | 18,075 |
<?php
/**
* @version 1.0.0
* @package com_oauth
* @copyright Copyright (C) 2011 - 2013 Slashes & Dots Sdn Bhd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Offiria Team
*/
// No direct access
defined('_JEXEC') or die;
/**
* HTML View class for the Oauth component
*/
class OauthViewOauth extends OauthView
{
/**
* The purpose of this view is to retrieve the token generated for the app
* Process flow:
* 1) Navigate to index.php/component/oauth/?view=oauth&task=authenticate&appId=[appId]
* 2) Get the device approved
* 3) Run in the background to retrieve the token generated in this view
*/
public function display() {
$model = OauthFactory::getModel('application');
$token = $model->getAppToken(JRequest::getVar('appId'));
// make sure only the token belongs to the user will be generate
if ($model->isAppBelongToUser(JRequest::getVar('appId'))) {
$vals['token'] = $token;
echo json_encode($vals);
}
exit;
}
} | epireve/bib | components/com_oauth/views/oauth/view.json.php | PHP | gpl-2.0 | 1,035 |
<?php
/**
* @version $Id: controller.php 14401 2010-01-26 14:10:00Z louis $
* @package Joomla
* @subpackage Content
* @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant to the
* GNU General Public License, and as distributed it includes or is derivative
* of works licensed under the GNU General Public License or other free or open
* source software licenses. See COPYRIGHT.php for copyright notices and
* details.
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Content Component Controller
*
* @package Joomla
* @subpackage Content
* @since 1.5
*/
class ContentController extends JController
{
/**
* Method to show an article as the main page display
*
* @access public
* @since 1.5
*/
function display()
{
JHTML::_('behavior.caption');
// Set a default view if none exists
if ( ! JRequest::getCmd( 'view' ) ) {
$default = JRequest::getInt('id') ? 'article' : 'frontpage';
JRequest::setVar('view', $default );
}
// View caching logic -- simple... are we logged in?
$user = &JFactory::getUser();
$view = JRequest::getVar('view');
$viewcache = JRequest::getVar('viewcache',1,'POST','INT');
if ($user->get('id') ||
($view == 'category' && JRequest::getVar('layout') != 'blog' && $viewcache == 0) ||
$view == 'archive' && $viewcache == 0) {
parent::display(false);
} else {
parent::display(true);
}
}
/**
* Edits an article
*
* @access public
* @since 1.5
*/
function edit()
{
$user =& JFactory::getUser();
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
// Create the view
$view = & $this->getView('article', 'html');
// Get/Create the model
$model = & $this->getModel('Article');
// new record
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if( $model->get('id') > 1 && $user->get('gid') <= 19 && $model->get('created_by') != $user->id ) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if ( $model->isCheckedOut($user->get('id')))
{
$msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The item'), $model->get('title'));
$this->setRedirect(JRoute::_('index.php?view=article&id='.$model->get('id'), false), $msg);
return;
}
//Checkout the article
$model->checkout();
// Push the model into the view (as default)
$view->setModel($model, true);
// Set the layout
$view->setLayout('form');
// Display the view
$view->display();
}
/**
* Saves the content item an edit form submit
*
* @todo
*/
function save()
{
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
// Initialize variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
$task = JRequest::getVar('task', null, 'default', 'cmd');
// Make sure you are logged in and have the necessary access rights
if ($user->get('gid') < 19) {
JError::raiseError( 403, JText::_('ALERTNOTAUTH') );
return;
}
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
//get data from the request
$model = $this->getModel('article');
//get data from request
$post = JRequest::get('post');
$post['text'] = JRequest::getVar('text', '', 'post', 'string', JREQUEST_ALLOWRAW);
//preform access checks
$isNew = ((int) $post['id'] < 1);
if ($model->store($post)) {
$msg = JText::_( 'Article Saved' );
if($isNew) {
$post['id'] = (int) $model->get('id');
}
} else {
$msg = JText::_( 'Error Saving Article' );
JError::raiseError( 500, $model->getError() );
}
// manage frontpage items
//TODO : Move this into a frontpage model
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_frontpage'.DS.'tables'.DS.'frontpage.php');
$fp = new TableFrontPage($db);
if (JRequest::getVar('frontpage', false, '', 'boolean'))
{
// toggles go to first place
if (!$fp->load($post['id']))
{
// new entry
$query = 'INSERT INTO #__content_frontpage' .
' VALUES ( '.(int) $post['id'].', 1 )';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseError( 500, $db->stderr());
}
$fp->ordering = 1;
}
}
else
{
// no frontpage mask
if (!$fp->delete($post['id'])) {
$msg .= $fp->stderr();
}
$fp->ordering = 0;
}
$fp->reorder();
$model->checkin();
// gets section name of item
$query = 'SELECT s.title' .
' FROM #__sections AS s' .
' WHERE s.scope = "content"' .
' AND s.id = ' . (int) $post['sectionid'];
$db->setQuery($query);
// gets category name of item
$section = $db->loadResult();
$query = 'SELECT c.title' .
' FROM #__categories AS c' .
' WHERE c.id = ' . (int) $post['catid'];
$db->setQuery($query);
$category = $db->loadResult();
if ($isNew)
{
// messaging for new items
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_messages'.DS.'tables'.DS.'message.php');
// load language for messaging
$lang =& JFactory::getLanguage();
$lang->load('com_messages');
$query = 'SELECT id' .
' FROM #__users' .
' WHERE sendEmail = 1';
$db->setQuery($query);
$users = $db->loadResultArray();
foreach ($users as $user_id)
{
$msg = new TableMessage($db);
$msg->send($user->get('id'), $user_id, JText::_('New Item'), JText::sprintf('ON_NEW_CONTENT', $user->get('username'), $post['title'], $section, $category));
}
} else {
// If the article isn't new, then we need to clean the cache so that our changes appear realtime :)
$cache = &JFactory::getCache('com_content');
$cache->clean();
}
if ($access->canPublish)
{
// Publishers, admins, etc just get the stock msg
$msg = JText::_('Item successfully saved.');
}
else
{
$msg = $isNew ? JText::_('THANK_SUB') : JText::_('Item successfully saved.');
}
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer, $msg);
}
/**
* Cancels an edit article operation
*
* @access public
* @since 1.5
*/
function cancel()
{
// Initialize some variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
// Get an article table object and bind post variabes to it [We don't need a full model here]
$article = & JTable::getInstance('content');
$article->bind(JRequest::get('post'));
if ($user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $article->created_by == $user->get('id'))) {
$article->checkin();
}
// If the task was edit or cancel, we go back to the content item
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer);
}
/**
* Rates an article
*
* @access public
* @since 1.5
*/
function vote()
{
$url = JRequest::getVar('url', '', 'default', 'string');
$rating = JRequest::getVar('user_rating', 0, '', 'int');
$id = JRequest::getVar('cid', 0, '', 'int');
// Get/Create the model
$model = & $this->getModel('Article' );
$model->setId($id);
if(!JURI::isInternal($url)) {
$url = JRoute::_('index.php?option=com_content&view=article&id='.$id);
}
if ($model->storeVote($rating)) {
$this->setRedirect($url, JText::_('Thanks for rating!'));
} else {
$this->setRedirect($url, JText::_('You already rated this article today!'));
}
}
/**
* Searches for an item by a key parameter
*
* @access public
* @since 1.5
*/
function findkey()
{
// Initialize variables
$db = & JFactory::getDBO();
$keyref = JRequest::getVar('keyref', null, 'default', 'cmd');
JRequest::setVar('keyref', $keyref);
// If no keyref left, throw 404
if( empty($keyref) === true ) {
JError::raiseError( 404, JText::_("Key Not Found") );
}
$keyref = $db->Quote( '%keyref='.$db->getEscaped( $keyref, true ).'%', false );
$query = 'SELECT id' .
' FROM #__content' .
' WHERE attribs LIKE '.$keyref;
$db->setQuery($query);
$id = (int) $db->loadResult();
if ($id > 0)
{
// Create the view
$view =& $this->getView('article', 'html');
// Get/Create the model
$model =& $this->getModel('Article' );
// Set the id of the article to display
$model->setId($id);
// Push the model into the view (as default)
$view->setModel($model, true);
// Display the view
$view->display();
}
else {
JError::raiseError( 404, JText::_( 'Key Not Found' ) );
}
}
/**
* Output the pagebreak dialog
*
* @access public
* @since 1.5
*/
function ins_pagebreak()
{
// Create the view
$view = & $this->getView('article', 'html');
// Set the layout
$view->setLayout('pagebreak');
// Display the view
$view->display();
}
}
| rbartolomeirb/joomlaatirb | components/com_content/controller.php | PHP | gpl-2.0 | 9,797 |
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "ci/bcEscapeAnalyzer.hpp"
#include "compiler/oopMap.hpp"
#include "opto/callGenerator.hpp"
#include "opto/callnode.hpp"
#include "opto/escape.hpp"
#include "opto/locknode.hpp"
#include "opto/machnode.hpp"
#include "opto/matcher.hpp"
#include "opto/parse.hpp"
#include "opto/regalloc.hpp"
#include "opto/regmask.hpp"
#include "opto/rootnode.hpp"
#include "opto/runtime.hpp"
// Portions of code courtesy of Clifford Click
// Optimization - Graph Style
//=============================================================================
uint StartNode::size_of() const { return sizeof(*this); }
uint StartNode::cmp( const Node &n ) const
{ return _domain == ((StartNode&)n)._domain; }
const Type *StartNode::bottom_type() const { return _domain; }
const Type *StartNode::Value(PhaseTransform *phase) const { return _domain; }
#ifndef PRODUCT
void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
#endif
//------------------------------Ideal------------------------------------------
Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------calling_convention-----------------------------
void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
}
//------------------------------Registers--------------------------------------
const RegMask &StartNode::in_RegMask(uint) const {
return RegMask::Empty;
}
//------------------------------match------------------------------------------
// Construct projections for incoming parameters, and their RegMask info
Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::FramePtr:
return new (match->C) MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
case TypeFunc::ReturnAdr:
return new (match->C) MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
case TypeFunc::Parms:
default: {
uint parm_num = proj->_con - TypeFunc::Parms;
const Type *t = _domain->field_at(proj->_con);
if (t->base() == Type::Half) // 2nd half of Longs and Doubles
return new (match->C) ConNode(Type::TOP);
uint ideal_reg = t->ideal_reg();
RegMask &rm = match->_calling_convention_mask[parm_num];
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
}
return NULL;
}
//------------------------------StartOSRNode----------------------------------
// The method start node for an on stack replacement adapter
//------------------------------osr_domain-----------------------------
const TypeTuple *StartOSRNode::osr_domain() {
const Type **fields = TypeTuple::fields(2);
fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // address of osr buffer
return TypeTuple::make(TypeFunc::Parms+1, fields);
}
//=============================================================================
const char * const ParmNode::names[TypeFunc::Parms+1] = {
"Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
};
#ifndef PRODUCT
void ParmNode::dump_spec(outputStream *st) const {
if( _con < TypeFunc::Parms ) {
st->print("%s", names[_con]);
} else {
st->print("Parm%d: ",_con-TypeFunc::Parms);
// Verbose and WizardMode dump bottom_type for all nodes
if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);
}
}
#endif
uint ParmNode::ideal_reg() const {
switch( _con ) {
case TypeFunc::Control : // fall through
case TypeFunc::I_O : // fall through
case TypeFunc::Memory : return 0;
case TypeFunc::FramePtr : // fall through
case TypeFunc::ReturnAdr: return Op_RegP;
default : assert( _con > TypeFunc::Parms, "" );
// fall through
case TypeFunc::Parms : {
// Type of argument being passed
const Type *t = in(0)->as_Start()->_domain->field_at(_con);
return t->ideal_reg();
}
}
ShouldNotReachHere();
return 0;
}
//=============================================================================
ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
init_req(TypeFunc::Control,cntrl);
init_req(TypeFunc::I_O,i_o);
init_req(TypeFunc::Memory,memory);
init_req(TypeFunc::FramePtr,frameptr);
init_req(TypeFunc::ReturnAdr,retadr);
}
Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *ReturnNode::Value( PhaseTransform *phase ) const {
return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
// Do we Match on this edge index or not? No edges on return nodes
uint ReturnNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void ReturnNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("returns");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
RethrowNode::RethrowNode(
Node* cntrl,
Node* i_o,
Node* memory,
Node* frameptr,
Node* ret_adr,
Node* exception
) : Node(TypeFunc::Parms + 1) {
init_req(TypeFunc::Control , cntrl );
init_req(TypeFunc::I_O , i_o );
init_req(TypeFunc::Memory , memory );
init_req(TypeFunc::FramePtr , frameptr );
init_req(TypeFunc::ReturnAdr, ret_adr);
init_req(TypeFunc::Parms , exception);
}
Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *RethrowNode::Value( PhaseTransform *phase ) const {
return (phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
uint RethrowNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void RethrowNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("exception");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
// Do we Match on this edge index or not? Match only target address & method
uint TailCallNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
// Do we Match on this edge index or not? Match only target address & oop
uint TailJumpNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
JVMState::JVMState(ciMethod* method, JVMState* caller) :
_method(method) {
assert(method != NULL, "must be valid call site");
_reexecute = Reexecute_Undefined;
debug_only(_bci = -99); // random garbage value
debug_only(_map = (SafePointNode*)-1);
_caller = caller;
_depth = 1 + (caller == NULL ? 0 : caller->depth());
_locoff = TypeFunc::Parms;
_stkoff = _locoff + _method->max_locals();
_monoff = _stkoff + _method->max_stack();
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
JVMState::JVMState(int stack_size) :
_method(NULL) {
_bci = InvocationEntryBci;
_reexecute = Reexecute_Undefined;
debug_only(_map = (SafePointNode*)-1);
_caller = NULL;
_depth = 1;
_locoff = TypeFunc::Parms;
_stkoff = _locoff;
_monoff = _stkoff + stack_size;
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
//--------------------------------of_depth-------------------------------------
JVMState* JVMState::of_depth(int d) const {
const JVMState* jvmp = this;
assert(0 < d && (uint)d <= depth(), "oob");
for (int skip = depth() - d; skip > 0; skip--) {
jvmp = jvmp->caller();
}
assert(jvmp->depth() == (uint)d, "found the right one");
return (JVMState*)jvmp;
}
//-----------------------------same_calls_as-----------------------------------
bool JVMState::same_calls_as(const JVMState* that) const {
if (this == that) return true;
if (this->depth() != that->depth()) return false;
const JVMState* p = this;
const JVMState* q = that;
for (;;) {
if (p->_method != q->_method) return false;
if (p->_method == NULL) return true; // bci is irrelevant
if (p->_bci != q->_bci) return false;
if (p->_reexecute != q->_reexecute) return false;
p = p->caller();
q = q->caller();
if (p == q) return true;
assert(p != NULL && q != NULL, "depth check ensures we don't run off end");
}
}
//------------------------------debug_start------------------------------------
uint JVMState::debug_start() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
return of_depth(1)->locoff();
}
//-------------------------------debug_end-------------------------------------
uint JVMState::debug_end() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
return endoff();
}
//------------------------------debug_depth------------------------------------
uint JVMState::debug_depth() const {
uint total = 0;
for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {
total += jvmp->debug_size();
}
return total;
}
#ifndef PRODUCT
//------------------------------format_helper----------------------------------
// Given an allocation (a Chaitin object) and a Node decide if the Node carries
// any defined value or not. If it does, print out the register or constant.
static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
if (n == NULL) { st->print(" NULL"); return; }
if (n->is_SafePointScalarObject()) {
// Scalar replacement.
SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
scobjs->append_if_missing(spobj);
int sco_n = scobjs->find(spobj);
assert(sco_n >= 0, "");
st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
return;
}
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
char buf[50];
regalloc->dump_register(n,buf);
st->print(" %s%d]=%s",msg,i,buf);
} else { // No register, but might be constant
const Type *t = n->bottom_type();
switch (t->base()) {
case Type::Int:
st->print(" %s%d]=#"INT32_FORMAT,msg,i,t->is_int()->get_con());
break;
case Type::AnyPtr:
assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
st->print(" %s%d]=#NULL",msg,i);
break;
case Type::AryPtr:
case Type::InstPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
break;
case Type::KlassPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));
break;
case Type::MetadataPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
break;
case Type::NarrowOop:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
break;
case Type::RawPtr:
st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
break;
case Type::DoubleCon:
st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
break;
case Type::FloatCon:
st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
break;
case Type::Long:
st->print(" %s%d]=#"INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
break;
case Type::Half:
case Type::Top:
st->print(" %s%d]=_",msg,i);
break;
default: ShouldNotReachHere();
}
}
}
//------------------------------format-----------------------------------------
void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
st->print(" #");
if (_method) {
_method->print_short_name(st);
st->print(" @ bci:%d ",_bci);
} else {
st->print_cr(" runtime stub ");
return;
}
if (n->is_MachSafePoint()) {
GrowableArray<SafePointScalarObjectNode*> scobjs;
MachSafePointNode *mcall = n->as_MachSafePoint();
uint i;
// Print locals
for (i = 0; i < (uint)loc_size(); i++)
format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
// Print stack
for (i = 0; i < (uint)stk_size(); i++) {
if ((uint)(_stkoff + i) >= mcall->len())
st->print(" oob ");
else
format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
}
for (i = 0; (int)i < nof_monitors(); i++) {
Node *box = mcall->monitor_box(this, i);
Node *obj = mcall->monitor_obj(this, i);
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(box))) {
box = BoxLockNode::box_node(box);
format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
} else {
OptoReg::Name box_reg = BoxLockNode::reg(box);
st->print(" MON-BOX%d=%s+%d",
i,
OptoReg::regname(OptoReg::c_frame_pointer),
regalloc->reg2offset(box_reg));
}
const char* obj_msg = "MON-OBJ[";
if (EliminateLocks) {
if (BoxLockNode::box_node(box)->is_eliminated())
obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
}
format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
}
for (i = 0; i < (uint)scobjs.length(); i++) {
// Scalar replaced objects.
st->cr();
st->print(" # ScObj" INT32_FORMAT " ", i);
SafePointScalarObjectNode* spobj = scobjs.at(i);
ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();
assert(cik->is_instance_klass() ||
cik->is_array_klass(), "Not supported allocation.");
ciInstanceKlass *iklass = NULL;
if (cik->is_instance_klass()) {
cik->print_name_on(st);
iklass = cik->as_instance_klass();
} else if (cik->is_type_array_klass()) {
cik->as_array_klass()->base_element_type()->print_name_on(st);
st->print("[%d]", spobj->n_fields());
} else if (cik->is_obj_array_klass()) {
ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
if (cie->is_instance_klass()) {
cie->print_name_on(st);
} else if (cie->is_type_array_klass()) {
cie->as_array_klass()->base_element_type()->print_name_on(st);
} else {
ShouldNotReachHere();
}
st->print("[%d]", spobj->n_fields());
int ndim = cik->as_array_klass()->dimension() - 1;
while (ndim-- > 0) {
st->print("[]");
}
}
st->print("={");
uint nf = spobj->n_fields();
if (nf > 0) {
uint first_ind = spobj->first_index(mcall->jvms());
Node* fld_node = mcall->in(first_ind);
ciField* cifield;
if (iklass != NULL) {
st->print(" [");
cifield = iklass->nonstatic_field_at(0);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
} else {
format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
}
for (uint j = 1; j < nf; j++) {
fld_node = mcall->in(first_ind+j);
if (iklass != NULL) {
st->print(", [");
cifield = iklass->nonstatic_field_at(j);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", j, &scobjs);
} else {
format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
}
}
}
st->print(" }");
}
}
st->cr();
if (caller() != NULL) caller()->format(regalloc, n, st);
}
void JVMState::dump_spec(outputStream *st) const {
if (_method != NULL) {
bool printed = false;
if (!Verbose) {
// The JVMS dumps make really, really long lines.
// Take out the most boring parts, which are the package prefixes.
char buf[500];
stringStream namest(buf, sizeof(buf));
_method->print_short_name(&namest);
if (namest.count() < sizeof(buf)) {
const char* name = namest.base();
if (name[0] == ' ') ++name;
const char* endcn = strchr(name, ':'); // end of class name
if (endcn == NULL) endcn = strchr(name, '(');
if (endcn == NULL) endcn = name + strlen(name);
while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
--endcn;
st->print(" %s", endcn);
printed = true;
}
}
if (!printed)
_method->print_short_name(st);
st->print(" @ bci:%d",_bci);
if(_reexecute == Reexecute_True)
st->print(" reexecute");
} else {
st->print(" runtime stub");
}
if (caller() != NULL) caller()->dump_spec(st);
}
void JVMState::dump_on(outputStream* st) const {
bool print_map = _map && !((uintptr_t)_map & 1) &&
((caller() == NULL) || (caller()->map() != _map));
if (print_map) {
if (_map->len() > _map->req()) { // _map->has_exceptions()
Node* ex = _map->in(_map->req()); // _map->next_exception()
// skip the first one; it's already being printed
while (ex != NULL && ex->len() > ex->req()) {
ex = ex->in(ex->req()); // ex->next_exception()
ex->dump(1);
}
}
_map->dump(Verbose ? 2 : 1);
}
if (caller() != NULL) {
caller()->dump_on(st);
}
st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
if (_method == NULL) {
st->print_cr("(none)");
} else {
_method->print_name(st);
st->cr();
if (bci() >= 0 && bci() < _method->code_size()) {
st->print(" bc: ");
_method->print_codes_on(bci(), bci()+1, st);
}
}
}
// Extra way to dump a jvms from the debugger,
// to avoid a bug with C++ member function calls.
void dump_jvms(JVMState* jvms) {
jvms->dump();
}
#endif
//--------------------------clone_shallow--------------------------------------
JVMState* JVMState::clone_shallow(Compile* C) const {
JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
n->set_bci(_bci);
n->_reexecute = _reexecute;
n->set_locoff(_locoff);
n->set_stkoff(_stkoff);
n->set_monoff(_monoff);
n->set_scloff(_scloff);
n->set_endoff(_endoff);
n->set_sp(_sp);
n->set_map(_map);
return n;
}
//---------------------------clone_deep----------------------------------------
JVMState* JVMState::clone_deep(Compile* C) const {
JVMState* n = clone_shallow(C);
for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {
p->_caller = p->_caller->clone_shallow(C);
}
assert(n->depth() == depth(), "sanity");
assert(n->debug_depth() == debug_depth(), "sanity");
return n;
}
/**
* Reset map for all callers
*/
void JVMState::set_map_deep(SafePointNode* map) {
for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {
p->set_map(map);
}
}
// Adapt offsets in in-array after adding or removing an edge.
// Prerequisite is that the JVMState is used by only one node.
void JVMState::adapt_position(int delta) {
for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {
jvms->set_locoff(jvms->locoff() + delta);
jvms->set_stkoff(jvms->stkoff() + delta);
jvms->set_monoff(jvms->monoff() + delta);
jvms->set_scloff(jvms->scloff() + delta);
jvms->set_endoff(jvms->endoff() + delta);
}
}
// Mirror the stack size calculation in the deopt code
// How much stack space would we need at this point in the program in
// case of deoptimization?
int JVMState::interpreter_frame_size() const {
const JVMState* jvms = this;
int size = 0;
int callee_parameters = 0;
int callee_locals = 0;
int extra_args = method()->max_stack() - stk_size();
while (jvms != NULL) {
int locks = jvms->nof_monitors();
int temps = jvms->stk_size();
bool is_top_frame = (jvms == this);
ciMethod* method = jvms->method();
int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
temps + callee_parameters,
extra_args,
locks,
callee_parameters,
callee_locals,
is_top_frame);
size += frame_size;
callee_parameters = method->size_of_parameters();
callee_locals = method->max_locals();
extra_args = 0;
jvms = jvms->caller();
}
return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
}
//=============================================================================
uint CallNode::cmp( const Node &n ) const
{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
#ifndef PRODUCT
void CallNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("(");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
st->print(")");
}
void CallNode::dump_spec(outputStream *st) const {
st->print(" ");
tf()->dump_on(st);
if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);
if (jvms() != NULL) jvms()->dump_spec(st);
}
#endif
const Type *CallNode::bottom_type() const { return tf()->range(); }
const Type *CallNode::Value(PhaseTransform *phase) const {
if (phase->type(in(0)) == Type::TOP) return Type::TOP;
return tf()->range();
}
//------------------------------calling_convention-----------------------------
void CallNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
// Use the standard compiler calling convention
Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
}
//------------------------------match------------------------------------------
// Construct projections for control, I/O, memory-fields, ..., and
// return result(s) along with their RegMask info
Node *CallNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::Parms+1: // For LONG & DOUBLE returns
assert(tf()->_range->field_at(TypeFunc::Parms+1) == Type::HALF, "");
// 2nd half of doubles and longs
return new (match->C) MachProjNode(this,proj->_con, RegMask::Empty, (uint)OptoReg::Bad);
case TypeFunc::Parms: { // Normal returns
uint ideal_reg = tf()->range()->field_at(TypeFunc::Parms)->ideal_reg();
OptoRegPair regs = is_CallRuntime()
? match->c_return_value(ideal_reg,true) // Calls into C runtime
: match-> return_value(ideal_reg,true); // Calls into compiled Java code
RegMask rm = RegMask(regs.first());
if( OptoReg::is_valid(regs.second()) )
rm.Insert( regs.second() );
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
case TypeFunc::ReturnAdr:
case TypeFunc::FramePtr:
default:
ShouldNotReachHere();
}
return NULL;
}
// Do we Match on this edge index or not? Match no edges
uint CallNode::match_edge(uint idx) const {
return 0;
}
//
// Determine whether the call could modify the field of the specified
// instance at the specified offset.
//
bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
assert((t_oop != NULL), "sanity");
if (t_oop->is_known_instance()) {
// The instance_id is set only for scalar-replaceable allocations which
// are not passed as arguments according to Escape Analysis.
return false;
}
if (t_oop->is_ptr_to_boxed_value()) {
ciKlass* boxing_klass = t_oop->klass();
if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
// Skip unrelated boxing methods.
Node* proj = proj_out(TypeFunc::Parms);
if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
return false;
}
}
if (is_CallJava() && as_CallJava()->method() != NULL) {
ciMethod* meth = as_CallJava()->method();
if (meth->is_accessor()) {
return false;
}
// May modify (by reflection) if an boxing object is passed
// as argument or returned.
if (returns_pointer() && (proj_out(TypeFunc::Parms) != NULL)) {
Node* proj = proj_out(TypeFunc::Parms);
const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
const TypeTuple* d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
return false;
}
}
return true;
}
// Does this call have a direct reference to n other than debug information?
bool CallNode::has_non_debug_use(Node *n) {
const TypeTuple * d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
Node *arg = in(i);
if (arg == n) {
return true;
}
}
return false;
}
// Returns the unique CheckCastPP of a call
// or 'this' if there are several CheckCastPP
// or returns NULL if there is no one.
Node *CallNode::result_cast() {
Node *cast = NULL;
Node *p = proj_out(TypeFunc::Parms);
if (p == NULL)
return NULL;
for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
Node *use = p->fast_out(i);
if (use->is_CheckCastPP()) {
if (cast != NULL) {
return this; // more than 1 CheckCastPP
}
cast = use;
}
}
return cast;
}
void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj) {
projs->fallthrough_proj = NULL;
projs->fallthrough_catchproj = NULL;
projs->fallthrough_ioproj = NULL;
projs->catchall_ioproj = NULL;
projs->catchall_catchproj = NULL;
projs->fallthrough_memproj = NULL;
projs->catchall_memproj = NULL;
projs->resproj = NULL;
projs->exobj = NULL;
for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
ProjNode *pn = fast_out(i)->as_Proj();
if (pn->outcnt() == 0) continue;
switch (pn->_con) {
case TypeFunc::Control:
{
// For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
projs->fallthrough_proj = pn;
DUIterator_Fast jmax, j = pn->fast_outs(jmax);
const Node *cn = pn->fast_out(j);
if (cn->is_Catch()) {
ProjNode *cpn = NULL;
for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
cpn = cn->fast_out(k)->as_Proj();
assert(cpn->is_CatchProj(), "must be a CatchProjNode");
if (cpn->_con == CatchProjNode::fall_through_index)
projs->fallthrough_catchproj = cpn;
else {
assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
projs->catchall_catchproj = cpn;
}
}
}
break;
}
case TypeFunc::I_O:
if (pn->_is_io_use)
projs->catchall_ioproj = pn;
else
projs->fallthrough_ioproj = pn;
for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
Node* e = pn->out(j);
if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
assert(projs->exobj == NULL, "only one");
projs->exobj = e;
}
}
break;
case TypeFunc::Memory:
if (pn->_is_io_use)
projs->catchall_memproj = pn;
else
projs->fallthrough_memproj = pn;
break;
case TypeFunc::Parms:
projs->resproj = pn;
break;
default:
assert(false, "unexpected projection from allocation node.");
}
}
// The resproj may not exist because the result couuld be ignored
// and the exception object may not exist if an exception handler
// swallows the exception but all the other must exist and be found.
assert(projs->fallthrough_proj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_catchproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_ioproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_catchproj != NULL, "must be found");
if (separate_io_proj) {
assert(Compile::current()->inlining_incrementally() || projs->catchall_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_ioproj != NULL, "must be found");
}
}
Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
CallGenerator* cg = generator();
if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
// Check whether this MH handle call becomes a candidate for inlining
ciMethod* callee = cg->method();
vmIntrinsics::ID iid = callee->intrinsic_id();
if (iid == vmIntrinsics::_invokeBasic) {
if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
} else {
assert(callee->has_member_arg(), "wrong type of call?");
if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
}
}
return SafePointNode::Ideal(phase, can_reshape);
}
//=============================================================================
uint CallJavaNode::size_of() const { return sizeof(*this); }
uint CallJavaNode::cmp( const Node &n ) const {
CallJavaNode &call = (CallJavaNode&)n;
return CallNode::cmp(call) && _method == call._method;
}
#ifndef PRODUCT
void CallJavaNode::dump_spec(outputStream *st) const {
if( _method ) _method->print_short_name(st);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
uint CallStaticJavaNode::cmp( const Node &n ) const {
CallStaticJavaNode &call = (CallStaticJavaNode&)n;
return CallJavaNode::cmp(call);
}
//----------------------------uncommon_trap_request----------------------------
// If this is an uncommon trap, return the request code, else zero.
int CallStaticJavaNode::uncommon_trap_request() const {
if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
return extract_uncommon_trap_request(this);
}
return 0;
}
int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
#ifndef PRODUCT
if (!(call->req() > TypeFunc::Parms &&
call->in(TypeFunc::Parms) != NULL &&
call->in(TypeFunc::Parms)->is_Con())) {
assert(in_dump() != 0, "OK if dumping");
tty->print("[bad uncommon trap]");
return 0;
}
#endif
return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
}
#ifndef PRODUCT
void CallStaticJavaNode::dump_spec(outputStream *st) const {
st->print("# Static ");
if (_name != NULL) {
st->print("%s", _name);
int trap_req = uncommon_trap_request();
if (trap_req != 0) {
char buf[100];
st->print("(%s)",
Deoptimization::format_trap_request(buf, sizeof(buf),
trap_req));
}
st->print(" ");
}
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
uint CallDynamicJavaNode::cmp( const Node &n ) const {
CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
return CallJavaNode::cmp(call);
}
#ifndef PRODUCT
void CallDynamicJavaNode::dump_spec(outputStream *st) const {
st->print("# Dynamic ");
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallRuntimeNode::size_of() const { return sizeof(*this); }
uint CallRuntimeNode::cmp( const Node &n ) const {
CallRuntimeNode &call = (CallRuntimeNode&)n;
return CallNode::cmp(call) && !strcmp(_name,call._name);
}
#ifndef PRODUCT
void CallRuntimeNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//------------------------------calling_convention-----------------------------
void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
}
//=============================================================================
//------------------------------calling_convention-----------------------------
//=============================================================================
#ifndef PRODUCT
void CallLeafNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
assert(verify_jvms(jvms), "jvms must match");
int loc = jvms->locoff() + idx;
if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
// If current local idx is top then local idx - 1 could
// be a long/double that needs to be killed since top could
// represent the 2nd half ofthe long/double.
uint ideal = in(loc -1)->ideal_reg();
if (ideal == Op_RegD || ideal == Op_RegL) {
// set other (low index) half to top
set_req(loc - 1, in(loc));
}
}
set_req(loc, c);
}
uint SafePointNode::size_of() const { return sizeof(*this); }
uint SafePointNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
//-------------------------set_next_exception----------------------------------
void SafePointNode::set_next_exception(SafePointNode* n) {
assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
if (len() == req()) {
if (n != NULL) add_prec(n);
} else {
set_prec(req(), n);
}
}
//----------------------------next_exception-----------------------------------
SafePointNode* SafePointNode::next_exception() const {
if (len() == req()) {
return NULL;
} else {
Node* n = in(req());
assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
return (SafePointNode*) n;
}
}
//------------------------------Ideal------------------------------------------
// Skip over any collapsed Regions
Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------Identity---------------------------------------
// Remove obviously duplicate safepoints
Node *SafePointNode::Identity( PhaseTransform *phase ) {
// If you have back to back safepoints, remove one
if( in(TypeFunc::Control)->is_SafePoint() )
return in(TypeFunc::Control);
if( in(0)->is_Proj() ) {
Node *n0 = in(0)->in(0);
// Check if he is a call projection (except Leaf Call)
if( n0->is_Catch() ) {
n0 = n0->in(0)->in(0);
assert( n0->is_Call(), "expect a call here" );
}
if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
// Useless Safepoint, so remove it
return in(TypeFunc::Control);
}
}
return this;
}
//------------------------------Value------------------------------------------
const Type *SafePointNode::Value( PhaseTransform *phase ) const {
if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
return Type::CONTROL;
}
#ifndef PRODUCT
void SafePointNode::dump_spec(outputStream *st) const {
st->print(" SafePoint ");
}
#endif
const RegMask &SafePointNode::in_RegMask(uint idx) const {
if( idx < TypeFunc::Parms ) return RegMask::Empty;
// Values outside the domain represent debug info
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointNode::out_RegMask() const {
return RegMask::Empty;
}
void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
assert((int)grow_by > 0, "sanity");
int monoff = jvms->monoff();
int scloff = jvms->scloff();
int endoff = jvms->endoff();
assert(endoff == (int)req(), "no other states or debug info after me");
Node* top = Compile::current()->top();
for (uint i = 0; i < grow_by; i++) {
ins_req(monoff, top);
}
jvms->set_monoff(monoff + grow_by);
jvms->set_scloff(scloff + grow_by);
jvms->set_endoff(endoff + grow_by);
}
void SafePointNode::push_monitor(const FastLockNode *lock) {
// Add a LockNode, which points to both the original BoxLockNode (the
// stack space for the monitor) and the Object being locked.
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
assert(req() == jvms()->endoff(), "correct sizing");
int nextmon = jvms()->scloff();
if (GenerateSynchronizationCode) {
ins_req(nextmon, lock->box_node());
ins_req(nextmon+1, lock->obj_node());
} else {
Node* top = Compile::current()->top();
ins_req(nextmon, top);
ins_req(nextmon, top);
}
jvms()->set_scloff(nextmon + MonitorEdges);
jvms()->set_endoff(req());
}
void SafePointNode::pop_monitor() {
// Delete last monitor from debug info
debug_only(int num_before_pop = jvms()->nof_monitors());
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
int scloff = jvms()->scloff();
int endoff = jvms()->endoff();
int new_scloff = scloff - MonitorEdges;
int new_endoff = endoff - MonitorEdges;
jvms()->set_scloff(new_scloff);
jvms()->set_endoff(new_endoff);
while (scloff > new_scloff) del_req_ordered(--scloff);
assert(jvms()->nof_monitors() == num_before_pop-1, "");
}
Node *SafePointNode::peek_monitor_box() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_box(jvms(), mon);
}
Node *SafePointNode::peek_monitor_obj() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_obj(jvms(), mon);
}
// Do we Match on this edge index or not? Match no edges
uint SafePointNode::match_edge(uint idx) const {
if( !needs_polling_address_input() )
return 0;
return (TypeFunc::Parms == idx);
}
//============== SafePointScalarObjectNode ==============
SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
#ifdef ASSERT
AllocateNode* alloc,
#endif
uint first_index,
uint n_fields) :
TypeNode(tp, 1), // 1 control input -- seems required. Get from root.
#ifdef ASSERT
_alloc(alloc),
#endif
_first_index(first_index),
_n_fields(n_fields)
{
init_class_id(Class_SafePointScalarObject);
}
// Do not allow value-numbering for SafePointScalarObject node.
uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
uint SafePointScalarObjectNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
uint SafePointScalarObjectNode::ideal_reg() const {
return 0; // No matching to machine instruction
}
const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointScalarObjectNode::out_RegMask() const {
return RegMask::Empty;
}
uint SafePointScalarObjectNode::match_edge(uint idx) const {
return 0;
}
SafePointScalarObjectNode*
SafePointScalarObjectNode::clone(Dict* sosn_map) const {
void* cached = (*sosn_map)[(void*)this];
if (cached != NULL) {
return (SafePointScalarObjectNode*)cached;
}
SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
sosn_map->Insert((void*)this, (void*)res);
return res;
}
#ifndef PRODUCT
void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
st->print(" # fields@[%d..%d]", first_index(),
first_index() + n_fields() - 1);
}
#endif
//=============================================================================
uint AllocateNode::size_of() const { return sizeof(*this); }
AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
Node *ctrl, Node *mem, Node *abio,
Node *size, Node *klass_node, Node *initial_test)
: CallNode(atype, NULL, TypeRawPtr::BOTTOM)
{
init_class_id(Class_Allocate);
init_flags(Flag_is_macro);
_is_scalar_replaceable = false;
_is_non_escaping = false;
Node *topnode = C->top();
init_req( TypeFunc::Control , ctrl );
init_req( TypeFunc::I_O , abio );
init_req( TypeFunc::Memory , mem );
init_req( TypeFunc::ReturnAdr, topnode );
init_req( TypeFunc::FramePtr , topnode );
init_req( AllocSize , size);
init_req( KlassNode , klass_node);
init_req( InitialTest , initial_test);
init_req( ALength , topnode);
C->add_macro_node(this);
}
//=============================================================================
Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
if (remove_dead_region(phase, can_reshape)) return this;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
const Type* type = phase->type(Ideal_length());
if (type->isa_int() && type->is_int()->_hi < 0) {
if (can_reshape) {
PhaseIterGVN *igvn = phase->is_IterGVN();
// Unreachable fall through path (negative array length),
// the allocation can only throw so disconnect it.
Node* proj = proj_out(TypeFunc::Control);
Node* catchproj = NULL;
if (proj != NULL) {
for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
Node *cn = proj->fast_out(i);
if (cn->is_Catch()) {
catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
break;
}
}
}
if (catchproj != NULL && catchproj->outcnt() > 0 &&
(catchproj->outcnt() > 1 ||
catchproj->unique_out()->Opcode() != Op_Halt)) {
assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
Node* nproj = catchproj->clone();
igvn->register_new_node_with_optimizer(nproj);
Node *frame = new (phase->C) ParmNode( phase->C->start(), TypeFunc::FramePtr );
frame = phase->transform(frame);
// Halt & Catch Fire
Node *halt = new (phase->C) HaltNode( nproj, frame );
phase->C->root()->add_req(halt);
phase->transform(halt);
igvn->replace_node(catchproj, phase->C->top());
return this;
}
} else {
// Can't correct it during regular GVN so register for IGVN
phase->C->record_for_igvn(this);
}
}
return NULL;
}
// Retrieve the length from the AllocateArrayNode. Narrow the type with a
// CastII, if appropriate. If we are not allowed to create new nodes, and
// a CastII is appropriate, return NULL.
Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
Node *length = in(AllocateNode::ALength);
assert(length != NULL, "length is not null");
const TypeInt* length_type = phase->find_int_type(length);
const TypeAryPtr* ary_type = oop_type->isa_aryptr();
if (ary_type != NULL && length_type != NULL) {
const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
if (narrow_length_type != length_type) {
// Assert one of:
// - the narrow_length is 0
// - the narrow_length is not wider than length
assert(narrow_length_type == TypeInt::ZERO ||
length_type->is_con() && narrow_length_type->is_con() &&
(narrow_length_type->_hi <= length_type->_lo) ||
(narrow_length_type->_hi <= length_type->_hi &&
narrow_length_type->_lo >= length_type->_lo),
"narrow type must be narrower than length type");
// Return NULL if new nodes are not allowed
if (!allow_new_nodes) return NULL;
// Create a cast which is control dependent on the initialization to
// propagate the fact that the array length must be positive.
length = new (phase->C) CastIINode(length, narrow_length_type);
length->set_req(0, initialization()->proj_out(0));
}
}
return length;
}
//=============================================================================
uint LockNode::size_of() const { return sizeof(*this); }
// Redundant lock elimination
//
// There are various patterns of locking where we release and
// immediately reacquire a lock in a piece of code where no operations
// occur in between that would be observable. In those cases we can
// skip releasing and reacquiring the lock without violating any
// fairness requirements. Doing this around a loop could cause a lock
// to be held for a very long time so we concentrate on non-looping
// control flow. We also require that the operations are fully
// redundant meaning that we don't introduce new lock operations on
// some paths so to be able to eliminate it on others ala PRE. This
// would probably require some more extensive graph manipulation to
// guarantee that the memory edges were all handled correctly.
//
// Assuming p is a simple predicate which can't trap in any way and s
// is a synchronized method consider this code:
//
// s();
// if (p)
// s();
// else
// s();
// s();
//
// 1. The unlocks of the first call to s can be eliminated if the
// locks inside the then and else branches are eliminated.
//
// 2. The unlocks of the then and else branches can be eliminated if
// the lock of the final call to s is eliminated.
//
// Either of these cases subsumes the simple case of sequential control flow
//
// Addtionally we can eliminate versions without the else case:
//
// s();
// if (p)
// s();
// s();
//
// 3. In this case we eliminate the unlock of the first s, the lock
// and unlock in the then case and the lock in the final s.
//
// Note also that in all these cases the then/else pieces don't have
// to be trivial as long as they begin and end with synchronization
// operations.
//
// s();
// if (p)
// s();
// f();
// s();
// s();
//
// The code will work properly for this case, leaving in the unlock
// before the call to f and the relock after it.
//
// A potentially interesting case which isn't handled here is when the
// locking is partially redundant.
//
// s();
// if (p)
// s();
//
// This could be eliminated putting unlocking on the else case and
// eliminating the first unlock and the lock in the then side.
// Alternatively the unlock could be moved out of the then side so it
// was after the merge and the first unlock and second lock
// eliminated. This might require less manipulation of the memory
// state to get correct.
//
// Additionally we might allow work between a unlock and lock before
// giving up eliminating the locks. The current code disallows any
// conditional control flow between these operations. A formulation
// similar to partial redundancy elimination computing the
// availability of unlocking and the anticipatability of locking at a
// program point would allow detection of fully redundant locking with
// some amount of work in between. I'm not sure how often I really
// think that would occur though. Most of the cases I've seen
// indicate it's likely non-trivial work would occur in between.
// There may be other more complicated constructs where we could
// eliminate locking but I haven't seen any others appear as hot or
// interesting.
//
// Locking and unlocking have a canonical form in ideal that looks
// roughly like this:
//
// <obj>
// | \\------+
// | \ \
// | BoxLock \
// | | | \
// | | \ \
// | | FastLock
// | | /
// | | /
// | | |
//
// Lock
// |
// Proj #0
// |
// MembarAcquire
// |
// Proj #0
//
// MembarRelease
// |
// Proj #0
// |
// Unlock
// |
// Proj #0
//
//
// This code proceeds by processing Lock nodes during PhaseIterGVN
// and searching back through its control for the proper code
// patterns. Once it finds a set of lock and unlock operations to
// eliminate they are marked as eliminatable which causes the
// expansion of the Lock and Unlock macro nodes to make the operation a NOP
//
//=============================================================================
//
// Utility function to skip over uninteresting control nodes. Nodes skipped are:
// - copy regions. (These may not have been optimized away yet.)
// - eliminated locking nodes
//
static Node *next_control(Node *ctrl) {
if (ctrl == NULL)
return NULL;
while (1) {
if (ctrl->is_Region()) {
RegionNode *r = ctrl->as_Region();
Node *n = r->is_copy();
if (n == NULL)
break; // hit a region, return it
else
ctrl = n;
} else if (ctrl->is_Proj()) {
Node *in0 = ctrl->in(0);
if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
ctrl = in0->in(0);
} else {
break;
}
} else {
break; // found an interesting control
}
}
return ctrl;
}
//
// Given a control, see if it's the control projection of an Unlock which
// operating on the same object as lock.
//
bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
Node *n = ctrl_proj->in(0);
if (n != NULL && n->is_Unlock()) {
UnlockNode *unlock = n->as_Unlock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
!unlock->is_eliminated()) {
lock_ops.append(unlock);
return true;
}
}
}
return false;
}
//
// Find the lock matching an unlock. Returns null if a safepoint
// or complicated control is encountered first.
LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
LockNode *lock_result = NULL;
// find the matching lock, or an intervening safepoint
Node *ctrl = next_control(unlock->in(0));
while (1) {
assert(ctrl != NULL, "invalid control graph");
assert(!ctrl->is_Start(), "missing lock for unlock");
if (ctrl->is_top()) break; // dead control path
if (ctrl->is_Proj()) ctrl = ctrl->in(0);
if (ctrl->is_SafePoint()) {
break; // found a safepoint (may be the lock we are searching for)
} else if (ctrl->is_Region()) {
// Check for a simple diamond pattern. Punt on anything more complicated
if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
Node *in1 = next_control(ctrl->in(1));
Node *in2 = next_control(ctrl->in(2));
if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
(in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
ctrl = next_control(in1->in(0)->in(0));
} else {
break;
}
} else {
break;
}
} else {
ctrl = next_control(ctrl->in(0)); // keep searching
}
}
if (ctrl->is_Lock()) {
LockNode *lock = ctrl->as_Lock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
lock_result = lock;
}
}
return lock_result;
}
// This code corresponds to case 3 above.
bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
Node* if_node = node->in(0);
bool if_true = node->is_IfTrue();
if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
Node *lock_ctrl = next_control(if_node->in(0));
if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
Node* lock1_node = NULL;
ProjNode* proj = if_node->as_If()->proj_out(!if_true);
if (if_true) {
if (proj->is_IfFalse() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
} else {
if (proj->is_IfTrue() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
}
if (lock1_node != NULL && lock1_node->is_Lock()) {
LockNode *lock1 = lock1_node->as_Lock();
if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
!lock1->is_eliminated()) {
lock_ops.append(lock1);
return true;
}
}
}
}
lock_ops.trunc_to(0);
return false;
}
bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
// check each control merging at this point for a matching unlock.
// in(0) should be self edge so skip it.
for (int i = 1; i < (int)region->req(); i++) {
Node *in_node = next_control(region->in(i));
if (in_node != NULL) {
if (find_matching_unlock(in_node, lock, lock_ops)) {
// found a match so keep on checking.
continue;
} else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
continue;
}
// If we fall through to here then it was some kind of node we
// don't understand or there wasn't a matching unlock, so give
// up trying to merge locks.
lock_ops.trunc_to(0);
return false;
}
}
return true;
}
#ifndef PRODUCT
//
// Create a counter which counts the number of times this lock is acquired
//
void AbstractLockNode::create_lock_counter(JVMState* state) {
_counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
}
void AbstractLockNode::set_eliminated_lock_counter() {
if (_counter) {
// Update the counter to indicate that this lock was eliminated.
// The counter update code will stay around even though the
// optimizer will eliminate the lock operation itself.
_counter->set_tag(NamedCounter::EliminatedLockCounter);
}
}
#endif
//=============================================================================
Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this lock. We don't actually
// remove the locking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the lock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are locking an unescaped object, the lock/unlock is unnecessary
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
return result;
}
//
// Try lock coarsening
//
PhaseIterGVN* iter = phase->is_IterGVN();
if (iter != NULL && !is_eliminated()) {
GrowableArray<AbstractLockNode*> lock_ops;
Node *ctrl = next_control(in(0));
// now search back for a matching Unlock
if (find_matching_unlock(ctrl, this, lock_ops)) {
// found an unlock directly preceding this lock. This is the
// case of single unlock directly control dependent on a
// single lock which is the trivial version of case 1 or 2.
} else if (ctrl->is_Region() ) {
if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
// found lock preceded by multiple unlocks along all paths
// joining at this point which is case 3 in description above.
}
} else {
// see if this lock comes from either half of an if and the
// predecessors merges unlocks and the other half of the if
// performs a lock.
if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
// found unlock splitting to an if with locks on both branches.
}
}
if (lock_ops.length() > 0) {
// add ourselves to the list of locks to be eliminated.
lock_ops.append(this);
#ifndef PRODUCT
if (PrintEliminateLocks) {
int locks = 0;
int unlocks = 0;
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
if (lock->Opcode() == Op_Lock)
locks++;
else
unlocks++;
if (Verbose) {
lock->dump(1);
}
}
tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
}
#endif
// for each of the identified locks, mark them
// as eliminatable
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
// Mark it eliminated by coarsening and update any counters
lock->set_coarsened();
}
} else if (ctrl->is_Region() &&
iter->_worklist.member(ctrl)) {
// We weren't able to find any opportunities but the region this
// lock is control dependent on hasn't been processed yet so put
// this lock back on the worklist so we can check again once any
// region simplification has occurred.
iter->_worklist.push(this);
}
}
}
return result;
}
//=============================================================================
bool LockNode::is_nested_lock_region() {
BoxLockNode* box = box_node()->as_BoxLock();
int stk_slot = box->stack_slot();
if (stk_slot <= 0)
return false; // External lock or it is not Box (Phi node).
// Ignore complex cases: merged locks or multiple locks.
Node* obj = obj_node();
LockNode* unique_lock = NULL;
if (!box->is_simple_lock_region(&unique_lock, obj) ||
(unique_lock != this)) {
return false;
}
// Look for external lock for the same object.
SafePointNode* sfn = this->as_SafePoint();
JVMState* youngest_jvms = sfn->jvms();
int max_depth = youngest_jvms->depth();
for (int depth = 1; depth <= max_depth; depth++) {
JVMState* jvms = youngest_jvms->of_depth(depth);
int num_mon = jvms->nof_monitors();
// Loop over monitors
for (int idx = 0; idx < num_mon; idx++) {
Node* obj_node = sfn->monitor_obj(jvms, idx);
BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
return true;
}
}
}
return false;
}
//=============================================================================
uint UnlockNode::size_of() const { return sizeof(*this); }
//=============================================================================
Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this unlock. We don't actually
// remove the unlocking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the unlock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
// Escape state is defined after Parse phase.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are unlocking an unescaped object, the lock/unlock is unnecessary.
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
}
}
return result;
}
| smarr/graal | src/share/vm/opto/callnode.cpp | C++ | gpl-2.0 | 64,301 |
<?php namespace Indikator\Backend\ReportWidgets;
use Backend\Classes\ReportWidgetBase;
use Exception;
use DB;
class Logs extends ReportWidgetBase
{
public function render()
{
try {
$this->loadData();
}
catch (Exception $ex) {
$this->vars['error'] = $ex->getMessage();
}
return $this->makePartial('widget');
}
public function defineProperties()
{
return [
'title' => [
'title' => 'backend::lang.dashboard.widget_title_label',
'default' => 'indikator.backend::lang.widgets.logs.label',
'type' => 'string',
'validationPattern' => '^.+$',
'validationMessage' => 'backend::lang.dashboard.widget_title_error'
],
'access' => [
'title' => 'indikator.backend::lang.properties.access',
'default' => true,
'type' => 'checkbox'
],
'event' => [
'title' => 'indikator.backend::lang.properties.event',
'default' => true,
'type' => 'checkbox'
],
'request' => [
'title' => 'indikator.backend::lang.properties.request',
'default' => true,
'type' => 'checkbox'
],
'total' => [
'title' => 'indikator.backend::lang.properties.total',
'default' => true,
'type' => 'checkbox'
]
];
}
protected function loadData()
{
$this->vars['access'] = DB::table('backend_access_log')->count();
$this->vars['event'] = DB::table('system_event_logs')->count();
$this->vars['request'] = DB::table('system_request_logs')->count();
}
}
| janusnic/Portfolio | hostweb/kernel/plugins/indikator/backend/reportwidgets/Logs.php | PHP | gpl-2.0 | 2,006 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.rm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class rep_movsb_a32 extends Executable
{
final int segIndex;
public rep_movsb_a32(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
segIndex = Prefices.getSegment(prefices, Processor.DS_INDEX);
}
public Branch execute(Processor cpu)
{
Segment seg = cpu.segs[segIndex];
StaticOpcodes.rep_movsb_a32(cpu, seg);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/rm/rep_movsb_a32.java | Java | gpl-2.0 | 1,819 |
#! /usr/local/bin/ruby -Kn
# usage: exyacc.rb [yaccfiles]
# this is coverted from exyacc.pl in the camel book
ARGF.each(nil) do |source|
sbeg = source.index("\n%%") + 1
send = source.rindex("\n%%") + 1
grammar = source[sbeg, send-sbeg]
grammar.sub!(/.*\n/, "")
grammar.gsub!(/'\{'/, "'\001'")
grammar.gsub!(/'\}'/, "'\002'")
grammar.gsub!(%r{\*/}, "\003\003")
grammar.gsub!(%r{/\*[^\003]*\003\003}, '')
while grammar.gsub!(/\{[^{}]*\}/, ''); end
grammar.gsub!(/'\001'/, "'{'")
grammar.gsub!(/'\002'/, "'}'")
while grammar.gsub!(/^[ \t]*\n(\s)/, '\1'); end
grammar.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
print grammar
end
| atmark-techno/atmark-dist | user/ruby/ruby-2.1.2/sample/exyacc.rb | Ruby | gpl-2.0 | 648 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package quest.beluslan;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.world.zone.ZoneName;
/**
* @author Ritsu
*
*/
public class _2533BeritrasCurse extends QuestHandler {
private final static int questId = 2533;
public _2533BeritrasCurse() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(204801).addOnQuestStart(questId); //Gigrite
qe.registerQuestNpc(204801).addOnTalkEvent(questId);
qe.registerQuestItem(182204425, questId);//Empty Durable Potion Bottle
qe.registerOnQuestTimerEnd(questId);
}
@Override
public HandlerResult onItemUseEvent(final QuestEnv env, Item item) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
if (player.isInsideZone(ZoneName.get("BERITRAS_WEAPON_220040000"))) {
QuestService.questTimerStart(env, 300);
return HandlerResult.fromBoolean(useQuestItem(env, item, 0, 1, false, 182204426, 1, 0));
}
}
return HandlerResult.SUCCESS; // ??
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
}
final QuestState qs = player.getQuestStateList().getQuestState(questId);
DialogAction dialog = env.getDialog();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 204801) {
if (dialog == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 4762);
} else if (dialog == DialogAction.QUEST_ACCEPT_1) {
if (!giveQuestItem(env, 182204425, 1)) {
return true;
}
return sendQuestStartDialog(env);
} else {
return sendQuestStartDialog(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 204801) {
switch (dialog) {
case QUEST_SELECT:
if (var == 1) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 1352);
}
case SELECT_QUEST_REWARD: {
QuestService.questTimerEnd(env);
return sendQuestDialog(env, 5);
}
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 204801) {
return sendQuestEndDialog(env);
}
}
return false;
}
@Override
public boolean onQuestTimerEndEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
removeQuestItem(env, 182204426, 1);
QuestService.abandonQuest(player, questId);
player.getController().updateNearbyQuests();
return true;
}
return false;
}
}
| GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/quest/beluslan/_2533BeritrasCurse.java | Java | gpl-2.0 | 5,403 |
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: form.php<br /><br />
*
* This is a very simple form sending a username and password.<br />
* It demonstrates how you can integrate the image script into your code.<br />
* By creating a new instance of the class and passing the user entered code as the only parameter, you can then immediately call $obj->checkCode() which will return true if the code is correct, or false otherwise.<br />
*
* This library 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 2.1 of the License, or any later version.<br /><br />
*
* This library 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.<br /><br />
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<br /><br />
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2007 Drew Phillips
* @author drew010 <drew@drew-phillips.com>
* @version 1.0.3.1 (March 23, 2008)
* @package Securimage
*
*/ ?>
<html>
<head>
<title>Securimage Test Form</title>
</head>
<body>
<?php
if (empty($_POST)) { ?>
<form method="POST">
Username:<br />
<input type="text" name="username" /><br />
Password:<br />
<input type="text" name="password" /><br />
<!-- pass a session id to the query string of the script to prevent ie caching -->
<img src="securimage_show.php?sid=<?php echo md5(uniqid(time())); ?>"><br />
<input type="text" name="code" /><br />
<input type="submit" value="Submit Form" />
</form>
<?php
} else { //form is posted
include("securimage.php");
$img = new Securimage();
$valid = $img->check($_POST['code']);
if($valid == true) {
echo "<center>Thanks, you entered the correct code.</center>";
} else {
echo "<center>Sorry, the code you entered was invalid. <a href=\"javascript:history.go(-1)\">Go back</a> to try again.</center>";
}
}
?>
</body>
</html>
| HadoDokis/OpenUpload | plugins/securimage/example_form.php | PHP | gpl-2.0 | 2,824 |
<p>No API Key or List Id Exist!</p> | xTesseracTx/WP-AromatikaWebsite | wp-content/plugins/yikes-inc-easy-mailchimp-extender/templates/shortcode_error_data.php | PHP | gpl-2.0 | 35 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.api;
import org.opennms.netmgt.model.OnmsMemo;
/**
* @author <a href="mailto:Markus@OpenNMS.com">Markus Neumann</a>
*/
public interface MemoDao extends OnmsDao<OnmsMemo, Integer> {
}
| rfdrake/opennms | opennms-dao-api/src/main/java/org/opennms/netmgt/dao/api/MemoDao.java | Java | gpl-2.0 | 1,404 |
<div>
{% for new in news %}
<div widget-toggle="news" id_widget_note="{{new.id_article}}">
<h2 change_key="title" replace="input">{{new.title}}</h2>
<div change_key="content" replace="ck">{{new.content}}</div>
</div>
{% endfor %}
<br clear="both">
</div> | akudryav/cms | v/themes/ura/widgets/v_news.php | PHP | gpl-2.0 | 286 |
package lejos.robotics.mapping;
import java.io.*;
import java.util.ArrayList;
import lejos.geom.Line;
import lejos.geom.Rectangle;
/*
* WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS.
* DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT.
*/
/**
* <p>This class loads map data from a Shapefile and produces a LineMap object, which can
* be used by the leJOS navigation package.</p>
*
* <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you
* have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and
* .dbf. The only file used by this class is .shp.</p>
*
* <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't
* mix polylines with polygons.</p>
*
* <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with
* points (only lines) so points and multipoints are discarded.</p>
*
* @author BB
*
*/
public class ShapefileLoader {
/* OTHER POTENTIAL MAP FILE FORMATS TO ADD:
* (none have really been researched yet for viability)
* KML
* GML
* WMS? (more of a service than a file)
* MIF/MID (MapInfo)
* SVG (Scalable Vector Graphics)
* EPS (Encapsulated Post Script)
* DXF (Autodesk)
* AI (Adobe Illustrator)
*
*/
// 2D shape types types:
private static final byte NULL_SHAPE = 0;
private static final byte POINT = 1;
private static final byte POLYLINE = 3;
private static final byte POLYGON = 5;
private static final byte MULTIPOINT = 8;
private final int SHAPEFILE_ID = 0x0000270a;
DataInputStream data_is = null;
/**
* Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream
* which points to the *.shp file containing the map data.
* @param in
*/
public ShapefileLoader(InputStream in) {
this.data_is = new DataInputStream(in);
}
/**
* Retrieves a LineMap object from the Shapefile input stream.
* @return the line map
* @throws IOException
*/
public LineMap readLineMap() throws IOException {
ArrayList <Line> lines = new ArrayList <Line> ();
int fileCode = data_is.readInt(); // Big Endian
if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile");
data_is.skipBytes(20); // Five int32 unused by Shapefile
/*int fileLength =*/ data_is.readInt();
//System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows.
/*int version =*/ readLEInt();
//System.out.println("Version: " + version);
/*int shapeType =*/ readLEInt();
//System.out.println("Shape type: " + shapeType);
// These x and y min/max values define bounding rectangle:
double xMin = readLEDouble();
double yMin = readLEDouble();
double xMax = readLEDouble();
double yMax = readLEDouble();
// Create bounding rectangle:
Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin));
/*double zMin =*/ readLEDouble();
/*double zMax =*/ readLEDouble();
/*double mMin =*/ readLEDouble();
/*double mMax =*/ readLEDouble();
// TODO These values seem to be rounded down to nearest 0.5. Must round them up?
//System.out.println("Xmin " + xMin + " Ymin " + yMin);
//System.out.println("Xmax " + xMax + " Ymax " + yMax);
try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding.
while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition.
// NOW ONTO READING INDIVIDUAL SHAPES:
// Record Header (2 values):
/*int recordNum =*/ data_is.readInt();
int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short?
// Record (variable length depending on shape type):
int recShapeType = readLEInt();
// Now to read the actual shape data
switch (recShapeType) {
case NULL_SHAPE:
break;
case POINT:
// DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly.
/*double pointX =*/ readLEDouble(); // TODO: skip bytes instead
/*double pointY =*/ readLEDouble();
break;
case POLYLINE:
// NOTE: Data structure for polygon/polyline is identical. Code should work for both.
case POLYGON:
// Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole.
// Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead.
/*double polyxMin =*/ readLEDouble();
/*double polyyMin =*/ readLEDouble();
/*double polyxMax =*/ readLEDouble();
/*double polyyMax =*/ readLEDouble();
int numParts = readLEInt();
int numPoints = readLEInt();
// Retrieve array of indexes for each part in the polygon
int [] partIndex = new int[numParts];
for(int i=0;i<numParts;i++) {
partIndex[i] = readLEInt();
}
// Now go through numParts times pulling out points
double firstX=0;
double firstY=0;
for(int i=0;i<numPoints-1;i++) {
// Could check here if onto new polygon (i = next index). If so, do something with line formation.
for(int j=0;j<numParts;j++) {
if(i == partIndex[j]) {
firstX = readLEDouble();
firstY = readLEDouble();
continue;
}
}
double secondX = readLEDouble();
double secondY = readLEDouble();
Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY);
lines.add(myLine);
firstX = secondX;
firstY = secondY;
}
break;
case MULTIPOINT:
// TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes?
/*double multixMin = */readLEDouble();
/*double multiyMin = */readLEDouble();
/*double multixMax = */readLEDouble();
/*double multiyMax = */readLEDouble();
int multiPoints = readLEInt();
double [] xVals = new double[multiPoints];
double [] yVals = new double[multiPoints];
for(int i=0;i<multiPoints;i++) {
xVals[i] = readLEDouble();
yVals[i] = readLEDouble();
}
break;
default:
// IGNORE REST OF SHAPE TYPES and skip over data using recordLen value
//System.out.println("Some other unknown shape");
data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point
}
} // END OF WHILE
} catch(EOFException e) {
// End of File, just needs to continue
}
Line [] arrList = new Line [lines.size()];
return new LineMap(lines.toArray(arrList), rect);
}
/**
* Translates a little endian int into a big endian int
*
* @return int A big endian int
*/
private int readLEInt() throws IOException {
int byte1, byte2, byte3, byte4;
synchronized (this) {
byte1 = data_is.read();
byte2 = data_is.read();
byte3 = data_is.read();
byte4 = data_is.read();
}
if (byte4 == -1) {
throw new EOFException();
}
return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
/**
* Reads a little endian double into a big endian double
*
* @return double A big endian double
*/
private final double readLEDouble() throws IOException {
return Double.longBitsToDouble(this.readLELong());
}
/**
* Translates a little endian long into a big endian long
*
* @return long A big endian long
*/
private long readLELong() throws IOException {
long byte1 = data_is.read();
long byte2 = data_is.read();
long byte3 = data_is.read();
long byte4 = data_is.read();
long byte5 = data_is.read();
long byte6 = data_is.read();
long byte7 = data_is.read();
long byte8 = data_is.read();
if (byte8 == -1) {
throw new EOFException();
}
return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32)
+ (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
}
| atsoc0ocsav/IEEE-Firefighter | ieeefirefighter-beta/pc/pccomm-src/lejos/robotics/mapping/ShapefileLoader.java | Java | gpl-2.0 | 9,323 |
<?php
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2013 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
$queue = str_replace("_", " ", substr($servicedesc, 6));
$opt[1] = "--vertical-label 'Queue length' -l0 --title \"$hostname / Exchange Queue: $queue\" ";
$def[1] = "DEF:length=$RRDFILE[1]:$DS[1]:MAX ";
$def[1] .= "AREA:length#6090ff:\"length\" ";
$def[1] .= "LINE:length#304f80 ";
$def[1] .= "GPRINT:length:LAST:\"last\: %.0lf %s\" ";
$def[1] .= "GPRINT:length:AVERAGE:\"average\: %.0lf %s\" ";
$def[1] .= "GPRINT:length:MAX:\"max\:%.0lf %s\\n\" ";
?>
| opinkerfi/check_mk | pnp-templates/check_mk-winperf_msx_queues.php | PHP | gpl-2.0 | 1,870 |
<?php
/**
* @file
* Contains \Drupal\google_analytics_reports\Routing\RouteSubscriber.
*/
namespace Drupal\google_analytics_reports\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for google analytics reports routes.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('google_analytics_reports_api.settings')) {
$route->setDefault('_form', 'Drupal\google_analytics_reports\Form\GoogleAnalyticsReportsAdminSettingsForm');
}
}
}
| yonashaile/google_analytics_reports | src/Routing/RouteSubscriber.php | PHP | gpl-2.0 | 651 |
<?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\AdsApi\Examples\AdWords\v201609\Reporting;
require '../../../../vendor/autoload.php';
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201609\ReportDownloader;
use Google\AdsApi\AdWords\Reporting\v201609\DownloadFormat;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
/**
* Downloads CRITERIA_PERFORMANCE_REPORT for the specified client customer ID.
*/
class DownloadCriteriaReportWithAwql {
public static function runExample(AdWordsSession $session, $reportFormat) {
// Create report query to get the data for last 7 days.
$reportQuery = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
. 'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT '
. 'WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS';
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
$reportQuery, $reportFormat);
print "Report was downloaded and printed below:\n";
print $reportDownloadResult->getAsString();
}
public static function main() {
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// See: ReportSettingsBuilder for more options (e.g., suppress headers)
// or set them in your adsapi_php.ini file.
$reportSettings = (new ReportSettingsBuilder())
->fromFile()
->includeZeroImpressions(false)
->build();
// See: AdWordsSessionBuilder for setting a client customer ID that is
// different from that specified in your adsapi_php.ini file.
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withReportSettings($reportSettings)
->build();
self::runExample($session, DownloadFormat::CSV);
}
}
DownloadCriteriaReportWithAwql::main();
| renshuki/dfp-manager | vendor/googleads/googleads-php-lib/examples/AdWords/v201609/Reporting/DownloadCriteriaReportWithAwql.php | PHP | gpl-2.0 | 2,811 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
\*---------------------------------------------------------------------------*/
#include "kinematicCloud.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(kinematicCloud, 0);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::kinematicCloud::kinematicCloud()
{}
// * * * * * * * * * * * * * * * * Destructors * * * * * * * * * * * * * * //
Foam::kinematicCloud::~kinematicCloud()
{}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev | src/lagrangian/intermediate/clouds/baseClasses/kinematicCloud/kinematicCloud.C | C++ | gpl-2.0 | 1,724 |
<?php
if(!function_exists ('ew_code')){
function ew_code($atts,$content = false){
extract(shortcode_atts(array(
),$atts));
//add_filter('the_content','ew_do_shortcode',1001);
return "<div class='border-code'><div class='background-code'><pre class='code'>".htmlspecialchars($content)."</pre></div></div>";
}
}
add_shortcode('code','ew_code');
?> | DiegoUX/recubre | wp-content/themes/recubre/framework/shortcodes/code.php | PHP | gpl-2.0 | 356 |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// 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. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <impl/Kokkos_Utilities.hpp> // type_list
#include <traits/Kokkos_Traits_fwd.hpp>
#ifndef KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
#define KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
namespace Kokkos {
namespace Impl {
//==============================================================================
// <editor-fold desc="Adapter for replacing/adding a trait"> {{{1
//------------------------------------------------------------------------------
// General strategy: given a TraitSpecification, go through the entries in the
// parameter pack of the policy template and find the first one that returns
// `true` for the nested `trait_matches_specification` variable template. If
// that nested variable template is not found these overloads should be safely
// ignored, and the trait can specialize PolicyTraitAdapterImpl to get the
// desired behavior.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <editor-fold desc="PolicyTraitMatcher"> {{{2
// To handle the WorkTag case, we need more than just a predicate; we need
// something that we can default to in the unspecialized case, just like we
// do for AnalyzeExecPolicy
template <class TraitSpec, class Trait, class Enable = void>
struct PolicyTraitMatcher;
template <class TraitSpec, class Trait>
struct PolicyTraitMatcher<
TraitSpec, Trait,
std::enable_if_t<
TraitSpec::template trait_matches_specification<Trait>::value>>
: std::true_type {};
// </editor-fold> end PolicyTraitMatcher }}}2
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <editor-fold desc="PolicyTraitAdaptorImpl specializations"> {{{2
// Matching version, replace the trait
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class MatchingTrait,
class... ToProcessTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate, type_list<ProcessedTraits...>,
type_list<MatchingTrait, ToProcessTraits...>, NewTrait,
std::enable_if_t<PolicyTraitMatcher<TraitSpec, MatchingTrait>::value>> {
static_assert(PolicyTraitMatcher<TraitSpec, NewTrait>::value, "");
using type = PolicyTemplate<ProcessedTraits..., NewTrait, ToProcessTraits...>;
};
// Non-matching version, check the next option
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class NonMatchingTrait,
class... ToProcessTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate, type_list<ProcessedTraits...>,
type_list<NonMatchingTrait, ToProcessTraits...>, NewTrait,
std::enable_if_t<!PolicyTraitMatcher<TraitSpec, NonMatchingTrait>::value>> {
using type = typename PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate,
type_list<ProcessedTraits..., NonMatchingTrait>,
type_list<ToProcessTraits...>, NewTrait>::type;
};
// Base case: no matches found; just add the trait to the end of the list
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<TraitSpec, PolicyTemplate,
type_list<ProcessedTraits...>, type_list<>,
NewTrait> {
static_assert(PolicyTraitMatcher<TraitSpec, NewTrait>::value, "");
using type = PolicyTemplate<ProcessedTraits..., NewTrait>;
};
// </editor-fold> end PolicyTraitAdaptorImpl specializations }}}2
//------------------------------------------------------------------------------
template <class TraitSpec, template <class...> class PolicyTemplate,
class... Traits, class NewTrait>
struct PolicyTraitAdaptor<TraitSpec, PolicyTemplate<Traits...>, NewTrait>
: PolicyTraitAdaptorImpl<TraitSpec, PolicyTemplate, type_list<>,
type_list<Traits...>, NewTrait> {};
// </editor-fold> end Adapter for replacing/adding a trait }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="CRTP Base class for trait specifications"> {{{1
template <class TraitSpec>
struct TraitSpecificationBase {
using trait_specification = TraitSpec;
template <class Policy, class Trait>
using policy_with_trait =
typename PolicyTraitAdaptor<TraitSpec, Policy, Trait>::type;
};
// </editor-fold> end CRTP Base class for trait specifications }}}1
//==============================================================================
} // end namespace Impl
} // end namespace Kokkos
#endif // KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
| jeremiahyan/lammps | lib/kokkos/core/src/traits/Kokkos_PolicyTraitAdaptor.hpp | C++ | gpl-2.0 | 6,825 |
/*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Felmyst
SD%Complete: 0
SDComment:
EndScriptData */
#include "ScriptMgr.h"
#include "CellImpl.h"
#include "GridNotifiersImpl.h"
#include "InstanceScript.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ScriptedCreature.h"
#include "sunwell_plateau.h"
#include "TemporarySummon.h"
enum Yells
{
YELL_BIRTH = 0,
YELL_KILL = 1,
YELL_BREATH = 2,
YELL_TAKEOFF = 3,
YELL_BERSERK = 4,
YELL_DEATH = 5,
//YELL_KALECGOS = 6, Not used. After felmyst's death spawned and say this
};
enum Spells
{
//Aura
AURA_SUNWELL_RADIANCE = 45769,
AURA_NOXIOUS_FUMES = 47002,
//Land phase
SPELL_CLEAVE = 19983,
SPELL_CORROSION = 45866,
SPELL_GAS_NOVA = 45855,
SPELL_ENCAPSULATE_CHANNEL = 45661,
// SPELL_ENCAPSULATE_EFFECT = 45665,
// SPELL_ENCAPSULATE_AOE = 45662,
//Flight phase
SPELL_VAPOR_SELECT = 45391, // fel to player, force cast 45392, 50000y selete target
SPELL_VAPOR_SUMMON = 45392, // player summon vapor, radius around caster, 5y,
SPELL_VAPOR_FORCE = 45388, // vapor to fel, force cast 45389
SPELL_VAPOR_CHANNEL = 45389, // fel to vapor, green beam channel
SPELL_VAPOR_TRIGGER = 45411, // linked to 45389, vapor to self, trigger 45410 and 46931
SPELL_VAPOR_DAMAGE = 46931, // vapor damage, 4000
SPELL_TRAIL_SUMMON = 45410, // vapor summon trail
SPELL_TRAIL_TRIGGER = 45399, // trail to self, trigger 45402
SPELL_TRAIL_DAMAGE = 45402, // trail damage, 2000 + 2000 dot
SPELL_DEAD_SUMMON = 45400, // summon blazing dead, 5min
SPELL_DEAD_PASSIVE = 45415,
SPELL_FOG_BREATH = 45495, // fel to self, speed burst
SPELL_FOG_TRIGGER = 45582, // fog to self, trigger 45782
SPELL_FOG_FORCE = 45782, // fog to player, force cast 45714
SPELL_FOG_INFORM = 45714, // player let fel cast 45717, script effect
SPELL_FOG_CHARM = 45717, // fel to player
SPELL_FOG_CHARM2 = 45726, // link to 45717
SPELL_TRANSFORM_TRIGGER = 44885, // madrigosa to self, trigger 46350
SPELL_TRANSFORM_VISUAL = 46350, // 46411stun?
SPELL_TRANSFORM_FELMYST = 45068, // become fel
SPELL_FELMYST_SUMMON = 45069,
//Other
SPELL_BERSERK = 45078,
SPELL_CLOUD_VISUAL = 45212,
SPELL_CLOUD_SUMMON = 45884
};
enum PhaseFelmyst
{
PHASE_NONE,
PHASE_GROUND,
PHASE_FLIGHT
};
enum EventFelmyst
{
EVENT_NONE,
EVENT_BERSERK,
EVENT_CLEAVE,
EVENT_CORROSION,
EVENT_GAS_NOVA,
EVENT_ENCAPSULATE,
EVENT_FLIGHT,
EVENT_FLIGHT_SEQUENCE,
EVENT_SUMMON_DEAD,
EVENT_SUMMON_FOG
};
class boss_felmyst : public CreatureScript
{
public:
boss_felmyst() : CreatureScript("boss_felmyst") { }
struct boss_felmystAI : public ScriptedAI
{
boss_felmystAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
uiBreathCount = 0;
breathX = 0.f;
breathY = 0.f;
}
void Initialize()
{
phase = PHASE_NONE;
uiFlightCount = 0;
}
InstanceScript* instance;
PhaseFelmyst phase;
EventMap events;
uint32 uiFlightCount;
uint32 uiBreathCount;
float breathX, breathY;
void Reset() override
{
Initialize();
events.Reset();
me->SetDisableGravity(true);
me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 10);
me->SetFloatValue(UNIT_FIELD_COMBATREACH, 10);
DespawnSummons(NPC_VAPOR_TRAIL);
me->setActive(false);
instance->SetBossState(DATA_FELMYST, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_BERSERK, 600000);
me->setActive(true);
DoZoneInCombat();
DoCast(me, AURA_SUNWELL_RADIANCE, true);
DoCast(me, AURA_NOXIOUS_FUMES, true);
EnterPhase(PHASE_GROUND);
instance->SetBossState(DATA_FELMYST, IN_PROGRESS);
}
void AttackStart(Unit* who) override
{
if (phase != PHASE_FLIGHT)
ScriptedAI::AttackStart(who);
}
void MoveInLineOfSight(Unit* who) override
{
if (phase != PHASE_FLIGHT)
ScriptedAI::MoveInLineOfSight(who);
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(YELL_KILL);
}
void JustRespawned() override
{
Talk(YELL_BIRTH);
}
void JustDied(Unit* /*killer*/) override
{
Talk(YELL_DEATH);
instance->SetBossState(DATA_FELMYST, DONE);
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
// workaround for linked aura
/*if (spell->Id == SPELL_VAPOR_FORCE)
{
caster->CastSpell(caster, SPELL_VAPOR_TRIGGER, true);
}*/
// workaround for mind control
if (spell->Id == SPELL_FOG_INFORM)
{
float x, y, z;
caster->GetPosition(x, y, z);
if (Unit* summon = me->SummonCreature(NPC_DEAD, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000))
{
summon->SetMaxHealth(caster->GetMaxHealth());
summon->SetHealth(caster->GetMaxHealth());
summon->CastSpell(summon, SPELL_FOG_CHARM, true);
summon->CastSpell(summon, SPELL_FOG_CHARM2, true);
}
me->DealDamage(caster, caster->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false);
}
}
void JustSummoned(Creature* summon) override
{
if (summon->GetEntry() == NPC_DEAD)
{
summon->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM));
DoZoneInCombat(summon);
summon->CastSpell(summon, SPELL_DEAD_PASSIVE, true);
}
}
void MovementInform(uint32, uint32) override
{
if (phase == PHASE_FLIGHT)
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
}
void DamageTaken(Unit*, uint32 &damage) override
{
if (phase != PHASE_GROUND && damage >= me->GetHealth())
damage = 0;
}
void EnterPhase(PhaseFelmyst NextPhase)
{
switch (NextPhase)
{
case PHASE_GROUND:
me->CastStop(SPELL_FOG_BREATH);
me->RemoveAurasDueToSpell(SPELL_FOG_BREATH);
me->StopMoving();
me->SetSpeedRate(MOVE_RUN, 2.0f);
events.ScheduleEvent(EVENT_CLEAVE, urand(5000, 10000));
events.ScheduleEvent(EVENT_CORROSION, urand(10000, 20000));
events.ScheduleEvent(EVENT_GAS_NOVA, urand(15000, 20000));
events.ScheduleEvent(EVENT_ENCAPSULATE, urand(20000, 25000));
events.ScheduleEvent(EVENT_FLIGHT, 60000);
break;
case PHASE_FLIGHT:
me->SetDisableGravity(true);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1000);
uiFlightCount = 0;
uiBreathCount = 0;
break;
default:
break;
}
phase = NextPhase;
}
void HandleFlightSequence()
{
switch (uiFlightCount)
{
case 0:
//me->AttackStop();
me->GetMotionMaster()->Clear(false);
me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF);
me->StopMoving();
Talk(YELL_TAKEOFF);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 2000);
break;
case 1:
me->GetMotionMaster()->MovePoint(0, me->GetPositionX()+1, me->GetPositionY(), me->GetPositionZ()+10);
break;
case 2:
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
if (Creature* Vapor = me->SummonCreature(NPC_VAPOR, target->GetPositionX() - 5 + rand32() % 10, target->GetPositionY() - 5 + rand32() % 10, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 9000))
{
Vapor->AI()->AttackStart(target);
me->InterruptNonMeleeSpells(false);
DoCast(Vapor, SPELL_VAPOR_CHANNEL, false); // core bug
Vapor->CastSpell(Vapor, SPELL_VAPOR_TRIGGER, true);
}
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
}
case 3:
{
DespawnSummons(NPC_VAPOR_TRAIL);
//DoCast(me, SPELL_VAPOR_SELECT); need core support
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
//target->CastSpell(target, SPELL_VAPOR_SUMMON, true); need core support
if (Creature* pVapor = me->SummonCreature(NPC_VAPOR, target->GetPositionX() - 5 + rand32() % 10, target->GetPositionY() - 5 + rand32() % 10, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 9000))
{
if (pVapor->AI())
pVapor->AI()->AttackStart(target);
me->InterruptNonMeleeSpells(false);
DoCast(pVapor, SPELL_VAPOR_CHANNEL, false); // core bug
pVapor->CastSpell(pVapor, SPELL_VAPOR_TRIGGER, true);
}
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
}
case 4:
DespawnSummons(NPC_VAPOR_TRAIL);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
break;
case 5:
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
breathX = target->GetPositionX();
breathY = target->GetPositionY();
float x, y, z;
target->GetContactPoint(me, x, y, z, 70);
me->GetMotionMaster()->MovePoint(0, x, y, z+10);
break;
}
case 6:
me->SetFacingTo(me->GetAngle(breathX, breathY));
//DoTextEmote("takes a deep breath.", nullptr);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
case 7:
{
DoCast(me, SPELL_FOG_BREATH, true);
float x, y, z;
me->GetPosition(x, y, z);
x = 2 * breathX - x;
y = 2 * breathY - y;
me->GetMotionMaster()->MovePoint(0, x, y, z);
events.ScheduleEvent(EVENT_SUMMON_FOG, 1);
break;
}
case 8:
me->CastStop(SPELL_FOG_BREATH);
me->RemoveAurasDueToSpell(SPELL_FOG_BREATH);
++uiBreathCount;
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
if (uiBreathCount < 3)
uiFlightCount = 4;
break;
case 9:
if (Unit* target = SelectTarget(SELECT_TARGET_MAXTHREAT))
DoStartMovement(target);
else
{
EnterEvadeMode();
return;
}
break;
case 10:
me->SetDisableGravity(false);
me->HandleEmoteCommand(EMOTE_ONESHOT_LAND);
EnterPhase(PHASE_GROUND);
AttackStart(SelectTarget(SELECT_TARGET_MAXTHREAT));
break;
}
++uiFlightCount;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
{
if (phase == PHASE_FLIGHT && !me->IsInEvadeMode())
EnterEvadeMode();
return;
}
events.Update(diff);
if (me->IsNonMeleeSpellCast(false))
return;
if (phase == PHASE_GROUND)
{
switch (events.ExecuteEvent())
{
case EVENT_BERSERK:
Talk(YELL_BERSERK);
DoCast(me, SPELL_BERSERK, true);
events.ScheduleEvent(EVENT_BERSERK, 10000);
break;
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE, false);
events.ScheduleEvent(EVENT_CLEAVE, urand(5000, 10000));
break;
case EVENT_CORROSION:
DoCastVictim(SPELL_CORROSION, false);
events.ScheduleEvent(EVENT_CORROSION, urand(20000, 30000));
break;
case EVENT_GAS_NOVA:
DoCast(me, SPELL_GAS_NOVA, false);
events.ScheduleEvent(EVENT_GAS_NOVA, urand(20000, 25000));
break;
case EVENT_ENCAPSULATE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true))
DoCast(target, SPELL_ENCAPSULATE_CHANNEL, false);
events.ScheduleEvent(EVENT_ENCAPSULATE, urand(25000, 30000));
break;
case EVENT_FLIGHT:
EnterPhase(PHASE_FLIGHT);
break;
default:
DoMeleeAttackIfReady();
break;
}
}
if (phase == PHASE_FLIGHT)
{
switch (events.ExecuteEvent())
{
case EVENT_BERSERK:
Talk(YELL_BERSERK);
DoCast(me, SPELL_BERSERK, true);
break;
case EVENT_FLIGHT_SEQUENCE:
HandleFlightSequence();
break;
case EVENT_SUMMON_FOG:
{
float x, y, z;
me->GetPosition(x, y, z);
me->UpdateGroundPositionZ(x, y, z);
if (Creature* Fog = me->SummonCreature(NPC_VAPOR_TRAIL, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN, 10000))
{
Fog->RemoveAurasDueToSpell(SPELL_TRAIL_TRIGGER);
Fog->CastSpell(Fog, SPELL_FOG_TRIGGER, true);
me->CastSpell(Fog, SPELL_FOG_FORCE, true);
}
}
events.ScheduleEvent(EVENT_SUMMON_FOG, 1000);
break;
}
}
}
void DespawnSummons(uint32 entry)
{
std::list<Creature*> templist;
float x, y, z;
me->GetPosition(x, y, z);
Trinity::AllCreaturesOfEntryInRange check(me, entry, 100);
Trinity::CreatureListSearcher<Trinity::AllCreaturesOfEntryInRange> searcher(me, templist, check);
Cell::VisitGridObjects(me, searcher, me->GetGridActivationRange());
for (std::list<Creature*>::const_iterator i = templist.begin(); i != templist.end(); ++i)
{
if (entry == NPC_VAPOR_TRAIL && phase == PHASE_FLIGHT)
{
(*i)->GetPosition(x, y, z);
me->SummonCreature(NPC_DEAD, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
}
(*i)->SetVisible(false);
(*i)->DespawnOrUnsummon();
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<boss_felmystAI>(creature);
}
};
class npc_felmyst_vapor : public CreatureScript
{
public:
npc_felmyst_vapor() : CreatureScript("npc_felmyst_vapor") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<npc_felmyst_vaporAI>(creature);
}
struct npc_felmyst_vaporAI : public ScriptedAI
{
npc_felmyst_vaporAI(Creature* creature) : ScriptedAI(creature)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetSpeedRate(MOVE_RUN, 0.8f);
}
void Reset() override { }
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
//DoCast(me, SPELL_VAPOR_FORCE, true); core bug
}
void UpdateAI(uint32 /*diff*/) override
{
if (!me->GetVictim())
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
AttackStart(target);
}
};
};
class npc_felmyst_trail : public CreatureScript
{
public:
npc_felmyst_trail() : CreatureScript("npc_felmyst_trail") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<npc_felmyst_trailAI>(creature);
}
struct npc_felmyst_trailAI : public ScriptedAI
{
npc_felmyst_trailAI(Creature* creature) : ScriptedAI(creature)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
DoCast(me, SPELL_TRAIL_TRIGGER, true);
me->SetTarget(me->GetGUID());
me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.01f); // core bug
}
void Reset() override { }
void EnterCombat(Unit* /*who*/) override { }
void AttackStart(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void UpdateAI(uint32 /*diff*/) override { }
};
};
void AddSC_boss_felmyst()
{
new boss_felmyst();
new npc_felmyst_vapor();
new npc_felmyst_trail();
}
| MoistBaguette/mangosbot | src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp | C++ | gpl-2.0 | 21,344 |
/*
* Copyright (C) 1996-2016 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
#include "squid.h"
#include "anyp/PortCfg.h"
#include "comm/Connection.h"
#include "CommCalls.h"
#include "fde.h"
#include "globals.h"
/* CommCommonCbParams */
CommCommonCbParams::CommCommonCbParams(void *aData):
data(cbdataReference(aData)), conn(), flag(Comm::OK), xerrno(0), fd(-1)
{
}
CommCommonCbParams::CommCommonCbParams(const CommCommonCbParams &p):
data(cbdataReference(p.data)), conn(p.conn), flag(p.flag), xerrno(p.xerrno), fd(p.fd)
{
}
CommCommonCbParams::~CommCommonCbParams()
{
cbdataReferenceDone(data);
}
void
CommCommonCbParams::print(std::ostream &os) const
{
if (conn != NULL)
os << conn;
else
os << "FD " << fd;
if (xerrno)
os << ", errno=" << xerrno;
if (flag != Comm::OK)
os << ", flag=" << flag;
if (data)
os << ", data=" << data;
}
/* CommAcceptCbParams */
CommAcceptCbParams::CommAcceptCbParams(void *aData):
CommCommonCbParams(aData), xaction()
{
}
void
CommAcceptCbParams::print(std::ostream &os) const
{
CommCommonCbParams::print(os);
if (xaction != NULL)
os << ", " << xaction->id;
}
/* CommConnectCbParams */
CommConnectCbParams::CommConnectCbParams(void *aData):
CommCommonCbParams(aData)
{
}
bool
CommConnectCbParams::syncWithComm()
{
// drop the call if the call was scheduled before comm_close but
// is being fired after comm_close
if (fd >= 0 && fd_table[fd].closing()) {
debugs(5, 3, HERE << "dropping late connect call: FD " << fd);
return false;
}
return true; // now we are in sync and can handle the call
}
/* CommIoCbParams */
CommIoCbParams::CommIoCbParams(void *aData): CommCommonCbParams(aData),
buf(NULL), size(0)
{
}
bool
CommIoCbParams::syncWithComm()
{
// change parameters if the call was scheduled before comm_close but
// is being fired after comm_close
if ((conn->fd < 0 || fd_table[conn->fd].closing()) && flag != Comm::ERR_CLOSING) {
debugs(5, 3, HERE << "converting late call to Comm::ERR_CLOSING: " << conn);
flag = Comm::ERR_CLOSING;
}
return true; // now we are in sync and can handle the call
}
void
CommIoCbParams::print(std::ostream &os) const
{
CommCommonCbParams::print(os);
if (buf) {
os << ", size=" << size;
os << ", buf=" << (void*)buf;
}
}
/* CommCloseCbParams */
CommCloseCbParams::CommCloseCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* CommTimeoutCbParams */
CommTimeoutCbParams::CommTimeoutCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* FdeCbParams */
FdeCbParams::FdeCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* CommAcceptCbPtrFun */
CommAcceptCbPtrFun::CommAcceptCbPtrFun(IOACB *aHandler,
const CommAcceptCbParams &aParams):
CommDialerParamsT<CommAcceptCbParams>(aParams),
handler(aHandler)
{
}
CommAcceptCbPtrFun::CommAcceptCbPtrFun(const CommAcceptCbPtrFun &o):
CommDialerParamsT<CommAcceptCbParams>(o.params),
handler(o.handler)
{
}
void
CommAcceptCbPtrFun::dial()
{
handler(params);
}
void
CommAcceptCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommConnectCbPtrFun */
CommConnectCbPtrFun::CommConnectCbPtrFun(CNCB *aHandler,
const CommConnectCbParams &aParams):
CommDialerParamsT<CommConnectCbParams>(aParams),
handler(aHandler)
{
}
void
CommConnectCbPtrFun::dial()
{
handler(params.conn, params.flag, params.xerrno, params.data);
}
void
CommConnectCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommIoCbPtrFun */
CommIoCbPtrFun::CommIoCbPtrFun(IOCB *aHandler, const CommIoCbParams &aParams):
CommDialerParamsT<CommIoCbParams>(aParams),
handler(aHandler)
{
}
void
CommIoCbPtrFun::dial()
{
handler(params.conn, params.buf, params.size, params.flag, params.xerrno, params.data);
}
void
CommIoCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommCloseCbPtrFun */
CommCloseCbPtrFun::CommCloseCbPtrFun(CLCB *aHandler,
const CommCloseCbParams &aParams):
CommDialerParamsT<CommCloseCbParams>(aParams),
handler(aHandler)
{
}
void
CommCloseCbPtrFun::dial()
{
handler(params);
}
void
CommCloseCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommTimeoutCbPtrFun */
CommTimeoutCbPtrFun::CommTimeoutCbPtrFun(CTCB *aHandler,
const CommTimeoutCbParams &aParams):
CommDialerParamsT<CommTimeoutCbParams>(aParams),
handler(aHandler)
{
}
void
CommTimeoutCbPtrFun::dial()
{
handler(params);
}
void
CommTimeoutCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* FdeCbPtrFun */
FdeCbPtrFun::FdeCbPtrFun(FDECB *aHandler, const FdeCbParams &aParams) :
CommDialerParamsT<FdeCbParams>(aParams),
handler(aHandler)
{
}
void
FdeCbPtrFun::dial()
{
handler(params);
}
void
FdeCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
| saucelabs/squid3 | src/CommCalls.cc | C++ | gpl-2.0 | 5,412 |
/* Thread pool
Copyright (C) 2019-2020 Free Software Foundation, Inc.
This file is part of GDB.
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 "common-defs.h"
#if CXX_STD_THREAD
#include "gdbsupport/thread-pool.h"
#include "gdbsupport/alt-stack.h"
#include "gdbsupport/block-signals.h"
#include <algorithm>
/* On the off chance that we have the pthread library on a Windows
host, but std::thread is not using it, avoid calling
pthread_setname_np on Windows. */
#ifndef _WIN32
#ifdef HAVE_PTHREAD_SETNAME_NP
#define USE_PTHREAD_SETNAME_NP
#endif
#endif
#ifdef USE_PTHREAD_SETNAME_NP
#include <pthread.h>
/* Handle platform discrepancies in pthread_setname_np: macOS uses a
single-argument form, while Linux uses a two-argument form. NetBSD
takes a printf-style format and an argument. This wrapper handles the
difference. */
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (pthread_t, const char *, void *),
const char *name)
{
set_name (pthread_self (), "%s", const_cast<char *> (name));
}
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (pthread_t, const char *), const char *name)
{
set_name (pthread_self (), name);
}
/* The macOS man page says that pthread_setname_np returns "void", but
the headers actually declare it returning "int". */
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (const char *), const char *name)
{
set_name (name);
}
#endif /* USE_PTHREAD_SETNAME_NP */
namespace gdb
{
/* The thread pool detach()s its threads, so that the threads will not
prevent the process from exiting. However, it was discovered that
if any detached threads were still waiting on a condition variable,
then the condition variable's destructor would wait for the threads
to exit -- defeating the purpose.
Allocating the thread pool on the heap and simply "leaking" it
avoids this problem.
*/
thread_pool *thread_pool::g_thread_pool = new thread_pool ();
thread_pool::~thread_pool ()
{
/* Because this is a singleton, we don't need to clean up. The
threads are detached so that they won't prevent process exit.
And, cleaning up here would be actively harmful in at least one
case -- see the comment by the definition of g_thread_pool. */
}
void
thread_pool::set_thread_count (size_t num_threads)
{
std::lock_guard<std::mutex> guard (m_tasks_mutex);
/* If the new size is larger, start some new threads. */
if (m_thread_count < num_threads)
{
/* Ensure that signals used by gdb are blocked in the new
threads. */
block_signals blocker;
for (size_t i = m_thread_count; i < num_threads; ++i)
{
std::thread thread (&thread_pool::thread_function, this);
thread.detach ();
}
}
/* If the new size is smaller, terminate some existing threads. */
if (num_threads < m_thread_count)
{
for (size_t i = num_threads; i < m_thread_count; ++i)
m_tasks.emplace ();
m_tasks_cv.notify_all ();
}
m_thread_count = num_threads;
}
std::future<void>
thread_pool::post_task (std::function<void ()> func)
{
std::packaged_task<void ()> t (func);
std::future<void> f = t.get_future ();
if (m_thread_count == 0)
{
/* Just execute it now. */
t ();
}
else
{
std::lock_guard<std::mutex> guard (m_tasks_mutex);
m_tasks.emplace (std::move (t));
m_tasks_cv.notify_one ();
}
return f;
}
void
thread_pool::thread_function ()
{
#ifdef USE_PTHREAD_SETNAME_NP
/* This must be done here, because on macOS one can only set the
name of the current thread. */
set_thread_name (pthread_setname_np, "gdb worker");
#endif
/* Ensure that SIGSEGV is delivered to an alternate signal
stack. */
gdb::alternate_signal_stack signal_stack;
while (true)
{
optional<task> t;
{
/* We want to hold the lock while examining the task list, but
not while invoking the task function. */
std::unique_lock<std::mutex> guard (m_tasks_mutex);
while (m_tasks.empty ())
m_tasks_cv.wait (guard);
t = std::move (m_tasks.front());
m_tasks.pop ();
}
if (!t.has_value ())
break;
(*t) ();
}
}
}
#endif /* CXX_STD_THREAD */
| mattstock/binutils-bexkat1 | gdbsupport/thread-pool.cc | C++ | gpl-2.0 | 4,811 |
require 'spec_helper'
require 'boost_trust_level'
describe BoostTrustLevel do
let(:user) { Fabricate(:user, trust_level: TrustLevel.levels[:newuser]) }
let(:logger) { StaffActionLogger.new(Fabricate(:admin)) }
it "should upgrade the trust level of a user" do
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:basic], logger: logger)
boostr.save!.should be_true
user.trust_level.should == TrustLevel.levels[:basic]
end
it "should log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).with(user, TrustLevel.levels[:newuser], TrustLevel.levels[:basic]).once
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:basic], logger: logger)
boostr.save!
end
describe "demotions" do
context "for a user that has not done the requisite things to attain their trust level" do
before do
# scenario: admin mistakenly promotes user's trust level
user.update_attributes(trust_level: TrustLevel.levels[:basic])
end
it "should demote the user and log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).with(user, TrustLevel.levels[:basic], TrustLevel.levels[:newuser]).once
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:newuser], logger: logger)
boostr.save!.should be_true
user.trust_level.should == TrustLevel.levels[:newuser]
end
end
context "for a user that has done the requisite things to attain their trust level" do
before do
user.topics_entered = SiteSetting.basic_requires_topics_entered + 1
user.posts_read_count = SiteSetting.basic_requires_read_posts + 1
user.time_read = SiteSetting.basic_requires_time_spent_mins * 60
user.save!
user.update_attributes(trust_level: TrustLevel.levels[:basic])
end
it "should not demote the user and not log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).never
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:newuser], logger: logger)
expect { boostr.save! }.to raise_error(Discourse::InvalidAccess, "You attempted to demote #{user.name} to 'newuser'. However their trust level is already 'basic'. #{user.name} will remain at 'basic'")
user.trust_level.should == TrustLevel.levels[:basic]
end
end
end
end
| concordia-publishing-house/discourse | spec/components/boost_trust_level_spec.rb | Ruby | gpl-2.0 | 2,430 |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module test {
// jdk.test.resources.classes.MyResourcesProvider is in named.bundles.
requires named.bundles;
uses jdk.test.resources.classes.MyResourcesProvider;
uses jdk.test.resources.props.MyResourcesProvider;
}
| FauxFaux/jdk9-jdk | test/java/util/ResourceBundle/modules/visibility/src/test/module-info.java | Java | gpl-2.0 | 1,283 |
/*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "OutdoorPvP.h"
#include "Language.h"
#include "World.h"
#include "ObjectMgr.h"
#include "Object.h"
#include "GameObject.h"
#include "Player.h"
/**
Function that adds a player to the players of the affected outdoor pvp zones
@param player to add
@param whether zone is main outdoor pvp zone or a affected zone
*/
void OutdoorPvP::HandlePlayerEnterZone(Player* player, bool isMainZone)
{
m_zonePlayers[player->GetObjectGuid()] = isMainZone;
}
/**
Function that removes a player from the players of the affected outdoor pvp zones
@param player to remove
@param whether zone is main outdoor pvp zone or a affected zone
*/
void OutdoorPvP::HandlePlayerLeaveZone(Player* player, bool isMainZone)
{
if (m_zonePlayers.erase(player->GetObjectGuid()))
{
// remove the world state information from the player
if (isMainZone && !player->GetSession()->PlayerLogout())
SendRemoveWorldStates(player);
sLog.outDebug("Player %s left an Outdoor PvP zone", player->GetName());
}
}
/**
Function that updates the world state for all the players of the outdoor pvp zone
@param world state to update
@param new world state value
*/
void OutdoorPvP::SendUpdateWorldState(uint32 field, uint32 value)
{
for (GuidZoneMap::const_iterator itr = m_zonePlayers.begin(); itr != m_zonePlayers.end(); ++itr)
{
// only send world state update to main zone
if (!itr->second)
continue;
if (!IsMember(itr->first))
continue;
if (Player* player = sObjectMgr.GetPlayer(itr->first))
player->SendUpdateWorldState(field, value);
}
}
/**
Function that updates world state for all the players in an outdoor pvp map
@param world state it to update
@param value which should update the world state
*/
void OutdoorPvP::SendUpdateWorldStateForMap(uint32 uiField, uint32 uiValue, Map* map)
{
Map::PlayerList const& pList = map->GetPlayers();
for (Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
{
if (!itr->getSource() || !itr->getSource()->IsInWorld())
continue;
itr->getSource()->SendUpdateWorldState(uiField, uiValue);
}
}
void OutdoorPvP::HandleGameObjectCreate(GameObject* go)
{
// set initial data and activate capture points
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_CAPTURE_POINT)
go->SetCapturePointSlider(sOutdoorPvPMgr.GetCapturePointSliderValue(go->GetEntry(), CAPTURE_SLIDER_MIDDLE));
}
void OutdoorPvP::HandleGameObjectRemove(GameObject* go)
{
// save capture point slider value (negative value if locked)
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_CAPTURE_POINT)
sOutdoorPvPMgr.SetCapturePointSlider(go->GetEntry(), go->getLootState() == GO_ACTIVATED ? go->GetCapturePointSlider() : -go->GetCapturePointSlider());
}
/**
Function that handles player kills in the main outdoor pvp zones
@param player who killed another player
@param victim who was killed
*/
void OutdoorPvP::HandlePlayerKill(Player* killer, Unit* victim)
{
Player* plr = victim->GetCharmerOrOwnerPlayerOrPlayerItself();
if (plr && killer->GetTeam() == plr->GetTeam())
return;
if (Group* group = killer->GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* groupMember = itr->getSource();
if (!groupMember)
continue;
// skip if too far away
if (!groupMember->IsAtGroupRewardDistance(victim))
continue;
// creature kills must be notified, even if not inside objective / not outdoor pvp active
// player kills only count if active and inside objective
if (groupMember->CanUseCapturePoint())
HandlePlayerKillInsideArea(groupMember, victim);
}
}
else
{
// creature kills must be notified, even if not inside objective / not outdoor pvp active
if (killer && killer->CanUseCapturePoint())
HandlePlayerKillInsideArea(killer, victim);
}
}
// apply a team buff for the main and affected zones
void OutdoorPvP::BuffTeam(Team team, uint32 spellId, bool remove /*= false*/, bool onlyMembers /*= true*/, uint32 area /*= 0*/)
{
for (GuidZoneMap::const_iterator itr = m_zonePlayers.begin(); itr != m_zonePlayers.end(); ++itr)
{
Player* player = sObjectMgr.GetPlayer(itr->first);
if (!player)
continue;
if (player && (team == TEAM_NONE || player->GetTeam() == team) && (!onlyMembers || IsMember(player->GetObjectGuid())))
{
if (!area || area == player->GetAreaId())
{
if (remove)
player->RemoveAurasDueToSpell(spellId);
else
player->CastSpell(player, spellId, true);
}
}
}
}
uint32 OutdoorPvP::GetBannerArtKit(Team team, uint32 artKitAlliance /*= CAPTURE_ARTKIT_ALLIANCE*/, uint32 artKitHorde /*= CAPTURE_ARTKIT_HORDE*/, uint32 artKitNeutral /*= CAPTURE_ARTKIT_NEUTRAL*/)
{
switch (team)
{
case ALLIANCE:
return artKitAlliance;
case HORDE:
return artKitHorde;
default:
return artKitNeutral;
}
}
void OutdoorPvP::SetBannerVisual(const WorldObject* objRef, ObjectGuid goGuid, uint32 artKit, uint32 animId)
{
if (GameObject* go = objRef->GetMap()->GetGameObject(goGuid))
SetBannerVisual(go, artKit, animId);
}
void OutdoorPvP::SetBannerVisual(GameObject* go, uint32 artKit, uint32 animId)
{
go->SendGameObjectCustomAnim(go->GetObjectGuid(), animId);
go->SetGoArtKit(artKit);
go->Refresh();
}
void OutdoorPvP::RespawnGO(const WorldObject* objRef, ObjectGuid goGuid, bool respawn)
{
if (GameObject* go = objRef->GetMap()->GetGameObject(goGuid))
{
go->SetRespawnTime(7 * DAY);
if (respawn)
go->Refresh();
else if (go->isSpawned())
go->SetLootState(GO_JUST_DEACTIVATED);
}
}
| cooler-SAI/murlocs_434 | src/game/OutdoorPvP/OutdoorPvP.cpp | C++ | gpl-2.0 | 6,919 |
#!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# By David Harrison
# I was playing with doctest when I wrote this. I still haven't
# decided how useful doctest is as opposed to implementing unit tests
# directly. --Dave
if __name__ == '__main__':
import sys
sys.path = ['.','..'] + sys.path # HACK to simplify unit testing.
from BTL.translation import _
class BEGIN: # represents special BEGIN location before first next.
pass
from UserDict import DictMixin
from cmap_swig import *
import sys
from weakref import WeakKeyDictionary
LEAK_TEST = False
class CMap(object,DictMixin):
"""In-order mapping. Provides same operations and behavior as a dict,
but provides in-order iteration. Additionally provides operations to
find the nearest key <= or >= a given key.
This provides a significantly wider set of operations than
berkeley db BTrees, but it provides no means for persistence.
LIMITATION: The key must be a python numeric type, e.g., an integer
or a float. The value can be any python object.
Operation: Time Applicable
Complexity: Methods:
---------------------------------------------------
Item insertion: O(log n) append, __setitem__
Item deletion: O(log n + k) __delitem__, erase
Key search: O(log n) __getitem__, get, find,
__contains__
Value search: n/a
Iteration step: amortized O(1), next, prev
worst-case O(log n)
Memory: O(n)
n = number of elements in map. k = number of iterators pointing
into map. CMap assumes there are few iterators in existence at
any given time.
Iterators are not invalidated by insertions. Iterators are
invalidated by deletions only when the key-value pair
referenced is deleted. Deletion has a '+k' because the
__delitem__ searches linearly through the set of iterators
pointing into this map to find any iterator pointing at the
deleted item and then invalidates the iterator.
This class is backed by the C++ STL map class, but conforms
to the Python container interface."""
class _AbstractIterator:
"""Iterates over elements in the map in order."""
def __init__(self, m, si = BEGIN ): # "s.." implies swig object.
"""Creates an iterator pointing to element si in map m.
Do not instantiate directly. Use iterkeys, itervalues, or
iteritems.
The _AbstractIterator takes ownership of any C++ iterator
(i.e., the swig object 'si') and will deallocate it when
the iterator is deallocated.
Examples of typical behavior:
>>> from CMap import *
>>> m = CMap()
>>> m[12] = 6
>>> m[9] = 4
>>> for k in m:
... print int(k)
...
9
12
>>>
Example edge cases (empty map):
>>> from CMap import *
>>> m = CMap()
>>> try:
... i = m.__iter__()
... i.value()
... except IndexError:
... print 'IndexError.'
...
IndexError.
>>> try:
... i.next()
... except StopIteration:
... print 'stopped'
...
stopped
@param map: CMap.
@param node: Node that this iterator will point at. If None
then the iterator points to end(). If BEGIN
then the iterator points to one before the beginning.
"""
assert isinstance(m, CMap)
assert not isinstance(si, CMap._AbstractIterator)
if si == None:
self._si = map_end(m._smap)
else:
self._si = si # C++ iterator wrapped by swig.
self._map = m
m._iterators[self] = 1 # using map as set of weak references.
def __hash__(self):
return id(self)
def __cmp__(self, other):
if not self._si or not other._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN and other._si == BEGIN: return 0
if self._si == BEGIN and other._si != BEGIN: return -1
elif self._si != BEGIN and other._si == BEGIN: return 1
return iter_cmp(self._map._smap, self._si, other._si )
def at_begin(self):
"""equivalent to self == m.begin() where m is a CMap.
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.begin()
>>> i == m.begin()
True
>>> i.at_begin()
True
>>> i == m.end() # no elements so begin()==end()
True
>>> i.at_end()
True
>>> m[6] = 'foo' # insertion does not invalidate iterators.
>>> i = m.begin()
>>> i == m.end()
False
>>> i.value()
'foo'
>>> try: # test at_begin when not at beginning.
... i.next()
... except StopIteration:
... print 'ok'
ok
>>> i.at_begin()
False
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN: # BEGIN is one before begin(). Yuck!!
return False
return map_iter_at_begin(self._map._smap, self._si)
def at_end(self):
"""equivalent to self == m.end() where m is a CMap, but
at_end is faster because it avoids the dynamic memory
alloation in m.end().
>>> from CMap import CMap
>>> m = CMap()
>>> m[6] = 'foo'
>>> i = m.end() # test when at end.
>>> i == m.end()
True
>>> i.at_end()
True
>>> int(i.prev())
6
>>> i.at_end() # testing when not at end.
False
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
return False
return map_iter_at_end(self._map._smap, self._si)
def key(self):
"""@return: the key of the key-value pair referenced by this
iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise IndexError(_("Cannot dereference iterator until after "
"first call to .next."))
elif map_iter_at_end(self._map._smap, self._si):
raise IndexError()
return iter_key(self._si)
def value(self):
"""@return: the value of the key-value pair currently referenced
by this iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise IndexError(_("Cannot dereference iterator until after "
"first call to next."))
elif map_iter_at_end(self._map._smap, self._si):
raise IndexError()
return iter_value(self._si)
def item(self):
"""@return the key-value pair referenced by this iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
return self.key(), self.value()
def _next(self):
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
self._si = map_begin(self._map._smap)
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
return
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
iter_incr(self._si)
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
def _prev(self):
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise StopIteration()
elif map_iter_at_begin(self._map._smap, self._si):
self._si = BEGIN
raise StopIteration
iter_decr(self._si)
def __del__(self):
# Python note: if a reference to x is intentionally
# eliminated using "del x" and there are other references
# to x then __del__ does not get called at this time.
# Only when the last reference is deleted by an intentional
# "del" or when the reference goes out of scope does
# the __del__ method get called.
self._invalidate()
def _invalidate(self):
if self._si == None:
return
try:
del self._map._iterators[self]
except KeyError:
pass # could've been removed because weak reference,
# and because _invalidate is called from __del__.
if self._si != BEGIN:
iter_delete(self._si)
self._si = None
def __iter__(self):
"""If the iterator is itself iteratable then we do things like:
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[11] = 'bar'
>>> for x in m.itervalues():
... print x
...
foo
bar
"""
return self
def __len__(self):
return len(self._map)
class KeyIterator(_AbstractIterator):
def next(self):
"""Returns the next key in the map.
Insertion does not invalidate iterators. Deletion only
invalidates an iterator if the iterator pointed at the
key-value pair being deleted.
This is implemented by moving the iterator and then
dereferencing it. If we dereferenced and then moved
then we would get the odd behavior:
Ex: I have keys [1,2,3]. The iterator i points at 1.
print i.next() # prints 1
print i.next() # prints 2
print i.prev() # prints 3
print i.prev() # prints 2
However, because we move and then dereference, when an
iterator is first created it points to nowhere
so that the first next moves to the first element.
Ex:
>>> from CMap import *
>>> m = CMap()
>>> m[5] = 1
>>> m[8] = 4
>>> i = m.__iter__()
>>> print int(i.next())
5
>>> print int(i.next())
8
>>> print int(i.prev())
5
We are still left with the odd behavior that an
iterator cannot be dereferenced until after the first next().
Ex edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.__iter__()
>>> try:
... i.prev()
... except StopIteration:
... print 'StopIteration'
...
StopIteration
>>> m[5]='a'
>>> i = m.iterkeys()
>>> int(i.next())
5
>>> try: i.next()
... except StopIteration: print 'StopIteration'
...
StopIteration
>>> int(i.prev())
5
>>> try: int(i.prev())
... except StopIteration: print 'StopIteration'
...
StopIteration
>>> int(i.next())
5
"""
self._next()
return self.key()
def prev(self):
"""Returns the previous key in the map.
See next() for more detail and examples.
"""
self._prev()
return self.key()
class ValueIterator(_AbstractIterator):
def next(self):
"""@return: next value in the map.
>>> from CMap import *
>>> m = CMap()
>>> m[5] = 10
>>> m[6] = 3
>>> i = m.itervalues()
>>> int(i.next())
10
>>> int(i.next())
3
"""
self._next()
return self.value()
def prev(self):
self._prev()
return self.value()
class ItemIterator(_AbstractIterator):
def next(self):
"""@return: next item in the map's key ordering.
>>> from CMap import CMap
>>> m = CMap()
>>> m[5] = 10
>>> m[6] = 3
>>> i = m.iteritems()
>>> k,v = i.next()
>>> int(k)
5
>>> int(v)
10
>>> k,v = i.next()
>>> int(k)
6
>>> int(v)
3
"""
self._next()
return self.key(), self.value()
def prev(self):
self._prev()
return self.key(), self.value()
def __init__(self, d={} ):
"""Instantiate RBTree containing values from passed dict and
ordered based on cmp.
>>> m = CMap()
>>> len(m)
0
>>> m[5]=2
>>> len(m)
1
>>> print m[5]
2
"""
#self._index = {} # to speed up searches.
self._smap = map_constructor() # C++ map wrapped by swig.
for key, value in d.items():
self[key]=value
self._iterators = WeakKeyDictionary()
# whenever node is deleted. search iterators
# for any iterator that becomes invalid.
def __contains__(self,x):
return self.get(x) != None
def __iter__(self):
"""@return: KeyIterator positioned one before the beginning of the
key ordering so that the first next() returns the first key."""
return CMap.KeyIterator(self)
def begin(self):
"""Returns an iterator pointing at first key-value pair. This
differs from iterkeys, itervalues, and iteritems which return an
iterator pointing one before the first key-value pair.
@return: key iterator to first key-value.
>>> from CMap import *
>>> m = CMap()
>>> m[5.0] = 'a'
>>> i = m.begin()
>>> int(i.key()) # raises no IndexError.
5
>>> i = m.iterkeys()
>>> try:
... i.key()
... except IndexError:
... print 'IndexError raised'
...
IndexError raised
"""
i = CMap.KeyIterator(self, map_begin(self._smap) )
return i
def end(self):
"""Returns an iterator pointing after end of key ordering.
The iterator's prev method will move to the last
key-value pair in the ordering. This in keeping with
the notion that a range is specified as [i,j) where
j is not in the range, and the range [i,j) where i==j
is an empty range.
This operation takes O(1) time.
@return: key iterator one after end.
"""
i = CMap.KeyIterator(self,None) # None means one after last node.
return i
def iterkeys(self):
return CMap.KeyIterator(self)
def itervalues(self):
return CMap.ValueIterator(self)
def iteritems(self):
return CMap.ItemIterator(self)
def __len__(self):
return map_size(self._smap)
def __str__(self):
s = "{"
first = True
for k,v in self.items():
if first:
first = False
else:
s += ", "
if type(v) == str:
s += "%s: '%s'" % (k,v)
else:
s += "%s: %s" % (k,v)
s += "}"
return s
def __repr__(self):
return self.__str__()
def __getitem__(self, key):
# IMPL 1: without _index
return map_find(self._smap,key) # raises KeyError if key not found
# IMPL 2: with _index.
#return iter_value(self._index[key])
def __setitem__(self, key, value):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>>
"""
assert type(key) == int or type(key) == float
# IMPL 1. without _index.
map_set(self._smap,key,value)
## IMPL 2. with _index
## If using indices following allows us to perform only one search.
#i = map_insert_iter(self._smap,key,value)
#if iter_value(i) != value:
# iter_set(i,value)
#else: self._index[key] = i
## END IMPL2
def __delitem__(self, key):
"""Deletes the item with matching key from the map.
This takes O(log n + k) where n is the number of elements
in the map and k is the number of iterators pointing into the map.
Before deleting the item it linearly searches through
all iterators pointing into the map and invalidates any that
are pointing at the item about to be deleted.
>>> from CMap import CMap
>>> m = CMap()
>>> m[12] = 'foo'
>>> m[13] = 'bar'
>>> m[14] = 'boo'
>>> del m[12]
>>> try:
... m[12]
... except KeyError:
... print 'ok'
...
ok
>>> j = m.begin()
>>> int(j.next())
14
>>> i = m.begin()
>>> i.value()
'bar'
>>> del m[13] # delete object referenced by an iterator
>>> try:
... i.value()
... except RuntimeError:
... print 'ok'
ok
>>> j.value() # deletion should not invalidate other iterators.
'boo'
"""
#map_erase( self._smap, key ) # map_erase is dangerous. It could
# delete the node causing an iterator
# to become invalid. --Dave
si = map_find_iter( self._smap, key ) # si = swig'd iterator.
if map_iter_at_end(self._smap, si):
iter_delete(si)
raise KeyError(key)
for i in list(self._iterators):
if iter_cmp( self._smap, i._si, si ) == 0:
i._invalidate()
map_iter_erase( self._smap, si )
iter_delete(si)
#iter_delete( self._index[key] ) # IMPL 2. with _index.
#del self._index[key] # IMPL 2. with _index.
def erase(self, iter):
"""Remove item pointed to by the iterator. All iterators that
point at the erased item including the passed iterator
are immediately invalidated after the deletion completes.
>>> from CMap import CMap
>>> m = CMap()
>>> m[12] = 'foo'
>>> i = m.find(12)
>>> m.erase(i)
>>> len(m) == 0
True
"""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair" ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different CMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot erase end() iterator.") )
# invalidate iterators.
for i in list(self._iterators):
if iter._si is not i._si and iiter_cmp( self._smmap, iter._si, i._si ) == 0:
i._invalidate()
# remove item from the map.
map_iter_erase( self._smap, iter._si )
# invalidate last iterator pointing to the deleted location in the map.
iter._invalidate()
def __del__(self):
# invalidate all iterators.
for i in list(self._iterators):
i._invalidate()
map_delete(self._smap)
def get(self, key, default=None):
"""@return value corresponding to specified key or return 'default'
if the key is not found.
"""
try:
return map_find(self._smap,key) # IMPL 1. without _index.
#return iter_value(self._index[key]) # IMPL 2. with _index.
except KeyError:
return default
def keys(self):
"""
>>> from CMap import *
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> [int(x) for x in m.keys()] # m.keys() but guaranteed integers.
[4, 6]
"""
k = []
for key in self:
k.append(key)
return k
def values(self):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> m.values()
[7, 3]
"""
i = self.itervalues()
v = []
try:
while True:
v.append(i.next())
except StopIteration:
pass
return v
def items(self):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> [(int(x[0]),int(x[1])) for x in m.items()]
[(4, 7), (6, 3)]
"""
i = self.iteritems()
itms = []
try:
while True:
itms.append(i.next())
except StopIteration:
pass
return itms
def has_key(self, key):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> if m.has_key(4): print 'ok'
...
ok
>>> if not m.has_key(7): print 'ok'
...
ok
"""
try:
self[key]
except KeyError:
return False
return True
def clear(self):
"""delete all entries
>>> from CMap import CMap
>>> m = CMap()
>>> m[4] = 7
>>> m.clear()
>>> print len(m)
0
"""
self.__del__()
self._smap = map_constructor()
def copy(self):
"""return shallow copy"""
return CMap(self)
def lower_bound(self,key):
"""
Finds smallest key equal to or above the lower bound.
Takes O(log n) time.
@param x: Key of (key, value) pair to be located.
@return: Key Iterator pointing to first item equal to or greater
than key, or end() if no such item exists.
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[15] = 'bar'
>>> i = m.lower_bound(11) # iterator.
>>> int(i.key())
15
>>> i.value()
'bar'
Edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.lower_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.lower_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> i = m.lower_bound(9)
>>> if i == m.begin(): print 'ok'
...
ok
"""
return CMap.KeyIterator(self, map_lower_bound( self._smap, key ))
def upper_bound(self, key):
"""
Finds largest key equal to or below the upper bound. In keeping
with the [begin,end) convention, the returned iterator
actually points to the key one above the upper bound.
Takes O(log n) time.
@param x: Key of (key, value) pair to be located.
@return: Iterator pointing to first element equal to or greater than
key, or end() if no such item exists.
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[15] = 'bar'
>>> m[17] = 'choo'
>>> i = m.upper_bound(11) # iterator.
>>> i.value()
'bar'
Edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.upper_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.upper_bound(9)
>>> i.value()
'foo'
>>> i = m.upper_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
"""
return CMap.KeyIterator(self, map_upper_bound( self._smap, key ))
def find(self,key):
"""
Finds the item with matching key and returns a KeyIterator
pointing at the item. If no match is found then returns end().
Takes O(log n) time.
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.find(10)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.find(10)
>>> int(i.key())
10
>>> i.value()
'foo'
"""
return CMap.KeyIterator(self, map_find_iter( self._smap, key ))
def update_key( self, iter, key ):
"""
Modifies the key of the item referenced by iter. If the
key change is small enough that no reordering occurs then
this takes amortized O(1) time. If a reordering occurs then
this takes O(log n).
WARNING!!! The passed iterator MUST be assumed to be invalid
upon return and should be deallocated.
Typical use:
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[8] = 'bar'
>>> i = m.find(10)
>>> m.update_key(i,7) # i is assumed to be invalid upon return.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()] # reordering occurred.
[(7, 'foo'), (8, 'bar')]
>>> i = m.find(8)
>>> m.update_key(i,9) # no reordering.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()]
[(7, 'foo'), (9, 'bar')]
Edge cases:
>>> i = m.find(7)
>>> i.value()
'foo'
>>> try: # update to key already in the map.
... m.update_key(i,9)
... except KeyError:
... print 'ok'
...
ok
>>> m[7]
'foo'
>>> i = m.iterkeys()
>>> try: # updating an iter pointing at BEGIN.
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
>>> i = m.end()
>>> try: # updating an iter pointing at end().
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
"""
assert isinstance(iter,CMap._AbstractIterator)
if iter._si == BEGIN:
raise IndexError( _("Iterator does not point at key-value pair") )
if self is not iter._map:
raise IndexError(_("Iterator points into a different CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
map_iter_update_key(self._smap, iter._si, key)
def append(self, key, value):
"""Performs an insertion with the hint that it probably should
go at the end.
Raises KeyError if the key is already in the map.
>>> from CMap import CMap
>>> m = CMap()
>>> m.append(5.0,'foo') # append to empty map.
>>> len(m)
1
>>> [int(x) for x in m.keys()] # see note (1)
[5]
>>> m.append(10.0, 'bar') # append in-order
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo'), (10, 'bar')]
>>> m.append(3.0, 'coo') # out-of-order.
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> try:
... m.append(10.0, 'blah') # append key already in map.
... except KeyError:
... print 'ok'
...
ok
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>>
note (1): int(x[0]) is used because 5.0 can appear as either 5
or 5.0 depending on the version of python.
"""
map_append(self._smap,key,value)
class CIndexedMap(CMap):
"""This is an ordered mapping, exactly like CMap except that it
provides a cross-index allowing average O(1) searches based on value.
This adds the constraint that values must be unique.
Operation: Time Applicable
Complexity: Methods:
---------------------------------------------------
Item insertion: O(log n) append, __setitem__
Item deletion: O(log n + k) __delitem__, erase
Key search: O(log n) __getitem__, get, find,
__contains__
Value search: average O(1) as per dict
Iteration step: amortized O(1), next, prev
worst-case O(log n)
Memory: O(n)
n = number of elements in map. k = number of iterators pointing
into map. CIndexedMap assumes there are few iterators in existence
at any given time.
The hash table increases the factor in the
O(n) memory cost of the Map by a constant
"""
def __init__(self, dict={} ):
CMap.__init__(self,dict)
self._value_index = {} # cross-index. maps value->iterator.
def __setitem__(self, key, value):
"""
>>> from CMap import *
>>> m = CIndexedMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>> int(m.get_key_by_value('bar'))
6
>>> try:
... m[7] = 'bar'
... except ValueError:
... print 'value error'
value error
>>> m[6] = 'foo'
>>> m[6]
'foo'
>>> m[7] = 'bar'
>>> m[7]
'bar'
>>> m[7] = 'bar' # should not raise exception
>>> m[7] = 'goo'
>>> m.get_key_by_value('bar') # should return None.
>>>
"""
assert type(key) == int or type(key) == float
if self._value_index.has_key(value) and \
iter_key(self._value_index[value]) != key:
raise ValueError( _("Value %s already exists. Values must be "
"unique.") % str(value) )
si = map_insert_iter(self._smap,key,value) # si points where insert
# should occur whether
# insert succeeded or not.
# si == "swig iterator"
sival = iter_value(si)
if sival != value: # if insert failed because k already exists
iter_set(si,value) # then force set.
self._value_index[value] = si
viter = self._value_index[sival]
iter_delete(viter) # remove old value from index
del self._value_index[sival]
else: # else insert succeeded so update index.
self._value_index[value] = si
#self._index[key] = si # IMPL 2. with _index.
def __delitem__(self, key):
"""
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>> int(m.get_key_by_value('bar'))
6
>>> del m[6]
>>> if m.get_key_by_value('bar'):
... print 'found'
... else:
... print 'not found.'
not found.
"""
i = map_find_iter( self._smap, key )
if map_iter_at_end( self._smap, i ):
iter_delete(i)
raise KeyError(key)
else:
value = iter_value(i)
for i in list(self._iterators):
if iter_cmp( self._smap, i._si, iter._si ) == 0:
i._invalidate()
map_iter_erase( self._smap, i )
viter = self._value_index[value]
iter_delete(i)
iter_delete( viter )
del self._value_index[value]
#del self._index[key] # IMPL 2. with _index.
assert map_size(self._smap) == len(self._value_index)
def has_value(self, value):
return self._value_index.has_key(value)
def get_key_by_value(self, value):
"""Returns the key cross-indexed from the passed unique value, or
returns None if the value is not in the map."""
si = self._value_index.get(value) # si == "swig iterator"
if si == None: return None
return iter_key(si)
def append( self, key, value ):
"""See CMap.append
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m.append(5,'foo')
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo')]
>>> m.append(10, 'bar')
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo'), (10, 'bar')]
>>> m.append(3, 'coo') # out-of-order.
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> int(m.get_key_by_value( 'bar' ))
10
>>> try:
... m.append(10, 'blah') # append key already in map.
... except KeyError:
... print 'ok'
...
ok
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> try:
... m.append(10, 'coo') # append value already in map.
... except ValueError:
... print 'ok'
...
ok
"""
if self._value_index.has_key(value) and \
iter_key(self._value_index[value]) != key:
raise ValueError(_("Value %s already exists and value must be "
"unique.") % str(value) )
si = map_append_iter(self._smap,key,value)
if iter_value(si) != value:
iter_delete(si)
raise KeyError(key)
self._value_index[value] = si
def find_key_by_value(self, value):
"""Returns a key iterator cross-indexed from the passed unique value
or end() if no value found.
>>> from Map import *
>>> m = CIndexedMap()
>>> m[6] = 'abc'
>>> i = m.find_key_by_value('abc')
>>> int(i.key())
6
>>> i = m.find_key_by_value('xyz')
>>> if i == m.end(): print 'i points at end()'
i points at end()
"""
si = self._value_index.get(value) # si == "swig iterator."
if si != None:
si = iter_copy(si); # copy else operations like increment on the
# KeyIterator would modify the value index.
return CMap.KeyIterator(self,si)
def copy(self):
"""return shallow copy"""
return CIndexedMap(self)
def update_key( self, iter, key ):
"""
see CMap.update_key.
WARNING!! You MUST assume that the passed iterator is invalidated
upon return.
Typical use:
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m[10] = 'foo'
>>> m[8] = 'bar'
>>> i = m.find(10)
>>> m.update_key(i,7) # i is assumed to be invalid upon return.
>>> del i
>>> int(m.get_key_by_value('foo'))
7
>>> [(int(x[0]),x[1]) for x in m.items()] # reordering occurred.
[(7, 'foo'), (8, 'bar')]
>>> i = m.find(8)
>>> m.update_key(i,9) # no reordering.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()]
[(7, 'foo'), (9, 'bar')]
Edge cases:
>>> i = m.find(7)
>>> i.value()
'foo'
>>> try:
... m.update_key(i,9)
... except KeyError:
... print 'ok'
...
ok
>>> m[7]
'foo'
>>> int(m.get_key_by_value('foo'))
7
>>> i = m.iterkeys()
>>> try: # updating an iter pointing at BEGIN.
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
>>> i = m.end()
>>> try: # updating an iter pointing at end().
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
"""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair" ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different "
"CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
si = map_iter_update_key_iter(self._smap, iter._si, key)
# raises KeyError if key already in map.
if si != iter._si: # if map is reordered...
value = iter.value();
val_si = self._value_index[value]
iter_delete(val_si)
self._value_index[value] = si
def erase(self, iter):
"""Remove item pointed to by the iterator. Iterator is immediately
invalidated after the deletion completes."""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair." ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different "
"CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
value = iter.value()
CMap.erase(self,iter)
del self._value_index[value]
if __name__ == "__main__":
import doctest
import random
##############################################
# UNIT TESTS
print "Testing module"
doctest.testmod(sys.modules[__name__])
print "doctest complete."
##############################################
# MEMORY LEAK TESTS
if LEAK_TEST:
i = 0
import gc
class X:
x = range(1000) # something moderately big.
# TEST 1. This does not cause memory to grow.
#m = CMap()
#map_insert(m._smap,10,X())
#while True:
# i += 1
# it = map_find_iter( m._smap, 10 )
# iter_delete(it)
# del it
# if i % 100 == 0:
# gc.collect()
# TEST 2: This does not caus a memory leak.
#m = map_constructor_double()
#while True:
# i += 1
# map_insert_double(m,10,5) # here
# it = map_find_iter_double( m, 10 )
# map_iter_erase_double( m, it ) # or here is the problem.
# iter_delete_double(it)
# del it
# #assert len(m) == 0
# assert map_size_double(m) == 0
# if i % 100 == 0:
# gc.collect()
# TEST 3. No memory leak
#m = CMap()
#while True:
# i += 1
# map_insert(m._smap,10,X()) # here
# it = map_find_iter( m._smap, 10 )
# map_iter_erase( m._smap, it ) # or here is the problem.
# iter_delete(it)
# del it
# assert len(m) == 0
# assert map_size(m._smap) == 0
# if i % 100 == 0:
# gc.collect()
# TEST 4: map creation and deletion.
#while True:
# m = map_constructor()
# map_delete(m);
# TEST 5: test iteration.
#m = map_constructor()
#for i in xrange(10):
# map_insert(m,i,X())
#while True:
# i = map_begin(m)
# while not map_iter_at_begin(m,i):
# iter_incr(i)
# iter_delete(i)
# TEST 6:
#m = map_constructor()
#for i in xrange(10):
# map_insert(m,i,X())
#while True:
# map_find( m, random.randint(0,9) )
# TEST 7:
#m = map_constructor()
#for i in xrange(50):
# map_insert( m, i, X() )
#while True:
# for i in xrange(50):
# map_set( m, i, X() )
# TEST 8
# aha! Another leak! Fixed.
#m = map_constructor()
#while True:
# i += 1
# map_insert(m,10,X())
# map_erase(m,10)
# assert map_size(m) == 0
# TEST 9
m = map_constructor()
for i in xrange(50):
map_insert( m, i, X() )
while True:
it = map_find_iter( m, 5 )
map_iter_update_key( m, it, 1000 )
iter_delete(it)
it = map_find_iter( m, 1000 )
map_iter_update_key( m, it, 5)
iter_delete(it)
| sulaweyo/torrentflux-b4rt-php7 | html/bin/clients/mainline/BTL/CMap.py | Python | gpl-2.0 | 44,894 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Loader
* @subpackage Autoloader
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id: Resource.php 20096 2010-01-06 02:05:09Z bkarwin $
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Loader_Autoloader_Interface */
require_once 'Zend/Loader/Autoloader/Interface.php';
/**
* Resource loader
*
* @uses Zend_Loader_Autoloader_Interface
* @package Zend_Loader
* @subpackage Autoloader
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Loader_Autoloader_Resource implements Zend_Loader_Autoloader_Interface
{
/**
* @var string Base path to resource classes
*/
protected $_basePath;
/**
* @var array Components handled within this resource
*/
protected $_components = array();
/**
* @var string Default resource/component to use when using object registry
*/
protected $_defaultResourceType;
/**
* @var string Namespace of classes within this resource
*/
protected $_namespace;
/**
* @var array Available resource types handled by this resource autoloader
*/
protected $_resourceTypes = array();
/**
* Constructor
*
* @param array|Zend_Config $options Configuration options for resource autoloader
* @return void
*/
public function __construct($options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (!is_array($options)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Options must be passed to resource loader constructor');
}
$this->setOptions($options);
$namespace = $this->getNamespace();
if ((null === $namespace)
|| (null === $this->getBasePath())
) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Resource loader requires both a namespace and a base path for initialization');
}
if (!empty($namespace)) {
$namespace .= '_';
}
Zend_Loader_Autoloader::getInstance()->unshiftAutoloader($this, $namespace);
}
/**
* Overloading: methods
*
* Allow retrieving concrete resource object instances using 'get<Resourcename>()'
* syntax. Example:
* <code>
* $loader = new Zend_Loader_Autoloader_Resource(array(
* 'namespace' => 'Stuff_',
* 'basePath' => '/path/to/some/stuff',
* ))
* $loader->addResourceType('Model', 'models', 'Model');
*
* $foo = $loader->getModel('Foo'); // get instance of Stuff_Model_Foo class
* </code>
*
* @param string $method
* @param array $args
* @return mixed
* @throws Zend_Loader_Exception if method not beginning with 'get' or not matching a valid resource type is called
*/
public function __call($method, $args)
{
if ('get' == substr($method, 0, 3)) {
$type = strtolower(substr($method, 3));
if (!$this->hasResourceType($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Invalid resource type $type; cannot load resource");
}
if (empty($args)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Cannot load resources; no resource specified");
}
$resource = array_shift($args);
return $this->load($resource, $type);
}
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Method '$method' is not supported");
}
/**
* Helper method to calculate the correct class path
*
* @param string $class
* @return False if not matched other wise the correct path
*/
public function getClassPath($class)
{
$segments = explode('_', $class);
$namespaceTopLevel = $this->getNamespace();
$namespace = '';
if (!empty($namespaceTopLevel)) {
$namespace = array_shift($segments);
if ($namespace != $namespaceTopLevel) {
// wrong prefix? we're done
return false;
}
}
if (count($segments) < 2) {
// assumes all resources have a component and class name, minimum
return false;
}
$final = array_pop($segments);
$component = $namespace;
$lastMatch = false;
do {
$segment = array_shift($segments);
$component .= empty($component) ? $segment : '_' . $segment;
if (isset($this->_components[$component])) {
$lastMatch = $component;
}
} while (count($segments));
if (!$lastMatch) {
return false;
}
$final = substr($class, strlen($lastMatch) + 1);
$path = $this->_components[$lastMatch];
$classPath = $path . '/' . str_replace('_', '/', $final) . '.php';
if (Zend_Loader::isReadable($classPath)) {
return $classPath;
}
return false;
}
/**
* Attempt to autoload a class
*
* @param string $class
* @return mixed False if not matched, otherwise result if include operation
*/
public function autoload($class)
{
$classPath = $this->getClassPath($class);
if (false !== $classPath) {
return include $classPath;
}
return false;
}
/**
* Set class state from options
*
* @param array $options
* @return Zend_Loader_Autoloader_Resource
*/
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
/**
* Set namespace that this autoloader handles
*
* @param string $namespace
* @return Zend_Loader_Autoloader_Resource
*/
public function setNamespace($namespace)
{
$this->_namespace = rtrim((string) $namespace, '_');
return $this;
}
/**
* Get namespace this autoloader handles
*
* @return string
*/
public function getNamespace()
{
return $this->_namespace;
}
/**
* Set base path for this set of resources
*
* @param string $path
* @return Zend_Loader_Autoloader_Resource
*/
public function setBasePath($path)
{
$this->_basePath = (string) $path;
return $this;
}
/**
* Get base path to this set of resources
*
* @return string
*/
public function getBasePath()
{
return $this->_basePath;
}
/**
* Add resource type
*
* @param string $type identifier for the resource type being loaded
* @param string $path path relative to resource base path containing the resource types
* @param null|string $namespace sub-component namespace to append to base namespace that qualifies this resource type
* @return Zend_Loader_Autoloader_Resource
*/
public function addResourceType($type, $path, $namespace = null)
{
$type = strtolower($type);
if (!isset($this->_resourceTypes[$type])) {
if (null === $namespace) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Initial definition of a resource type must include a namespace');
}
$namespaceTopLevel = $this->getNamespace();
$namespace = ucfirst(trim($namespace, '_'));
$this->_resourceTypes[$type] = array(
'namespace' => empty($namespaceTopLevel) ? $namespace : $namespaceTopLevel . '_' . $namespace,
);
}
if (!is_string($path)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Invalid path specification provided; must be string');
}
$this->_resourceTypes[$type]['path'] = $this->getBasePath() . '/' . rtrim($path, '\/');
$component = $this->_resourceTypes[$type]['namespace'];
$this->_components[$component] = $this->_resourceTypes[$type]['path'];
return $this;
}
/**
* Add multiple resources at once
*
* $types should be an associative array of resource type => specification
* pairs. Each specification should be an associative array containing
* minimally the 'path' key (specifying the path relative to the resource
* base path) and optionally the 'namespace' key (indicating the subcomponent
* namespace to append to the resource namespace).
*
* As an example:
* <code>
* $loader->addResourceTypes(array(
* 'model' => array(
* 'path' => 'models',
* 'namespace' => 'Model',
* ),
* 'form' => array(
* 'path' => 'forms',
* 'namespace' => 'Form',
* ),
* ));
* </code>
*
* @param array $types
* @return Zend_Loader_Autoloader_Resource
*/
public function addResourceTypes(array $types)
{
foreach ($types as $type => $spec) {
if (!is_array($spec)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('addResourceTypes() expects an array of arrays');
}
if (!isset($spec['path'])) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('addResourceTypes() expects each array to include a paths element');
}
$paths = $spec['path'];
$namespace = null;
if (isset($spec['namespace'])) {
$namespace = $spec['namespace'];
}
$this->addResourceType($type, $paths, $namespace);
}
return $this;
}
/**
* Overwrite existing and set multiple resource types at once
*
* @see Zend_Loader_Autoloader_Resource::addResourceTypes()
* @param array $types
* @return Zend_Loader_Autoloader_Resource
*/
public function setResourceTypes(array $types)
{
$this->clearResourceTypes();
return $this->addResourceTypes($types);
}
/**
* Retrieve resource type mappings
*
* @return array
*/
public function getResourceTypes()
{
return $this->_resourceTypes;
}
/**
* Is the requested resource type defined?
*
* @param string $type
* @return bool
*/
public function hasResourceType($type)
{
return isset($this->_resourceTypes[$type]);
}
/**
* Remove the requested resource type
*
* @param string $type
* @return Zend_Loader_Autoloader_Resource
*/
public function removeResourceType($type)
{
if ($this->hasResourceType($type)) {
$namespace = $this->_resourceTypes[$type]['namespace'];
unset($this->_components[$namespace]);
unset($this->_resourceTypes[$type]);
}
return $this;
}
/**
* Clear all resource types
*
* @return Zend_Loader_Autoloader_Resource
*/
public function clearResourceTypes()
{
$this->_resourceTypes = array();
$this->_components = array();
return $this;
}
/**
* Set default resource type to use when calling load()
*
* @param string $type
* @return Zend_Loader_Autoloader_Resource
*/
public function setDefaultResourceType($type)
{
if ($this->hasResourceType($type)) {
$this->_defaultResourceType = $type;
}
return $this;
}
/**
* Get default resource type to use when calling load()
*
* @return string|null
*/
public function getDefaultResourceType()
{
return $this->_defaultResourceType;
}
/**
* Object registry and factory
*
* Loads the requested resource of type $type (or uses the default resource
* type if none provided). If the resource has been loaded previously,
* returns the previous instance; otherwise, instantiates it.
*
* @param string $resource
* @param string $type
* @return object
* @throws Zend_Loader_Exception if resource type not specified or invalid
*/
public function load($resource, $type = null)
{
if (null === $type) {
$type = $this->getDefaultResourceType();
if (empty($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('No resource type specified');
}
}
if (!$this->hasResourceType($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Invalid resource type specified');
}
$namespace = $this->_resourceTypes[$type]['namespace'];
$class = $namespace . '_' . ucfirst($resource);
if (!isset($this->_resources[$class])) {
$this->_resources[$class] = new $class;
}
return $this->_resources[$class];
}
}
| Tpo76/centreon | lib/Zend/Loader/Autoloader/Resource.php | PHP | gpl-2.0 | 14,136 |
#!/usr/bin/python
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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 this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2006 XenSource Ltd.
#============================================================================
import sys
import time
import re
import os
sys.path.append('/usr/lib/python')
from xen.util.xmlrpclib2 import ServerProxy
from optparse import *
from pprint import pprint
from types import DictType
from getpass import getpass
# Get default values from the environment
SERVER_URI = os.environ.get('XAPI_SERVER_URI', 'http://localhost:9363/')
SERVER_USER = os.environ.get('XAPI_SERVER_USER', '')
SERVER_PASS = os.environ.get('XAPI_SERVER_PASS', '')
MB = 1024 * 1024
HOST_INFO_FORMAT = '%-20s: %-50s'
VM_LIST_FORMAT = '%(name_label)-18s %(memory_actual)-5s %(VCPUs_number)-5s'\
' %(power_state)-10s %(uuid)-36s'
SR_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(physical_size)-10s' \
'%(type)-10s'
VDI_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(virtual_size)-8s'
VBD_LIST_FORMAT = '%(device)-6s %(uuid)-36s %(VDI)-8s'
TASK_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(status)-8s %(progress)-4s'
VIF_LIST_FORMAT = '%(name)-8s %(device)-7s %(uuid)-36s %(MAC)-10s'
CONSOLE_LIST_FORMAT = '%(uuid)-36s %(protocol)-8s %(location)-32s'
COMMANDS = {
'host-info': ('', 'Get Xen Host Info'),
'host-set-name': ('', 'Set host name'),
'pif-list': ('', 'List all PIFs'),
'sr-list': ('', 'List all SRs'),
'vbd-list': ('', 'List all VBDs'),
'vbd-create': ('<domname> <pycfg> [opts]',
'Create VBD attached to domname'),
'vdi-create': ('<pycfg> [opts]', 'Create a VDI'),
'vdi-list' : ('', 'List all VDI'),
'vdi-rename': ('<vdi_uuid> <new_name>', 'Rename VDI'),
'vdi-destroy': ('<vdi_uuid>', 'Delete VDI'),
'vif-create': ('<domname> <pycfg>', 'Create VIF attached to domname'),
'vtpm-create' : ('<domname> <pycfg>', 'Create VTPM attached to domname'),
'vm-create': ('<pycfg>', 'Create VM with python config'),
'vm-destroy': ('<domname>', 'Delete VM'),
'vm-list': ('[--long]', 'List all domains.'),
'vm-name': ('<uuid>', 'Name of UUID.'),
'vm-shutdown': ('<name> [opts]', 'Shutdown VM with name'),
'vm-start': ('<name>', 'Start VM with name'),
'vm-uuid': ('<name>', 'UUID of a domain by name.'),
'async-vm-start': ('<name>', 'Start VM asynchronously'),
}
OPTIONS = {
'sr-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of SR'})
],
'vdi-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VDI'})
],
'vif-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VIF'})
],
'vm-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VMs'})
],
'vm-shutdown': [(('-f', '--force'), {'help': 'Shutdown Forcefully',
'action': 'store_true'})],
'vdi-create': [(('--name-label',), {'help': 'Name for VDI'}),
(('--name-description',), {'help': 'Description for VDI'}),
(('--virtual-size',), {'type': 'int',
'default': 0,
'help': 'Size of VDI in bytes'}),
(('--type',), {'choices': ['system', 'user', 'ephemeral'],
'default': 'system',
'help': 'VDI type'}),
(('--sharable',), {'action': 'store_true',
'help': 'VDI sharable'}),
(('--read-only',), {'action': 'store_true',
'help': 'Read only'}),
(('--sr',), {})],
'vbd-create': [(('--VDI',), {'help': 'UUID of VDI to attach to.'}),
(('--mode',), {'choices': ['RO', 'RW'],
'help': 'device mount mode'}),
(('--driver',), {'choices':['paravirtualised', 'ioemu'],
'help': 'Driver for VBD'}),
(('--device',), {'help': 'Device name on guest domain'})]
}
class OptionError(Exception):
pass
class XenAPIError(Exception):
pass
#
# Extra utility functions
#
class IterableValues(Values):
"""Better interface to the list of values from optparse."""
def __iter__(self):
for opt, val in self.__dict__.items():
if opt[0] == '_' or callable(val):
continue
yield opt, val
def parse_args(cmd_name, args, set_defaults = False):
argstring, desc = COMMANDS[cmd_name]
parser = OptionParser(usage = 'xapi %s %s' % (cmd_name, argstring),
description = desc)
if cmd_name in OPTIONS:
for optargs, optkwds in OPTIONS[cmd_name]:
parser.add_option(*optargs, **optkwds)
if set_defaults:
default_values = parser.get_default_values()
defaults = IterableValues(default_values.__dict__)
else:
defaults = IterableValues()
(opts, extraargs) = parser.parse_args(args = list(args),
values = defaults)
return opts, extraargs
def execute(server, fn, args, async = False):
if async:
func = eval('server.Async.%s' % fn)
else:
func = eval('server.%s' % fn)
result = func(*args)
if type(result) != DictType:
raise TypeError("Function returned object of type: %s" %
str(type(result)))
if 'Value' not in result:
raise XenAPIError(*result['ErrorDescription'])
return result['Value']
_initialised = False
_server = None
_session = None
def connect(*args):
global _server, _session, _initialised
if not _initialised:
# try without password or default credentials
try:
_server = ServerProxy(SERVER_URI)
_session = execute(_server.session, 'login_with_password',
(SERVER_USER, SERVER_PASS))
except:
login = raw_input("Login: ")
password = getpass()
creds = (login, password)
_server = ServerProxy(SERVER_URI)
_session = execute(_server.session, 'login_with_password',
creds)
_initialised = True
return (_server, _session)
def _stringify(adict):
return dict([(k, str(v)) for k, v in adict.items()])
def _read_python_cfg(filename):
cfg = {}
execfile(filename, {}, cfg)
return cfg
def resolve_vm(server, session, vm_name):
vm_uuid = execute(server, 'VM.get_by_name_label', (session, vm_name))
if not vm_uuid:
return None
else:
return vm_uuid[0]
def resolve_vdi(server, session, vdi_name):
vdi_uuid = execute(server, 'VDI.get_by_name_label', (session, vdi_name))
if not vdi_uuid:
return None
else:
return vdi_uuid[0]
#
# Actual commands
#
def xapi_host_info(args, async = False):
server, session = connect()
hosts = execute(server, 'host.get_all', (session,))
for host in hosts: # there is only one, but ..
hostinfo = execute(server, 'host.get_record', (session, host))
print HOST_INFO_FORMAT % ('Name', hostinfo['name_label'])
print HOST_INFO_FORMAT % ('Version', hostinfo['software_version'])
print HOST_INFO_FORMAT % ('CPUs', len(hostinfo['host_CPUs']))
print HOST_INFO_FORMAT % ('VMs', len(hostinfo['resident_VMs']))
print HOST_INFO_FORMAT % ('UUID', host)
for host_cpu_uuid in hostinfo['host_CPUs']:
host_cpu = execute(server, 'host_cpu.get_record',
(session, host_cpu_uuid))
print 'CPU %s Util: %.2f' % (host_cpu['number'],
float(host_cpu['utilisation']))
def xapi_host_set_name(args, async = False):
if len(args) < 1:
raise OptionError("No hostname specified")
server, session = connect()
hosts = execute(server, 'host.get_all', (session,))
if len(hosts) > 0:
execute(server, 'host.set_name_label', (session, hosts[0], args[0]))
print 'Hostname: %s' % execute(server, 'host.get_name_label',
(session, hosts[0]))
def xapi_vm_uuid(args, async = False):
if len(args) < 1:
raise OptionError("No domain name specified")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print vm_uuid
def xapi_vm_name(args, async = False):
if len(args) < 1:
raise OptionError("No UUID specified")
server, session = connect()
vm_name = execute(server, 'VM.get_name_label', (session, args[0]))
print vm_name
def xapi_vm_list(args, async = False):
opts, args = parse_args('vm-list', args, set_defaults = True)
is_long = opts and opts.long
list_only = args
server, session = connect()
vm_uuids = execute(server, 'VM.get_all', (session,))
if not is_long:
print VM_LIST_FORMAT % {'name_label':'Name',
'memory_actual':'Mem',
'VCPUs_number': 'VCPUs',
'power_state': 'State',
'uuid': 'UUID'}
for uuid in vm_uuids:
vm_info = execute(server, 'VM.get_record', (session, uuid))
# skip domain if we don't want
if list_only and vm_info['name_label'] not in list_only:
continue
if is_long:
vbds = vm_info['VBDs']
vifs = vm_info['VIFs']
vtpms = vm_info['VTPMs']
vif_infos = []
vbd_infos = []
vtpm_infos = []
for vbd in vbds:
vbd_info = execute(server, 'VBD.get_record', (session, vbd))
vbd_infos.append(vbd_info)
for vif in vifs:
vif_info = execute(server, 'VIF.get_record', (session, vif))
vif_infos.append(vif_info)
for vtpm in vtpms:
vtpm_info = execute(server, 'VTPM.get_record', (session, vtpm))
vtpm_infos.append(vtpm_info)
vm_info['VBDs'] = vbd_infos
vm_info['VIFs'] = vif_infos
vm_info['VTPMs'] = vtpm_infos
pprint(vm_info)
else:
print VM_LIST_FORMAT % _stringify(vm_info)
def xapi_vm_create(args, async = False):
if len(args) < 1:
raise OptionError("Configuration file not specified")
filename = args[0]
cfg = _read_python_cfg(filename)
print 'Creating VM from %s ..' % filename
server, session = connect()
uuid = execute(server, 'VM.create', (session, cfg), async = async)
print 'Done. (%s)' % uuid
print uuid
def xapi_vm_destroy(args, async = False):
if len(args) < 1:
raise OptionError("No domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Destroying VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.destroy', (session, vm_uuid), async = async)
print 'Done.'
def xapi_vm_start(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Starting VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.start', (session, vm_uuid, False), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_suspend(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Suspending VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.suspend', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_resume(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Resuming VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.resume', (session, vm_uuid, False), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_pause(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Pausing VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.pause', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_unpause(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Pausing VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.unpause', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_task_list(args, async = False):
server, session = connect()
all_tasks = execute(server, 'task.get_all', (session,))
print TASK_LIST_FORMAT % {'name_label': 'Task Name',
'uuid': 'UUID',
'status': 'Status',
'progress': '%'}
for task_uuid in all_tasks:
task = execute(server, 'task.get_record', (session, task_uuid))
print TASK_LIST_FORMAT % task
def xapi_task_clear(args, async = False):
server, session = connect()
all_tasks = execute(server, 'task.get_all', (session,))
for task_uuid in all_tasks:
success = execute(server, 'task.destroy', (session, task_uuid))
print 'Destroyed Task %s' % task_uuid
def xapi_vm_shutdown(args, async = False):
opts, args = parse_args("vm-shutdown", args, set_defaults = True)
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
if opts.force:
print 'Forcefully shutting down VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.hard_shutdown', (session, vm_uuid), async = async)
else:
print 'Shutting down VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.clean_shutdown', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vbd_create(args, async = False):
opts, args = parse_args('vbd-create', args)
if len(args) < 2:
raise OptionError("Configuration file and domain not specified")
domname = args[0]
if len(args) > 1:
filename = args[1]
cfg = _read_python_cfg(filename)
else:
cfg = {}
for opt, val in opts:
cfg[opt] = val
print 'Creating VBD ...',
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
vbd_uuid = execute(server, 'VBD.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % vbd_uuid
else:
print 'Done. (%s)' % vbd_uuid
def xapi_vif_create(args, async = False):
if len(args) < 2:
raise OptionError("Configuration file not specified")
domname = args[0]
filename = args[1]
cfg = _read_python_cfg(filename)
print 'Creating VIF from %s ..' % filename
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
vif_uuid = execute(server, 'VIF.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % vif_uuid
else:
print 'Done. (%s)' % vif_uuid
def xapi_vbd_list(args, async = False):
server, session = connect()
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))
print VBD_LIST_FORMAT % {'device': 'Device',
'uuid' : 'UUID',
'VDI': 'VDI'}
for vbd in vbds:
vbd_struct = execute(server, 'VBD.get_record', (session, vbd))
print VBD_LIST_FORMAT % vbd_struct
def xapi_vbd_stats(args, async = False):
server, session = connect()
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))
for vbd_uuid in vbds:
print execute(server, 'VBD.get_io_read_kbs', (session, vbd_uuid))
def xapi_vif_list(args, async = False):
server, session = connect()
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vifs = execute(server, 'VM.get_VIFs', (session, dom_uuid))
if not is_long:
print VIF_LIST_FORMAT % {'name': 'Name',
'device': 'Device',
'uuid' : 'UUID',
'MAC': 'MAC'}
for vif in vifs:
vif_struct = execute(server, 'VIF.get_record', (session, vif))
print VIF_LIST_FORMAT % vif_struct
else:
for vif in vifs:
vif_struct = execute(server, 'VIF.get_record', (session, vif))
pprint(vif_struct)
def xapi_console_list(args, async = False):
server, session = connect()
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
consoles = execute(server, 'VM.get_consoles', (session, dom_uuid))
if not is_long:
print CONSOLE_LIST_FORMAT % {'protocol': 'Protocol',
'location': 'Location',
'uuid': 'UUID'}
for console in consoles:
console_struct = execute(server, 'console.get_record',
(session, console))
print CONSOLE_LIST_FORMAT % console_struct
else:
for console in consoles:
console_struct = execute(server, 'console.get_record',
(session, console))
pprint(console_struct)
def xapi_vdi_list(args, async = False):
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
server, session = connect()
vdis = execute(server, 'VDI.get_all', (session,))
if not is_long:
print VDI_LIST_FORMAT % {'name_label': 'VDI Label',
'uuid' : 'UUID',
'virtual_size': 'Bytes'}
for vdi in vdis:
vdi_struct = execute(server, 'VDI.get_record', (session, vdi))
print VDI_LIST_FORMAT % vdi_struct
else:
for vdi in vdis:
vdi_struct = execute(server, 'VDI.get_record', (session, vdi))
pprint(vdi_struct)
def xapi_sr_list(args, async = False):
opts, args = parse_args('sr-list', args, set_defaults = True)
is_long = opts and opts.long
server, session = connect()
srs = execute(server, 'SR.get_all', (session,))
if not is_long:
print SR_LIST_FORMAT % {'name_label': 'SR Label',
'uuid' : 'UUID',
'physical_size': 'Size (MB)',
'type': 'Type'}
for sr in srs:
sr_struct = execute(server, 'SR.get_record', (session, sr))
sr_struct['physical_size'] = int(sr_struct['physical_size'])/MB
print SR_LIST_FORMAT % sr_struct
else:
for sr in srs:
sr_struct = execute(server, 'SR.get_record', (session, sr))
pprint(sr_struct)
def xapi_sr_rename(args, async = False):
server, session = connect()
sr = execute(server, 'SR.get_by_name_label', (session, args[0]))
execute(server, 'SR.set_name_label', (session, sr[0], args[1]))
def xapi_vdi_create(args, async = False):
opts, args = parse_args('vdi-create', args)
if len(args) > 0:
cfg = _read_python_cfg(args[0])
else:
cfg = {}
for opt, val in opts:
cfg[opt] = val
server, session = connect()
srs = []
if cfg.get('SR'):
srs = execute(server, 'SR.get_by_name_label', (session, cfg['SR']))
else:
srs = execute(server, 'SR.get_all', (session,))
sr = srs[0]
cfg['SR'] = sr
size = cfg['virtual_size']/MB
print 'Creating VDI of size: %dMB ..' % size,
uuid = execute(server, 'VDI.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % uuid
else:
print 'Done. (%s)' % uuid
def xapi_vdi_destroy(args, async = False):
server, session = connect()
if len(args) < 1:
raise OptionError('Not enough arguments')
vdi_uuid = args[0]
print 'Deleting VDI %s' % vdi_uuid
result = execute(server, 'VDI.destroy', (session, vdi_uuid), async = async)
if async:
print 'Task started: %s' % result
else:
print 'Done.'
def xapi_vdi_rename(args, async = False):
server, session = connect()
if len(args) < 2:
raise OptionError('Not enough arguments')
vdi_uuid = execute(server, 'VDI.get_by_name_label', session, args[0])
vdi_name = args[1]
print 'Renaming VDI %s to %s' % (vdi_uuid[0], vdi_name)
result = execute(server, 'VDI.set_name_label',
(session, vdi_uuid[0], vdi_name), async = async)
if async:
print 'Task started: %s' % result
else:
print 'Done.'
def xapi_vtpm_create(args, async = False):
server, session = connect()
domname = args[0]
cfg = _read_python_cfg(args[1])
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
print "Creating vTPM with cfg = %s" % cfg
vtpm_uuid = execute(server, 'VTPM.create', (session, cfg))
print "Done. (%s)" % vtpm_uuid
def xapi_pif_list(args, async = False):
server, session = connect()
pif_uuids = execute(server, 'PIF.get_all', (session,))
for pif_uuid in pif_uuids:
pif = execute(server, 'PIF.get_record', (session, pif_uuid))
print pif
def xapi_debug_wait(args, async = False):
secs = 10
if len(args) > 0:
secs = int(args[0])
server, session = connect()
task_uuid = execute(server, 'debug.wait', (session, secs), async=async)
print 'Task UUID: %s' % task_uuid
def xapi_vm_stat(args, async = False):
domname = args[0]
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
vif_uuids = execute(server, 'VM.get_VIFs', (session, vm_uuid))
vbd_uuids = execute(server, 'VM.get_VBDs', (session, vm_uuid))
vcpus_utils = execute(server, 'VM.get_VCPUs_utilisation',
(session, vm_uuid))
for vcpu_num in sorted(vcpus_utils.keys()):
print 'CPU %s : %5.2f%%' % (vcpu_num, vcpus_utils[vcpu_num] * 100)
for vif_uuid in vif_uuids:
vif = execute(server, 'VIF.get_record', (session, vif_uuid))
print '%(device)s: rx: %(io_read_kbs)10.2f tx: %(io_write_kbs)10.2f' \
% vif
for vbd_uuid in vbd_uuids:
vbd = execute(server, 'VBD.get_record', (session, vbd_uuid))
print '%(device)s: rd: %(io_read_kbs)10.2f wr: %(io_write_kbs)10.2f' \
% vbd
#
# Command Line Utils
#
import cmd
import shlex
class XenAPICmd(cmd.Cmd):
def __init__(self, server, session):
cmd.Cmd.__init__(self)
self.server = server
self.session = session
self.prompt = ">>> "
def default(self, line):
words = shlex.split(line)
if len(words) > 0:
cmd_name = words[0].replace('-', '_')
is_async = 'async' in cmd_name
if is_async:
cmd_name = re.sub('async_', '', cmd_name)
func_name = 'xapi_%s' % cmd_name
func = globals().get(func_name)
if func:
try:
args = tuple(words[1:])
func(args, async = is_async)
return True
except SystemExit:
return False
except OptionError, e:
print 'Error:', str(e)
return False
except Exception, e:
import traceback
traceback.print_exc()
return False
print '*** Unknown command: %s' % words[0]
return False
def do_EOF(self, line):
print
sys.exit(0)
def do_help(self, line):
usage(print_usage = False)
def emptyline(self):
pass
def postcmd(self, stop, line):
return False
def precmd(self, line):
words = shlex.split(line)
if len(words) > 0:
words0 = words[0].replace('-', '_')
return ' '.join([words0] + words[1:])
else:
return line
def shell():
server, session = connect()
x = XenAPICmd(server, session)
x.cmdloop('Xen API Prompt. Type "help" for a list of functions')
def usage(command = None, print_usage = True):
if not command:
if print_usage:
print 'Usage: xapi <subcommand> [options] [args]'
print
print 'Subcommands:'
print
for func in sorted(globals().keys()):
if func.startswith('xapi_'):
command = func[5:].replace('_', '-')
args, description = COMMANDS.get(command, ('', ''))
print '%-16s %-40s' % (command, description)
print
else:
parse_args(command, ['-h'])
def main(args):
# poor man's optparse that doesn't abort on unrecognised opts
options = {}
remaining = []
arg_n = 0
while args:
arg = args.pop(0)
if arg in ('--help', '-h'):
options['help'] = True
elif arg in ('--server', '-s') and args:
options['server'] = args.pop(0)
elif arg in ('--user', '-u') and args:
options['user'] = args.pop(0)
elif arg in ('--password', '-p') and args:
options['password'] = args.pop(0)
else:
remaining.append(arg)
# abort here if these conditions are true
if options.get('help') and not remaining:
usage()
sys.exit(1)
if options.get('help') and remaining:
usage(remaining[0])
sys.exit(1)
if not remaining:
usage()
sys.exit(1)
if options.get('server'):
# it is ugly to use a global, but it is simple
global SERVER_URI
SERVER_URI = options['server']
if options.get('user'):
global SERVER_USER
SERVER_USER = options['user']
if options.get('password'):
global SERVER_PASS
SERVER_PASS = options['password']
subcmd = remaining[0].replace('-', '_')
is_async = 'async' in subcmd
if is_async:
subcmd = re.sub('async_', '', subcmd)
subcmd_func_name = 'xapi_' + subcmd
subcmd_func = globals().get(subcmd_func_name, None)
if subcmd == 'shell':
shell()
elif not subcmd_func or not callable(subcmd_func):
print 'Error: Unable to find subcommand \'%s\'' % subcmd
usage()
sys.exit(1)
try:
subcmd_func(remaining[1:], async = is_async)
except XenAPIError, e:
print 'Error: %s' % str(e.args[0])
sys.exit(2)
except OptionError, e:
print 'Error: %s' % e
sys.exit(0)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
| mikesun/xen-cow-checkpointing | tools/python/scripts/xapi.py | Python | gpl-2.0 | 29,258 |
/* Copyright 2005,2006 Sven Reimers, Florian Vogler
*
* This file is part of the Software Quality Environment Project.
*
* The Software Quality Environment Project 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.
*
* The Software Quality Environment Project 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package org.nbheaven.sqe.codedefects.history.action;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.nbheaven.sqe.codedefects.core.util.SQECodedefectSupport;
import org.nbheaven.sqe.codedefects.history.util.CodeDefectHistoryPersistence;
import org.netbeans.api.project.Project;
import org.openide.util.ContextAwareAction;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
/**
*
* @author Sven Reimers
*/
public class SnapshotAction extends AbstractAction implements LookupListener, ContextAwareAction {
private Lookup context;
private Lookup.Result<Project> lkpInfo;
public SnapshotAction() {
this(Utilities.actionsGlobalContext());
}
public SnapshotAction(Lookup context) {
putValue("noIconInMenu", Boolean.TRUE); // NOI18N
putValue(Action.SHORT_DESCRIPTION,
NbBundle.getMessage(SnapshotAction.class, "HINT_Action"));
putValue(SMALL_ICON, ImageUtilities.image2Icon(ImageUtilities.loadImage("org/nbheaven/sqe/codedefects/history/resources/camera.png")));
this.context = context;
//The thing we want to listen for the presence or absence of
//on the global selection
Lookup.Template<Project> tpl = new Lookup.Template<Project>(Project.class);
lkpInfo = context.lookup(tpl);
lkpInfo.addLookupListener(this);
resultChanged(null);
}
@Override
public Action createContextAwareInstance(Lookup context) {
return new SnapshotAction(context);
}
@Override
public void resultChanged(LookupEvent ev) {
updateEnableState();
}
public String getName() {
return NbBundle.getMessage(SnapshotAction.class, "LBL_Action");
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (null != getActiveProject()) {
Project project = getActiveProject();
CodeDefectHistoryPersistence.addSnapshot(project);
}
}
private void updateEnableState() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(() -> updateEnableState());
return;
}
setEnabled(SQECodedefectSupport.isQualityAwareProject(getActiveProject()));
}
private Project getActiveProject() {
Collection<? extends Project> projects = lkpInfo.allInstances();
if (projects.size() == 1) {
Project project = projects.iterator().next();
return project;
}
return null;
}
}
| sqe-team/sqe | codedefects.history/src/org/nbheaven/sqe/codedefects/history/action/SnapshotAction.java | Java | gpl-2.0 | 3,600 |
<?php
/**
* Image helper class
*
* This class was derived from the show_image_in_imgtag.php and imageTools.class.php files in VM. It provides some
* image functions that are used throughout the VirtueMart shop.
*
* @package VirtueMart
* @subpackage Helpers
* @author Max Milbers
* @copyright Copyright (c) 2004-2008 Soeren Eberhardt-Biermann, 2009 VirtueMart Team. All rights reserved.
*/
defined('_JEXEC') or die();
if (!class_exists('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'mediahandler.php');
class VmImage extends VmMediaHandler {
function processAction($data){
if(empty($data['media_action'])) return $data;
$data = parent::processAction($data);
if( $data['media_action'] == 'upload_create_thumb' ){
$oldFileUrl = $this->file_url;
$file_name = $this->uploadFile($this->file_url_folder);
if($file_name){
if($file_name!=$oldFileUrl && !empty($this->filename)){
$this->deleteFile($oldFileUrl);
}
$this->file_url = $this->file_url_folder.$file_name;
$this->filename = $file_name;
$oldFileUrlThumb = $this->file_url_thumb;
$this->file_url_thumb = $this->createThumb();
if($this->file_url_thumb!=$oldFileUrlThumb){
$this->deleteFile($oldFileUrlThumb);
}
}
} //creating the thumbnail image
else if( $data['media_action'] == 'create_thumb' ){
$this->file_url_thumb = $this->createThumb();
}
if(empty($this->file_title) && !empty($file_name)) $this->file_title = $file_name;
return $data;
}
function displayMediaFull($imageArgs='',$lightbox=true,$effect ="class='modal'",$description = true ){
if(!$this->file_is_forSale){
// Remote image URL
if( substr( $this->file_url, 0, 4) == "http" ) {
$file_url = $this->file_url;
$file_alt = $this->file_title;
} else {
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = JPATH_ROOT.DS.$rel_path.$this->file_name.'.'.$this->file_extension;
if (!file_exists($fullSizeFilenamePath)) {
$file_url = $this->theme_url.'assets/images/vmgeneral/'.VmConfig::get('no_image_found');
$file_alt = JText::_('COM_VIRTUEMART_NO_IMAGE_FOUND').' '.$this->file_description;
} else {
$file_url = $this->file_url;
$file_alt = $this->file_meta;
}
}
$postText = '';
if($description) $postText = $this->file_description;
return $this->displayIt($file_url, $file_alt, $imageArgs,$lightbox,'',$postText);
} else {
//Media which should be sold, show them only as thumb (works as preview)
return $this->displayMediaThumb('id="vm_display_image"',false);
}
}
/**
* a small function that ensures that we always build the thumbnail name with the same method
*/
public function createThumbName($width=0,$height=0){
if(empty($this->file_name)) return false;
if(empty($width)) $width = VmConfig::get('img_width', 90);
if(empty($height)) $height = VmConfig::get('img_height', 90);
$this->file_name_thumb = $this->file_name.'_'.$width.'x'.$height;
return $this->file_name_thumb;
}
/**
* This function actually creates the thumb
* and when it is instanciated with one of the getImage function automatically updates the db
*
* @author Max Milbers
* @param boolean $save Execute update function
* @return name of the thumbnail
*/
public function createThumb() {
$synchronise = JRequest::getString('synchronise',false);
if(!VmConfig::get('img_resize_enable') || $synchronise) return;
//now lets create the thumbnail, saving is done in this function
$width = VmConfig::get('img_width', 90);
$height = VmConfig::get('img_height', 90);
// Don't allow sizes beyond 2000 pixels //I dont think that this is good, should be config
// $width = min($width, 2000);
// $height = min($height, 2000);
$maxsize = false;
$bgred = 255;
$bggreen = 255;
$bgblue = 255;
$root = '';
if($this->file_is_forSale==0){
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = JPATH_ROOT.DS.$rel_path.$this->file_name.'.'.$this->file_extension;
} else {
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = $this->file_url_folder.$this->file_name.'.'.$this->file_extension;
}
$this->file_name_thumb = $this->createThumbName();
$file_path_thumb = str_replace('/',DS,$this->file_url_folder_thumb);
$resizedFilenamePath = JPATH_ROOT.DS.$file_path_thumb.$this->file_name_thumb.'.'.$this->file_extension;
$this->checkPathCreateFolders($file_path_thumb);
if (file_exists($fullSizeFilenamePath)) {
if (!class_exists('Img2Thumb')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'img2thumb.php');
$createdImage = new Img2Thumb($fullSizeFilenamePath, $width, $height, $resizedFilenamePath, $maxsize, $bgred, $bggreen, $bgblue);
if($createdImage){
return $this->file_url_folder_thumb.$this->file_name_thumb.'.'.$this->file_extension;
} else {
return 0;
}
} else {
vmError('Couldnt create thumb, file not found '.$fullSizeFilenamePath);
return 0;
}
}
public function checkPathCreateFolders($path){
$elements = explode(DS,$path);
$examine = JPATH_ROOT;
foreach($elements as $piece){
$examine = $examine.DS.$piece;
if(!JFolder::exists($examine)){
JFolder::create($examine);
vmInfo('create folder for resized image '.$examine);
}
}
}
/**
* Display an image icon for the given image and create a link to the given link.
*
* @param string $link Link to use in the href tag
* @param string $image Name of the image file to display
* @param string $text Text to use for the image alt text and to display under the image.
*/
public function displayImageButton($link, $imageclass, $text) {
$button = '<a title="' . $text . '" href="' . $link . '">';
$button .= '<span class="vmicon48 '.$imageclass.'"></span>';
$button .= '<br />' . $text.'</a>';
echo $button;
}
}
| Fundacion-AG/PaginaWebFAG | tmp/install_535533f62cdf3/administrator/components/com_virtuemart/helpers/image.php | PHP | gpl-2.0 | 5,890 |
/*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2007 - 2017 Fiji developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package spim.fiji.plugin;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import mpicbg.spim.data.sequence.Channel;
import mpicbg.spim.data.sequence.ViewDescription;
import mpicbg.spim.data.sequence.ViewId;
import mpicbg.spim.data.sequence.VoxelDimensions;
import mpicbg.spim.io.IOFunctions;
import net.imglib2.KDTree;
import net.imglib2.RealPoint;
import net.imglib2.neighborsearch.KNearestNeighborSearchOnKDTree;
import spim.fiji.plugin.queryXML.LoadParseQueryXML;
import spim.fiji.plugin.thinout.ChannelProcessThinOut;
import spim.fiji.plugin.thinout.Histogram;
import spim.fiji.spimdata.SpimData2;
import spim.fiji.spimdata.interestpoints.InterestPoint;
import spim.fiji.spimdata.interestpoints.InterestPointList;
import spim.fiji.spimdata.interestpoints.ViewInterestPointLists;
import spim.fiji.spimdata.interestpoints.ViewInterestPoints;
public class ThinOut_Detections implements PlugIn
{
public static boolean[] defaultShowHistogram;
public static int[] defaultSubSampling;
public static String[] defaultNewLabels;
public static int[] defaultRemoveKeep;
public static double[] defaultCutoffThresholdMin, defaultCutoffThresholdMax;
public static String[] removeKeepChoice = new String[]{ "Remove Range", "Keep Range" };
public static double defaultThresholdMinValue = 0;
public static double defaultThresholdMaxValue = 5;
public static int defaultSubSamplingValue = 1;
public static String defaultNewLabelText = "thinned-out";
public static int defaultRemoveKeepValue = 0; // 0 == remove, 1 == keep
@Override
public void run( final String arg )
{
final LoadParseQueryXML xml = new LoadParseQueryXML();
if ( !xml.queryXML( "", true, false, true, true ) )
return;
final SpimData2 data = xml.getData();
final List< ViewId > viewIds = SpimData2.getAllViewIdsSorted( data, xml.getViewSetupsToProcess(), xml.getTimePointsToProcess() );
// ask which channels have the objects we are searching for
final List< ChannelProcessThinOut > channels = getChannelsAndLabels( data, viewIds );
if ( channels == null )
return;
// get the actual min/max thresholds for cutting out
if ( !getThinOutThresholds( data, viewIds, channels ) )
return;
// thin out detections and save the new interestpoint files
if ( !thinOut( data, viewIds, channels, true ) )
return;
// write new xml
SpimData2.saveXML( data, xml.getXMLFileName(), xml.getClusterExtension() );
}
public static boolean thinOut( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels, final boolean save )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
for ( final ChannelProcessThinOut channel : channels )
{
final double minDistance = channel.getMin();
final double maxDistance = channel.getMax();
final boolean keepRange = channel.keepRange();
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList oldIpl = vipl.getInterestPointList( channel.getLabel() );
if ( oldIpl.getInterestPoints() == null )
oldIpl.loadInterestPoints();
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
// assemble the list of points (we need two lists as the KDTree sorts the list)
// we assume that the order of list2 and points is preserved!
final List< RealPoint > list1 = new ArrayList< RealPoint >();
final List< RealPoint > list2 = new ArrayList< RealPoint >();
final List< double[] > points = new ArrayList< double[] >();
for ( final InterestPoint ip : oldIpl.getInterestPoints() )
{
list1.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
list2.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
points.add( ip.getL() );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list1, list1 );
// Nearest neighbor for each point, populate the new list
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
final InterestPointList newIpl = new InterestPointList(
oldIpl.getBaseDir(),
new File(
oldIpl.getFile().getParentFile(),
"tpId_" + viewId.getTimePointId() + "_viewSetupId_" + viewId.getViewSetupId() + "." + channel.getNewLabel() ) );
newIpl.setInterestPoints( new ArrayList< InterestPoint >() );
int id = 0;
for ( int j = 0; j < list2.size(); ++j )
{
final RealPoint p = list2.get( j );
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
final double d = nn.getDistance( 1 );
if ( ( keepRange && d >= minDistance && d <= maxDistance ) || ( !keepRange && ( d < minDistance || d > maxDistance ) ) )
{
newIpl.getInterestPoints().add( new InterestPoint( id++, points.get( j ).clone() ) );
}
}
if ( keepRange )
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', kept range from " + minDistance + " to " + maxDistance );
else
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', removed range from " + minDistance + " to " + maxDistance );
vipl.addInterestPointList( channel.getNewLabel(), newIpl );
IOFunctions.println( new Date( System.currentTimeMillis() ) + ": TP=" + vd.getTimePointId() + " ViewSetup=" + vd.getViewSetupId() +
", Detections: " + oldIpl.getInterestPoints().size() + " >>> " + newIpl.getInterestPoints().size() );
if ( save && !newIpl.saveInterestPoints() )
{
IOFunctions.println( "Error saving interest point list: " + new File( newIpl.getBaseDir(), newIpl.getFile().toString() + newIpl.getInterestPointsExt() ) );
return false;
}
}
}
return true;
}
public static boolean getThinOutThresholds( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels )
{
for ( final ChannelProcessThinOut channel : channels )
if ( channel.showHistogram() )
plotHistogram( spimData, viewIds, channel );
if ( defaultCutoffThresholdMin == null || defaultCutoffThresholdMin.length != channels.size() ||
defaultCutoffThresholdMax == null || defaultCutoffThresholdMax.length != channels.size() )
{
defaultCutoffThresholdMin = new double[ channels.size() ];
defaultCutoffThresholdMax = new double[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
{
defaultCutoffThresholdMin[ i ] = defaultThresholdMinValue;
defaultCutoffThresholdMax[ i ] = defaultThresholdMaxValue;
}
}
if ( defaultRemoveKeep == null || defaultRemoveKeep.length != channels.size() )
{
defaultRemoveKeep = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultRemoveKeep[ i ] = defaultRemoveKeepValue;
}
final GenericDialog gd = new GenericDialog( "Define cut-off threshold" );
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
gd.addChoice( "Channel_" + channel.getChannel().getName() + "_", removeKeepChoice, removeKeepChoice[ defaultRemoveKeep[ c ] ] );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_lower_threshold", defaultCutoffThresholdMin[ c ], 2 );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_upper_threshold", defaultCutoffThresholdMax[ c ], 2 );
gd.addMessage( "" );
}
gd.showDialog();
if ( gd.wasCanceled() )
return false;
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
final int removeKeep = defaultRemoveKeep[ c ] = gd.getNextChoiceIndex();
if ( removeKeep == 1 )
channel.setKeepRange( true );
else
channel.setKeepRange( false );
channel.setMin( defaultCutoffThresholdMin[ c ] = gd.getNextNumber() );
channel.setMax( defaultCutoffThresholdMax[ c ] = gd.getNextNumber() );
if ( channel.getMin() >= channel.getMax() )
{
IOFunctions.println( "You selected the minimal threshold larger than the maximal threshold for channel " + channel.getChannel().getName() );
IOFunctions.println( "Stopping." );
return false;
}
else
{
if ( channel.keepRange() )
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": keep only distances from " + channel.getMin() + " >>> " + channel.getMax() );
else
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": remove distances from " + channel.getMin() + " >>> " + channel.getMax() );
}
}
return true;
}
public static Histogram plotHistogram( final SpimData2 spimData, final List< ViewId > viewIds, final ChannelProcessThinOut channel )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
// list of all distances
final ArrayList< Double > distances = new ArrayList< Double >();
final Random rnd = new Random( System.currentTimeMillis() );
String unit = null;
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList ipl = vipl.getInterestPointList( channel.getLabel() );
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
if ( ipl.getInterestPoints() == null )
ipl.loadInterestPoints();
if ( unit == null )
unit = vd.getViewSetup().getVoxelSize().unit();
// assemble the list of points
final List< RealPoint > list = new ArrayList< RealPoint >();
for ( final InterestPoint ip : ipl.getInterestPoints() )
{
list.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list, list );
// Nearest neighbor for each point
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
for ( final RealPoint p : list )
{
// every n'th point only
if ( rnd.nextDouble() < 1.0 / (double)channel.getSubsampling() )
{
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
distances.add( nn.getDistance( 1 ) );
}
}
}
final Histogram h = new Histogram( distances, 100, "Distance Histogram [Channel=" + channel.getChannel().getName() + "]", unit );
h.showHistogram();
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": min distance=" + h.getMin() + ", max distance=" + h.getMax() );
return h;
}
public static ArrayList< ChannelProcessThinOut > getChannelsAndLabels(
final SpimData2 spimData,
final List< ViewId > viewIds )
{
// build up the dialog
final GenericDialog gd = new GenericDialog( "Choose segmentations to thin out" );
final List< Channel > channels = SpimData2.getAllChannelsSorted( spimData, viewIds );
final int nAllChannels = spimData.getSequenceDescription().getAllChannelsOrdered().size();
if ( Interest_Point_Registration.defaultChannelLabels == null || Interest_Point_Registration.defaultChannelLabels.length != nAllChannels )
Interest_Point_Registration.defaultChannelLabels = new int[ nAllChannels ];
if ( defaultShowHistogram == null || defaultShowHistogram.length != channels.size() )
{
defaultShowHistogram = new boolean[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultShowHistogram[ i ] = true;
}
if ( defaultSubSampling == null || defaultSubSampling.length != channels.size() )
{
defaultSubSampling = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultSubSampling[ i ] = defaultSubSamplingValue;
}
if ( defaultNewLabels == null || defaultNewLabels.length != channels.size() )
{
defaultNewLabels = new String[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultNewLabels[ i ] = defaultNewLabelText;
}
// check which channels and labels are available and build the choices
final ArrayList< String[] > channelLabels = new ArrayList< String[] >();
int j = 0;
for ( final Channel channel : channels )
{
final String[] labels = Interest_Point_Registration.getAllInterestPointLabelsForChannel(
spimData,
viewIds,
channel,
"thin out" );
if ( Interest_Point_Registration.defaultChannelLabels[ j ] >= labels.length )
Interest_Point_Registration.defaultChannelLabels[ j ] = 0;
String ch = channel.getName().replace( ' ', '_' );
gd.addCheckbox( "Channel_" + ch + "_Display_distance_histogram", defaultShowHistogram[ j ] );
gd.addChoice( "Channel_" + ch + "_Interest_points", labels, labels[ Interest_Point_Registration.defaultChannelLabels[ j ] ] );
gd.addStringField( "Channel_" + ch + "_New_label", defaultNewLabels[ j ], 20 );
gd.addNumericField( "Channel_" + ch + "_Subsample histogram", defaultSubSampling[ j ], 0, 5, "times" );
channelLabels.add( labels );
++j;
}
gd.showDialog();
if ( gd.wasCanceled() )
return null;
// assemble which channels have been selected with with label
final ArrayList< ChannelProcessThinOut > channelsToProcess = new ArrayList< ChannelProcessThinOut >();
j = 0;
for ( final Channel channel : channels )
{
final boolean showHistogram = defaultShowHistogram[ j ] = gd.getNextBoolean();
final int channelChoice = Interest_Point_Registration.defaultChannelLabels[ j ] = gd.getNextChoiceIndex();
final String newLabel = defaultNewLabels[ j ] = gd.getNextString();
final int subSampling = defaultSubSampling[ j ] = (int)Math.round( gd.getNextNumber() );
if ( channelChoice < channelLabels.get( j ).length - 1 )
{
String label = channelLabels.get( j )[ channelChoice ];
if ( label.contains( Interest_Point_Registration.warningLabel ) )
label = label.substring( 0, label.indexOf( Interest_Point_Registration.warningLabel ) );
channelsToProcess.add( new ChannelProcessThinOut( channel, label, newLabel, showHistogram, subSampling ) );
}
++j;
}
return channelsToProcess;
}
public static void main( final String[] args )
{
new ThinOut_Detections().run( null );
}
}
| bigdataviewer/SPIM_Registration | src/main/java/spim/fiji/plugin/ThinOut_Detections.java | Java | gpl-2.0 | 15,827 |
<?
require_once("pdfoprdesubi.php");
$obj= new pdfreporte();
# $obj->AddPage();
# $obj->AliasNbPages();
# $obj->Cuerpo();
# $obj->Output();
$tb=$obj->bd->select($obj->sql);
if (!$tb->EOF)
{ //HAY DATOS
$obj->AliasNbPages();
$obj->AddPage();
$obj->Cuerpo();
$obj->Output();
}
else
{ //NO HAY DATOS
?>
<script>
alert('No hay informacion para procesar este reporte...');
location=("oprdesubi.php");
</script>
<?
}
?> | cidesa/roraima | web/reportes/reportes/tesoreria/roprdesubi.php | PHP | gpl-2.0 | 463 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2022 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
namespace Glpi\Tests\Api\Deprecated;
interface DeprecatedInterface
{
/**
* Get deprecated type
* @return string
*/
public static function getDeprecatedType(): string;
/**
* Get current type
* @return string
*/
public static function getCurrentType(): string;
/**
* Get deprecated expected fields
* @return array
*/
public static function getDeprecatedFields(): array;
/**
* Get current add input
* @return array
*/
public static function getCurrentAddInput(): array;
/**
* Get deprecated add input
* @return array
*/
public static function getDeprecatedAddInput(): array;
/**
* Get deprecated update input
* @return array
*/
public static function getDeprecatedUpdateInput(): array;
/**
* Get expected data after insert
* @return array
*/
public static function getExpectedAfterInsert(): array;
/**
* Get expected data after update
* @return array
*/
public static function getExpectedAfterUpdate(): array;
/**
* Get deprecated search query
* @return string
*/
public static function getDeprecatedSearchQuery(): string;
/**
* Get current search query
* @return string
*/
public static function getCurrentSearchQuery(): string;
}
| stweil/glpi | tests/src/Api/Deprecated/DeprecatedInterface.php | PHP | gpl-2.0 | 2,534 |
/*
* Copyright (C) 2005-2010 MaNGOS <http://getmangos.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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/** \file
\ingroup u2w
*/
#include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Player.h"
#include "ObjectMgr.h"
#include "Group.h"
#include "Guild.h"
#include "World.h"
#include "BattleGroundMgr.h"
#include "MapManager.h"
#include "SocialMgr.h"
#include "Auth/AuthCrypt.h"
#include "Auth/HMACSHA1.h"
#include "zlib/zlib.h"
// select opcodes appropriate for processing in Map::Update context for current session state
static bool MapSessionFilterHelper(WorldSession* session, OpcodeHandler const& opHandle)
{
// we do not process thread-unsafe packets
if (opHandle.packetProcessing == PROCESS_THREADUNSAFE)
return false;
// we do not process not loggined player packets
Player * plr = session->GetPlayer();
if (!plr)
return false;
// in Map::Update() we do not process packets where player is not in world!
return plr->IsInWorld();
}
bool MapSessionFilter::Process(WorldPacket * packet)
{
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
if (opHandle.packetProcessing == PROCESS_INPLACE)
return true;
// let's check if our opcode can be really processed in Map::Update()
return MapSessionFilterHelper(m_pSession, opHandle);
}
// we should process ALL packets when player is not in world/logged in
// OR packet handler is not thread-safe!
bool WorldSessionFilter::Process(WorldPacket* packet)
{
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
// check if packet handler is supposed to be safe
if (opHandle.packetProcessing == PROCESS_INPLACE)
return true;
// let's check if our opcode can't be processed in Map::Update()
return !MapSessionFilterHelper(m_pSession, opHandle);
}
/// WorldSession constructor
WorldSession::WorldSession(uint32 id, WorldSocket *sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
_player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion), _logoutTime(0),
m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_playerSave(false),
m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(sObjectMgr.GetIndexForLocale(locale)),
m_latency(0), m_tutorialState(TUTORIALDATA_UNCHANGED)
{
if (sock)
{
m_Address = sock->GetRemoteAddress ();
sock->AddReference ();
}
}
/// WorldSession destructor
WorldSession::~WorldSession()
{
///- unload player if not unloaded
if (_player)
LogoutPlayer (true);
/// - If have unclosed socket, close it
if (m_Socket)
{
m_Socket->CloseSocket ();
m_Socket->RemoveReference ();
m_Socket = NULL;
}
///- empty incoming packet queue
WorldPacket* packet;
while(_recvQueue.next(packet))
delete packet;
}
void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
{
sLog.outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt crash server?), skipped",
GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
}
/// Get the player name
char const* WorldSession::GetPlayerName() const
{
return GetPlayer() ? GetPlayer()->GetName() : "<none>";
}
/// Send a packet to the client
void WorldSession::SendPacket(WorldPacket const* packet)
{
if (!m_Socket)
return;
#ifdef MANGOS_DEBUG
// Code for network use statistic
static uint64 sendPacketCount = 0;
static uint64 sendPacketBytes = 0;
static time_t firstTime = time(NULL);
static time_t lastTime = firstTime; // next 60 secs start time
static uint64 sendLastPacketCount = 0;
static uint64 sendLastPacketBytes = 0;
time_t cur_time = time(NULL);
if((cur_time - lastTime) < 60)
{
sendPacketCount+=1;
sendPacketBytes+=packet->size();
sendLastPacketCount+=1;
sendLastPacketBytes+=packet->size();
}
else
{
uint64 minTime = uint64(cur_time - lastTime);
uint64 fullTime = uint64(lastTime - firstTime);
DETAIL_LOG("Send all time packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u",sendPacketCount,sendPacketBytes,float(sendPacketCount)/fullTime,float(sendPacketBytes)/fullTime,uint32(fullTime));
DETAIL_LOG("Send last min packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f",sendLastPacketCount,sendLastPacketBytes,float(sendLastPacketCount)/minTime,float(sendLastPacketBytes)/minTime);
lastTime = cur_time;
sendLastPacketCount = 1;
sendLastPacketBytes = packet->wpos(); // wpos is real written size
}
#endif // !MANGOS_DEBUG
if (m_Socket->SendPacket (*packet) == -1)
m_Socket->CloseSocket ();
}
/// Add an incoming packet to the queue
void WorldSession::QueuePacket(WorldPacket* new_packet)
{
_recvQueue.add(new_packet);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char *reason)
{
sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(),
reason);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnprocessedTail(WorldPacket *packet)
{
sLog.outError( "SESSION: opcode %s (0x%.4X) have unprocessed tail data (read stop at " SIZEFMTD " from " SIZEFMTD ")",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(),
packet->rpos(),packet->wpos());
}
/// Update the WorldSession (triggered by World update)
bool WorldSession::Update(uint32 diff, PacketFilter& updater)
{
///- Retrieve packets from the receive queue and call the appropriate handlers
/// not process packets if socket already closed
WorldPacket* packet;
while (m_Socket && !m_Socket->IsClosed() && _recvQueue.next(packet, updater))
{
/*#if 1
sLog.outError( "MOEP: %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
#endif*/
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
try
{
switch (opHandle.status)
{
case STATUS_LOGGEDIN:
if(!_player)
{
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
if(!m_playerRecentlyLogout)
LogUnexpectedOpcode(packet, "the player has not logged in yet");
}
else if(_player->IsInWorld())
ExecuteOpcode(opHandle, packet);
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break;
case STATUS_LOGGEDIN_OR_RECENTLY_LOGGEDOUT:
if(!_player && !m_playerRecentlyLogout)
{
LogUnexpectedOpcode(packet, "the player has not logged in yet and not recently logout");
}
else
// not expected _player or must checked in packet hanlder
ExecuteOpcode(opHandle, packet);
break;
case STATUS_TRANSFER:
if(!_player)
LogUnexpectedOpcode(packet, "the player has not logged in yet");
else if(_player->IsInWorld())
LogUnexpectedOpcode(packet, "the player is still in world");
else
ExecuteOpcode(opHandle, packet);
break;
case STATUS_AUTHED:
// prevent cheating with skip queue wait
if(m_inQueue)
{
LogUnexpectedOpcode(packet, "the player not pass queue yet");
break;
}
// single from authed time opcodes send in to after logout time
// and before other STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes.
if (packet->GetOpcode() != CMSG_SET_ACTIVE_VOICE_CHANNEL)
m_playerRecentlyLogout = false;
ExecuteOpcode(opHandle, packet);
break;
case STATUS_NEVER:
sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
case STATUS_UNHANDLED:
DEBUG_LOG("SESSION: received not handled opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
default:
sLog.outError("SESSION: received wrong-status-req opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
}
}
catch (ByteBufferException &)
{
sLog.outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i.",
packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
{
sLog.outDebug("Dumping error causing packet:");
packet->hexlike();
}
if (sWorld.getConfig(CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET))
{
DETAIL_LOG("Disconnecting session [account id %u / address %s] for badly formatted packet.",
GetAccountId(), GetRemoteAddress().c_str());
KickPlayer();
}
}
delete packet;
}
///- Cleanup socket pointer if need
if (m_Socket && m_Socket->IsClosed ())
{
m_Socket->RemoveReference ();
m_Socket = NULL;
}
//check if we are safe to proceed with logout
//logout procedure should happen only in World::UpdateSessions() method!!!
if(updater.ProcessLogout())
{
///- If necessary, log the player out
time_t currTime = time(NULL);
if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
LogoutPlayer(true);
if (!m_Socket)
return false; //Will remove this session from the world session map
}
return true;
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool Save)
{
// finish pending transfers before starting the logout
while(_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
m_playerLogout = true;
m_playerSave = Save;
if (_player)
{
sLog.outChar("Account: %d (IP: %s) Logout Character:[%s] (guid: %u)", GetAccountId(), GetRemoteAddress().c_str(), _player->GetName() ,_player->GetGUIDLow());
if (uint64 lguid = GetPlayer()->GetLootGUID())
DoLootRelease(lguid);
///- If the player just died before logging out, make him appear as a ghost
//FIXME: logout must be delayed in case lost connection with client in time of combat
if (_player->GetDeathTimer())
{
_player->getHostileRefManager().deleteReferences();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (!_player->getAttackers().empty())
{
_player->CombatStop();
_player->getHostileRefManager().setOnlineOfflineState(false);
_player->RemoveAllAurasOnDeath();
// build set of player who attack _player or who have pet attacking of _player
std::set<Player*> aset;
for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
{
Unit* owner = (*itr)->GetOwner(); // including player controlled case
if(owner)
{
if(owner->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)owner);
}
else
if((*itr)->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)(*itr));
}
_player->SetPvPDeath(!aset.empty());
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
// give honor to all attackers from set like group case
for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
(*itr)->RewardHonor(_player,aset.size());
// give bg rewards and update counters like kill by first from attackers
// this can't be called for all attackers.
if(!aset.empty())
if(BattleGround *bg = _player->GetBattleGround())
bg->HandleKillPlayer(_player,*aset.begin());
}
else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
{
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
//_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
//drop a flag if player is carrying it
if(BattleGround *bg = _player->GetBattleGround())
bg->EventPlayerLoggedOut(_player);
///- Teleport to home if the player is in an invalid instance
if(!_player->m_InstanceValid && !_player->isGameMaster())
{
_player->TeleportToHomebind();
//this is a bad place to call for far teleport because we need player to be in world for successful logout
//maybe we should implement delayed far teleport logout?
}
// FG: finish pending transfers after starting the logout
// this should fix players beeing able to logout and login back with full hp at death position
while(_player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if(BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i))
{
_player->RemoveBattleGroundQueueId(bgQueueTypeId);
sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetObjectGuid(), true);
}
}
///- Reset the online field in the account table
// no point resetting online in character table here as Player::SaveToDB() will set it to 1 since player has not been removed from world at this stage
// No SQL injection as AccountID is uint32
LoginDatabase.PExecute("UPDATE account SET active_realm_id = 0 WHERE id = '%u'", GetAccountId());
///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
if (Guild *guild = sObjectMgr.GetGuildById(_player->GetGuildId()))
{
if (MemberSlot* slot = guild->GetMemberSlot(_player->GetObjectGuid()))
{
slot->SetMemberStats(_player);
slot->UpdateLogoutTime();
}
guild->BroadcastEvent(GE_SIGNED_OFF, _player->GetGUID(), _player->GetName());
}
///- Remove pet
_player->RemovePet(PET_SAVE_AS_CURRENT);
///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc)
if(Save)
{
uint32 eslot;
for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
{
eslot = j - BUYBACK_SLOT_START;
_player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
}
_player->SaveToDB();
}
///- Leave all channels before player delete...
_player->CleanupChannels();
///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
_player->UninviteFromGroup();
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
_player->RemoveFromGroup();
///- Send update to group
if(_player->GetGroup())
_player->GetGroup()->SendUpdate();
///- Broadcast a logout message to the player's friends
sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetObjectGuid(), true);
sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
///- Remove the player from the world
// the player may not be in the world when logging out
// e.g if he got disconnected during a transfer to another map
// calls to GetMap in this case may cause crashes
Map* _map = _player->GetMap();
_map->Remove(_player, true);
SetPlayer(NULL); // deleted in Remove call
///- Send the 'logout complete' packet to the client
WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
SendPacket( &data );
///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
//No SQL injection as AccountId is uint32
CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
GetAccountId());
DEBUG_LOG( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
}
m_playerLogout = false;
m_playerSave = false;
m_playerRecentlyLogout = true;
LogoutRequest(0);
}
/// Kick a player out of the World
void WorldSession::KickPlayer()
{
if (m_Socket)
m_Socket->CloseSocket ();
}
/// Cancel channeling handler
void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, Text);
vsnprintf( szStr, 1024, Text, ap );
va_end(ap);
uint32 length = strlen(szStr)+1;
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
data << length;
data << szStr;
SendPacket(&data);
}
void WorldSession::SendNotification(const char *format,...)
{
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, format);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendNotification(int32 string_id,...)
{
char const* format = GetMangosString(string_id);
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, string_id);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendSetPhaseShift(uint32 PhaseShift)
{
WorldPacket data(SMSG_SET_PHASE_SHIFT, 4);
data << uint32(PhaseShift);
SendPacket(&data);
}
const char * WorldSession::GetMangosString( int32 entry ) const
{
return sObjectMgr.GetMangosString(entry,GetSessionDbLocaleIndex());
}
void WorldSession::Handle_NULL( WorldPacket& recvPacket )
{
DEBUG_LOG("SESSION: received unimplemented opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
{
sLog.outError("SESSION: received server-side opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_Deprecated( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::SendAuthWaitQue(uint32 position)
{
if(position == 0)
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
packet << uint8( AUTH_OK );
SendPacket(&packet);
}
else
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 1+4+1 );
packet << uint8(AUTH_WAIT_QUEUE);
packet << uint32(position);
packet << uint8(0); // unk 3.3.0
SendPacket(&packet);
}
}
void WorldSession::LoadGlobalAccountData()
{
LoadAccountData(
CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId()),
GLOBAL_CACHE_MASK
);
}
void WorldSession::LoadAccountData(QueryResult* result, uint32 mask)
{
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
m_accountData[i] = AccountData();
if(!result)
return;
do
{
Field *fields = result->Fetch();
uint32 type = fields[0].GetUInt32();
if (type >= NUM_ACCOUNT_DATA_TYPES)
{
sLog.outError("Table `%s` have invalid account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
if ((mask & (1 << type))==0)
{
sLog.outError("Table `%s` have non appropriate for table account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
m_accountData[type].Time = time_t(fields[1].GetUInt64());
m_accountData[type].Data = fields[2].GetCppString();
} while (result->NextRow());
delete result;
}
void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::string data)
{
if ((1 << type) & GLOBAL_CACHE_MASK)
{
uint32 acc = GetAccountId();
CharacterDatabase.BeginTransaction ();
CharacterDatabase.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc, type);
std::string safe_data = data;
CharacterDatabase.escape_string(safe_data);
CharacterDatabase.PExecute("INSERT INTO account_data VALUES ('%u','%u','" UI64FMTD "','%s')", acc, type, uint64(time_), safe_data.c_str());
CharacterDatabase.CommitTransaction ();
}
else
{
// _player can be NULL and packet received after logout but m_GUID still store correct guid
if(!m_GUIDLow)
return;
CharacterDatabase.BeginTransaction ();
CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid='%u' AND type='%u'", m_GUIDLow, type);
std::string safe_data = data;
CharacterDatabase.escape_string(safe_data);
CharacterDatabase.PExecute("INSERT INTO character_account_data VALUES ('%u','%u','" UI64FMTD "','%s')", m_GUIDLow, type, uint64(time_), safe_data.c_str());
CharacterDatabase.CommitTransaction ();
}
m_accountData[type].Time = time_;
m_accountData[type].Data = data;
}
void WorldSession::SendAccountDataTimes(uint32 mask)
{
WorldPacket data( SMSG_ACCOUNT_DATA_TIMES, 4+1+4+8*4 ); // changed in WotLK
data << uint32(time(NULL)); // unix time of something
data << uint8(1);
data << uint32(mask); // type mask
for(uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if(mask & (1 << i))
data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
SendPacket(&data);
}
void WorldSession::LoadTutorialsData()
{
for ( int aX = 0 ; aX < 8 ; ++aX )
m_Tutorials[ aX ] = 0;
QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId());
if(!result)
{
m_tutorialState = TUTORIALDATA_NEW;
return;
}
do
{
Field *fields = result->Fetch();
for (int iI = 0; iI < 8; ++iI)
m_Tutorials[iI] = fields[iI].GetUInt32();
}
while( result->NextRow() );
delete result;
m_tutorialState = TUTORIALDATA_UNCHANGED;
}
void WorldSession::SendTutorialsData()
{
WorldPacket data(SMSG_TUTORIAL_FLAGS, 4*8);
for(uint32 i = 0; i < 8; ++i)
data << m_Tutorials[i];
SendPacket(&data);
}
void WorldSession::SaveTutorialsData()
{
switch(m_tutorialState)
{
case TUTORIALDATA_CHANGED:
CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u'",
m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetAccountId());
break;
case TUTORIALDATA_NEW:
CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
GetAccountId(), m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
break;
case TUTORIALDATA_UNCHANGED:
break;
}
m_tutorialState = TUTORIALDATA_UNCHANGED;
}
void WorldSession::ReadAddonsInfo(WorldPacket &data)
{
if (data.rpos() + 4 > data.size())
return;
uint32 size;
data >> size;
if(!size)
return;
if(size > 0xFFFFF)
{
sLog.outError("WorldSession::ReadAddonsInfo addon info too big, size %u", size);
return;
}
uLongf uSize = size;
uint32 pos = data.rpos();
ByteBuffer addonInfo;
addonInfo.resize(size);
if (uncompress(const_cast<uint8*>(addonInfo.contents()), &uSize, const_cast<uint8*>(data.contents() + pos), data.size() - pos) == Z_OK)
{
uint32 addonsCount;
addonInfo >> addonsCount; // addons count
for(uint32 i = 0; i < addonsCount; ++i)
{
std::string addonName;
uint8 enabled;
uint32 crc, unk1;
// check next addon data format correctness
if(addonInfo.rpos()+1 > addonInfo.size())
return;
addonInfo >> addonName;
addonInfo >> enabled >> crc >> unk1;
DEBUG_LOG("ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);
m_addonsList.push_back(AddonInfo(addonName, enabled, crc));
}
uint32 unk2;
addonInfo >> unk2;
if(addonInfo.rpos() != addonInfo.size())
DEBUG_LOG("packet under read!");
}
else
sLog.outError("Addon packet uncompress error!");
}
void WorldSession::SendAddonsInfo()
{
unsigned char tdata[256] =
{
0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
};
WorldPacket data(SMSG_ADDON_INFO, 4);
for(AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
{
uint8 state = 2; // 2 is sent here
data << uint8(state);
uint8 unk1 = 1; // 1 is sent here
data << uint8(unk1);
if (unk1)
{
uint8 unk2 = (itr->CRC != 0x4c1c776d); // If addon is Standard addon CRC
data << uint8(unk2); // if 1, than add addon public signature
if (unk2) // if CRC is wrong, add public key (client need it)
data.append(tdata, sizeof(tdata));
data << uint32(0);
}
uint8 unk3 = 0; // 0 is sent here
data << uint8(unk3); // use <Addon>\<Addon>.url file or not
if (unk3)
{
// String, 256 (null terminated?)
data << uint8(0);
}
}
m_addonsList.clear();
uint32 count = 0;
data << uint32(count); // BannedAddons count
/*for(uint32 i = 0; i < count; ++i)
{
uint32
string (16 bytes)
string (16 bytes)
uint32
uint32
uint32
}*/
SendPacket(&data);
}
void WorldSession::SetPlayer( Player *plr )
{
_player = plr;
// set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
if(_player)
m_GUIDLow = _player->GetGUIDLow();
}
void WorldSession::SendRedirectClient(std::string& ip, uint16 port)
{
uint32 ip2 = ACE_OS::inet_addr(ip.c_str());
WorldPacket pkt(SMSG_REDIRECT_CLIENT, 4 + 2 + 4 + 20);
pkt << uint32(ip2); // inet_addr(ipstr)
pkt << uint16(port); // port
pkt << uint32(GetLatency()); // latency-related?
HMACSHA1 sha1(20, m_Socket->GetSessionKey().AsByteArray());
sha1.UpdateData((uint8*)&ip2, 4);
sha1.UpdateData((uint8*)&port, 2);
sha1.Finalize();
pkt.append(sha1.GetDigest(), 20); // hmacsha1(ip+port) w/ sessionkey as seed
SendPacket(&pkt);
}
void WorldSession::ExecuteOpcode( OpcodeHandler const& opHandle, WorldPacket* packet )
{
// need prevent do internal far teleports in handlers because some handlers do lot steps
// or call code that can do far teleports in some conditions unexpectedly for generic way work code
if (_player)
_player->SetCanDelayTeleport(true);
(this->*opHandle.handler)(*packet);
if (_player)
{
// can be not set in fact for login opcode, but this not create porblems.
_player->SetCanDelayTeleport(false);
//we should execute delayed teleports only for alive(!) players
//because we don't want player's ghost teleported from graveyard
if (_player->IsHasDelayedTeleport())
_player->TeleportTo(_player->m_teleport_dest, _player->m_teleport_options);
}
if (packet->rpos() < packet->wpos() && sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
LogUnprocessedTail(packet);
}
| koksneo/MangosBack | src/game/WorldSession.cpp | C++ | gpl-2.0 | 34,123 |
function ValidarPuntaje(id)
{
var aux = id.split("_");
var name=aux[0];
var fil=parseInt(aux[1]);
var col=parseInt(aux[2]);
var colpuntaje=col;
var colpuntajereal=col+1;
var puntaje=name+"_"+fil+"_"+colpuntaje;
var puntajereal=name+"_"+fil+"_"+colpuntajereal;
var num1=toFloat(puntaje);
var num2=toFloat(puntajereal);
if (num1>num2)
{
alert("El puntaje introducido no puede ser mayor al definido: "+$(puntajereal).value);
$(puntaje).value="0.00";
}
}
function totalizar()
{
var monrec=toFloat('cobdocume_recdoc');
var dscdoc=toFloat('cobdocume_dscdoc');
var abodoc=toFloat('cobdocume_abodoc');
var mondoc=toFloat('cobdocume_mondoc');
var tototal= mondoc+monrec-dscdoc+abodoc;
$('cobdocume_saldoc').value=format(tototal.toFixed(2),'.',',','.');
}
| cidesa/roraima | web/js/licitaciones/liasptecanalisis.js | JavaScript | gpl-2.0 | 835 |
/*
* XMIResultFormatter.java
*
* Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU General Public License.
*
* authors: Andreas Fay, Jannik Strötgen
* email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de
*
* HeidelTime is a multilingual, cross-domain temporal tagger.
* For details, see http://dbs.ifi.uni-heidelberg.de/heideltime
*/
package de.unihd.dbs.heideltime.standalone.components.impl;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.cas.impl.XmiCasSerializer;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.XMLSerializer;
import de.unihd.dbs.heideltime.standalone.components.ResultFormatter;
/**
* Result formatter based on XMI.
*
* @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer}
*
* @author Andreas Fay, University of Heidelberg
* @version 1.0
*/
public class XMIResultFormatter implements ResultFormatter {
@Override
public String format(JCas jcas) throws Exception {
ByteArrayOutputStream outStream = null;
try {
// Write XMI
outStream = new ByteArrayOutputStream();
XmiCasSerializer ser = new XmiCasSerializer(jcas.getTypeSystem());
XMLSerializer xmlSer = new XMLSerializer(outStream, false);
ser.serialize(jcas.getCas(), xmlSer.getContentHandler());
// Convert output stream to string
// String newOut = outStream.toString("UTF-8");
String newOut = outStream.toString();
// System.err.println("NEWOUT:"+newOut);
//
// if (newOut.matches("^<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>.*$")){
// newOut = newOut.replaceFirst("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>",
// "<\\?xml version=\"1.0\" encoding=\""+Charset.defaultCharset().name()+"\"\\?>");
// }
// if (newOut.matches("^.*?sofaString=\"(.*?)\".*$")){
// for (MatchResult r : findMatches(Pattern.compile("^(.*?sofaString=\")(.*?)(\".*)$"), newOut)){
// String stringBegin = r.group(1);
// String sofaString = r.group(2);
// System.err.println("SOFASTRING:"+sofaString);
// String stringEnd = r.group(3);
// // The sofaString is encoded as UTF-8.
// // However, at this point it has to be translated back into the defaultCharset.
// byte[] defaultDocText = new String(sofaString.getBytes(), "UTF-8").getBytes(Charset.defaultCharset().name());
// String docText = new String(defaultDocText);
// System.err.println("DOCTEXT:"+docText);
// newOut = stringBegin + docText + stringEnd;
//// newOut = newOut.replaceFirst("sofaString=\".*?\"", "sofaString=\"" + docText + "\"");
// }
// }
// System.err.println("NEWOUT:"+newOut);
return newOut;
} finally {
if (outStream != null) {
outStream.close();
}
}
}
/**
* Find all the matches of a pattern in a charSequence and return the
* results as list.
*
* @param pattern
* @param s
* @return
*/
public static Iterable<MatchResult> findMatches(Pattern pattern,
CharSequence s) {
List<MatchResult> results = new ArrayList<MatchResult>();
for (Matcher m = pattern.matcher(s); m.find();)
results.add(m.toMatchResult());
return results;
}
}
| reboutli-crim/heideltime | src/main/java/de/unihd/dbs/heideltime/standalone/components/impl/XMIResultFormatter.java | Java | gpl-3.0 | 3,537 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 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/>.
*
*/
/**
* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino Sd2Card Library
*/
#include "../inc/MarlinConfig.h"
#if ENABLED(SDSUPPORT)
#include "SdFile.h"
/**
* Create a file object and open it in the current working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*/
SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) { }
/**
* Write data to an open file.
*
* \note Data is moved to the cache but may not be written to the
* storage device until sync() is called.
*
* \param[in] buf Pointer to the location of the data to be written.
*
* \param[in] nbyte Number of bytes to write.
*
* \return For success write() returns the number of bytes written, always
* \a nbyte. If an error occurs, write() returns -1. Possible errors
* include write() is called before a file has been opened, write is called
* for a read-only file, device is full, a corrupt file system or an I/O error.
*
*/
int16_t SdFile::write(const void* buf, uint16_t nbyte) { return SdBaseFile::write(buf, nbyte); }
/**
* Write a byte to a file. Required by the Arduino Print class.
* \param[in] b the byte to be written.
* Use writeError to check for errors.
*/
#if ARDUINO >= 100
size_t SdFile::write(uint8_t b) { return SdBaseFile::write(&b, 1); }
#else
void SdFile::write(uint8_t b) { SdBaseFile::write(&b, 1); }
#endif
/**
* Write a string to a file. Used by the Arduino Print class.
* \param[in] str Pointer to the string.
* Use writeError to check for errors.
*/
void SdFile::write(const char* str) { SdBaseFile::write(str, strlen(str)); }
/**
* Write a PROGMEM string to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::write_P(PGM_P str) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
}
/**
* Write a PROGMEM string followed by CR/LF to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::writeln_P(PGM_P str) {
write_P(str);
write_P(PSTR("\r\n"));
}
#endif // SDSUPPORT
| MoonshineSG/Marlin | Marlin/src/sd/SdFile.cpp | C++ | gpl-3.0 | 3,173 |
/***********************************************************************
*
* Copyright (C) 2011, 2014 Graeme Gott <graeme@gottcode.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#include "clipboard_windows.h"
#include <QMimeData>
//-----------------------------------------------------------------------------
RTF::Clipboard::Clipboard() :
QWinMime()
{
CF_RTF = QWinMime::registerMimeType(QLatin1String("Rich Text Format"));
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::canConvertFromMime(const FORMATETC& format, const QMimeData* mime_data) const
{
return (format.cfFormat == CF_RTF) && mime_data->hasFormat(QLatin1String("text/rtf"));
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::canConvertToMime(const QString& mime_type, IDataObject* data_obj) const
{
bool result = false;
if (mime_type == QLatin1String("text/rtf")) {
FORMATETC format = initFormat();
format.tymed |= TYMED_ISTREAM;
result = (data_obj->QueryGetData(&format) == S_OK);
}
return result;
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::convertFromMime(const FORMATETC& format, const QMimeData* mime_data, STGMEDIUM* storage_medium) const
{
if (canConvertFromMime(format, mime_data)) {
QByteArray data = mime_data->data(QLatin1String("text/rtf"));
HANDLE data_handle = GlobalAlloc(0, data.size());
if (!data_handle) {
return false;
}
void* data_ptr = GlobalLock(data_handle);
memcpy(data_ptr, data.data(), data.size());
GlobalUnlock(data_handle);
storage_medium->tymed = TYMED_HGLOBAL;
storage_medium->hGlobal = data_handle;
storage_medium->pUnkForRelease = NULL;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
QVariant RTF::Clipboard::convertToMime(const QString& mime_type, IDataObject* data_obj, QVariant::Type preferred_type) const
{
Q_UNUSED(preferred_type);
QVariant result;
if (canConvertToMime(mime_type, data_obj)) {
QByteArray data;
FORMATETC format = initFormat();
format.tymed |= TYMED_ISTREAM;
STGMEDIUM storage_medium;
if (data_obj->GetData(&format, &storage_medium) == S_OK) {
if (storage_medium.tymed == TYMED_HGLOBAL) {
char* data_ptr = reinterpret_cast<char*>(GlobalLock(storage_medium.hGlobal));
data = QByteArray::fromRawData(data_ptr, GlobalSize(storage_medium.hGlobal));
data.detach();
GlobalUnlock(storage_medium.hGlobal);
} else if (storage_medium.tymed == TYMED_ISTREAM) {
char buffer[4096];
ULONG amount_read = 0;
LARGE_INTEGER pos = {{0, 0}};
HRESULT stream_result = storage_medium.pstm->Seek(pos, STREAM_SEEK_SET, NULL);
while (SUCCEEDED(stream_result)) {
stream_result = storage_medium.pstm->Read(buffer, sizeof(buffer), &amount_read);
if (SUCCEEDED(stream_result) && (amount_read > 0)) {
data += QByteArray::fromRawData(buffer, amount_read);
}
if (amount_read != sizeof(buffer)) {
break;
}
}
data.detach();
}
ReleaseStgMedium(&storage_medium);
}
if (!data.isEmpty()) {
result = data;
}
}
return result;
}
//-----------------------------------------------------------------------------
QVector<FORMATETC> RTF::Clipboard::formatsForMime(const QString& mime_type, const QMimeData* mime_data) const
{
QVector<FORMATETC> result;
if ((mime_type == QLatin1String("text/rtf")) && mime_data->hasFormat(QLatin1String("text/rtf"))) {
result += initFormat();
}
return result;
}
//-----------------------------------------------------------------------------
QString RTF::Clipboard::mimeForFormat(const FORMATETC& format) const
{
if (format.cfFormat == CF_RTF) {
return QLatin1String("text/rtf");
}
return QString();
}
//-----------------------------------------------------------------------------
FORMATETC RTF::Clipboard::initFormat() const
{
FORMATETC format;
format.cfFormat = CF_RTF;
format.ptd = NULL;
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
return format;
}
//-----------------------------------------------------------------------------
| barak/focuswriter | src/fileformats/clipboard_windows.cpp | C++ | gpl-3.0 | 4,898 |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'ismail@kartoza.com'
__revision__ = '$Format:%H$'
__date__ = '10/12/15'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import json
from types import NoneType
from safe.common.exceptions import MetadataCastError
from safe.metadata.property import BaseProperty
class ListProperty(BaseProperty):
"""A property that accepts list input."""
# if you edit this you need to adapt accordingly xml_value and is_valid
_allowed_python_types = [list, NoneType]
def __init__(self, name, value, xml_path):
super(ListProperty, self).__init__(
name, value, xml_path, self._allowed_python_types)
@classmethod
def is_valid(cls, value):
return True
def cast_from_str(self, value):
try:
return json.loads(value)
except ValueError as e:
raise MetadataCastError(e)
@property
def xml_value(self):
if self.python_type is list:
return json.dumps(self.value)
elif self.python_type is NoneType:
return ''
else:
raise RuntimeError('self._allowed_python_types and self.xml_value'
'are out of sync. This should never happen')
| Gustry/inasafe | safe/metadata/property/list_property.py | Python | gpl-3.0 | 1,695 |
<?php defined('PHALAPI_INSTALL') || die('no access'); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://webtools.qiniudn.com/dog_catch.png">
<title>快速安装 - PhalApi</title>
<link href="./static/css/pintuer.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- <script src="../../assets/js/ie-emulation-modes-warning.js"></script> -->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<style>
body{
background-color:#333;
color: #fff;
}
.window{
height: auto; margin: 0px auto;margin-top: 50px
}
.window_big{
width: 800px;
}
.window_small{
width: 600px;
}
.window_title{
border-radius: 4px 4px 0px 0px;padding: 20px;
}
.t_normal{
background-color: #FCB244 !important;
}
.t_error{
background-color: #DE4E4E
}
.t_success{
background-color: #7AC997
}
.footer{text-align: center;color: #333;}
</style>
<body>
<div class="container">
| xiaolovecai/PhalApi | Public/install/_header.php | PHP | gpl-3.0 | 1,762 |
/*
* Copyright 2011-2019 Arx Libertatis Team (see the AUTHORS file)
*
* This file is part of Arx Libertatis.
*
* Arx Libertatis 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.
*
* Arx Libertatis 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 Arx Libertatis. If not, see <http://www.gnu.org/licenses/>.
*
* Based on:
*
* blast.c
* Copyright (C) 2003 Mark Adler
* For conditions of distribution and use, see copyright notice in Blast.h
* version 1.1, 16 Feb 2003
*
* blast.c decompresses data compressed by the PKWare Compression Library.
* This function provides functionality similar to the explode() function of
* the PKWare library, hence the name "blast".
*
* This decompressor is based on the excellent format description provided by
* Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the
* example Ben provided in the post is incorrect. The distance 110001 should
* instead be 111000. When corrected, the example byte stream becomes:
*
* 00 04 82 24 25 8f 80 7f
*
* which decompresses to "AIAIAIAIAIAIA" (without the quotes).
*/
#include "io/Blast.h"
#include <cstring>
#include <cstdlib>
#include <exception>
#include "io/log/Logger.h"
#define MAXBITS 13 /* maximum code length */
#define MAXWIN 4096 /* maximum window size */
namespace {
struct blast_truncated_error : public std::exception { };
} // anonymous namespace
/* input and output state */
struct state {
/* input state */
blast_in infun; /* input function provided by user */
void * inhow; /* opaque information passed to infun() */
const unsigned char * in; /* next input location */
unsigned left; /* available input at in */
int bitbuf; /* bit buffer */
int bitcnt; /* number of bits in bit buffer */
/* output state */
blast_out outfun; /* output function provided by user */
void * outhow; /* opaque information passed to outfun() */
unsigned next; /* index of next write location in out[] */
int first; /* true to check distances (for first 4K) */
unsigned char out[MAXWIN]; /* output buffer and sliding window */
};
/*
* Return need bits from the input stream. This always leaves less than
* eight bits in the buffer. bits() works properly for need == 0.
*
* Format notes:
*
* - Bits are stored in bytes from the least significant bit to the most
* significant bit. Therefore bits are dropped from the bottom of the bit
* buffer, using shift right, and new bytes are appended to the top of the
* bit buffer, using shift left.
*/
static int bits(state * s, int need) {
int val; /* bit accumulator */
/* load at least need bits into val */
val = s->bitbuf;
while(s->bitcnt < need) {
if(s->left == 0) {
s->left = s->infun(s->inhow, &(s->in));
if (s->left == 0) throw blast_truncated_error(); /* out of input */
}
val |= int(*(s->in)++) << s->bitcnt; /* load eight bits */
s->left--;
s->bitcnt += 8;
}
/* drop need bits and update buffer, always zero to seven bits left */
s->bitbuf = val >> need;
s->bitcnt -= need;
/* return need bits, zeroing the bits above that */
return val & ((1 << need) - 1);
}
/*
* Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of
* each length, which for a canonical code are stepped through in order.
* symbol[] are the symbol values in canonical order, where the number of
* entries is the sum of the counts in count[]. The decoding process can be
* seen in the function decode() below.
*/
struct huffman {
short * count; /* number of symbols of each length */
short * symbol; /* canonically ordered symbols */
};
/*
* Decode a code from the stream s using huffman table h. Return the symbol or
* a negative value if there is an error. If all of the lengths are zero, i.e.
* an empty code, or if the code is incomplete and an invalid code is received,
* then -9 is returned after reading MAXBITS bits.
*
* Format notes:
*
* - The codes as stored in the compressed data are bit-reversed relative to
* a simple integer ordering of codes of the same lengths. Hence below the
* bits are pulled from the compressed data one at a time and used to
* build the code value reversed from what is in the stream in order to
* permit simple integer comparisons for decoding.
*
* - The first code for the shortest length is all ones. Subsequent codes of
* the same length are simply integer decrements of the previous code. When
* moving up a length, a one bit is appended to the code. For a complete
* code, the last code of the longest length will be all zeros. To support
* this ordering, the bits pulled during decoding are inverted to apply the
* more "natural" ordering starting with all zeros and incrementing.
*/
static int decode(state * s, huffman * h) {
int len; /* current number of bits in code */
int code; /* len bits being decoded */
int first; /* first code of length len */
int count; /* number of codes of length len */
int index; /* index of first code of length len in symbol table */
int bitbuf; /* bits from stream */
int left; /* bits left in next or left to process */
short * next; /* next number of codes */
bitbuf = s->bitbuf;
left = s->bitcnt;
code = first = index = 0;
len = 1;
next = h->count + 1;
while(true) {
while(left--) {
code |= (bitbuf & 1) ^ 1; /* invert code */
bitbuf >>= 1;
count = *next++;
if(code < first + count) { /* if length len, return symbol */
s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)];
}
index += count; /* else update for next length */
first += count;
first <<= 1;
code <<= 1;
len++;
}
left = (MAXBITS + 1) - len;
if(left == 0) break;
if(s->left == 0) {
s->left = s->infun(s->inhow, &(s->in));
if (s->left == 0) throw blast_truncated_error(); /* out of input */
}
bitbuf = *(s->in)++;
s->left--;
if (left > 8) left = 8;
}
return -9; /* ran out of codes */
}
/*
* Given a list of repeated code lengths rep[0..n-1], where each byte is a
* count (high four bits + 1) and a code length (low four bits), generate the
* list of code lengths. This compaction reduces the size of the object code.
* Then given the list of code lengths length[0..n-1] representing a canonical
* Huffman code for n symbols, construct the tables required to decode those
* codes. Those tables are the number of codes of each length, and the symbols
* sorted by length, retaining their original order within each length. The
* return value is zero for a complete code set, negative for an over-
* subscribed code set, and positive for an incomplete code set. The tables
* can be used if the return value is zero or positive, but they cannot be used
* if the return value is negative. If the return value is zero, it is not
* possible for decode() using that table to return an error--any stream of
* enough bits will resolve to a symbol. If the return value is positive, then
* it is possible for decode() using that table to return an error for received
* codes past the end of the incomplete lengths.
*/
static int construct(huffman * h, const unsigned char * rep, int n) {
int symbol; /* current symbol when stepping through length[] */
int len; /* current length when stepping through h->count[] */
int left; /* number of possible codes left of current length */
short offs[MAXBITS + 1]; /* offsets in symbol table for each length */
short length[256]; /* code lengths */
/* convert compact repeat counts into symbol bit length list */
symbol = 0;
do {
len = *rep++;
left = (len >> 4) + 1;
len &= 15;
do {
length[symbol++] = len;
} while(--left);
} while(--n);
n = symbol;
/* count number of codes of each length */
for(len = 0; len <= MAXBITS; len++) {
h->count[len] = 0;
}
for(symbol = 0; symbol < n; symbol++) {
(h->count[length[symbol]])++; /* assumes lengths are within bounds */
}
if(h->count[0] == n) { /* no codes! */
return 0; /* complete, but decode() will fail */
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1; /* one possible code of zero length */
for(len = 1; len <= MAXBITS; len++) {
left <<= 1; /* one more bit, double codes left */
left -= h->count[len]; /* deduct count from possible codes */
if(left < 0) return left; /* over-subscribed--return negative */
} /* left > 0 means incomplete */
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for(len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + h->count[len];
}
/*
* put symbols in table sorted by length, by symbol order within each
* length
*/
for(symbol = 0; symbol < n; symbol++) {
if(length[symbol] != 0) {
h->symbol[offs[length[symbol]]++] = symbol;
}
}
/* return zero for complete set, positive for incomplete set */
return left;
}
/*
* Decode PKWare Compression Library stream.
*
* Format notes:
*
* - First byte is 0 if literals are uncoded or 1 if they are coded. Second
* byte is 4, 5, or 6 for the number of extra bits in the distance code.
* This is the base-2 logarithm of the dictionary size minus six.
*
* - Compressed data is a combination of literals and length/distance pairs
* terminated by an end code. Literals are either Huffman coded or
* uncoded bytes. A length/distance pair is a coded length followed by a
* coded distance to represent a string that occurs earlier in the
* uncompressed data that occurs again at the current location.
*
* - A bit preceding a literal or length/distance pair indicates which comes
* next, 0 for literals, 1 for length/distance.
*
* - If literals are uncoded, then the next eight bits are the literal, in the
* normal bit order in th stream, i.e. no bit-reversal is needed. Similarly,
* no bit reversal is needed for either the length extra bits or the distance
* extra bits.
*
* - Literal bytes are simply written to the output. A length/distance pair is
* an instruction to copy previously uncompressed bytes to the output. The
* copy is from distance bytes back in the output stream, copying for length
* bytes.
*
* - Distances pointing before the beginning of the output data are not
* permitted.
*
* - Overlapped copies, where the length is greater than the distance, are
* allowed and common. For example, a distance of one and a length of 518
* simply copies the last byte 518 times. A distance of four and a length of
* twelve copies the last four bytes three times. A simple forward copy
* ignoring whether the length is greater than the distance or not implements
* this correctly.
*/
static BlastResult blastDecompress(state * s) {
int lit; /* true if literals are coded */
int dict; /* log2(dictionary size) - 6 */
int symbol; /* decoded symbol, extra bits for distance */
int len; /* length for copy */
int dist; /* distance for copy */
int copy; /* copy counter */
unsigned char * from, *to; /* copy pointers */
static int virgin = 1; /* build tables once */
static short litcnt[MAXBITS + 1], litsym[256]; /* litcode memory */
static short lencnt[MAXBITS + 1], lensym[16]; /* lencode memory */
static short distcnt[MAXBITS + 1], distsym[64]; /* distcode memory */
static huffman litcode = {litcnt, litsym}; /* length code */
static huffman lencode = {lencnt, lensym}; /* length code */
static huffman distcode = {distcnt, distsym};/* distance code */
/* bit lengths of literal codes */
static const unsigned char litlen[] = {
11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8,
9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5,
7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12,
8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27,
44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45,
44, 173
};
/* bit lengths of length codes 0..15 */
static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23};
/* bit lengths of distance codes 0..63 */
static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248};
static const short base[16] = { /* base for length codes */
3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264
};
static const char extra[16] = { /* extra bits for length codes */
0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8
};
/* set up decoding tables (once--might not be thread-safe) */
if(virgin) {
construct(&litcode, litlen, sizeof(litlen));
construct(&lencode, lenlen, sizeof(lenlen));
construct(&distcode, distlen, sizeof(distlen));
virgin = 0;
}
/* read header */
lit = bits(s, 8);
if (lit > 1) return BLAST_INVALID_LITERAL_FLAG;
dict = bits(s, 8);
if (dict < 4 || dict > 6) return BLAST_INVALID_DIC_SIZE;
/* decode literals and length/distance pairs */
do {
if(bits(s, 1)) {
/* get length */
symbol = decode(s, &lencode);
len = base[symbol] + bits(s, extra[symbol]);
if (len == 519) break; /* end code */
/* get distance */
symbol = len == 2 ? 2 : dict;
dist = decode(s, &distcode) << symbol;
dist += bits(s, symbol);
dist++;
if(s->first && dist > int(s->next)) {
return BLAST_INVALID_OFFSET;
}
/* copy length bytes from distance bytes back */
do {
to = s->out + s->next;
from = to - dist;
copy = MAXWIN;
if(int(s->next) < dist) {
from += copy;
copy = dist;
}
copy -= s->next;
if (copy > len) copy = len;
len -= copy;
s->next += copy;
do {
*to++ = *from++;
} while(--copy);
if(s->next == MAXWIN) {
if(s->outfun(s->outhow, s->out, s->next)) return BLAST_OUTPUT_ERROR;
s->next = 0;
s->first = 0;
}
} while(len != 0);
} else {
/* get literal and write it */
symbol = lit ? decode(s, &litcode) : bits(s, 8);
s->out[s->next++] = symbol;
if(s->next == MAXWIN) {
if(s->outfun(s->outhow, s->out, s->next)) return BLAST_OUTPUT_ERROR;
s->next = 0;
s->first = 0;
}
}
} while(true);
return BLAST_SUCCESS;
}
BlastResult blast(blast_in infun, void * inhow, blast_out outfun, void * outhow) {
state s;
// initialize input state
s.infun = infun;
s.inhow = inhow;
s.left = 0;
s.bitbuf = 0;
s.bitcnt = 0;
// initialize output state
s.outfun = outfun;
s.outhow = outhow;
s.next = 0;
s.first = 1;
BlastResult err;
try {
err = blastDecompress(&s);
} catch(const blast_truncated_error &) {
err = BLAST_TRUNCATED_INPUT;
}
// write any leftover output and update the error code if needed
if(err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) {
err = BLAST_OUTPUT_ERROR;
}
return err;
}
// Additional functions.
size_t blastInMem(void * param, const unsigned char ** buf) {
BlastMemInBuffer * p = static_cast<BlastMemInBuffer *>(param);
*buf = reinterpret_cast<const unsigned char *>(p->buf);
size_t size = p->size;
p->buf += size;
p->size = 0;
return size;
}
int blastOutString(void * param, unsigned char * buf, size_t len) {
BlastMemOutString * p = static_cast<BlastMemOutString *>(param);
p->buffer.append(reinterpret_cast<const char *>(buf), len);
return 0;
}
std::string blast(const char * from, size_t fromSize, size_t toSizeHint) {
std::string uncompressed;
uncompressed.reserve(toSizeHint == size_t(-1) ? fromSize : toSizeHint);
BlastMemInBuffer in(from, fromSize);
BlastMemOutString out(uncompressed);
BlastResult error = blast(blastInMem, &in, blastOutString, &out);
if(error) {
LogError << "blast error " << int(error) << " for " << fromSize;
uncompressed.clear();
}
return uncompressed;
}
| Thoronador/ArxLibertatis | src/io/Blast.cpp | C++ | gpl-3.0 | 16,642 |
#!/usr/bin/env python3
#
# Copyright (C) 2018-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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.
#
# ESPResSo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
if not os.environ.get('CI_COMMIT_REF_NAME', '').startswith('PR-'):
print("Not a pull request. Exiting now.")
exit(0)
import subprocess
import gh_post
SIZELIMIT = 10000
TOKEN_ESPRESSO_CI = 'style.patch'
# Delete obsolete posts
gh_post.delete_comments_by_token(TOKEN_ESPRESSO_CI)
MESSAGE = '''Your pull request does not meet our code formatting \
rules. {header}, please do one of the following:
- You can download a patch with my suggested changes \
[here]({url}/artifacts/raw/style.patch), inspect it and make \
changes manually.
- You can directly apply it to your repository by running \
`curl {url}/artifacts/raw/style.patch | git apply -`.
- You can run `maintainer/CI/fix_style.sh` to automatically fix your coding \
style. This is the same command that I have executed to generate the patch \
above, but it requires certain tools to be installed on your computer.
You can run `gitlab-runner exec docker style` afterwards to check if your \
changes worked out properly.
Please note that there are often multiple ways to correctly format code. \
As I am just a robot, I sometimes fail to identify the most aesthetically \
pleasing way. So please look over my suggested changes and adapt them \
where the style does not make sense.\
'''
# If the working directory is not clean, post a new comment
if subprocess.call(["git", "diff-index", "--quiet", "HEAD", "--"]) != 0:
patch = subprocess.check_output(['git', '--no-pager', 'diff'])
if len(patch) <= SIZELIMIT:
comment = 'Specifically, I suggest you make the following changes:'
comment += '\n```diff\n'
comment += patch.decode('utf-8').replace('`', r'\`').strip()
comment += '\n```\n'
comment += 'To apply these changes'
else:
comment = 'To fix this'
comment = MESSAGE.format(header=comment, url=gh_post.CI_JOB_URL)
if patch:
assert TOKEN_ESPRESSO_CI in comment
gh_post.post_message(comment)
| espressomd/espresso | maintainer/gh_post_style_patch.py | Python | gpl-3.0 | 2,704 |
/*
Drawpile - a collaborative drawing program.
Copyright (C) 2014-2019 Calle Laakkonen
Drawpile 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.
Drawpile 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 Drawpile. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "stats.h"
#include "../libshared/record/reader.h"
#include "../libshared/record/writer.h"
#include "../libclient/canvas/aclfilter.h"
#include <QCoreApplication>
#include <QStringList>
#include <QScopedPointer>
#include <QRegularExpression>
#include <QCommandLineParser>
#include <QTextStream>
#include <QFile>
using namespace recording;
void printVersion()
{
printf("dprectool " DRAWPILE_VERSION "\n");
printf("Protocol version: %s\n", qPrintable(protocol::ProtocolVersion::current().asString()));
printf("Qt version: %s (compiled against %s)\n", qVersion(), QT_VERSION_STR);
}
bool convertRecording(const QString &inputfilename, const QString &outputfilename, const QString &outputFormat, bool doAclFiltering)
{
// Open input file
Reader reader(inputfilename);
Compatibility compat = reader.open();
switch(compat) {
case INCOMPATIBLE:
fprintf(
stderr,
"This recording is incompatible (format version %s). It was made with Drawpile version %s.\n",
qPrintable(reader.formatVersion().asString()),
qPrintable(reader.writerVersion())
);
return false;
case NOT_DPREC:
fprintf(stderr, "Input file is not a Drawpile recording!\n");
return false;
case CANNOT_READ:
fprintf(stderr, "Unable to read input file: %s\n", qPrintable(reader.errorString()));
return false;
case COMPATIBLE:
case MINOR_INCOMPATIBILITY:
case UNKNOWN_COMPATIBILITY:
// OK to proceed
break;
}
// Open output file (stdout if no filename given)
QScopedPointer<Writer> writer;
if(outputfilename.isEmpty()) {
// No output filename given? Write to stdout
QFile *out = new QFile();
out->open(stdout, QFile::WriteOnly);
writer.reset(new Writer(out));
out->setParent(writer.data());
writer->setEncoding(Writer::Encoding::Text);
} else {
writer.reset(new Writer(outputfilename));
}
// Output format override
if(outputFormat == "text")
writer->setEncoding(Writer::Encoding::Text);
else if(outputFormat == "binary")
writer->setEncoding(Writer::Encoding::Binary);
else if(!outputFormat.isEmpty()) {
fprintf(stderr, "Invalid output format: %s\n", qPrintable(outputFormat));
return false;
}
// Open output file
if(!writer->open()) {
fprintf(stderr, "Couldn't open %s: %s\n",
qPrintable(outputfilename),
qPrintable(writer->errorString())
);
return false;
}
if(!writer->writeHeader(reader.metadata())) {
fprintf(stderr, "Error while writing header: %s\n",
qPrintable(writer->errorString())
);
return false;
}
// Prepare filters
canvas::AclFilter aclFilter;
aclFilter.reset(1, false);
// Convert and/or filter recording
bool notEof = true;
do {
MessageRecord mr = reader.readNext();
switch(mr.status) {
case MessageRecord::OK: {
if(doAclFiltering && !aclFilter.filterMessage(*mr.message)) {
writer->writeMessage(*mr.message->asFiltered());
} else {
if(!writer->writeMessage(*mr.message)) {
fprintf(stderr, "Error while writing message: %s\n",
qPrintable(writer->errorString())
);
return false;
}
}
break;
}
case MessageRecord::INVALID:
writer->writeComment(QStringLiteral("WARNING: Unrecognized message type %1 of length %2 at offset 0x%3")
.arg(int(mr.invalid_type))
.arg(mr.invalid_len)
.arg(reader.currentPosition())
);
break;
case MessageRecord::END_OF_RECORDING:
notEof = false;
break;
}
} while(notEof);
return true;
}
/**
* Print the version number of this recording. The output can be parsed easily in a shell script.
* Output format: <compatibility flag> <protocol version> <client version string>
* Example: C dp:4.20.1 2.0.5
* Compatability flag is one of:
* - C: fully compatible with this dprectool/drawpile-cmd version
* - M: minor incompatibility (might render differently)
* - U: unknown compatibility (made with a newer version: some features may be missing)
* - I: known to be incompatible
*/
bool printRecordingVersion(const QString &inputFilename)
{
Reader reader(inputFilename);
const Compatibility compat = reader.open();
char compatflag = '?';
switch(compat) {
case COMPATIBLE: compatflag = 'C'; break;
case MINOR_INCOMPATIBILITY: compatflag = 'M'; break;
case UNKNOWN_COMPATIBILITY: compatflag = 'U'; break;
case INCOMPATIBLE: compatflag = 'I'; break;
case NOT_DPREC:
fprintf(stderr, "Not a drawpile recording!\n");
return false;
case CANNOT_READ:
fprintf(stderr, "Cannot read file: %s", qPrintable(reader.errorString()));
return false;
}
printf("%c %s %s\n",
compatflag,
qPrintable(reader.formatVersion().asString()),
reader.writerVersion().isEmpty() ? "(no writer version)" : qPrintable(reader.writerVersion())
);
return true;
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName("drawpile");
QCoreApplication::setOrganizationDomain("drawpile.net");
QCoreApplication::setApplicationName("dprectool");
QCoreApplication::setApplicationVersion(DRAWPILE_VERSION);
// Set up command line arguments
QCommandLineParser parser;
parser.setApplicationDescription("Convert Drawpile recordings between text and binary formats");
parser.addHelpOption();
// --version, -v
QCommandLineOption versionOption(QStringList() << "v" << "version", "Displays version information.");
parser.addOption(versionOption);
// --out, -o
QCommandLineOption outOption(QStringList() << "o" << "out", "Output file", "output");
parser.addOption(outOption);
// --format, -f
QCommandLineOption formatOption(QStringList() << "f" << "format", "Output format (binary/text/version)", "format");
parser.addOption(formatOption);
// --acl, -A
QCommandLineOption aclOption(QStringList() << "A" << "acl", "Perform ACL filtering");
parser.addOption(aclOption);
// --msg-freq
QCommandLineOption msgFreqOption(QStringList() << "msg-freq", "Print message frequency table");
parser.addOption(msgFreqOption);
// input file name
parser.addPositionalArgument("input", "recording file", "<input.dprec>");
// Parse
parser.process(app);
if(parser.isSet(versionOption)) {
printVersion();
return 0;
}
const QStringList inputfiles = parser.positionalArguments();
if(inputfiles.isEmpty()) {
parser.showHelp(1);
return 1;
}
const QString format = parser.value(formatOption);
if(format == "version") {
return !printRecordingVersion(inputfiles.at(0));
}
if(parser.isSet(msgFreqOption)) {
return printMessageFrequency(inputfiles.at(0)) ? 0 : 1;
}
if(!convertRecording(
inputfiles.at(0),
parser.value(outOption),
parser.value(formatOption),
parser.isSet(aclOption)
))
return 1;
return 0;
}
| drawpile/Drawpile | src/tools/dprectool.cpp | C++ | gpl-3.0 | 7,369 |
var classgr__interleave =
[
[ "~gr_interleave", "classgr__interleave.html#ae342ba63322b78359ee71de113e41fc1", null ],
[ "check_topology", "classgr__interleave.html#ade74f196c0fc8a91ca4f853a2d1202e1", null ],
[ "work", "classgr__interleave.html#a44664518c86559da58b3feccb9e45d7f", null ],
[ "gr_make_interleave", "classgr__interleave.html#acf7153a343a7bfbf2687bcc4c98d410e", null ]
]; | aviralchandra/Sandhi | build/gr36/docs/doxygen/html/classgr__interleave.js | JavaScript | gpl-3.0 | 399 |
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import { observer } from 'mobx-react';
import React, { Component, PropTypes } from 'react';
import { FormattedMessage } from 'react-intl';
import shapeshiftLogo from '~/../assets/images/shapeshift-logo.png';
import { Button, IdentityIcon, Portal } from '~/ui';
import { CancelIcon, DoneIcon } from '~/ui/Icons';
import AwaitingDepositStep from './AwaitingDepositStep';
import AwaitingExchangeStep from './AwaitingExchangeStep';
import CompletedStep from './CompletedStep';
import ErrorStep from './ErrorStep';
import OptionsStep from './OptionsStep';
import Store, { STAGE_COMPLETED, STAGE_OPTIONS, STAGE_WAIT_DEPOSIT, STAGE_WAIT_EXCHANGE } from './store';
import styles from './shapeshift.css';
const STAGE_TITLES = [
<FormattedMessage
id='shapeshift.title.details'
defaultMessage='details'
/>,
<FormattedMessage
id='shapeshift.title.deposit'
defaultMessage='awaiting deposit'
/>,
<FormattedMessage
id='shapeshift.title.exchange'
defaultMessage='awaiting exchange'
/>,
<FormattedMessage
id='shapeshift.title.completed'
defaultMessage='completed'
/>
];
const ERROR_TITLE = (
<FormattedMessage
id='shapeshift.title.error'
defaultMessage='exchange failed'
/>
);
@observer
export default class Shapeshift extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
}
static propTypes = {
address: PropTypes.string.isRequired,
onClose: PropTypes.func
}
store = new Store(this.props.address);
componentDidMount () {
this.store.retrieveCoins();
}
componentWillUnmount () {
this.store.unsubscribe();
}
render () {
const { error, stage } = this.store;
return (
<Portal
activeStep={ stage }
busySteps={ [
STAGE_WAIT_DEPOSIT,
STAGE_WAIT_EXCHANGE
] }
buttons={ this.renderDialogActions() }
onClose={ this.onClose }
open
steps={
error
? null
: STAGE_TITLES
}
title={
error
? ERROR_TITLE
: null
}
>
{ this.renderPage() }
</Portal>
);
}
renderDialogActions () {
const { address } = this.props;
const { coins, error, hasAcceptedTerms, stage } = this.store;
const logo = (
<a
className={ styles.shapeshift }
href='http://shapeshift.io'
key='logo'
target='_blank'
>
<img src={ shapeshiftLogo } />
</a>
);
const cancelBtn = (
<Button
icon={ <CancelIcon /> }
key='cancel'
label={
<FormattedMessage
id='shapeshift.button.cancel'
defaultMessage='Cancel'
/>
}
onClick={ this.onClose }
/>
);
if (error) {
return [
logo,
cancelBtn
];
}
switch (stage) {
case STAGE_OPTIONS:
return [
logo,
cancelBtn,
<Button
disabled={ !coins.length || !hasAcceptedTerms }
icon={
<IdentityIcon
address={ address }
button
/>
}
key='shift'
label={
<FormattedMessage
id='shapeshift.button.shift'
defaultMessage='Shift Funds'
/>
}
onClick={ this.onShift }
/>
];
case STAGE_WAIT_DEPOSIT:
case STAGE_WAIT_EXCHANGE:
return [
logo,
cancelBtn
];
case STAGE_COMPLETED:
return [
logo,
<Button
icon={ <DoneIcon /> }
key='done'
label={
<FormattedMessage
id='shapeshift.button.done'
defaultMessage='Close'
/>
}
onClick={ this.onClose }
/>
];
}
}
renderPage () {
const { error, stage } = this.store;
if (error) {
return (
<ErrorStep store={ this.store } />
);
}
switch (stage) {
case STAGE_OPTIONS:
return (
<OptionsStep store={ this.store } />
);
case STAGE_WAIT_DEPOSIT:
return (
<AwaitingDepositStep store={ this.store } />
);
case STAGE_WAIT_EXCHANGE:
return (
<AwaitingExchangeStep store={ this.store } />
);
case STAGE_COMPLETED:
return (
<CompletedStep store={ this.store } />
);
}
}
onClose = () => {
this.store.setStage(STAGE_OPTIONS);
this.props.onClose && this.props.onClose();
}
onShift = () => {
return this.store.shift();
}
}
| nipunn1313/parity | js/src/modals/Shapeshift/shapeshift.js | JavaScript | gpl-3.0 | 5,450 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program 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.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\network\protocol;
#include <rules/DataPacket.h>
class RemoveBlockPacket extends DataPacket{
const NETWORK_ID = Info::REMOVE_BLOCK_PACKET;
public $x;
public $y;
public $z;
public function getName(){
return "RemoveBlockPacket";
}
public function decode(){
$this->getBlockCoords($this->x, $this->y, $this->z);
}
public function encode(){
}
}
| StarrySky-PE/StarrySky | src/pocketmine/network/protocol/RemoveBlockPacket.php | PHP | gpl-3.0 | 1,097 |
<?php
/**
* OpenSKOS
*
* LICENSE
*
* This source file is subject to the GPLv3 license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category OpenSKOS
* @package OpenSKOS
* @copyright Copyright (c) 2011 Pictura Database Publishing. (http://www.pictura-dp.nl)
* @author Mark Lindeman
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
class Editor_IndexController extends OpenSKOS_Controller_Editor
{
public function indexAction()
{
$schemesCache = $this->getDI()->get('Editor_Models_ConceptSchemesCache');
$user = OpenSKOS_Db_Table_Users::requireFromIdentity();
$tenant = $this->readTenant()->getOpenSkos2Tenant();
$this->view->assign('conceptSchemes', $schemesCache->fetchUrisMap());
$this->view->assign('disableSearchProfileChanging', $user->disableSearchProfileChanging);
$this->view->assign('exportForm', Editor_Forms_Export::getInstance());
$this->view->assign('deleteForm', Editor_Forms_Delete::getInstance());
$this->view->assign('changeStatusForm', Editor_Forms_ChangeStatus::getInstance());
$this->view->assign('oActiveUser', $user);
$this->view->assign('oActiveTenant', $tenant);
$this->view->assign('searchForm', Editor_Forms_Search::getInstance());
}
}
| CatchPlus/OpenSKOS | application/editor/controllers/IndexController.php | PHP | gpl-3.0 | 1,621 |
<?php
/**
* @file
* This is the template file for the metadata description for an object.
*
* Available variables:
* - $islandora_object: The Islandora object rendered in this template file
* - $found: Boolean indicating if a Solr doc was found for the current object.
*
* @see template_preprocess_islandora_solr_metadata_description()
* @see template_process_islandora_solr_metadata_description()
*/
?>
<?php if ($found && !empty($description)): ?>
<div class="islandora-solr-metadata-sidebar">
<?php if ($combine): ?>
<h2><?php if (count($description) > 1):
print (t('Description'));
else:
$desc_array = reset($description);
print ($desc_array['display_label']); ?>
<?php endif; ?></h2>
<?php foreach($description as $value): ?>
<p property="description"><?php print check_markup(implode("\n", $value['value']), 'filtered_html'); ?></p>
<?php endforeach; ?>
<?php else: ?>
<?php foreach ($description as $value): ?>
<h2><?php print $value['display_label']; ?></h2>
<p><?php print check_markup(implode("\n", $value['value']), 'filtered_html'); ?></p>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endif; ?>
| jordandukart/islandora_solr_metadata | theme/islandora-solr-metadata-description.tpl.php | PHP | gpl-3.0 | 1,232 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
Copyright (C) 2015 Robert Beckebans
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.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "dmap.h"
idList<interAreaPortal_t> interAreaPortals;
int c_active_portals;
int c_peak_portals;
/*
===========
AllocPortal
===========
*/
uPortal_t* AllocPortal()
{
uPortal_t* p;
c_active_portals++;
if( c_active_portals > c_peak_portals )
{
c_peak_portals = c_active_portals;
}
p = ( uPortal_t* )Mem_Alloc( sizeof( uPortal_t ), TAG_TOOLS );
memset( p, 0, sizeof( uPortal_t ) );
return p;
}
void FreePortal( uPortal_t* p )
{
if( p->winding )
{
delete p->winding;
}
c_active_portals--;
Mem_Free( p );
}
//==============================================================
/*
=============
Portal_Passable
Returns true if the portal has non-opaque leafs on both sides
=============
*/
static bool Portal_Passable( uPortal_t* p )
{
if( !p->onnode )
{
return false; // to global outsideleaf
}
if( p->nodes[0]->planenum != PLANENUM_LEAF
|| p->nodes[1]->planenum != PLANENUM_LEAF )
{
common->Error( "Portal_EntityFlood: not a leaf" );
}
if( !p->nodes[0]->opaque && !p->nodes[1]->opaque )
{
return true;
}
return false;
}
//=============================================================================
int c_tinyportals;
/*
=============
AddPortalToNodes
=============
*/
void AddPortalToNodes( uPortal_t* p, node_t* front, node_t* back )
{
if( p->nodes[0] || p->nodes[1] )
{
common->Error( "AddPortalToNode: allready included" );
}
p->nodes[0] = front;
p->next[0] = front->portals;
front->portals = p;
p->nodes[1] = back;
p->next[1] = back->portals;
back->portals = p;
}
/*
=============
RemovePortalFromNode
=============
*/
void RemovePortalFromNode( uPortal_t* portal, node_t* l )
{
uPortal_t** pp, *t;
// remove reference to the current portal
pp = &l->portals;
while( 1 )
{
t = *pp;
if( !t )
{
common->Error( "RemovePortalFromNode: portal not in leaf" );
}
if( t == portal )
{
break;
}
if( t->nodes[0] == l )
{
pp = &t->next[0];
}
else if( t->nodes[1] == l )
{
pp = &t->next[1];
}
else
{
common->Error( "RemovePortalFromNode: portal not bounding leaf" );
}
}
if( portal->nodes[0] == l )
{
*pp = portal->next[0];
portal->nodes[0] = NULL;
}
else if( portal->nodes[1] == l )
{
*pp = portal->next[1];
portal->nodes[1] = NULL;
}
else
{
common->Error( "RemovePortalFromNode: mislinked" );
}
}
//============================================================================
void PrintPortal( uPortal_t* p )
{
int i;
idWinding* w;
w = p->winding;
for( i = 0; i < w->GetNumPoints(); i++ )
{
common->Printf( "(%5.0f,%5.0f,%5.0f)\n", ( *w )[i][0], ( *w )[i][1], ( *w )[i][2] );
}
}
/*
================
MakeHeadnodePortals
The created portals will face the global outside_node
================
*/
#define SIDESPACE 8
static void MakeHeadnodePortals( tree_t* tree )
{
idBounds bounds;
int i, j, n;
uPortal_t* p, *portals[6];
idPlane bplanes[6], *pl;
node_t* node;
node = tree->headnode;
tree->outside_node.planenum = PLANENUM_LEAF;
tree->outside_node.brushlist = NULL;
tree->outside_node.portals = NULL;
tree->outside_node.opaque = false;
// if no nodes, don't go any farther
if( node->planenum == PLANENUM_LEAF )
{
return;
}
// pad with some space so there will never be null volume leafs
for( i = 0 ; i < 3 ; i++ )
{
bounds[0][i] = tree->bounds[0][i] - SIDESPACE;
bounds[1][i] = tree->bounds[1][i] + SIDESPACE;
if( bounds[0][i] >= bounds[1][i] )
{
common->Error( "Backwards tree volume" );
}
}
for( i = 0 ; i < 3 ; i++ )
{
for( j = 0 ; j < 2 ; j++ )
{
n = j * 3 + i;
p = AllocPortal();
portals[n] = p;
pl = &bplanes[n];
memset( pl, 0, sizeof( *pl ) );
if( j )
{
( *pl )[i] = -1;
( *pl )[3] = bounds[j][i];
}
else
{
( *pl )[i] = 1;
( *pl )[3] = -bounds[j][i];
}
p->plane = *pl;
p->winding = new idWinding( *pl );
AddPortalToNodes( p, node, &tree->outside_node );
}
}
// clip the basewindings by all the other planes
for( i = 0 ; i < 6 ; i++ )
{
for( j = 0 ; j < 6 ; j++ )
{
if( j == i )
{
continue;
}
portals[i]->winding = portals[i]->winding->Clip( bplanes[j], ON_EPSILON );
}
}
}
//===================================================
/*
================
BaseWindingForNode
================
*/
#define BASE_WINDING_EPSILON 0.001f
#define SPLIT_WINDING_EPSILON 0.001f
idWinding* BaseWindingForNode( node_t* node )
{
idWinding* w;
node_t* n;
w = new idWinding( dmapGlobals.mapPlanes[node->planenum] );
// clip by all the parents
for( n = node->parent ; n && w ; )
{
idPlane& plane = dmapGlobals.mapPlanes[n->planenum];
if( n->children[0] == node )
{
// take front
w = w->Clip( plane, BASE_WINDING_EPSILON );
}
else
{
// take back
idPlane back = -plane;
w = w->Clip( back, BASE_WINDING_EPSILON );
}
node = n;
n = n->parent;
}
return w;
}
//============================================================
/*
==================
MakeNodePortal
create the new portal by taking the full plane winding for the cutting plane
and clipping it by all of parents of this node
==================
*/
static void MakeNodePortal( node_t* node )
{
uPortal_t* new_portal, *p;
idWinding* w;
idVec3 normal;
int side;
w = BaseWindingForNode( node );
// clip the portal by all the other portals in the node
for( p = node->portals ; p && w; p = p->next[side] )
{
idPlane plane;
if( p->nodes[0] == node )
{
side = 0;
plane = p->plane;
}
else if( p->nodes[1] == node )
{
side = 1;
plane = -p->plane;
}
else
{
common->Error( "CutNodePortals_r: mislinked portal" );
side = 0; // quiet a compiler warning
}
w = w->Clip( plane, CLIP_EPSILON );
}
if( !w )
{
return;
}
if( w->IsTiny() )
{
c_tinyportals++;
delete w;
return;
}
new_portal = AllocPortal();
new_portal->plane = dmapGlobals.mapPlanes[node->planenum];
new_portal->onnode = node;
new_portal->winding = w;
AddPortalToNodes( new_portal, node->children[0], node->children[1] );
}
/*
==============
SplitNodePortals
Move or split the portals that bound node so that the node's
children have portals instead of node.
==============
*/
static void SplitNodePortals( node_t* node )
{
uPortal_t* p, *next_portal, *new_portal;
node_t* f, *b, *other_node;
int side;
idPlane* plane;
idWinding* frontwinding, *backwinding;
plane = &dmapGlobals.mapPlanes[node->planenum];
f = node->children[0];
b = node->children[1];
for( p = node->portals ; p ; p = next_portal )
{
if( p->nodes[0] == node )
{
side = 0;
}
else if( p->nodes[1] == node )
{
side = 1;
}
else
{
common->Error( "SplitNodePortals: mislinked portal" );
side = 0; // quiet a compiler warning
}
next_portal = p->next[side];
other_node = p->nodes[!side];
RemovePortalFromNode( p, p->nodes[0] );
RemovePortalFromNode( p, p->nodes[1] );
//
// cut the portal into two portals, one on each side of the cut plane
//
p->winding->Split( *plane, SPLIT_WINDING_EPSILON, &frontwinding, &backwinding );
if( frontwinding && frontwinding->IsTiny() )
{
delete frontwinding;
frontwinding = NULL;
c_tinyportals++;
}
if( backwinding && backwinding->IsTiny() )
{
delete backwinding;
backwinding = NULL;
c_tinyportals++;
}
if( !frontwinding && !backwinding )
{
// tiny windings on both sides
continue;
}
if( !frontwinding )
{
delete backwinding;
if( side == 0 )
{
AddPortalToNodes( p, b, other_node );
}
else
{
AddPortalToNodes( p, other_node, b );
}
continue;
}
if( !backwinding )
{
delete frontwinding;
if( side == 0 )
{
AddPortalToNodes( p, f, other_node );
}
else
{
AddPortalToNodes( p, other_node, f );
}
continue;
}
// the winding is split
new_portal = AllocPortal();
*new_portal = *p;
new_portal->winding = backwinding;
delete p->winding;
p->winding = frontwinding;
if( side == 0 )
{
AddPortalToNodes( p, f, other_node );
AddPortalToNodes( new_portal, b, other_node );
}
else
{
AddPortalToNodes( p, other_node, f );
AddPortalToNodes( new_portal, other_node, b );
}
}
node->portals = NULL;
}
/*
================
CalcNodeBounds
================
*/
void CalcNodeBounds( node_t* node )
{
uPortal_t* p;
int s;
int i;
// calc mins/maxs for both leafs and nodes
node->bounds.Clear();
for( p = node->portals ; p ; p = p->next[s] )
{
s = ( p->nodes[1] == node );
for( i = 0; i < p->winding->GetNumPoints(); i++ )
{
node->bounds.AddPoint( ( *p->winding )[i].ToVec3() );
}
}
}
/*
==================
MakeTreePortals_r
==================
*/
void MakeTreePortals_r( node_t* node )
{
int i;
CalcNodeBounds( node );
if( node->bounds[0][0] >= node->bounds[1][0] )
{
common->Warning( "node without a volume" );
}
for( i = 0; i < 3; i++ )
{
if( node->bounds[0][i] < MIN_WORLD_COORD || node->bounds[1][i] > MAX_WORLD_COORD )
{
common->Warning( "node with unbounded volume" );
break;
}
}
if( node->planenum == PLANENUM_LEAF )
{
return;
}
MakeNodePortal( node );
SplitNodePortals( node );
MakeTreePortals_r( node->children[0] );
MakeTreePortals_r( node->children[1] );
}
/*
==================
MakeTreePortals
==================
*/
void MakeTreePortals( tree_t* tree )
{
common->Printf( "----- MakeTreePortals -----\n" );
MakeHeadnodePortals( tree );
MakeTreePortals_r( tree->headnode );
}
/*
=========================================================
FLOOD ENTITIES
=========================================================
*/
int c_floodedleafs;
/*
=============
FloodPortals_r
=============
*/
void FloodPortals_r( node_t* node, int dist )
{
uPortal_t* p;
int s;
if( node->occupied )
{
return;
}
if( node->opaque )
{
return;
}
c_floodedleafs++;
node->occupied = dist;
for( p = node->portals ; p ; p = p->next[s] )
{
s = ( p->nodes[1] == node );
FloodPortals_r( p->nodes[!s], dist + 1 );
}
}
/*
=============
PlaceOccupant
=============
*/
bool PlaceOccupant( node_t* headnode, idVec3 origin, uEntity_t* occupant )
{
node_t* node;
float d;
idPlane* plane;
// find the leaf to start in
node = headnode;
while( node->planenum != PLANENUM_LEAF )
{
plane = &dmapGlobals.mapPlanes[node->planenum];
d = plane->Distance( origin );
if( d >= 0.0f )
{
node = node->children[0];
}
else
{
node = node->children[1];
}
}
if( node->opaque )
{
return false;
}
node->occupant = occupant;
FloodPortals_r( node, 1 );
return true;
}
/*
=============
FloodEntities
Marks all nodes that can be reached by entites
=============
*/
bool FloodEntities( tree_t* tree )
{
int i;
idVec3 origin;
const char* cl;
bool inside;
node_t* headnode;
headnode = tree->headnode;
common->Printf( "--- FloodEntities ---\n" );
inside = false;
tree->outside_node.occupied = 0;
c_floodedleafs = 0;
bool errorShown = false;
for( i = 1 ; i < dmapGlobals.num_entities ; i++ )
{
idMapEntity* mapEnt;
mapEnt = dmapGlobals.uEntities[i].mapEntity;
if( !mapEnt->epairs.GetVector( "origin", "", origin ) )
{
continue;
}
// any entity can have "noFlood" set to skip it
if( mapEnt->epairs.GetString( "noFlood", "", &cl ) )
{
continue;
}
mapEnt->epairs.GetString( "classname", "", &cl );
if( !strcmp( cl, "light" ) )
{
const char* v;
// don't place lights that have a light_start field, because they can still
// be valid if their origin is outside the world
mapEnt->epairs.GetString( "light_start", "", &v );
if( v[0] )
{
continue;
}
// don't place fog lights, because they often
// have origins outside the light
mapEnt->epairs.GetString( "texture", "", &v );
if( v[0] )
{
const idMaterial* mat = declManager->FindMaterial( v );
if( mat->IsFogLight() )
{
continue;
}
}
}
if( PlaceOccupant( headnode, origin, &dmapGlobals.uEntities[i] ) )
{
inside = true;
}
if( tree->outside_node.occupied && !errorShown )
{
errorShown = true;
common->Printf( "Leak on entity # %d\n", i );
const char* p;
mapEnt->epairs.GetString( "classname", "", &p );
common->Printf( "Entity classname was: %s\n", p );
mapEnt->epairs.GetString( "name", "", &p );
common->Printf( "Entity name was: %s\n", p );
idVec3 origin;
if( mapEnt->epairs.GetVector( "origin", "", origin ) )
{
common->Printf( "Entity origin is: %f %f %f\n\n\n", origin.x, origin.y, origin.z );
}
}
}
common->Printf( "%5i flooded leafs\n", c_floodedleafs );
if( !inside )
{
common->Printf( "no entities in open -- no filling\n" );
}
else if( tree->outside_node.occupied )
{
common->Printf( "entity reached from outside -- no filling\n" );
}
return ( bool )( inside && !tree->outside_node.occupied );
}
/*
=========================================================
FLOOD AREAS
=========================================================
*/
static int c_areas;
static int c_areaFloods;
/*
=================
FindSideForPortal
=================
*/
static side_t* FindSideForPortal( uPortal_t* p )
{
int i, j, k;
node_t* node;
uBrush_t* b, *orig;
side_t* s, *s2;
// scan both bordering nodes brush lists for a portal brush
// that shares the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( b = node->brushlist ; b ; b = b->next )
{
if( !( b->contents & CONTENTS_AREAPORTAL ) )
{
continue;
}
orig = b->original;
for( j = 0 ; j < orig->numsides ; j++ )
{
s = orig->sides + j;
if( !s->visibleHull )
{
continue;
}
if( !( s->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( s->planenum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
// remove the visible hull from any other portal sides of this portal brush
for( k = 0; k < orig->numsides; k++ )
{
if( k == j )
{
continue;
}
s2 = orig->sides + k;
if( s2->visibleHull == NULL )
{
continue;
}
if( !( s2->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
common->Warning( "brush has multiple area portal sides at %s", s2->visibleHull->GetCenter().ToString() );
delete s2->visibleHull;
s2->visibleHull = NULL;
}
return s;
}
}
}
return NULL;
}
// RB: extra function to avoid many allocations
static bool CheckTrianglesForPortal( uPortal_t* p )
{
int i;
node_t* node;
mapTri_t* tri;
// scan both bordering nodes triangle lists for portal triangles that share the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( tri = node->areaPortalTris; tri; tri = tri->next )
{
if( !( tri->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( tri->planeNum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
return true;
}
}
return false;
}
static bool FindTrianglesForPortal( uPortal_t* p, idList<mapTri_t*>& tris )
{
int i;
node_t* node;
mapTri_t* tri;
tris.Clear();
// scan both bordering nodes triangle lists for portal triangles that share the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( tri = node->areaPortalTris; tri; tri = tri->next )
{
if( !( tri->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( tri->planeNum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
tris.Append( tri );
}
}
return tris.Num() > 0;
}
// RB end
/*
=============
FloodAreas_r
=============
*/
void FloodAreas_r( node_t* node )
{
uPortal_t* p;
int s;
if( node->area != -1 )
{
return; // allready got it
}
if( node->opaque )
{
return;
}
c_areaFloods++;
node->area = c_areas;
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( !Portal_Passable( p ) )
{
continue;
}
// can't flood through an area portal
if( FindSideForPortal( p ) )
{
continue;
}
// RB: check area portal triangles as well
if( CheckTrianglesForPortal( p ) )
{
continue;
}
FloodAreas_r( other );
}
}
/*
=============
FindAreas_r
Just decend the tree, and for each node that hasn't had an
area set, flood fill out from there
=============
*/
void FindAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
FindAreas_r( node->children[0] );
FindAreas_r( node->children[1] );
return;
}
if( node->opaque )
{
return;
}
if( node->area != -1 )
{
return; // allready got it
}
c_areaFloods = 0;
FloodAreas_r( node );
common->Printf( "area %i has %i leafs\n", c_areas, c_areaFloods );
c_areas++;
}
/*
============
CheckAreas_r
============
*/
void CheckAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
CheckAreas_r( node->children[0] );
CheckAreas_r( node->children[1] );
return;
}
if( !node->opaque && node->area < 0 )
{
common->Error( "CheckAreas_r: area = %i", node->area );
}
}
/*
============
ClearAreas_r
Set all the areas to -1 before filling
============
*/
void ClearAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
ClearAreas_r( node->children[0] );
ClearAreas_r( node->children[1] );
return;
}
node->area = -1;
}
//=============================================================
/*
=================
FindInterAreaPortals_r
=================
*/
static void FindInterAreaPortals_r( node_t* node )
{
uPortal_t* p;
int s;
int i;
idWinding* w;
interAreaPortal_t* iap;
side_t* side;
if( node->planenum != PLANENUM_LEAF )
{
FindInterAreaPortals_r( node->children[0] );
FindInterAreaPortals_r( node->children[1] );
return;
}
if( node->opaque )
{
return;
}
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( other->opaque )
{
continue;
}
// only report areas going from lower number to higher number
// so we don't report the portal twice
if( other->area <= node->area )
{
continue;
}
side = FindSideForPortal( p );
// w = p->winding;
if( !side )
{
common->Warning( "FindSideForPortal failed at %s", p->winding->GetCenter().ToString() );
continue;
}
w = side->visibleHull;
if( !w )
{
continue;
}
// see if we have created this portal before
for( i = 0; i < interAreaPortals.Num(); i++ )
{
iap = &interAreaPortals[i];
if( side == iap->side &&
( ( p->nodes[0]->area == iap->area0 && p->nodes[1]->area == iap->area1 )
|| ( p->nodes[1]->area == iap->area0 && p->nodes[0]->area == iap->area1 ) ) )
{
break;
}
}
if( i != interAreaPortals.Num() )
{
continue; // already emited
}
iap = &interAreaPortals.Alloc();
if( side->planenum == p->onnode->planenum )
{
iap->area0 = p->nodes[0]->area;
iap->area1 = p->nodes[1]->area;
}
else
{
iap->area0 = p->nodes[1]->area;
iap->area1 = p->nodes[0]->area;
}
iap->side = side;
}
// RB: check area portal triangles
idList<mapTri_t*> apTriangles;
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( other->opaque )
{
continue;
}
// only report areas going from lower number to higher number
// so we don't report the portal twice
if( other->area <= node->area )
{
continue;
}
FindTrianglesForPortal( p, apTriangles );
if( apTriangles.Num() < 2 )
{
//common->Warning( "FindTrianglesForPortal failed at %s", p->winding->GetCenter().ToString() );
continue;
}
// see if we have created this portal before
for( i = 0; i < interAreaPortals.Num(); i++ )
{
iap = &interAreaPortals[i];
if( apTriangles[0]->polygonId == iap->polygonId &&
( ( p->nodes[0]->area == iap->area0 && p->nodes[1]->area == iap->area1 )
|| ( p->nodes[1]->area == iap->area0 && p->nodes[0]->area == iap->area1 ) ) )
{
break;
}
}
if( i != interAreaPortals.Num() )
{
continue; // already emited
}
iap = &interAreaPortals.Alloc();
if( apTriangles[0]->planeNum == p->onnode->planenum )
{
iap->area0 = p->nodes[0]->area;
iap->area1 = p->nodes[1]->area;
}
else
{
iap->area0 = p->nodes[1]->area;
iap->area1 = p->nodes[0]->area;
}
iap->polygonId = apTriangles[0]->polygonId;
// merge triangles to a new winding
for( int j = 0; j < apTriangles.Num(); j++ )
{
mapTri_t* tri = apTriangles[j];
idVec3 planeNormal = dmapGlobals.mapPlanes[ tri->planeNum].Normal();
for( int k = 0; k < 3; k++ )
{
iap->w.AddToConvexHull( tri->v[k].xyz, planeNormal );
}
}
}
// RB end
}
/*
=============
FloodAreas
Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL
Sets e->areas.numAreas
=============
*/
void FloodAreas( uEntity_t* e )
{
common->Printf( "--- FloodAreas ---\n" );
// set all areas to -1
ClearAreas_r( e->tree->headnode );
// flood fill from non-opaque areas
c_areas = 0;
FindAreas_r( e->tree->headnode );
common->Printf( "%5i areas\n", c_areas );
e->numAreas = c_areas;
// make sure we got all of them
CheckAreas_r( e->tree->headnode );
// identify all portals between areas if this is the world
if( e == &dmapGlobals.uEntities[0] )
{
interAreaPortals.Clear();
FindInterAreaPortals_r( e->tree->headnode );
}
}
/*
======================================================
FILL OUTSIDE
======================================================
*/
static int c_outside;
static int c_inside;
static int c_solid;
void FillOutside_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
FillOutside_r( node->children[0] );
FillOutside_r( node->children[1] );
return;
}
// anything not reachable by an entity
// can be filled away
if( !node->occupied )
{
if( !node->opaque )
{
c_outside++;
node->opaque = true;
}
else
{
c_solid++;
}
}
else
{
c_inside++;
}
}
/*
=============
FillOutside
Fill (set node->opaque = true) all nodes that can't be reached by entities
=============
*/
void FillOutside( uEntity_t* e )
{
c_outside = 0;
c_inside = 0;
c_solid = 0;
common->Printf( "--- FillOutside ---\n" );
FillOutside_r( e->tree->headnode );
common->Printf( "%5i solid leafs\n", c_solid );
common->Printf( "%5i leafs filled\n", c_outside );
common->Printf( "%5i inside leafs\n", c_inside );
}
| raynorpat/RBDOOM-3-BFG | neo/tools/compilers/dmap/portals.cpp | C++ | gpl-3.0 | 23,955 |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'committer',
'version': '1.0'}
DOCUMENTATION = """
---
module: ec2_asg
short_description: Create or delete AWS Autoscaling Groups
description:
- Can create or delete AWS Autoscaling Groups
- Works with the ec2_lc module to manage Launch Configurations
version_added: "1.6"
author: "Gareth Rushgrove (@garethr)"
options:
state:
description:
- register or deregister the instance
required: false
choices: ['present', 'absent']
default: present
name:
description:
- Unique name for group to be created or deleted
required: true
load_balancers:
description:
- List of ELB names to use for the group
required: false
availability_zones:
description:
- List of availability zone names in which to create the group. Defaults to all the availability zones in the region if vpc_zone_identifier is not set.
required: false
launch_config_name:
description:
- Name of the Launch configuration to use for the group. See the ec2_lc module for managing these.
required: true
min_size:
description:
- Minimum number of instances in group, if unspecified then the current group value will be used.
required: false
max_size:
description:
- Maximum number of instances in group, if unspecified then the current group value will be used.
required: false
placement_group:
description:
- Physical location of your cluster placement group created in Amazon EC2.
required: false
version_added: "2.3"
default: None
desired_capacity:
description:
- Desired number of instances in group, if unspecified then the current group value will be used.
required: false
replace_all_instances:
description:
- In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration.
required: false
version_added: "1.8"
default: False
replace_batch_size:
description:
- Number of instances you'd like to replace at a time. Used with replace_all_instances.
required: false
version_added: "1.8"
default: 1
replace_instances:
description:
- List of instance_ids belonging to the named ASG that you would like to terminate and be replaced with instances matching the current launch configuration.
required: false
version_added: "1.8"
default: None
lc_check:
description:
- Check to make sure instances that are being replaced with replace_instances do not already have the current launch_config.
required: false
version_added: "1.8"
default: True
vpc_zone_identifier:
description:
- List of VPC subnets to use
required: false
default: None
tags:
description:
- A list of tags to add to the Auto Scale Group. Optional key is 'propagate_at_launch', which defaults to true.
required: false
default: None
version_added: "1.7"
health_check_period:
description:
- Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
required: false
default: 500 seconds
version_added: "1.7"
health_check_type:
description:
- The service you want the health status from, Amazon EC2 or Elastic Load Balancer.
required: false
default: EC2
version_added: "1.7"
choices: ['EC2', 'ELB']
default_cooldown:
description:
- The number of seconds after a scaling activity completes before another can begin.
required: false
default: 300 seconds
version_added: "2.0"
wait_timeout:
description:
- how long before wait instances to become viable when replaced. Used in conjunction with instance_ids option.
default: 300
version_added: "1.8"
wait_for_instances:
description:
- Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all instances have a lifecycle_state of "InService" and a health_status of "Healthy".
version_added: "1.9"
default: yes
required: False
termination_policies:
description:
- An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.
- For 'Default', when used to create a new autoscaling group, the "Default"i value is used. When used to change an existent autoscaling group, the current termination policies are maintained.
required: false
default: Default
choices: ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default']
version_added: "2.0"
notification_topic:
description:
- A SNS topic ARN to send auto scaling notifications to.
default: None
required: false
version_added: "2.2"
notification_types:
description:
- A list of auto scaling events to trigger notifications on.
default: ['autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR']
required: false
version_added: "2.2"
suspend_processes:
description:
- A list of scaling processes to suspend.
required: False
default: []
choices: ['Launch', 'Terminate', 'HealthCheck', 'ReplaceUnhealthy', 'AZRebalance', 'AlarmNotification', 'ScheduledActions', 'AddToLoadBalancer']
version_added: "2.3"
extends_documentation_fragment:
- aws
- ec2
"""
EXAMPLES = '''
# Basic configuration
- ec2_asg:
name: special
load_balancers: [ 'lb1', 'lb2' ]
availability_zones: [ 'eu-west-1a', 'eu-west-1b' ]
launch_config_name: 'lc-1'
min_size: 1
max_size: 10
desired_capacity: 5
vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]
tags:
- environment: production
propagate_at_launch: no
# Rolling ASG Updates
Below is an example of how to assign a new launch config to an ASG and terminate old instances.
All instances in "myasg" that do not have the launch configuration named "my_new_lc" will be terminated in
a rolling fashion with instances using the current launch configuration, "my_new_lc".
This could also be considered a rolling deploy of a pre-baked AMI.
If this is a newly created group, the instances will not be replaced since all instances
will have the current launch configuration.
- name: create launch config
ec2_lc:
name: my_new_lc
image_id: ami-lkajsf
key_name: mykey
region: us-east-1
security_groups: sg-23423
instance_type: m1.small
assign_public_ip: yes
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_all_instances: yes
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
To only replace a couple of instances instead of all of them, supply a list
to "replace_instances":
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_instances:
- i-b345231
- i-24c2931
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
'''
import time
import logging as log
import traceback
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
log.getLogger('boto').setLevel(log.CRITICAL)
#log.basicConfig(filename='/tmp/ansible_ec2_asg.log',level=log.DEBUG, format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
try:
import boto.ec2.autoscale
from boto.ec2.autoscale import AutoScaleConnection, AutoScalingGroup, Tag
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
ASG_ATTRIBUTES = ('availability_zones', 'default_cooldown', 'desired_capacity',
'health_check_period', 'health_check_type', 'launch_config_name',
'load_balancers', 'max_size', 'min_size', 'name', 'placement_group',
'termination_policies', 'vpc_zone_identifier')
INSTANCE_ATTRIBUTES = ('instance_id', 'health_status', 'lifecycle_state', 'launch_config_name')
def enforce_required_arguments(module):
''' As many arguments are not required for autoscale group deletion
they cannot be mandatory arguments for the module, so we enforce
them here '''
missing_args = []
for arg in ('min_size', 'max_size', 'launch_config_name'):
if module.params[arg] is None:
missing_args.append(arg)
if missing_args:
module.fail_json(msg="Missing required arguments for autoscaling group create/update: %s" % ",".join(missing_args))
def get_properties(autoscaling_group):
properties = dict((attr, getattr(autoscaling_group, attr)) for attr in ASG_ATTRIBUTES)
# Ugly hack to make this JSON-serializable. We take a list of boto Tag
# objects and replace them with a dict-representation. Needed because the
# tags are included in ansible's return value (which is jsonified)
if 'tags' in properties and isinstance(properties['tags'], list):
serializable_tags = {}
for tag in properties['tags']:
serializable_tags[tag.key] = [tag.value, tag.propagate_at_launch]
properties['tags'] = serializable_tags
properties['healthy_instances'] = 0
properties['in_service_instances'] = 0
properties['unhealthy_instances'] = 0
properties['pending_instances'] = 0
properties['viable_instances'] = 0
properties['terminating_instances'] = 0
instance_facts = {}
if autoscaling_group.instances:
properties['instances'] = [i.instance_id for i in autoscaling_group.instances]
for i in autoscaling_group.instances:
instance_facts[i.instance_id] = {'health_status': i.health_status,
'lifecycle_state': i.lifecycle_state,
'launch_config_name': i.launch_config_name }
if i.health_status == 'Healthy' and i.lifecycle_state == 'InService':
properties['viable_instances'] += 1
if i.health_status == 'Healthy':
properties['healthy_instances'] += 1
else:
properties['unhealthy_instances'] += 1
if i.lifecycle_state == 'InService':
properties['in_service_instances'] += 1
if i.lifecycle_state == 'Terminating':
properties['terminating_instances'] += 1
if i.lifecycle_state == 'Pending':
properties['pending_instances'] += 1
properties['instance_facts'] = instance_facts
properties['load_balancers'] = autoscaling_group.load_balancers
if getattr(autoscaling_group, "tags", None):
properties['tags'] = dict((t.key, t.value) for t in autoscaling_group.tags)
return properties
def elb_dreg(asg_connection, module, group_name, instance_id):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
as_group = asg_connection.get_all_groups(names=[group_name])[0]
wait_timeout = module.params.get('wait_timeout')
props = get_properties(as_group)
count = 1
if as_group.load_balancers and as_group.health_check_type == 'ELB':
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
else:
return
for lb in as_group.load_balancers:
elb_connection.deregister_instances(lb, instance_id)
log.debug("De-registering {0} from ELB {1}".format(instance_id, lb))
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
count = 0
for lb in as_group.load_balancers:
lb_instances = elb_connection.describe_instance_health(lb)
for i in lb_instances:
if i.instance_id == instance_id and i.state == "InService":
count += 1
log.debug("{0}: {1}, {2}".format(i.instance_id, i.state, i.description))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for instance to deregister. {0}".format(time.asctime()))
def elb_healthy(asg_connection, elb_connection, module, group_name):
healthy_instances = set()
as_group = asg_connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
# get healthy, inservice instances from ASG
instances = []
for instance, settings in props['instance_facts'].items():
if settings['lifecycle_state'] == 'InService' and settings['health_status'] == 'Healthy':
instances.append(instance)
log.debug("ASG considers the following instances InService and Healthy: {0}".format(instances))
log.debug("ELB instance status:")
for lb in as_group.load_balancers:
# we catch a race condition that sometimes happens if the instance exists in the ASG
# but has not yet show up in the ELB
try:
lb_instances = elb_connection.describe_instance_health(lb, instances=instances)
except boto.exception.BotoServerError as e:
if e.error_code == 'InvalidInstance':
return None
module.fail_json(msg=str(e))
for i in lb_instances:
if i.state == "InService":
healthy_instances.add(i.instance_id)
log.debug("{0}: {1}".format(i.instance_id, i.state))
return len(healthy_instances)
def wait_for_elb(asg_connection, module, group_name):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
wait_timeout = module.params.get('wait_timeout')
# if the health_check_type is ELB, we want to query the ELBs directly for instance
# status as to avoid health_check_grace period that is awarded to ASG instances
as_group = asg_connection.get_all_groups(names=[group_name])[0]
if as_group.load_balancers and as_group.health_check_type == 'ELB':
log.debug("Waiting for ELB to consider instances healthy.")
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
wait_timeout = time.time() + wait_timeout
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
while healthy_instances < as_group.min_size and wait_timeout > time.time():
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
log.debug("ELB thinks {0} instances are healthy.".format(healthy_instances))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for ELB instances to be healthy. %s" % time.asctime())
log.debug("Waiting complete. ELB thinks {0} instances are healthy.".format(healthy_instances))
def suspend_processes(as_group, module):
suspend_processes = set(module.params.get('suspend_processes'))
try:
suspended_processes = set([p.process_name for p in as_group.suspended_processes])
except AttributeError:
# New ASG being created, no suspended_processes defined yet
suspended_processes = set()
if suspend_processes == suspended_processes:
return False
resume_processes = list(suspended_processes - suspend_processes)
if resume_processes:
as_group.resume_processes(resume_processes)
if suspend_processes:
as_group.suspend_processes(list(suspend_processes))
return True
def create_autoscaling_group(connection, module):
group_name = module.params.get('name')
load_balancers = module.params['load_balancers']
availability_zones = module.params['availability_zones']
launch_config_name = module.params.get('launch_config_name')
min_size = module.params['min_size']
max_size = module.params['max_size']
placement_group = module.params.get('placement_group')
desired_capacity = module.params.get('desired_capacity')
vpc_zone_identifier = module.params.get('vpc_zone_identifier')
set_tags = module.params.get('tags')
health_check_period = module.params.get('health_check_period')
health_check_type = module.params.get('health_check_type')
default_cooldown = module.params.get('default_cooldown')
wait_for_instances = module.params.get('wait_for_instances')
as_groups = connection.get_all_groups(names=[group_name])
wait_timeout = module.params.get('wait_timeout')
termination_policies = module.params.get('termination_policies')
notification_topic = module.params.get('notification_topic')
notification_types = module.params.get('notification_types')
if not vpc_zone_identifier and not availability_zones:
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
ec2_connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif vpc_zone_identifier:
vpc_zone_identifier = ','.join(vpc_zone_identifier)
asg_tags = []
for tag in set_tags:
for k,v in tag.items():
if k !='propagate_at_launch':
asg_tags.append(Tag(key=k,
value=v,
propagate_at_launch=bool(tag.get('propagate_at_launch', True)),
resource_id=group_name))
if not as_groups:
if not vpc_zone_identifier and not availability_zones:
availability_zones = module.params['availability_zones'] = [zone.name for zone in ec2_connection.get_all_zones()]
enforce_required_arguments(module)
launch_configs = connection.get_all_launch_configurations(names=[launch_config_name])
if len(launch_configs) == 0:
module.fail_json(msg="No launch config found with name %s" % launch_config_name)
ag = AutoScalingGroup(
group_name=group_name,
load_balancers=load_balancers,
availability_zones=availability_zones,
launch_config=launch_configs[0],
min_size=min_size,
max_size=max_size,
placement_group=placement_group,
desired_capacity=desired_capacity,
vpc_zone_identifier=vpc_zone_identifier,
connection=connection,
tags=asg_tags,
health_check_period=health_check_period,
health_check_type=health_check_type,
default_cooldown=default_cooldown,
termination_policies=termination_policies)
try:
connection.create_auto_scaling_group(ag)
suspend_processes(ag, module)
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
if notification_topic:
ag.put_notification_configuration(notification_topic, notification_types)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
changed = True
return(changed, asg_properties)
except BotoServerError as e:
module.fail_json(msg="Failed to create Autoscaling Group: %s" % str(e), exception=traceback.format_exc(e))
else:
as_group = as_groups[0]
changed = False
if suspend_processes(as_group, module):
changed = True
for attr in ASG_ATTRIBUTES:
if module.params.get(attr, None) is not None:
module_attr = module.params.get(attr)
if attr == 'vpc_zone_identifier':
module_attr = ','.join(module_attr)
group_attr = getattr(as_group, attr)
# we do this because AWS and the module may return the same list
# sorted differently
if attr != 'termination_policies':
try:
module_attr.sort()
except:
pass
try:
group_attr.sort()
except:
pass
if group_attr != module_attr:
changed = True
setattr(as_group, attr, module_attr)
if len(set_tags) > 0:
have_tags = {}
want_tags = {}
for tag in asg_tags:
want_tags[tag.key] = [tag.value, tag.propagate_at_launch]
dead_tags = []
for tag in as_group.tags:
have_tags[tag.key] = [tag.value, tag.propagate_at_launch]
if tag.key not in want_tags:
changed = True
dead_tags.append(tag)
if dead_tags != []:
connection.delete_tags(dead_tags)
if have_tags != want_tags:
changed = True
connection.create_or_update_tags(asg_tags)
# handle loadbalancers separately because None != []
load_balancers = module.params.get('load_balancers') or []
if load_balancers and as_group.load_balancers != load_balancers:
changed = True
as_group.load_balancers = module.params.get('load_balancers')
if changed:
try:
as_group.update()
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group: %s" % str(e), exception=traceback.format_exc(e))
if notification_topic:
try:
as_group.put_notification_configuration(notification_topic, notification_types)
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group notifications: %s" % str(e), exception=traceback.format_exc(e))
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
try:
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
except BotoServerError as e:
module.fail_json(msg="Failed to read existing Autoscaling Groups: %s" % str(e), exception=traceback.format_exc(e))
return(changed, asg_properties)
def delete_autoscaling_group(connection, module):
group_name = module.params.get('name')
notification_topic = module.params.get('notification_topic')
if notification_topic:
ag.delete_notification_configuration(notification_topic)
groups = connection.get_all_groups(names=[group_name])
if groups:
group = groups[0]
group.max_size = 0
group.min_size = 0
group.desired_capacity = 0
group.update()
instances = True
while instances:
tmp_groups = connection.get_all_groups(names=[group_name])
if tmp_groups:
tmp_group = tmp_groups[0]
if not tmp_group.instances:
instances = False
time.sleep(10)
group.delete()
while len(connection.get_all_groups(names=[group_name])):
time.sleep(5)
changed=True
return changed
else:
changed=False
return changed
def get_chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def update_size(group, max_size, min_size, dc):
log.debug("setting ASG sizes")
log.debug("minimum size: {0}, desired_capacity: {1}, max size: {2}".format(min_size, dc, max_size ))
group.max_size = max_size
group.min_size = min_size
group.desired_capacity = dc
group.update()
def replace(connection, module):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
max_size = module.params.get('max_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
lc_check = module.params.get('lc_check')
replace_instances = module.params.get('replace_instances')
as_group = connection.get_all_groups(names=[group_name])[0]
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
#check if min_size/max_size/desired capacity have been specified and if not use ASG values
if min_size is None:
min_size = as_group.min_size
if max_size is None:
max_size = as_group.max_size
if desired_capacity is None:
desired_capacity = as_group.desired_capacity
# check to see if instances are replaceable if checking launch configs
new_instances, old_instances = get_instances_by_lc(props, lc_check, instances)
num_new_inst_needed = desired_capacity - len(new_instances)
if lc_check:
if num_new_inst_needed == 0 and old_instances:
log.debug("No new instances needed, but old instances are present. Removing old instances")
terminate_batch(connection, module, old_instances, instances, True)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
changed = True
return(changed, props)
# we don't want to spin up extra instances if not necessary
if num_new_inst_needed < batch_size:
log.debug("Overriding batch size to {0}".format(num_new_inst_needed))
batch_size = num_new_inst_needed
if not old_instances:
changed = False
return(changed, props)
# set temporary settings and wait for them to be reached
# This should get overwritten if the number of instances left is less than the batch size.
as_group = connection.get_all_groups(names=[group_name])[0]
update_size(as_group, max_size + batch_size, min_size + batch_size, desired_capacity + batch_size)
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
log.debug("beginning main loop")
for i in get_chunks(instances, batch_size):
# break out of this loop if we have enough new instances
break_early, desired_size, term_instances = terminate_batch(connection, module, i, instances, False)
wait_for_term_inst(connection, module, term_instances)
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
if break_early:
log.debug("breaking loop")
break
update_size(as_group, max_size, min_size, desired_capacity)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
log.debug("Rolling update complete.")
changed=True
return(changed, asg_properties)
def get_instances_by_lc(props, lc_check, initial_instances):
new_instances = []
old_instances = []
# old instances are those that have the old launch config
if lc_check:
for i in props['instances']:
if props['instance_facts'][i]['launch_config_name'] == props['launch_config_name']:
new_instances.append(i)
else:
old_instances.append(i)
else:
log.debug("Comparing initial instances with current: {0}".format(initial_instances))
for i in props['instances']:
if i not in initial_instances:
new_instances.append(i)
else:
old_instances.append(i)
log.debug("New instances: {0}, {1}".format(len(new_instances), new_instances))
log.debug("Old instances: {0}, {1}".format(len(old_instances), old_instances))
return new_instances, old_instances
def list_purgeable_instances(props, lc_check, replace_instances, initial_instances):
instances_to_terminate = []
instances = ( inst_id for inst_id in replace_instances if inst_id in props['instances'])
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
if lc_check:
for i in instances:
if props['instance_facts'][i]['launch_config_name'] != props['launch_config_name']:
instances_to_terminate.append(i)
else:
for i in instances:
if i in initial_instances:
instances_to_terminate.append(i)
return instances_to_terminate
def terminate_batch(connection, module, replace_instances, initial_instances, leftovers=False):
batch_size = module.params.get('replace_batch_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
group_name = module.params.get('name')
wait_timeout = int(module.params.get('wait_timeout'))
lc_check = module.params.get('lc_check')
decrement_capacity = False
break_loop = False
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
desired_size = as_group.min_size
new_instances, old_instances = get_instances_by_lc(props, lc_check, initial_instances)
num_new_inst_needed = desired_capacity - len(new_instances)
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
instances_to_terminate = list_purgeable_instances(props, lc_check, replace_instances, initial_instances)
log.debug("new instances needed: {0}".format(num_new_inst_needed))
log.debug("new instances: {0}".format(new_instances))
log.debug("old instances: {0}".format(old_instances))
log.debug("batch instances: {0}".format(",".join(instances_to_terminate)))
if num_new_inst_needed == 0:
decrement_capacity = True
if as_group.min_size != min_size:
as_group.min_size = min_size
as_group.update()
log.debug("Updating minimum size back to original of {0}".format(min_size))
#if are some leftover old instances, but we are already at capacity with new ones
# we don't want to decrement capacity
if leftovers:
decrement_capacity = False
break_loop = True
instances_to_terminate = old_instances
desired_size = min_size
log.debug("No new instances needed")
if num_new_inst_needed < batch_size and num_new_inst_needed !=0 :
instances_to_terminate = instances_to_terminate[:num_new_inst_needed]
decrement_capacity = False
break_loop = False
log.debug("{0} new instances needed".format(num_new_inst_needed))
log.debug("decrementing capacity: {0}".format(decrement_capacity))
for instance_id in instances_to_terminate:
elb_dreg(connection, module, group_name, instance_id)
log.debug("terminating instance: {0}".format(instance_id))
connection.terminate_instance(instance_id, decrement_capacity=decrement_capacity)
# we wait to make sure the machines we marked as Unhealthy are
# no longer in the list
return break_loop, desired_size, instances_to_terminate
def wait_for_term_inst(connection, module, term_instances):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
lc_check = module.params.get('lc_check')
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
count = 1
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
log.debug("waiting for instances to terminate")
count = 0
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instance_facts = props['instance_facts']
instances = ( i for i in instance_facts if i in term_instances)
for i in instances:
lifecycle = instance_facts[i]['lifecycle_state']
health = instance_facts[i]['health_status']
log.debug("Instance {0} has state of {1},{2}".format(i,lifecycle,health ))
if lifecycle == 'Terminating' or health == 'Unhealthy':
count += 1
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for old instances to terminate. %s" % time.asctime())
def wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, prop):
# make sure we have the latest stats after that last loop.
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
# now we make sure that we have enough instances in a viable state
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and desired_size > props[prop]:
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
time.sleep(10)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for new instances to become viable. %s" % time.asctime())
log.debug("Reached {0}: {1}".format(prop, desired_size))
return props
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
name=dict(required=True, type='str'),
load_balancers=dict(type='list'),
availability_zones=dict(type='list'),
launch_config_name=dict(type='str'),
min_size=dict(type='int'),
max_size=dict(type='int'),
placement_group=dict(type='str'),
desired_capacity=dict(type='int'),
vpc_zone_identifier=dict(type='list'),
replace_batch_size=dict(type='int', default=1),
replace_all_instances=dict(type='bool', default=False),
replace_instances=dict(type='list', default=[]),
lc_check=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=300),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(type='list', default=[]),
health_check_period=dict(type='int', default=300),
health_check_type=dict(default='EC2', choices=['EC2', 'ELB']),
default_cooldown=dict(type='int', default=300),
wait_for_instances=dict(type='bool', default=True),
termination_policies=dict(type='list', default='Default'),
notification_topic=dict(type='str', default=None),
notification_types=dict(type='list', default=[
'autoscaling:EC2_INSTANCE_LAUNCH',
'autoscaling:EC2_INSTANCE_LAUNCH_ERROR',
'autoscaling:EC2_INSTANCE_TERMINATE',
'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'
]),
suspend_processes=dict(type='list', default=[])
),
)
module = AnsibleModule(
argument_spec=argument_spec,
mutually_exclusive = [['replace_all_instances', 'replace_instances']]
)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
state = module.params.get('state')
replace_instances = module.params.get('replace_instances')
replace_all_instances = module.params.get('replace_all_instances')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params)
if not connection:
module.fail_json(msg="failed to connect to AWS for the given region: %s" % str(region))
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
changed = create_changed = replace_changed = False
if state == 'present':
create_changed, asg_properties=create_autoscaling_group(connection, module)
elif state == 'absent':
changed = delete_autoscaling_group(connection, module)
module.exit_json( changed = changed )
if replace_all_instances or replace_instances:
replace_changed, asg_properties=replace(connection, module)
if create_changed or replace_changed:
changed = True
module.exit_json( changed = changed, **asg_properties )
if __name__ == '__main__':
main()
| zahodi/ansible | lib/ansible/modules/cloud/amazon/ec2_asg.py | Python | gpl-3.0 | 38,091 |
using EloBuddy;
using LeagueSharp.Common;
namespace Nasus
{
using LeagueSharp.Common;
public class MenuInit
{
public static Menu Menu;
public static void Initialize()
{
Menu = new Menu("Nasus - The Crazy Dog", "L# Nasus", true);
var orbwalkerMenu = new Menu("Orbwalker", "orbwalker");
Standards.Orbwalker = new Orbwalking.Orbwalker(orbwalkerMenu);
Menu.AddSubMenu(orbwalkerMenu);
TargetSelector.AddToMenu(TargetSelectorMenu());
#region Combo Menu
var comboMenu = Menu.AddSubMenu(new Menu("Combo", "MenuCombo"));
{
comboMenu
.AddItem(new MenuItem("Combo.Use.Q", "Use Q").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.W", "Use W").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.E", "Use E").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.R", "Use R").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Min.HP.Use.R", "HP to use R").SetValue(new Slider(35)));
}
#endregion
#region Harass Menu
var harassMenu = Menu.AddSubMenu(new Menu("Harass", "MenuHarass"));
{
harassMenu
.AddItem(new MenuItem("Harass.Use.Q", "Use Q").SetValue(true));
harassMenu
.AddItem(new MenuItem("Harass.Use.W", "Use W").SetValue(true));
harassMenu
.AddItem(new MenuItem("Harass.Use.E", "Use E").SetValue(true));
}
#endregion
#region Lane Clear
var laneClearMenu = Menu.AddSubMenu(new Menu("Lane Clear", "MenuLaneClear"));
{
laneClearMenu
.AddItem(new MenuItem("LaneClear.Use.Q", "Use Q").SetValue(true));
laneClearMenu
.AddItem(new MenuItem("LaneClear.Use.E", "Use E").SetValue(true));
}
#endregion
#region Last Hit
var lastHitMenu = Menu.AddSubMenu(new Menu("Stack Siphoning Strike", "MenuStackQ"));
{
lastHitMenu
.AddItem(new MenuItem("Use.StackQ", "Stack").SetValue(true));
}
#endregion
Menu.AddItem(new MenuItem("devCredits", "Dev by @ TwoHam"));
Menu.AddToMainMenu();
}
private static Menu TargetSelectorMenu()
{
return Menu.AddSubMenu(new Menu("Target Selector", "TargetSelector"));
}
}
}
| tk8226/YamiPortAIO-v2 | Core/Champion Ports/Nasus/Nasus The Crazy Dog/MenuInit.cs | C# | gpl-3.0 | 2,750 |
import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else:
tag = None
value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character
| aurora-pro/apex-sigma | sigma/plugins/fun/vn_char.py | Python | gpl-3.0 | 2,210 |
<?php
// Heading
$_['heading_title'] = 'OpenBay Pro';
// Text
$_['text_module'] = 'フィード設定';
$_['text_installed'] = 'OpenBayProモジュールがインストールされました。 拡張機能 -> OpenBay Proで利用することができます'; | huylv-hust/opencart | admin/language/japanese/feed/openbaypro.php | PHP | gpl-3.0 | 264 |
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "w32prefix.h"
#include "globdefs.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
//#include "execpt.h"
bool MCFileSystemPathToNative(const char *p_path, void*& r_native_path)
{
unichar_t *t_w_path;
t_w_path = nil;
if (!MCCStringToUnicode(p_path, t_w_path))
return false;
for(uint32_t i = 0; t_w_path[i] != 0; i++)
if (t_w_path[i] == '/')
t_w_path[i] = '\\';
r_native_path = t_w_path;
return true;
}
bool MCFileSystemPathFromNative(const void *p_native_path, char*& r_path)
{
char *t_path;
t_path = nil;
if (!MCCStringFromUnicode((const unichar_t *)p_native_path, t_path))
return false;
for(uint32_t i = 0; t_path[i] != 0; i++)
if (t_path[i] == '\\')
t_path[i] = '/';
r_path = t_path;
return true;
}
bool MCFileSystemListEntries(const char *p_folder, uint32_t p_options, MCFileSystemListCallback p_callback, void *p_context)
{
bool t_success;
t_success = true;
char *t_pattern;
t_pattern = nil;
if (t_success)
t_success = MCCStringFormat(t_pattern, "%s%s", p_folder, MCCStringEndsWith(p_folder, "/") ? "*" : "/*");
void *t_native_pattern;
t_native_pattern = nil;
if (t_success)
t_success = MCFileSystemPathToNative(t_pattern, t_native_pattern);
HANDLE t_find_handle;
WIN32_FIND_DATAW t_find_data;
t_find_handle = INVALID_HANDLE_VALUE;
if (t_success)
{
t_find_handle = FindFirstFileW((LPCWSTR)t_native_pattern, &t_find_data);
if (t_find_handle == INVALID_HANDLE_VALUE)
t_success = false;
}
while(t_success)
{
char *t_entry_filename;
if (t_success)
t_success = MCFileSystemPathFromNative(t_find_data . cFileName, t_entry_filename);
MCFileSystemEntry t_entry;
if (t_success)
{
t_entry . type = (t_find_data . dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ? kMCFileSystemEntryFolder : kMCFileSystemEntryFile;
MCStringCreateWithCString(t_entry_filename, t_entry.filename);
//t_entry . filename = t_entry_filename;
t_success = p_callback(p_context, t_entry);
}
MCCStringFree(t_entry_filename);
////
if (!FindNextFileW(t_find_handle, &t_find_data))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
break;
t_success = false;
}
}
if (t_find_handle != INVALID_HANDLE_VALUE)
FindClose(t_find_handle);
MCMemoryDeallocate(t_native_pattern);
MCCStringFree(t_pattern);
return t_success;
}
bool MCFileSystemPathResolve(const char *p_path, char*& r_resolved_path)
{
return MCCStringClone(p_path, r_resolved_path);
}
bool MCFileSystemPathExists(const char *p_path, bool p_folder, bool& r_exists)
{
bool t_success;
t_success = true;
void *t_native_path;
t_native_path = nil;
if (t_success)
t_success = MCFileSystemPathToNative(p_path, t_native_path);
if (t_success)
{
DWORD t_result;
t_result = GetFileAttributesW((LPCWSTR)t_native_path);
if (t_result != INVALID_FILE_ATTRIBUTES)
{
r_exists =
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) == 0 && !p_folder) ||
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) != 0 && p_folder);
}
else
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
r_exists = false;
else
t_success = false;
}
}
MCMemoryDeleteArray(t_native_path);
return t_success;
}
| LiveCodeSteven/livecode | engine/src/sysw32fs.cpp | C++ | gpl-3.0 | 3,808 |
define(
[
'jquery',
'stapes',
'./conditionals'
],
function(
$,
Stapes,
conditionalsMediator
) {
'use strict';
/**
* Global Mediator (included on every page)
* @module Globals
* @implements {Stapes}
*/
var Mediator = Stapes.subclass({
/**
* Reference to conditionals mediator singleton
* @type {Object}
*/
conditionals: conditionalsMediator,
/**
* Mediator Constructor
* @return {void}
*/
constructor: function (){
var self = this;
self.initEvents();
$(function(){
self.emit('domready');
});
},
/**
* Initialize events
* @return {void}
*/
initEvents: function(){
var self = this;
self.on('domready', self.onDomReady);
// // DEBUG
// conditionalsMediator.on('all', function(val, e){
// console.log(e.type, val);
// });
},
/**
* DomReady Callback
* @return {void}
*/
onDomReady: function(){
var self = this;
}
});
return new Mediator();
}
);
| minutelabsio/sed-postcard-map | app/library/js/mediators/globals.js | JavaScript | gpl-3.0 | 1,501 |
require 'spec_helper'
describe 'puppet::agent' do
on_supported_os.each do |os, os_facts|
next if only_test_os() and not only_test_os.include?(os)
next if exclude_test_os() and exclude_test_os.include?(os)
context "on #{os}" do
let (:default_facts) do
os_facts.merge({
:clientcert => 'puppetmaster.example.com',
:concat_basedir => '/nonexistant',
:fqdn => 'puppetmaster.example.com',
:puppetversion => Puppet.version,
}) end
if Puppet.version < '4.0'
client_package = 'puppet'
confdir = '/etc/puppet'
case os_facts[:osfamily]
when 'FreeBSD'
client_package = 'puppet38'
confdir = '/usr/local/etc/puppet'
when 'windows'
client_package = 'puppet'
confdir = 'C:/ProgramData/PuppetLabs/puppet/etc'
end
additional_facts = {}
else
client_package = 'puppet-agent'
confdir = '/etc/puppetlabs/puppet'
additional_facts = {:rubysitedir => '/opt/puppetlabs/puppet/lib/ruby/site_ruby/2.1.0'}
case os_facts[:osfamily]
when 'FreeBSD'
client_package = 'puppet4'
confdir = '/usr/local/etc/puppet'
additional_facts = {}
when 'windows'
client_package = 'puppet-agent'
confdir = 'C:/ProgramData/PuppetLabs/puppet/etc'
additional_facts = {}
end
end
let :facts do
default_facts.merge(additional_facts)
end
describe 'with no custom parameters' do
let :pre_condition do
"class {'puppet': agent => true}"
end
it { should contain_class('puppet::agent::install') }
it { should contain_class('puppet::agent::config') }
it { should contain_class('puppet::agent::service') }
it { should contain_file(confdir).with_ensure('directory') }
it { should contain_concat("#{confdir}/puppet.conf") }
it { should contain_package(client_package).with_ensure('present') }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/^\[agent\]/).
with({})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*puppetmaster\.example\.com/)
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/prerun_command\s*=/)
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/postrun_command\s*=/)
end
end
describe 'puppetmaster parameter overrides server fqdn' do
let(:pre_condition) { "class {'puppet': agent => true, puppetmaster => 'mymaster.example.com'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'global puppetmaster overrides fqdn' do
let(:pre_condition) { "class {'puppet': agent => true}" }
let :facts do
default_facts.merge({:puppetmaster => 'mymaster.example.com'})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'puppetmaster parameter overrides global puppetmaster' do
let(:pre_condition) { "class {'puppet': agent => true, puppetmaster => 'mymaster.example.com'}" }
let :facts do
default_facts.merge({:puppetmaster => 'global.example.com'})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'use_srv_records removes server setting' do
let(:pre_condition) { "class {'puppet': agent => true, use_srv_records => true}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/server\s*=/)
end
end
describe 'set prerun_command will be included in config' do
let(:pre_condition) { "class {'puppet': agent => true, prerun_command => '/my/prerun'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/prerun_command.*\/my\/prerun/)
end
end
describe 'set postrun_command will be included in config' do
let(:pre_condition) { "class {'puppet': agent => true, postrun_command => '/my/postrun'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/postrun_command.*\/my\/postrun/)
end
end
describe 'with additional settings' do
let :pre_condition do
"class {'puppet':
agent_additional_settings => {ignoreschedules => true},
}"
end
it 'should configure puppet.conf' do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/^\s+ignoreschedules\s+= true$/).
with({}) # So we can use a trailing dot on each with_content line
end
end
end
end
end
| szemlyanoy/puppet-puppet | spec/classes/puppet_agent_spec.rb | Ruby | gpl-3.0 | 5,356 |
<?php
return [
'AF' => 'Afganisztán',
'AX' => 'Åland-szigetek',
'AL' => 'Albánia',
'DZ' => 'Algéria',
'AS' => 'Amerikai Szamoa',
'VI' => 'Amerikai Virgin-szigetek',
'AD' => 'Andorra',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AQ' => 'Antarktisz',
'AG' => 'Antigua és Barbuda',
'AR' => 'Argentína',
'AW' => 'Aruba',
'AU' => 'Ausztrália',
'AT' => 'Ausztria',
'UM' => 'Az USA lakatlan külbirtokai',
'AZ' => 'Azerbajdzsán',
'BS' => 'Bahama-szigetek',
'BH' => 'Bahrein',
'BD' => 'Banglades',
'BB' => 'Barbados',
'BY' => 'Belarusz',
'BE' => 'Belgium',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermuda',
'BT' => 'Bhután',
'GW' => 'Bissau-Guinea',
'BO' => 'Bolívia',
'BA' => 'Bosznia-Hercegovina',
'BW' => 'Botswana',
'BV' => 'Bouvet-sziget',
'BR' => 'Brazília',
'IO' => 'Brit Indiai-óceáni Terület',
'VG' => 'Brit Virgin-szigetek',
'BN' => 'Brunei',
'BG' => 'Bulgária',
'BF' => 'Burkina Faso',
'BI' => 'Burundi',
'CL' => 'Chile',
'CY' => 'Ciprus',
'KM' => 'Comore-szigetek',
'CK' => 'Cook-szigetek',
'CR' => 'Costa Rica',
'CW' => 'Curaçao',
'TD' => 'Csád',
'CZ' => 'Csehország',
'DK' => 'Dánia',
'ZA' => 'Dél-afrikai Köztársaság',
'KR' => 'Dél-Korea',
'SS' => 'Dél-Szudán',
'GS' => 'Déli-Georgia és Déli-Sandwich-szigetek',
'DM' => 'Dominika',
'DO' => 'Dominikai Köztársaság',
'DJ' => 'Dzsibuti',
'EC' => 'Ecuador',
'GQ' => 'Egyenlítői-Guinea',
'US' => 'Egyesült Államok',
'AE' => 'Egyesült Arab Emírségek',
'GB' => 'Egyesült Királyság',
'EG' => 'Egyiptom',
'CI' => 'Elefántcsontpart',
'ER' => 'Eritrea',
'KP' => 'Észak-Korea',
'MK' => 'Észak-Macedónia',
'MP' => 'Északi Mariana-szigetek',
'EE' => 'Észtország',
'ET' => 'Etiópia',
'FK' => 'Falkland-szigetek',
'FO' => 'Feröer szigetek',
'FJ' => 'Fidzsi',
'FI' => 'Finnország',
'TF' => 'Francia Déli Területek',
'GF' => 'Francia Guyana',
'PF' => 'Francia Polinézia',
'FR' => 'Franciaország',
'PH' => 'Fülöp-szigetek',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GH' => 'Ghána',
'GI' => 'Gibraltár',
'GR' => 'Görögország',
'GD' => 'Grenada',
'GL' => 'Grönland',
'GE' => 'Grúzia',
'GP' => 'Guadeloupe',
'GU' => 'Guam',
'GT' => 'Guatemala',
'GG' => 'Guernsey',
'GN' => 'Guinea',
'GY' => 'Guyana',
'HT' => 'Haiti',
'HM' => 'Heard-sziget és McDonald-szigetek',
'BQ' => 'Holland Karib-térség',
'NL' => 'Hollandia',
'HN' => 'Honduras',
'HK' => 'Hongkong KKT',
'HR' => 'Horvátország',
'IN' => 'India',
'ID' => 'Indonézia',
'IQ' => 'Irak',
'IR' => 'Irán',
'IE' => 'Írország',
'IS' => 'Izland',
'IL' => 'Izrael',
'JM' => 'Jamaica',
'JP' => 'Japán',
'YE' => 'Jemen',
'JE' => 'Jersey',
'JO' => 'Jordánia',
'KY' => 'Kajmán-szigetek',
'KH' => 'Kambodzsa',
'CM' => 'Kamerun',
'CA' => 'Kanada',
'CX' => 'Karácsony-sziget',
'QA' => 'Katar',
'KZ' => 'Kazahsztán',
'TL' => 'Kelet-Timor',
'KE' => 'Kenya',
'CN' => 'Kína',
'KG' => 'Kirgizisztán',
'KI' => 'Kiribati',
'CC' => 'Kókusz (Keeling)-szigetek',
'CO' => 'Kolumbia',
'CG' => 'Kongó – Brazzaville',
'CD' => 'Kongó – Kinshasa',
'CF' => 'Közép-afrikai Köztársaság',
'CU' => 'Kuba',
'KW' => 'Kuvait',
'LA' => 'Laosz',
'PL' => 'Lengyelország',
'LS' => 'Lesotho',
'LV' => 'Lettország',
'LB' => 'Libanon',
'LR' => 'Libéria',
'LY' => 'Líbia',
'LI' => 'Liechtenstein',
'LT' => 'Litvánia',
'LU' => 'Luxemburg',
'MG' => 'Madagaszkár',
'HU' => 'Magyarország',
'MO' => 'Makaó KKT',
'MY' => 'Malajzia',
'MW' => 'Malawi',
'MV' => 'Maldív-szigetek',
'ML' => 'Mali',
'MT' => 'Málta',
'IM' => 'Man-sziget',
'MA' => 'Marokkó',
'MH' => 'Marshall-szigetek',
'MQ' => 'Martinique',
'MR' => 'Mauritánia',
'MU' => 'Mauritius',
'YT' => 'Mayotte',
'MX' => 'Mexikó',
'MM' => 'Mianmar',
'FM' => 'Mikronézia',
'MD' => 'Moldova',
'MC' => 'Monaco',
'MN' => 'Mongólia',
'ME' => 'Montenegró',
'MS' => 'Montserrat',
'MZ' => 'Mozambik',
'NA' => 'Namíbia',
'NR' => 'Nauru',
'DE' => 'Németország',
'NP' => 'Nepál',
'NI' => 'Nicaragua',
'NE' => 'Niger',
'NG' => 'Nigéria',
'NU' => 'Niue',
'NF' => 'Norfolk-sziget',
'NO' => 'Norvégia',
'EH' => 'Nyugat-Szahara',
'IT' => 'Olaszország',
'OM' => 'Omán',
'RU' => 'Oroszország',
'AM' => 'Örményország',
'PK' => 'Pakisztán',
'PW' => 'Palau',
'PS' => 'Palesztin Autonómia',
'PA' => 'Panama',
'PG' => 'Pápua Új-Guinea',
'PY' => 'Paraguay',
'PE' => 'Peru',
'PN' => 'Pitcairn-szigetek',
'PT' => 'Portugália',
'PR' => 'Puerto Rico',
'RE' => 'Réunion',
'RO' => 'Románia',
'RW' => 'Ruanda',
'KN' => 'Saint Kitts és Nevis',
'LC' => 'Saint Lucia',
'MF' => 'Saint Martin',
'VC' => 'Saint Vincent és a Grenadine-szigetek',
'BL' => 'Saint-Barthélemy',
'PM' => 'Saint-Pierre és Miquelon',
'SB' => 'Salamon-szigetek',
'SV' => 'Salvador',
'SM' => 'San Marino',
'ST' => 'São Tomé és Príncipe',
'SC' => 'Seychelle-szigetek',
'SL' => 'Sierra Leone',
'SX' => 'Sint Maarten',
'ES' => 'Spanyolország',
'LK' => 'Srí Lanka',
'SR' => 'Suriname',
'CH' => 'Svájc',
'SJ' => 'Svalbard és Jan Mayen',
'SE' => 'Svédország',
'WS' => 'Szamoa',
'SA' => 'Szaúd-Arábia',
'SN' => 'Szenegál',
'SH' => 'Szent Ilona',
'RS' => 'Szerbia',
'SG' => 'Szingapúr',
'SY' => 'Szíria',
'SK' => 'Szlovákia',
'SI' => 'Szlovénia',
'SO' => 'Szomália',
'SD' => 'Szudán',
'SZ' => 'Szváziföld',
'TJ' => 'Tádzsikisztán',
'TW' => 'Tajvan',
'TZ' => 'Tanzánia',
'TH' => 'Thaiföld',
'TG' => 'Togo',
'TK' => 'Tokelau',
'TO' => 'Tonga',
'TR' => 'Törökország',
'TT' => 'Trinidad és Tobago',
'TN' => 'Tunézia',
'TC' => 'Turks- és Caicos-szigetek',
'TV' => 'Tuvalu',
'TM' => 'Türkmenisztán',
'UG' => 'Uganda',
'NC' => 'Új-Kaledónia',
'NZ' => 'Új-Zéland',
'UA' => 'Ukrajna',
'UY' => 'Uruguay',
'UZ' => 'Üzbegisztán',
'VU' => 'Vanuatu',
'VA' => 'Vatikán',
'VE' => 'Venezuela',
'VN' => 'Vietnám',
'WF' => 'Wallis és Futuna',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe',
'CV' => 'Zöld-foki Köztársaság',
];
| akaunting/akaunting | resources/lang/hu-HU/countries.php | PHP | gpl-3.0 | 6,780 |
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7d23177b1abff1b80b9a2d6ffbc881f6562a2359/hapi/hapi.d.ts
declare module "hapi" {
import http = require("http");
import stream = require("stream");
import Events = require("events");
import url = require("url");
interface IDictionary<T> {
[key: string]: T;
}
interface IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IThenable<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IThenable<U>;
}
interface IPromise<R> extends IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
}
export interface IHeaderOptions {
append?: boolean;
separator?: string;
override?: boolean;
duplicate?: boolean;
}
/** Boom Module for errors. https://github.com/hapijs/boom
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */
export interface IBoom extends Error {
/** if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** convenience bool indicating status code >= 500. */
isServer: boolean;
/** the error message. */
message: string;
/** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */
output: {
/** the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
/** an object containing any HTTP headers where each key is a header name and value is the header content. */
headers: IDictionary<string>;
/** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */
payload: {
/** the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** the error message derived from error.message. */
message: string;
};
};
/** reformat()rebuilds error.output using the other object properties. */
reformat(): void;
}
/** cache functionality via the "CatBox" module. */
export interface ICatBoxCacheOptions {
/** a prototype function or catbox engine object. */
engine: any;
/** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */
name?: string;
/** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
shared?: boolean;
}
/** Any connections configuration server defaults can be included to override and customize the individual connection. */
export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults {
/** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/
host?: string;
/** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/
address?: string;
/** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/
port?: string | number;
/** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/
uri?: string;
/** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/
listener?: any;
/** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/
autoListen?: boolean;
/** caching headers configuration: */
cache?: {
/** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */
statuses: number[];
};
/** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/
labels?: string | string[];
/** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */
tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object;
}
export interface IConnectionConfigurationServerDefaults {
/** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */
app?: any;
/** connection load limits configuration where: */
load?: {
/** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxHeapUsedBytes: number;
/** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxRssBytes: number;
/** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxEventLoopDelay: number;
};
/** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */
plugins?: any;
/** controls how incoming request URIs are matched against the routing table: */
router?: {
/** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */
isCaseSensitive: boolean;
/** removes trailing slashes on incoming paths. Defaults to false. */
stripTrailingSlash: boolean;
};
/** a route options object used to set the default configuration for every route. */
routes?: IRouteAdditionalConfigurationOptions;
state?: IServerState;
}
/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/
export interface IServerOptions {
/** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */
app?: any;
/** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned:
a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')).
a configuration object with the following options:
enginea prototype function or catbox engine object.
namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well.
sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false.
other options passed to the catbox strategy used.
an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */
cache?: string | ICatBoxCacheOptions | Array<ICatBoxCacheOptions> | any;
/** sets the default connections configuration which can be overridden by each connection where: */
connections?: IConnectionConfigurationServerDefaults;
/** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/
debug?: boolean | {
/** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */
log: string[];
/** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/
request: string[];
};
/** file system related settings*/
files?: {
/** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/
etagsCacheMaxSize?: number;
};
/** process load monitoring*/
load?: {
/** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/
sampleInterval?: number;
};
/** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/
mime?: any;
/** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */
minimal?: boolean;
/** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/
plugins?: IDictionary<any>;
}
export interface IServerViewCompile {
(template: string, options: any): void;
(template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void;
}
export interface IServerViewsAdditionalOptions {
/** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/
path?: string;
/**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path).
*/
partialsPath?: string;
/**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/
helpersPath?: string;
/**relativeTo - a base path used as prefix for path and partialsPath.No default.*/
relativeTo?: string;
/**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/
layout?: boolean | string;
/**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/
layoutPath?: string;
/**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/
layoutKeywork?: string;
/**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/
encoding?: string;
/**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/
isCached?: boolean;
/**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/
allowAbsolutePaths?: boolean;
/**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/
allowInsecureAccess?: boolean;
/**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/
compileOptions?: any;
/**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/
runtimeOptions?: any;
/**contentType - the content type of the engine results.Defaults to 'text/html'.*/
contentType?: string;
/**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/
compileMode?: string;
/**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/
context?: any;
}
export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions {
/**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings.
* If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/
module: {
compile?(template: any, options: any): (context: any, options: any) => void;
compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void;
};
}
/**Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.
*/
export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions {
/** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/
engines: IDictionary<any> | IServerViewsEnginesOptions;
/** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/
defaultExtension?: string;
}
interface IReplyMethods {
/** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200.
* The data argument is only used for passing back authentication data and is ignored elsewhere. */
continue(credentialData?: any): void;
/** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */
file(/** the file path. */
path: string,
/** optional settings: */
options?: {
/** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string;
/** specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */
lookupCompressed: boolean;
}): void;
/** Concludes the handler activity by returning control over to the router with a templatized view response.
the response flow control rules apply. */
view(/** the template filename and path, relative to the templates path configured via the server views manager. */
template: string,
/** optional object used by the template to render context-specific result. Defaults to no context {}. */
context?: {},
/** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */
options?: any): Response;
/** Sets a header on the response */
header(name: string, value: string, options?: IHeaderOptions): Response;
/** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed
The response flow control rules do not apply. */
close(options?: {
/** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */
end?: boolean;
}): void;
/** Proxies the request to an upstream endpoint.
the response flow control rules do not apply. */
proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */
options: IProxyHandlerConfig): void;
/** Redirects the client to the specified uri. Same as calling reply().redirect(uri).
he response flow control rules apply. */
redirect(uri: string): ResponseRedirect;
/** Replies with the specified response */
response(result: any): Response;
/** Sets a cookie on the response */
state(name: string, value: any, options?: any): void;
/** Clears a cookie on the response */
unstate(name: string, options?: any): void;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IReply extends IReplyMethods {
<T>(err: Error,
result?: string | number | boolean | Buffer | stream.Stream | IPromise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
<T>(result: string | number | boolean | Buffer | stream.Stream | IPromise<T> | T): Response;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IStrictReply<T> extends IReplyMethods {
(err: Error,
result?: IPromise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
(result: IPromise<T> | T): Response;
}
export interface ISessionHandler {
(request: Request, reply: IReply): void;
<T>(request: Request, reply: IStrictReply<T>): void;
}
export interface IRequestHandler<T> {
(request: Request): T;
}
export interface IFailAction {
(source: string, error: any, next: () => void): void
}
/** generates a reverse proxy handler */
export interface IProxyHandlerConfig {
/** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/
host?: string;
/** the upstream service port. */
port?: number;
/** The protocol to use when making a request to the proxied host:
'http'
'https'*/
protocol?: string;
/** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/
uri?: string;
/** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/
passThrough?: boolean;
/** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/
localStatePassThrough?: boolean;
/**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/
acceptEncoding?: boolean;
/** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/
rejectUnauthorized?: boolean;
/**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/
xforward?: boolean;
/** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/
redirects?: boolean | number;
/**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/
timeout?: number;
/** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where:
request - is the incoming request object.
callback - is function(err, uri, headers) where:
err - internal error condition.
uri - the absolute proxy URI.
headers - optional object where each key is an HTTP request header and the value is the header content.*/
mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void;
/** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/
onResponse?: (err: any,
res: http.ServerResponse,
req: Request,
reply: IReply,
settings: IProxyHandlerConfig,
ttl: number) => void;
/** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/
ttl?: number;
/** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */
agent?: http.Agent;
/** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/
maxSockets?: boolean | number;
}
/** TODO: fill in joi definition */
export interface IJoi {
}
/** a validation function using the signature function(value, options, next) */
export interface IValidationFunction {
(/** the object containing the path parameters. */
value: any,
/** the server validation options. */
options: any,
/** the callback function called when validation is completed. */
next: (err: any, value: any) => void): void;
}
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
export interface IRouteFailFunction {
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
(/** - the [request object]. */
request: Request,
/** the continuation reply interface. */
reply: IReply,
/** the source of the invalid field (e.g. 'path', 'query', 'payload'). */
source: string,
/** the error object prepared for the client response (including the validation function error under error.data). */
error: any): void;
}
/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */
export interface IRouteAdditionalConfigurationOptions {
/** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */
app?: any;
/** authentication configuration.Value can be: false to disable authentication if a default strategy is set.
a string with the name of an authentication strategy registered with server.auth.strategy().
an object */
auth?: boolean | string |
{
/** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values:
'required'authentication is required.
'optional'authentication is optional (must be valid if present).
'try'same as 'optional' but allows for invalid authentication. */
mode?: string;
/** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */
strategies?: string | Array<string>;
/** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values:
falseno payload authentication.This is the default value.
'required'payload authentication required.This is the default value when the scheme sets options.payload to true.
'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */
payload?: string;
/** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */
scope?: string | Array<string> | boolean;
/** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values:
anythe authentication can be on behalf of a user or application.This is the default value.
userthe authentication must be on behalf of a user.
appthe authentication must be on behalf of an application. */
entity?: string;
/**
* an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming
* request and access is granted if at least one rule matches. Each rule object must include at least one of:
*/
access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[];
};
/** an object passed back to the provided handler (via this) when called. */
bind?: any;
/** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */
cache?: {
/** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are:
fault'no privacy flag.This is the default setting.
'public'mark the response as suitable for public caching.
'private'mark the response as suitable only for private caching. */
privacy: string;
/** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */
expiresIn: number;
/** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */
expiresAt: string;
};
/** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */
cors?: {
/** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */
origin?: Array<string>;
/** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */
matchOrigin?: boolean;
/** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */
isOriginExposed?: boolean;
/** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */
maxAge?: number;
/** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */
headers?: string[];
/** a strings array of additional headers to headers.Use this to keep the default headers in place. */
additionalHeaders?: string[];
/** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */
methods?: string[];
/** a strings array of additional methods to methods.Use this to keep the default methods in place. */
additionalMethods?: string[];
/** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */
exposedHeaders?: string[];
/** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */
additionalExposedHeaders?: string[];
/** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */
credentials?: boolean;
/** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */
override?: boolean;
};
/** defines the behavior for serving static resources using the built-in route handlers for files and directories: */
files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */
relativeTo: string;
};
/** an alternative location for the route handler option. */
handler?: ISessionHandler | string | IRouteHandlerConfig;
/** an optional unique identifier used to look up the route using server.lookup(). */
id?: number;
/** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */
json?: {
/** the replacer function or array.Defaults to no action. */
replacer?: Function | string[];
/** number of spaces to indent nested object keys.Defaults to no indentation. */
space?: number | string;
/** string suffix added after conversion to JSON string.Defaults to no suffix. */
suffix?: string;
};
/** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */
jsonp?: string;
/** determines how the request payload is processed: */
payload?: {
/** the type of payload representation requested. The value must be one of:
'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used.
'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.
'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */
output?: string;
/** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are:
'application/json'
'application/x-www-form-urlencoded'
'application/octet-stream'
'text/ *'
'multipart/form-data' */
parse?: string | boolean;
/** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */
allow?: string | string[];
/** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */
override?: string;
/** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */
maxBytes?: number;
/** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */
timeout?: number;
/** the directory used for writing file uploads.Defaults to os.tmpDir(). */
uploads?: string;
/** determines how to handle payload parsing errors. Allowed values are:
'error'return a Bad Request (400) error response. This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action and continue processing the request. */
failAction?: string;
};
/** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */
plugins?: IDictionary<any>;
/** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */
pre?: any[];
/** validation rules for the outgoing response payload (response body).Can only validate object response: */
response?: {
/** the default HTTP status code when the payload is empty. Value can be 200 or 204.
Note that a 200 status code is converted to a 204 only at the time or response transmission
(the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */
emptyStatusCode?: number;
/** the default response object validation rules (for all non-error responses) expressed as one of:
true - any payload allowed (no validation performed). This is the default.
false - no payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
value - the object containing the response object.
options - the server validation options.
next(err) - the callback function called when validation is completed. */
schema?: boolean | any;
/** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */
status?: { [statusCode: number]: boolean | any };
/** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */
sample?: number;
/** defines what to do when a response fails validation.Options are:
errorreturn an Internal Server Error (500) error response.This is the default value.
loglog the error but send the response. */
failAction?: string;
/** if true, applies the validation rule changes to the response.Defaults to false. */
modify?: boolean;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options?: any;
};
/** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */
security?: boolean | {
/** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */
hsts?: boolean | number | {
/** the max- age portion of the header, as a number.Default is 15768000. */
maxAge?: number;
/** a boolean specifying whether to add the includeSubdomains flag to the header. */
includeSubdomains?: boolean;
/** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */
preload?: boolean;
};
/** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */
xframe?: {
/** either 'deny', 'sameorigin', or 'allow-from' */
rule: string;
/** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */
source: string;
};
/** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */
xss?: boolean;
/** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */
noOpen?: boolean;
/** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */
noSniff?: boolean;
};
/** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */
state?: {
/** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */
parse: boolean;
/** determines how to handle cookie parsing errors.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action. */
failAction: string;
};
/** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */
validate?: {
/** validation rules for incoming request headers.Values allowed:
* trueany headers allowed (no validation performed).This is the default.
falseno headers allowed (this will cause all valid HTTP requests to fail).
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the request headers.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed.
*/
headers?: boolean | IJoi | IValidationFunction;
/** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed:
trueany path parameters allowed (no validation performed).This is the default.
falseno path variables allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the path parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
params?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed:
trueany query parameters allowed (no validation performed).This is the default.
falseno query parameters allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the query parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
query?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request payload (request body).Values allowed:
trueany payload allowed (no validation performed).This is the default.
falseno payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the payload object.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
payload?: boolean | IJoi | IValidationFunction;
/** an optional object with error fields copied into every validation error response. */
errorFields?: any;
/** determines how to handle invalid requests.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'log the error but continue processing the request.
'ignore'take no action.
OR a custom error handler function with the signature 'function(request, reply, source, error)` where:
requestthe request object.
replythe continuation reply interface.
sourcethe source of the invalid field (e.g. 'path', 'query', 'payload').
errorthe error object prepared for the client response (including the validation function error under error.data). */
failAction?: string | IRouteFailFunction;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options?: any;
};
/** define timeouts for processing durations: */
timeout?: {
/** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */
server: boolean | number;
/** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */
socket: boolean | number;
};
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route description used for generating documentation (string).
*/
description?: string;
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route notes used for generating documentation (string or array of strings).
*/
notes?: string | string[];
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route tags used for generating documentation (array of strings).
*/
tags?: string[]
}
/**
* specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches
*/
export interface IRouteAdditionalConfigurationAuthAccess {
/**
* the application scope required to access the route. Value can be a scope string or an array of scope strings.
* The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.
* If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character,
* that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials'
* scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties
* on the request object (query and params} to populate a dynamic scope by using {} characters around the property name,
* such as 'user-{params.id}'. Defaults to false (no scope requirements).
*/
scope?: string | Array<string> | boolean;
/** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values:
* any - the authentication can be on behalf of a user or application. This is the default value.
* user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy.
* app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy.
*/
entity?: string;
}
/** server.realm http://hapijs.com/api#serverrealm
The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(),
the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin).
Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties.
The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]).
exports.register = function (server, options, next) {
console.log(server.realm.modifiers.route.prefix);
return next();
};
*/
export interface IServerRealm {
/** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */
modifiers: {
/** routes preferences: */
route: {
/** - the route path prefix used by any calls to server.route() from the server. */
prefix: string;
/** the route virtual host settings used by any calls to server.route() from the server. */
vhost: string;
};
};
/** the active plugin name (empty string if at the server root). */
plugin: string;
/** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */
plugins: IDictionary<any>;
/** settings overrides */
settings: {
files: {
relativeTo: any;
};
bind: any;
}
}
/** server.state(name, [options]) http://hapijs.com/api#serverstatename-options
HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/
export interface IServerState {
/** - the cookie name string. */name: string;
/** - are the optional cookie settings: */options: {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number;
/** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean;
/** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean
/** - the path scope.Defaults to null (no path).*/path: any;
/** - the domain scope.Defaults to null (no domain). */domain: any;
/** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue: (request: Request, next: (err: any, value: any) => void) => void;
/** - encoding performs on the provided value before serialization. Options are:
'none' - no encoding. When used, the cookie value must be a string. This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON-stringified than encoded using Base64.
'form' - object value is encoded using the x-www-form-urlencoded method.
'iron' - Encrypts and sign the value using iron.*/
encoding: string;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: {
/** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any;
/** - password used for HMAC key generation.*/password: string;
};
/** - password used for 'iron' encoding.*/password: string;
/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any;
/** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean;
/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean;
/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean;
/** - overrides the default proxy localStatePassThrough setting.*/passThrough: any;
};
}
export interface IFileHandlerConfig {
/** a path string or function as described above.*/
path: string;
/** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string;
/**- specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/
lookupCompressed: boolean;
}
/**http://hapijs.com/api#route-handler
Built-in handlers
The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/
export interface IRouteHandlerConfig {
/** generates a static file endpoint for serving a single file. file can be set to:
a relative or absolute file path string (relative paths are resolved based on the route files configuration).
a function with the signature function(request) which returns the relative or absolute file path.
an object with the following options */
file?: string | IRequestHandler<void> | IFileHandlerConfig;
/** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options:
path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be:
a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string.
an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string).
a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response.
index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true.
listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false.
showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false.
redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false.
lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.
defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/
directory?: {
path: string | Array<string> | IRequestHandler<string> | IRequestHandler<Array<string>>;
index?: boolean | string | string[];
listing?: boolean;
showHidden?: boolean;
redirectToSlash?: boolean;
lookupCompressed?: boolean;
defaultExtension?: string;
};
proxy?: IProxyHandlerConfig;
view?: string | {
template: string;
context: {
payload: any;
params: any;
query: any;
pre: any;
}
};
config?: {
handler: any;
bind: any;
app: any;
plugins: {
[name: string]: any;
};
pre: Array<() => void>;
validate: {
headers: any;
params: any;
query: any;
payload: any;
errorFields?: any;
failAction?: string | IFailAction;
};
payload: {
output: {
data: any;
stream: any;
file: any;
};
parse?: any;
allow?: string | Array<string>;
override?: string;
maxBytes?: number;
uploads?: number;
failAction?: string;
};
response: {
schema: any;
sample: number;
failAction: string;
};
cache: {
privacy: string;
expiresIn: number;
expiresAt: number;
};
auth: string | boolean | {
mode: string;
strategies: Array<string>;
payload?: boolean | string;
tos?: boolean | string;
scope?: string | Array<string>;
entity: string;
};
cors?: boolean;
jsonp?: string;
description?: string;
notes?: string | Array<string>;
tags?: Array<string>;
};
}
/** Route configuration
The route configuration object*/
export interface IRouteConfiguration {
/** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/
path: string;
/** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match).
* Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/
method: string | string[];
/** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/
vhost?: string;
/** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/
handler?: ISessionHandler | string | IRouteHandlerConfig;
/** - additional route options.*/
config?: IRouteAdditionalConfigurationOptions;
}
/** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */
export interface IRoute {
/** the route HTTP method. */
method: string;
/** the route path. */
path: string;
/** the route vhost option if configured. */
vhost?: string | Array<string>;
/** the [active realm] associated with the route.*/
realm: IServerRealm;
/** the [route options] object with all defaults applied. */
settings: IRouteAdditionalConfigurationOptions;
}
export interface IServerAuthScheme {
/** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where:
request - the request object.
reply - the reply interface the authentication method must call when done authenticating the request where:
reply(err, response, result) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
result - an object containing:
credentials - the authenticated credentials.
artifacts - optional authentication artifacts.
reply.continue(result) - is called if authentication succeeded where:
result - same object as result above.
When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route.
.If the err returned by the reply() method includes a message, no additional strategies will be attempted.
If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
var server = new Hapi.Server();
server.connection({ port: 80 });
var scheme = function (server, options) {
return {
authenticate: function (request, reply) {
var req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply(null, { credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);*/
authenticate(request: Request, reply: IReply): void;
authenticate<T>(request: Request, reply: IStrictReply<T>): void;
/** payload(request, reply) - optional function called to authenticate the request payload where:
request - the request object.
reply(err, response) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
reply.continue() - is called if payload authentication succeeded.
When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/
payload?(request: Request, reply: IReply): void;
payload?<T>(request: Request, reply: IStrictReply<T>): void;
/** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where:
request - the request object.
reply(err, response) - is called if an error occurred where:
err - any authentication error.
response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required.
reply.continue() - is called if the operation succeeded.*/
response?(request: Request, reply: IReply): void;
response?<T>(request: Request, reply: IStrictReply<T>): void;
/** an optional object */
options?: {
/** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/
payload: boolean;
}
}
/**the response object where:
statusCode - the HTTP status code.
headers - an object containing the headers set.
payload - the response payload string.
rawPayload - the raw response payload buffer.
raw - an object with the injection request and response objects:
req - the simulated node request object.
res - the simulated node response object.
result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string).
request - the request object.*/
export interface IServerInjectResponse {
statusCode: number;
headers: IDictionary<string>;
payload: string;
rawPayload: Buffer;
raw: {
req: http.IncomingMessage;
res: http.ServerResponse
};
result: string;
request: Request;
}
export interface IServerInject {
(options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void;
(options: string | IServerInjectOptions): IPromise<IServerInjectResponse>;
}
export interface IServerInjectOptions {
/** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/
method: string;
/** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/
url: string;
/** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/
headers?: IDictionary<string>;
/** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/
payload?: string | {} | Buffer;
/** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/
credentials?: any;
/** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/
artifacts?: any;
/** sets the initial value of request.app*/
app?: any;
/** sets the initial value of request.plugins*/
plugins?: any;
/** allows access to routes with config.isInternal set to true. Defaults to false.*/
allowInternals?: boolean;
/** sets the remote address for the incoming connection.*/
remoteAddress?: boolean;
/**object with options used to simulate client request stream conditions for testing:
error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
end - if false, does not end the stream. Defaults to true.*/
simulate?: {
error: boolean;
close: boolean;
end: boolean;
};
}
/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.*/
export interface IConnectionTable {
info: any;
labels: any;
table: IRoute[];
}
export interface ICookieSettings {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/
ttl?: number;
/** - sets the 'Secure' flag.Defaults to false.*/
isSecure?: boolean;
/** - sets the 'HttpOnly' flag.Defaults to false.*/
isHttpOnly?: boolean;
/** - the path scope.Defaults to null (no path).*/
path?: string;
/** - the domain scope.Defaults to null (no domain).*/
domain?: any;
/** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue?: (request: Request, next: (err: any, value: any) => void) => void;
/** - encoding performs on the provided value before serialization.Options are:
'none' - no encoding.When used, the cookie value must be a string.This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON- stringified than encoded using Base64.
'form' - object value is encoded using the x- www - form - urlencoded method. */
encoding?: string;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:
integrity - algorithm options.Defaults to require('iron').defaults.integrity.
password - password used for HMAC key generation. */
sign?: { integrity: any; password: string; }
password?: string;
iron?: any;
ignoreErrors?: boolean;
clearInvalid?: boolean;
strictHeader?: boolean;
passThrough?: any;
}
/** method - the method function with the signature is one of:
function(arg1, arg2, ..., argn, next) where:
arg1, arg2, etc. - the method function arguments.
next - the function called when the method is done with the signature function(err, result, ttl) where:
err - error response if the method failed.
result - the return value.
ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
function(arg1, arg2, ..., argn) where:
arg1, arg2, etc. - the method function arguments.
the callback option is set to false.
the method must returns a value (result, Error, or a promise) or throw an Error.*/
export interface IServerMethod {
//(): void;
//(next: (err: any, result: any, ttl: number) => void): void;
//(arg1: any): void;
//(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void;
//(arg1: any, arg2: any): void;
(...args: any[]): void;
}
/** options - optional configuration:
bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered.
cache - the same cache configuration used in server.cache().
callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true.
generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/
export interface IServerMethodOptions {
bind?: any;
cache?: ICatBoxCacheOptions;
callback?: boolean;
generateKey?(args: any[]): string;
}
/** Request object
The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle.
Request events
The request object supports the following events:
'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the request payload finished reading. The event method signature is function ().
'disconnect' - emitted when a request errors or aborts unexpectedly.
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
var hash = Crypto.createHash('sha1');
request.on('peek', function (chunk) {
hash.update(chunk);
});
request.once('finish', function () {
console.log(hash.digest('hex'));
});
request.once('disconnect', function () {
console.error('request aborted');
});
return reply.continue();
});*/
export class Request extends Events.EventEmitter {
/** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** authentication information*/
auth: {
/** true is the request has been successfully authenticated, otherwise false.*/
isAuthenticated: boolean;
/** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/
credentials: any;
/** an artifact object received from the authentication strategy and used in authentication-related actions.*/
artifacts: any;
/** the route authentication mode.*/
mode: any;
/** the authentication error is failed and mode set to 'try'.*/
error: any;
};
/** the connection used by this request*/
connection: ServerConnection;
/** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/
domain: any;
/** the raw request headers (references request.raw.headers).*/
headers: IDictionary<string>;
/** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/
id: number;
/** request information */
info: {
/** the request preferred encoding. */
acceptEncoding: string;
/** if CORS is enabled for the route, contains the following: */
cors: {
isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */
};
/** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
host: string;
/** the hostname part of the 'Host' header (e.g. 'example.com').*/
hostname: string;
/** request reception timestamp. */
received: number;
/** content of the HTTP 'Referrer' (or 'Referer') header. */
referrer: string;
/** remote client IP address. */
remoteAddress: string;
/** remote client port. */
remotePort: number;
/** request response timestamp (0 is not responded yet). */
responded: number;
};
/** the request method in lower case (e.g. 'get', 'post'). */
method: string;
/** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */
mime: string;
/** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/
orig: {
params: any;
query: any;
payload: any;
};
/** an object where each key is a path parameter name with matching value as described in Path parameters.*/
params: IDictionary<string>;
/** an array containing all the path params values in the order they appeared in the path.*/
paramsArray: string[];
/** the request URI's path component. */
path: string;
/** the request payload based on the route payload.output and payload.parse settings.*/
payload: stream.Readable | Buffer | any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/
plugins: any;
/** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/
pre: IDictionary<any>;
/** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/
response: Response;
/**preResponses - same as pre but represented as the response object created by the pre method.*/
preResponses: any;
/**an object containing the query parameters.*/
query: any;
/** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/
raw: {
req: http.IncomingMessage;
res: http.ServerResponse;
};
/** the route public interface.*/
route: IRoute;
/** the server object. */
server: Server;
/** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */
state: any;
/** complex object contining details on the url */
url: {
/** null when i tested */
auth: any;
/** null when i tested */
hash: any;
/** null when i tested */
host: any;
/** null when i tested */
hostname: any;
href: string;
path: string;
/** path without search*/
pathname: string;
/** null when i tested */
port: any;
/** null when i tested */
protocol: any;
/** querystring parameters*/
query: IDictionary<string>;
/** querystring parameters as a string*/
search: string;
/** null when i tested */
slashes: any;
};
/** request.setUrl(url)
Available only in 'onRequest' extension methods.
Changes the request URI before the router begins processing the request where:
url - the new request path value.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});*/
setUrl(url: string | url.Url): void;
/** request.setMethod(method)
Available only in 'onRequest' extension methods.
Changes the request method before the router begins processing the request where:
method - is the request HTTP method (e.g. 'GET').
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to 'GET'
request.setMethod('GET');
return reply.continue();
});*/
setMethod(method: string): void;
/** request.log(tags, [data, [timestamp]])
Always available.
Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request', function (request, event, tags) {
if (tags.error) {
console.log(event);
}
});
var handler = function (request, reply) {
request.log(['test', 'error'], 'Test event');
return reply();
};
*/
log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/
tags: string | string[],
/** an optional message string or object with the application data being logged.*/
data?: any,
/** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/
timestamp?: number): void;
/** request.getLog([tags], [internal])
Always available.
Returns an array containing the events matching any of the tags specified (logical OR)
request.getLog();
request.getLog('error');
request.getLog(['error', 'auth']);
request.getLog(['error'], true);
request.getLog(false);*/
getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/
tags?: string,
/** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/
internal?: boolean): string[];
/** request.tail([name])
Available until immediately after the 'response' event is emitted.
Adds a request tail which has to complete before the request lifecycle is complete where:
name - an optional tail name used for logging purposes.
Returns a tail function which must be called when the tail activity is completed.
Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it).
When all tails completed, the server emits a 'tail' event.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
var get = function (request, reply) {
var dbTail = request.tail('write to database');
db.save('key', 'value', function () {
dbTail();
});
return reply('Success!');
};
server.route({ method: 'GET', path: '/', handler: get });
server.on('tail', function (request) {
console.log('Request completed including db activity');
});*/
tail(/** an optional tail name used for logging purposes.*/
name?: string): Function;
}
/** Response events
The response object supports the following events:
'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onPreResponse', function (request, reply) {
var response = request.response;
if (response.isBoom) {
return reply();
}
var hash = Crypto.createHash('sha1');
response.on('peek', function (chunk) {
hash.update(chunk);
});
response.once('finish', function () {
console.log(hash.digest('hex'));
});
return reply.continue();
});*/
export class Response extends Events.EventEmitter {
isBoom: boolean;
/** the HTTP response status code. Defaults to 200 (except for errors).*/
statusCode: number;
/** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/
headers: IDictionary<string>;
/** the value provided using the reply interface.*/
source: any;
/** a string indicating the type of source with available values:
'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view).
'buffer' - a Buffer.
'view' - a view generated with reply.view().
'file' - a file generated with reply.file() of via the directory handler.
'stream' - a Stream.
'promise' - a Promise object. */
variety: string;
/** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */
plugins: any;
/** settings - response handling flags:
charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'.
encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'.
passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true.
stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding.
ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override.
varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/
settings: {
charset: string;
encoding: string;
passThrough: boolean;
stringify: any;
ttl: number;
varyEtag: boolean;
}
/** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
length - the header value. Must match the actual payload size.*/
bytes(length: number): Response;
/** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/
charset(charset: string): Response;
/** sets the HTTP status code where:
statusCode - the HTTP status code.*/
code(statusCode: number): Response;
/** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/
created(uri: string): Response;
/** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/
encoding(encoding: string): Response;
/** etag(tag, options) - sets the representation entity tag where:
tag - the entity tag string without the double-quote.
options - optional settings where:
weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false.
vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/
etag(tag: string, options: {
weak: boolean; vary: boolean;
}): Response;
/**header(name, value, options) - sets an HTTP header where:
name - the header name.
value - the header value.
options - optional settings where:
append - if true, the value is appended to any existing header value using separator. Defaults to false.
separator - string used as separator when appending to an exiting value. Defaults to ','.
override - if false, the header value is not set if an existing value present. Defaults to true.*/
header(name: string, value: string, options?: IHeaderOptions): Response;
/** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */
hold(): Response;
/** location(uri) - sets the HTTP 'Location' header where:
uri - an absolute or relative URI used as the 'Location' header value.*/
location(uri: string): Response;
/** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where:
uri - an absolute or relative URI used to redirect the client to another resource. */
redirect(uri: string): Response;
/** replacer(method) - sets the JSON.stringify() replacer argument where:
method - the replacer function or array. Defaults to none.*/
replacer(method: Function | Array<Function>): Response;
/** spaces(count) - sets the JSON.stringify() space argument where:
count - the number of spaces to indent nested object keys. Defaults to no indentation. */
spaces(count: number): Response;
/**state(name, value, [options]) - sets an HTTP cookie where:
name - the cookie name.
value - the cookie value. If no encoding is defined, must be a string.
options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
state(name: string, value: string, options?: any): Response;
/** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */
send(): void;
/** sets a string suffix when the response is process via JSON.stringify().*/
suffix(suffix: string): void;
/** overrides the default route cache expiration rule for this response instance where:
msec - the time-to-live value in milliseconds.*/
ttl(msec: number): void;
/** type(mimeType) - sets the HTTP 'Content-Type' header where:
mimeType - is the mime type. Should only be used to override the built-in default for each response type. */
type(mimeType: string): Response;
/** clears the HTTP cookie by setting an expired value where:
name - the cookie name.
options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
unstate(name: string, options?: { [key: string]: string }): Response;
/** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
header - the HTTP request header name.*/
vary(header: string): void;
}
/** When using the redirect() method, the response object provides these additional methods */
export class ResponseRedirect extends Response {
/** sets the status code to 302 or 307 (based on the rewritable() setting) where:
isTemporary - if false, sets status to permanent. Defaults to true.*/
temporary(isTemporary: boolean): void;
/** sets the status code to 301 or 308 (based on the rewritable() setting) where:
isPermanent - if true, sets status to temporary. Defaults to false. */
permanent(isPermanent: boolean): void;
/** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments:
isRewritable - if false, sets to non-rewritable. Defaults to true.
Permanent Temporary
Rewritable 301 302(1)
Non-rewritable 308(2) 307
Notes: 1. Default value. 2. Proposed code, not supported by all clients. */
rewritable(isRewritable: boolean): void;
}
/** info about a server connection */
export interface IServerConnectionInfo {
/** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/
id: string;
/** - the connection creation timestamp.*/
created: number;
/** - the connection start timestamp (0 when stopped).*/
started: number;
/** the connection port based on the following rules:
the configured port value before the server has been started.
the actual port assigned when no port is configured or set to 0 after the server has been started.*/
port: number;
/** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/
host: string;
/** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/
address: string;
/** - the protocol used:
'http' - HTTP.
'https' - HTTPS.
'socket' - UNIX domain socket or Windows named pipe.*/
protocol: string;
/** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/
uri: string;
}
/**
* undocumented. The connection object constructed after calling server.connection();
* can be accessed via server.connections; or request.connection;
*/
export class ServerConnection extends Events.EventEmitter {
domain: any;
_events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function };
_eventsCount: number;
settings: IServerConnectionOptions;
server: Server;
/** ex: "tcp" */
type: string;
_started: boolean;
/** dictionary of sockets */
_connections: { [ip_port: string]: any };
_onConnection: Function;
registrations: any;
_extensions: any;
_requestCounter: { value: number; min: number; max: number };
_load: any;
states: {
settings: any; cookies: any; names: any[]
};
auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; };
_router: any;
MSPluginsCollection: any;
applicationCache: any;
addEventListener: any;
info: IServerConnectionInfo;
}
type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse";
type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop";
/** Server http://hapijs.com/api#server
rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080).
Server events
The server object inherits from Events.EventEmitter and emits the following events:
'log' - events logged with server.log() and server events generated internally by the framework.
'start' - emitted when the server is started using server.start().
'stop' - emitted when the server is stopped using server.stop().
'request' - events generated by request.log(). Does not include any internally generated events.
'request-internal' - request events generated internally by the framework (multiple events per request).
'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request.
'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request.
'tail' - emitted when a request finished processing, including any registered tails. Single event per request.
Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events.
MORE EVENTS HERE: http://hapijs.com/api#server-events*/
export class Server extends Events.EventEmitter {
constructor(options?: IServerOptions);
/** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object.
var Hapi = require('hapi');
server = new Hapi.Server();
server.app.key = 'value';
var handler = function (request, reply) {
return reply(request.server.app.key);
}; */
app: any;
/** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria.
var server = new Hapi.Server();
server.connection({ port: 80, labels: 'a' });
server.connection({ port: 8080, labels: 'b' });
// server.connections.length === 2
var a = server.select('a');
// a.connections.length === 1*/
connections: Array<ServerConnection>;
/** When the server contains exactly one connection, info is an object containing information about the sole connection.
* When the server contains more than one connection, each server.connections array member provides its own connection.info.
var server = new Hapi.Server();
server.connection({ port: 80 });
// server.info.port === 80
server.connection({ port: 8080 });
// server.info === null
// server.connections[1].info.port === 8080
*/
info: IServerConnectionInfo;
/** An object containing the process load metrics (when load.sampleInterval is enabled):
rss - RSS memory usage.
var Hapi = require('hapi');
var server = new Hapi.Server({ load: { sampleInterval: 1000 } });
console.log(server.load.rss);*/
load: {
/** - event loop delay milliseconds.*/
eventLoopDelay: number;
/** - V8 heap usage.*/
heapUsed: number;
};
/** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection.
When the server contains more than one connection, each server.connections array member provides its own connection.listener.
var Hapi = require('hapi');
var SocketIO = require('socket.io');
var server = new Hapi.Server();
server.connection({ port: 80 });
var io = SocketIO.listen(server.listener);
io.sockets.on('connection', function(socket) {
socket.emit({ msg: 'welcome' });
});*/
listener: http.Server;
/** server.methods
An object providing access to the server methods where each server method name is an object property.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.method('add', function (a, b, next) {
return next(null, a + b);
});
server.methods.add(1, 2, function (err, result) {
// result === 3
});*/
methods: IDictionary<Function>;
/** server.mime
Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting.
var Hapi = require('hapi');
var options = {
mime: {
override: {
'node/module': {
source: 'steve',
compressible: false,
extensions: ['node', 'module', 'npm'],
type: 'node/module'
}
}
}
};
var server = new Hapi.Server(options);
// server.mime.path('code.js').type === 'application/javascript'
// server.mime.path('file.npm').type === 'node/module'*/
mime: any;
/**server.plugins
An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method.
exports.register = function (server, options, next) {
server.expose('key', 'value');
// server.plugins.example.key === 'value'
return next();
};
exports.register.attributes = {
name: 'example'
};*/
plugins: IDictionary<any>;
/** server.realm
The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties.
modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes:
route - routes preferences:
prefix - the route path prefix used by any calls to server.route() from the server.
vhost - the route virtual host settings used by any calls to server.route() from the server.
plugin - the active plugin name (empty string if at the server root).
plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state.
settings - settings overrides:
files.relativeTo
bind
The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]).
exports.register = function (server, options, next) {
console.log(server.realm.modifiers.route.prefix);
return next();
};*/
realm: IServerRealm;
/** server.root
The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/
root: Server;
/** server.settings
The server configuration object after defaults applied.
var Hapi = require('hapi');
var server = new Hapi.Server({
app: {
key: 'value'
}
});
// server.settings.app === { key: 'value' }*/
settings: IServerOptions;
/** server.version
The hapi module version number.
var Hapi = require('hapi');
var server = new Hapi.Server();
// server.version === '8.0.0'*/
version: string;
/** server.after(method, [dependencies])
Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where:
after - the method with signature function(plugin, next) where:
server - server object the after() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error which is returned back via the server.start() callback.
dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.after(function () {
// Perform some pre-start logic
});
server.start(function (err) {
// After method already executed
});
server.auth.default(options)*/
after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void;
auth: {
/** server.auth.api
An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function.
When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object.
const server = new Hapi.Server();
server.connection({ port: 80 });
const scheme = function (server, options) {
return {
api: {
settings: {
x: 5
}
},
authenticate: function (request, reply) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply.continue({ credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
console.log(server.auth.api.default.settings.x); // 5
*/
api: {
[index: string]: any;
}
/** server.auth.default(options)
Sets a default strategy which is applied to every route where:
options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options.
The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior.
The default auth strategy configuration can be accessed via connection.auth.settings.default.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.auth.default('default');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply(request.auth.credentials.user);
}
});*/
default(options: string): void;
default(options: { strategy: string }): void;
default(options: { strategies: string[] }): void;
/** server.auth.scheme(name, scheme)
Registers an authentication scheme where:
name - the scheme name.
scheme - the method implementing the scheme with signature function(server, options) where:
server - a reference to the server object the scheme is added to.
options - optional scheme settings used to instantiate a strategy.*/
scheme(name: string,
/** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.
server = new Hapi.Server();
server.connection({ port: 80 });
scheme = function (server, options) {
urn {
authenticate: function (request, reply) {
req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
urn reply(null, { credentials: { user: 'john' } });
}
};
};
*/
scheme: (server: Server, options: any) => IServerAuthScheme): void;
/** server.auth.strategy(name, scheme, [mode], [options])
Registers an authentication strategy where:
name - the strategy name.
scheme - the scheme name (must be previously registered using server.auth.scheme()).
mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
options - scheme options based on the scheme requirements.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
config: {
auth: 'default',
handler: function (request, reply) {
return reply(request.auth.credentials.user);
}
}
});*/
strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void;
/** server.auth.test(strategy, request, next)
Tests a request against an authentication strategy where:
strategy - the strategy name registered with server.auth.strategy().
request - the request object.
next - the callback function with signature function(err, credentials) where:
err - the error if authentication failed.
credentials - the authentication credentials object if authentication was successful.
Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
request.server.auth.test('default', request, function (err, credentials) {
if (err) {
return reply({ status: false });
}
return reply({ status: true, user: credentials.name });
});
}
});*/
test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void;
};
/** server.bind(context)
Sets a global context used as the default bind object when adding a route or an extension where:
context - the object used to bind this in handler and extension methods.
When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set.
var handler = function (request, reply) {
return reply(this.message);
};
exports.register = function (server, options, next) {
var bind = {
message: 'hello'
};
server.bind(bind);
server.route({ method: 'GET', path: '/', handler: handler });
return next();
};*/
bind(context: any): void;
/** server.cache(options)
Provisions a cache segment within the server cache facility where:
options - catbox policy configuration where:
expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn.
generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn.
staleTimeout - number of milliseconds to wait before checking if an item is stale.
generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests.
cache - the cache name configured in 'server.cache`. Defaults to the default cache.
segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin.
shared - if true, allows multiple cache provisions to share the same segment. Default to false.
var server = new Hapi.Server();
server.connection({ port: 80 });
var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 });
cache.set('norway', { capital: 'oslo' }, null, function (err) {
cache.get('norway', function (err, value, cached, log) {
// value === { capital: 'oslo' };
});
});*/
cache(options: ICatBoxCacheOptions): void;
/** server.connection([options])
Adds an incoming server connection
Returns a server object with the new connection selected.
Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()).
Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on.
var Hapi = require('hapi');
var server = new Hapi.Server();
var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] });
var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] });
// server.connections.length === 2
// web.connections.length === 1
// admin.connections.length === 1 */
connection(options: IServerConnectionOptions): Server;
/** server.decorate(type, property, method, [options])
Extends various framework interfaces with custom methods where:
type - the interface being decorated. Supported types:
'reply' - adds methods to the reply interface.
'server' - adds methods to the Server object.
property - the object decoration key name.
method - the extension function.
options - if the type is 'request', supports the following optional settings:
'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration.
Note that decorations apply to the entire server and all its connections regardless of current selection.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.decorate('reply', 'success', function () {
return this.response({ status: 'ok' });
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply.success();
}
});*/
decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void;
/** server.dependency(dependencies, [after])
Used within a plugin to declares a required dependency on other plugins where:
dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies.
after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where:
server - the server the dependency() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error condition, which is returned back via the server.start() callback.
exports.register = function (server, options, next) {
server.dependency('yar', after);
return next();
};
var after = function (server, next) {
// Additional plugin registration logic
return next();
};*/
dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void;
/** server.expose(key, value)
Used within a plugin to expose a property via server.plugins[name] where:
key - the key assigned (server.plugins[name][key]).
value - the value assigned.
exports.register = function (server, options, next) {
server.expose('util', function () { console.log('something'); });
return next();
};*/
expose(key: string, value: any): void;
/** server.expose(obj)
Merges a deep copy of an object into to the existing content of server.plugins[name] where:
obj - the object merged into the exposed properties container.
exports.register = function (server, options, next) {
server.expose({ util: function () { console.log('something'); } });
return next();
};*/
expose(obj: any): void;
/** server.ext(event, method, [options])
Registers an extension function in one of the available extension points where:
event - the event name.
method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where:
request - the request object. NOTE: Access the Response via request.response
reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response.
this - the object provided via options.bind or the current active context set with server.bind().
options - an optional object with the following:
before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
bind - a context object passed back to the provided method (via this) when called.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});
var handler = function (request, reply) {
return reply({ status: 'ok' });
};
server.route({ method: 'GET', path: '/test', handler: handler });
server.start();
// All requests will get routed to '/test'*/
ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext<T>(event: RequestExtPoints, method: (request: Request, reply: IStrictReply<T>, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
/** server.handler(name, method)
Registers a new handler type to be used in routes where:
name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type.
method - the function used to generate the route handler using the signature function(route, options) where:
route - the route public interface object.
options - the configuration object provided in the handler config.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
// Defines new handler for routes on this server
server.handler('test', function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
});
server.route({
method: 'GET',
path: '/',
handler: { test: { msg: 'test' } }
});
server.start();
The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
var handler = function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
};
// Change the default payload processing for this handler
handler.defaults = {
payload: {
output: 'stream',
parse: false
}
};
server.handler('test', handler);*/
handler<THandlerConfig>(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void;
/** server.initialize([callback])
Initializes the server (starts the caches, finalizes plugin registration) but does not start listening
on the connection ports, where:
- `callback` - the callback method when server initialization is completed or failed with the signature
`function(err)` where:
- `err` - any initialization error condition.
If no `callback` is provided, a `Promise` object is returned.
Note that if the method fails and the callback includes an error, the server is considered to be in
an undefined state and should be shut down. In most cases it would be impossible to fully recover as
the various plugins, caches, and other event listeners will get confused by repeated attempts to
start the server or make assumptions about the healthy state of the environment. It is recommended
to assert that no error has been returned after calling `initialize()` to abort the process when the
server fails to start properly. If you must try to resume after an error, call `server.stop()`
first to reset the server state.
*/
initialize(callback?: (error: any) => void): IPromise<void>;
/** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection.
Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack.
Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties
* When the server contains more than one connection, each server.connections array member provides its own connection.inject().
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
var handler = function (request, reply) {
return reply('Success!');
};
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
console.log(res.result);
});
*/
inject: IServerInject;
/** server.log(tags, [data, [timestamp]])
Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are:
tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('log', function (event, tags) {
if (tags.error) {
console.log(event);
}
});
server.log(['test', 'error'], 'Test event');*/
log(tags: string | string[], data?: string | any, timestamp?: number): void;
/**server.lookup(id)
When the server contains exactly one connection, looks up a route configuration where:
id - the route identifier as set in the route options.
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.lookup('root');
When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/
lookup(id: string): IRoute;
/** server.match(method, path, [host])
When the server contains exactly one connection, looks up a route configuration where:
method - the HTTP method (e.g. 'GET', 'POST').
path - the requested path (must begin with '/').
host - optional hostname (to match against routes with vhost).
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.match('get', '/');
When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/
match(method: string, path: string, host?: string): IRoute;
/** server.method(name, method, [options])
Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module.
Methods are registered via server.method(name, method, [options])
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Simple arguments
var add = function (a, b, next) {
return next(null, a + b);
};
server.method('sum', add, { cache: { expiresIn: 2000 } });
server.methods.sum(4, 5, function (err, result) {
console.log(result);
});
// Object argument
var addArray = function (array, next) {
var sum = 0;
array.forEach(function (item) {
sum += item;
});
return next(null, sum);
};
server.method('sumObj', addArray, {
cache: { expiresIn: 2000 },
generateKey: function (array) {
return array.join(',');
}
});
server.methods.sumObj([5, 6], function (err, result) {
console.log(result);
});
// Synchronous method with cache
var addSync = function (a, b) {
return a + b;
};
server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false });
server.methods.sumSync(4, 5, function (err, result) {
console.log(result);
}); */
method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/
name: string,
method: IServerMethod,
options?: IServerMethodOptions): void;
/**server.method(methods)
Registers a server method function as described in server.method() using a configuration object where:
methods - an object or an array of objects where each one contains:
name - the method name.
method - the method function.
options - optional settings.
var add = function (a, b, next) {
next(null, a + b);
};
server.method({
name: 'sum',
method: add,
options: {
cache: {
expiresIn: 2000
}
}
});*/
method(methods: {
name: string; method: IServerMethod; options?: IServerMethodOptions
} | Array<{
name: string; method: IServerMethod; options?: IServerMethodOptions
}>): void;
/**server.path(relativeTo)
Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where:
relativeTo - the path prefix added to any relative file path starting with '.'.
Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set.
exports.register = function (server, options, next) {
server.path(__dirname + '../static');
server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } });
next();
};*/
path(relativeTo: string): void;
/**
* server.register(plugins, [options], callback)
* Registers a plugin where:
* plugins - an object or array of objects where each one is either:
* a plugin registration function.
* an object with the following:
* register - the plugin registration function.
* options - optional options passed to the registration function when called.
* options - optional registration options (different from the options passed to the registration function):
* select - a string or array of string labels used to pre-select connections for plugin registration.
* routes - modifiers applied to each route added by the plugin:
* prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix.
* vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
* callback - the callback function with signature function(err) where:
* err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework.
*
* If no callback is provided, a Promise object is returned.
*/
register(plugins: any | any[], options: {
select: string | string[];
routes: {
prefix: string; vhost?: string | string[]
};
}, callback: (err: any) => void): void;
register(plugins: any | any[], options: {
select: string | string[];
routes: {
prefix: string; vhost?: string | string[]
};
}): IPromise<any>;
register(plugins: any | any[], callback: (err: any) => void): void;
register(plugins: any | any[]): IPromise<any>;
/**server.render(template, context, [options], callback)
Utilizes the server views manager to render a template where:
template - the template filename and path, relative to the views manager templates path (path or relativeTo).
context - optional object used by the template to render context-specific result. Defaults to no context ({}).
options - optional object used to override the views manager configuration.
callback - the callback function with signature function (err, rendered, config) where:
err - the rendering error if any.
rendered - the result view string.
config - the configuration used to render the template.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
var context = {
title: 'Views Example',
message: 'Hello, World'
};
server.render('hello', context, function (err, rendered, config) {
console.log(rendered);
});*/
render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void;
/** server.route(options)
Adds a connection route where:
options - a route configuration object or an array of configuration objects.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } });
server.route([
{ method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } },
{ method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } }
]);*/
route(options: IRouteConfiguration): void;
route(options: IRouteConfiguration[]): void;
/**server.select(labels)
Selects a subset of the server's connections where:
labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration.
Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, labels: ['a'] });
server.connection({ port: 8080, labels: ['b'] });
server.connection({ port: 8081, labels: ['c'] });
server.connection({ port: 8082, labels: ['c','d'] });
var a = server.select('a'); // The server with port 80
var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080
var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */
select(labels: string | string[]): Server | Server[];
/** server.start([callback])
Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where:
callback - optional callback when server startup is completed or failed with the signature function(err) where:
err - any startup error condition.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.start(function (err) {
console.log('Server started at: ' + server.info.uri);
});*/
start(callback?: (err: any) => void): IPromise<void>;
/** server.state(name, [options])
HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions
State defaults can be modified via the server connections.routes.state configuration option.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Set cookie definition
server.state('session', {
ttl: 24 * 60 * 60 * 1000, // One day
isSecure: true,
path: '/',
encoding: 'base64json'
});
// Set state in route handler
var handler = function (request, reply) {
var session = request.state.session;
if (!session) {
session = { user: 'joe' };
}
session.last = Date.now();
return reply('Success').state('session', session);
};
Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request-internal', function (request, event, tags) {
if (tags.error && tags.state) {
console.error(event);
}
}); */
state(name: string, options?: ICookieSettings): void;
/** server.stop([options], [callback])
Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where:
options - optional object with:
timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds).
callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.stop({ timeout: 60 * 1000 }, function () {
console.log('Server stopped');
});*/
stop(options?: { timeout: number }, callback?: () => void): IPromise<void>;
/**server.table([host])
Returns a copy of the routing table where:
host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.
Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.table();
When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.connections[0].table();
//[
// {
// method: 'get',
// path: '/example',
// settings: { ... }
// }
//]
*/
table(host?: any): IConnectionTable;
/**server.views(options)
Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.*/
views(options: IServerViewsConfiguration): void;
}
}
| navgurukul/galileo | typings/globals/hapi/index.d.ts | TypeScript | gpl-3.0 | 145,113 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Psr\Log\LoggerInterface;
/**
* UrlGenerator can generate a URL or a path for any route in the RouteCollection
* based on the passed parameters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
{
/**
* @var RouteCollection
*/
protected $routes;
/**
* @var RequestContext
*/
protected $context;
/**
* @var bool|null
*/
protected $strictRequirements = true;
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
*
* PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
* to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
* "?" and "#" (would be interpreted wrongly as query and fragment identifier),
* "'" and """ (are used as delimiters in HTML).
*/
protected $decodedChars = array(
// the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
// some webservers don't allow the slash in encoded form in the path for security reasons anyway
// see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
'%2F' => '/',
// the following chars are general delimiters in the URI specification but have only special meaning in the authority component
// so they can safely be used in the path in unencoded form
'%40' => '@',
'%3A' => ':',
// these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
// so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
);
/**
* @var string This regexp matches all characters that are not or should not be encoded by rawurlencode (see list in array above).
*/
private $urlEncodingSkipRegexp = '#[^-.~a-zA-Z0-9_/@:;,=+!*|]#';
/**
* Constructor.
*
* @param RouteCollection $routes A RouteCollection instance
* @param RequestContext $context The context
* @param LoggerInterface|null $logger A logger instance
*/
public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
{
$this->routes = $routes;
$this->context = $context;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function setStrictRequirements($enabled)
{
$this->strictRequirements = null === $enabled ? null : (bool) $enabled;
}
/**
* {@inheritdoc}
*/
public function isStrictRequirements()
{
return $this->strictRequirements;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (null === $route = $this->routes->get($name)) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
}
/**
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
{
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $mergedParams)) {
throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
// check requirement
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$url = $token[1].$mergedParams[$token[3]].$url;
$optional = false;
}
} else {
// static text
$url = $token[1].$url;
$optional = false;
}
}
if ('' === $url) {
$url = '/';
} elseif (preg_match($this->urlEncodingSkipRegexp, $url)) {
// the context base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
$url = strtr(rawurlencode($url), $this->decodedChars);
}
// the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we need to encode them as they are not used for this purpose here
// otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
if (false !== strpos($url, '/.')) {
$url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
if ('/..' === substr($url, -3)) {
$url = substr($url, 0, -2).'%2E%2E';
} elseif ('/.' === substr($url, -2)) {
$url = substr($url, 0, -1).'%2E';
}
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
if (!in_array($scheme, $requiredSchemes, true)) {
$referenceType = self::ABSOLUTE_URL;
$scheme = current($requiredSchemes);
}
}
if ($hostTokens) {
$routeHost = '';
foreach ($hostTokens as $token) {
if ('variable' === $token[0]) {
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
} else {
$routeHost = $token[1].$routeHost;
}
}
if ($routeHost !== $host) {
$host = $routeHost;
if (self::ABSOLUTE_URL !== $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);
} else {
$url = $schemeAuthority.$this->context->getBaseUrl().$url;
}
// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
$url .= '?'.(false === strpos($query, '%2F') ? $query : strtr($query, array('%2F' => '/')));
}
return $url;
}
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
}
| AngelSanz1/quieroundoc | vendor/symfony/routing/Generator/UrlGenerator.php | PHP | gpl-3.0 | 13,482 |
// Copyright (C) 2012 Tuma Solutions, LLC
// Team Functionality Add-ons for the Process Dashboard
//
// 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.
//
// Additional permissions also apply; see the README-license.txt
// file in the project root directory for more information.
//
// 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/>.
//
// The author(s) may be contacted at:
// processdash@tuma-solutions.com
// processdash-devel@lists.sourceforge.net
package teamdash.wbs.columns;
import teamdash.wbs.WBSModel;
import teamdash.wbs.WBSNode;
import teamdash.wbs.WBSNodeTest;
public class ErrorNotesColumn extends AbstractNotesColumn {
/** The ID we use for this column in the data model */
public static final String COLUMN_ID = "Error Notes";
/** The attribute this column uses to store task notes for a WBS node */
public static final String VALUE_ATTR = "Error Notes";
public ErrorNotesColumn(String authorName) {
super(VALUE_ATTR, authorName);
this.columnID = COLUMN_ID;
this.columnName = resources.getString("Error_Notes.Name");
}
@Override
protected String getEditDialogTitle() {
return columnName;
}
@Override
protected Object getEditDialogHeader(WBSNode node) {
return new Object[] {
resources.getStrings("Error_Notes.Edit_Dialog_Header"), " " };
}
public static String getTextAt(WBSNode node) {
return getTextAt(node, VALUE_ATTR);
}
public static String getTooltipAt(WBSNode node, boolean includeByline) {
return getTooltipAt(node, includeByline, VALUE_ATTR);
}
/**
* Find nodes that have errors attached, and expand their ancestors as
* needed to ensure that they are visible.
*
* @param wbs
* the WBSModel
* @param belowNode
* an optional starting point for the search, to limit expansion
* to a particular branch of the tree; can be null to search from
* the root
* @param condition
* an optional condition to test; only nodes matching the
* condition will be made visible. Can be null to show all nodes
* with errors
*/
public static void showNodesWithErrors(WBSModel wbs, WBSNode belowNode,
WBSNodeTest condition) {
if (belowNode == null)
belowNode = wbs.getRoot();
for (WBSNode node : wbs.getDescendants(belowNode)) {
String errText = getTextAt(node, VALUE_ATTR);
if (errText != null && errText.trim().length() > 0) {
if (condition == null || condition.test(node))
wbs.makeVisible(node);
}
}
}
}
| superzadeh/processdash | teamdash/src/teamdash/wbs/columns/ErrorNotesColumn.java | Java | gpl-3.0 | 3,288 |
<?php
/**
Copyright 2011-2014 Nick Korbel
This file is part of Booked Scheduler 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 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'lib/Graphics/Image.php');
require_once(ROOT_DIR . 'lib/Graphics/ImageFactory.php');
?> | pluanant/booktu | lib/Graphics/namespace.php | PHP | gpl-3.0 | 784 |
package gobol
// Error - defines a common http error interface
type Error interface {
error
StatusCode() int
Message() string
Package() string
Function() string
ErrorCode() string
}
| uol/mycenae | vendor/github.com/uol/gobol/error.go | GO | gpl-3.0 | 189 |
namespace Hfr.Model
{
public enum View
{
Connect,
Main,
Editor,
Settings,
CategoriesList,
CategoryThreadsList,
PrivateChatsList,
PrivateChat
}
}
| ThomasNigro/HFR10 | Hfr/Hfr/Models/Page.cs | C# | gpl-3.0 | 224 |
//===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of a target
// register bank for a code generator.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/BitVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "CodeGenHwModes.h"
#include "CodeGenRegisters.h"
#include "CodeGenTarget.h"
#define DEBUG_TYPE "register-bank-emitter"
using namespace llvm;
namespace {
class RegisterBank {
/// A vector of register classes that are included in the register bank.
typedef std::vector<const CodeGenRegisterClass *> RegisterClassesTy;
private:
const Record &TheDef;
/// The register classes that are covered by the register bank.
RegisterClassesTy RCs;
/// The register class with the largest register size.
const CodeGenRegisterClass *RCWithLargestRegsSize;
public:
RegisterBank(const Record &TheDef)
: TheDef(TheDef), RCs(), RCWithLargestRegsSize(nullptr) {}
/// Get the human-readable name for the bank.
StringRef getName() const { return TheDef.getValueAsString("Name"); }
/// Get the name of the enumerator in the ID enumeration.
std::string getEnumeratorName() const { return (TheDef.getName() + "ID").str(); }
/// Get the name of the array holding the register class coverage data;
std::string getCoverageArrayName() const {
return (TheDef.getName() + "CoverageData").str();
}
/// Get the name of the global instance variable.
StringRef getInstanceVarName() const { return TheDef.getName(); }
const Record &getDef() const { return TheDef; }
/// Get the register classes listed in the RegisterBank.RegisterClasses field.
std::vector<const CodeGenRegisterClass *>
getExplicitlySpecifiedRegisterClasses(
const CodeGenRegBank &RegisterClassHierarchy) const {
std::vector<const CodeGenRegisterClass *> RCs;
for (const auto *RCDef : getDef().getValueAsListOfDefs("RegisterClasses"))
RCs.push_back(RegisterClassHierarchy.getRegClass(RCDef));
return RCs;
}
/// Add a register class to the bank without duplicates.
void addRegisterClass(const CodeGenRegisterClass *RC) {
if (llvm::is_contained(RCs, RC))
return;
// FIXME? We really want the register size rather than the spill size
// since the spill size may be bigger on some targets with
// limited load/store instructions. However, we don't store the
// register size anywhere (we could sum the sizes of the subregisters
// but there may be additional bits too) and we can't derive it from
// the VT's reliably due to Untyped.
if (RCWithLargestRegsSize == nullptr)
RCWithLargestRegsSize = RC;
else if (RCWithLargestRegsSize->RSI.get(DefaultMode).SpillSize <
RC->RSI.get(DefaultMode).SpillSize)
RCWithLargestRegsSize = RC;
assert(RCWithLargestRegsSize && "RC was nullptr?");
RCs.emplace_back(RC);
}
const CodeGenRegisterClass *getRCWithLargestRegsSize() const {
return RCWithLargestRegsSize;
}
iterator_range<typename RegisterClassesTy::const_iterator>
register_classes() const {
return llvm::make_range(RCs.begin(), RCs.end());
}
};
class RegisterBankEmitter {
private:
CodeGenTarget Target;
RecordKeeper &Records;
void emitHeader(raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks);
void emitBaseClassDefinition(raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks);
void emitBaseClassImplementation(raw_ostream &OS, const StringRef TargetName,
std::vector<RegisterBank> &Banks);
public:
RegisterBankEmitter(RecordKeeper &R) : Target(R), Records(R) {}
void run(raw_ostream &OS);
};
} // end anonymous namespace
/// Emit code to declare the ID enumeration and external global instance
/// variables.
void RegisterBankEmitter::emitHeader(raw_ostream &OS,
const StringRef TargetName,
const std::vector<RegisterBank> &Banks) {
// <Target>RegisterBankInfo.h
OS << "namespace llvm {\n"
<< "namespace " << TargetName << " {\n"
<< "enum : unsigned {\n";
OS << " InvalidRegBankID = ~0u,\n";
unsigned ID = 0;
for (const auto &Bank : Banks)
OS << " " << Bank.getEnumeratorName() << " = " << ID++ << ",\n";
OS << " NumRegisterBanks,\n"
<< "};\n"
<< "} // end namespace " << TargetName << "\n"
<< "} // end namespace llvm\n";
}
/// Emit declarations of the <Target>GenRegisterBankInfo class.
void RegisterBankEmitter::emitBaseClassDefinition(
raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks) {
OS << "private:\n"
<< " static RegisterBank *RegBanks[];\n\n"
<< "protected:\n"
<< " " << TargetName << "GenRegisterBankInfo();\n"
<< "\n";
}
/// Visit each register class belonging to the given register bank.
///
/// A class belongs to the bank iff any of these apply:
/// * It is explicitly specified
/// * It is a subclass of a class that is a member.
/// * It is a class containing subregisters of the registers of a class that
/// is a member. This is known as a subreg-class.
///
/// This function must be called for each explicitly specified register class.
///
/// \param RC The register class to search.
/// \param Kind A debug string containing the path the visitor took to reach RC.
/// \param VisitFn The action to take for each class visited. It may be called
/// multiple times for a given class if there are multiple paths
/// to the class.
static void visitRegisterBankClasses(
const CodeGenRegBank &RegisterClassHierarchy,
const CodeGenRegisterClass *RC, const Twine &Kind,
std::function<void(const CodeGenRegisterClass *, StringRef)> VisitFn,
SmallPtrSetImpl<const CodeGenRegisterClass *> &VisitedRCs) {
// Make sure we only visit each class once to avoid infinite loops.
if (VisitedRCs.count(RC))
return;
VisitedRCs.insert(RC);
// Visit each explicitly named class.
VisitFn(RC, Kind.str());
for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) {
std::string TmpKind =
(Kind + " (" + PossibleSubclass.getName() + ")").str();
// Visit each subclass of an explicitly named class.
if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass))
visitRegisterBankClasses(RegisterClassHierarchy, &PossibleSubclass,
TmpKind + " " + RC->getName() + " subclass",
VisitFn, VisitedRCs);
// Visit each class that contains only subregisters of RC with a common
// subregister-index.
//
// More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in
// PossibleSubclass for all registers Reg from RC using any
// subregister-index SubReg
for (const auto &SubIdx : RegisterClassHierarchy.getSubRegIndices()) {
BitVector BV(RegisterClassHierarchy.getRegClasses().size());
PossibleSubclass.getSuperRegClasses(&SubIdx, BV);
if (BV.test(RC->EnumValue)) {
std::string TmpKind2 = (Twine(TmpKind) + " " + RC->getName() +
" class-with-subregs: " + RC->getName())
.str();
VisitFn(&PossibleSubclass, TmpKind2);
}
}
}
}
void RegisterBankEmitter::emitBaseClassImplementation(
raw_ostream &OS, StringRef TargetName,
std::vector<RegisterBank> &Banks) {
const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
OS << "namespace llvm {\n"
<< "namespace " << TargetName << " {\n";
for (const auto &Bank : Banks) {
std::vector<std::vector<const CodeGenRegisterClass *>> RCsGroupedByWord(
(RegisterClassHierarchy.getRegClasses().size() + 31) / 32);
for (const auto &RC : Bank.register_classes())
RCsGroupedByWord[RC->EnumValue / 32].push_back(RC);
OS << "const uint32_t " << Bank.getCoverageArrayName() << "[] = {\n";
unsigned LowestIdxInWord = 0;
for (const auto &RCs : RCsGroupedByWord) {
OS << " // " << LowestIdxInWord << "-" << (LowestIdxInWord + 31) << "\n";
for (const auto &RC : RCs) {
std::string QualifiedRegClassID =
(Twine(RC->Namespace) + "::" + RC->getName() + "RegClassID").str();
OS << " (1u << (" << QualifiedRegClassID << " - "
<< LowestIdxInWord << ")) |\n";
}
OS << " 0,\n";
LowestIdxInWord += 32;
}
OS << "};\n";
}
OS << "\n";
for (const auto &Bank : Banks) {
std::string QualifiedBankID =
(TargetName + "::" + Bank.getEnumeratorName()).str();
const CodeGenRegisterClass &RC = *Bank.getRCWithLargestRegsSize();
unsigned Size = RC.RSI.get(DefaultMode).SpillSize;
OS << "RegisterBank " << Bank.getInstanceVarName() << "(/* ID */ "
<< QualifiedBankID << ", /* Name */ \"" << Bank.getName()
<< "\", /* Size */ " << Size << ", "
<< "/* CoveredRegClasses */ " << Bank.getCoverageArrayName()
<< ", /* NumRegClasses */ "
<< RegisterClassHierarchy.getRegClasses().size() << ");\n";
}
OS << "} // end namespace " << TargetName << "\n"
<< "\n";
OS << "RegisterBank *" << TargetName
<< "GenRegisterBankInfo::RegBanks[] = {\n";
for (const auto &Bank : Banks)
OS << " &" << TargetName << "::" << Bank.getInstanceVarName() << ",\n";
OS << "};\n\n";
OS << TargetName << "GenRegisterBankInfo::" << TargetName
<< "GenRegisterBankInfo()\n"
<< " : RegisterBankInfo(RegBanks, " << TargetName
<< "::NumRegisterBanks) {\n"
<< " // Assert that RegBank indices match their ID's\n"
<< "#ifndef NDEBUG\n"
<< " unsigned Index = 0;\n"
<< " for (const auto &RB : RegBanks)\n"
<< " assert(Index++ == RB->getID() && \"Index != ID\");\n"
<< "#endif // NDEBUG\n"
<< "}\n"
<< "} // end namespace llvm\n";
}
void RegisterBankEmitter::run(raw_ostream &OS) {
StringRef TargetName = Target.getName();
const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
Records.startTimer("Analyze records");
std::vector<RegisterBank> Banks;
for (const auto &V : Records.getAllDerivedDefinitions("RegisterBank")) {
SmallPtrSet<const CodeGenRegisterClass *, 8> VisitedRCs;
RegisterBank Bank(*V);
for (const CodeGenRegisterClass *RC :
Bank.getExplicitlySpecifiedRegisterClasses(RegisterClassHierarchy)) {
visitRegisterBankClasses(
RegisterClassHierarchy, RC, "explicit",
[&Bank](const CodeGenRegisterClass *RC, StringRef Kind) {
LLVM_DEBUG(dbgs()
<< "Added " << RC->getName() << "(" << Kind << ")\n");
Bank.addRegisterClass(RC);
},
VisitedRCs);
}
Banks.push_back(Bank);
}
// Warn about ambiguous MIR caused by register bank/class name clashes.
Records.startTimer("Warn ambiguous");
for (const auto &Class : RegisterClassHierarchy.getRegClasses()) {
for (const auto &Bank : Banks) {
if (Bank.getName().lower() == StringRef(Class.getName()).lower()) {
PrintWarning(Bank.getDef().getLoc(), "Register bank names should be "
"distinct from register classes "
"to avoid ambiguous MIR");
PrintNote(Bank.getDef().getLoc(), "RegisterBank was declared here");
PrintNote(Class.getDef()->getLoc(), "RegisterClass was declared here");
}
}
}
Records.startTimer("Emit output");
emitSourceFileHeader("Register Bank Source Fragments", OS);
OS << "#ifdef GET_REGBANK_DECLARATIONS\n"
<< "#undef GET_REGBANK_DECLARATIONS\n";
emitHeader(OS, TargetName, Banks);
OS << "#endif // GET_REGBANK_DECLARATIONS\n\n"
<< "#ifdef GET_TARGET_REGBANK_CLASS\n"
<< "#undef GET_TARGET_REGBANK_CLASS\n";
emitBaseClassDefinition(OS, TargetName, Banks);
OS << "#endif // GET_TARGET_REGBANK_CLASS\n\n"
<< "#ifdef GET_TARGET_REGBANK_IMPL\n"
<< "#undef GET_TARGET_REGBANK_IMPL\n";
emitBaseClassImplementation(OS, TargetName, Banks);
OS << "#endif // GET_TARGET_REGBANK_IMPL\n";
}
namespace llvm {
void EmitRegisterBank(RecordKeeper &RK, raw_ostream &OS) {
RegisterBankEmitter(RK).run(OS);
}
} // end namespace llvm
| sabel83/metashell | 3rd/templight/llvm/utils/TableGen/RegisterBankEmitter.cpp | C++ | gpl-3.0 | 12,878 |
# -*- coding: utf-8 -*-
"""
pythoner.net
Copyright (C) 2013 PYTHONER.ORG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django.contrib import admin
from models import *
class ProfileAdmin(admin.ModelAdmin):
list_display = ('screen_name','city','introduction')
admin.site.register(UserProfile,ProfileAdmin) | yohn89/pythoner.net | pythoner/accounts/admin.py | Python | gpl-3.0 | 915 |
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2017
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <Graphics/GteViewVolumeNode.h>
using namespace gte;
ViewVolumeNode::ViewVolumeNode(std::shared_ptr<ViewVolume> const& viewVolume)
:
mOnUpdate([](ViewVolumeNode*){})
{
SetViewVolume(viewVolume);
}
void ViewVolumeNode::SetViewVolume(std::shared_ptr<ViewVolume> const& viewVolume)
{
mViewVolume = viewVolume;
if (mViewVolume)
{
Matrix4x4<float> rotate;
#if defined(GTE_USE_MAT_VEC)
rotate.SetCol(0, mViewVolume->GetDVector());
rotate.SetCol(1, mViewVolume->GetUVector());
rotate.SetCol(2, mViewVolume->GetRVector());
rotate.SetCol(3, { 0.0f, 0.0f, 0.0f, 1.0f });
#else
rotate.SetRow(0, mViewVolume->GetDVector());
rotate.SetRow(1, mViewVolume->GetUVector());
rotate.SetRow(2, mViewVolume->GetRVector());
rotate.SetRow(3, { 0.0f, 0.0f, 0.0f, 1.0f });
#endif
localTransform.SetTranslation(mViewVolume->GetPosition());
localTransform.SetRotation(rotate);
Update();
}
}
void ViewVolumeNode::UpdateWorldData(double applicationTime)
{
Node::UpdateWorldData(applicationTime);
if (mViewVolume)
{
Vector4<float> position = worldTransform.GetTranslationW1();
Matrix4x4<float> const& rotate = worldTransform.GetHMatrix();
#if defined(GTE_USE_MAT_VEC)
Vector4<float> dVector = rotate.GetCol(0);
Vector4<float> uVector = rotate.GetCol(1);
Vector4<float> rVector = rotate.GetCol(2);
#else
Vector4<float> dVector = rotate.GetRow(0);
Vector4<float> uVector = rotate.GetRow(1);
Vector4<float> rVector = rotate.GetRow(2);
#endif
mViewVolume->SetFrame(position, dVector, uVector, rVector);
mOnUpdate(this);
}
}
| yijiangh/FrameFab | ext/GTEngine/Source/Graphics/GteViewVolumeNode.cpp | C++ | gpl-3.0 | 2,029 |
from django.conf.urls.defaults import *
from indivo.views import *
from indivo.lib.utils import MethodDispatcher
urlpatterns = patterns('',
(r'^$', MethodDispatcher({
'DELETE' : carenet_delete})),
(r'^/rename$', MethodDispatcher({
'POST' : carenet_rename})),
(r'^/record$', MethodDispatcher({'GET':carenet_record})),
# Manage documents
(r'^/documents/', include('indivo.urls.carenet_documents')),
# Manage accounts
(r'^/accounts/$',
MethodDispatcher({
'GET' : carenet_account_list,
'POST' : carenet_account_create
})),
(r'^/accounts/(?P<account_id>[^/]+)$',
MethodDispatcher({ 'DELETE' : carenet_account_delete })),
# Manage apps
(r'^/apps/$',
MethodDispatcher({ 'GET' : carenet_apps_list})),
(r'^/apps/(?P<pha_email>[^/]+)$',
MethodDispatcher({ 'PUT' : carenet_apps_create,
'DELETE': carenet_apps_delete})),
# Permissions Calls
(r'^/accounts/(?P<account_id>[^/]+)/permissions$',
MethodDispatcher({ 'GET' : carenet_account_permissions })),
(r'^/apps/(?P<pha_email>[^/]+)/permissions$',
MethodDispatcher({ 'GET' : carenet_app_permissions })),
# Reporting Calls
(r'^/reports/minimal/procedures/$',
MethodDispatcher({'GET':carenet_procedure_list})),
(r'^/reports/minimal/simple-clinical-notes/$',
MethodDispatcher({'GET':carenet_simple_clinical_notes_list})),
(r'^/reports/minimal/equipment/$',
MethodDispatcher({'GET':carenet_equipment_list})),
(r'^/reports/minimal/measurements/(?P<lab_code>[^/]+)/$',
MethodDispatcher({'GET':carenet_measurement_list})),
(r'^/reports/(?P<data_model>[^/]+)/$',
MethodDispatcher({'GET':carenet_generic_list})),
# Demographics
(r'^/demographics$', MethodDispatcher({'GET': read_demographics_carenet})),
)
| sayan801/indivo_server | indivo/urls/carenet.py | Python | gpl-3.0 | 1,997 |
# coding: utf-8
import json
import logging
import dateutil.parser
import pytz
from werkzeug import urls
from odoo import api, fields, models, _
from odoo.addons.payment.models.payment_acquirer import ValidationError
from odoo.addons.payment_paypal.controllers.main import PaypalController
from odoo.tools.float_utils import float_compare
_logger = logging.getLogger(__name__)
class AcquirerPaypal(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming from Paypal are valid and secured.')
paypal_use_ipn = fields.Boolean('Use IPN', default=True, help='Paypal Instant Payment Notification', groups='base.group_user')
paypal_pdt_token = fields.Char(string='Paypal PDT Token', help='Payment Data Transfer allows you to receive notification of successful payments as they are made.', groups='base.group_user')
# Server 2 server
paypal_api_enabled = fields.Boolean('Use Rest API', default=False)
paypal_api_username = fields.Char('Rest API Username', groups='base.group_user')
paypal_api_password = fields.Char('Rest API Password', groups='base.group_user')
paypal_api_access_token = fields.Char('Access Token', groups='base.group_user')
paypal_api_access_token_validity = fields.Datetime('Access Token Validity', groups='base.group_user')
# Default paypal fees
fees_dom_fixed = fields.Float(default=0.35)
fees_dom_var = fields.Float(default=3.4)
fees_int_fixed = fields.Float(default=0.35)
fees_int_var = fields.Float(default=3.9)
def _get_feature_support(self):
"""Get advanced feature support by provider.
Each provider should add its technical in the corresponding
key for the following features:
* fees: support payment fees computations
* authorize: support authorizing payment (separates
authorization and capture)
* tokenize: support saving payment data in a payment.tokenize
object
"""
res = super(AcquirerPaypal, self)._get_feature_support()
res['fees'].append('paypal')
return res
@api.model
def _get_paypal_urls(self, environment):
""" Paypal URLS """
if environment == 'prod':
return {
'paypal_form_url': 'https://www.paypal.com/cgi-bin/webscr',
'paypal_rest_url': 'https://api.paypal.com/v1/oauth2/token',
}
else:
return {
'paypal_form_url': 'https://www.sandbox.paypal.com/cgi-bin/webscr',
'paypal_rest_url': 'https://api.sandbox.paypal.com/v1/oauth2/token',
}
@api.multi
def paypal_compute_fees(self, amount, currency_id, country_id):
""" Compute paypal fees.
:param float amount: the amount to pay
:param integer country_id: an ID of a res.country, or None. This is
the customer's country, to be compared to
the acquirer company country.
:return float fees: computed fees
"""
if not self.fees_active:
return 0.0
country = self.env['res.country'].browse(country_id)
if country and self.company_id.country_id.id == country.id:
percentage = self.fees_dom_var
fixed = self.fees_dom_fixed
else:
percentage = self.fees_int_var
fixed = self.fees_int_fixed
fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0)
return fees
@api.multi
def paypal_form_generate_values(self, values):
base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
paypal_tx_values = dict(values)
paypal_tx_values.update({
'cmd': '_xclick',
'business': self.paypal_email_account,
'item_name': '%s: %s' % (self.company_id.name, values['reference']),
'item_number': values['reference'],
'amount': values['amount'],
'currency_code': values['currency'] and values['currency'].name or '',
'address1': values.get('partner_address'),
'city': values.get('partner_city'),
'country': values.get('partner_country') and values.get('partner_country').code or '',
'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '',
'email': values.get('partner_email'),
'zip_code': values.get('partner_zip'),
'first_name': values.get('partner_first_name'),
'last_name': values.get('partner_last_name'),
'paypal_return': urls.url_join(base_url, PaypalController._return_url),
'notify_url': urls.url_join(base_url, PaypalController._notify_url),
'cancel_return': urls.url_join(base_url, PaypalController._cancel_url),
'handling': '%.2f' % paypal_tx_values.pop('fees', 0.0) if self.fees_active else False,
'custom': json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) if paypal_tx_values.get('return_url') else False,
})
return paypal_tx_values
@api.multi
def paypal_get_form_action_url(self):
return self._get_paypal_urls(self.environment)['paypal_form_url']
class TxPaypal(models.Model):
_inherit = 'payment.transaction'
paypal_txn_type = fields.Char('Transaction type')
# --------------------------------------------------
# FORM RELATED METHODS
# --------------------------------------------------
@api.model
def _paypal_form_get_tx_from_data(self, data):
reference, txn_id = data.get('item_number'), data.get('txn_id')
if not reference or not txn_id:
error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)
# find tx -> @TDENOTE use txn_id ?
txs = self.env['payment.transaction'].search([('reference', '=', reference)])
if not txs or len(txs) > 1:
error_msg = 'Paypal: received data for reference %s' % (reference)
if not txs:
error_msg += '; no order found'
else:
error_msg += '; multiple order found'
_logger.info(error_msg)
raise ValidationError(error_msg)
return txs[0]
@api.multi
def _paypal_form_get_invalid_parameters(self, data):
invalid_parameters = []
_logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version'))
if data.get('test_ipn'):
_logger.warning(
'Received a notification from Paypal using sandbox'
),
# TODO: txn_id: shoudl be false at draft, set afterwards, and verified with txn details
if self.acquirer_reference and data.get('txn_id') != self.acquirer_reference:
invalid_parameters.append(('txn_id', data.get('txn_id'), self.acquirer_reference))
# check what is buyed
if float_compare(float(data.get('mc_gross', '0.0')), (self.amount + self.fees), 2) != 0:
invalid_parameters.append(('mc_gross', data.get('mc_gross'), '%.2f' % self.amount)) # mc_gross is amount + fees
if data.get('mc_currency') != self.currency_id.name:
invalid_parameters.append(('mc_currency', data.get('mc_currency'), self.currency_id.name))
if 'handling_amount' in data and float_compare(float(data.get('handling_amount')), self.fees, 2) != 0:
invalid_parameters.append(('handling_amount', data.get('handling_amount'), self.fees))
# check buyer
if self.payment_token_id and data.get('payer_id') != self.payment_token_id.acquirer_ref:
invalid_parameters.append(('payer_id', data.get('payer_id'), self.payment_token_id.acquirer_ref))
# check seller
if data.get('receiver_id') and self.acquirer_id.paypal_seller_account and data['receiver_id'] != self.acquirer_id.paypal_seller_account:
invalid_parameters.append(('receiver_id', data.get('receiver_id'), self.acquirer_id.paypal_seller_account))
if not data.get('receiver_id') or not self.acquirer_id.paypal_seller_account:
# Check receiver_email only if receiver_id was not checked.
# In Paypal, this is possible to configure as receiver_email a different email than the business email (the login email)
# In Odoo, there is only one field for the Paypal email: the business email. This isn't possible to set a receiver_email
# different than the business email. Therefore, if you want such a configuration in your Paypal, you are then obliged to fill
# the Merchant ID in the Paypal payment acquirer in Odoo, so the check is performed on this variable instead of the receiver_email.
# At least one of the two checks must be done, to avoid fraudsters.
if data.get('receiver_email') != self.acquirer_id.paypal_email_account:
invalid_parameters.append(('receiver_email', data.get('receiver_email'), self.acquirer_id.paypal_email_account))
return invalid_parameters
@api.multi
def _paypal_form_validate(self, data):
status = data.get('payment_status')
res = {
'acquirer_reference': data.get('txn_id'),
'paypal_txn_type': data.get('payment_type'),
}
if status in ['Completed', 'Processed']:
_logger.info('Validated Paypal payment for tx %s: set as done' % (self.reference))
try:
# dateutil and pytz don't recognize abbreviations PDT/PST
tzinfos = {
'PST': -8 * 3600,
'PDT': -7 * 3600,
}
date = dateutil.parser.parse(data.get('payment_date'), tzinfos=tzinfos).astimezone(pytz.utc)
except:
date = fields.Datetime.now()
res.update(date=date)
self._set_transaction_done()
return self.write(res)
elif status in ['Pending', 'Expired']:
_logger.info('Received notification for Paypal payment %s: set as pending' % (self.reference))
res.update(state_message=data.get('pending_reason', ''))
self._set_transaction_pending()
return self.write(res)
else:
error = 'Received unrecognized status for Paypal payment %s: %s, set as error' % (self.reference, status)
_logger.info(error)
res.update(state_message=error)
self._set_transaction_cancel()
return self.write(res)
| t3dev/odoo | addons/payment_paypal/models/payment.py | Python | gpl-3.0 | 11,083 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCL.Net;
namespace Conv.NET
{
[Serializable]
public class FullyConnectedLayer : Layer
{
#region Fields
private double dropoutParameter;
// Host
private float[] weightsHost;
private float[] biasesHost;
// Device
[NonSerialized]
private Mem dropoutMaskGPU;
[NonSerialized]
private Mem weightsGPU;
[NonSerialized]
private Mem biasesGPU;
[NonSerialized]
private Mem weightsGradientsGPU;
[NonSerialized]
private Mem biasesGradientsGPU;
[NonSerialized]
private Mem weightsSpeedGPU;
[NonSerialized]
private Mem biasesSpeedGPU;
// Global and local work-group sizes (for OpenCL kernels) - will be set in SetWorkGroupSizes();
private IntPtr[] forwardGlobalWorkSizePtr;
private IntPtr[] forwardLocalWorkSizePtr;
private IntPtr[] backwardGlobalWorkSizePtr;
private IntPtr[] backwardLocalWorkSizePtr;
private IntPtr[] updateGlobalWorkSizePtr;
private IntPtr[] updateLocalWorkSizePtr;
private IntPtr[] constrainNormGlobalWorkSizePtr;
private IntPtr[] constrainNormLocalWorkSizePtr;
#endregion
#region Properties
public override Mem WeightsGPU
{
get { return weightsGPU; }
}
public override double DropoutParameter
{
set { this.dropoutParameter = value; }
}
#endregion
#region Setup methods
/// <summary>
/// Constructor of fully connected layer type. Specify number of units as argument.
/// </summary>
/// <param name="nUnits"></param>
public FullyConnectedLayer(int nUnits)
{
this.type = "FullyConnected";
this.nOutputUnits = nUnits;
}
public override void SetupOutput()
{
this.outputDepth = nOutputUnits;
this.outputHeight = 1;
this.outputWidth = 1;
this.outputNeurons = new Neurons(this.nOutputUnits);
#if OPENCL_ENABLED
this.dropoutMaskGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)(sizeof(bool) * nOutputUnits * inputNeurons.MiniBatchSize),
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "InitializeParameters(): Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(dropoutMaskGPU, nOutputUnits * inputNeurons.MiniBatchSize, typeof(bool));
#endif
}
public override void InitializeParameters(string Option)
{
base.InitializeParameters(Option); // makes sure this method is only call AFTER "SetupOutput()"
if (Option == "random") // sample new parameters
{
// WEIGHTS are initialized as normally distributed numbers with mean 0 and std equals to sqrt(2/nInputUnits)
// BIASES are initialized to a small positive number, e.g. 0.001
this.weightsHost = new float[nOutputUnits * nInputUnits];
this.biasesHost = new float[nOutputUnits];
double weightsStdDev = Math.Sqrt(2.0 / (10 * nInputUnits));
double uniformRand1;
double uniformRand2;
double tmp;
for (int iRow = 0; iRow < nOutputUnits; iRow++)
{
for (int iCol = 0; iCol < nInputUnits; iCol++)
{
uniformRand1 = Global.rng.NextDouble();
uniformRand2 = Global.rng.NextDouble();
// Use a Box-Muller transform to get a random normal(0,1)
tmp = Math.Sqrt(-2.0 * Math.Log(uniformRand1)) * Math.Sin(2.0 * Math.PI * uniformRand2);
tmp = weightsStdDev * tmp; // rescale
weightsHost[iRow * nInputUnits + iCol] = (float)tmp;
}
biasesHost[iRow] = 0.00f;
}
}
// else Option must be ''load'' => do not sample parameters, just load them from host to device
int weightBufferSize = sizeof(float) * (outputNeurons.NumberOfUnits * inputNeurons.NumberOfUnits);
int biasesBufferSize = sizeof(float) * outputNeurons.NumberOfUnits;
this.weightsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)weightBufferSize,
weightsHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
this.biasesGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)biasesBufferSize,
biasesHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
// Also create weightsGradients and biasesGradients buffers and initialize them to zero
this.weightsGradientsGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsGradientsGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesGradientsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesGradientsGPU, nOutputUnits, typeof(float));
// Also create weightsSpeed and biasesSpeed buffers and initialize them to zero
this.weightsSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsSpeedGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesSpeedGPU, nOutputUnits, typeof(float));
}
public override void SetWorkGroups()
{
// Work group sizes will be set as follows:
// global work size = smallest multiple of OPTIMAL_GROUP_SIZE larger than
// the total number of processes needed (for efficiency).
// local work size = as close as possible to OPTIMAL_GROUP_SIZE (making sure
// that global worksize is a multiple of this)
// OPTIMAL_GROUP_SIZE is a small multiple of BASE_GROUP_SIZE, which in turn is a
// constant multiple of 2, platform-dependent, e.g. 32 (Nvidia
// WARP) or 64 (AMD WAVEFRONT).
int miniBatchSize = outputNeurons.MiniBatchSize;
// FeedForward (2D) ________________________________________________________________________________
// Local
int optimalToBaseRatio = OpenCLSpace.OPTIMAL_GROUP_SIZE / OpenCLSpace.BASE_GROUP_SIZE;
this.forwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
int smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
int smallestMultiple1 = (int)(optimalToBaseRatio * Math.Ceiling((double)(miniBatchSize) / (double)optimalToBaseRatio));
this.forwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// BackPropagate (2D) _________________________________________________________________________________
// Local
this.backwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); // input this time!
this.backwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// UpdateSpeeds and UpdateParameters (2D) ________________________________________________________________
// Local
this.updateLocalWorkSizePtr = new IntPtr[] { (IntPtr)optimalToBaseRatio, (IntPtr)OpenCLSpace.BASE_GROUP_SIZE }; // product is OPTIMAL_WORK_SIZE
// Global
smallestMultiple0 = (int)(optimalToBaseRatio * Math.Ceiling((double)(nOutputUnits) / (double)optimalToBaseRatio));
smallestMultiple1 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.updateGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// Max norm constrain
this.constrainNormLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE };
int smallestMultipleAux = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.constrainNormGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultipleAux };
}
public override void CopyBuffersToHost()
{
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
weightsHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer weightsGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
biasesHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer biasesGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Speeds are not saved.
}
#endregion
#region Methods
public override void FeedForward()
{
#if TIMING_LAYERS
Utils.FCForwardTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCForward, 0, outputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 1, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 3, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 7, (IntPtr)sizeof(float), (float)dropoutParameter);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 8, (IntPtr)sizeof(ulong), (ulong)Guid.NewGuid().GetHashCode()); // this should be quite a good random seed
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 9, dropoutMaskGPU);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCForward,
2,
null,
forwardGlobalWorkSizePtr,
forwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
// TODO: add dropout CPU
// Generate dropout mask
if (dropoutParameter < 1)
{
for (int iUnit = 0; iUnit < nOutputUnits * inputNeurons.MiniBatchSize; ++iUnit)
dropoutMask[iUnit] = Global.RandomDouble() < dropoutParameter;
}
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
double[] unbiasedOutput = Utils.MultiplyMatrixByVector(weights, inputNeurons.GetHost()[m]);
this.outputNeurons.SetHost(m, unbiasedOutput.Zip(biases, (x, y) => x + y).ToArray());
}
#endif
#if TIMING_LAYERS
Utils.FCForwardTimer.Stop();
#endif
}
public override void BackPropagate()
{
#if TIMING_LAYERS
Utils.FCBackpropTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 0, inputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 1, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 3, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCBackward,
2,
null,
backwardGlobalWorkSizePtr,
backwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
inputNeurons.DeltaHost[m] = Utils.MultiplyMatrixTranspByVector(weights, outputNeurons.DeltaHost[m]);
}
#endif
#if TIMING_LAYERS
Utils.FCBackpropTimer.Stop();
#endif
}
public override void UpdateSpeeds(double learningRate, double momentumCoefficient, double weightDecayCoefficient)
{
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Start();
#endif
#if DEBUGGING_STEPBYSTEP_FC
float[,] weightsBeforeUpdate = new float[output.NumberOfUnits, input.NumberOfUnits];
/* ------------------------- DEBUGGING --------------------------------------------- */
#if OPENCL_ENABLED
// Display weights before update
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
weightsBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsBeforeUpdate");
#else
weightsBeforeUpdate = weights;
#endif
Console.WriteLine("\nWeights BEFORE update:");
for (int i = 0; i < weightsBeforeUpdate.GetLength(0); i++)
{
for (int j = 0; j < weightsBeforeUpdate.GetLength(1); j++)
Console.Write("{0} ", weightsBeforeUpdate[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display biases before update
float[] biasesBeforeUpdate = new float[output.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
biasesBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer biasesBeforeUpdate");
#else
biasesBeforeUpdate = biases;
#endif
Console.WriteLine("\nBiases BEFORE update:");
for (int i = 0; i < biasesBeforeUpdate.Length; i++)
{
Console.Write("{0} ", biasesBeforeUpdate[i]);
}
Console.WriteLine();
Console.ReadKey();
// Display weight update speed before update
float[,] tmpWeightsUpdateSpeed = new float[output.NumberOfUnits, input.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsUpdateSpeedGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
tmpWeightsUpdateSpeed, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsUpdateSpeed");
#else
tmpWeightsUpdateSpeed = weightsUpdateSpeed;
#endif
Console.WriteLine("\nWeight update speed BEFORE update:");
for (int i = 0; i < tmpWeightsUpdateSpeed.GetLength(0); i++)
{
for (int j = 0; j < tmpWeightsUpdateSpeed.GetLength(1); j++)
Console.Write("{0} ", tmpWeightsUpdateSpeed[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display input activations before update
/*
float[] inputActivations = new float[input.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
input.ActivationsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(input.NumberOfUnits * sizeof(float)),
inputActivations, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer inputActivations");
Console.WriteLine("\nInput activations BEFORE update:");
for (int j = 0; j < inputActivations.Length; j++)
{
Console.Write("{0} ", inputActivations[j]);
}
Console.WriteLine();
Console.ReadKey();
// Display output delta before update
float[] outputDelta = new float[output.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
output.DeltaGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
outputDelta, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer outputDelta");
Console.WriteLine("\nOutput delta BEFORE update:");
for (int i = 0; i < outputDelta.Length; i++)
{
Console.Write("{0}", outputDelta[i]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
*/
/*------------------------- END DEBUGGING --------------------------------------------- */
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 0, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 1, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 2, weightsGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 3, biasesGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 4, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 5, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 6, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 7, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 8, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 9, (IntPtr)sizeof(float), (float)momentumCoefficient);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 10, (IntPtr)sizeof(float), (float)learningRate);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 11, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 12, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 13, (IntPtr)sizeof(float), (float)weightDecayCoefficient);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateSpeeds,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
int miniBatchSize = inputNeurons.MiniBatchSize;
for (int m = 0; m < miniBatchSize; m++)
{
for (int i = 0; i < nOutputUnits; i++)
{
// weights speed
for (int j = 0; j < nInputUnits; j++)
{
if (m == 0)
weightsUpdateSpeed[i, j] *= momentumCoefficient;
weightsUpdateSpeed[i, j] -= learningRate/miniBatchSize * inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
weightsGradients[i, j] = inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#endif
}
// update biases
if (m == 0)
biasesUpdateSpeed[i] *= momentumCoefficient;
biasesUpdateSpeed[i] -= learningRate/miniBatchSize * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
biasesGradients[i] = outputNeurons.DeltaHost[m][i];
#endif
}
} // end loop over mini-batch
#endif
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Stop();
#endif
}
public override void UpdateParameters(double weightMaxNorm)
{
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 1, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 2, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 3, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateParameters,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
// Now constrain norm of each weight vector
if (!double.IsInfinity(weightMaxNorm))
{
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 1, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 2, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 3, (IntPtr)sizeof(float), (float)weightMaxNorm);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue,
OpenCLSpace.FCConstrainWeightNorm,
1,
null,
constrainNormGlobalWorkSizePtr,
constrainNormLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
}
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int i = 0; i < nOutputUnits; i++)
{
// weights update
for (int j = 0; j < nInputUnits; j++)
{
weights[i, j] += weightsUpdateSpeed[i, j];
}
// update biases
biases[i] += biasesUpdateSpeed[i];
}
#endif
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Stop();
#endif
}
#endregion
#region Gradient check
public override double[] GetParameters()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameters = new double[nParameters];
// Copy weights and biases buffers to host
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiases = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameters array
for (int i = 0; i < nInputUnits*nOutputUnits; ++i)
{
parameters[i] = (double)tmpWeights[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
parameters[nInputUnits * nOutputUnits + i] = (double)tmpBiases[i];
}
return parameters;
}
public override double[] GetParameterGradients()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameterGradients = new double[nParameters];
// Copy weights and biases gradients buffers to host
float[] tmpWeightsGrad = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeightsGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiasesGrad = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiasesGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameterGradients
//Console.WriteLine("Weight gradients:\n");
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
parameterGradients[i] = (double)tmpWeightsGrad[i];
//Console.Write(" {0}", tmpWeightsGrad[i]);
}
//Console.ReadKey();
for (int i = 0; i < nOutputUnits; ++i)
{
parameterGradients[nInputUnits * nOutputUnits + i] = (double)tmpBiasesGrad[i];
}
return parameterGradients;
}
public override void SetParameters(double[] NewParameters)
{
// Convert to float and write into tmp arrays
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
float[] tmpBiases = new float[nOutputUnits];
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
tmpWeights[i] = (float)NewParameters[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
tmpBiases[i] = (float)NewParameters[nInputUnits * nOutputUnits + i];
}
// Write arrays into buffers on device
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
weightsGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
biasesGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
}
#endregion
}
}
| jcredi/ConvDotNet | Conv.NET/FullyConnectedLayer.cs | C# | gpl-3.0 | 42,556 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Scanner;
use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function array_slice;
use function count;
use function is_int;
use function is_string;
use function ltrim;
use function strtolower;
use function substr_count;
use function var_export;
class MethodScanner implements ScannerInterface
{
/**
* @var bool
*/
protected $isScanned = false;
/**
* @var string
*/
protected $docComment;
/**
* @var ClassScanner
*/
protected $scannerClass;
/**
* @var string
*/
protected $class;
/**
* @var string
*/
protected $name;
/**
* @var int
*/
protected $lineStart;
/**
* @var int
*/
protected $lineEnd;
/**
* @var bool
*/
protected $isFinal = false;
/**
* @var bool
*/
protected $isAbstract = false;
/**
* @var bool
*/
protected $isPublic = true;
/**
* @var bool
*/
protected $isProtected = false;
/**
* @var bool
*/
protected $isPrivate = false;
/**
* @var bool
*/
protected $isStatic = false;
/**
* @var string
*/
protected $body = '';
/**
* @var array
*/
protected $tokens = [];
/**
* @var NameInformation
*/
protected $nameInformation;
/**
* @var array
*/
protected $infos = [];
/**
* @param array $methodTokens
* @param NameInformation $nameInformation
*/
public function __construct(array $methodTokens, NameInformation $nameInformation = null)
{
$this->tokens = $methodTokens;
$this->nameInformation = $nameInformation;
}
/**
* @param string $class
* @return MethodScanner
*/
public function setClass($class)
{
$this->class = (string) $class;
return $this;
}
/**
* @param ClassScanner $scannerClass
* @return MethodScanner
*/
public function setScannerClass(ClassScanner $scannerClass)
{
$this->scannerClass = $scannerClass;
return $this;
}
/**
* @return ClassScanner
*/
public function getClassScanner()
{
return $this->scannerClass;
}
/**
* @return string
*/
public function getName()
{
$this->scan();
return $this->name;
}
/**
* @return int
*/
public function getLineStart()
{
$this->scan();
return $this->lineStart;
}
/**
* @return int
*/
public function getLineEnd()
{
$this->scan();
return $this->lineEnd;
}
/**
* @return string
*/
public function getDocComment()
{
$this->scan();
return $this->docComment;
}
/**
* @param AnnotationManager $annotationManager
* @return AnnotationScanner|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
if (($docComment = $this->getDocComment()) == '') {
return false;
}
return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation);
}
/**
* @return bool
*/
public function isFinal()
{
$this->scan();
return $this->isFinal;
}
/**
* @return bool
*/
public function isAbstract()
{
$this->scan();
return $this->isAbstract;
}
/**
* @return bool
*/
public function isPublic()
{
$this->scan();
return $this->isPublic;
}
/**
* @return bool
*/
public function isProtected()
{
$this->scan();
return $this->isProtected;
}
/**
* @return bool
*/
public function isPrivate()
{
$this->scan();
return $this->isPrivate;
}
/**
* @return bool
*/
public function isStatic()
{
$this->scan();
return $this->isStatic;
}
/**
* Override the given name for a method, this is necessary to
* support traits.
*
* @param string $name
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Visibility must be of T_PUBLIC, T_PRIVATE or T_PROTECTED
* Needed to support traits
*
* @param int $visibility T_PUBLIC | T_PRIVATE | T_PROTECTED
* @return self
* @throws \Zend\Code\Exception\InvalidArgumentException
*/
public function setVisibility($visibility)
{
switch ($visibility) {
case T_PUBLIC:
$this->isPublic = true;
$this->isPrivate = false;
$this->isProtected = false;
break;
case T_PRIVATE:
$this->isPublic = false;
$this->isPrivate = true;
$this->isProtected = false;
break;
case T_PROTECTED:
$this->isPublic = false;
$this->isPrivate = false;
$this->isProtected = true;
break;
default:
throw new Exception\InvalidArgumentException('Invalid visibility argument passed to setVisibility.');
}
return $this;
}
/**
* @return int
*/
public function getNumberOfParameters()
{
return count($this->getParameters());
}
/**
* @param bool $returnScanner
* @return array
*/
public function getParameters($returnScanner = false)
{
$this->scan();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'parameter') {
continue;
}
if (! $returnScanner) {
$return[] = $info['name'];
} else {
$return[] = $this->getParameter($info['name']);
}
}
return $return;
}
/**
* @param int|string $parameterNameOrInfoIndex
* @return ParameterScanner
* @throws Exception\InvalidArgumentException
*/
public function getParameter($parameterNameOrInfoIndex)
{
$this->scan();
if (is_int($parameterNameOrInfoIndex)) {
$info = $this->infos[$parameterNameOrInfoIndex];
if ($info['type'] != 'parameter') {
throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter');
}
} elseif (is_string($parameterNameOrInfoIndex)) {
foreach ($this->infos as $info) {
if ($info['type'] === 'parameter' && $info['name'] === $parameterNameOrInfoIndex) {
break;
}
unset($info);
}
if (! isset($info)) {
throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter');
}
}
$p = new ParameterScanner(
array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart']),
$this->nameInformation
);
$p->setDeclaringFunction($this->name);
$p->setDeclaringScannerFunction($this);
$p->setDeclaringClass($this->class);
$p->setDeclaringScannerClass($this->scannerClass);
$p->setPosition($info['position']);
return $p;
}
/**
* @return string
*/
public function getBody()
{
$this->scan();
return $this->body;
}
public static function export()
{
// @todo
}
public function __toString()
{
$this->scan();
return var_export($this, true);
}
protected function scan()
{
if ($this->isScanned) {
return;
}
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
/**
* Variables & Setup
*/
$tokens = &$this->tokens; // localize
$infos = &$this->infos; // localize
$tokenIndex = null;
$token = null;
$tokenType = null;
$tokenContent = null;
$tokenLine = null;
$infoIndex = 0;
$parentCount = 0;
/*
* MACRO creation
*/
$MACRO_TOKEN_ADVANCE = function () use (
&$tokens,
&$tokenIndex,
&$token,
&$tokenType,
&$tokenContent,
&$tokenLine
) {
static $lastTokenArray = null;
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
if (! isset($tokens[$tokenIndex])) {
$token = false;
$tokenContent = false;
$tokenType = false;
$tokenLine = false;
return false;
}
$token = $tokens[$tokenIndex];
if (is_string($token)) {
$tokenType = null;
$tokenContent = $token;
$tokenLine += substr_count(
$lastTokenArray[1] ?? '',
"\n"
); // adjust token line by last known newline count
} else {
$lastTokenArray = $token;
[$tokenType, $tokenContent, $tokenLine] = $token;
}
return $tokenIndex;
};
$MACRO_INFO_START = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex] = [
'type' => 'parameter',
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
'lineStart' => $tokenLine,
'lineEnd' => $tokenLine,
'name' => null,
'position' => $infoIndex + 1, // position is +1 of infoIndex
];
};
$MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex]['tokenEnd'] = $tokenIndex;
$infos[$infoIndex]['lineEnd'] = $tokenLine;
$infoIndex++;
return $infoIndex;
};
/**
* START FINITE STATE MACHINE FOR SCANNING TOKENS
*/
// Initialize token
$MACRO_TOKEN_ADVANCE();
SCANNER_TOP:
$this->lineStart = $this->lineStart ? : $tokenLine;
switch ($tokenType) {
case T_DOC_COMMENT:
$this->lineStart = null;
if ($this->docComment === null && $this->name === null) {
$this->docComment = $tokenContent;
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_FINAL:
$this->isFinal = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_ABSTRACT:
$this->isAbstract = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PUBLIC:
// use defaults
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PROTECTED:
$this->setVisibility(T_PROTECTED);
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PRIVATE:
$this->setVisibility(T_PRIVATE);
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_STATIC:
$this->isStatic = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_NS_SEPARATOR:
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_VARIABLE:
case T_STRING:
if ($tokenType === T_STRING && $parentCount === 0) {
$this->name = $tokenContent;
}
if ($parentCount === 1) {
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
if ($tokenType === T_VARIABLE) {
$infos[$infoIndex]['name'] = ltrim($tokenContent, '$');
}
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case null:
switch ($tokenContent) {
case '&':
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case '(':
$parentCount++;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case ')':
$parentCount--;
if ($parentCount > 0) {
goto SCANNER_CONTINUE_SIGNATURE;
}
if ($parentCount === 0) {
if ($infos) {
$MACRO_INFO_ADVANCE();
}
$context = 'body';
}
goto SCANNER_CONTINUE_BODY;
// goto (no break needed);
case ',':
if ($parentCount === 1) {
$MACRO_INFO_ADVANCE();
}
goto SCANNER_CONTINUE_SIGNATURE;
}
}
SCANNER_CONTINUE_SIGNATURE:
if ($MACRO_TOKEN_ADVANCE() === false) {
goto SCANNER_END;
}
goto SCANNER_TOP;
SCANNER_CONTINUE_BODY:
$braceCount = 0;
while ($MACRO_TOKEN_ADVANCE() !== false) {
if ($tokenContent == '}') {
$braceCount--;
}
if ($braceCount > 0) {
$this->body .= $tokenContent;
}
if ($tokenContent == '{') {
$braceCount++;
}
$this->lineEnd = $tokenLine;
}
SCANNER_END:
$this->isScanned = true;
}
}
| monocasual/giada-www | src/forum/vendor/zendframework/zend-code/src/Scanner/MethodScanner.php | PHP | gpl-3.0 | 15,018 |
/*
Copyright 2013 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
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 com.redhat.lightblue.config;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.redhat.lightblue.Request;
import com.redhat.lightblue.crud.DeleteRequest;
import com.redhat.lightblue.util.test.FileUtil;
import static com.redhat.lightblue.util.JsonUtils.json;
public class CrudValidationTest {
@Test
public void testValidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testValidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
try {
lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.fail();
} catch (Exception e) {
System.out.println(e);
}
}
}
| bserdar/lightblue-core | config/src/test/java/com/redhat/lightblue/config/CrudValidationTest.java | Java | gpl-3.0 | 3,200 |
/*
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/>.
*/
/*
control code for tailsitters. Enabled by setting Q_FRAME_CLASS=10
*/
#include "Plane.h"
/*
return true when flying a tailsitter
*/
bool QuadPlane::is_tailsitter(void)
{
return available() && frame_class == AP_Motors::MOTOR_FRAME_TAILSITTER;
}
/*
check if we are flying as a tailsitter
*/
bool QuadPlane::tailsitter_active(void)
{
return is_tailsitter() && in_vtol_mode();
}
/*
run output for tailsitters
*/
void QuadPlane::tailsitter_output(void)
{
if (!is_tailsitter()) {
return;
}
if (!tailsitter_active()) {
if (tailsitter.vectored_forward_gain > 0) {
// thrust vectoring in fixed wing flight
float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron);
float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator);
float tilt_left = (elevator + aileron) * tailsitter.vectored_forward_gain;
float tilt_right = (elevator - aileron) * tailsitter.vectored_forward_gain;
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right);
} else {
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, 0);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, 0);
}
return;
}
motors_output();
plane.pitchController.reset_I();
plane.rollController.reset_I();
if (tailsitter.vectored_hover_gain > 0) {
// thrust vectoring VTOL modes
float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron);
float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator);
float tilt_left = (elevator + aileron) * tailsitter.vectored_hover_gain;
float tilt_right = (elevator - aileron) * tailsitter.vectored_hover_gain;
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right);
}
if (tailsitter.input_mask_chan > 0 &&
tailsitter.input_mask > 0 &&
hal.rcin->read(tailsitter.input_mask_chan-1) > 1700) {
// the user is learning to prop-hang
if (tailsitter.input_mask & TAILSITTER_MASK_AILERON) {
SRV_Channels::set_output_scaled(SRV_Channel::k_aileron, plane.channel_roll->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_ELEVATOR) {
SRV_Channels::set_output_scaled(SRV_Channel::k_elevator, plane.channel_pitch->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_THROTTLE) {
SRV_Channels::set_output_scaled(SRV_Channel::k_throttle, plane.channel_throttle->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_RUDDER) {
SRV_Channels::set_output_scaled(SRV_Channel::k_rudder, plane.channel_rudder->get_control_in_zero_dz());
}
}
}
/*
return true when we have completed enough of a transition to switch to fixed wing control
*/
bool QuadPlane::tailsitter_transition_complete(void)
{
if (plane.fly_inverted()) {
// transition immediately
return true;
}
if (labs(ahrs_view->pitch_sensor) > tailsitter.transition_angle*100 ||
labs(ahrs_view->roll_sensor) > tailsitter.transition_angle*100 ||
AP_HAL::millis() - transition_start_ms > 2000) {
return true;
}
// still waiting
return false;
}
// handle different tailsitter input types
void QuadPlane::tailsitter_check_input(void)
{
if (tailsitter_active() &&
tailsitter.input_type == TAILSITTER_INPUT_PLANE) {
// the user has asked for body frame controls when tailsitter
// is active. We switch around the control_in value for the
// channels to do this, as that ensures the value is
// consistent throughout the code
int16_t roll_in = plane.channel_roll->get_control_in();
int16_t yaw_in = plane.channel_rudder->get_control_in();
plane.channel_roll->set_control_in(yaw_in);
plane.channel_rudder->set_control_in(-roll_in);
}
}
| ChristopherOlson/ArduHeli | ArduPlane/tailsitter.cpp | C++ | gpl-3.0 | 4,878 |
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "HeadSpin.h"
#include "plComponent.h"
#include "plComponentReg.h"
#include "plMiscComponents.h"
#include "MaxMain/plMaxNode.h"
#include "resource.h"
#include <iparamm2.h>
#pragma hdrstop
#include "MaxMain/plPlasmaRefMsgs.h"
#include "pnSceneObject/plSceneObject.h"
#include "pnSceneObject/plCoordinateInterface.h"
#include "pnSceneObject/plDrawInterface.h"
#include "plMessage/plSimStateMsg.h"
#include "pnMessage/plEnableMsg.h"
#include "MaxMain/plPluginResManager.h"
void DummyCodeIncludeFuncIgnore() {}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Ignore Component
//
//
//Class that accesses the paramblock below.
class plIgnoreComponent : public plComponent
{
public:
plIgnoreComponent();
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
virtual void CollectNonDrawables(INodeTab& nonDrawables);
};
//Max desc stuff necessary below.
CLASS_DESC(plIgnoreComponent, gIgnoreDesc, "Ignore", "Ignore", COMP_TYPE_IGNORE, Class_ID(0x48326288, 0x528a3dea))
enum
{
kIgnoreMeCheckBx
};
ParamBlockDesc2 gIgnoreBk
(
plComponent::kBlkComp, _T("Ignore"), 0, &gIgnoreDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_IGNORE, IDS_COMP_IGNORES, 0, 0, NULL,
kIgnoreMeCheckBx, _T("Ignore"), TYPE_BOOL, 0, 0,
p_default, TRUE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORE_CKBX,
end,
end
);
plIgnoreComponent::plIgnoreComponent()
{
fClassDesc = &gIgnoreDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
void plIgnoreComponent::CollectNonDrawables(INodeTab& nonDrawables)
{
if (fCompPB->GetInt(kIgnoreMeCheckBx))
{
AddTargetsToList(nonDrawables);
}
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plIgnoreComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
if (fCompPB->GetInt(kIgnoreMeCheckBx))
pNode->SetCanConvert(false);
return true;
}
bool plIgnoreComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// IgnoreLite Component
//
//
//Class that accesses the paramblock below.
class plIgnoreLiteComponent : public plComponent
{
public:
enum {
kSelectedOnly
};
enum LightState {
kTurnOn,
kTurnOff,
kToggle
};
public:
plIgnoreLiteComponent();
void SetState(LightState s);
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; }
bool PreConvert(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; }
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; }
};
class plIgnoreLiteProc : public ParamMap2UserDlgProc
{
public:
BOOL DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_COMMAND:
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_ON) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kTurnOn);
return TRUE;
}
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_OFF) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kTurnOff);
return TRUE;
}
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_TOGGLE) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kToggle);
return TRUE;
}
break;
}
return false;
}
void DeleteThis() {}
};
static plIgnoreLiteProc gIgnoreLiteProc;
//Max desc stuff necessary below.
CLASS_DESC(plIgnoreLiteComponent, gIgnoreLiteDesc, "Control Max Light", "ControlLite", COMP_TYPE_IGNORE, IGNORELITE_CID)
ParamBlockDesc2 gIgnoreLiteBk
(
plComponent::kBlkComp, _T("IgnoreLite"), 0, &gIgnoreLiteDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_IGNORELITE, IDS_COMP_IGNORELITES, 0, 0, &gIgnoreLiteProc,
plIgnoreLiteComponent::kSelectedOnly, _T("SelectedOnly"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORELITE_SELECTED,
end,
end
);
plIgnoreLiteComponent::plIgnoreLiteComponent()
{
fClassDesc = &gIgnoreLiteDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
void plIgnoreLiteComponent::SetState(LightState s)
{
BOOL selectedOnly = fCompPB->GetInt(kSelectedOnly);
int numTarg = NumTargets();
int i;
for( i = 0; i < numTarg; i++ )
{
plMaxNodeBase* targ = GetTarget(i);
if( targ )
{
if( selectedOnly && !targ->Selected() )
continue;
Object *obj = targ->EvalWorldState(TimeValue(0)).obj;
if (obj && (obj->SuperClassID() == SClass_ID(LIGHT_CLASS_ID)))
{
LightObject* liObj = (LightObject*)obj;
switch( s )
{
case kTurnOn:
liObj->SetUseLight(true);
break;
case kTurnOff:
liObj->SetUseLight(false);
break;
case kToggle:
liObj->SetUseLight(!liObj->GetUseLight());
break;
}
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Barney Component
//
//
//Class that accesses the paramblock below.
class plBarneyComponent : public plComponent
{
public:
plBarneyComponent();
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
};
//Max desc stuff necessary below.
CLASS_DESC(plBarneyComponent, gBarneyDesc, "Barney", "Barney", COMP_TYPE_IGNORE, Class_ID(0x376955dc, 0x2fec50ae))
ParamBlockDesc2 gBarneyBk
(
plComponent::kBlkComp, _T("Barney"), 0, &gBarneyDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_BARNEY, IDS_COMP_BARNEYS, 0, 0, NULL,
end
);
plBarneyComponent::plBarneyComponent()
{
fClassDesc = &gBarneyDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plBarneyComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
pNode->SetCanConvert(false);
pNode->SetIsBarney(true);
return true;
}
bool plBarneyComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// NoShow Component
//
//
//Class that accesses the paramblock below.
class plNoShowComponent : public plComponent
{
public:
enum
{
kShowable,
kAffectDraw,
kAffectPhys
};
public:
plNoShowComponent();
virtual void CollectNonDrawables(INodeTab& nonDrawables);
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
};
const Class_ID COMP_NOSHOW_CID(0x41cb2b85, 0x615932c6);
//Max desc stuff necessary below.
CLASS_DESC(plNoShowComponent, gNoShowDesc, "NoShow", "NoShow", COMP_TYPE_IGNORE, COMP_NOSHOW_CID)
ParamBlockDesc2 gNoShowBk
(
plComponent::kBlkComp, _T("NoShow"), 0, &gNoShowDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_NOSHOW, IDS_COMP_NOSHOW, 0, 0, NULL,
plNoShowComponent::kShowable, _T("Showable"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_SHOWABLE,
end,
plNoShowComponent::kAffectDraw, _T("AffectDraw"), TYPE_BOOL, 0, 0,
p_default, TRUE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTDRAW,
end,
plNoShowComponent::kAffectPhys, _T("AffectPhys"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTPHYS,
end,
end
);
plNoShowComponent::plNoShowComponent()
{
fClassDesc = &gNoShowDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plNoShowComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
if( !fCompPB->GetInt(kShowable) )
{
if( fCompPB->GetInt(kAffectDraw) )
pNode->SetDrawable(false);
if( fCompPB->GetInt(kAffectPhys) )
pNode->SetPhysical(false);
}
return true;
}
bool plNoShowComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
plSceneObject* obj = node->GetSceneObject();
if( !obj )
return true;
if( fCompPB->GetInt(kShowable) )
{
if( fCompPB->GetInt(kAffectDraw) )
{
plEnableMsg* eMsg = new plEnableMsg(nil, plEnableMsg::kDisable, plEnableMsg::kDrawable);
eMsg->AddReceiver(obj->GetKey());
eMsg->Send();
}
if( fCompPB->GetInt(kAffectPhys) )
{
hsAssert(0, "Who uses this?");
// plEventGroupEnableMsg* pMsg = new plEventGroupEnableMsg;
// pMsg->SetFlags(plEventGroupEnableMsg::kCollideOff | plEventGroupEnableMsg::kReportOff);
// pMsg->AddReceiver(obj->GetKey());
// pMsg->Send();
}
#if 0
plDrawInterface* di = node->GetDrawInterface();
if( di &&
{
di->SetProperty(plDrawInterface::kDisable, true);
}
#endif
}
return true;
}
void plNoShowComponent::CollectNonDrawables(INodeTab& nonDrawables)
{
if( fCompPB->GetInt(kAffectDraw) )
AddTargetsToList(nonDrawables);
}
| Lyrositor/Plasma | Sources/Tools/MaxComponent/plIgnoreComponent.cpp | C++ | gpl-3.0 | 12,779 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "branchmodel.h"
#include "gitclient.h"
#include <utils/qtcassert.h>
#include <vcsbase/vcsoutputwindow.h>
#include <vcsbase/vcscommand.h>
#include <QFont>
using namespace VcsBase;
namespace Git {
namespace Internal {
enum RootNodes {
LocalBranches = 0,
RemoteBranches = 1,
Tags = 2
};
// --------------------------------------------------------------------------
// BranchNode:
// --------------------------------------------------------------------------
class BranchNode
{
public:
BranchNode() :
parent(0),
name(QLatin1String("<ROOT>"))
{ }
BranchNode(const QString &n, const QString &s = QString(), const QString &t = QString()) :
parent(0), name(n), sha(s), tracking(t)
{ }
~BranchNode()
{
while (!children.isEmpty())
delete children.first();
if (parent)
parent->children.removeAll(this);
}
BranchNode *rootNode() const
{
return parent ? parent->rootNode() : const_cast<BranchNode *>(this);
}
int count() const
{
return children.count();
}
bool isLeaf() const
{
return children.isEmpty() && parent && parent->parent;
}
bool childOf(BranchNode *node) const
{
if (this == node)
return true;
return parent ? parent->childOf(node) : false;
}
bool childOfRoot(RootNodes root) const
{
BranchNode *rn = rootNode();
if (rn->isLeaf())
return false;
if (root >= rn->children.count())
return false;
return childOf(rn->children.at(root));
}
bool isTag() const
{
return childOfRoot(Tags);
}
bool isLocal() const
{
return childOfRoot(LocalBranches);
}
BranchNode *childOfName(const QString &name) const
{
for (int i = 0; i < children.count(); ++i) {
if (children.at(i)->name == name)
return children.at(i);
}
return 0;
}
QStringList fullName(bool includePrefix = false) const
{
QTC_ASSERT(isLeaf(), return QStringList());
QStringList fn;
QList<const BranchNode *> nodes;
const BranchNode *current = this;
while (current->parent) {
nodes.prepend(current);
current = current->parent;
}
if (includePrefix)
fn.append(nodes.first()->sha);
nodes.removeFirst();
foreach (const BranchNode *n, nodes)
fn.append(n->name);
return fn;
}
void insert(const QStringList &path, BranchNode *n)
{
BranchNode *current = this;
for (int i = 0; i < path.count(); ++i) {
BranchNode *c = current->childOfName(path.at(i));
if (c)
current = c;
else
current = current->append(new BranchNode(path.at(i)));
}
current->append(n);
}
BranchNode *append(BranchNode *n)
{
n->parent = this;
children.append(n);
return n;
}
QStringList childrenNames() const
{
if (children.count() > 0) {
QStringList names;
foreach (BranchNode *n, children) {
names.append(n->childrenNames());
}
return names;
}
return QStringList(fullName().join(QLatin1Char('/')));
}
int rowOf(BranchNode *node)
{
return children.indexOf(node);
}
BranchNode *parent;
QList<BranchNode *> children;
QString name;
QString sha;
QString tracking;
mutable QString toolTip;
};
// --------------------------------------------------------------------------
// BranchModel:
// --------------------------------------------------------------------------
BranchModel::BranchModel(GitClient *client, QObject *parent) :
QAbstractItemModel(parent),
m_client(client),
m_rootNode(new BranchNode),
m_currentBranch(0)
{
QTC_CHECK(m_client);
// Abuse the sha field for ref prefix
m_rootNode->append(new BranchNode(tr("Local Branches"), QLatin1String("refs/heads")));
m_rootNode->append(new BranchNode(tr("Remote Branches"), QLatin1String("refs/remotes")));
}
BranchModel::~BranchModel()
{
delete m_rootNode;
}
QModelIndex BranchModel::index(int row, int column, const QModelIndex &parentIdx) const
{
if (column != 0)
return QModelIndex();
BranchNode *parentNode = indexToNode(parentIdx);
if (row >= parentNode->count())
return QModelIndex();
return nodeToIndex(parentNode->children.at(row));
}
QModelIndex BranchModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
BranchNode *node = indexToNode(index);
if (node->parent == m_rootNode)
return QModelIndex();
return nodeToIndex(node->parent);
}
int BranchModel::rowCount(const QModelIndex &parentIdx) const
{
if (parentIdx.column() > 0)
return 0;
return indexToNode(parentIdx)->count();
}
int BranchModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant BranchModel::data(const QModelIndex &index, int role) const
{
BranchNode *node = indexToNode(index);
if (!node)
return QVariant();
switch (role) {
case Qt::DisplayRole: {
QString res = node->name;
if (!node->tracking.isEmpty())
res += QLatin1String(" [") + node->tracking + QLatin1Char(']');
return res;
}
case Qt::EditRole:
return node->name;
case Qt::ToolTipRole:
if (!node->isLeaf())
return QVariant();
if (node->toolTip.isEmpty())
node->toolTip = toolTip(node->sha);
return node->toolTip;
case Qt::FontRole:
{
QFont font;
if (!node->isLeaf()) {
font.setBold(true);
} else if (node == m_currentBranch) {
font.setBold(true);
font.setUnderline(true);
}
return font;
}
default:
return QVariant();
}
}
bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
BranchNode *node = indexToNode(index);
if (!node)
return false;
const QString newName = value.toString();
if (newName.isEmpty())
return false;
if (node->name == newName)
return true;
QStringList oldFullName = node->fullName();
node->name = newName;
QStringList newFullName = node->fullName();
QString output;
QString errorMessage;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m")
<< oldFullName.last()
<< newFullName.last(),
&output, &errorMessage)) {
node->name = oldFullName.last();
VcsOutputWindow::appendError(errorMessage);
return false;
}
emit dataChanged(index, index);
return true;
}
Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const
{
BranchNode *node = indexToNode(index);
if (!node)
return Qt::NoItemFlags;
if (node->isLeaf() && node->isLocal())
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
else
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
void BranchModel::clear()
{
foreach (BranchNode *root, m_rootNode->children)
while (root->count())
delete root->children.takeLast();
if (hasTags())
m_rootNode->children.takeLast();
m_currentBranch = 0;
}
bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
beginResetModel();
clear();
if (workingDirectory.isEmpty()) {
endResetModel();
return false;
}
m_currentSha = m_client->synchronousTopRevision(workingDirectory);
QStringList args;
args << QLatin1String("--format=%(objectname)\t%(refname)\t%(upstream:short)\t%(*objectname)");
QString output;
if (!m_client->synchronousForEachRefCmd(workingDirectory, args, &output, errorMessage))
VcsOutputWindow::appendError(*errorMessage);
m_workingDirectory = workingDirectory;
const QStringList lines = output.split(QLatin1Char('\n'));
foreach (const QString &l, lines)
parseOutputLine(l);
if (m_currentBranch) {
if (m_currentBranch->parent == m_rootNode->children.at(LocalBranches))
m_currentBranch = 0;
setCurrentBranch();
}
endResetModel();
return true;
}
void BranchModel::setCurrentBranch()
{
QString currentBranch = m_client->synchronousCurrentLocalBranch(m_workingDirectory);
if (currentBranch.isEmpty())
return;
BranchNode *local = m_rootNode->children.at(LocalBranches);
int pos = 0;
for (pos = 0; pos < local->count(); ++pos) {
if (local->children.at(pos)->name == currentBranch)
m_currentBranch = local->children[pos];
}
}
void BranchModel::renameBranch(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m") << oldName << newName,
&output, &errorMessage))
VcsOutputWindow::appendError(errorMessage);
else
refresh(m_workingDirectory, &errorMessage);
}
void BranchModel::renameTag(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousTagCmd(m_workingDirectory, QStringList() << newName << oldName,
&output, &errorMessage)
|| !m_client->synchronousTagCmd(m_workingDirectory,
QStringList() << QLatin1String("-d") << oldName,
&output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
} else {
refresh(m_workingDirectory, &errorMessage);
}
}
QString BranchModel::workingDirectory() const
{
return m_workingDirectory;
}
GitClient *BranchModel::client() const
{
return m_client;
}
QModelIndex BranchModel::currentBranch() const
{
if (!m_currentBranch)
return QModelIndex();
return nodeToIndex(m_currentBranch);
}
QString BranchModel::fullName(const QModelIndex &idx, bool includePrefix) const
{
if (!idx.isValid())
return QString();
BranchNode *node = indexToNode(idx);
if (!node || !node->isLeaf())
return QString();
QStringList path = node->fullName(includePrefix);
return path.join(QLatin1Char('/'));
}
QStringList BranchModel::localBranchNames() const
{
if (!m_rootNode || !m_rootNode->count())
return QStringList();
return m_rootNode->children.at(LocalBranches)->childrenNames();
}
QString BranchModel::sha(const QModelIndex &idx) const
{
if (!idx.isValid())
return QString();
BranchNode *node = indexToNode(idx);
return node->sha;
}
bool BranchModel::hasTags() const
{
return m_rootNode->children.count() > Tags;
}
bool BranchModel::isLocal(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
BranchNode *node = indexToNode(idx);
return node->isLocal();
}
bool BranchModel::isLeaf(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
BranchNode *node = indexToNode(idx);
return node->isLeaf();
}
bool BranchModel::isTag(const QModelIndex &idx) const
{
if (!idx.isValid() || !hasTags())
return false;
return indexToNode(idx)->isTag();
}
void BranchModel::removeBranch(const QModelIndex &idx)
{
QString branch = fullName(idx);
if (branch.isEmpty())
return;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-D") << branch;
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
removeNode(idx);
}
void BranchModel::removeTag(const QModelIndex &idx)
{
QString tag = fullName(idx);
if (tag.isEmpty())
return;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-d") << tag;
if (!m_client->synchronousTagCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
removeNode(idx);
}
void BranchModel::checkoutBranch(const QModelIndex &idx)
{
QString branch = fullName(idx, !isLocal(idx));
if (branch.isEmpty())
return;
// No StashGuard since this function for now is only used with clean working dir.
// If it is ever used from another place, please add StashGuard here
m_client->synchronousCheckout(m_workingDirectory, branch);
}
bool BranchModel::branchIsMerged(const QModelIndex &idx)
{
QString branch = fullName(idx);
if (branch.isEmpty())
return false;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-a") << QLatin1String("--contains") << sha(idx);
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage))
VcsOutputWindow::appendError(errorMessage);
QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts);
foreach (const QString &l, lines) {
QString currentBranch = l.mid(2); // remove first letters (those are either
// " " or "* " depending on whether it is
// the currently checked out branch or not)
if (currentBranch != branch)
return true;
}
return false;
}
static int positionForName(BranchNode *node, const QString &name)
{
int pos = 0;
for (pos = 0; pos < node->count(); ++pos) {
if (node->children.at(pos)->name >= name)
break;
}
return pos;
}
QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModelIndex &startPoint)
{
if (!m_rootNode || !m_rootNode->count())
return QModelIndex();
const QString trackedBranch = fullName(startPoint);
const QString fullTrackedBranch = fullName(startPoint, true);
QString startSha;
QString output;
QString errorMessage;
QStringList args;
args << (track ? QLatin1String("--track") : QLatin1String("--no-track"));
args << name;
if (!fullTrackedBranch.isEmpty()) {
args << fullTrackedBranch;
startSha = sha(startPoint);
} else {
startSha = m_client->synchronousTopRevision(m_workingDirectory);
}
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return QModelIndex();
}
BranchNode *local = m_rootNode->children.at(LocalBranches);
const int slash = name.indexOf(QLatin1Char('/'));
const QString leafName = slash == -1 ? name : name.mid(slash + 1);
bool added = false;
if (slash != -1) {
const QString nodeName = name.left(slash);
int pos = positionForName(local, nodeName);
BranchNode *child = (pos == local->count()) ? 0 : local->children.at(pos);
if (!child || child->name != nodeName) {
child = new BranchNode(nodeName);
beginInsertRows(nodeToIndex(local), pos, pos);
added = true;
child->parent = local;
local->children.insert(pos, child);
}
local = child;
}
int pos = positionForName(local, leafName);
auto newNode = new BranchNode(leafName, startSha, track ? trackedBranch : QString());
if (!added)
beginInsertRows(nodeToIndex(local), pos, pos);
newNode->parent = local;
local->children.insert(pos, newNode);
endInsertRows();
return nodeToIndex(newNode);
}
void BranchModel::setRemoteTracking(const QModelIndex &trackingIndex)
{
QModelIndex current = currentBranch();
QTC_ASSERT(current.isValid(), return);
const QString currentName = fullName(current);
const QString shortTracking = fullName(trackingIndex);
const QString tracking = fullName(trackingIndex, true);
m_client->synchronousSetTrackingBranch(m_workingDirectory, currentName, tracking);
m_currentBranch->tracking = shortTracking;
emit dataChanged(current, current);
}
void BranchModel::parseOutputLine(const QString &line)
{
if (line.size() < 3)
return;
QStringList lineParts = line.split(QLatin1Char('\t'));
const QString shaDeref = lineParts.at(3);
const QString sha = shaDeref.isEmpty() ? lineParts.at(0) : shaDeref;
const QString fullName = lineParts.at(1);
bool current = (sha == m_currentSha);
bool showTags = m_client->settings().boolValue(GitSettings::showTagsKey);
// insert node into tree:
QStringList nameParts = fullName.split(QLatin1Char('/'));
nameParts.removeFirst(); // remove refs...
BranchNode *root = 0;
if (nameParts.first() == QLatin1String("heads")) {
root = m_rootNode->children.at(LocalBranches);
} else if (nameParts.first() == QLatin1String("remotes")) {
root = m_rootNode->children.at(RemoteBranches);
} else if (showTags && nameParts.first() == QLatin1String("tags")) {
if (!hasTags()) // Tags is missing, add it
m_rootNode->append(new BranchNode(tr("Tags"), QLatin1String("refs/tags")));
root = m_rootNode->children.at(Tags);
} else {
return;
}
nameParts.removeFirst();
// limit depth of list. Git basically only ever wants one / and considers the rest as part of
// the name.
while (nameParts.count() > 3) {
nameParts[2] = nameParts.at(2) + QLatin1Char('/') + nameParts.at(3);
nameParts.removeAt(3);
}
const QString name = nameParts.last();
nameParts.removeLast();
auto newNode = new BranchNode(name, sha, lineParts.at(2));
root->insert(nameParts, newNode);
if (current)
m_currentBranch = newNode;
}
BranchNode *BranchModel::indexToNode(const QModelIndex &index) const
{
if (index.column() > 0)
return 0;
if (!index.isValid())
return m_rootNode;
return static_cast<BranchNode *>(index.internalPointer());
}
QModelIndex BranchModel::nodeToIndex(BranchNode *node) const
{
if (node == m_rootNode)
return QModelIndex();
return createIndex(node->parent->rowOf(node), 0, static_cast<void *>(node));
}
void BranchModel::removeNode(const QModelIndex &idx)
{
QModelIndex nodeIndex = idx; // idx is a leaf, so count must be 0.
BranchNode *node = indexToNode(nodeIndex);
while (node->count() == 0 && node->parent != m_rootNode) {
BranchNode *parentNode = node->parent;
const QModelIndex parentIndex = nodeToIndex(parentNode);
const int nodeRow = nodeIndex.row();
beginRemoveRows(parentIndex, nodeRow, nodeRow);
parentNode->children.removeAt(nodeRow);
delete node;
endRemoveRows();
node = parentNode;
nodeIndex = parentIndex;
}
}
QString BranchModel::toolTip(const QString &sha) const
{
// Show the sha description excluding diff as toolTip
QString output;
QString errorMessage;
QStringList arguments(QLatin1String("-n1"));
arguments << sha;
if (!m_client->synchronousLog(m_workingDirectory, arguments, &output, &errorMessage,
VcsCommand::SuppressCommandLogging)) {
return errorMessage;
}
return output;
}
} // namespace Internal
} // namespace Git
| frostasm/qt-creator | src/plugins/git/branchmodel.cpp | C++ | gpl-3.0 | 21,355 |
package com.github.bordertech.wcomponents.examples;
import com.github.bordertech.wcomponents.RadioButtonGroup;
import com.github.bordertech.wcomponents.Size;
import com.github.bordertech.wcomponents.WLabel;
import com.github.bordertech.wcomponents.WPanel;
import com.github.bordertech.wcomponents.WRadioButton;
import com.github.bordertech.wcomponents.layout.FlowLayout;
import com.github.bordertech.wcomponents.layout.FlowLayout.Alignment;
/**
* {@link WRadioButton} example.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
public class RadioButtonExample extends WPanel {
/**
* Creates a RadioButtonExample.
*/
public RadioButtonExample() {
this.setLayout(new FlowLayout(Alignment.VERTICAL));
WPanel panel = new WPanel();
RadioButtonGroup group1 = new RadioButtonGroup();
panel.add(group1);
WRadioButton rb1 = group1.addRadioButton(1);
panel.add(new WLabel("Default", rb1));
panel.add(rb1);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group2 = new RadioButtonGroup();
panel.add(group2);
WRadioButton rb2 = group2.addRadioButton(1);
rb2.setSelected(true);
panel.add(new WLabel("Initially selected", rb2));
panel.add(rb2);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group3 = new RadioButtonGroup();
panel.add(group3);
WRadioButton rb3 = group3.addRadioButton(1);
rb3.setDisabled(true);
rb3.setToolTip("This is disabled.");
panel.add(new WLabel("Disabled", rb3));
panel.add(rb3);
this.add(panel);
RadioButtonGroup group = new RadioButtonGroup();
WRadioButton rb4 = group.addRadioButton("A");
WRadioButton rb5 = group.addRadioButton("B");
WRadioButton rb6 = group.addRadioButton("C");
panel = new WPanel();
panel.setLayout(new FlowLayout(Alignment.LEFT, Size.MEDIUM));
add(new WLabel("Group"));
panel.add(new WLabel("A", rb4));
panel.add(rb4);
panel.add(new WLabel("B", rb5));
panel.add(rb5);
panel.add(new WLabel("C", rb6));
panel.add(rb6);
panel.add(group);
this.add(panel);
}
}
| bordertechorg/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/RadioButtonExample.java | Java | gpl-3.0 | 2,008 |
/*
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2016 Crafter Software Corporation.
*
* 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.craftercms.studio.impl.v1.service.activity;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.craftercms.commons.validation.annotations.param.ValidateIntegerParam;
import org.craftercms.commons.validation.annotations.param.ValidateParams;
import org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam;
import org.craftercms.commons.validation.annotations.param.ValidateStringParam;
import org.craftercms.studio.api.v1.constant.StudioConstants;
import org.craftercms.studio.api.v1.constant.DmConstants;
import org.craftercms.studio.api.v1.dal.AuditFeed;
import org.craftercms.studio.api.v1.dal.AuditFeedMapper;
import org.craftercms.studio.api.v1.exception.ServiceException;
import org.craftercms.studio.api.v1.exception.SiteNotFoundException;
import org.craftercms.studio.api.v1.log.Logger;
import org.craftercms.studio.api.v1.log.LoggerFactory;
import org.craftercms.studio.api.v1.service.AbstractRegistrableService;
import org.craftercms.studio.api.v1.service.activity.ActivityService;
import org.craftercms.studio.api.v1.service.content.ContentService;
import org.craftercms.studio.api.v1.service.deployment.DeploymentService;
import org.craftercms.studio.api.v1.service.objectstate.State;
import org.craftercms.studio.api.v1.service.site.SiteService;
import org.craftercms.studio.api.v1.to.ContentItemTO;
import org.craftercms.studio.api.v1.util.DebugUtils;
import org.craftercms.studio.api.v1.util.StudioConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.craftercms.studio.api.v1.service.security.SecurityService;
import static org.craftercms.studio.api.v1.constant.StudioConstants.CONTENT_TYPE_PAGE;
import static org.craftercms.studio.api.v1.util.StudioConfiguration.ACTIVITY_USERNAME_CASE_SENSITIVE;
public class ActivityServiceImpl extends AbstractRegistrableService implements ActivityService {
private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
protected static final int MAX_LEN_USER_ID = 255; // needs to match schema:
// feed_user_id,
// post_user_id
protected static final int MAX_LEN_SITE_ID = 255; // needs to match schema:
// site_network
protected static final int MAX_LEN_ACTIVITY_TYPE = 255; // needs to match
// schema:
// activity_type
protected static final int MAX_LEN_ACTIVITY_DATA = 4000; // needs to match
// schema:
// activity_data
protected static final int MAX_LEN_APP_TOOL_ID = 36; // needs to match
// schema: app_tool
/** activity post properties **/
protected static final String ACTIVITY_PROP_ACTIVITY_SUMMARY = "activitySummary";
protected static final String ACTIVITY_PROP_ID = "id";
protected static final String ACTIVITY_PROP_POST_DATE = "postDate";
protected static final String ACTIVITY_PROP_USER = "user";
protected static final String ACTIVITY_PROP_FEEDUSER = "feedUserId";
protected static final String ACTIVITY_PROP_CONTENTID = "contentId";
/** activity feed format **/
protected static final String ACTIVITY_FEED_FORMAT = "json";
@Autowired
protected AuditFeedMapper auditFeedMapper;
protected SiteService siteService;
protected ContentService contentService;
protected SecurityService securityService;
protected StudioConfiguration studioConfiguration;
protected DeploymentService deploymentService;
@Override
public void register() {
getServicesManager().registerService(ActivityService.class, this);
}
@Override
@ValidateParams
public void postActivity(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateSecurePathParam(name = "contentId") String contentId, ActivityType activity, ActivitySource source, Map<String,String> extraInfo) {
JSONObject activityPost = new JSONObject();
activityPost.put(ACTIVITY_PROP_USER, user);
activityPost.put(ACTIVITY_PROP_ID, contentId);
if (extraInfo != null) {
activityPost.putAll(extraInfo);
}
String contentType = null;
if (extraInfo != null) {
contentType = extraInfo.get(DmConstants.KEY_CONTENT_TYPE);
}
postActivity(activity.toString(), source.toString(), site, null, activityPost.toString(),contentId,contentType, user);
}
private void postActivity(String activityType, String activitySource, String siteNetwork, String appTool, String activityData,
String contentId, String contentType, String approver) {
String currentUser = (StringUtils.isEmpty(approver)) ? securityService.getCurrentUser() : approver;
try {
// optional - default to empty string
if (siteNetwork == null) {
siteNetwork = "";
} else if (siteNetwork.length() > MAX_LEN_SITE_ID) {
throw new ServiceException("Invalid site network - exceeds " + MAX_LEN_SITE_ID + " chars: "
+ siteNetwork);
}
// optional - default to empty string
if (appTool == null) {
appTool = "";
} else if (appTool.length() > MAX_LEN_APP_TOOL_ID) {
throw new ServiceException("Invalid app tool - exceeds " + MAX_LEN_APP_TOOL_ID + " chars: " + appTool);
}
// required
if (StringUtils.isEmpty(activityType)) {
throw new ServiceException("Invalid activity type - activity type is empty");
} else if (activityType.length() > MAX_LEN_ACTIVITY_TYPE) {
throw new ServiceException("Invalid activity type - exceeds " + MAX_LEN_ACTIVITY_TYPE + " chars: "
+ activityType);
}
// optional - default to empty string
if (activityData == null) {
activityData = "";
} else if (activityType.length() > MAX_LEN_ACTIVITY_DATA) {
throw new ServiceException("Invalid activity data - exceeds " + MAX_LEN_ACTIVITY_DATA + " chars: "
+ activityData);
}
// required
if (StringUtils.isEmpty(currentUser)) {
throw new ServiceException("Invalid user - user is empty");
} else if (currentUser.length() > MAX_LEN_USER_ID) {
throw new ServiceException("Invalid user - exceeds " + MAX_LEN_USER_ID + " chars: " + currentUser);
} else {
// user names are not case-sensitive
currentUser = currentUser.toLowerCase();
}
if (contentType == null) {
contentType = CONTENT_TYPE_PAGE;
}
} catch (ServiceException e) {
// log error and throw exception
logger.error("Error in getting feeds", e);
}
try {
ZonedDateTime postDate = ZonedDateTime.now(ZoneOffset.UTC);
AuditFeed activityPost = new AuditFeed();
activityPost.setUserId(currentUser);
activityPost.setSiteNetwork(siteNetwork);
activityPost.setSummary(activityData);
activityPost.setType(activityType);
activityPost.setCreationDate(postDate);
activityPost.setModifiedDate(postDate);
activityPost.setSummaryFormat("json");
activityPost.setContentId(contentId);
activityPost.setContentType(contentType);
activityPost.setSource(activitySource);
try {
activityPost.setCreationDate(ZonedDateTime.now(ZoneOffset.UTC));
long postId = insertFeedEntry(activityPost);
activityPost.setId(postId);
logger.debug("Posted: " + activityPost);
} catch (Exception e) {
throw new ServiceException("Failed to post activity: " + e, e);
}
}
catch (ServiceException e) {
// log error, subsume exception (for post activity)
logger.error("Error in posting feed", e);
}
}
private long insertFeedEntry(AuditFeed activityFeed) {
DebugUtils.addDebugStack(logger);
logger.debug("Insert activity " + activityFeed.getContentId());
Long id = auditFeedMapper.insertActivityFeed(activityFeed);
return (id != null ? id : -1);
}
@Override
@ValidateParams
public void renameContentId(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "oldUrl") String oldUrl, @ValidateSecurePathParam(name = "newUrl") String newUrl) {
DebugUtils.addDebugStack(logger);
logger.debug("Rename " + oldUrl + " to " + newUrl);
Map<String, String> params = new HashMap<String, String>();
params.put("newPath", newUrl);
params.put("site", site);
params.put("oldPath", oldUrl);
auditFeedMapper.renameContent(params);
}
@Override
@ValidateParams
public List<ContentItemTO> getActivities(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateIntegerParam(name = "num") int num, @ValidateStringParam(name = "sort") String sort, boolean ascending, boolean excludeLive, @ValidateStringParam(name = "filterType") String filterType) throws ServiceException {
int startPos = 0;
List<ContentItemTO> contentItems = new ArrayList<ContentItemTO>();
boolean hasMoreItems = true;
while(contentItems.size() < num && hasMoreItems){
int remainingItems = num - contentItems.size();
hasMoreItems = getActivityFeeds(user, site, startPos, num , filterType, excludeLive,contentItems,remainingItems);
startPos = startPos+num;
}
if(contentItems.size() > num){
return contentItems.subList(0, num);
}
return contentItems;
}
/**
*
* Returns all non-live items if hideLiveItems is true, else should return all feeds back
*
*/
protected boolean getActivityFeeds(String user, String site,int startPos, int size, String filterType,boolean hideLiveItems,List<ContentItemTO> contentItems,int remainingItem){
List<String> activityFeedEntries = new ArrayList<String>();
if (!getUserNamesAreCaseSensitive()) {
user = user.toLowerCase();
}
List<AuditFeed> activityFeeds = null;
activityFeeds = selectUserFeedEntries(user, ACTIVITY_FEED_FORMAT, site, startPos, size,
filterType, hideLiveItems);
for (AuditFeed activityFeed : activityFeeds) {
activityFeedEntries.add(activityFeed.getJSONString());
}
boolean hasMoreItems=true;
//if number of items returned is less than size it means that table has no more records
if(activityFeedEntries.size()<size){
hasMoreItems=false;
}
if (activityFeedEntries != null && activityFeedEntries.size() > 0) {
for (int index = 0; index < activityFeedEntries.size() && remainingItem!=0; index++) {
JSONObject feedObject = JSONObject.fromObject(activityFeedEntries.get(index));
String id = (feedObject.containsKey(ACTIVITY_PROP_CONTENTID)) ? feedObject.getString(ACTIVITY_PROP_CONTENTID) : "";
ContentItemTO item = createActivityItem(site, feedObject, id);
item.published = true;
item.setPublished(true);
ZonedDateTime pubDate = deploymentService.getLastDeploymentDate(site, id);
item.publishedDate = pubDate;
item.setPublishedDate(pubDate);
contentItems.add(item);
remainingItem--;
}
}
logger.debug("Total Item post live filter : " + contentItems.size() + " hasMoreItems : "+hasMoreItems);
return hasMoreItems;
}
/**
* create an activity from the given feed
*
* @param site
* @param feedObject
* @return activity
*/
protected ContentItemTO createActivityItem(String site, JSONObject feedObject, String id) {
try {
ContentItemTO item = contentService.getContentItem(site, id, 0);
if(item == null || item.isDeleted()) {
item = contentService.createDummyDmContentItemForDeletedNode(site, id);
String modifier = (feedObject.containsKey(ACTIVITY_PROP_FEEDUSER)) ? feedObject.getString(ACTIVITY_PROP_FEEDUSER) : "";
if(modifier != null && !modifier.isEmpty()) {
item.user = modifier;
}
String activitySummary = (feedObject.containsKey(ACTIVITY_PROP_ACTIVITY_SUMMARY)) ? feedObject.getString(ACTIVITY_PROP_ACTIVITY_SUMMARY) : "";
JSONObject summaryObject = JSONObject.fromObject(activitySummary);
if (summaryObject.containsKey(DmConstants.KEY_CONTENT_TYPE)) {
String contentType = (String)summaryObject.get(DmConstants.KEY_CONTENT_TYPE);
item.contentType = contentType;
}
if(summaryObject.containsKey(StudioConstants.INTERNAL_NAME)) {
String internalName = (String)summaryObject.get(StudioConstants.INTERNAL_NAME);
item.internalName = internalName;
}
if(summaryObject.containsKey(StudioConstants.BROWSER_URI)) {
String browserUri = (String)summaryObject.get(StudioConstants.BROWSER_URI);
item.browserUri = browserUri;
}
item.setLockOwner("");
}
String postDate = (feedObject.containsKey(ACTIVITY_PROP_POST_DATE)) ? feedObject.getString(ACTIVITY_PROP_POST_DATE) : "";
ZonedDateTime editedDate = ZonedDateTime.parse(postDate);
if (editedDate != null) {
item.eventDate = editedDate.withZoneSameInstant(ZoneOffset.UTC);
} else {
item.eventDate = editedDate;
}
return item;
} catch (Exception e) {
logger.error("Error fetching content item for [" + id + "]", e.getMessage());
return null;
}
}
private List<AuditFeed> selectUserFeedEntries(String feedUserId, String format, String siteId, int startPos, int feedSize, String contentType, boolean hideLiveItems) {
HashMap<String,Object> params = new HashMap<String,Object>();
params.put("userId",feedUserId);
params.put("summaryFormat",format);
params.put("siteNetwork",siteId);
params.put("startPos", startPos);
params.put("feedSize", feedSize);
params.put("activities", Arrays.asList(ActivityType.CREATED, ActivityType.DELETED, ActivityType.UPDATED, ActivityType.MOVED));
if(StringUtils.isNotEmpty(contentType) && !contentType.toLowerCase().equals("all")){
params.put("contentType",contentType.toLowerCase());
}
if (hideLiveItems) {
List<String> statesValues = new ArrayList<String>();
for (State state : State.LIVE_STATES) {
statesValues.add(state.name());
}
params.put("states", statesValues);
return auditFeedMapper.selectUserFeedEntriesHideLive(params);
} else {
return auditFeedMapper.selectUserFeedEntries(params);
}
}
@Override
@ValidateParams
public AuditFeed getDeletedActivity(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path) {
HashMap<String,String> params = new HashMap<String,String>();
params.put("contentId", path);
params.put("siteNetwork", site);
String activityType = ActivityType.DELETED.toString();
params.put("activityType", activityType);
return auditFeedMapper.getDeletedActivity(params);
}
@Override
@ValidateParams
public void deleteActivitiesForSite(@ValidateStringParam(name = "site") String site) {
Map<String, String> params = new HashMap<String, String>();
params.put("site", site);
auditFeedMapper.deleteActivitiesForSite(params);
}
@Override
@ValidateParams
public List<AuditFeed> getAuditLogForSite(@ValidateStringParam(name = "site") String site, @ValidateIntegerParam(name = "start") int start, @ValidateIntegerParam(name = "number") int number, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
params.put("start", start);
params.put("number", number);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSite(params);
}
}
@Override
@ValidateParams
public long getAuditLogForSiteTotal(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSiteTotal(params);
}
}
public boolean getUserNamesAreCaseSensitive() {
boolean toReturn = Boolean.parseBoolean(studioConfiguration.getProperty(ACTIVITY_USERNAME_CASE_SENSITIVE));
return toReturn;
}
public SiteService getSiteService() {
return siteService;
}
public void setSiteService(final SiteService siteService) {
this.siteService = siteService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public SecurityService getSecurityService() {return securityService; }
public void setSecurityService(SecurityService securityService) { this.securityService = securityService; }
public StudioConfiguration getStudioConfiguration() { return studioConfiguration; }
public void setStudioConfiguration(StudioConfiguration studioConfiguration) { this.studioConfiguration = studioConfiguration; }
public DeploymentService getDeploymentService() { return deploymentService; }
public void setDeploymentService(DeploymentService deploymentService) { this.deploymentService = deploymentService; }
}
| dejan-brkic/studio2 | src/main/java/org/craftercms/studio/impl/v1/service/activity/ActivityServiceImpl.java | Java | gpl-3.0 | 20,008 |
package org.thoughtcrime.securesms.testutil;
import org.signal.core.util.logging.Log;
public final class SystemOutLogger extends Log.Logger {
@Override
public void v(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('v', tag, message, t);
}
@Override
public void d(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('d', tag, message, t);
}
@Override
public void i(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('i', tag, message, t);
}
@Override
public void w(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('w', tag, message, t);
}
@Override
public void e(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('e', tag, message, t);
}
@Override
public void flush() { }
private void printlnFormatted(char level, String tag, String message, Throwable t) {
System.out.println(format(level, tag, message, t));
}
private String format(char level, String tag, String message, Throwable t) {
if (t != null) {
return String.format("%c[%s] %s %s:%s", level, tag, message, t.getClass().getSimpleName(), t.getMessage());
} else {
return String.format("%c[%s] %s", level, tag, message);
}
}
}
| WhisperSystems/Signal-Android | app/src/test/java/org/thoughtcrime/securesms/testutil/SystemOutLogger.java | Java | gpl-3.0 | 1,332 |
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS 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.
//
// Openbravo POS 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 Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.printer.escpos;
public class CodesIthaca extends Codes {
private static final byte[] INITSEQUENCE = {};
private static final byte[] CHAR_SIZE_0 = {0x1D, 0x21, 0x00};
private static final byte[] CHAR_SIZE_1 = {0x1D, 0x21, 0x01};
private static final byte[] CHAR_SIZE_2 = {0x1D, 0x21, 0x30};
private static final byte[] CHAR_SIZE_3 = {0x1D, 0x21, 0x31};
public static final byte[] BOLD_SET = {0x1B, 0x45, 0x01};
public static final byte[] BOLD_RESET = {0x1B, 0x45, 0x00};
public static final byte[] UNDERLINE_SET = {0x1B, 0x2D, 0x01};
public static final byte[] UNDERLINE_RESET = {0x1B, 0x2D, 0x00};
private static final byte[] OPEN_DRAWER = {0x1B, 0x78, 0x01};
private static final byte[] PARTIAL_CUT = {0x1B, 0x50, 0x00};
private static final byte[] IMAGE_HEADER = {0x1D, 0x76, 0x30, 0x03};
private static final byte[] NEW_LINE = {0x0D, 0x0A}; // Print and carriage return
/** Creates a new instance of CodesIthaca */
public CodesIthaca() {
}
public byte[] getInitSequence() { return INITSEQUENCE; }
public byte[] getSize0() { return CHAR_SIZE_0; }
public byte[] getSize1() { return CHAR_SIZE_1; }
public byte[] getSize2() { return CHAR_SIZE_2; }
public byte[] getSize3() { return CHAR_SIZE_3; }
public byte[] getBoldSet() { return BOLD_SET; }
public byte[] getBoldReset() { return BOLD_RESET; }
public byte[] getUnderlineSet() { return UNDERLINE_SET; }
public byte[] getUnderlineReset() { return UNDERLINE_RESET; }
public byte[] getOpenDrawer() { return OPEN_DRAWER; }
public byte[] getCutReceipt() { return PARTIAL_CUT; }
public byte[] getNewLine() { return NEW_LINE; }
public byte[] getImageHeader() { return IMAGE_HEADER; }
public int getImageWidth() { return 256; }
}
| ZarGate/OpenbravoPOS | src-pos/com/openbravo/pos/printer/escpos/CodesIthaca.java | Java | gpl-3.0 | 2,760 |
#ifndef UTIL_BIT_PACKING__
#define UTIL_BIT_PACKING__
/* Bit-level packing routines */
#include <assert.h>
#ifdef __APPLE__
#include <architecture/byte_order.h>
#elif __linux__
#include <endian.h>
#else
#include <arpa/nameser_compat.h>
#endif
#include <inttypes.h>
namespace util {
/* WARNING WARNING WARNING:
* The write functions assume that memory is zero initially. This makes them
* faster and is the appropriate case for mmapped language model construction.
* These routines assume that unaligned access to uint64_t is fast and that
* storage is little endian. This is the case on x86_64. I'm not sure how
* fast unaligned 64-bit access is on x86 but my target audience is large
* language models for which 64-bit is necessary.
*
* Call the BitPackingSanity function to sanity check. Calling once suffices,
* but it may be called multiple times when that's inconvenient.
*/
// Fun fact: __BYTE_ORDER is wrong on Solaris Sparc, but the version without __ is correct.
#if BYTE_ORDER == LITTLE_ENDIAN
inline uint8_t BitPackShift(uint8_t bit, uint8_t /*length*/) {
return bit;
}
#elif BYTE_ORDER == BIG_ENDIAN
inline uint8_t BitPackShift(uint8_t bit, uint8_t length) {
return 64 - length - bit;
}
#else
#error "Bit packing code isn't written for your byte order."
#endif
inline uint64_t ReadOff(const void *base, uint64_t bit_off) {
return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3));
}
/* Pack integers up to 57 bits using their least significant digits.
* The length is specified using mask:
* Assumes mask == (1 << length) - 1 where length <= 57.
*/
inline uint64_t ReadInt57(const void *base, uint64_t bit_off, uint8_t length, uint64_t mask) {
return (ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, length)) & mask;
}
/* Assumes value < (1 << length) and length <= 57.
* Assumes the memory is zero initially.
*/
inline void WriteInt57(void *base, uint64_t bit_off, uint8_t length, uint64_t value) {
*reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
(value << BitPackShift(bit_off & 7, length));
}
/* Same caveats as above, but for a 25 bit limit. */
inline uint32_t ReadInt25(const void *base, uint64_t bit_off, uint8_t length, uint32_t mask) {
return (*reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)) >> BitPackShift(bit_off & 7, length)) & mask;
}
inline void WriteInt25(void *base, uint64_t bit_off, uint8_t length, uint32_t value) {
*reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
(value << BitPackShift(bit_off & 7, length));
}
typedef union { float f; uint32_t i; } FloatEnc;
inline float ReadFloat32(const void *base, uint64_t bit_off) {
FloatEnc encoded;
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 32);
return encoded.f;
}
inline void WriteFloat32(void *base, uint64_t bit_off, float value) {
FloatEnc encoded;
encoded.f = value;
WriteInt57(base, bit_off, 32, encoded.i);
}
const uint32_t kSignBit = 0x80000000;
inline void SetSign(float &to) {
FloatEnc enc;
enc.f = to;
enc.i |= kSignBit;
to = enc.f;
}
inline void UnsetSign(float &to) {
FloatEnc enc;
enc.f = to;
enc.i &= ~kSignBit;
to = enc.f;
}
inline float ReadNonPositiveFloat31(const void *base, uint64_t bit_off) {
FloatEnc encoded;
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 31);
// Sign bit set means negative.
encoded.i |= kSignBit;
return encoded.f;
}
inline void WriteNonPositiveFloat31(void *base, uint64_t bit_off, float value) {
FloatEnc encoded;
encoded.f = value;
encoded.i &= ~kSignBit;
WriteInt57(base, bit_off, 31, encoded.i);
}
void BitPackingSanity();
// Return bits required to store integers upto max_value. Not the most
// efficient implementation, but this is only called a few times to size tries.
uint8_t RequiredBits(uint64_t max_value);
struct BitsMask {
static BitsMask ByMax(uint64_t max_value) {
BitsMask ret;
ret.FromMax(max_value);
return ret;
}
static BitsMask ByBits(uint8_t bits) {
BitsMask ret;
ret.bits = bits;
ret.mask = (1ULL << bits) - 1;
return ret;
}
void FromMax(uint64_t max_value) {
bits = RequiredBits(max_value);
mask = (1ULL << bits) - 1;
}
uint8_t bits;
uint64_t mask;
};
} // namespace util
#endif // UTIL_BIT_PACKING__
| kpm/kenlm-rb | util/bit_packing.hh | C++ | gpl-3.0 | 4,424 |
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Traits;
namespace OpenRA.Mods.RA
{
[Desc("Used to waypoint units after production or repair is finished.")]
public class RallyPointInfo : ITraitInfo
{
public readonly int[] RallyPoint = { 1, 3 };
public readonly string IndicatorPalettePrefix = "player";
public object Create(ActorInitializer init) { return new RallyPoint(init.self, this); }
}
public class RallyPoint : IIssueOrder, IResolveOrder, ISync
{
[Sync] public CPos rallyPoint;
public int nearEnough = 1;
public RallyPoint(Actor self, RallyPointInfo info)
{
rallyPoint = self.Location + new CVec(info.RallyPoint[0], info.RallyPoint[1]);
self.World.AddFrameEndTask(w => w.Add(new Effects.RallyPoint(self, info.IndicatorPalettePrefix)));
}
public IEnumerable<IOrderTargeter> Orders
{
get { yield return new RallyPointOrderTargeter(); }
}
public Order IssueOrder( Actor self, IOrderTargeter order, Target target, bool queued )
{
if( order.OrderID == "SetRallyPoint" )
return new Order(order.OrderID, self, false) { TargetLocation = target.CenterPosition.ToCPos() };
return null;
}
public void ResolveOrder( Actor self, Order order )
{
if( order.OrderString == "SetRallyPoint" )
rallyPoint = order.TargetLocation;
}
class RallyPointOrderTargeter : IOrderTargeter
{
public string OrderID { get { return "SetRallyPoint"; } }
public int OrderPriority { get { return 0; } }
public bool CanTarget(Actor self, Target target, List<Actor> othersAtTarget, TargetModifiers modifiers, ref string cursor)
{
if (target.Type != TargetType.Terrain)
return false;
var location = target.CenterPosition.ToCPos();
if (self.World.Map.IsInMap(location))
{
cursor = "ability";
return true;
}
return false;
}
public bool IsQueued { get { return false; } } // unused
}
}
}
| obrakmann/OpenRA | OpenRA.Mods.RA/RallyPoint.cs | C# | gpl-3.0 | 2,264 |
<?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 "namespaces" collection of methods.
* Typical usage is:
* <code>
* $runService = new Google_Service_CloudRun(...);
* $namespaces = $runService->namespaces;
* </code>
*/
class Google_Service_CloudRun_Resource_ProjectsLocationsNamespaces extends Google_Service_Resource
{
/**
* Rpc to get information about a namespace. (namespaces.get)
*
* @param string $name Required. The name of the namespace being retrieved. If
* needed, replace {namespace_id} with the project ID.
* @param array $optParams Optional parameters.
* @return Google_Service_CloudRun_RunNamespace
*/
public function get($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_CloudRun_RunNamespace");
}
/**
* Rpc to update a namespace. (namespaces.patch)
*
* @param string $name Required. The name of the namespace being retrieved. If
* needed, replace {namespace_id} with the project ID.
* @param Google_Service_CloudRun_RunNamespace $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Required. Indicates which fields in the provided
* namespace to update. This field is currently unused.
* @return Google_Service_CloudRun_RunNamespace
*/
public function patch($name, Google_Service_CloudRun_RunNamespace $postBody, $optParams = array())
{
$params = array('name' => $name, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_CloudRun_RunNamespace");
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/CloudRun/Resource/ProjectsLocationsNamespaces.php | PHP | gpl-3.0 | 2,264 |
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
* http://wiki.mahara.org/Contributors
*
* 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 mahara
* @subpackage lang
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
*
*/
defined('INTERNAL') || die();
$string['pluginname'] = 'Profile';
$string['profile'] = 'Profile';
$string['mandatory'] = 'Mandatory';
$string['public'] = 'Public';
$string['aboutdescription'] = 'Enter your real first and last name here. If you want to show a different name to people in the system, put that name in as your display name.';
$string['infoisprivate'] = 'This information is private until you include it in a page that is shared with others.';
$string['viewmyprofile'] = 'View my profile';
// profile categories
$string['aboutme'] = 'About me';
$string['contact'] = 'Contact information';
$string['messaging'] = 'Messaging';
$string['general'] = 'General';
// profile fields
$string['firstname'] = 'First Name';
$string['lastname'] = 'Last Name';
$string['fullname'] = 'Full Name';
$string['institution'] = 'Institution';
$string['studentid'] = 'Student ID';
$string['preferredname'] = 'Display Name';
$string['introduction'] = 'Introduction';
$string['email'] = 'Email Address';
$string['maildisabled'] = 'Email Disabled';
$string['officialwebsite'] = 'Official Website Address';
$string['personalwebsite'] = 'Personal Website Address';
$string['blogaddress'] = 'Blog Address';
$string['address'] = 'Postal Address';
$string['town'] = 'Town';
$string['city'] = 'City/Region';
$string['country'] = 'Country';
$string['homenumber'] = 'Home Phone';
$string['businessnumber'] = 'Business Phone';
$string['mobilenumber'] = 'Mobile Phone';
$string['faxnumber'] = 'Fax Number';
$string['icqnumber'] = 'ICQ Number';
$string['msnnumber'] = 'MSN Chat';
$string['aimscreenname'] = 'AIM Screen Name';
$string['yahoochat'] = 'Yahoo Chat';
$string['skypeusername'] = 'Skype Username';
$string['jabberusername'] = 'Jabber Username';
$string['occupation'] = 'Occupation';
$string['industry'] = 'Industry';
// Field names for view user and search user display
$string['name'] = 'Name';
$string['principalemailaddress'] = 'Primary email';
$string['emailaddress'] = 'Alternative email';
$string['saveprofile'] = 'Save Profile';
$string['profilesaved'] = 'Profile saved successfully';
$string['profilefailedsaved'] = 'Profile saving failed';
$string['emailvalidation_subject'] = 'Email validation';
$string['emailvalidation_body'] = <<<EOF
Hello %s,
You have added email address %s to your user account in Mahara. Please visit the link below to activate this address.
%s
If this email belongs to you but you have not requested adding it to your Mahara account, follow the link below to decline email activation.
%s
EOF;
$string['validationemailwillbesent'] = 'a validation email will be sent when you save your profile';
$string['validationemailsent'] = 'a validation email has been sent';
$string['emailactivation'] = 'Email Activation';
$string['emailactivationsucceeded'] = 'Email Activation Successful';
$string['emailalreadyactivated'] = 'Email already activiated';
$string['emailactivationfailed'] = 'Email Activation Failed';
$string['emailactivationdeclined'] = 'Email Activation Declined Successfully';
$string['verificationlinkexpired'] = 'Verification link expired';
$string['invalidemailaddress'] = 'Invalid email address';
$string['unvalidatedemailalreadytaken'] = 'The e-mail address you are trying to validate is already taken';
$string['addbutton'] = 'Add';
$string['emailingfailed'] = 'Profile saved, but emails were not sent to: %s';
$string['loseyourchanges'] = 'Lose your changes?';
$string['Title'] = 'Title';
$string['Created'] = 'Created';
$string['Description'] = 'Description';
$string['Download'] = 'Download';
$string['lastmodified'] = 'Last Modified';
$string['Owner'] = 'Owner';
$string['Preview'] = 'Preview';
$string['Size'] = 'Size';
$string['Type'] = 'Type';
$string['profileinformation'] = 'Profile Information';
$string['profilepage'] = 'Profile Page';
$string['viewprofilepage'] = 'View profile page';
$string['viewallprofileinformation'] = 'View all profile information';
| plymouthstate/mahara | htdocs/artefact/internal/lang/en.utf8/artefact.internal.php | PHP | gpl-3.0 | 4,994 |
/* This file is part of HSPlasma.
*
* HSPlasma 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.
*
* HSPlasma 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 HSPlasma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plSDL.h"
unsigned int plSDL::VariableLengthRead(hsStream* S, size_t size) {
if (size < 0x100)
return S->readByte();
else if (size < 0x10000)
return S->readShort();
else
return S->readInt();
}
void plSDL::VariableLengthWrite(hsStream* S, size_t size, unsigned int value) {
if (size < 0x100)
S->writeByte(value);
else if (size < 0x10000)
S->writeShort(value);
else
S->writeInt(value);
}
| NadnerbD/libhsplasma | core/SDL/plSDL.cpp | C++ | gpl-3.0 | 1,145 |
package com.redhat.jcliff;
import java.io.StringBufferInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.jboss.dmr.ModelNode;
public class DeploymentTest {
@Test
public void replace() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
Map<String,Set<String>> map=d.findDeploymentsToReplace(newDeployments,existingDeployments);
Assert.assertEquals("app2",map.get("app2").iterator().next());
Assert.assertNull(map.get("app1"));
Assert.assertEquals(1,map.size());
}
@Test
public void newdeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] news=d.getNewDeployments(newDeployments,existingDeployments.keys());
Assert.assertEquals(1,news.length);
Assert.assertEquals("app3",news[0]);
}
@Test
public void undeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"}, \"app4\"=>\"deleted\" }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] und=d.getUndeployments(newDeployments,existingDeployments);
Assert.assertEquals(1,und.length);
Assert.assertEquals("app1",und[0]);
}
}
| mkrakowitzer/jcliff | src/test/java/com/redhat/jcliff/DeploymentTest.java | Java | gpl-3.0 | 2,307 |
package raft
import (
"bytes"
crand "crypto/rand"
"fmt"
"math"
"math/big"
"math/rand"
"time"
"github.com/hashicorp/go-msgpack/codec"
)
func init() {
// Ensure we use a high-entropy seed for the pseudo-random generator
rand.Seed(newSeed())
}
// returns an int64 from a crypto random source
// can be used to seed a source for a math/rand.
func newSeed() int64 {
r, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return r.Int64()
}
// randomTimeout returns a value that is between the minVal and 2x minVal.
func randomTimeout(minVal time.Duration) <-chan time.Time {
if minVal == 0 {
return nil
}
extra := (time.Duration(rand.Int63()) % minVal)
return time.After(minVal + extra)
}
// min returns the minimum.
func min(a, b uint64) uint64 {
if a <= b {
return a
}
return b
}
// max returns the maximum.
func max(a, b uint64) uint64 {
if a >= b {
return a
}
return b
}
// generateUUID is used to generate a random UUID.
func generateUUID() string {
buf := make([]byte, 16)
if _, err := crand.Read(buf); err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16])
}
// asyncNotifyCh is used to do an async channel send
// to a single channel without blocking.
func asyncNotifyCh(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// drainNotifyCh empties out a single-item notification channel without
// blocking, and returns whether it received anything.
func drainNotifyCh(ch chan struct{}) bool {
select {
case <-ch:
return true
default:
return false
}
}
// asyncNotifyBool is used to do an async notification
// on a bool channel.
func asyncNotifyBool(ch chan bool, v bool) {
select {
case ch <- v:
default:
}
}
// overrideNotifyBool is used to notify on a bool channel
// but override existing value if value is present.
// ch must be 1-item buffered channel.
//
// This method does not support multiple concurrent calls.
func overrideNotifyBool(ch chan bool, v bool) {
select {
case ch <- v:
// value sent, all done
case <-ch:
// channel had an old value
select {
case ch <- v:
default:
panic("race: channel was sent concurrently")
}
}
}
// Decode reverses the encode operation on a byte slice input.
func decodeMsgPack(buf []byte, out interface{}) error {
r := bytes.NewBuffer(buf)
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(r, &hd)
return dec.Decode(out)
}
// Encode writes an encoded object to a new bytes buffer.
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
// backoff is used to compute an exponential backoff
// duration. Base time is scaled by the current round,
// up to some maximum scale factor.
func backoff(base time.Duration, round, limit uint64) time.Duration {
power := min(round, limit)
for power > 2 {
base *= 2
power--
}
return base
}
// Needed for sorting []uint64, used to determine commitment
type uint64Slice []uint64
func (p uint64Slice) Len() int { return len(p) }
func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
| hartsock/vault | vendor/github.com/hashicorp/raft/util.go | GO | mpl-2.0 | 3,420 |
package net.tropicraft.world.genlayer;
import net.minecraft.world.gen.layer.IntCache;
public class GenLayerTropiVoronoiZoom extends GenLayerTropicraft {
public enum Mode {
CARTESIAN, MANHATTAN;
}
public Mode zoomMode;
public GenLayerTropiVoronoiZoom(long seed, GenLayerTropicraft parent, Mode zoomMode)
{
super(seed);
super.parent = parent;
this.zoomMode = zoomMode;
this.setZoom(1);
}
/**
* Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall
* amounts, or biomeList[] indices based on the particular GenLayer subclass.
*/
public int[] getInts(int x, int y, int width, int length)
{
final int randomResolution = 1024;
final double half = 0.5D;
final double almostTileSize = 3.6D;
final double tileSize = 4D;
x -= 2;
y -= 2;
int scaledX = x >> 2;
int scaledY = y >> 2;
int scaledWidth = (width >> 2) + 2;
int scaledLength = (length >> 2) + 2;
int[] parentValues = this.parent.getInts(scaledX, scaledY, scaledWidth, scaledLength);
int bitshiftedWidth = scaledWidth - 1 << 2;
int bitshiftedLength = scaledLength - 1 << 2;
int[] aint1 = IntCache.getIntCache(bitshiftedWidth * bitshiftedLength);
int i;
for(int j = 0; j < scaledLength - 1; ++j) {
i = 0;
int baseValue = parentValues[i + 0 + (j + 0) * scaledWidth];
for(int advancedValueJ = parentValues[i + 0 + (j + 1) * scaledWidth]; i < scaledWidth - 1; ++i) {
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY << 2));
double offsetY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY << 2));
double offsetYY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY + 1 << 2));
double offsetYX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetXX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY + 1 << 2));
double offsetYXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
int advancedValueI = parentValues[i + 1 + (j + 0) * scaledWidth] & 255;
int advancedValueIJ = parentValues[i + 1 + (j + 1) * scaledWidth] & 255;
for(int innerX = 0; innerX < 4; ++innerX) {
int index = ((j << 2) + innerX) * bitshiftedWidth + (i << 2);
for(int innerY = 0; innerY < 4; ++innerY) {
double baseDistance;
double distanceY;
double distanceX;
double distanceXY;
switch(zoomMode) {
case CARTESIAN:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
break;
case MANHATTAN:
baseDistance = Math.abs(innerX - offsetX) + Math.abs(innerY - offsetY);
distanceY = Math.abs(innerX - offsetXY) + Math.abs(innerY - offsetYY);
distanceX = Math.abs(innerX - offsetXX) + Math.abs(innerY - offsetYX);
distanceXY = Math.abs(innerX - offsetXXY) + Math.abs(innerY - offsetYXY);
break;
default:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
}
if(baseDistance < distanceY && baseDistance < distanceX && baseDistance < distanceXY) {
aint1[index++] = baseValue;
} else if(distanceY < baseDistance && distanceY < distanceX && distanceY < distanceXY) {
aint1[index++] = advancedValueI;
} else if(distanceX < baseDistance && distanceX < distanceY && distanceX < distanceXY) {
aint1[index++] = advancedValueJ;
} else {
aint1[index++] = advancedValueIJ;
}
}
}
baseValue = advancedValueI;
advancedValueJ = advancedValueIJ;
}
}
int[] aint2 = IntCache.getIntCache(width * length);
for(i = 0; i < length; ++i) {
System.arraycopy(aint1, (i + (y & 3)) * bitshiftedWidth + (x & 3), aint2, i * width, width);
}
return aint2;
}
@Override
public void setZoom(int zoom) {
this.zoom = zoom;
parent.setZoom(zoom * 4);
}
} | Vexatos/Tropicraft | src/main/java/net/tropicraft/world/genlayer/GenLayerTropiVoronoiZoom.java | Java | mpl-2.0 | 6,674 |
import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey="H"
changePositionKey="Q"
>
<LogMonitor />
</DockMonitor>
)
| blockstack/blockstack-browser | app/js/components/DevTools.js | JavaScript | mpl-2.0 | 323 |
/*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
var ExitHandlers = {
// a widget can dynamically set "do-not-exit" or "do-not-exit-once" classes on the field to indicate we should not
// exit the field. "do-not-exit-once" will be cleared after a single exit attempt.
'manual-exit': {
handleExit: function(fieldModel) {
var doNotExit = fieldModel.element.hasClass('do-not-exit') || fieldModel.element.hasClass('do-not-exit-once');
fieldModel.element.removeClass('do-not-exit-once');
return !doNotExit;
}
},
'leading-zeros': {
handleExit: function(fieldModel) {
var val = fieldModel.element.val();
if (val) { // if the field is blank, leave it alone
var maxLength = parseInt(fieldModel.element.attr('maxlength'));
if (maxLength > 0) {
while (val.length < maxLength) {
val = "0" + val;
}
fieldModel.element.val(val);
}
}
return true;
}
}
}; | yadamz/first-module | omod/src/main/webapp/resources/scripts/navigator/exitHandlers.js | JavaScript | mpl-2.0 | 1,610 |
import { Model, belongsTo } from 'ember-cli-mirage';
export default Model.extend({
parent: belongsTo('alloc-file'),
});
| hashicorp/nomad | ui/mirage/models/alloc-file.js | JavaScript | mpl-2.0 | 123 |
<?php
use Faker\Generator;
class IssueModuleCest
{
/**
* @var string $lastView helps the test skip some repeated tests in order to make the test framework run faster at the
* potential cost of being accurate and reliable
*/
protected $lastView;
/**
* @var Generator $fakeData
*/
protected $fakeData;
/**
* @var integer $fakeDataSeed
*/
protected $fakeDataSeed;
/**
* @param AcceptanceTester $I
*/
public function _before(AcceptanceTester $I)
{
if (!$this->fakeData) {
$this->fakeData = Faker\Factory::create();
$this->fakeDataSeed = rand(0, 2048);
}
$this->fakeData->seed($this->fakeDataSeed);
}
/**
* @param AcceptanceTester $I
*/
public function _after(AcceptanceTester $I)
{
}
// Tests
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\ModuleBuilder $moduleBuilder
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As an administrator I want to create and deploy a issue module so that I can test
* that the issue functionality is working. Given that I have already created a module I expect to deploy
* the module before testing.
*/
public function testScenarioCreateIssueModule(
\AcceptanceTester $I,
\Step\Acceptance\ModuleBuilder $moduleBuilder,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Create a issue module for testing');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
$moduleBuilder->createModule(
\Page\IssueModule::$PACKAGE_NAME,
\Page\IssueModule::$NAME,
\SuiteCRM\Enumerator\SugarObjectType::issue
);
$this->lastView = 'ModuleBuilder';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to view my issue test module so that I can see if it has been
* deployed correctly.
*/
public function testScenarioViewIssueTestModule(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('View Issue Test Module');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Navigate to module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\EditView $editView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to create a record with my issue test module so that I can test
* the standard fields.
*/
public function testScenarioCreateRecord(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\EditView $editView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Create Issue Test Module Record');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select create Issue Test Module form the current menu
$navigationBar->clickCurrentMenuItem('Create ' . \Page\IssueModule::$NAME);
// Create a record
$this->fakeData->seed($this->fakeDataSeed);
$editView->waitForEditViewVisible();
$editView->fillField('#name', $this->fakeData->name);
$editView->fillField('#description', $this->fakeData->paragraph);
$editView->clickSaveButton();
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to view the record by selecting it in the list view
*/
public function testScenarioViewRecordFromListView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Select Record from list view');
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Step\Acceptance\EditView $editView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to edit the record by selecting it in the detail view
*/
public function testScenarioEditRecordFromDetailView(
\AcceptanceTester$I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Step\Acceptance\EditView $editView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Edit Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Edit Record
$detailView->clickActionMenuItem('Edit');
// Save record
$editView->click('Save');
$detailView->waitForDetailViewVisible();
$this->lastView = 'DetailView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Step\Acceptance\EditView $editView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to duplicate the record
*/
public function testScenarioDuplicateRecordFromDetailView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Step\Acceptance\EditView $editView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Duplicate Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Edit Record
$detailView->clickActionMenuItem('Duplicate');
$this->fakeData->seed($this->fakeDataSeed);
$editView->fillField('#name', $this->fakeData->name . '1');
// Save record
$editView->click('Save');
$detailView->waitForDetailViewVisible();
$detailView->clickActionMenuItem('Delete');
$detailView->acceptPopup();
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
/**
* @param \AcceptanceTester $I
* @param \Step\Acceptance\NavigationBarTester $navigationBar
* @param \Step\Acceptance\ListView $listView
* @param \Step\Acceptance\DetailView $detailView
* @param \Helper\WebDriverHelper $webDriverHelper
*
* As administrative user I want to delete the record by selecting it in the detail view
*/
public function testScenarioDeleteRecordFromDetailView(
\AcceptanceTester $I,
\Step\Acceptance\NavigationBarTester $navigationBar,
\Step\Acceptance\ListView $listView,
\Step\Acceptance\DetailView $detailView,
\Helper\WebDriverHelper $webDriverHelper
) {
$I->wantTo('Delete Issue Test Module Record from detail view');
if ($this->lastView !== 'DetailView') {
$I->amOnUrl(
$webDriverHelper->getInstanceURL()
);
$I->loginAsAdmin();
// Go to Issue Test Module
$navigationBar->clickAllMenuItem(\Page\IssueModule::$NAME);
$listView->waitForListViewVisible();
// Select record from list view
$listView->clickFilterButton();
$listView->click('Quick Filter');
$this->fakeData->seed($this->fakeDataSeed);
$listView->fillField('#name_basic', $this->fakeData->name);
$listView->click('Search', '.submitButtons');
$listView->wait(1);
$this->fakeData->seed($this->fakeDataSeed);
$listView->clickNameLink($this->fakeData->name);
}
// Delete Record
$detailView->clickActionMenuItem('Delete');
$detailView->acceptPopup();
$listView->waitForListViewVisible();
$this->lastView = 'ListView';
}
}
| willrennie/SuiteCRM | tests/acceptance/Core/IssueModuleCest.php | PHP | agpl-3.0 | 11,748 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\ESIndexingBundle\Product;
use Shopware\Bundle\ESIndexingBundle\LastIdQuery;
/**
* Class ProductQueryFactoryInterface
*/
interface ProductQueryFactoryInterface
{
/**
* @param int $categoryId
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createCategoryQuery($categoryId, $limit = null);
/**
* @param int[] $priceIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPriceIdQuery($priceIds, $limit = null);
/**
* @param int[] $unitIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createUnitIdQuery($unitIds, $limit = null);
/**
* @param int[] $voteIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createVoteIdQuery($voteIds, $limit = null);
/**
* @param int[] $productIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createProductIdQuery($productIds, $limit = null);
/**
* @param int[] $variantIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createVariantIdQuery($variantIds, $limit = null);
/**
* @param int[] $taxIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createTaxQuery($taxIds, $limit = null);
/**
* @param int[] $manufacturerIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createManufacturerQuery($manufacturerIds, $limit = null);
/**
* @param int[] $categoryIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createProductCategoryQuery($categoryIds, $limit = null);
/**
* @param int[] $groupIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPropertyGroupQuery($groupIds, $limit = null);
/**
* @param int[] $optionIds
* @param int|null $limit
*
* @return LastIdQuery
*/
public function createPropertyOptionQuery($optionIds, $limit = null);
}
| wlwwt/shopware | engine/Shopware/Bundle/ESIndexingBundle/Product/ProductQueryFactoryInterface.php | PHP | agpl-3.0 | 3,161 |
<?php
/**
* Live media server object, represents a media server association with live stream entry
*
* @package Core
* @subpackage model
*
*/
class kLiveMediaServer
{
/**
* @var int
*/
protected $mediaServerId;
/**
* @var int
*/
protected $index;
/**
* @var int
*/
protected $dc;
/**
* @var string
*/
protected $hostname;
/**
* @var int
*/
protected $time;
/**
* @var string
*/
protected $applicationName;
public function __construct($index, $hostname, $dc = null, $id = null, $applicationName = null)
{
$this->index = $index;
$this->mediaServerId = $id;
$this->hostname = $hostname;
$this->dc = $dc;
$this->time = time();
$this->applicationName = $applicationName;
}
/**
* @return int $mediaServerId
*/
public function getMediaServerId()
{
return $this->mediaServerId;
}
/**
* @return MediaServerNode
*/
public function getMediaServer()
{
$mediaServer = ServerNodePeer::retrieveByPK($this->mediaServerId);
if($mediaServer instanceof MediaServerNode)
return $mediaServer;
return null;
}
/**
* @return int $index
*/
public function getIndex()
{
return $this->index;
}
/**
* @return int $dc
*/
public function getDc()
{
return $this->dc;
}
/**
* @return string $hostname
*/
public function getHostname()
{
return $this->hostname;
}
/**
* @return int $time
*/
public function getTime()
{
return $this->time;
}
/**
* @return the $applicationName
*/
public function getApplicationName() {
return $this->applicationName;
}
} | doubleshot/server | alpha/lib/data/live/kLiveMediaServer.php | PHP | agpl-3.0 | 1,582 |
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio 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.
*
* Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*
* Description : focusable component / Tab navigation
*/
Interface.create("IContextMenuable", {
setContextualMenu : function(contextMenu){}
}); | FredPassos/pydio-core | core/src/plugins/gui.ajax/res/js/ui/prototype/interfaces/class.IContextMenuable.js | JavaScript | agpl-3.0 | 964 |
module Formtastic
module Helpers
# @private
module FieldsetWrapper
protected
# Generates a fieldset and wraps the content in an ordered list. When working
# with nested attributes, it allows %i as interpolation option in :name. So you can do:
#
# f.inputs :name => 'Task #%i', :for => :tasks
#
# or the shorter equivalent:
#
# f.inputs 'Task #%i', :for => :tasks
#
# And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
# 'Task #3' and so on.
#
# Note: Special case for the inline inputs (non-block):
# f.inputs "My little legend", :title, :body, :author # Explicit legend string => "My little legend"
# f.inputs :my_little_legend, :title, :body, :author # Localized (118n) legend with I18n key => I18n.t(:my_little_legend, ...)
# f.inputs :title, :body, :author # First argument is a column => (no legend)
def field_set_and_list_wrapping(*args, &block) # @private
contents = args[-1].is_a?(::Hash) ? '' : args.pop.flatten
html_options = args.extract_options!
if block_given?
contents = if template.respond_to?(:is_haml?) && template.is_haml?
template.capture_haml(&block)
else
template.capture(&block)
end
end
# Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
contents = contents.join if contents.respond_to?(:join)
legend = field_set_legend(html_options)
fieldset = template.content_tag(:fieldset,
Formtastic::Util.html_safe(legend) << template.content_tag(:ol, Formtastic::Util.html_safe(contents)),
html_options.except(:builder, :parent, :name)
)
fieldset
end
def field_set_legend(html_options)
legend = (html_options[:name] || '').to_s
legend %= parent_child_index(html_options[:parent]) if html_options[:parent] && legend.include?('%i') # only applying if String includes '%i' avoids argument error when $DEBUG is true
legend = template.content_tag(:legend, template.content_tag(:span, Formtastic::Util.html_safe(legend))) unless legend.blank?
legend
end
# Gets the nested_child_index value from the parent builder. It returns a hash with each
# association that the parent builds.
def parent_child_index(parent) # @private
# Could be {"post[authors_attributes]"=>0} or { :authors => 0 }
duck = parent[:builder].instance_variable_get('@nested_child_index')
# Could be symbol for the association, or a model (or an array of either, I think? TODO)
child = parent[:for]
# Pull a sybol or model out of Array (TODO: check if there's an Array)
child = child.first if child.respond_to?(:first)
# If it's an object, get a symbol from the class name
child = child.class.name.underscore.to_sym unless child.is_a?(Symbol)
key = "#{parent[:builder].object_name}[#{child}_attributes]"
# TODO: One of the tests produces a scenario where duck is "0" and the test looks for a "1"
# in the legend, so if we have a number, return it with a +1 until we can verify this scenario.
return duck + 1 if duck.is_a?(Fixnum)
# First try to extract key from duck Hash, then try child
(duck[key] || duck[child]).to_i + 1
end
end
end
end
| BibNumUMontreal/DMPonline_v4 | vendor/ruby/2.1.0/gems/formtastic-3.1.4/lib/formtastic/helpers/fieldset_wrapper.rb | Ruby | agpl-3.0 | 3,480 |
<?php
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$app_list_strings['moduleList']['CON_Contratos'] = 'Contratos';
$app_list_strings['con_contratos_type_dom']['Administration'] = 'Administration';
$app_list_strings['con_contratos_type_dom']['Product'] = 'Product';
$app_list_strings['con_contratos_type_dom']['User'] = 'User';
$app_list_strings['con_contratos_status_dom']['New'] = 'New';
$app_list_strings['con_contratos_status_dom']['Assigned'] = 'Assigned';
$app_list_strings['con_contratos_status_dom']['Closed'] = 'Closed';
$app_list_strings['con_contratos_status_dom']['Pending Input'] = 'Pending Input';
$app_list_strings['con_contratos_status_dom']['Rejected'] = 'Rejected';
$app_list_strings['con_contratos_status_dom']['Duplicate'] = 'Duplicate';
$app_list_strings['con_contratos_priority_dom']['P1'] = 'High';
$app_list_strings['con_contratos_priority_dom']['P2'] = 'Medium';
$app_list_strings['con_contratos_priority_dom']['P3'] = 'Low';
$app_list_strings['con_contratos_resolution_dom'][''] = '';
$app_list_strings['con_contratos_resolution_dom']['Accepted'] = 'Accepted';
$app_list_strings['con_contratos_resolution_dom']['Duplicate'] = 'Duplicate';
$app_list_strings['con_contratos_resolution_dom']['Closed'] = 'Closed';
$app_list_strings['con_contratos_resolution_dom']['Out of Date'] = 'Out of Date';
$app_list_strings['con_contratos_resolution_dom']['Invalid'] = 'Invalid';
$app_list_strings['accion_list']['Alta'] = 'Alta';
$app_list_strings['accion_list']['Baja'] = 'Baja';
$app_list_strings['accion_list']['Modificacion'] = 'Modificacion';
$app_list_strings['tipo_contrato_list']['Indefinido'] = 'Indefinido';
$app_list_strings['tipo_contrato_list']['Temporal'] = 'Temporal';
$app_list_strings['tipo_contrato_list']['Obra'] = 'Obra';
$app_list_strings['tipo_contrato_list'][''] = '';
$app_list_strings['categoria_list']['Profesor'] = 'Profesor';
$app_list_strings['categoria_list']['Administrativo'] = 'Administrativo';
$app_list_strings['categoria_list'][''] = '';
$app_list_strings['_type_dom']['Administration'] = 'Administración';
$app_list_strings['_type_dom']['Product'] = 'Producto';
$app_list_strings['_type_dom']['User'] = 'Usuario';
$app_list_strings['_status_dom']['New'] = 'Nuevo';
$app_list_strings['_status_dom']['Assigned'] = 'Asignado';
$app_list_strings['_status_dom']['Closed'] = 'Cerrado';
$app_list_strings['_status_dom']['Pending Input'] = 'Pendiente de Información';
$app_list_strings['_status_dom']['Rejected'] = 'Rechazado';
$app_list_strings['_status_dom']['Duplicate'] = 'Duplicado';
$app_list_strings['_priority_dom']['P1'] = 'Alta';
$app_list_strings['_priority_dom']['P2'] = 'Media';
$app_list_strings['_priority_dom']['P3'] = 'Baja';
$app_list_strings['_resolution_dom'][''] = '';
$app_list_strings['_resolution_dom']['Accepted'] = 'Aceptado';
$app_list_strings['_resolution_dom']['Duplicate'] = 'Duplicado';
$app_list_strings['_resolution_dom']['Closed'] = 'Cerrado';
$app_list_strings['_resolution_dom']['Out of Date'] = 'Caducado';
$app_list_strings['_resolution_dom']['Invalid'] = 'No Válido';
| witxo/bonos | custom/modulebuilder/packages/Contratos/language/application/es_ES.lang.php | PHP | agpl-3.0 | 5,024 |