code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/*
* This file is part of the coreboot project.
*
* Copyright 2014 Google 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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <arch/io.h>
#include <gpio.h>
#include <reset.h>
#include "board.h"
void hard_reset(void)
{
gpio_output(GPIO_RESET, 1);
while (1)
;
}
| Java |
<?php
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2013 [email protected] |
# +------------------------------------------------------------------+
#
# 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\" ";
?>
| Java |
<?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');
}
}
}
| Java |
/* Duplicate handle for selection of locales.
Copyright (C) 1997, 2000, 2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1997.
The GNU C 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 (at your option) any later version.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <locale.h>
#include <bits/libc-lock.h>
#include <stdlib.h>
#include <localeinfo.h>
/* Lock for protecting global data. */
__libc_lock_define (extern , __libc_setlocale_lock)
__locale_t
__duplocale (__locale_t dataset)
{
__locale_t result;
/* We modify global data. */
__libc_lock_lock (__libc_setlocale_lock);
/* Get memory. */
result = (__locale_t) malloc (sizeof (struct __locale_struct));
if (result != NULL)
{
int cnt;
for (cnt = 0; cnt < __LC_LAST; ++cnt)
if (cnt != LC_ALL)
{
result->__locales[cnt] = dataset->__locales[cnt];
if (result->__locales[cnt]->usage_count < MAX_USAGE_COUNT)
++result->__locales[cnt]->usage_count;
}
}
/* Update the special members. */
result->__ctype_b = dataset->__ctype_b;
result->__ctype_tolower = dataset->__ctype_tolower;
result->__ctype_toupper = dataset->__ctype_toupper;
/* It's done. */
__libc_lock_unlock (__libc_setlocale_lock);
return result;
}
| Java |
/* packet-bpkmreq.c
* Routines for Baseline Privacy Key Management Request dissection
* Copyright 2002, Anand V. Narwani <anand[AT]narwani.org>
*
* $Id: packet-bpkmreq.c 45015 2012-09-20 01:29:52Z morriss $
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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.
*/
#include "config.h"
#include <epan/packet.h>
/* Initialize the protocol and registered fields */
static int proto_docsis_bpkmreq = -1;
static int hf_docsis_bpkmreq_code = -1;
static int hf_docsis_bpkmreq_length = -1;
static int hf_docsis_bpkmreq_ident = -1;
static const value_string code_field_vals[] = {
{0, "Reserved"},
{1, "Reserved"},
{2, "Reserved"},
{3, "Reserved"},
{4, "Auth Request"},
{5, "Auth Reply"},
{6, "Auth Reject"},
{7, "Key Request"},
{8, "Key Reply"},
{9, "Key Reject"},
{10, "Auth Invalid"},
{11, "TEK Invalid"},
{12, "Authent Info"},
{13, "Map Request"},
{14, "Map Reply"},
{15, "Map Reject"},
{0, NULL},
};
/* Initialize the subtree pointers */
static gint ett_docsis_bpkmreq = -1;
static dissector_handle_t attrs_handle;
/* Code to actually dissect the packets */
static void
dissect_bpkmreq (tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree)
{
proto_item *it;
proto_tree *bpkmreq_tree;
guint8 code;
tvbuff_t *attrs_tvb;
code = tvb_get_guint8 (tvb, 0);
col_add_fstr (pinfo->cinfo, COL_INFO, "BPKM Request (%s)",
val_to_str (code, code_field_vals, "%d"));
if (tree)
{
it =
proto_tree_add_protocol_format (tree, proto_docsis_bpkmreq, tvb, 0, -1,
"BPKM Request Message");
bpkmreq_tree = proto_item_add_subtree (it, ett_docsis_bpkmreq);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_code, tvb, 0, 1,
ENC_BIG_ENDIAN);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_ident, tvb, 1, 1,
ENC_BIG_ENDIAN);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_length, tvb, 2, 2,
ENC_BIG_ENDIAN);
}
/* Code to Call subdissector */
attrs_tvb = tvb_new_subset_remaining (tvb, 4);
call_dissector (attrs_handle, attrs_tvb, pinfo, tree);
}
/* Register the protocol with Wireshark */
/* this format is require because a script is used to build the C function
that calls all the protocol registration.
*/
void
proto_register_docsis_bpkmreq (void)
{
/* Setup list of header fields See Section 1.6.1 for details*/
static hf_register_info hf[] = {
{&hf_docsis_bpkmreq_code,
{"BPKM Code", "docsis_bpkmreq.code",
FT_UINT8, BASE_DEC, VALS (code_field_vals), 0x0,
"BPKM Request Message", HFILL}
},
{&hf_docsis_bpkmreq_ident,
{"BPKM Identifier", "docsis_bpkmreq.ident",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL}
},
{&hf_docsis_bpkmreq_length,
{"BPKM Length", "docsis_bpkmreq.length",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL}
},
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_docsis_bpkmreq,
};
/* Register the protocol name and description */
proto_docsis_bpkmreq =
proto_register_protocol ("DOCSIS Baseline Privacy Key Management Request",
"DOCSIS BPKM-REQ", "docsis_bpkmreq");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array (proto_docsis_bpkmreq, hf, array_length (hf));
proto_register_subtree_array (ett, array_length (ett));
register_dissector ("docsis_bpkmreq", dissect_bpkmreq,
proto_docsis_bpkmreq);
}
/* If this dissector uses sub-dissector registration add a registration routine.
This format is required because a script is used to find these routines and
create the code that calls these routines.
*/
void
proto_reg_handoff_docsis_bpkmreq (void)
{
dissector_handle_t docsis_bpkmreq_handle;
docsis_bpkmreq_handle = find_dissector ("docsis_bpkmreq");
attrs_handle = find_dissector ("docsis_bpkmattr");
dissector_add_uint ("docsis_mgmt", 0x0C, docsis_bpkmreq_handle);
}
| Java |
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Tests\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\Structure\RealRowCountController;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tests\AbstractTestCase;
use PhpMyAdmin\Tests\Stubs\ResponseRenderer as ResponseStub;
use function json_encode;
/**
* @covers \PhpMyAdmin\Controllers\Database\Structure\RealRowCountController
*/
class RealRowCountControllerTest extends AbstractTestCase
{
public function testRealRowCount(): void
{
$GLOBALS['server'] = 1;
$GLOBALS['text_dir'] = 'ltr';
$GLOBALS['PMA_PHP_SELF'] = 'index.php';
$GLOBALS['cfg']['Server']['DisableIS'] = true;
$GLOBALS['is_db'] = true;
$GLOBALS['db'] = 'world';
$response = new ResponseStub();
$response->setAjax(true);
$_REQUEST['table'] = 'City';
(new RealRowCountController($response, new Template(), $this->dbi))();
$json = $response->getJSONResult();
$this->assertEquals('4,079', $json['real_row_count']);
$_REQUEST['real_row_count_all'] = 'on';
(new RealRowCountController($response, new Template(), $this->dbi))();
$json = $response->getJSONResult();
$expected = [
['table' => 'City', 'row_count' => 4079],
['table' => 'Country', 'row_count' => 239],
['table' => 'CountryLanguage', 'row_count' => 984],
];
$this->assertEquals(json_encode($expected), $json['real_row_count_all']);
}
}
| Java |
//
// This file was automatically generated by wxrc, do not edit by hand.
//
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include <wx/filesys.h>
#include <wx/fs_mem.h>
#include <wx/xrc/xmlres.h>
#include <wx/xrc/xh_all.h>
#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805
#define XRC_ADD_FILE(name, data, size, mime) \
wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)
#else
#define XRC_ADD_FILE(name, data, size, mime) \
wxMemoryFSHandler::AddFile(name, data, size)
#endif
static size_t xml_res_size_0 = 137;
static unsigned char xml_res_file_0[] = {
60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,
110,99,111,100,105,110,103,61,34,85,84,70,45,56,34,63,62,10,60,114,101,
115,111,117,114,99,101,32,120,109,108,110,115,61,34,104,116,116,112,58,
47,47,119,119,119,46,119,120,119,105,100,103,101,116,115,46,111,114,103,
47,119,120,120,114,99,34,62,10,32,32,60,33,45,45,32,72,97,110,100,108,101,
114,32,71,101,110,101,114,97,116,105,111,110,32,105,115,32,79,78,32,45,
45,62,10,60,47,114,101,115,111,117,114,99,101,62,10};
void wxC47E7InitBitmapResources()
{
// Check for memory FS. If not present, load the handler:
{
wxMemoryFSHandler::AddFile(wxT("XRC_resource/dummy_file"), wxT("dummy one"));
wxFileSystem fsys;
wxFSFile *f = fsys.OpenFile(wxT("memory:XRC_resource/dummy_file"));
wxMemoryFSHandler::RemoveFile(wxT("XRC_resource/dummy_file"));
if (f) delete f;
else wxFileSystem::AddHandler(new wxMemoryFSHandlerBase);
}
XRC_ADD_FILE(wxT("XRC_resource/continousbuildbasepane_continuousbuild_bitmaps.cpp$C__src_codelite_ContinuousBuild_continousbuildbasepane_continuousbuild_bitmaps.xrc"), xml_res_file_0, xml_res_size_0, wxT("text/xml"));
wxXmlResource::Get()->Load(wxT("memory:XRC_resource/continousbuildbasepane_continuousbuild_bitmaps.cpp$C__src_codelite_ContinuousBuild_continousbuildbasepane_continuousbuild_bitmaps.xrc"));
}
| Java |
<?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();
| Java |
-- license:BSD-3-Clause
-- copyright-holders:MAMEdev Team
---------------------------------------------------------------------------
--
-- tools.lua
--
-- Rules for the building of tools
--
---------------------------------------------------------------------------
--------------------------------------------------
-- romcmp
--------------------------------------------------
project("romcmp")
uuid ("1b40275b-194c-497b-8abd-9338775a21b8")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/romcmp.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- chdman
--------------------------------------------------
project("chdman")
uuid ("7d948868-42db-432a-9bb5-70ce5c5f4620")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/chdman.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
MAME_DIR .. "src/version.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- jedutil
--------------------------------------------------
project("jedutil")
uuid ("bda60edb-f7f5-489f-b232-23d33c43dda1")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/jedutil.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- unidasm
--------------------------------------------------
project("unidasm")
uuid ("65f81d3b-299a-4b08-a3fa-d5241afa9fd1")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"dasm",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/emu",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
files {
MAME_DIR .. "src/tools/unidasm.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- ldresample
--------------------------------------------------
project("ldresample")
uuid ("3401561a-4407-4e13-9c6d-c0801330f7cc")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/ldresample.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- ldverify
--------------------------------------------------
project("ldverify")
uuid ("3e66560d-b928-4227-928b-eadd0a10f00a")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/ldverify.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- regrep
--------------------------------------------------
project("regrep")
uuid ("7f6de580-d800-4e8d-bed6-9fc86829584d")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/regrep.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- srcclean
---------------------------------------------------
project("srcclean")
uuid ("4dd58139-313a-42c5-965d-f378bdeed220")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/srcclean.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- src2html
--------------------------------------------------
project("src2html")
uuid ("b31e963a-09ef-4696-acbd-e663e35ce6f7")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/src2html.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- split
--------------------------------------------------
project("split")
uuid ("8ef6ff18-3199-4cc2-afd0-d64033070faa")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/split.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- pngcmp
--------------------------------------------------
project("pngcmp")
uuid ("61f647d9-b129-409b-9c62-8acf98ed39be")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/pngcmp.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- nltool
--------------------------------------------------
project("nltool")
uuid ("853a03b7-fa37-41a8-8250-0dc23dd935d6")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
"netlist",
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "src/lib/netlist",
}
files {
MAME_DIR .. "src/lib/netlist/prg/nltool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- nlwav
--------------------------------------------------
project("nlwav")
uuid ("7c5396d1-2a1a-4c93-bed6-6b8fa182054a")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
"ocore_" .. _OPTIONS["osd"],
"netlist",
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "src/lib/netlist",
}
files {
MAME_DIR .. "src/lib/netlist/prg/nlwav.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- castool
--------------------------------------------------
project("castool")
uuid ("7d9ed428-e2ba-4448-832d-d882a64d5c22")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/castool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- floptool
--------------------------------------------------
project("floptool")
uuid ("85d8e3a6-1661-4ac9-8c21-281d20cbaf5b")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"emu",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/floptool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- imgtool
--------------------------------------------------
project("imgtool")
uuid ("f3707807-e587-4297-a5d8-bc98f3d0b1ca")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"emu",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
ext_includedir("zlib"),
MAME_DIR .. "src/tools/imgtool",
}
files {
MAME_DIR .. "src/tools/imgtool/main.cpp",
MAME_DIR .. "src/tools/imgtool/main.h",
MAME_DIR .. "src/tools/imgtool/stream.cpp",
MAME_DIR .. "src/tools/imgtool/stream.h",
MAME_DIR .. "src/tools/imgtool/library.cpp",
MAME_DIR .. "src/tools/imgtool/library.h",
MAME_DIR .. "src/tools/imgtool/modules.cpp",
MAME_DIR .. "src/tools/imgtool/modules.h",
MAME_DIR .. "src/tools/imgtool/iflopimg.cpp",
MAME_DIR .. "src/tools/imgtool/iflopimg.h",
MAME_DIR .. "src/tools/imgtool/filter.cpp",
MAME_DIR .. "src/tools/imgtool/filter.h",
MAME_DIR .. "src/tools/imgtool/filteoln.cpp",
MAME_DIR .. "src/tools/imgtool/filtbas.cpp",
MAME_DIR .. "src/tools/imgtool/imgtool.cpp",
MAME_DIR .. "src/tools/imgtool/imgtool.h",
MAME_DIR .. "src/tools/imgtool/imgterrs.cpp",
MAME_DIR .. "src/tools/imgtool/imgterrs.h",
MAME_DIR .. "src/tools/imgtool/imghd.cpp",
MAME_DIR .. "src/tools/imgtool/imghd.h",
MAME_DIR .. "src/tools/imgtool/charconv.cpp",
MAME_DIR .. "src/tools/imgtool/charconv.h",
MAME_DIR .. "src/tools/imgtool/formats/vt_dsk.cpp",
MAME_DIR .. "src/tools/imgtool/formats/vt_dsk.h",
MAME_DIR .. "src/tools/imgtool/formats/coco_dsk.cpp",
MAME_DIR .. "src/tools/imgtool/formats/coco_dsk.h",
MAME_DIR .. "src/tools/imgtool/modules/amiga.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macbin.cpp",
MAME_DIR .. "src/tools/imgtool/modules/rsdos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/os9.cpp",
MAME_DIR .. "src/tools/imgtool/modules/mac.cpp",
MAME_DIR .. "src/tools/imgtool/modules/ti99.cpp",
MAME_DIR .. "src/tools/imgtool/modules/ti990hd.cpp",
MAME_DIR .. "src/tools/imgtool/modules/concept.cpp",
MAME_DIR .. "src/tools/imgtool/modules/fat.cpp",
MAME_DIR .. "src/tools/imgtool/modules/fat.h",
MAME_DIR .. "src/tools/imgtool/modules/pc_flop.cpp",
MAME_DIR .. "src/tools/imgtool/modules/pc_hard.cpp",
MAME_DIR .. "src/tools/imgtool/modules/prodos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/vzdos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/thomson.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macutil.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macutil.h",
MAME_DIR .. "src/tools/imgtool/modules/cybiko.cpp",
MAME_DIR .. "src/tools/imgtool/modules/cybikoxt.cpp",
MAME_DIR .. "src/tools/imgtool/modules/psion.cpp",
MAME_DIR .. "src/tools/imgtool/modules/bml3.cpp",
MAME_DIR .. "src/tools/imgtool/modules/hp48.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- aueffectutil
--------------------------------------------------
if _OPTIONS["targetos"] == "macosx" then
project("aueffectutil")
uuid ("3db8316d-fad7-4f5b-b46a-99373c91550e")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
linkoptions {
"-sectcreate __TEXT __info_plist " .. MAME_DIR .. "src/tools/aueffectutil-Info.plist",
}
dependency {
{ "aueffectutil", MAME_DIR .. "src/tools/aueffectutil-Info.plist", true },
}
links {
"AudioUnit.framework",
"AudioToolbox.framework",
"CoreAudio.framework",
"CoreAudioKit.framework",
"CoreServices.framework",
}
files {
MAME_DIR .. "src/tools/aueffectutil.mm",
}
configuration { }
strip()
end
| Java |
/* hostlist_sctp.c 2008 Stig Bjorlykke
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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.
*/
#include "config.h"
#include <string.h>
#include <gtk/gtk.h>
#include "epan/packet.h"
#include <epan/stat_cmd_args.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-sctp.h>
#include "../stat_menu.h"
#include "ui/gtk/gui_stat_menu.h"
#include "ui/gtk/hostlist_table.h"
void register_tap_listener_sctp_hostlist(void);
static int
sctp_hostlist_packet(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip)
{
hostlist_table *hosts=(hostlist_table *)pit;
const struct _sctp_info *sctphdr=(const struct _sctp_info *)vip;
/* Take two "add" passes per packet, adding for each direction, ensures that all
packets are counted properly (even if address is sending to itself)
XXX - this could probably be done more efficiently inside hostlist_table */
add_hostlist_table_data(hosts, &sctphdr->ip_src, sctphdr->sport, TRUE, 1,
pinfo->fd->pkt_len, SAT_NONE, PT_SCTP);
add_hostlist_table_data(hosts, &sctphdr->ip_dst, sctphdr->dport, FALSE, 1,
pinfo->fd->pkt_len, SAT_NONE, PT_SCTP);
return 1;
}
static void
gtk_sctp_hostlist_init(const char *opt_arg, void* userdata _U_)
{
const char *filter=NULL;
if(!strncmp(opt_arg,"hosts,sctp,",11)){
filter=opt_arg+11;
} else {
filter=NULL;
}
init_hostlist_table(FALSE, "SCTP", "sctp", filter, sctp_hostlist_packet);
}
void
gtk_sctp_hostlist_cb(GtkAction *action _U_, gpointer user_data _U_)
{
gtk_sctp_hostlist_init("hosts,sctp",NULL);
}
void
register_tap_listener_sctp_hostlist(void)
{
register_stat_cmd_arg("hosts,sctp", gtk_sctp_hostlist_init,NULL);
register_hostlist_table(FALSE, "SCTP", "sctp", NULL /*filter*/, sctp_hostlist_packet);
}
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / 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()
{}
// ************************************************************************* //
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Mon Dec 02 20:33:00 CET 2013 -->
<title>NVTextureRectangle (LWJGL API)</title>
<meta name="date" content="2013-12-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NVTextureRectangle (LWJGL API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/NVTextureRectangle.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/opengl/NVTextureMultisample.html" title="class in org.lwjgl.opengl"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/opengl/NVTextureShader.html" title="class in org.lwjgl.opengl"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/opengl/NVTextureRectangle.html" target="_top">Frames</a></li>
<li><a href="NVTextureRectangle.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.lwjgl.opengl</div>
<h2 title="Class NVTextureRectangle" class="title">Class NVTextureRectangle</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.lwjgl.opengl.NVTextureRectangle</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public final class <span class="strong">NVTextureRectangle</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_PROXY_TEXTURE_RECTANGLE_NV">GL_PROXY_TEXTURE_RECTANGLE_NV</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_TEXTURE_BINDING_RECTANGLE_NV">GL_TEXTURE_BINDING_RECTANGLE_NV</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_TEXTURE_RECTANGLE_NV">GL_TEXTURE_RECTANGLE_NV</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="GL_TEXTURE_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_TEXTURE_RECTANGLE_NV</h4>
<pre>public static final int GL_TEXTURE_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_TEXTURE_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_TEXTURE_BINDING_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_TEXTURE_BINDING_RECTANGLE_NV</h4>
<pre>public static final int GL_TEXTURE_BINDING_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_TEXTURE_BINDING_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_PROXY_TEXTURE_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_PROXY_TEXTURE_RECTANGLE_NV</h4>
<pre>public static final int GL_PROXY_TEXTURE_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_PROXY_TEXTURE_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</h4>
<pre>public static final int GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/NVTextureRectangle.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/opengl/NVTextureMultisample.html" title="class in org.lwjgl.opengl"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/opengl/NVTextureShader.html" title="class in org.lwjgl.opengl"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/opengl/NVTextureRectangle.html" target="_top">Frames</a></li>
<li><a href="NVTextureRectangle.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i></small></p>
</body>
</html>
| Java |
<?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');
?> | Java |
/*
//@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 ([email protected])
//
// ************************************************************************
//@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
| Java |
/*
* Fence mechanism for dma-buf and to allow for asynchronous dma access
*
* Copyright (C) 2012 Canonical Ltd
* Copyright (C) 2012 Texas Instruments
*
* Authors:
* Rob Clark <[email protected]>
* Maarten Lankhorst <[email protected]>
*
* 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.
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/atomic.h>
#include <linux/fence.h>
#define CREATE_TRACE_POINTS
#include <trace/events/fence.h>
EXPORT_TRACEPOINT_SYMBOL(fence_annotate_wait_on);
EXPORT_TRACEPOINT_SYMBOL(fence_emit);
/*
* fence context counter: each execution context should have its own
* fence context, this allows checking if fences belong to the same
* context or not. One device can have multiple separate contexts,
* and they're used if some engine can run independently of another.
*/
static atomic_t fence_context_counter = ATOMIC_INIT(0);
/**
* fence_context_alloc - allocate an array of fence contexts
* @num: [in] amount of contexts to allocate
*
* This function will return the first index of the number of fences allocated.
* The fence context is used for setting fence->context to a unique number.
*/
unsigned fence_context_alloc(unsigned num)
{
BUG_ON(!num);
return atomic_add_return(num, &fence_context_counter) - num;
}
EXPORT_SYMBOL(fence_context_alloc);
/**
* fence_signal_locked - signal completion of a fence
* @fence: the fence to signal
*
* Signal completion for software callbacks on a fence, this will unblock
* fence_wait() calls and run all the callbacks added with
* fence_add_callback(). Can be called multiple times, but since a fence
* can only go from unsignaled to signaled state, it will only be effective
* the first time.
*
* Unlike fence_signal, this function must be called with fence->lock held.
*/
int fence_signal_locked(struct fence *fence)
{
struct fence_cb *cur, *tmp;
int ret = 0;
if (WARN_ON(!fence))
return -EINVAL;
if (!ktime_to_ns(fence->timestamp)) {
fence->timestamp = ktime_get();
smp_mb();
}
if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
ret = -EINVAL;
/*
* we might have raced with the unlocked fence_signal,
* still run through all callbacks
*/
} else
trace_fence_signaled(fence);
list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
list_del_init(&cur->node);
cur->func(fence, cur);
}
return ret;
}
EXPORT_SYMBOL(fence_signal_locked);
/**
* fence_signal - signal completion of a fence
* @fence: the fence to signal
*
* Signal completion for software callbacks on a fence, this will unblock
* fence_wait() calls and run all the callbacks added with
* fence_add_callback(). Can be called multiple times, but since a fence
* can only go from unsignaled to signaled state, it will only be effective
* the first time.
*/
int fence_signal(struct fence *fence)
{
unsigned long flags;
if (!fence)
return -EINVAL;
if (!ktime_to_ns(fence->timestamp)) {
fence->timestamp = ktime_get();
smp_mb();
}
if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
return -EINVAL;
trace_fence_signaled(fence);
if (test_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
struct fence_cb *cur, *tmp;
spin_lock_irqsave(fence->lock, flags);
list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
list_del_init(&cur->node);
cur->func(fence, cur);
}
spin_unlock_irqrestore(fence->lock, flags);
}
return 0;
}
EXPORT_SYMBOL(fence_signal);
/**
* fence_wait_timeout - sleep until the fence gets signaled
* or until timeout elapses
* @fence: [in] the fence to wait on
* @intr: [in] if true, do an interruptible wait
* @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
*
* Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
* remaining timeout in jiffies on success. Other error values may be
* returned on custom implementations.
*
* Performs a synchronous wait on this fence. It is assumed the caller
* directly or indirectly (buf-mgr between reservation and committing)
* holds a reference to the fence, otherwise the fence might be
* freed before return, resulting in undefined behavior.
*/
signed long
fence_wait_timeout(struct fence *fence, bool intr, signed long timeout)
{
signed long ret;
if (WARN_ON(timeout < 0))
return -EINVAL;
trace_fence_wait_start(fence);
ret = fence->ops->wait(fence, intr, timeout);
trace_fence_wait_end(fence);
return ret;
}
EXPORT_SYMBOL(fence_wait_timeout);
void fence_release(struct kref *kref)
{
struct fence *fence =
container_of(kref, struct fence, refcount);
trace_fence_destroy(fence);
BUG_ON(!list_empty(&fence->cb_list));
if (fence->ops->release)
fence->ops->release(fence);
else
fence_free(fence);
}
EXPORT_SYMBOL(fence_release);
void fence_free(struct fence *fence)
{
kfree_rcu(fence, rcu);
}
EXPORT_SYMBOL(fence_free);
/**
* fence_enable_sw_signaling - enable signaling on fence
* @fence: [in] the fence to enable
*
* this will request for sw signaling to be enabled, to make the fence
* complete as soon as possible
*/
void fence_enable_sw_signaling(struct fence *fence)
{
unsigned long flags;
if (!test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags) &&
!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
trace_fence_enable_signal(fence);
spin_lock_irqsave(fence->lock, flags);
if (!fence->ops->enable_signaling(fence))
fence_signal_locked(fence);
spin_unlock_irqrestore(fence->lock, flags);
}
}
EXPORT_SYMBOL(fence_enable_sw_signaling);
/**
* fence_add_callback - add a callback to be called when the fence
* is signaled
* @fence: [in] the fence to wait on
* @cb: [in] the callback to register
* @func: [in] the function to call
*
* cb will be initialized by fence_add_callback, no initialization
* by the caller is required. Any number of callbacks can be registered
* to a fence, but a callback can only be registered to one fence at a time.
*
* Note that the callback can be called from an atomic context. If
* fence is already signaled, this function will return -ENOENT (and
* *not* call the callback)
*
* Add a software callback to the fence. Same restrictions apply to
* refcount as it does to fence_wait, however the caller doesn't need to
* keep a refcount to fence afterwards: when software access is enabled,
* the creator of the fence is required to keep the fence alive until
* after it signals with fence_signal. The callback itself can be called
* from irq context.
*
*/
int fence_add_callback(struct fence *fence, struct fence_cb *cb,
fence_func_t func)
{
unsigned long flags;
int ret = 0;
bool was_set;
if (WARN_ON(!fence || !func))
return -EINVAL;
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
INIT_LIST_HEAD(&cb->node);
return -ENOENT;
}
spin_lock_irqsave(fence->lock, flags);
was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
ret = -ENOENT;
else if (!was_set) {
trace_fence_enable_signal(fence);
if (!fence->ops->enable_signaling(fence)) {
fence_signal_locked(fence);
ret = -ENOENT;
}
}
if (!ret) {
cb->func = func;
list_add_tail(&cb->node, &fence->cb_list);
} else
INIT_LIST_HEAD(&cb->node);
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_add_callback);
/**
* fence_remove_callback - remove a callback from the signaling list
* @fence: [in] the fence to wait on
* @cb: [in] the callback to remove
*
* Remove a previously queued callback from the fence. This function returns
* true if the callback is succesfully removed, or false if the fence has
* already been signaled.
*
* *WARNING*:
* Cancelling a callback should only be done if you really know what you're
* doing, since deadlocks and race conditions could occur all too easily. For
* this reason, it should only ever be done on hardware lockup recovery,
* with a reference held to the fence.
*/
bool
fence_remove_callback(struct fence *fence, struct fence_cb *cb)
{
unsigned long flags;
bool ret;
spin_lock_irqsave(fence->lock, flags);
ret = !list_empty(&cb->node);
if (ret)
list_del_init(&cb->node);
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_remove_callback);
struct default_wait_cb {
struct fence_cb base;
struct task_struct *task;
};
static void
fence_default_wait_cb(struct fence *fence, struct fence_cb *cb)
{
struct default_wait_cb *wait =
container_of(cb, struct default_wait_cb, base);
wake_up_state(wait->task, TASK_NORMAL);
}
/**
* fence_default_wait - default sleep until the fence gets signaled
* or until timeout elapses
* @fence: [in] the fence to wait on
* @intr: [in] if true, do an interruptible wait
* @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
*
* Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
* remaining timeout in jiffies on success.
*/
signed long
fence_default_wait(struct fence *fence, bool intr, signed long timeout)
{
struct default_wait_cb cb;
unsigned long flags;
signed long ret = timeout;
bool was_set;
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
return timeout;
spin_lock_irqsave(fence->lock, flags);
if (intr && signal_pending(current)) {
ret = -ERESTARTSYS;
goto out;
}
was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
goto out;
if (!was_set) {
trace_fence_enable_signal(fence);
if (!fence->ops->enable_signaling(fence)) {
fence_signal_locked(fence);
goto out;
}
}
cb.base.func = fence_default_wait_cb;
cb.task = current;
list_add(&cb.base.node, &fence->cb_list);
while (!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
if (intr)
__set_current_state(TASK_INTERRUPTIBLE);
else
__set_current_state(TASK_UNINTERRUPTIBLE);
spin_unlock_irqrestore(fence->lock, flags);
ret = schedule_timeout(ret);
spin_lock_irqsave(fence->lock, flags);
if (ret > 0 && intr && signal_pending(current))
ret = -ERESTARTSYS;
}
if (!list_empty(&cb.base.node))
list_del(&cb.base.node);
__set_current_state(TASK_RUNNING);
out:
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_default_wait);
/**
* fence_init - Initialize a custom fence.
* @fence: [in] the fence to initialize
* @ops: [in] the fence_ops for operations on this fence
* @lock: [in] the irqsafe spinlock to use for locking this fence
* @context: [in] the execution context this fence is run on
* @seqno: [in] a linear increasing sequence number for this context
*
* Initializes an allocated fence, the caller doesn't have to keep its
* refcount after committing with this fence, but it will need to hold a
* refcount again if fence_ops.enable_signaling gets called. This can
* be used for other implementing other types of fence.
*
* context and seqno are used for easy comparison between fences, allowing
* to check which fence is later by simply using fence_later.
*/
void
fence_init(struct fence *fence, const struct fence_ops *ops,
spinlock_t *lock, unsigned context, unsigned seqno)
{
BUG_ON(!lock);
BUG_ON(!ops || !ops->wait || !ops->enable_signaling ||
!ops->get_driver_name || !ops->get_timeline_name);
kref_init(&fence->refcount);
fence->ops = ops;
INIT_LIST_HEAD(&fence->cb_list);
fence->lock = lock;
fence->context = context;
fence->seqno = seqno;
fence->flags = 0UL;
trace_fence_init(fence);
}
EXPORT_SYMBOL(fence_init);
| Java |
/*
* 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();
}
| Java |
/*
* 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 << ')';
}
| Java |
/* 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 */
| Java |
GCC_VERSION := $(shell $(CONFIG_SHELL) $(PWD)/scripts/gcc-version.sh $(CROSS_COMPILE)gcc)
ifeq ($(GCC_VERSION),0404)
CFLAGS_REMOVE_msm_vfe8x.o = -Wframe-larger-than=1024
endif
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
EXTRA_CFLAGS += -Idrivers/media/video/msm/csi
EXTRA_CFLAGS += -Idrivers/media/video/msm/io
EXTRA_CFLAGS += -Idrivers/media/video/msm/sensors
obj-$(CONFIG_MSM_CAMERA) += msm_isp.o msm.o msm_mem.o msm_mctl.o msm_mctl_buf.o msm_mctl_pp.o
obj-$(CONFIG_MSM_CAMERA) += rawchip-v4l2/ io/ sensors/ actuators/ csi/
else
ifeq ($(CONFIG_ARCH_MSM8X60),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera-8x60.o sensors/
ifeq ($(CONFIG_CAMERA_3D),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera_liteon.o sensors/
endif
else
ifeq ($(CONFIG_ARCH_MSM7X30),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera-7x30.o sensors/ rawchip/
else
obj-$(CONFIG_MSM_CAMERA) += msm_camera.o
endif
endif
endif
obj-$(CONFIG_MSM_CAMERA) += msm_axi_qos.o
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_MSM_CAMERA) += gemini/
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash_v4l2.o
else
obj-$(CONFIG_MSM_CAMERA) += gemini_8x60/
ifeq ($(CONFIG_ARCH_MSM7X27A),y)
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash.o
else
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash_8x60.o
endif
endif
obj-$(CONFIG_ARCH_MSM_ARM11) += msm_vfe7x.o msm_io7x.o
obj-$(CONFIG_ARCH_MSM7X27A) += msm_vfe7x27a.o msm_io_7x27a.o
obj-$(CONFIG_ARCH_MSM7X30) += msm_vfe_7x30.o msm_io_7x30.o msm_vpe1_7x30.o
obj-$(CONFIG_ARCH_QSD8X50) += msm_vfe8x.o msm_vfe8x_proc.o msm_io8x.o
ifdef CONFIG_S5K4E5YX
obj-$(CONFIG_MACH_BLISS) += s5k4e5yx.o s5k4e5yx_reg_bls.o
obj-$(CONFIG_MACH_BLISSC) += s5k4e5yx.o s5k4e5yx_reg_bls.o
obj-$(CONFIG_MACH_PRIMOU) += s5k4e5yx.o s5k4e5yx_reg_pro.o
obj-$(CONFIG_MACH_PRIMOC) += s5k4e5yx.o s5k4e5yx_reg_pro.o
obj-$(CONFIG_MACH_KINGDOM) += s5k4e5yx.o s5k4e5yx_reg_kin.o
endif
ifdef CONFIG_MACH_VISION
obj-$(CONFIG_S5K4E1GX) += s5k4e1gx.o s5k4e1gx_reg.o
endif
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60_v4l2.o msm_vfe31_v4l2.o msm_vpe_8x60_v4l2.o
else
ifdef CONFIG_CAMERA_ZSL
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60_ZSL.o msm_vpe1_8x60.o
else
ifdef CONFIG_CAMERA_3D
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60.o msm_vpe1_8x60.o
obj-$(CONFIG_ARCH_MSM8X60) += msm_vfe31_liteon.o msm_vpe1_liteon.o
else
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60.o msm_vpe1_8x60.o
endif
endif
endif
obj-$(CONFIG_ARCH_MSM8960) += msm_io_8960.o msm_ispif.o msm_vfe32.o msm_vpe.o
obj-$(CONFIG_MT9T013) += mt9t013.o mt9t013_reg.o
obj-$(CONFIG_SN12M0PZ) += sn12m0pz.o sn12m0pz_reg.o
obj-$(CONFIG_MT9P012) += mt9p012_reg.o
ifeq ($(CONFIG_S5K4E1),y)
ifdef CONFIG_MACH_PRIMOTD
obj-$(CONFIG_S5K4E1) += s5k4e1_td.o s5k4e1_reg_td.o
else
ifdef CONFIG_MACH_GOLFC
obj-$(CONFIG_S5K4E1) += s5k4e1_ff.o s5k4e1_reg_ff.o
else
obj-$(CONFIG_S5K4E1) += s5k4e1.o s5k4e1_reg.o
endif
endif
endif
obj-$(CONFIG_MSM_CAMERA_AF_FOXCONN) += mt9p012_fox.o
obj-$(CONFIG_MSM_CAMERA_AF_BAM) += mt9p012_bam.o
obj-$(CONFIG_MT9P012_KM) += mt9p012_km.o mt9p012_km_reg.o
obj-$(CONFIG_MT9E013) += mt9e013.o mt9e013_reg.o
obj-$(CONFIG_S5K3E2FX) += s5k3e2fx.o
ifdef CONFIG_MACH_PYRAMID
obj-$(CONFIG_S5K3H1GX) += s5k3h1gx.o s5k3h1gx_reg.o
endif
ifdef CONFIG_S5K3H1GX
obj-$(CONFIG_MACH_SPADE) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVO) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVOW) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVOW_CT) += s5k3h1gx.o s5k3h1gx_reg.o
endif
#FIXME: Merge the two ifeq causes VX6953 preview not coming up.
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_VX6953) += vx6953_v4l2.o vx6953_reg_v4l2.o
obj-$(CONFIG_MT9V113) += mt9v113_v4l2.o mt9v113_ville_reg_lens_9251.o
else
obj-$(CONFIG_MT9V113) += mt9v113.o mt9v113_reg_lens_9251.o
obj-$(CONFIG_VX6953) += vx6953.o vx6953_reg.o
obj-$(CONFIG_IMX074) += imx074.o imx074_reg.o
endif
obj-$(CONFIG_QS_MT9P017) += qs_mt9p017.o qs_mt9p017_reg.o
obj-$(CONFIG_VB6801) += vb6801.o
obj-$(CONFIG_IMX072) += imx072.o imx072_reg.o
obj-$(CONFIG_WEBCAM_OV9726) += ov9726.o ov9726_reg.o
obj-$(CONFIG_WEBCAM_OV7692) += ov7692.o
obj-$(CONFIG_OV8810) += ov8810.o
obj-$(CONFIG_MT9D112) += mt9d112.o mt9d112_reg.o
obj-$(CONFIG_MT9D113) += mt9d113.o mt9d113_reg.o
| Java |
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
| Java |
/*
* ------------------------------------------------------------------------
* JA Slideshow Module for J25 & J31
* ------------------------------------------------------------------------
* Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
.ja-slidewrap_erio {
width: 100%;
position: relative;
}
.ja-slide-item img {
background: #fff;
}
.active .ja-slide-thumb-inner {
border: none;
color: #fff;
}
.active .ja-slide-thumb-inner img {
background: #57212A;
border: 1px solid #67373F;
}
.ja-slide-thumbs-mask-left,
.ja-slide-thumbs-mask-right,
.ja-slide-thumbs-mask-center {
float: left;
}
.ja-slide-thumbs-mask-left, .ja-slide-thumbs-mask-right {}
/* Mask Desc */
.maskDesc {
z-index: 11;
top: 0;
}
.main .maskDesc .inner {
padding: 0 0 0 510px;
position: absolute;
top: 252px;
left: 0;
z-index: 12;
}
.maskDesc a.readon {
background: #61abd6;
color: #fff;
padding: 7px 15px 6px;
display: inline-block;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
.maskDesc a.readon span { cursor: pointer; }
.maskDesc a.readmore { margin-top: 30px; }
.maskDesc a.readon:hover, .maskDesc a.readon:active, .maskDesc a.readon:focus {
background: #666;
}
.ja-slide-desc {
position: absolute;
top: 0;
right: 0;
height: 268px;
width: 390px;
background: #000;
opacity: .9;
filter: alpha(opacity = 90);
padding: 52px 40px 40px;
}
div.ja-moduletable .ja-slide-desc h3 {
color: #fff;
font-size: 300%;
}
div.ja-moduletable .ja-slide-desc h3 a { color: #fff; }
.ja-slide-desc p { color: #7b7d80; line-height: 2; }
/* Slide buttons */
#ja-slideshow .ja-slide-buttons {
height: 10px;
position: relative;
top: 10px;
width: 28px;
bottom: 0;
left: 470px !important;
z-index: 50;
}
.ja-slide-buttons .ja-slide-playback, .ja-slide-buttons .ja-slide-stop,
.ja-slide-buttons .ja-slide-play {
display: none !important;
}
.ja-slide-buttons span.ja-slide-prev, .ja-slide-buttons span.ja-slide-next {
width: 10px;
height: 10px;
font-size: 0px;
line-height: 0px;
text-indent: -9999em;
background: url("thumb.png") no-repeat scroll left top;
padding: 0px !important;
margin: 0px 0px 0px 3px !important;
}
.ja-slide-buttons span.ja-slide-prev.hover,
.ja-slide-buttons span.ja-slide-next.hover {
background: url("thumb.png") no-repeat scroll left bottom;
}
.ja-slide-buttons span {
color: #fff;
cursor: pointer;
display: block;
float: left;
margin-right: 5px;
padding: 2px 5px;
background: #61abd6;
}
/* From Articles */
.ja-articles .ja-slide-thumbs-handles,
.ja-slide-thumbs-wrap .ja-slide-thumbs-handles {
opacity: 0.001 !important;
filter: alpha(opacity = 0.10) !important;
background: #000 ;
}
.ja-slide-thumbs, .ja-slide-thumbs-mask, .ja-slide-thumbs-handles {
width: auto;
height: auto;
position: absolute;
top: 0;
left: 0 !important;
}
.ja-slide-thumb-inner {
background: none;
border: none;
margin: 0px !important;
padding: 0px !important;
}
#ja-slideshow .ja-slide-thumb img {
padding: 0px !important;
border: none;
margin: 0px !important;
}
#ja-slideshow .ja-slide-thumbs-wrap {
bottom: 0px;
right: 0px;
background: none;
}
p.ja-slide-thumbs-handles {
z-index: 1000;
}
.ja-slide-thumb .ja-slide-thumb-inner,
.ja-slide-thumbs .ja-slide-thumb {
background: #000 !important;
opacity: 0.3;
filter: alpha(opacity = 30);
}
.ja-slide-thumb.active .ja-slide-thumb-inner,
.ja-slide-thumbs .ja-slide-thumb.active {
opacity: 1;
filter: alpha(opacity = 100);
}
.ja-slide-thumb-inner h3 {
display: none;
}
.ja-slide-thumbs-mask {
background: #000;
opacity: 0.1;
filter: alpha(opacity = 10);
}
.ja-slide-desc a {
color: #fff;
font-size: 300%;
line-height: 1.2;
margin: 0px 0px 25px;
padding: 0px 0px 13px;
background: url(short_hor_line.gif) no-repeat scroll 0 100%;
display: block;
font-family: Helvetica,Arial,sans-serif;
}
.ja-slide-desc a:hover,
.ja-slide-desc a:focus,
.ja-slide-desc a:active {
color: #fff;
} | Java |
/*
* 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;
}
| Java |
/*
* 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);
}
}
| Java |
#!/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)
| Java |
/* SPDX-License-Identifier: LGPL-2.1+ */
#pragma once
#define VERB_ANY ((unsigned) -1)
typedef enum VerbFlags {
VERB_DEFAULT = 1 << 0,
VERB_ONLINE_ONLY = 1 << 1,
VERB_MUST_BE_ROOT = 1 << 2,
} VerbFlags;
typedef struct {
const char *verb;
unsigned min_args, max_args;
VerbFlags flags;
int (* const dispatch)(int argc, char *argv[], void *userdata);
} Verb;
bool running_in_chroot_or_offline(void);
int dispatch_verb(int argc, char *argv[], const Verb verbs[], void *userdata);
| Java |
/* SPDX-License-Identifier: LGPL-2.1+ */
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd 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
(at your option) any later version.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include "hostname-setup.h"
#include "util.h"
int main(int argc, char* argv[]) {
int r;
r = hostname_setup();
if (r < 0)
log_error_errno(r, "hostname: %m");
return 0;
}
| Java |
/* NSDate+MAPIStore.h - this file is part of SOGo
*
* Copyright (C) 2010-2012 Inverse inc.
*
* Author: Wolfgang Sourdeau <[email protected]>
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef NSCALENDARDATE_MAPISTORE_H
#define NSCALENDARDATE_MAPISTORE_H
#import <Foundation/NSDate.h>
@class NSCalendarDate;
@interface NSDate (MAPIStoreDataTypes)
+ (NSCalendarDate *) dateFromMinutesSince1601: (uint32_t) minutes;
- (uint32_t) asMinutesSince1601;
+ (id) dateFromFileTime: (const struct FILETIME *) timeValue;
- (struct FILETIME *) asFileTimeInMemCtx: (void *) memCtx;
- (BOOL) isNever; /* occurs on 4500-12-31 */
+ (NSCalendarDate *) dateFromSystemTime: (struct SYSTEMTIME) date
andRuleYear: (uint16_t) rYear;
@end
NSComparisonResult NSDateCompare (id date1, id date2, void *);
#endif /* NSCALENDARDATE+MAPISTORE_H */
| Java |
### 1.7.3 - 15/04/2015
Changes:
* Fixed #114 Background image appears when page is loading
### 1.7.1 - 08/04/2015
Changes:
* Fixed XSS vulnerability with contact form
### 1.7.1 - 07/04/2015
Changes:
* Padding issue
* Fixed #104 No image appears on the blog page on IE8
### 1.6.9 - 04/04/2015
Changes:
* Fixed #85, error in js, when contact form is not displayed, which caused about us circles to stop working
* Fixed #82, problem with Our Focus widget colors
* Replaced screenshot with the new format
1200x900
.jpg -> .png
* Merge pull request #87 from DragosBubu/development
Replaced screenshot with the new format
* Fixed #80 No Compatible with IE9
* Fixed #94 WooCommerce Pagination Issue
* Fixed #95 Featured products issue
* This fixes #88
New screenshot
* Merge pull request #96 from DragosBubu/development
This fixes #88
* Fixed #99, removed sidebar from woocommerce templates
* Fixed #100, removed sidebar from checkout page
* Fixed #101, theme not loading on IE8, included scrollReveal.js for versions greater then IE8
* H tags incompatible with plugins
* Fixed large bottom padding on frontpage sections
* Introduced new (large) template for Blog
* Fixed #103 Blog alignment problem
* Fixed #105 New blog template looks very bad on IE8
### 1.6.0 - 17/03/2015
Changes:
* Woocommerce style issues
* Fixed Shop page mobile issue
* Fixed #79 Responsive menu issues
* Fixed #78, added author link for testimonial widget
### 1.5.4 - 05/03/2015
Changes:
* Latest news issue on iPad
* Woocommerce display for older versions
* Branding
- Modified background image
+ added focus images
* Branding - follow-up
removed unnecessary images
added screenshot
* Replaced screenshot
* Merge pull request #74 from DragosBubu/development
Branding
### 1.4.7 - 12/02/2015
Changes:
* Fixed #62, #51 our team widgets default alignment
* Increased version
### 1.4.6 - 06/02/2015
Changes:
* Open social links in new tab
Open social links in new tab
* added travis
added travis
* fixed travis
* fixed syntax error
* Update style.css
* Merge pull request #56 from HardeepAsrani/development
Open social links in new tab
* remove travis
### 1.4.5 - 30/01/2015
Changes:
* Update style.css
* Update customizer.php
### 1.4.5 - 30/01/2015
Changes:
* Update style.css
* Update style.css
* Update style.css
* Fixed #42, big title enclosing tag h1 , not h6
* Fixed #44, disable preloader from customizer
* Fix #38, fixed our focus section hover colors
* Fixed #48, replace wp product review by login customizer
* Fixed #41, reversed telephone and mail icons in footer
* Fixed #40, fixed team member widgets for more than 4
* Fixed #32, load customizer scripts just in customizer, not in all backend pages
* Fix #16, hover efects for our focus widgets, when more than 4
### 1.4.4 - 19/01/2015
Changes:
* This fixes #35, translate strings plus generate pot file
* Fixes our focus centering when theme is first installed
* Update style.css
### 1.4.3 - 09/01/2015
Changes:
* This fixes #31 , translation issue
* This fixes #30, wrong textdomain
* This fixes #28, header cuts of title on mobile
* This fixes #9, overlap header with text
* Aliniere compononete Our focus
* Footer apare in partea de jos a ecranului, dar nu a site-ului
* This fixes #22, .pot file
### 1.4.2 - 08/01/2015
Changes:
* This fixes #13 upsell in customizer
* This fixes #22, updated pot file
* THis fixes #15, responsive background image
* This fixes #23, changing section names in customizer
* This fixes #24, hover radio buttons, + update style version
* Cart without sidebar
* This fixes #25, remove widget customizer for wp greater versions
### 1.4.1 - 02/01/2015
Changes:
* disable fonts for some languages
* Update style.css
* Update functions.php
### 1.4.0 - 31/12/2014
Changes:
* Merge pull request #20 from Codeinwp/production
merge back-ward
* added full width page
### 1.3.5 - 19/11/2014
Changes:
* Update home.php
* Update style.css
### 1.3.4 - 19/11/2014
Changes:
* fixed form subject issue, added linkedin icon and icons for socials, our focus clickable, contact section button and email, link on read more
* Added pro extra options in customizer
* woocommerce , wpml and rtl support, fixed undefined index errors, changed description, added more themes page and fixed front page
* fixed wrong description, links and tagline
fixed wrong description, links and tagline
* Fixed fotter and added woocommerce style
* Frontpage template
* Fixed wp.org fronpage and blog
* Update home.php
### 1.1 - 23/10/2014
Changes:
* Fixed dropdown menu
* Updated theme version
### 1.0.9 - 21/10/2014
Changes:
* Fixed fonts, added fontawesome notification footer links
Fixed fonts, added fontawesome notification footer links
### 1.0.7 - 21/10/2014
Changes:
* removed widget customizer plugin
* Update style.css
### 1.0.6 - 20/10/2014
Changes:
* Update functions.php
* fixed the font issue with https websites
### 1.0.5 - 17/10/2014
Changes:
* First version
* some fixes for responsive
* I added <Product Rewiew> and <Tweet old post> plugin
* removed error.log
* sync with wp.org
| Java |
<?php
class ITSEC_Away_Mode {
function run() {
//Execute away mode functions on admin init
add_filter( 'itsec_logger_modules', array( $this, 'register_logger' ) );
add_action( 'itsec_admin_init', array( $this, 'execute_away_mode' ) );
add_action( 'login_init', array( $this, 'execute_away_mode' ) );
//Register Sync
add_filter( 'itsec_sync_modules', array( $this, 'register_sync' ) );
}
/**
* Check if away mode is active
*
* @since 4.4
*
* @param array $input [NULL] Input of options to check if calling from form
* @param bool $remaining will return the number of seconds remaining
* @param bool $override Whether or not we're calculating override values
*
* @return mixed true if locked out else false or times until next condition (negative until lockout, positive until release)
*/
public static function check_away( $input = NULL, $remaining = false, $override = false ) {
global $itsec_globals;
ITSEC_Lib::clear_caches(); //lets try to make sure nothing is storing a bad time
$form = true;
$has_away_file = @file_exists( $itsec_globals['ithemes_dir'] . '/itsec_away.confg' );
$status = false; //assume they're not locked out to start
//Normal usage check
if ( $input === NULL ) { //if we didn't provide input to check we need to get it
$form = false;
$input = get_site_option( 'itsec_away_mode' );
}
if ( ( $form === false && ! isset( $input['enabled'] ) ) || ! isset( $input['type'] ) || ! isset( $input['start'] ) || ! isset( $input['end'] ) || ! $has_away_file ) {
return false; //if we don't have complete settings don't lock them out
}
$current_time = $itsec_globals['current_time']; //use current time
$enabled = isset( $input['enabled'] ) ? $input['enabled'] : $form;
$test_type = $input['type'];
$test_start = $input['start'];
$test_end = $input['end'];
if ( $test_type === 1 ) { //daily
$test_start -= strtotime( date( 'Y-m-d', $test_start ) );
$test_end -= strtotime( date( 'Y-m-d', $test_end ) );
$day_seconds = $current_time - strtotime( date( 'Y-m-d', $current_time ) );
if ( $test_start === $test_end ) {
$status = false;
}
if ( $test_start < $test_end ) { //same day
if ( $test_start <= $day_seconds && $test_end >= $day_seconds && $enabled === true ) {
$status = $test_end - $day_seconds;
}
} else { //overnight
if ( ( $test_start < $day_seconds || $test_end > $day_seconds ) && $enabled === true ) {
if ( $day_seconds >= $test_start ) {
$status = ( 86400 - $day_seconds ) + $test_end;
} else {
$status = $test_end - $day_seconds;
}
}
}
} else if ( $test_start !== $test_end && $test_start <= $current_time && $test_end >= $current_time && $enabled === true ) { //one time
$status = $test_end - $current_time;
}
//they are allowed to log in
if ( $status === false ) {
if ( $test_type === 1 ) {
if ( $day_seconds > $test_start ) { //actually starts tomorrow
$status = - ( ( 86400 + $test_start ) - $day_seconds );
} else { //starts today
$status = - ( $test_start - $day_seconds );
}
} else {
$status = - ( $test_start - $current_time );
if ( $status > 0 ) {
if ( $form === false && isset( $input['enabled'] ) && $input['enabled'] === true ) { //disable away mode if one-time is in the past
$input['enabled'] = false;
update_site_option( 'itsec_away_mode', $input );
}
$status = 0;
}
}
}
if ( $override === false ) {
//work in an override from sync
$override_option = get_site_option( 'itsec_away_mode_sync_override' );
$override = $override_option['intention'];
$expires = $override_option['expires'];
if ( $expires < $itsec_globals['current_time'] ) {
delete_site_option( 'itsec_away_mode_sync_override' );
} else {
if ( $override === 'activate' ) {
if ( $status <= 0 ) { //not currently locked out
$input['start'] = $current_time - 1;
$status = ITSEC_Away_Mode::check_away( $input, true, true );
} else {
delete_site_option( 'itsec_away_mode_sync_override' );
}
} elseif ( $override === 'deactivate' ) {
if ( $status > 0 ) { //currently locked out
$input['end'] = $current_time - 1;
$status = ITSEC_Away_Mode::check_away( $input, true, true );
} else {
delete_site_option( 'itsec_away_mode_sync_override' );
}
}
}
}
if ( $remaining === true ) {
return $status;
} else {
if ( $status > 0 && $status !== false ) {
return true;
}
}
return false; //always default to NOT locking folks out
}
/**
* Execute away mode functionality
*
* @return void
*/
public function execute_away_mode() {
global $itsec_logger;
//execute lockout if applicable
if ( $this->check_away() ) {
$itsec_logger->log_event(
'away_mode',
5,
array(
__( 'A host was prevented from accessing the dashboard due to away-mode restrictions being in effect',
'it-l10n-better-wp-security' ),
),
ITSEC_Lib::get_ip(),
'',
'',
'',
''
);
wp_redirect( get_option( 'siteurl' ) );
wp_clear_auth_cookie();
}
}
/**
* Register 404 and file change detection for logger
*
* @param array $logger_modules array of logger modules
*
* @return array array of logger modules
*/
public function register_logger( $logger_modules ) {
$logger_modules['away_mode'] = array(
'type' => 'away_mode',
'function' => __( 'Away Mode Triggered', 'it-l10n-better-wp-security' ),
);
return $logger_modules;
}
/**
* Register Lockouts for Sync
*
* @param array $sync_modules array of logger modules
*
* @return array array of logger modules
*/
public function register_sync( $sync_modules ) {
$sync_modules['away_mode'] = array(
'verbs' => array(
'itsec-get-away-mode' => 'Ithemes_Sync_Verb_ITSEC_Get_Away_Mode',
'itsec-override-away-mode' => 'Ithemes_Sync_Verb_ITSEC_Override_Away_Mode'
),
'everything' => 'itsec-get-away-mode',
'path' => dirname( __FILE__ ),
);
return $sync_modules;
}
}
| Java |
/*
* Altera SoCFPGA PinMux configuration
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SOCFPGA_PINMUX_CONFIG_H__
#define __SOCFPGA_PINMUX_CONFIG_H__
const u8 sys_mgr_init_table[] = {
3, /* EMACIO0 */
2, /* EMACIO1 */
2, /* EMACIO2 */
2, /* EMACIO3 */
2, /* EMACIO4 */
2, /* EMACIO5 */
2, /* EMACIO6 */
2, /* EMACIO7 */
2, /* EMACIO8 */
3, /* EMACIO9 */
2, /* EMACIO10 */
2, /* EMACIO11 */
2, /* EMACIO12 */
2, /* EMACIO13 */
0, /* EMACIO14 */
0, /* EMACIO15 */
0, /* EMACIO16 */
0, /* EMACIO17 */
0, /* EMACIO18 */
0, /* EMACIO19 */
3, /* FLASHIO0 */
0, /* FLASHIO1 */
3, /* FLASHIO2 */
3, /* FLASHIO3 */
3, /* FLASHIO4 */
3, /* FLASHIO5 */
3, /* FLASHIO6 */
3, /* FLASHIO7 */
0, /* FLASHIO8 */
3, /* FLASHIO9 */
3, /* FLASHIO10 */
3, /* FLASHIO11 */
0, /* GENERALIO0 */
1, /* GENERALIO1 */
1, /* GENERALIO2 */
0, /* GENERALIO3 */
0, /* GENERALIO4 */
1, /* GENERALIO5 */
1, /* GENERALIO6 */
1, /* GENERALIO7 */
1, /* GENERALIO8 */
0, /* GENERALIO9 */
0, /* GENERALIO10 */
0, /* GENERALIO11 */
0, /* GENERALIO12 */
2, /* GENERALIO13 */
2, /* GENERALIO14 */
3, /* GENERALIO15 */
3, /* GENERALIO16 */
2, /* GENERALIO17 */
2, /* GENERALIO18 */
0, /* GENERALIO19 */
0, /* GENERALIO20 */
0, /* GENERALIO21 */
0, /* GENERALIO22 */
0, /* GENERALIO23 */
0, /* GENERALIO24 */
0, /* GENERALIO25 */
0, /* GENERALIO26 */
0, /* GENERALIO27 */
0, /* GENERALIO28 */
0, /* GENERALIO29 */
0, /* GENERALIO30 */
0, /* GENERALIO31 */
2, /* MIXED1IO0 */
2, /* MIXED1IO1 */
2, /* MIXED1IO2 */
2, /* MIXED1IO3 */
2, /* MIXED1IO4 */
2, /* MIXED1IO5 */
2, /* MIXED1IO6 */
2, /* MIXED1IO7 */
2, /* MIXED1IO8 */
2, /* MIXED1IO9 */
2, /* MIXED1IO10 */
2, /* MIXED1IO11 */
2, /* MIXED1IO12 */
2, /* MIXED1IO13 */
0, /* MIXED1IO14 */
3, /* MIXED1IO15 */
3, /* MIXED1IO16 */
3, /* MIXED1IO17 */
3, /* MIXED1IO18 */
3, /* MIXED1IO19 */
3, /* MIXED1IO20 */
0, /* MIXED1IO21 */
0, /* MIXED2IO0 */
0, /* MIXED2IO1 */
0, /* MIXED2IO2 */
0, /* MIXED2IO3 */
0, /* MIXED2IO4 */
0, /* MIXED2IO5 */
0, /* MIXED2IO6 */
0, /* MIXED2IO7 */
0, /* GPLINMUX48 */
0, /* GPLINMUX49 */
0, /* GPLINMUX50 */
0, /* GPLINMUX51 */
0, /* GPLINMUX52 */
0, /* GPLINMUX53 */
0, /* GPLINMUX54 */
0, /* GPLINMUX55 */
0, /* GPLINMUX56 */
0, /* GPLINMUX57 */
0, /* GPLINMUX58 */
0, /* GPLINMUX59 */
0, /* GPLINMUX60 */
0, /* GPLINMUX61 */
0, /* GPLINMUX62 */
0, /* GPLINMUX63 */
0, /* GPLINMUX64 */
0, /* GPLINMUX65 */
0, /* GPLINMUX66 */
0, /* GPLINMUX67 */
0, /* GPLINMUX68 */
0, /* GPLINMUX69 */
0, /* GPLINMUX70 */
1, /* GPLMUX0 */
1, /* GPLMUX1 */
1, /* GPLMUX2 */
1, /* GPLMUX3 */
1, /* GPLMUX4 */
1, /* GPLMUX5 */
1, /* GPLMUX6 */
1, /* GPLMUX7 */
1, /* GPLMUX8 */
1, /* GPLMUX9 */
1, /* GPLMUX10 */
1, /* GPLMUX11 */
1, /* GPLMUX12 */
1, /* GPLMUX13 */
1, /* GPLMUX14 */
1, /* GPLMUX15 */
1, /* GPLMUX16 */
1, /* GPLMUX17 */
1, /* GPLMUX18 */
1, /* GPLMUX19 */
1, /* GPLMUX20 */
1, /* GPLMUX21 */
1, /* GPLMUX22 */
1, /* GPLMUX23 */
1, /* GPLMUX24 */
1, /* GPLMUX25 */
1, /* GPLMUX26 */
1, /* GPLMUX27 */
1, /* GPLMUX28 */
1, /* GPLMUX29 */
1, /* GPLMUX30 */
1, /* GPLMUX31 */
1, /* GPLMUX32 */
1, /* GPLMUX33 */
1, /* GPLMUX34 */
1, /* GPLMUX35 */
1, /* GPLMUX36 */
1, /* GPLMUX37 */
1, /* GPLMUX38 */
1, /* GPLMUX39 */
1, /* GPLMUX40 */
1, /* GPLMUX41 */
1, /* GPLMUX42 */
1, /* GPLMUX43 */
1, /* GPLMUX44 */
1, /* GPLMUX45 */
1, /* GPLMUX46 */
1, /* GPLMUX47 */
1, /* GPLMUX48 */
1, /* GPLMUX49 */
1, /* GPLMUX50 */
1, /* GPLMUX51 */
1, /* GPLMUX52 */
1, /* GPLMUX53 */
1, /* GPLMUX54 */
1, /* GPLMUX55 */
1, /* GPLMUX56 */
1, /* GPLMUX57 */
1, /* GPLMUX58 */
1, /* GPLMUX59 */
1, /* GPLMUX60 */
1, /* GPLMUX61 */
1, /* GPLMUX62 */
1, /* GPLMUX63 */
1, /* GPLMUX64 */
1, /* GPLMUX65 */
1, /* GPLMUX66 */
1, /* GPLMUX67 */
1, /* GPLMUX68 */
1, /* GPLMUX69 */
1, /* GPLMUX70 */
0, /* NANDUSEFPGA */
0, /* UART0USEFPGA */
0, /* RGMII1USEFPGA */
0, /* SPIS0USEFPGA */
0, /* CAN0USEFPGA */
0, /* I2C0USEFPGA */
0, /* SDMMCUSEFPGA */
0, /* QSPIUSEFPGA */
0, /* SPIS1USEFPGA */
0, /* RGMII0USEFPGA */
0, /* UART1USEFPGA */
0, /* CAN1USEFPGA */
0, /* USB1USEFPGA */
0, /* I2C3USEFPGA */
0, /* I2C2USEFPGA */
0, /* I2C1USEFPGA */
0, /* SPIM1USEFPGA */
0, /* USB0USEFPGA */
0 /* SPIM0USEFPGA */
};
#endif /* __SOCFPGA_PINMUX_CONFIG_H__ */
| Java |
<?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 [email protected] 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];
}
}
| Java |
#!/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:])
| Java |
/* Copyright (C) 1991, 1993, 1995, 1996, 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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 (at your option) any later version.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <stdlib.h>
/* Execute LINE as a shell command. */
int
__libc_system (line)
const char *line;
{
if (line == NULL)
return 0; /* This indicates no command processor. */
__sys_errno (ENOSYS);
return -1;
}
weak_alias (__libc_system, system)
stub_warning (system)
#include <stub-tag.h>
| Java |
/* 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;
}
}
| Java |
/* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#ifndef CRYPT_HASHGEN_IMPL_H
#define CRYPT_HASHGEN_IMPL_H
#define ROUNDS_DEFAULT 5000
#define ROUNDS_MIN 1000
#define ROUNDS_MAX ROUNDS_DEFAULT
#define MIXCHARS 32
#define CRYPT_SALT_LENGTH 20
#define CRYPT_MAGIC_LENGTH 3
#define CRYPT_PARAM_LENGTH 13
#define SHA256_HASH_LENGTH 43
#define CRYPT_MAX_PASSWORD_SIZE (CRYPT_SALT_LENGTH + \
SHA256_HASH_LENGTH + \
CRYPT_MAGIC_LENGTH + \
CRYPT_PARAM_LENGTH)
#define MAX_PLAINTEXT_LENGTH 256
#include <stddef.h>
#include <my_global.h>
int extract_user_salt(char **salt_begin,
char **salt_end);
C_MODE_START
char *
my_crypt_genhash(char *ctbuffer,
size_t ctbufflen,
const char *plaintext,
int plaintext_len,
const char *switchsalt,
const char **params);
void generate_user_salt(char *buffer, int buffer_len);
void xor_string(char *to, int to_len, char *pattern, int pattern_len);
C_MODE_END
#endif
| Java |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2007-2008, Trinity College Computing Center
* Written by David Chappell <[email protected]>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Trivial application to read an extension into a variable
*
* \author David Chappell <[email protected]>
*
* \ingroup applications
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_REGISTER_FILE()
#include "asterisk/file.h"
#include "asterisk/pbx.h"
#include "asterisk/app.h"
#include "asterisk/module.h"
#include "asterisk/indications.h"
#include "asterisk/channel.h"
/*** DOCUMENTATION
<application name="ReadExten" language="en_US">
<synopsis>
Read an extension into a variable.
</synopsis>
<syntax>
<parameter name="variable" required="true" />
<parameter name="filename">
<para>File to play before reading digits or tone with option <literal>i</literal></para>
</parameter>
<parameter name="context">
<para>Context in which to match extensions.</para>
</parameter>
<parameter name="option">
<optionlist>
<option name="s">
<para>Return immediately if the channel is not answered.</para>
</option>
<option name="i">
<para>Play <replaceable>filename</replaceable> as an indication tone from your
<filename>indications.conf</filename> or a directly specified list of
frequencies and durations.</para>
</option>
<option name="n">
<para>Read digits even if the channel is not answered.</para>
</option>
</optionlist>
</parameter>
<parameter name="timeout">
<para>An integer number of seconds to wait for a digit response. If
greater than <literal>0</literal>, that value will override the default timeout.</para>
</parameter>
</syntax>
<description>
<para>Reads a <literal>#</literal> terminated string of digits from the user into the given variable.</para>
<para>Will set READEXTENSTATUS on exit with one of the following statuses:</para>
<variablelist>
<variable name="READEXTENSTATUS">
<value name="OK">
A valid extension exists in ${variable}.
</value>
<value name="TIMEOUT">
No extension was entered in the specified time. Also sets ${variable} to "t".
</value>
<value name="INVALID">
An invalid extension, ${INVALID_EXTEN}, was entered. Also sets ${variable} to "i".
</value>
<value name="SKIP">
Line was not up and the option 's' was specified.
</value>
<value name="ERROR">
Invalid arguments were passed.
</value>
</variable>
</variablelist>
</description>
</application>
***/
enum readexten_option_flags {
OPT_SKIP = (1 << 0),
OPT_INDICATION = (1 << 1),
OPT_NOANSWER = (1 << 2),
};
AST_APP_OPTIONS(readexten_app_options, {
AST_APP_OPTION('s', OPT_SKIP),
AST_APP_OPTION('i', OPT_INDICATION),
AST_APP_OPTION('n', OPT_NOANSWER),
});
static char *app = "ReadExten";
static int readexten_exec(struct ast_channel *chan, const char *data)
{
int res = 0;
char exten[256] = "";
int maxdigits = sizeof(exten) - 1;
int timeout = 0, digit_timeout = 0, x = 0;
char *argcopy = NULL, *status = "";
struct ast_tone_zone_sound *ts = NULL;
struct ast_flags flags = {0};
AST_DECLARE_APP_ARGS(arglist,
AST_APP_ARG(variable);
AST_APP_ARG(filename);
AST_APP_ARG(context);
AST_APP_ARG(options);
AST_APP_ARG(timeout);
);
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "ReadExten requires at least one argument\n");
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR");
return 0;
}
argcopy = ast_strdupa(data);
AST_STANDARD_APP_ARGS(arglist, argcopy);
if (ast_strlen_zero(arglist.variable)) {
ast_log(LOG_WARNING, "Usage: ReadExten(variable[,filename[,context[,options[,timeout]]]])\n");
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR");
return 0;
}
if (ast_strlen_zero(arglist.filename)) {
arglist.filename = NULL;
}
if (ast_strlen_zero(arglist.context)) {
arglist.context = ast_strdupa(ast_channel_context(chan));
}
if (!ast_strlen_zero(arglist.options)) {
ast_app_parse_options(readexten_app_options, &flags, NULL, arglist.options);
}
if (!ast_strlen_zero(arglist.timeout)) {
timeout = atoi(arglist.timeout);
if (timeout > 0)
timeout *= 1000;
}
if (timeout <= 0)
timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000;
if (digit_timeout <= 0)
digit_timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
if (ast_test_flag(&flags, OPT_INDICATION) && !ast_strlen_zero(arglist.filename)) {
ts = ast_get_indication_tone(ast_channel_zone(chan), arglist.filename);
}
do {
if (ast_channel_state(chan) != AST_STATE_UP) {
if (ast_test_flag(&flags, OPT_SKIP)) {
/* At the user's option, skip if the line is not up */
pbx_builtin_setvar_helper(chan, arglist.variable, "");
status = "SKIP";
break;
} else if (!ast_test_flag(&flags, OPT_NOANSWER)) {
/* Otherwise answer unless we're supposed to read while on-hook */
res = ast_answer(chan);
}
}
if (res < 0) {
status = "HANGUP";
break;
}
ast_playtones_stop(chan);
ast_stopstream(chan);
if (ts && ts->data[0]) {
res = ast_playtones_start(chan, 0, ts->data, 0);
} else if (arglist.filename) {
if (ast_test_flag(&flags, OPT_INDICATION) && ast_fileexists(arglist.filename, NULL, ast_channel_language(chan)) <= 0) {
/*
* We were asked to play an indication that did not exist in the config.
* If no such file exists, play it as a tonelist. With any luck they won't
* have a file named "350+440.ulaw"
* (but honestly, who would do something so silly?)
*/
res = ast_playtones_start(chan, 0, arglist.filename, 0);
} else {
res = ast_streamfile(chan, arglist.filename, ast_channel_language(chan));
}
}
for (x = 0; x < maxdigits; x++) {
ast_debug(3, "extension so far: '%s', timeout: %d\n", exten, timeout);
res = ast_waitfordigit(chan, timeout);
ast_playtones_stop(chan);
ast_stopstream(chan);
timeout = digit_timeout;
if (res < 1) { /* timeout expired or hangup */
if (ast_check_hangup(chan)) {
status = "HANGUP";
} else if (x == 0) {
pbx_builtin_setvar_helper(chan, arglist.variable, "t");
status = "TIMEOUT";
}
break;
}
exten[x] = res;
if (!ast_matchmore_extension(chan, arglist.context, exten, 1 /* priority */,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
if (!ast_exists_extension(chan, arglist.context, exten, 1,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))
&& res == '#') {
exten[x] = '\0';
}
break;
}
}
if (!ast_strlen_zero(status))
break;
if (ast_exists_extension(chan, arglist.context, exten, 1,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
ast_debug(3, "User entered valid extension '%s'\n", exten);
pbx_builtin_setvar_helper(chan, arglist.variable, exten);
status = "OK";
} else {
ast_debug(3, "User dialed invalid extension '%s' in context '%s' on %s\n", exten, arglist.context, ast_channel_name(chan));
pbx_builtin_setvar_helper(chan, arglist.variable, "i");
pbx_builtin_setvar_helper(chan, "INVALID_EXTEN", exten);
status = "INVALID";
}
} while (0);
if (ts) {
ts = ast_tone_zone_sound_unref(ts);
}
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", status);
return status[0] == 'H' ? -1 : 0;
}
static int unload_module(void)
{
int res = ast_unregister_application(app);
return res;
}
static int load_module(void)
{
int res = ast_register_application_xml(app, readexten_exec);
return res;
}
AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Read and evaluate extension validity");
| Java |
<?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;
}
}
| Java |
#ifndef __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__
#define __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__
#include "gedit-file-browser-message-activation.h"
#include "gedit-file-browser-message-add-context-item.h"
#include "gedit-file-browser-message-add-filter.h"
#include "gedit-file-browser-message-get-root.h"
#include "gedit-file-browser-message-get-view.h"
#include "gedit-file-browser-message-id.h"
#include "gedit-file-browser-message-id-location.h"
#include "gedit-file-browser-message-set-emblem.h"
#include "gedit-file-browser-message-set-root.h"
#endif /* __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__ */
| Java |
/*-
* #%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 );
}
}
| Java |
<?
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>
<?
}
?> | Java |
<?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;
}
| Java |
/*
* arch/arm/mach-tegra/board-smba1002.c
*
* Copyright (C) 2011 Eduardo José Tagle <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <linux/console.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <linux/clk.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/dma-mapping.h>
#include <linux/fsl_devices.h>
#include <linux/platform_data/tegra_usb.h>
#include <linux/pda_power.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/i2c-tegra.h>
#include <linux/memblock.h>
#include <linux/antares_dock.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/setup.h>
#include <mach/io.h>
#include <mach/w1.h>
#include <mach/iomap.h>
#include <mach/irqs.h>
#include <mach/nand.h>
#include <mach/iomap.h>
#include <mach/sdhci.h>
#include <mach/gpio.h>
#include <mach/clk.h>
#include <mach/usb_phy.h>
#include <mach/i2s.h>
#include <mach/system.h>
#include <linux/nvmap.h>
#include "board.h"
#include "board-smba1002.h"
#include "clock.h"
#include "gpio-names.h"
#include "devices.h"
#include "pm.h"
#include "wakeups-t2.h"
#include "wdt-recovery.h"
#include <linux/rfkill-gpio.h>
#define PMC_CTRL 0x0
#define PMC_CTRL_INTR_LOW (1 << 17)
static struct rfkill_gpio_platform_data bluetooth_rfkill = {
.name = "bluetooth_rfkill",
.shutdown_gpio = -1,
.reset_gpio = SMBA1002_BT_RESET,
.type = RFKILL_TYPE_BLUETOOTH,
};
static struct platform_device bluetooth_rfkill_device = {
.name = "rfkill_gpio",
.id = -1,
.dev = {
.platform_data = &bluetooth_rfkill,
},
};
#ifdef CONFIG_BT_BLUEDROID
extern void bluesleep_setup_uart_port(struct platform_device *uart_dev);
#endif
void __init smba_setup_bluesleep(void)
{
/*Add Clock Resource*/
clk_add_alias("bcm4329_32k_clk", bluetooth_rfkill_device.name, \
"blink", NULL);
#ifdef CONFIG_BT_BLUEDROID
bluesleep_setup_uart_port(&tegra_uartc_device);
#endif
return;
}
static struct resource smba_bluesleep_resources[] = {
[0] = {
.name = "gpio_host_wake",
.start = SMBA1002_BT_IRQ,
.end = SMBA1002_BT_IRQ,
.flags = IORESOURCE_IO,
},
[1] = {
.name = "gpio_ext_wake",
.start = SMBA1002_BT_WAKEUP,
.end = SMBA1002_BT_WAKEUP,
.flags = IORESOURCE_IO,
},
[2] = {
.name = "host_wake",
.start = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ),
.end = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE,
},
};
static struct platform_device smba_bluesleep_device = {
.name = "bluesleep",
.id = -1,
.num_resources = ARRAY_SIZE(smba_bluesleep_resources),
.resource = smba_bluesleep_resources,
};
static struct dock_platform_data dock_on_platform_data = {
.irq = TEGRA_GPIO_TO_IRQ(SMBA1002_DOCK),
.gpio_num = SMBA1002_DOCK,
};
static struct platform_device tegra_dock_device =
{
.name = "tegra_dock",
.id = -1,
.dev = {
.platform_data = &dock_on_platform_data,
},
};
static struct platform_device *smba_devices[] __initdata = {
&tegra_pmu_device,
&tegra_gart_device,
&tegra_aes_device,
&bluetooth_rfkill_device,
&smba_bluesleep_device,
&tegra_wdt_device,
&tegra_avp_device,
&tegra_dock_device
};
static void __init tegra_smba_init(void)
{
/* Initialize the pinmux */
smba_pinmux_init();
/* Initialize the clocks - clocks require the pinmux to be initialized first */
smba_clks_init();
platform_add_devices(smba_devices,ARRAY_SIZE(smba_devices));
/* Register i2c devices - required for Power management and MUST be done before the power register */
smba_i2c_register_devices();
/* Register the power subsystem - Including the poweroff handler - Required by all the others */
smba_charge_init();
smba_regulator_init();
/* Register the USB device */
smba_usb_register_devices();
/* Register UART devices */
smba_uart_register_devices();
/* Register RAM Console */
tegra_ram_console_debug_init();
/* Register GPU devices */
smba_panel_init();
/* Register Audio devices */
smba_audio_register_devices();
/* Register all the keyboard devices */
smba_keys_init();
/* Register touchscreen devices */
smba_touch_register_devices();
/* Register accelerometer device */
smba_sensors_register_devices();
/* Register Camera powermanagement devices */
smba_camera_register_devices();
/* Register NAND flash devices */
smba_nand_register_devices();
/* Register SDHCI devices */
smba_sdhci_init();
/* Register Bluetooth powermanagement devices */
smba_setup_bluesleep();
/* Release the tegra bootloader framebuffer */
tegra_release_bootloader_fb();
}
static void __init tegra_smba_reserve(void)
{
if (memblock_reserve(0x0, 4096) < 0)
pr_warn("Cannot reserve first 4K of memory for safety\n");
/* Reserve the graphics memory */
tegra_reserve(SMBA1002_GPU_MEM_SIZE, SMBA1002_FB1_MEM_SIZE, SMBA1002_FB2_MEM_SIZE);
tegra_ram_console_debug_reserve(SZ_1M);
}
static void __init tegra_smba_fixup(struct machine_desc *desc,
struct tag *tags, char **cmdline, struct meminfo *mi)
{
mi->nr_banks = SMBA1002_MEM_BANKS;
mi->bank[0].start = PHYS_OFFSET;
mi->bank[0].size = SMBA1002_MEM_SIZE - SMBA1002_TOTAL_GPU_MEM_SIZE;
}
MACHINE_START(HARMONY, "harmony")
.boot_params = 0x00000100,
.fixup = tegra_smba_fixup,
.map_io = tegra_map_common_io,
.reserve = tegra_smba_reserve,
.init_early = tegra_init_early,
.init_irq = tegra_init_irq,
.timer = &tegra_timer,
.init_machine = tegra_smba_init,
MACHINE_END
| Java |
/*
* 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);
}
| Java |
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),'.',',','.');
}
| Java |
/*
* 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: [email protected], [email protected]
*
* 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;
}
}
| Java |
/**
* 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
| Java |
<html><body>Karuda:<br>
You can earn the following rewards:<br>
<font color="LEVEL">S80 weapon recipe</font> - Requires 500 Cursed Grave Goods<br>
<font color="LEVEL">Leonard</font> - Requires 8 Cursed Grave Goods<br>
<font color="LEVEL">Adamantine</font> - Requires 15 Cursed Grave Goods<br>
<font color="LEVEL">Orichalcum</font> - Requires 12 Cursed Grave Goods<br>
Remember, I'm counting on you!
</body></html> | Java |
/***********************************************************************
*
* Copyright (C) 2011, 2014 Graeme Gott <[email protected]>
*
* 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;
}
//-----------------------------------------------------------------------------
| Java |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : [email protected]
.. 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__ = '[email protected]'
__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')
| Java |
<?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">
| Java |
/*****************************************************************************
* Copyright (c) 2014-2018 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include "../scenario/Scenario.h"
#include "Object.h"
class StexObject final : public Object
{
private:
rct_stex_entry _legacyType = {};
public:
explicit StexObject(const rct_object_entry& entry)
: Object(entry)
{
}
void* GetLegacyData() override
{
return &_legacyType;
}
void ReadLegacy(IReadObjectContext* context, IStream* stream) override;
void Load() override;
void Unload() override;
void DrawPreview(rct_drawpixelinfo* dpi, int32_t width, int32_t height) const override;
std::string GetName() const override;
std::string GetScenarioName() const;
std::string GetScenarioDetails() const;
std::string GetParkName() const;
};
| Java |
/*
* 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;
}
| Java |
IMAGES="test-r test-python"
IMAGE_VERSION="0.1"
DOCKER_REGISTRY="localhost:5000"
for IMAGE in ${IMAGES} ; do
docker build --tag ${DOCKER_REGISTRY}/dpa/${IMAGE}:${IMAGE_VERSION} tasks/${IMAGE}
docker push ${DOCKER_REGISTRY}/dpa/${IMAGE}:${IMAGE_VERSION}
done
| Java |
from django.conf.urls.defaults import *
"""
Also used in cms.tests.ApphooksTestCase
"""
urlpatterns = patterns('cms.test_utils.project.sampleapp.views',
url(r'^$', 'sample_view', {'message': 'sample root page',}, name='sample-root'),
url(r'^settings/$', 'sample_view', kwargs={'message': 'sample settings page'}, name='sample-settings'),
url(r'^account/$', 'sample_view', {'message': 'sample account page'}, name='sample-account'),
url(r'^account/my_profile/$', 'sample_view', {'message': 'sample my profile page'}, name='sample-profile'),
url(r'^(?P<id>[0-9]+)/$', 'category_view', name='category_view'),
url(r'^notfound/$', 'notfound', name='notfound'),
url(r'^extra_1/$', 'extra_view', {'message': 'test urlconf'}, name='extra_first'),
url(r'^', include('cms.test_utils.project.sampleapp.urls_extra')),
)
| Java |
############################################################################
# Copyright (c) 2010 Robotnik Automation, SLL #
# Makefile for standard Robotnik component #
############################################################################
BUILD = ./build/
BINDIR = ./bin/
SRC = ./src/
LIB = ./lib/
#LIBS = -L$(LIB) -lpthread -lremotelog -lcurses -lrt
INC = ./include/SerialDevice
CPP = g++
CCFLAGS = -Wall -c -g3 -I$(INC)
# -g3 -Wno-deprecated -Wall
OBJECTS = \
$(BUILD)SerialDevice.o \
default: $(BINDIR)$(EXE)
all: $(BINDIR)$(EXE)
$(BUILD)SerialDevice.o : $(SRC)SerialDevice.cc
$(CPP) $(CCFLAGS) -o $(BUILD)SerialDevice.o $(SRC)SerialDevice.cc
#$(BINDIR)$(EXE) : $(OBJECTS)
# $(CPP) -I$(INC) -o $(BINDIR)$(EXE) $(OBJECTS) $(LIBS)
clean:
rm -fv $(BUILD)*.o
rm -fv $(BINDIR)$(EXE)
| Java |
#ifndef MANTID_CURVEFITTING_SEQDOMAIN_H_
#define MANTID_CURVEFITTING_SEQDOMAIN_H_
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidCurveFitting/DllConfig.h"
#include "MantidAPI/FunctionDomain.h"
#include "MantidAPI/FunctionValues.h"
#include "MantidAPI/IDomainCreator.h"
#include "MantidCurveFitting/CostFunctions/CostFuncLeastSquares.h"
#include "MantidCurveFitting/CostFunctions/CostFuncRwp.h"
#include <stdexcept>
#include <vector>
#include <algorithm>
namespace Mantid {
namespace CurveFitting {
/** An implementation of CompositeDomain.
@author Roman Tolchenov, Tessella plc
@date 15/11/2011
Copyright © 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
National Laboratory & European Spallation Source
This file is part of Mantid.
Mantid 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.
Mantid 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/>.
File change history is stored at: <https://github.com/mantidproject/mantid>.
Code Documentation is available at: <http://doxygen.mantidproject.org>
*/
class MANTID_CURVEFITTING_DLL SeqDomain : public API::FunctionDomain {
public:
SeqDomain() : API::FunctionDomain(), m_currentIndex(0) {}
/// Return the number of points in the domain
size_t size() const override;
/// Return the number of parts in the domain
virtual size_t getNDomains() const;
/// Create and return i-th domain and i-th values, (i-1)th domain is released.
virtual void getDomainAndValues(size_t i, API::FunctionDomain_sptr &domain,
API::FunctionValues_sptr &values) const;
/// Add new domain creator
void addCreator(API::IDomainCreator_sptr creator);
/// Calculate the value of a least squares cost function
virtual void
leastSquaresVal(const CostFunctions::CostFuncLeastSquares &leastSquares);
/// Calculate the value, first and second derivatives of a least squares cost
/// function
virtual void leastSquaresValDerivHessian(
const CostFunctions::CostFuncLeastSquares &leastSquares, bool evalDeriv,
bool evalHessian);
/// Calculate the value of a Rwp cost function
void rwpVal(const CostFunctions::CostFuncRwp &rwp);
/// Calculate the value, first and second derivatives of a RWP cost function
void rwpValDerivHessian(const CostFunctions::CostFuncRwp &rwp, bool evalDeriv,
bool evalHessian);
/// Create an instance of SeqDomain in one of two forms: either SeqDomain for
/// sequential domain creation
/// or ParDomain for parallel calculations
static SeqDomain *create(API::IDomainCreator::DomainType type);
protected:
/// Current index
mutable size_t m_currentIndex;
/// Currently active domain.
mutable std::vector<API::FunctionDomain_sptr> m_domain;
/// Currently active values.
mutable std::vector<API::FunctionValues_sptr> m_values;
/// Domain creators.
std::vector<boost::shared_ptr<API::IDomainCreator>> m_creators;
};
} // namespace CurveFitting
} // namespace Mantid
#endif /*MANTID_CURVEFITTING_SEQDOMAIN_H_*/
| Java |
/* XGGState - Implements graphic state drawing for Xlib
Copyright (C) 1995 Free Software Foundation, Inc.
Written by: Adam Fedor <[email protected]>
Date: Nov 1995
This file is part of the GNU Objective C User Interface Library.
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 of the License, or (at your option) any later version.
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; see the file COPYING.LIB.
If not, see <http://www.gnu.org/licenses/> or write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef _XGGState_h_INCLUDE
#define _XGGState_h_INCLUDE
#include <Foundation/NSArray.h>
#include <Foundation/NSObject.h>
#include "gsc/GSGState.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "x11/XGServer.h"
#ifdef HAVE_XFT
#define id xwindowsid
#include <X11/Xft/Xft.h>
#undef id
#endif
@class NSBezierPath;
@class NSFont;
@interface XGGState : GSGState
{
@public
void *context;
void *windevice;
XGDrawMechanism drawMechanism;
GC xgcntxt;
GC agcntxt;
XGCValues gcv;
Drawable draw;
Drawable alpha_buffer;
Region clipregion;
#ifdef HAVE_XFT
XftDraw *xft_draw;
XftDraw *xft_alpha_draw;
XftColor xft_color;
#endif
BOOL drawingAlpha;
BOOL sharedGC; /* Do we own the GC or share it? */
}
- (void) setWindowDevice: (void *)device;
- (void) setGraphicContext: (GC)xGraphicContext;
- (void) setGCValues: (XGCValues)values withMask: (int)mask;
- (void) setClipMask;
- (Region) xClipRegion;
- (BOOL) hasDrawable;
- (BOOL) hasGraphicContext;
- (void *) windevice;
- (Drawable) drawable;
- (GC) graphicContext;
- (NSRect) clipRect;
#ifdef HAVE_XFT
- (XftDraw *)xftDrawForDrawable: (Drawable)d;
- (XftColor)xftColor;
#endif
- (XPoint) viewPointToX: (NSPoint)aPoint;
- (XRectangle) viewRectToX: (NSRect)aRect;
- (XPoint) windowPointToX: (NSPoint)aPoint;
- (XRectangle) windowRectToX: (NSRect)aRect;
@end
@interface XGGState (Ops)
- (NSDictionary *) GSReadRect: (NSRect)rect;
@end
#endif /* _XGGState_h_INCLUDE */
| Java |
#!/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)
| Java |
/*
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;
}
| Java |
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 ]
]; | Java |
(function(jQuery){jQuery.fn.addLittleSisToolbar=function(){var defaults={z_index:10002,height:180,width:100,background_color:'#FFF'};return this.each(function(){if(jQuery('#littlesis-toolbar').length==0){var elements=jQuery(this);elements.css({'margin-top':(defaults.height+10)+'px'});var wrapper=jQuery('<div id="littlesis-toolbar"/>').appendTo(elements).css({'display':'block','position':'fixed','background-color':defaults.background_color,'top':0,'z-index':(defaults.z_index-1),'height':defaults.height+'px','width':defaults.width+'%'});jQuery('#littlesis-toolbar').append('<iframe id="littlesis-toolbar-iframe" src="https://littlesis.org/relationship/toolbar?title='+escape(document.title)+'&url='+escape(document.URL)+'">No Support</iframe>');jQuery('#littlesis-toolbar-iframe').css({'width':defaults.width+'%','height':defaults.height+'px','border':0,'border-bottom':'3px solid #ccc'})}})}})(jQuery);
| Java |
! This file is F-compatible, except for upper/lower case conventions.
!--------------------------------------------------------------------
Module CubatureRule_C2
USE Precision_Model, ONLY: stnd
Implicit NONE
PRIVATE
PUBLIC :: Rule_C2a
CONTAINS
SUBROUTINE Rule_C2a(VER,INFOLD,AREA,NUMFUN,Integrand,BASVAL,RGNERR,NUM)
!
!***BEGIN PROLOGUE Rule_C2a
!***PURPOSE To compute basic integration rule values and
! corresponding error estimates.
! ***REVISION DATE 950531 (YYMMDD) (Fortran90 transformation)
! ***REVISION DATE 990527 (YYMMDD) (F transformation)
! ***AUTHOR
! Ronald Cools, Dept. of Computer Science,
! Katholieke Universiteit Leuven, Celestijnenlaan 200A,
! B-3001 Heverlee, Belgium
! Email: [email protected]
!
! ***REFERENCES
! The cubature formula of degree 13 with 37 points is from
! Rabinowitz & Richter. The tuning of the error estimator
! is described in:
! R. Cools.
! "The subdivision strategy and reliablity in adaptive
! integration revisited."
! Report TW 213, Dept. of Computer Science, K.U.Leuven, 1994.
!
!***DESCRIPTION Rule_C2a computes basic integration rule values
! for a vector of integrands over a rectangular region.
! Rule_C2a also computes estimates for the errors by
! using several null rule approximations.
! ON ENTRY
!
! VER Real array of dimension (2,3).
! The coordinates of the vertices of the parallellogram.
! NUMFUN Integer.
! Number of components of the vector integrand.
! INFOLD Integer array
! Integrand Externally declared subroutine for computing
! all components of the integrand at the given
! evaluation point.
! It must have parameters (DIM,X,NUMFUN,FUNVLS)
! Input parameters:
! DIM = 2
! X(1) The x-coordinate of the evaluation point.
! X(2) The y-coordinate of the evaluation point.
! NUMFUN Integer that defines the number of
! components of I.
! Output parameter:
! FUNVLS Real array of dimension NUMFUN
! that defines NUMFUN components of the integrand.
!
! ON RETURN
!
! BASVAL Real array of dimension NUMFUN.
! The values for the basic rule for each component
! of the integrand.
! RGNERR Real array of dimension NUMFUN.
! The error estimates for each component of the integrand.
! NUM Integer
! The number of function evaluations used.
! INFOLD Integer array
!
!***ROUTINES CALLED Integrand
!***END PROLOGUE Rule_C2a
!
! Global variables.
!
INTERFACE
FUNCTION Integrand(NUMFUN,X) RESULT(Value)
USE Precision_Model
INTEGER, INTENT(IN) :: NUMFUN
REAL(kind=stnd), DIMENSION(:), INTENT(IN) :: X
REAL(kind=stnd), DIMENSION(NUMFUN) :: Value
END FUNCTION Integrand
END INTERFACE
INTEGER, INTENT(IN) :: NUMFUN
INTEGER, INTENT(OUT) :: NUM
INTEGER, DIMENSION(:), INTENT(IN OUT) :: INFOLD
REAL(kind=stnd), INTENT(IN) :: AREA
REAL(kind=stnd), DIMENSION(:,:), INTENT(IN) :: VER
REAL(kind=stnd), DIMENSION(:), INTENT(OUT) :: BASVAL, RGNERR
!
! Parameters
!
INTEGER, DIMENSION(0:3), PARAMETER :: &
K = (/1,2,3,2/) ! Rule structure parameters
INTEGER, PARAMETER :: &
ORBITS = 8 ! Number of orbits in rule
REAL(kind=stnd), PARAMETER :: &
HALF = 0.5_stnd, &
FOUR = 4.0_stnd, &
CRIVAL = 0.4_stnd, &
FACMED = 8.0_stnd, &
FACOPT = FACMED/CRIVAL**2, &
TRES = 50*EPSILON(HALF), &
CUTOFF = 1.0E-4_stnd , &
DFCLEV = 0.55_stnd
REAL(kind=stnd), DIMENSION(0:2), PARAMETER :: &
DFC = (/2.97397430397053625382_stnd, &
1.0_stnd, &
-2.48698715198526812691_stnd /)
!
! Cubature formula of degree 13 with 37 points (Rabinowitz & Richter)
!
!
! Information for the generators
!
INTEGER :: I
REAL(kind=stnd), DIMENSION(1:2), PARAMETER :: &
TYPE1 = (/ 0.9909890363004326469792722978603_stnd, &
0.6283940712305315063814483471116_stnd /)
REAL(kind=stnd), DIMENSION(1:3), PARAMETER :: &
TYPE2 = (/ 0.9194861553393073086142137772149_stnd, &
0.6973201917871173078084506730937_stnd, &
0.3805687186904854497424188074662_stnd /)
REAL(kind=stnd), DIMENSION(1:2,1:2), PARAMETER :: &
TYPE3 = RESHAPE( SOURCE= &
(/ 0.9708504361720225062147290554088_stnd, &
0.6390348393207252159077623446225_stnd, &
0.8623637916722781475018696425693_stnd, &
0.3162277660168700033875075593701_stnd /),&
SHAPE=(/2,2/) )
! The weights of the basic rule and the null rules.
! WEIGHT(1,1),...,WEIGHT(1,ORBITS) are weights for the basic rule.
! WEIGHT(I,1),...,WEIGHT(I,ORBITS) for I>1 are null rule weights.
!
!
! Weights of the cubature formula.
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W1 = (/ &
2.995235559387052215463143056692E-1_stnd , &
3.311006686692356205977471655046E-2_stnd , &
1.802214941550624038355347399683E-1_stnd , &
3.916727896035153300761243260674E-2_stnd , &
1.387748348777288706306435595057E-1_stnd , &
2.268881207335707037147066705814E-1_stnd , &
3.657395765508995601240002438981E-2_stnd , &
1.169047000557533546701746277951E-1_stnd /)
!
! Weights of the rules of degree 7, 7, 5 , 5 , 3 , 3 and 1.
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W2 = (/ &
7.610781847149629154716409791983E-2_stnd , &
1.486101247399760261471935168346E-1_stnd , &
-2.077685631717747007172983323970E-1_stnd , &
6.850758313011924198538315395405E-2_stnd , &
2.024205813317813585572881715385E-1_stnd , &
1.108627473745508429879249169864E-1_stnd , &
-1.187411393304862640859204217487E-1_stnd , &
-5.208857468077715683772080394959E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W3 = (/ &
4.016494861405949747097510013162E-2_stnd , &
-1.093132962444079541048635452881E-1_stnd , &
-2.270251673633777452624380129694E-1_stnd , &
1.231674163356097016086203579325E-2_stnd , &
-1.420402526499201540699111172200E-1_stnd , &
1.189080551229557928776504129312E-1_stnd , &
-4.482039658150474743804189300793E-3_stnd , &
1.730383808319875827592824151609E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W4 = (/ &
-5.643905795781771973971259866415E-1_stnd , &
2.878418073676293225652331648545E-2_stnd , &
1.159354231997583294689565314470E-1_stnd , &
1.376081498690624477894043101438E-1_stnd , &
-7.909780225340130915490382973570E-2_stnd , &
1.174335441429478112778176601234E-1_stnd , &
-1.107251942334134124782600707843E-1_stnd , &
2.094226883312045633400182488252E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W5 = (/ &
-2.269001713589584730602581694579E-1_stnd , &
2.976190892690301120078774620049E-2_stnd , &
-7.440193483272787588251423144751E-2_stnd , &
-1.224665989043784131260454301280E-1_stnd , &
-4.857910454732976198562745578156E-2_stnd , &
2.228157325962656425537280474671E-1_stnd , &
1.459764751457503859063666414952E-1_stnd , &
-1.211789553452468781539987084682E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W6 = (/ &
-3.326760468009974589269134283992E-1_stnd , &
1.796655319904795478676993902115E-1_stnd , &
-4.389976396805911868560791966472E-2_stnd , &
-2.295841771339316497310760908889E-1_stnd , &
6.182618387692816082856552878852E-2_stnd , &
-1.202703885325137746461829140891E-1_stnd , &
5.109536580363550180208564374234E-3_stnd , &
1.126062761533095493689566169969E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W7 = (/ &
2.290638530086106512999345512401E-1_stnd , &
2.702070398116919449911037051753E-1_stnd , &
-9.078047988731123605988441792069E-3_stnd , &
4.618480310858703283999169489655E-2_stnd , &
-2.598231009547631799096616255056E-1_stnd , &
-2.518433931146441037986247681820E-2_stnd , &
-1.257796993152456033984707367389E-2_stnd , &
-2.720818902721190304043617320910E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W8 = (/ &
2.746908885094872977794932213372E-1_stnd , &
-1.149427039769738298032807785523E-2_stnd , &
1.596178537820019535731955591283E-1_stnd , &
-2.180626972663360443142752377527E-1_stnd , &
-8.711748038292630173597899697063E-3_stnd , &
1.902786182960269617633915869710E-1_stnd , &
-1.189840649092108827784089292890E-1_stnd , &
2.883382565767354162177931122471E-2_stnd /)
REAL(kind=stnd), DIMENSION(1:8,1:ORBITS), PARAMETER :: &
WEIGHT = RESHAPE( SOURCE= (/ W1,W2,W3,W4,W5,W6,W7,W8 /),&
SHAPE=(/8,ORBITS/), ORDER=(/2,1/) )
!
! Local variables.
!
INTEGER :: J,NUMBER,GENTYPE,NR,P
REAL(kind=stnd):: R1,R2,R3,R,NOISE,DEG7,DEG5,DEG3,DEG1, &
DIFFX,DIFFY,Z1,Z2
REAL(kind=stnd), DIMENSION(2,8) :: X
REAL(kind=stnd), DIMENSION(NUMFUN,7) :: NullRule
REAL(kind=stnd), DIMENSION(NUMFUN) :: SUMVAL
!
!***FIRST EXECUTABLE STATEMENT Rule_C2a
!
! The number of points used by the cubature formula is
! NUM = K(0) + 4*K(1) + 4*K(2) + 8*K(3)
NUM = 37
!
!
! Initialise BASVAL and NullRule
!
BASVAL = 0
NullRule = 0
P = 1
!
! Compute contributions from orbits with 1, 4 and 8 points
!
DO GENTYPE = 0,3
DO NR = 1,K(GENTYPE)
SELECT CASE (GENTYPE)
CASE (0) ! Generator ( 0 , 0 )
NUMBER = 1
X(:,1) = (VER(:,2)+VER(:,3))*HALF
CASE (1) ! Generator ( z1 , 0 )
Z1 = TYPE1(NR)
NUMBER = 4
Z1 = Z1*HALF
X(:,1) = -VER(:,1)*Z1 + VER(:,2)*HALF + &
VER(:,3)* (Z1+HALF)
X(:,2) = VER(:,1)*Z1 + VER(:,2)*HALF + &
VER(:,3)* (-Z1+HALF)
X(:,3) = VER(:,1)*Z1 + VER(:,2)* (-Z1+HALF) + &
VER(:,3)*HALF
X(:,4) = -VER(:,1)*Z1 + VER(:,2)* (Z1+HALF) + &
VER(:,3)*HALF
CASE (2) ! Generator ( z(1) , z(1) )
Z1 = TYPE2(NR)
NUMBER = 4
Z1 = Z1*HALF
X(:,1) = -2*VER(:,1)*Z1 + VER(:,2)* (HALF+Z1) +&
VER(:,3)* (Z1+HALF)
X(:,2) = VER(:,2)* (HALF+Z1) + VER(:,3)* (-Z1+HALF)
X(:,3) = VER(:,2)* (HALF-Z1) + VER(:,3)* (Z1+HALF)
X(:,4) = 2*VER(:,1)*Z1 + VER(:,2)* (HALF-Z1) + &
VER(:,3)* (-Z1+HALF)
CASE (3) ! Generator ( z(1) , z(2) )
Z1 = TYPE3(1,NR)*HALF
Z2 = TYPE3(2,NR)*HALF
NUMBER = 8
X(:,1) = VER(:,1)* (-Z1-Z2) + &
VER(:,2)* (HALF+Z2) + VER(:,3)* (HALF+Z1)
X(:,2) = VER(:,1)* (+Z1-Z2) + &
VER(:,2)* (HALF+Z2) + VER(:,3)* (HALF-Z1)
X(:,3) = VER(:,1)* (-Z1+Z2) + &
VER(:,2)* (HALF-Z2) + VER(:,3)* (HALF+Z1)
X(:,4) = VER(:,1)* (+Z1+Z2) + &
VER(:,2)* (HALF-Z2) + VER(:,3)* (HALF-Z1)
X(:,5) = VER(:,1)* (-Z1-Z2) + &
VER(:,2)* (HALF+Z1) + VER(:,3)* (HALF+Z2)
X(:,6) = VER(:,1)* (+Z2-Z1) + &
VER(:,2)* (HALF+Z1) + VER(:,3)* (HALF-Z2)
X(:,7) = VER(:,1)* (-Z2+Z1) + &
VER(:,2)* (HALF-Z1) + VER(:,3)* (HALF+Z2)
X(:,8) = VER(:,1)* (+Z1+Z2) + &
VER(:,2)* (HALF-Z1) + VER(:,3)* (HALF-Z2)
END SELECT
! CALL Integrand(2,X(1,1),NUMFUN,SUMVAL)
SUMVAL = Integrand(NUMFUN,X(:,1))
SELECT CASE (GENTYPE)
CASE (0)
DIFFy = SUMVAL(1)*DFC(0)
DIFFx = DIFFy
CASE (1)
DIFFy = DIFFy + SUMVAL(1)*DFC(NR)
END SELECT
DO J = 2,NUMBER
RGNERR = Integrand(NUMFUN,X(:,J))
! CALL Integrand(2,X(1,J),NUMFUN,RGNERR)
IF (GENTYPE == 1) THEN
IF (J <= 2) THEN
DIFFy = DIFFy + RGNERR(1)*DFC(NR)
ELSE
DIFFx = DIFFx + RGNERR(1)*DFC(NR)
END IF
END IF
DO I = 1,NUMFUN
SUMVAL(I) = SUMVAL(I) + RGNERR(I)
END DO
END DO
DO J = 1,NUMFUN
BASVAL(J) = BASVAL(J) + WEIGHT(1,P)*SUMVAL(J)
DO I = 1,7
NullRule(J,I) = NullRule(J,I) + WEIGHT(I+1,P)*SUMVAL(J)
END DO
END DO
P = P + 1
END DO
END DO
!
! Decide on future subdivision direction
!
DIFFy = ABS(DIFFy)
DIFFx = ABS(DIFFx)
IF (MAX(DIFFy,DIFFx) < CUTOFF) THEN
INFOLD(4) = 0
ELSE IF (DIFFy < DFCLEV*DIFFx) THEN
INFOLD(4) = 1
ELSE IF (DIFFx < DFCLEV*DIFFy) THEN
INFOLD(4) = 2
ELSE
INFOLD(4) = 0
END IF
!
! Compute errors.
!
DO J = 1,NUMFUN
NOISE = ABS(BASVAL(J))*TRES
DEG7 = SQRT(NullRule(J,1)**2+NullRule(J,2)**2)
IF (DEG7 <= NOISE) THEN
RGNERR(J) = NOISE
ELSE
DEG5 = SQRT(NullRule(J,3)**2+NullRule(J,4)**2)
DEG3 = SQRT(NullRule(J,5)**2+NullRule(J,6)**2)
DEG1 = SQRT(NullRule(J,7)**2+NullRule(J,6)**2)
IF (DEG5 /= 0) THEN
R1 = DEG7/DEG5
ELSE
R1 = 1
END IF
IF (DEG3 /= 0) THEN
R2 = DEG5/DEG3
ELSE
R2 = 1
END IF
IF (DEG1 /= 0) THEN
R3 = DEG3/DEG1
ELSE
R3 = 1
END IF
R = MAX(R1,R2,R3)
IF (R >= 1) THEN
INFOLD(5) = 0
RGNERR(J) = FACMED*DEG7
ELSE IF (R >= CRIVAL) THEN
INFOLD(5) = 0
RGNERR(J) = FACMED*DEG7*R
ELSE
INFOLD(5) = 1
RGNERR(J) = FACOPT* (R**3)*DEG7
END IF
RGNERR(J) = MAX(NOISE,RGNERR(J))
END IF
RGNERR(J) = AREA*RGNERR(J)/FOUR
BASVAL(J) = AREA*BASVAL(J)/FOUR
END DO
RETURN
END SUBROUTINE Rule_C2a
END Module CubatureRule_C2
| Java |
/*
FreeRTOS V7.4.2 - Copyright (C) 2013 Real Time Engineers Ltd.
FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT
http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS 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 AND MODIFIED BY the FreeRTOS exception.
>>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel.
FreeRTOS 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
and the FreeRTOS license exception along with FreeRTOS; if not it can be
viewed here: http://www.freertos.org/a00114.html and also obtained by
writing to Real Time Engineers Ltd., contact details for whom are available
on the FreeRTOS WEB site.
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, books, training, latest versions,
license and Real Time Engineers Ltd. contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, and our new
fully thread aware and reentrant UDP/IP stack.
http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
Integrity Systems, who sell the code with commercial support,
indemnification and middleware, under the OpenRTOS brand.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
*/
#ifndef STACK_MACROS_H
#define STACK_MACROS_H
/*
* Call the stack overflow hook function if the stack of the task being swapped
* out is currently overflowed, or looks like it might have overflowed in the
* past.
*
* Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check
* the current stack state only - comparing the current top of stack value to
* the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1
* will also cause the last few stack bytes to be checked to ensure the value
* to which the bytes were set when the task was created have not been
* overwritten. Note this second test does not guarantee that an overflowed
* stack will always be recognised.
*/
/*-----------------------------------------------------------*/
#if( configCHECK_FOR_STACK_OVERFLOW == 0 )
/* FreeRTOSConfig.h is not set to check for stack overflows. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
#endif /* configCHECK_FOR_STACK_OVERFLOW == 0 */
/*-----------------------------------------------------------*/
#if( configCHECK_FOR_STACK_OVERFLOW == 1 )
/* FreeRTOSConfig.h is only set to use the first method of
overflow checking. */
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
#endif
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH < 0 ) )
/* Only the current stack state is to be checked. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \
{ \
/* Is the currently saved stack pointer within the stack limit? */ \
if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* configCHECK_FOR_STACK_OVERFLOW > 0 */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH > 0 ) )
/* Only the current stack state is to be checked. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \
{ \
\
/* Is the currently saved stack pointer within the stack limit? */ \
if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \
{ \
static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \
\
\
/* Has the extremity of the task stack ever been written over? */ \
if( memcmp( ( void * ) pxCurrentTCB->pxStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \
{ \
char *pcEndOfStack = ( char * ) pxCurrentTCB->pxEndOfStack; \
static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \
\
\
pcEndOfStack -= sizeof( ucExpectedStackBytes ); \
\
/* Has the extremity of the task stack ever been written over? */ \
if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
/*-----------------------------------------------------------*/
#endif /* STACK_MACROS_H */
| Java |
#ifndef CA_USERTOOLS_H
#define CA_USERTOOLS_H
#include <vector>
namespace ca {
std::vector<int> range(int from, int upto);
}
#endif // CA_USERTOOLS_H
| Java |
//
// VMime library (http://www.vmime.org)
// Copyright (C) 2002-2013 Vincent Richard <[email protected]>
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library. Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//
#include "tests/testUtils.hpp"
VMIME_TEST_SUITE_BEGIN(messageTest)
VMIME_TEST_LIST_BEGIN
VMIME_TEST(testGetGeneratedSize)
VMIME_TEST_LIST_END
void testGetGeneratedSize()
{
vmime::generationContext ctx;
vmime::shared_ptr <vmime::message> msg = vmime::make_shared <vmime::message>();
msg->getHeader()->getField("Foo")->setValue(vmime::string("bar"));
vmime::htmlTextPart textPart;
textPart.setPlainText(vmime::make_shared <vmime::stringContentHandler>("Foo bar bazé foo foo foo"));
textPart.setText(vmime::make_shared <vmime::stringContentHandler>("Foo bar <strong>bazé</strong> foo foo foo"));
textPart.generateIn(msg, msg);
// Estimated/computed generated size must be greater than the actual generated size
const vmime::size_t genSize = msg->getGeneratedSize(ctx);
const vmime::size_t actualSize = msg->generate().length();
std::ostringstream oss;
oss << "estimated size (" << genSize << ") >= actual size (" << actualSize << ")";
VASSERT(oss.str(), genSize >= actualSize);
}
VMIME_TEST_SUITE_END
| Java |
/*
* This file is part of Cleanflight.
*
* Cleanflight 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.
*
* Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <platform.h>
#include "drivers/io.h"
#include "drivers/pwm_mapping.h"
const uint16_t multiPPM[] = {
PWM1 | (MAP_TO_PPM_INPUT << 8), // PPM input
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM11 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM12 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM13 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM14 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM5 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM6 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM7 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM8 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
0xFFFF
};
const uint16_t multiPWM[] = {
PWM1 | (MAP_TO_PWM_INPUT << 8), // input #1
PWM2 | (MAP_TO_PWM_INPUT << 8),
PWM3 | (MAP_TO_PWM_INPUT << 8),
PWM4 | (MAP_TO_PWM_INPUT << 8),
PWM5 | (MAP_TO_PWM_INPUT << 8),
PWM6 | (MAP_TO_PWM_INPUT << 8),
PWM7 | (MAP_TO_PWM_INPUT << 8),
PWM8 | (MAP_TO_PWM_INPUT << 8), // input #8
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1 or servo #1 (swap to servo if needed)
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2 or servo #2 (swap to servo if needed)
PWM11 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1 or #3
PWM12 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM13 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM14 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #4 or #6
0xFFFF
};
const uint16_t airPPM[] = {
PWM1 | (MAP_TO_PPM_INPUT << 8), // PPM input
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2
PWM11 | (MAP_TO_SERVO_OUTPUT << 8), // servo #1
PWM12 | (MAP_TO_SERVO_OUTPUT << 8),
PWM13 | (MAP_TO_SERVO_OUTPUT << 8),
PWM14 | (MAP_TO_SERVO_OUTPUT << 8), // servo #4
PWM5 | (MAP_TO_SERVO_OUTPUT << 8), // servo #5
PWM6 | (MAP_TO_SERVO_OUTPUT << 8),
PWM7 | (MAP_TO_SERVO_OUTPUT << 8),
PWM8 | (MAP_TO_SERVO_OUTPUT << 8), // servo #8
0xFFFF
};
const uint16_t airPWM[] = {
PWM1 | (MAP_TO_PWM_INPUT << 8), // input #1
PWM2 | (MAP_TO_PWM_INPUT << 8),
PWM3 | (MAP_TO_PWM_INPUT << 8),
PWM4 | (MAP_TO_PWM_INPUT << 8),
PWM5 | (MAP_TO_PWM_INPUT << 8),
PWM6 | (MAP_TO_PWM_INPUT << 8),
PWM7 | (MAP_TO_PWM_INPUT << 8),
PWM8 | (MAP_TO_PWM_INPUT << 8), // input #8
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2
PWM11 | (MAP_TO_SERVO_OUTPUT << 8), // servo #1
PWM12 | (MAP_TO_SERVO_OUTPUT << 8),
PWM13 | (MAP_TO_SERVO_OUTPUT << 8),
PWM14 | (MAP_TO_SERVO_OUTPUT << 8), // servo #4
0xFFFF
};
const timerHardware_t timerHardware[USABLE_TIMER_CHANNEL_COUNT] = {
{ TIM1, IO_TAG(PA8), TIM_Channel_1, TIM1_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_6 }, // PWM1 - PA8
{ TIM16, IO_TAG(PB8), TIM_Channel_1, TIM1_UP_TIM16_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_1 }, // PWM2 - PB8
{ TIM17, IO_TAG(PB9), TIM_Channel_1, TIM1_TRG_COM_TIM17_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_1 }, // PWM3 - PB9
{ TIM8, IO_TAG(PC6), TIM_Channel_1, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM4 - PC6
{ TIM8, IO_TAG(PC7), TIM_Channel_2, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM5 - PC7
{ TIM8, IO_TAG(PC8), TIM_Channel_3, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM6 - PC8
{ TIM3, IO_TAG(PB1), TIM_Channel_4, TIM3_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_2 }, // PWM7 - PB1
{ TIM3, IO_TAG(PA4), TIM_Channel_2, TIM3_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_2 }, // PWM8 - PA2
{ TIM4, IO_TAG(PD12), TIM_Channel_1, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM9 - PD12
{ TIM4, IO_TAG(PD13), TIM_Channel_2, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM10 - PD13
{ TIM4, IO_TAG(PD14), TIM_Channel_3, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM11 - PD14
{ TIM4, IO_TAG(PD15), TIM_Channel_4, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM12 - PD15
{ TIM2, IO_TAG(PA1), TIM_Channel_2, TIM2_IRQn, 0, IOCFG_AF_PP, GPIO_AF_1 }, // PWM13 - PA1
{ TIM2, IO_TAG(PA2), TIM_Channel_3, TIM2_IRQn, 0, IOCFG_AF_PP, GPIO_AF_1 } // PWM14 - PA2
};
| Java |
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program 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 program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#pragma ident "@(#) libfi/mpp_scan/scanmax_sp_6.c 92.1 07/13/99 10:21:33"
#include <stdlib.h>
#include <liberrno.h>
#include <fmath.h>
#include <cray/dopevec.h>
#include "f90_macros.h"
#define RANK 6
/*
* Compiler generated call: CALL _SCANMAX_SP6(RES, SRC, STOP, DIM, MASK)
*
* Purpose: Determine the maximum value of the elements of SRC
* along dimension DIM corresponding to the true elements
* of MASK. This particular routine handles source arrays
* of rank 6 with a data type of 64-bit floating point.
*
* Arguments:
* RES - Dope vector for temporary result array
* SRC - Dope vector for user source array
* STOP - Dope vector for stop array
* DIM - Dimension to operate along
* MASK - Dope vector for logical mask array
*
* Description:
* This is the MPP version of SCANMAX. This particular
* file contains the the intermediate type-specific
* routines. These routines parse and update the dope
* vectors, allocate either shared or private space for
* the result temporary, and possibly update the shared
* data desriptor (sdd) for the result temporary. Once
* this set-up work is complete, a Fortran subroutine
* is called which uses features from the Fortran
* Programming Model to distribute the word across all
* processors.
*
* Include file segmented_scan_p.h contains the rank independent
* source code for this routine.
*/
void
_SCANMAX_SP6 ( DopeVectorType *result,
DopeVectorType *source,
DopeVectorType *stop,
long *dim,
DopeVectorType *mask)
{
#include "segmented_scan_p.h"
if (stop_flag > 0) {
if (mask_flag == 1) {
SCANMAX_MASK_SP6@ (result_sdd_ptr, source_sdd_ptr,
stop_sdd_ptr, &dim_val, mask_sdd_ptr, src_extents,
blkcnts);
} else {
SCANMAX_NOMASK_SP6@ (result_sdd_ptr, source_sdd_ptr,
stop_sdd_ptr, &dim_val, src_extents, blkcnts);
}
}
}
| Java |
/*********************************************************************/
/* */
/* Optimized BLAS libraries */
/* By Kazushige Goto <[email protected]> */
/* */
/* Copyright (c) The University of Texas, 2009. All rights reserved. */
/* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING */
/* THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, */
/* NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY */
/* THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF */
/* TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO */
/* THE USE OF THE SOFTWARE OR DOCUMENTATION. */
/* Under no circumstances shall University be liable for incidental, */
/* special, indirect, direct or consequential damages or loss of */
/* profits, interruption of business, or related expenses which may */
/* arise from use of Software or Documentation, including but not */
/* limited to those resulting from defects in Software and/or */
/* Documentation, or loss or inaccuracy of data of any kind. */
/*********************************************************************/
#include <stdio.h>
#include "common.h"
#ifndef SMP
#define blas_cpu_number 1
#else
int blas_cpu_number = 1;
int blas_get_cpu_number(void){
return blas_cpu_number;
}
#endif
#define FIXED_PAGESIZE 4096
void *sa = NULL;
void *sb = NULL;
static double static_buffer[BUFFER_SIZE/sizeof(double)];
void *blas_memory_alloc(int numproc){
if (sa == NULL){
#if 1
sa = (void *)qalloc(QFAST, BUFFER_SIZE);
#else
sa = (void *)malloc(BUFFER_SIZE);
#endif
sb = (void *)&static_buffer[0];
}
return sa;
}
void blas_memory_free(void *free_area){
return;
}
| Java |
#ifdef __cplusplus
extern "C" {
#endif
/* Get next in EBYEDAT data buffers (exogam) */
int acq_ebyedat_get_next_event(UNSINT16* Buffer,
UNSINT16** EvtAddr,
int* EvtNum,
int EvtFormat);
/* Get next in EBYEDAT data buffers (exogam) ; reentrant version */
int acq_ebyedat_get_next_event_r(UNSINT16* Buffer,
UNSINT16** EvtAddr,
int* EvtNum,
int EvtFormat,
UNSINT16** NextEvent);
#ifdef __cplusplus
}
#endif
| Java |
// 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();
}
}
| Java |
<?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(){
}
}
| Java |
@charset "utf-8";
/* CSS Document */
/* **宽度变换** */
.main, .crumbcon {width:1190px !important;}
.linqigou-nav, .linqigou-filter-box, .tuanIndex, .sscardIndex, .brandList-wrap, .brandIndex, .specialsub-btmnav, .specialsub-con, .specialsub-banner, .specialsub, .specialSell, .specialTop-con, .shanshanNav-con, .headerCon, #sn-con {width:1190px;} | Java |
/*
* gain.cpp
*
* Created on: Sep 28, 2009
* Author: dc
*/
#include <ostream>
#include <gtest/gtest.h>
#include <barrett/systems/gain.h>
#include <barrett/systems/manual_execution_manager.h>
#include <barrett/systems/helpers.h>
#include "./exposed_io_system.h"
namespace {
using namespace barrett;
class GainSystemTest : public ::testing::Test {
public:
GainSystemTest() {
mem.startManaging(eios);
}
protected:
systems::ManualExecutionManager mem;
ExposedIOSystem<double> eios;
};
TEST_F(GainSystemTest, OutputInitiallyUndefined) {
systems::Gain<double> gainSys(12.5);
EXPECT_FALSE(gainSys.input.valueDefined())
<< "value defined without input";
}
TEST_F(GainSystemTest, ConnectsIO) {
systems::Gain<double> gainSys(1.0);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
checkConnected(mem, &eios, eios, 3463.2);
}
TEST_F(GainSystemTest, MultipliesInput) {
systems::Gain<double> gainSys(14.2);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
eios.setOutputValue(-38.52);
mem.runExecutionCycle();
EXPECT_EQ(14.2 * -38.52, eios.getInputValue());
}
TEST_F(GainSystemTest, SetGain) {
systems::Gain<double> gainSys(14.2);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
eios.setOutputValue(-38.52);
mem.runExecutionCycle();
EXPECT_EQ(14.2 * -38.52, eios.getInputValue());
gainSys.setGain(-3.8);
mem.runExecutionCycle();
EXPECT_EQ(-3.8 * -38.52, eios.getInputValue());
}
using std::ostream;
class A;
class B;
class C;
class A {
friend const C operator * (const B& b, const A& a);
private:
float value;
public:
A() : value(0.0) {}
explicit A(float value) :
value(value) {}
};
class B {
friend const C operator * (const B& b, const A& a);
private:
float value;
public:
explicit B(float value) :
value(value) {}
};
class C {
friend ostream& operator<<(ostream& os, C c);
private:
float value;
public:
C() : value(0.0) {}
explicit C(float value) :
value(value) {}
bool operator== (const C& other) const {
return value == other.value;
}
};
const C operator* (const B& b, const A& a) {
return C(a.value * b.value);
}
ostream& operator<<(ostream& os, C c) {
os << c.value;
return os;
}
// mostly, we just want this to compile
TEST_F(GainSystemTest, IGOCanBeDifferentTypes) {
systems::Gain<A, B, C> gainSys(B(-3.0));
ExposedIOSystem<A> out;
ExposedIOSystem<C> in;
mem.startManaging(in);
systems::connect(gainSys.output, in.input);
systems::connect(out.output, gainSys.input);
out.setOutputValue(A(9.0));
mem.runExecutionCycle();
EXPECT_EQ(B(-3.0) * A(9.0), in.getInputValue())
<< "did multiplication wrong";
}
}
| Java |
<?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 [email protected] 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());
}
}
| Java |
. $PSScriptRoot\Shared.ps1
InModuleScope PSJira {
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '', Scope='*', Target='SuppressImportModule')]
$SuppressImportModule = $true
. $PSScriptRoot\Shared.ps1
Describe "Get-JiraIssueCreateMetadata" {
if ($ShowDebugText)
{
Mock 'Write-Debug' {
Write-Host " [DEBUG] $Message" -ForegroundColor Yellow
}
}
Mock Get-JiraConfigServer {
'https://jira.example.com'
}
# If we don't override this in a context or test, we don't want it to
# actually try to query a JIRA instance
Mock Invoke-JiraMethod -ModuleName PSJira {
if ($ShowMockData)
{
Write-Host " Mocked Invoke-WebRequest" -ForegroundColor Cyan
Write-Host " [Uri] $Uri" -ForegroundColor Cyan
Write-Host " [Method] $Method" -ForegroundColor Cyan
}
}
Context "Sanity checking" {
$command = Get-Command -Name Get-JiraIssueCreateMetadata
function defParam($name)
{
It "Has a -$name parameter" {
$command.Parameters.Item($name) | Should Not BeNullOrEmpty
}
}
defParam 'Project'
defParam 'IssueType'
defParam 'Credential'
}
Context "Behavior testing" {
$restResult = ConvertFrom-Json2 @'
{
"expand": "projects",
"projects": [
{
"expand": "issuetypes",
"self": "https://jira.example.com/rest/api/2/project/10003",
"id": "10003",
"key": "TEST",
"name": "Test Project",
"issuetypes": [
{
"self": "https://jira.example.com/rest/api/latest/issuetype/2",
"id": "2",
"iconUrl": "https://jira.example.com/images/icons/issuetypes/newfeature.png",
"name": "Test Issue Type",
"subtask": false,
"expand": "fields",
"fields": {
"summary": {
"required": true,
"schema": {
"type": "string",
"system": "summary"
},
"name": "Summary",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"issuetype": {
"required": true,
"schema": {
"type": "issuetype",
"system": "issuetype"
},
"name": "Issue Type",
"hasDefaultValue": false,
"operations": [],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/issuetype/2",
"id": "2",
"description": "This is a test issue type",
"iconUrl": "https://jira.example.com/images/icons/issuetypes/newfeature.png",
"name": "Test Issue Type",
"subtask": false
}
]
},
"description": {
"required": false,
"schema": {
"type": "string",
"system": "description"
},
"name": "Description",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"project": {
"required": true,
"schema": {
"type": "project",
"system": "project"
},
"name": "Project",
"hasDefaultValue": false,
"operations": [
"set"
],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/project/10003",
"id": "10003",
"key": "TEST",
"name": "Test Project",
"projectCategory": {
"self": "https://jira.example.com/rest/api/2/projectCategory/10000",
"id": "10000",
"description": "All Project Catagories",
"name": "All Project"
}
}
]
},
"reporter": {
"required": true,
"schema": {
"type": "user",
"system": "reporter"
},
"name": "Reporter",
"autoCompleteUrl": "https://jira.example.com/rest/api/latest/user/search?username=",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"assignee": {
"required": false,
"schema": {
"type": "user",
"system": "assignee"
},
"name": "Assignee",
"autoCompleteUrl": "https://jira.example.com/rest/api/latest/user/assignable/search?issueKey=null&username=",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"priority": {
"required": false,
"schema": {
"type": "priority",
"system": "priority"
},
"name": "Priority",
"hasDefaultValue": true,
"operations": [
"set"
],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/priority/1",
"iconUrl": "https://jira.example.com/images/icons/priorities/blocker.png",
"name": "Blocker",
"id": "1"
},
{
"self": "https://jira.example.com/rest/api/2/priority/2",
"iconUrl": "https://jira.example.com/images/icons/priorities/critical.png",
"name": "Critical",
"id": "2"
},
{
"self": "https://jira.example.com/rest/api/2/priority/3",
"iconUrl": "https://jira.example.com/images/icons/priorities/major.png",
"name": "Major",
"id": "3"
},
{
"self": "https://jira.example.com/rest/api/2/priority/4",
"iconUrl": "https://jira.example.com/images/icons/priorities/minor.png",
"name": "Minor",
"id": "4"
},
{
"self": "https://jira.example.com/rest/api/2/priority/5",
"iconUrl": "https://jira.example.com/images/icons/priorities/trivial.png",
"name": "Trivial",
"id": "5"
}
]
},
"labels": {
"required": false,
"schema": {
"type": "array",
"items": "string",
"system": "labels"
},
"name": "Labels",
"autoCompleteUrl": "https://jira.example.com/rest/api/1.0/labels/suggest?query=",
"hasDefaultValue": false,
"operations": [
"add",
"set",
"remove"
]
}
}
}
]
}
]
}
'@
Mock Get-JiraProject -ModuleName PSJira {
[PSCustomObject] @{
ID = 10003;
Name = 'Test Project';
}
}
Mock Get-JiraIssueType -ModuleName PSJira {
[PSCustomObject] @{
ID = 2;
Name = 'Test Issue Type';
}
}
It "Queries Jira for metadata information about creating an issue" {
{ Get-JiraIssueCreateMetadata -Project 10003 -IssueType 2 } | Should Not Throw
Assert-MockCalled -CommandName Invoke-JiraMethod -ModuleName PSJira -Exactly -Times 1 -Scope It -ParameterFilter {$Method -eq 'Get' -and $URI -like '*/rest/api/*/issue/createmeta?projectIds=10003&issuetypeIds=2&expand=projects.issuetypes.fields'}
}
It "Uses ConvertTo-JiraCreateMetaField to output CreateMetaField objects if JIRA returns data" {
# This is a simplified version of what JIRA will give back
Mock Invoke-JiraMethod -ModuleName PSJira {
@{
projects = @{
issuetypes = @{
fields = [PSCustomObject] @{
'a' = 1;
'b' = 2;
}
}
}
}
}
Mock ConvertTo-JiraCreateMetaField -ModuleName PSJira {}
{ Get-JiraIssueCreateMetadata -Project 10003 -IssueType 2 } | Should Not Throw
Assert-MockCalled -CommandName Invoke-JiraMethod -ModuleName PSJira -Exactly -Times 1 -Scope It -ParameterFilter {$Method -eq 'Get' -and $URI -like '*/rest/api/*/issue/createmeta?projectIds=10003&issuetypeIds=2&expand=projects.issuetypes.fields'}
# There are 2 example fields in our mock above, but they should
# be passed to Convert-JiraCreateMetaField as a single object.
# The method should only be called once.
Assert-MockCalled -CommandName ConvertTo-JiraCreateMetaField -ModuleName PSJira -Exactly -Times 1 -Scope It
}
}
}
}
| Java |
#pragma once
#define LONG_NAME "<%= config.info.longName %>"
#define VERSION_LABEL "<%= config.info.versionLabel %>"
#define UUID "<%= config.info.uuid %>"
<% for (prop in config.info.appKeys) {
%>#define <%= prop %> <%= config.info.appKeys[prop] %>
<% } %>
| Java |
-----------------------------------
-- Area: Western Adoulin
-- NPC: Pagnelle
-- Type: Standard NPC and Quest NPC
-- Starts, Involved with, and Finishes Quest: 'Raptor Rapture'
-- @zone 256
-- !pos -8 0 -100 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Raptor_Rapture = player:getQuestStatus(ADOULIN, RAPTOR_RAPTURE);
local Raptor_Rapture_Status = player:getVar("Raptor_Rapture_Status");
if (Raptor_Rapture == QUEST_AVAILABLE) then
if (Raptor_Rapture_Status < 3) then
-- Starts chain of events for the introduction CS for Quest: 'Raptor Rapture'.
-- If player somehow doesn't finish the chain of events, they can just talk to Pagnelle again to retry.
player:setVar("Raptor_Rapture_Status", 1);
player:startEvent(0x13A8);
else
-- Player has finished introductory CS event chain, but didn't accept the quest.
-- Offers Quest: 'Raptor Rapture' if player has yet to accept it.
player:startEvent(0x13C5);
end
elseif (Raptor_Rapture == QUEST_ACCEPTED) then
if (Raptor_Rapture_Status == 4) then
-- Reminder during Quest: 'Raptor Rapture', speak to Ilney.
player:startEvent(0x13A9);
elseif (Raptor_Rapture_Status == 5) then
-- Progresses Quest: 'Raptor Rapture', spoke to Ilney.
player:startEvent(0x13AB);
elseif (Raptor_Rapture_Status == 6) then
local Has_Rockberries = player:hasKeyItem(ROCKBERRY1) and player:hasKeyItem(ROCKBERRY2) and player:hasKeyItem(ROCKBERRY3)
if (Has_Rockberries) then
-- Progresses Quest: 'Raptor Rapture', turning in rockberries.
player:startEvent(0x13AD);
else
-- Reminder during Quest: 'Raptor Rapture', bring rockberries.
player:startEvent(0x13AC);
end
elseif (Raptor_Rapture_Status == 7) then
-- Reminder during Quest: 'Raptor Rapture', go to Rala.
player:startEvent(0x13AE);
elseif (Raptor_Rapture_Status == 8) then
-- Finishes Quest: 'Raptor Rapture'
player:startEvent(0x13AF);
end
else
if (player:needToZone()) then
-- Dialogue after finishing Quest: 'Raptor Rapture', before zoning
player:startEvent(0x13B0);
else
-- Dialogue after finishing Quest: 'Raptor Rapture', after zoning
player:startEvent(0x13B1);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x13A8) then
-- Warps player to Rala Waterways to continue intrductory CS for Quest: 'Raptor Rapture'
player:setPos(0, 0, 0, 0, 258);
elseif ((csid == 0x13C5) and (option == 1)) then
-- Starts Quest: 'Raptor Rapture'
player:addQuest(ADOULIN, RAPTOR_RAPTURE);
player:setVar("Raptor_Rapture_Status", 4);
elseif (csid == 0x13AB) then
-- Progresses Quest: 'Raptor Rapture', spoke to Ilney, now need rockberries.
player:setVar("Raptor_Rapture_Status", 6);
elseif (csid == 0x13AD) then
-- Progresses Quest: 'Raptor Rapture', brought rockberries, now need to go to Rala.
player:delKeyItem(ROCKBERRY1);
player:delKeyItem(ROCKBERRY2);
player:delKeyItem(ROCKBERRY3);
player:setVar("Raptor_Rapture_Status", 7);
elseif (csid == 0x13AF) then
-- Finishing Quest: 'Raptor Rapture'
player:setVar("Raptor_Rapture_Status", 0);
player:completeQuest(ADOULIN, RAPTOR_RAPTURE);
player:addCurrency('bayld', 1000 * BAYLD_RATE);
player:messageSpecial(BAYLD_OBTAINED, 1000 * BAYLD_RATE);
player:addFame(ADOULIN);
player:needToZone(true);
end
end;
| Java |
#ifndef COIN_3DSLOADER_H
#define COIN_3DSLOADER_H
/**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) 1998-2005 by Systems in Motion. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Systems in Motion about acquiring
* a Coin Professional Edition License.
*
* See <URL:http://www.coin3d.org/> for more information.
*
* Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY.
* <URL:http://www.sim.no/>.
*
\**************************************************************************/
#include <Inventor/C/basic.h> // for M_PI
class SoInput;
class SoSeparator;
SbBool coin_3ds_read_file(SoInput * in, SoSeparator *& root,
int appendNormals = 2,
float creaseAngle = 25.f/180.f*M_PI,
SbBool loadMaterials = TRUE,
SbBool loadTextures = TRUE,
SbBool loadObjNames = FALSE,
SbBool indexedTriSet = FALSE,
SbBool centerModel = TRUE,
float modelSize = 10.f);
#endif // !COIN_3DSLOADER_H
| Java |
<?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; ?>
| Java |
/*
===========================================================================
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 );
}
| Java |
-----------------------------------
-- Area: King Ranperre's Tomb
-- NPC: Tombstone
-- Involved in Quest: Grave Concerns
-- @pos 1 0.1 -101 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,GRAVE_CONCERNS) == QUEST_ACCEPTED) then
if(trade:hasItemQty(567,1) and trade:getItemCount() == 1) then -- Trade Well Water
player:startEvent(0x0003);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(SANDORIA);
local MissionStatus = player:getVar("MissionStatus");
local BatHuntCompleted = player:hasCompletedMission(SANDORIA,BAT_HUNT); -- quest repeatable and clicking tombstone should not produce cutscene on repeat
local X = npc:getXPos();
local Z = npc:getZPos();
if(X >= -1 and X <= 1 and Z >= -106 and Z <= -102) then
if(player:getCurrentMission(SANDORIA) == BAT_HUNT and MissionStatus <= 1 and BatHuntCompleted == false) then -- Bug caused players to have MissionStatus 1 at start, so self-healing is necessary.
player:startEvent(0x0004);
else
player:startEvent(0x0002);
end
elseif(currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then
player:startEvent(0x0008);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0004) then
player:setVar("MissionStatus",2);
elseif(csid == 0x0002) then
local graveConcerns = player:getQuestStatus(SANDORIA,GRAVE_CONCERNS);
if(graveConcerns == QUEST_ACCEPTED and player:hasItem(547) == false and player:hasItem(567) == false) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,547); -- Tomb Waterskin
else
player:addItem(547);
player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin
end
end
elseif(csid == 0x0003) then
player:tradeComplete();
player:setVar("OfferingWaterOK",1);
player:addItem(547);
player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin
elseif(csid == 0x0008) then
player:setVar("MissionStatus",3);
player:addKeyItem(ANCIENT_SANDORIAN_BOOK);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_SANDORIAN_BOOK);
end
end;
| Java |
#!/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()
| Java |
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"));
}
}
}
| Java |
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
| Java |
<?php
// Heading
$_['heading_title'] = 'OpenBay Pro';
// Text
$_['text_module'] = 'フィード設定';
$_['text_installed'] = 'OpenBayProモジュールがインストールされました。 拡張機能 -> OpenBay Proで利用することができます'; | Java |
/*
* Copyright (C) 2009 Lalit Pant <[email protected]>
*
* The contents of this file are subject to the GNU General Public License
* Version 3 (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.gnu.org/copyleft/gpl.html
*
* 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.
*
*/
package net.kogics.kojo
package staging
//import org.junit.After
//import org.junit.Before
import org.junit.Test
import org.junit.Assert._
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.{CountDownLatch, TimeUnit}
import net.kogics.kojo.core.RunContext
import net.kogics.kojo.util._
/* Testing policy
*
* Every member of the interface shall be tested, preferably for effect but at
* least for executability.
*
* The implementation is tested as needed but is generally considered to be
* sufficiently correct if the interface works correctly.
*
*/
// cargo coding off CodePaneTest
class StagingTestBase extends KojoTestBase {
initNetbeansDirs()
val runCtx = new TestRunContext(this)
val codeRunner = new xscala.ScalaCodeRunner(runCtx, SpriteCanvas.instance)
val pane = new javax.swing.JEditorPane()
val Delimiter = ""
var latch: CountDownLatch = _
def runCode() {
latch = new CountDownLatch(1)
codeRunner.runCode(pane.getText())
latch.await()
}
object Tester {
var resCounter = 0
var res = ""
def postIncrCounter = {
val c = resCounter
resCounter += 1
c
}
def isMultiLine(cmd: String) = cmd.contains("\n") || cmd.contains(" ; ")
def outputPrefix(cmd: String) = {
if (isMultiLine(cmd)) ""
else "res" + postIncrCounter + ": "
}
def apply (cmd: String, s: Option[String] = None) = {
runCtx.clearOutput
pane.setText(cmd)
runCtx.success.set(false)
runCode()
Utils.runInSwingThreadAndWait { /* noop */ }
assertTrue(runCtx.success.get)
val output = stripCrLfs(runCtx.getCurrentOutput)
s foreach { ss =>
if (ss isEmpty) {
// an empty expected string means print output
println(output)
} else if (ss(0) == '$') {
val regexp = outputPrefix(cmd) + ss.tail
assertTrue(output matches regexp)
} else {
val expect = outputPrefix(cmd) + ss
assertEquals(expect, output)
}
}
}
}
type PNode = edu.umd.cs.piccolo.PNode
type PPath = edu.umd.cs.piccolo.nodes.PPath
def stripCrLfs(str: String) = str.replaceAll("\r?\n", "")
val CL = java.awt.geom.PathIterator.SEG_CLOSE // 4
val CT = java.awt.geom.PathIterator.SEG_CUBICTO // 3
val LT = java.awt.geom.PathIterator.SEG_LINETO // 1
val MT = java.awt.geom.PathIterator.SEG_MOVETO // 0
val QT = java.awt.geom.PathIterator.SEG_QUADTO // 2
val fmt = "%g"
def segmentToString(t: Int, coords: Array[Double]) = t match {
case MT =>
"M" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " "
case LT =>
"L" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " "
case QT =>
"Q" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " " +
(fmt format coords(2)) + "," + (fmt format coords(3)) + " "
case CT =>
"C" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " " +
(fmt format coords(2)) + "," + (fmt format coords(3)) + " " +
(fmt format coords(4)) + "," + (fmt format coords(5)) + " "
case CL =>
"z "
}
def pathIteratorToString(pi: java.awt.geom.PathIterator) = {
var res = new StringBuffer
while (!pi.isDone) {
pi.next
val coords = Array[Double](0, 0, 0, 0, 0, 0)
val t = pi.currentSegment(coords)
res.append(segmentToString(t, coords))
}
res.toString
}
def pathReferenceToString(pr: java.awt.geom.Path2D) = {
val at = new java.awt.geom.AffineTransform
val pi = pr.getPathIterator(at)
pathIteratorToString(pi)
}
def pathData(polyLine: kgeom.PolyLine) = {
pathReferenceToString(polyLine.polyLinePath)
}
def pathData(ppath: PPath) = {
pathReferenceToString(ppath.getPathReference)
}
def makeString(pnode: PNode) = {
val x = pnode.getX.round + 1
val y = pnode.getY.round + 1
if (pnode.isInstanceOf[kgeom.PolyLine]) {
"PolyLine(" + (x + 1) + "," + (y + 1) + " " +
pathData(pnode.asInstanceOf[kgeom.PolyLine]) + ")"
}
else if (pnode.isInstanceOf[PPath]) {
"PPath(" + x + "," + y + " " +
pathData(pnode.asInstanceOf[PPath]) + ")"
}
else pnode.toString
}
}
| Java |
/* 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;
}
| Java |
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();
}
);
| Java |
<html><head><body>Pet Manager Lundy:<br>
All the people who can give you information about pet wolves are here in the <font color="LEVEL">Town of Gludio</font>.<br>
First, go see <font color="LEVEL">Gatekeeper Bella</font>.
</body></html> | Java |
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
| Java |
/*
Copyright 2005, 2006, 2007 Dennis van Weeren
Copyright 2008, 2009 Jakub Bednarski
This file is part of Minimig
Minimig 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.
Minimig 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/>.
*/
// 2009-11-14 - OSD labels changed
// 2009-12-15 - added display of directory name extensions
// 2010-01-09 - support for variable number of tracks
//#include "AT91SAM7S256.h"
//#include "stdbool.h"
#include "stdio.h"
#include "string.h"
#include "errors.h"
#include "mmc.h"
#include "fat.h"
#include "osd.h"
#include "fpga.h"
#include "fdd.h"
#include "hdd.h"
#include "hardware.h"
#include "firmware.h"
#include "config.h"
#include "menu.h"
// other constants
#define DIRSIZE 8 // number of items in directory display window
unsigned char menustate = MENU_NONE1;
unsigned char parentstate;
unsigned char menusub = 0;
unsigned int menumask = 0; // Used to determine which rows are selectable...
unsigned long menu_timer;
extern unsigned char drives;
extern adfTYPE df[4];
extern configTYPE config;
extern fileTYPE file;
extern char s[40];
extern unsigned char fat32;
extern DIRENTRY DirEntry[MAXDIRENTRIES];
extern unsigned char sort_table[MAXDIRENTRIES];
extern unsigned char nDirEntries;
extern unsigned char iSelectedEntry;
extern unsigned long iCurrentDirectory;
extern char DirEntryLFN[MAXDIRENTRIES][261];
char DirEntryInfo[MAXDIRENTRIES][5]; // disk number info of dir entries
char DiskInfo[5]; // disk number info of selected entry
extern const char version[];
const char *config_filter_msg[] = {"none", "HORIZONTAL", "VERTICAL", "H+V"};
const char *config_memory_chip_msg[] = {"0.5 MB", "1.0 MB", "1.5 MB", "2.0 MB"};
const char *config_memory_slow_msg[] = {"none ", "0.5 MB", "1.0 MB", "1.5 MB"};
const char *config_scanlines_msg[] = {"off", "dim", "black"};
const char *config_memory_fast_msg[] = {"none ", "2.0 MB", "4.0 MB"};
const char *config_cpu_msg[] = {"68000 ", "68010", "-----","020 alpha"};
const char *config_hdf_msg[] = {"Disabled", "Hardfile (disk img)", "MMC/SD card", "MMC/SD partition 1", "MMC/SD partition 2", "MMC/SD partition 3", "MMC/SD partition 4"};
const char *config_chipset_msg[] = {"OCS-A500", "OCS-A1000", "ECS", "---"};
char *config_autofire_msg[] = {" AUTOFIRE OFF", " AUTOFIRE FAST", " AUTOFIRE MEDIUM", " AUTOFIRE SLOW"};
enum HelpText_Message {HELPTEXT_NONE,HELPTEXT_MAIN,HELPTEXT_HARDFILE,HELPTEXT_CHIPSET,HELPTEXT_MEMORY,HELPTEXT_VIDEO};
const char *helptexts[]={
0,
" Welcome to Minimig! Use the cursor keys to navigate the menus. Use space bar or enter to select an item. Press Esc or F12 to exit the menus. Joystick emulation on the numeric keypad can be toggled with the numlock key, while pressing Ctrl-Alt-0 (numeric keypad) toggles autofire mode.",
" Minimig can emulate an A600 IDE harddisk interface. The emulation can make use of Minimig-style hardfiles (complete disk images) or UAE-style hardfiles (filesystem images with no partition table). It is also possible to use either the entire SD card or an individual partition as an emulated harddisk.",
" Minimig's processor core can emulate a 68000 or 68020 processor (though the 68020 mode is still experimental.) If you're running software built for 68000, there's no advantage to using the 68020 mode, since the 68000 emulation runs just as fast.",
#ifdef ACTIONREPLAY_BROKEN
" Minimig can make use of up to 2 megabytes of Chip RAM, up to 1.5 megabytes of Slow RAM (A500 Trapdoor RAM), and up to 8 megabytes of true Fast RAM.",
#else
" Minimig can make use of up to 2 megabytes of Chip RAM, up to 1.5 megabytes of Slow RAM (A500 Trapdoor RAM), and up to 8 megabytes of true Fast RAM. To use the Action Replay feature you will need an Action Replay 3 ROM file on the SD card, named AR3.ROM. You will also need to set Fast RAM to no more than 2 megabytes.",
#endif
" Minimig's video features include a blur filter, to simulate the poorer picture quality on older monitors, and also scanline generation to simulate the appearance of a screen with low vertical resolution.",
0
};
//extern unsigned char DEBUG;
unsigned char config_autofire = 0;
// file selection menu variables
char *fs_pFileExt = NULL;
unsigned char fs_Options;
unsigned char fs_MenuSelect;
unsigned char fs_MenuCancel;
static char debuglines[8*32+1];
static char debugptr=0;
void _showdebugmessages()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
int i;
for(i=0;i<8;++i)
{
int j=(debugptr+i)&7;
debuglines[j*32+31]=0;
OsdWrite(i,&debuglines[j*32],i==7,0);
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
void SelectFile(char* pFileExt, unsigned char Options, unsigned char MenuSelect, unsigned char MenuCancel)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
// this function displays file selection menu
if (strncmp(pFileExt, fs_pFileExt, 3) != 0) // check desired file extension
{ // if different from the current one go to the root directory and init entry buffer
ChangeDirectory(DIRECTORY_ROOT);
ScanDirectory(SCAN_INIT, pFileExt, Options);
}
fs_pFileExt = pFileExt;
fs_Options = Options;
fs_MenuSelect = MenuSelect;
fs_MenuCancel = MenuCancel;
menustate = MENU_FILE_SELECT1;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
#define STD_EXIT " exit"
#define HELPTEXT_DELAY 10000
#define FRAME_DELAY 150
void ShowSplash()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L0);
OsdSetTitle("Welcome",0);
OsdWrite(0, "", 0,0);
OsdDrawLogo(1,0,0);
OsdDrawLogo(2,1,0);
OsdDrawLogo(3,2,0);
OsdDrawLogo(4,3,0);
OsdDrawLogo(5,4,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
OsdEnable(0);
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L0);
}
void HideSplash()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L0);
OsdDisable();
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L0);
}
void HandleUI(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
unsigned char i, c, up, down, select, menu, right, left, plus, minus;
unsigned long len;
static hardfileTYPE t_hardfile[2]; // temporary copy of former hardfile configuration
static unsigned char ctrl = false;
static unsigned char lalt = false;
char enable;
static long helptext_timer;
static const char *helptext;
static char helpstate=0;
// get user control codes
c = OsdGetCtrl();
// decode and set events
menu = false;
select = false;
up = false;
down = false;
left = false;
right = false;
plus=false;
minus=false;
switch (c)
{
case KEY_CTRL :
ctrl = true;
break;
case KEY_CTRL | KEY_UPSTROKE :
ctrl = false;
break;
case KEY_LALT :
lalt = true;
break;
case KEY_LALT | KEY_UPSTROKE :
lalt = false;
break;
case KEY_KPPLUS :
if (ctrl && lalt)
{
config.chipset |= CONFIG_TURBO;
ConfigChipset(config.chipset);
if (menustate == MENU_SETTINGS_CHIPSET2)
menustate = MENU_SETTINGS_CHIPSET1;
else if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(" TURBO");
}
else
plus=true;
break;
case KEY_KPMINUS :
if (ctrl && lalt)
{
config.chipset &= ~CONFIG_TURBO;
ConfigChipset(config.chipset);
if (menustate == MENU_SETTINGS_CHIPSET2)
menustate = MENU_SETTINGS_CHIPSET1;
else if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(" NORMAL");
}
else
minus=true;
break;
case KEY_KP0 :
if (ctrl && lalt)
{
if (menustate == MENU_NONE2 || menustate == MENU_INFO)
{
config_autofire++;
config_autofire &= 3;
ConfigAutofire(config_autofire);
if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(config_autofire_msg[config_autofire]);
}
}
break;
case KEY_MENU :
if (ctrl && lalt)
{
OsdSetTitle("Debug",0);
DebugMode=DebugMode^1;
menustate = MENU_NONE1;
}
else
menu = true;
break;
case KEY_ESC :
if (menustate != MENU_NONE2)
menu = true;
break;
case KEY_ENTER :
case KEY_SPACE :
select = true;
break;
case KEY_UP :
up = true;
break;
case KEY_DOWN :
down = true;
break;
case KEY_LEFT :
left = true;
break;
case KEY_RIGHT :
right = true;
break;
}
if(menu || select || up || down || left || right )
{
if(helpstate)
OsdWrite(7,STD_EXIT,(menumask-((1<<(menusub+1))-1))<=0,0); // Redraw the Exit line...
helpstate=0;
helptext_timer=GetTimer(HELPTEXT_DELAY);
}
if(helptext)
{
if(helpstate<9)
{
if(CheckTimer(helptext_timer))
{
helptext_timer=GetTimer(FRAME_DELAY);
OsdWriteOffset(7,STD_EXIT,0,0,helpstate);
++helpstate;
}
}
else if(helpstate==9)
{
ScrollReset();
++helpstate;
}
else
ScrollText(7,helptext,0,0,0);
}
// Standardised menu up/down.
// The screen should set menumask, bit 0 to make the top line selectable, bit 1 for the 2nd line, etc.
// (Lines in this context don't have to correspond to rows on the OSD.)
// Also set parentstate to the appropriate menustate.
if(menumask)
{
if ((unsigned)down && ((unsigned)menumask>=(unsigned)(1<<(menusub+1)))) // Any active entries left?
{
do
menusub++;
while((menumask & (1<<menusub)) == 0);
menustate = parentstate;
}
if (up && menusub > 0 && (menumask<<(8-menusub)))
{
do
--menusub;
while((menumask & (1<<menusub)) == 0);
menustate = parentstate;
}
}
switch (menustate)
{
/******************************************************************/
/* no menu selected */
/******************************************************************/
case MENU_NONE1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0;
if(DebugMode)
{
helptext=helptexts[HELPTEXT_NONE];
OsdEnable(0);
}
else
OsdDisable();
menustate = MENU_NONE2;
break;
case MENU_NONE2 :
if(DebugMode)
_showdebugmessages();
if (menu)
{
menustate = MENU_MAIN1;
menusub = 0;
OsdClear();
OsdEnable(DISABLE_KEYBOARD);
}
break;
/******************************************************************/
/* main menu */
/******************************************************************/
case MENU_MAIN1 :
menumask=0x70; // b01110000 Floppy turbo, Harddisk options & Exit.
OsdSetTitle("Minimig",OSD_ARROW_RIGHT);
helptext=helptexts[HELPTEXT_MAIN];
// floppy drive info
// We display a line for each drive that's active
// in the config file, but grey out any that the FPGA doesn't think are active.
// We also print a help text in place of the last drive if it's inactive.
for (i = 0; i < 4; i++)
{
if(i==config.floppy.drives+1)
OsdWrite(i," KP +/- to add/remove drives",0,1);
else
{
strcpy(s, " dfx: ");
s[3] = i + '0';
if(i<=drives)
{
menumask|=(1<<i); // Make enabled drives selectable
if (df[i].status & DSK_INSERTED) // floppy disk is inserted
{
strncpy(&s[6], df[i].name, sizeof(df[0].name));
if(!(df[i].status & DSK_WRITABLE))
strcpy(&s[6 + sizeof(df[i].name)-1], " \x17"); // padlock icon for write-protected disks
else
strcpy(&s[6 + sizeof(df[i].name)-1], " "); // clear padlock icon for write-enabled disks
}
else // no floppy disk
{
strcat(s, "* no disk *");
}
}
else if(i<=config.floppy.drives)
{
strcat(s,"* active after reset *");
}
else
strcpy(s,"");
OsdWrite(i, s, menusub == i,(i>drives)||(i>config.floppy.drives));
}
}
sprintf(s," Floppy disk turbo : %s",config.floppy.speed ? "on" : "off");
OsdWrite(4, s, menusub==4,0);
OsdWrite(5, " Hard disk settings \x16", menusub == 5,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 6,0);
menustate = MENU_MAIN2;
parentstate=MENU_MAIN1;
break;
case MENU_MAIN2 :
if (menu)
menustate = MENU_NONE1;
else if(plus && (config.floppy.drives<3))
{
config.floppy.drives++;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if(minus && (config.floppy.drives>0))
{
config.floppy.drives--;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if (select)
{
if (menusub < 4)
{
if (df[menusub].status & DSK_INSERTED) // eject selected floppy
{
df[menusub].status = 0;
menustate = MENU_MAIN1;
}
else
{
df[menusub].status = 0;
SelectFile("ADF", SCAN_DIR | SCAN_LFN, MENU_FILE_SELECTED, MENU_MAIN1);
}
}
else if (menusub == 4) // Toggle floppy turbo
{
config.floppy.speed^=1;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if (menusub == 5) // Go to harddrives page.
{
t_hardfile[0] = config.hardfile[0];
t_hardfile[1] = config.hardfile[1];
menustate = MENU_SETTINGS_HARDFILE1;
menusub=0;
}
else if (menusub == 6)
menustate = MENU_NONE1;
}
else if (c == KEY_BACK) // eject all floppies
{
for (i = 0; i <= drives; i++)
df[i].status = 0;
menustate = MENU_MAIN1;
}
else if (right)
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
break;
case MENU_FILE_SELECTED : // file successfully selected
InsertFloppy(&df[menusub]);
menustate = MENU_MAIN1;
menusub++;
if (menusub > drives)
menusub = 6;
break;
/******************************************************************/
/* second part of the main menu */
/******************************************************************/
case MENU_MAIN2_1 :
helptext=helptexts[HELPTEXT_MAIN];
menumask=0x3f;
OsdSetTitle("Settings",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, " load configuration", menusub == 0,0);
OsdWrite(1, " save configuration", menusub == 1,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " chipset settings \x16", menusub == 2,0);
OsdWrite(4, " memory settings \x16", menusub == 3,0);
OsdWrite(5, " video settings \x16", menusub == 4,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
parentstate = menustate;
menustate = MENU_MAIN2_2;
break;
case MENU_MAIN2_2 :
if (menu)
menustate = MENU_NONE1;
else if (select)
{
if (menusub == 0)
{
menusub = 0;
menustate = MENU_LOADCONFIG_1;
}
else if (menusub == 1)
{
menusub = 0;
menustate = MENU_SAVECONFIG_1;
}
else if (menusub == 2)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (menusub == 3)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (menusub == 4)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (menusub == 5)
menustate = MENU_NONE1;
}
else if (left)
{
menustate = MENU_MAIN1;
menusub = 0;
}
else if (right)
{
menustate = MENU_MISC1;
menusub = 0;
}
break;
case MENU_MISC1 :
helptext=helptexts[HELPTEXT_MAIN];
menumask=0x0f; // Reset, about and exit.
OsdSetTitle("Misc",OSD_ARROW_LEFT);
OsdWrite(0, " Reset", menusub == 0,0);
OsdWrite(1, "", 0,0);
OsdWrite(2, " Return to Chameleon", menusub == 1,0);
// OsdWrite(3, " (Not yet implemented)", 0,1);
OsdWrite(3, "", 0,0);
OsdWrite(4, " About", menusub == 2,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
parentstate = menustate;
menustate = MENU_MISC2;
break;
case MENU_MISC2 :
if (menu)
menusub=0, menustate = MENU_NONE1;
if (left)
menusub=0, menustate = MENU_MAIN2_1;
else if (select)
{
if (menusub == 0) // Reset
{
menusub = 0;
menustate=MENU_RESET1;
}
if (menusub == 1) // Reconfig
{
menusub=0;
menustate=MENU_RECONF1;
}
if (menusub == 2) // About
{
menusub=0;
menustate=MENU_ABOUT1;
}
if (menusub == 3) // Exit
{
menustate=MENU_NONE1;
}
}
break;
case MENU_ABOUT1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0x01; // Just Exit
OsdSetTitle("About",0);
OsdDrawLogo(0,0,1);
OsdDrawLogo(1,1,1);
OsdDrawLogo(2,2,1);
OsdDrawLogo(3,3,1);
OsdDrawLogo(4,4,1);
OsdDrawLogo(6,6,1);
// OsdWrite(1, "", 0,0);
// OsdWriteDoubleSize(2," Minimig",0);
// OsdWriteDoubleSize(3," Minimig",1);
// OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 0,0);
StarsInit();
ScrollReset();
parentstate = menustate;
menustate = MENU_ABOUT2;
break;
case MENU_ABOUT2 :
StarsUpdate();
OsdDrawLogo(0,0,1);
OsdDrawLogo(1,1,1);
OsdDrawLogo(2,2,1);
OsdDrawLogo(3,3,1);
OsdDrawLogo(4,4,1);
OsdDrawLogo(6,6,1);
ScrollText(5," Minimig by Dennis van Weeren. Chipset improvements by Jakub Bednarski and Sascha Boing. TG68 softcore and Chameleon port by Tobias Gubener. Menu / disk code by Dennis van Weeren, Jakub Bednarski and Alastair M. Robinson. Build process, repository and tooling by Christian Vogelgsang. Minimig logo based on a design by Loriano Pagni. Minimig is distributed under the terms of the GNU General Public License version 3.",0,0,0);
if (select || menu)
{
menusub = 2;
menustate=MENU_MISC1;
}
break;
case MENU_LOADCONFIG_1 :
helptext=helptexts[HELPTEXT_NONE];
if(parentstate!=menustate) // First run?
{
menumask=0x20;
SetConfigurationFilename(0); if(ConfigurationExists(0)) menumask|=0x01;
SetConfigurationFilename(1); if(ConfigurationExists(0)) menumask|=0x02;
SetConfigurationFilename(2); if(ConfigurationExists(0)) menumask|=0x04;
SetConfigurationFilename(3); if(ConfigurationExists(0)) menumask|=0x08;
SetConfigurationFilename(4); if(ConfigurationExists(0)) menumask|=0x10;
}
parentstate=menustate;
OsdSetTitle("Load",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Default", menusub == 0,(menumask & 1)==0);
OsdWrite(2, " 1", menusub == 1,(menumask & 2)==0);
OsdWrite(3, " 2", menusub == 2,(menumask & 4)==0);
OsdWrite(4, " 3", menusub == 3,(menumask & 8)==0);
OsdWrite(5, " 4", menusub == 4,(menumask & 0x10)==0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_LOADCONFIG_2;
break;
case MENU_LOADCONFIG_2 :
if (down)
{
// if (menusub < 3)
if (menusub < 5)
menusub++;
menustate = MENU_LOADCONFIG_1;
}
else if (select)
{
if(menusub<5)
{
OsdDisable();
SetConfigurationFilename(menusub);
LoadConfiguration(NULL);
// OsdReset(RESET_NORMAL);
menustate = MENU_NONE1;
}
else
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
}
if (menu) // exit menu
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
break;
/******************************************************************/
/* file selection menu */
/******************************************************************/
case MENU_FILE_SELECT1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Select",0);
PrintDirectory();
menustate = MENU_FILE_SELECT2;
break;
case MENU_FILE_SELECT2 :
menumask=0;
ScrollLongName(); // scrolls file name if longer than display line
if (c == KEY_HOME)
{
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (c == KEY_BACK)
{
if (iCurrentDirectory) // if not root directory
{
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
ChangeDirectory(DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0));
if (ScanDirectory(SCAN_INIT_FIRST, fs_pFileExt, fs_Options))
ScanDirectory(SCAN_INIT_NEXT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
}
if (c == KEY_PGUP)
{
ScanDirectory(SCAN_PREV_PAGE, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1; }
if (c == KEY_PGDN)
{
ScanDirectory(SCAN_NEXT_PAGE, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (down) // scroll down one entry
{
ScanDirectory(SCAN_NEXT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (up) // scroll up one entry
{
ScanDirectory(SCAN_PREV, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if ((i = GetASCIIKey(c)))
{ // find an entry beginning with given character
if (nDirEntries)
{
if (DirEntry[sort_table[iSelectedEntry]].Attributes & ATTR_DIRECTORY)
{ // it's a directory
if (i < DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
else if (i > DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
else
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options)) // find nexr
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
}
else
{ // it's a file
if (i < DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
else if (i > DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
else
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options)) // find next
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
}
}
menustate = MENU_FILE_SELECT1;
}
if (select)
{
if (DirEntry[sort_table[iSelectedEntry]].Attributes & ATTR_DIRECTORY)
{
ChangeDirectory(DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0));
{
if (strncmp((char*)DirEntry[sort_table[iSelectedEntry]].Name, "..", 2) == 0)
{ // parent dir selected
if (ScanDirectory(SCAN_INIT_FIRST, fs_pFileExt, fs_Options))
ScanDirectory(SCAN_INIT_NEXT, fs_pFileExt, fs_Options);
else
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
}
else
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
}
else
{
if (nDirEntries)
{
file.long_name[0] = 0;
len = strlen(DirEntryLFN[sort_table[iSelectedEntry]]);
if (len > 4)
if (DirEntryLFN[sort_table[iSelectedEntry]][len-4] == '.')
len -= 4; // remove extension
if (len > sizeof(file.long_name))
len = sizeof(file.long_name);
strncpy(file.name, (const char*)DirEntry[sort_table[iSelectedEntry]].Name, sizeof(file.name));
memset(file.long_name, 0, sizeof(file.long_name));
strncpy(file.long_name, DirEntryLFN[sort_table[iSelectedEntry]], len);
strncpy(DiskInfo, DirEntryInfo[iSelectedEntry], sizeof(DiskInfo));
file.size = DirEntry[sort_table[iSelectedEntry]].FileSize;
file.attributes = DirEntry[sort_table[iSelectedEntry]].Attributes;
file.start_cluster = DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0);
file.cluster = file.start_cluster;
file.sector = 0;
menustate = fs_MenuSelect;
}
}
}
if (menu)
{
menustate = fs_MenuCancel;
}
break;
/******************************************************************/
/* reset menu */
/******************************************************************/
case MENU_RESET1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Reset",0);
menumask=0x03; // Yes / No
parentstate=menustate;
OsdWrite(0, "", 0,0);
OsdWrite(1, " Reset Minimig?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_RESET2;
break;
case MENU_RESET2 :
if (select && menusub == 0)
{
menustate = MENU_NONE1;
OsdReset(RESET_NORMAL);
}
if (menu || (select && (menusub == 1))) // exit menu
{
menustate = MENU_MISC1;
menusub = 0;
}
break;
/******************************************************************/
/* reconfigure confirmation */
/******************************************************************/
case MENU_RECONF1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Exit",0);
menumask=0x03; // Yes / No
parentstate=menustate;
OsdWrite(0, "", 0,0);
OsdWrite(1, " Return to Chameleon?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_RECONF2;
break;
case MENU_RECONF2 :
if (select && menusub == 0)
{
OsdReconfig();
}
if (menu || (select && (menusub == 1))) // exit menu
{
menustate = MENU_MISC1;
menusub = 1;
}
break;
/******************************************************************/
/* settings menu */
/******************************************************************/
/*
case MENU_SETTINGS1 :
menumask=0;
OsdSetTitle("Settings",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " chipset", menusub == 0,0);
OsdWrite(2, " memory", menusub == 1,0);
OsdWrite(3, " drives", menusub == 2,0);
OsdWrite(4, " video", menusub == 3,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
if (menusub == 5)
OsdWrite(7, " \x12 save \x12", 1,0);
else if (menusub == 4)
OsdWrite(7, " \x13 exit \x13", 1,0);
else
OsdWrite(7, STD_EXIT, 0,0);
menustate = MENU_SETTINGS2;
break;
case MENU_SETTINGS2 :
if (down && menusub < 5)
{
menusub++;
menustate = MENU_SETTINGS1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS1;
}
if (select)
{
if (menusub == 0)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (menusub == 1)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (menusub == 2)
{
menustate = MENU_SETTINGS_DRIVES1;
menusub = 0;
}
else if (menusub == 3)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (menusub == 4)
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
else if (menusub == 5)
{
// SaveConfiguration(0); // Use slot-based config filename instead
menustate = MENU_SAVECONFIG_1;
menusub = 0;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
break;
*/
case MENU_SAVECONFIG_1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0x3f;
parentstate=menustate;
OsdSetTitle("Save",0);
OsdWrite(0, "", 0, 0);
OsdWrite(1, " Default", menusub == 0,0);
OsdWrite(2, " 1", menusub == 1,0);
OsdWrite(3, " 2", menusub == 2,0);
OsdWrite(4, " 3", menusub == 3,0);
OsdWrite(5, " 4", menusub == 4,0);
OsdWrite(6, "", 0,0);
// OsdWrite(7, " exit", menusub == 3);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SAVECONFIG_2;
break;
case MENU_SAVECONFIG_2 :
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 5;
}
else if (up)
{
if (menusub > 0)
menusub--;
menustate = MENU_SAVECONFIG_1;
}
else if (down)
{
// if (menusub < 3)
if (menusub < 5)
menusub++;
menustate = MENU_SAVECONFIG_1;
}
else if (select)
{
if(menusub<5)
{
SetConfigurationFilename(menusub);
SaveConfiguration(NULL);
menustate = MENU_NONE1;
}
else
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
}
if (menu) // exit menu
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
break;
/******************************************************************/
/* chipset settings menu */
/******************************************************************/
case MENU_SETTINGS_CHIPSET1 :
helptext=helptexts[HELPTEXT_CHIPSET];
menumask=0;
OsdSetTitle("Chipset",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " CPU : ");
// strcat(s, config.chipset & CONFIG_TURBO ? "turbo" : "normal");
strcat(s, config_cpu_msg[config.cpu & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " Video : ");
strcat(s, config.chipset & CONFIG_NTSC ? "NTSC" : "PAL");
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " Chipset : ");
strcat(s, config_chipset_msg[config.chipset >> 2 & 3]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
menustate = MENU_SETTINGS_CHIPSET2;
break;
case MENU_SETTINGS_CHIPSET2 :
if (down && menusub < 3)
{
menusub++;
menustate = MENU_SETTINGS_CHIPSET1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS_CHIPSET1;
}
if (select)
{
if (menusub == 0)
{
// config.chipset ^= CONFIG_TURBO;
menustate = MENU_SETTINGS_CHIPSET1;
config.cpu += 1;
if ((config.cpu & 0x03)==0x02)
config.cpu += 1;
// ConfigChipset(config.chipset);
ConfigCPU(config.cpu);
}
else if (menusub == 1)
{
config.chipset ^= CONFIG_NTSC;
menustate = MENU_SETTINGS_CHIPSET1;
ConfigChipset(config.chipset);
}
else if (menusub == 2)
{
if (config.chipset & CONFIG_ECS)
config.chipset &= ~(CONFIG_ECS|CONFIG_A1000);
else
config.chipset += CONFIG_A1000;
menustate = MENU_SETTINGS_CHIPSET1;
ConfigChipset(config.chipset);
}
else if (menusub == 3)
{
menustate = MENU_MAIN2_1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 2;
}
else if (right)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
break;
/******************************************************************/
/* memory settings menu */
/******************************************************************/
case MENU_SETTINGS_MEMORY1 :
helptext=helptexts[HELPTEXT_MEMORY];
menumask=0x3f;
parentstate=menustate;
OsdSetTitle("Memory",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " CHIP : ");
strcat(s, config_memory_chip_msg[config.memory & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " SLOW : ");
strcat(s, config_memory_slow_msg[config.memory >> 2 & 0x03]);
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " FAST : ");
strcat(s, config_memory_fast_msg[config.memory >> 4 & 0x03]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
strcpy(s, " ROM : ");
if (config.kickstart.long_name[0])
strncat(s, config.kickstart.long_name, sizeof(config.kickstart.long_name));
else
strncat(s, config.kickstart.name, sizeof(config.kickstart.name));
OsdWrite(5, s, menusub == 3,0);
#ifdef ACTIONREPLAY_BROKEN
OsdWrite(0, "", 0,0);
menumask&=0xef; // Remove bit 4
#else
strcpy(s, " AR3 : ");
strcat(s, config.disable_ar3 ? "disabled" : "enabled ");
OsdWrite(6, s, menusub == 4,config.memory&0x20); // Grey out AR3 if more than 2MB fast memory
#endif
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SETTINGS_MEMORY2;
break;
case MENU_SETTINGS_MEMORY2 :
if (select)
{
if (menusub == 0)
{
config.memory = ((config.memory + 1) & 0x03) | (config.memory & ~0x03);
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 1)
{
config.memory = ((config.memory + 4) & 0x0C) | (config.memory & ~0x0C);
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 2)
{
config.memory = ((config.memory + 0x10) & 0x30) | (config.memory & ~0x30);
if ((config.memory & 0x30) == 0x30)
config.memory -= 0x30;
// if (!(config.disable_ar3 & 0x01)&&(config.memory & 0x20))
// config.memory &= ~0x30;
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 3)
{
SelectFile("ROM", SCAN_LFN, MENU_ROMFILE_SELECTED, MENU_SETTINGS_MEMORY1);
}
else if (menusub == 4)
{
if (!(config.disable_ar3 & 0x01)||(config.memory & 0x20))
config.disable_ar3 |= 0x01;
else
config.disable_ar3 &= 0xFE;
menustate = MENU_SETTINGS_MEMORY1;
}
else if (menusub == 5)
{
menustate = MENU_MAIN2_1;
menusub = 3;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 3;
}
else if (right)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
break;
/******************************************************************/
/* drive settings menu */
/******************************************************************/
/*
case MENU_SETTINGS_DRIVES1 :
menumask=0;
OsdSetTitle("Drives",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
sprintf(s, " drives : %d", config.floppy.drives + 1,0);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " speed : ");
strcat(s, config.floppy.speed ? "fast " : "normal");
OsdWrite(2, s, menusub == 1,0);
OsdWrite(3, "", 0,0);
strcpy(s, " A600 IDE : ");
strcat(s, config.enable_ide ? "on " : "off");
OsdWrite(4, s, menusub == 2,0);
sprintf(s, " hardfiles : %d", (config.hardfile[0].present & config.hardfile[0].enabled) + (config.hardfile[1].present & config.hardfile[1].enabled));
OsdWrite(5,s, menusub == 3,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 4,0);
menustate = MENU_SETTINGS_DRIVES2;
break;
case MENU_SETTINGS_DRIVES2 :
if (down && menusub < 4)
{
menusub++;
menustate = MENU_SETTINGS_DRIVES1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS_DRIVES1;
}
if (select)
{
if (menusub == 0)
{
config.floppy.drives++;
config.floppy.drives &= 0x03;
menustate = MENU_SETTINGS_DRIVES1;
ConfigFloppy(config.floppy.drives, config.floppy.speed);
}
else if (menusub == 1)
{
config.floppy.speed++;
config.floppy.speed &= 0x01;
menustate = MENU_SETTINGS_DRIVES1;
ConfigFloppy(config.floppy.drives, config.floppy.speed);
}
else if (menusub == 2)
{
config.enable_ide ^= 0x01;
menustate = MENU_SETTINGS_DRIVES1;
ConfigIDE(config.enable_ide, config.hardfile[0].present && config.hardfile[0].enabled, config.hardfile[1].present && config.hardfile[1].enabled);
}
else if (menusub == 3)
{
t_hardfile[0] = config.hardfile[0];
t_hardfile[1] = config.hardfile[1];
menustate = MENU_SETTINGS_HARDFILE1;
menusub = 4;
}
else if (menusub == 4)
{
menustate = MENU_SETTINGS1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_SETTINGS1;
menusub = 2;
}
else if (right)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
break;
*/
/******************************************************************/
/* hardfile settings menu */
/******************************************************************/
// FIXME! Nasty race condition here. Changing HDF type has immediate effect
// which could be disastrous if the user's writing to the drive at the time!
// Make the menu work on the copy, not the original, and copy on acceptance,
// not on rejection.
case MENU_SETTINGS_HARDFILE1 :
helptext=helptexts[HELPTEXT_HARDFILE];
OsdSetTitle("Harddisks",0);
parentstate = menustate;
menumask=0x21; // b00100001 - On/off & exit enabled by default...
if(config.enable_ide)
menumask|=0x0a; // b00001010 - HD0 and HD1 type
strcpy(s, " A600 IDE : ");
strcat(s, config.enable_ide ? "on " : "off");
OsdWrite(0, s, menusub == 0,0);
OsdWrite(1, "", 0,0);
strcpy(s, " Master : ");
if(config.hardfile[0].enabled==(HDF_FILE|HDF_SYNTHRDB))
strcat(s,"Hardfile (filesys)");
else
strcat(s, config_hdf_msg[config.hardfile[0].enabled & HDF_TYPEMASK]);
OsdWrite(2, s, config.enable_ide ? (menusub == 1) : 0 ,config.enable_ide==0);
if (config.hardfile[0].present)
{
strcpy(s, " ");
if (config.hardfile[0].long_name[0])
strncpy(&s[14], config.hardfile[0].long_name, sizeof(config.hardfile[0].long_name));
else
strncpy(&s[14], config.hardfile[0].name, sizeof(config.hardfile[0].name));
}
else
strcpy(s, " ** file not found **");
enable=config.enable_ide && ((config.hardfile[0].enabled&HDF_TYPEMASK)==HDF_FILE);
if(enable)
menumask|=0x04; // Make hardfile selectable
OsdWrite(3, s, enable ? (menusub == 2) : 0 , enable==0);
strcpy(s, " Slave : ");
if(config.hardfile[1].enabled==(HDF_FILE|HDF_SYNTHRDB))
strcat(s,"Hardfile (filesys)");
else
strcat(s, config_hdf_msg[config.hardfile[1].enabled & HDF_TYPEMASK]);
OsdWrite(4, s, config.enable_ide ? (menusub == 3) : 0 ,config.enable_ide==0);
if (config.hardfile[1].present)
{
strcpy(s, " ");
if (config.hardfile[1].long_name[0])
strncpy(&s[14], config.hardfile[1].long_name, sizeof(config.hardfile[0].long_name));
else
strncpy(&s[14], config.hardfile[1].name, sizeof(config.hardfile[0].name));
}
else
strcpy(s, " ** file not found **");
enable=config.enable_ide && ((config.hardfile[1].enabled&HDF_TYPEMASK)==HDF_FILE);
if(enable)
menumask|=0x10; // Make hardfile selectable
OsdWrite(5, s, enable ? (menusub == 4) : 0 ,enable==0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SETTINGS_HARDFILE2;
break;
case MENU_SETTINGS_HARDFILE2 :
if (select)
{
if (menusub == 0)
{
config.enable_ide=(config.enable_ide==0);
menustate = MENU_SETTINGS_HARDFILE1;
}
if (menusub == 1)
{
if(config.hardfile[0].enabled==HDF_FILE)
{
config.hardfile[0].enabled|=HDF_SYNTHRDB;
}
else if(config.hardfile[0].enabled==(HDF_FILE|HDF_SYNTHRDB))
{
config.hardfile[0].enabled&=~HDF_SYNTHRDB;
config.hardfile[0].enabled +=1;
}
else
{
config.hardfile[0].enabled +=1;
config.hardfile[0].enabled %=HDF_CARDPART0+partitioncount;
}
menustate = MENU_SETTINGS_HARDFILE1;
}
else if (menusub == 2)
{
SelectFile("HDF", SCAN_LFN, MENU_HARDFILE_SELECTED, MENU_SETTINGS_HARDFILE1);
}
else if (menusub == 3)
{
if(config.hardfile[1].enabled==HDF_FILE)
{
config.hardfile[1].enabled|=HDF_SYNTHRDB;
}
else if(config.hardfile[1].enabled==(HDF_FILE|HDF_SYNTHRDB))
{
config.hardfile[1].enabled&=~HDF_SYNTHRDB;
config.hardfile[1].enabled +=1;
}
else
{
config.hardfile[1].enabled +=1;
config.hardfile[1].enabled %=HDF_CARDPART0+partitioncount;
}
menustate = MENU_SETTINGS_HARDFILE1;
}
else if (menusub == 4)
{
SelectFile("HDF", SCAN_LFN, MENU_HARDFILE_SELECTED, MENU_SETTINGS_HARDFILE1);
}
else if (menusub == 5) // return to previous menu
{
menustate = MENU_HARDFILE_EXIT;
}
}
if (menu) // return to previous menu
{
menustate = MENU_HARDFILE_EXIT;
}
break;
/******************************************************************/
/* hardfile selected menu */
/******************************************************************/
case MENU_HARDFILE_SELECTED :
if (menusub == 2) // master drive selected
{
// Read RDB from selected drive and determine type...
memcpy((void*)config.hardfile[0].name, (void*)file.name, sizeof(config.hardfile[0].name));
memcpy((void*)config.hardfile[0].long_name, (void*)file.long_name, sizeof(config.hardfile[0].long_name));
switch(GetHDFFileType(file.name))
{
case HDF_FILETYPE_RDB:
config.hardfile[0].enabled=HDF_FILE;
config.hardfile[0].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_DOS:
config.hardfile[0].enabled=HDF_FILE|HDF_SYNTHRDB;
config.hardfile[0].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_UNKNOWN:
config.hardfile[0].present = 1;
if(config.hardfile[0].enabled==HDF_FILE) // Warn if we can't detect the type
menustate=MENU_SYNTHRDB1;
else
menustate=MENU_SYNTHRDB2_1;
menusub=0;
break;
case HDF_FILETYPE_NOTFOUND:
default:
config.hardfile[0].present = 0;
menustate = MENU_SETTINGS_HARDFILE1;
break;
}
}
if (menusub == 4) // slave drive selected
{
memcpy((void*)config.hardfile[1].name, (void*)file.name, sizeof(config.hardfile[1].name));
memcpy((void*)config.hardfile[1].long_name, (void*)file.long_name, sizeof(config.hardfile[1].long_name));
switch(GetHDFFileType(file.name))
{
case HDF_FILETYPE_RDB:
config.hardfile[1].enabled=HDF_FILE;
config.hardfile[1].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_DOS:
config.hardfile[1].enabled=HDF_FILE|HDF_SYNTHRDB;
config.hardfile[1].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_UNKNOWN:
config.hardfile[1].present = 1;
if(config.hardfile[1].enabled==HDF_FILE) // Warn if we can't detect the type...
menustate=MENU_SYNTHRDB1;
else
menustate=MENU_SYNTHRDB2_1;
menusub=0;
break;
case HDF_FILETYPE_NOTFOUND:
default:
config.hardfile[1].present = 0;
menustate = MENU_SETTINGS_HARDFILE1;
break;
}
}
break;
// check if hardfile configuration has changed
case MENU_HARDFILE_EXIT :
if (memcmp(config.hardfile, t_hardfile, sizeof(t_hardfile)) != 0)
{
menustate = MENU_HARDFILE_CHANGED1;
menusub = 1;
}
else
{
menustate = MENU_MAIN1;
menusub = 5;
}
break;
// hardfile configuration has changed, ask user if he wants to use the new settings
case MENU_HARDFILE_CHANGED1 :
menumask=0x03;
parentstate=menustate;
OsdSetTitle("Confirm",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Changing configuration", 0,0);
OsdWrite(2, " requires reset.", 0,0);
OsdWrite(3, "", 0,0);
OsdWrite(4, " Reset Minimig?", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, " yes", menusub == 0,0);
OsdWrite(7, " no", menusub == 1,0);
menustate = MENU_HARDFILE_CHANGED2;
break;
case MENU_HARDFILE_CHANGED2 :
if (select)
{
if (menusub == 0) // yes
{
// FIXME - waiting for user-confirmation increases the window of opportunity for file corruption!
if ((config.hardfile[0].enabled != t_hardfile[0].enabled)
|| (strncmp(config.hardfile[0].name, t_hardfile[0].name, sizeof(t_hardfile[0].name)) != 0))
{
OpenHardfile(0);
// if((config.hardfile[0].enabled == HDF_FILE) && !FindRDB(0))
// menustate = MENU_SYNTHRDB1;
}
if (config.hardfile[1].enabled != t_hardfile[1].enabled
|| (strncmp(config.hardfile[1].name, t_hardfile[1].name, sizeof(t_hardfile[1].name)) != 0))
{
OpenHardfile(1);
// if((config.hardfile[1].enabled == HDF_FILE) && !FindRDB(1))
// menustate = MENU_SYNTHRDB2_1;
}
if(menustate==MENU_HARDFILE_CHANGED2)
{
ConfigIDE(config.enable_ide, config.hardfile[0].present && config.hardfile[0].enabled, config.hardfile[1].present && config.hardfile[1].enabled);
OsdReset(RESET_NORMAL);
menustate = MENU_NONE1;
}
}
else if (menusub == 1) // no
{
memcpy(config.hardfile, t_hardfile, sizeof(t_hardfile)); // restore configuration
menustate = MENU_MAIN1;
menusub = 3;
}
}
if (menu)
{
memcpy(config.hardfile, t_hardfile, sizeof(t_hardfile)); // restore configuration
menustate = MENU_MAIN1;
menusub = 3;
}
break;
case MENU_SYNTHRDB1 :
menumask=0x01;
parentstate=menustate;
OsdSetTitle("Warning",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " No partition table found -", 0,0);
OsdWrite(2, " Hardfile image may need", 0,0);
OsdWrite(3, " to be prepped with HDToolbox,", 0,0);
OsdWrite(4, " then formatted.", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, " OK", menusub == 0,0);
menustate = MENU_SYNTHRDB2;
break;
case MENU_SYNTHRDB2_1 :
menumask=0x01;
parentstate=menustate;
OsdSetTitle("Warning",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " No filesystem recognised.", 0,0);
OsdWrite(2, " Hardfile may need formatting", 0,0);
OsdWrite(3, " (or may simply be an", 0,0);
OsdWrite(4, " unrecognised filesystem)", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, " OK", menusub == 0,0);
menustate = MENU_SYNTHRDB2;
break;
case MENU_SYNTHRDB2 :
if (select || menu)
{
if (menusub == 0) // OK
menustate = MENU_SETTINGS_HARDFILE1;
}
break;
/******************************************************************/
/* video settings menu */
/******************************************************************/
case MENU_SETTINGS_VIDEO1 :
menumask=0x0f;
parentstate=menustate;
helptext=helptexts[HELPTEXT_VIDEO];
OsdSetTitle("Video",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " Lores Filter : ");
strcat(s, config_filter_msg[config.filter.lores & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " Hires Filter : ");
strcat(s, config_filter_msg[config.filter.hires & 0x03]);
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " Scanlines : ");
strcat(s, config_scanlines_msg[config.scanlines % 3]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
menustate = MENU_SETTINGS_VIDEO2;
break;
case MENU_SETTINGS_VIDEO2 :
if (select)
{
if (menusub == 0)
{
config.filter.lores++;
config.filter.lores &= 0x03;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigFilter(config.filter.lores, config.filter.hires);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 1)
{
config.filter.hires++;
config.filter.hires &= 0x03;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigFilter(config.filter.lores, config.filter.hires);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 2)
{
config.scanlines++;
if (config.scanlines > 2)
config.scanlines = 0;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigScanlines(config.scanlines);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 3)
{
menustate = MENU_MAIN2_1;
menusub = 4;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 4;
}
else if (right)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
break;
/******************************************************************/
/* rom file selected menu */
/******************************************************************/
case MENU_ROMFILE_SELECTED :
menusub = 1;
menustate=MENU_ROMFILE_SELECTED1;
// no break intended
case MENU_ROMFILE_SELECTED1 :
menumask=0x03;
parentstate=menustate;
OsdSetTitle("Confirm",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Reload Kickstart?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_ROMFILE_SELECTED2;
break;
case MENU_ROMFILE_SELECTED2 :
if (select)
{
if (menusub == 0)
{
memcpy((void*)config.kickstart.name, (void*)file.name, sizeof(config.kickstart.name));
memcpy((void*)config.kickstart.long_name, (void*)file.long_name, sizeof(config.kickstart.long_name));
OsdDisable();
//OsdReset(RESET_BOOTLOADER);
//ConfigChipset(config.chipset | CONFIG_TURBO);
//ConfigFloppy(config.floppy.drives, CONFIG_FLOPPY2X);
EnableOsd();
SPI(OSD_CMD_RST);
rstval = (SPI_RST_CPU | SPI_CPU_HLT);
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
UploadKickstart(config.kickstart.name);
EnableOsd();
SPI(OSD_CMD_RST);
rstval = (SPI_RST_USR | SPI_RST_CPU);
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
EnableOsd();
SPI(OSD_CMD_RST);
rstval = 0;
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
//ConfigChipset(config.chipset); // restore CPU speed mode
//ConfigFloppy(config.floppy.drives, config.floppy.speed); // restore floppy speed mode
menustate = MENU_NONE1;
}
else if (menusub == 1)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 2;
}
break;
// /******************************************************************/
// /* firmware menu */
// /******************************************************************/
// case MENU_FIRMWARE1 :
//
// OsdWrite(0, " *** Firmware ***", 0);
// OsdWrite(1, "", 0);
// sprintf(s, " ARM s/w ver. %s", version + 5);
// OsdWrite(2, s, 0);
// OsdWrite(3, "", 0);
// OsdWrite(4, " update", menusub == 0);
// OsdWrite(5, " options", menusub == 1);
// OsdWrite(6, "", 0);
// OsdWrite(7, " exit", menusub == 2);
//
// menustate = MENU_FIRMWARE2;
// break;
//
// case MENU_FIRMWARE2 :
//
// if (menu)
// {
// menusub = 2;
// menustate = MENU_MAIN2_1;
// }
// else if (up)
// {
// if (menusub > 0)
// menusub--;
// menustate = MENU_FIRMWARE1;
// }
// else if (down)
// {
// if (menusub < 2)
// menusub++;
// menustate = MENU_FIRMWARE1;
// }
// else if (select)
// {
// if (menusub == 0)
// {
//// if (CheckFirmware(&file, "FIRMWAREUPG"))
//// menustate = MENU_FIRMWARE_UPDATE1;
//// else
// menustate = MENU_FIRMWARE_UPDATE_ERROR1;
// menusub = 1;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE_OPTIONS1;
// menusub = 1;
// OsdClear();
// }
// else if (menusub == 2)
// {
// menustate = MENU_MAIN2_1;
// menusub = 2;
// }
// }
// break;
//
// /******************************************************************/
// /* firmware update message menu */
// /******************************************************************/
// case MENU_FIRMWARE_UPDATE1 :
//
// OsdWrite(2, " Are you sure?", 0);
//
// OsdWrite(6, " yes", menusub == 0);
// OsdWrite(7, " no", menusub == 1);
//
// menustate = MENU_FIRMWARE_UPDATE2;
// break;
//
// case MENU_FIRMWARE_UPDATE2 :
//
// if (down && menusub < 1)
// {
// menusub++;
// menustate = MENU_FIRMWARE_UPDATE1;
// }
//
// if (up && menusub > 0)
// {
// menusub--;
// menustate = MENU_FIRMWARE_UPDATE1;
// }
//
// if (select)
// {
// if (menusub == 0)
// {
// menustate = MENU_FIRMWARE_UPDATING1;
// menusub = 0;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE1;
// menusub = 2;
// }
// }
// break;
//
// /******************************************************************/
// /* firmware update in progress message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_UPDATING1 :
//
// OsdWrite(1, " Updating firmware", 0);
// OsdWrite(3, " Please wait", 0);
// menustate = MENU_FIRMWARE_UPDATING2;
// break;
//
// case MENU_FIRMWARE_UPDATING2 :
//
//// WriteFirmware(&file);
// Error = ERROR_UPDATE_FAILED;
// menustate = MENU_FIRMWARE_UPDATE_ERROR1;
// menusub = 0;
// OsdClear();
// break;
//
// /******************************************************************/
// /* firmware update error message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_UPDATE_ERROR1 :
//
// switch (Error)
// {
// case ERROR_FILE_NOT_FOUND :
// OsdWrite(1, " Update file", 0);
// OsdWrite(2, " not found!", 0);
// break;
// case ERROR_INVALID_DATA :
// OsdWrite(1, " Invalid ", 0);
// OsdWrite(2, " update file!", 0);
// break;
// case ERROR_UPDATE_FAILED :
// OsdWrite(2, " Update failed!", 0);
// break;
// }
// OsdWrite(7, " OK", 1);
// menustate = MENU_FIRMWARE_UPDATE_ERROR2;
// break;
//
// case MENU_FIRMWARE_UPDATE_ERROR2 :
//
// if (select)
// {
// menustate = MENU_FIRMWARE1;
// menusub = 2;
// }
// break;
//
// /******************************************************************/
// /* firmware options menu */
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS1 :
//
// OsdWrite(0, " ** Options **", 0);
//
//// if (GetSPIMode() == SPIMODE_FAST)
//// OsdWrite(2, " Fast SPI enabled", menusub == 0);
//// else
// OsdWrite(2, " Enable Fast SPI ", menusub == 0);
//
// OsdWrite(7, " exit", menusub == 1);
//
// menustate = MENU_FIRMWARE_OPTIONS2;
// break;
//
// case MENU_FIRMWARE_OPTIONS2 :
//
// if (c == KEY_F8)
// {
// if (DEBUG)
// {
// DEBUG = 0;
// printf("DEBUG OFF\r");
// }
// else
// {
// DEBUG = 1;
// printf("DEBUG ON\r");
// }
// }
// else if (menu)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE1;
// }
// else if (up)
// {
//// if (menusub > 0 && GetSPIMode() != SPIMODE_FAST)
// menusub--;
//
// menustate = MENU_FIRMWARE_OPTIONS1;
// }
// else if (down)
// {
// if (menusub < 1)
// menusub++;
// menustate = MENU_FIRMWARE_OPTIONS1;
// }
// else if (select)
// {
// if (menusub == 0)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE1;
// }
// }
// break;
//
// /******************************************************************/
// /* SPI high speed mode enable message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS_ENABLE1 :
//
// OsdWrite(0, " Enabling fast SPI without", 0);
// OsdWrite(1, " hardware modification", 0);
// OsdWrite(2, " will be fatal!", 0);
// OsdWrite(4, " Enable?", 0);
// OsdWrite(6, " yes", menusub == 0);
// OsdWrite(7, " no", menusub == 1);
//
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE2;
// break;
//
// case MENU_FIRMWARE_OPTIONS_ENABLE2 :
//
// if (down && menusub < 1)
// {
// menusub++;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// }
//
// if (up && menusub > 0)
// {
// menusub--;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// }
//
// if (select)
// {
// if (menusub == 0)
// {
//// SetSPIMode(SPIMODE_FAST);
// menustate = MENU_FIRMWARE_OPTIONS_ENABLED1;
// menusub = 0;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE_OPTIONS1;
// menusub = 0;
// OsdClear();
// }
// }
// break;
//
// /******************************************************************/
// /* SPI high speed mode enabled message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS_ENABLED1 :
//
// OsdWrite(1, " Fast SPI mode will be", 0);
// OsdWrite(2, " activated after restart.", 0);
// OsdWrite(3, " Hold MENU button while", 0);
// OsdWrite(4, " powering-on to disable it.", 0);
//
// OsdWrite(7, " OK", menusub == 0);
//
// menustate = MENU_FIRMWARE_OPTIONS_ENABLED2;
// break;
//
// case MENU_FIRMWARE_OPTIONS_ENABLED2 :
//
// if (select)
// {
// menustate = MENU_NONE1;
// menusub = 0;
// OsdClear();
// }
// break;
/******************************************************************/
/* error message menu */
/******************************************************************/
case MENU_ERROR :
if (menu)
menustate = MENU_MAIN1;
break;
/******************************************************************/
/* popup info menu */
/******************************************************************/
case MENU_INFO :
if (menu)
menustate = MENU_MAIN1;
else if (CheckTimer(menu_timer))
menustate = MENU_NONE1;
break;
/******************************************************************/
/* we should never come here */
/******************************************************************/
default :
break;
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
void ScrollLongName(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
// this function is called periodically when file selection window is displayed
// it checks if predefined period of time has elapsed and scrolls the name if necessary
char k = sort_table[iSelectedEntry];
static int len;
int max_len;
if (DirEntryLFN[k][0]) // && CheckTimer(scroll_timer)) // scroll if long name and timer delay elapsed
{
// FIXME - yuk, we don't want to do this every frame!
len = strlen(DirEntryLFN[k]); // get name length
if (len > 4)
if (DirEntryLFN[k][len - 4] == '.')
len -= 4; // remove extension
max_len = 30; // number of file name characters to display (one more required for scrolling)
if (DirEntry[k].Attributes & ATTR_DIRECTORY)
max_len = 25; // number of directory name characters to display
ScrollText(iSelectedEntry,DirEntryLFN[k],len,max_len,1);
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
char* GetDiskInfo(char* lfn, long len)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
// extracts disk number substring form file name
// if file name contains "X of Y" substring where X and Y are one or two digit number
// then the number substrings are extracted and put into the temporary buffer for further processing
// comparision is case sensitive
short i, k;
static char info[] = "XX/XX"; // temporary buffer
static char template[4] = " of "; // template substring to search for
char *ptr1, *ptr2, c;
unsigned char cmp;
if (len > 20) // scan only names which can't be fully displayed
{
for (i = (unsigned short)len - 1 - sizeof(template); i > 0; i--) // scan through the file name starting from its end
{
ptr1 = &lfn[i]; // current start position
ptr2 = template;
cmp = 0;
for (k = 0; (unsigned int)k < sizeof(template); k++) // scan through template
{
cmp |= *ptr1++ ^ *ptr2++; // compare substrings' characters one by one
if (cmp)
break; // stop further comparing if difference already found
}
if (!cmp) // match found
{
k = i - 1; // no need to check if k is valid since i is greater than zero
c = lfn[k]; // get the first character to the left of the matched template substring
if (c >= '0' && c <= '9') // check if a digit
{
info[1] = c; // copy to buffer
info[0] = ' '; // clear previous character
k--; // go to the preceding character
if (k >= 0) // check if index is valid
{
c = lfn[k];
if (c >= '0' && c <= '9') // check if a digit
info[0] = c; // copy to buffer
}
k = i + sizeof(template); // get first character to the right of the mached template substring
c = lfn[k]; // no need to check if index is valid
if (c >= '0' && c <= '9') // check if a digit
{
info[3] = c; // copy to buffer
info[4] = ' '; // clear next char
k++; // go to the followwing character
if (k < len) // check if index is valid
{
c = lfn[k];
if (c >= '0' && c <= '9') // check if a digit
info[4] = c; // copy to buffer
}
return info;
}
}
}
}
}
return NULL;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
// print directory contents
void PrintDirectory(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
unsigned char i;
unsigned char k;
unsigned long len;
char *lfn;
char *info;
char *p;
unsigned char j;
s[32] = 0; // set temporary string length to OSD line length
ScrollReset();
for (i = 0; i < 8; i++)
{
memset(s, ' ', 32); // clear line buffer
if (i < nDirEntries)
{
k = sort_table[i]; // ordered index in storage buffer
lfn = DirEntryLFN[k]; // long file name pointer
DirEntryInfo[i][0] = 0; // clear disk number info buffer
if (lfn[0]) // item has long name
{
len = strlen(lfn); // get name length
info = NULL; // no disk info
if (!(DirEntry[k].Attributes & ATTR_DIRECTORY)) // if a file
{
if (len > 4)
if (lfn[len-4] == '.')
len -= 4; // remove extension
info = GetDiskInfo(lfn, len); // extract disk number info
if (info != NULL)
memcpy(DirEntryInfo[i], info, 5); // copy disk number info if present
}
if (len > 30)
len = 30; // trim display length if longer than 30 characters
if (i != iSelectedEntry && info != NULL)
{ // display disk number info for not selected items
strncpy(s + 1, lfn, 30-6); // trimmed name
strncpy(s + 1+30-5, info, 5); // disk number
}
else
strncpy(s + 1, lfn, len); // display only name
}
else // no LFN
{
strncpy(s + 1, (const char*)DirEntry[k].Name, 8); // if no LFN then display base name (8 chars)
if (DirEntry[k].Attributes & ATTR_DIRECTORY && DirEntry[k].Extension[0] != ' ')
{
p = (char*)&DirEntry[k].Name[7];
j = 8;
do
{
if (*p-- != ' ')
break;
} while (--j);
s[1 + j++] = '.';
strncpy(s + 1 + j, (const char*)DirEntry[k].Extension, 3); // if no LFN then display base name (8 chars)
}
}
if (DirEntry[k].Attributes & ATTR_DIRECTORY) // mark directory with suffix
strcpy(&s[22], " <DIR>");
}
else
{
if (i == 0 && nDirEntries == 0) // selected directory is empty
strcpy(s, " No files!");
}
OsdWrite(i, s, i == iSelectedEntry,0); // display formatted line text
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void _strncpy(char* pStr1, const char* pStr2, size_t nCount)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
// customized strncpy() function to fill remaing destination string part with spaces
while (*pStr2 && nCount)
{
*pStr1++ = *pStr2++; // copy strings
nCount--;
}
while (nCount--)
*pStr1++ = ' '; // fill remaining space with spaces
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
// insert floppy image pointed to to by global <file> into <drive>
void InsertFloppy(adfTYPE *drive)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
unsigned char i, j;
unsigned long tracks;
// calculate number of tracks in the ADF image file
tracks = file.size / (512*11);
if (tracks > MAX_TRACKS)
{
printf("UNSUPPORTED ADF SIZE!!! Too many tracks: %lu\r", tracks);
tracks = MAX_TRACKS;
}
drive->tracks = (unsigned char)tracks;
// fill index cache
for (i = 0; i < tracks; i++) // for every track get its start position within image file
{
drive->cache[i] = file.cluster; // start of the track within image file
for (j = 0; j < 11; j++)
FileNextSector(&file); // advance by track length (11 sectors)
}
// copy image file name into drive struct
if (file.long_name[0]) // file has long name
_strncpy(drive->name, file.long_name, sizeof(drive->name)); // copy long name
else
{
strncpy(drive->name, file.name, 8); // copy base name
memset(&drive->name[8], ' ', sizeof(drive->name) - 8); // fill the rest of the name with spaces
}
if (DiskInfo[0]) // if selected file has valid disk number info then copy it to its name in drive struct
{
drive->name[16] = ' '; // precede disk number info with space character
strncpy(&drive->name[17], DiskInfo, sizeof(DiskInfo)); // copy disk number info
}
// initialize the rest of drive struct
drive->status = DSK_INSERTED;
if (!(file.attributes & ATTR_READONLY)) // read-only attribute
drive->status |= DSK_WRITABLE;
drive->cluster_offset = drive->cache[0];
drive->sector_offset = 0;
drive->track = 0;
drive->track_prev = -1;
// some debug info
if (file.long_name[0])
printf("Inserting floppy: \"%s\"\r", file.long_name);
else
printf("Inserting floppy: \"%.11s\"\r", file.name);
printf("file attributes: 0x%02X\r", file.attributes);
printf("file size: %lu (%lu KB)\r", file.size, file.size >> 10);
printf("drive tracks: %u\r", drive->tracks);
printf("drive status: 0x%02X\r", drive->status);
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
/* Error Message */
void ErrorMessage(const char *message, unsigned char code)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
if (menustate == MENU_NONE2)
menustate = MENU_ERROR;
if (menustate == MENU_ERROR)
{
// OsdClear();
OsdSetTitle("Error",0);
OsdWrite(0, " *** ERROR ***", 1,0);
OsdWrite(1, "", 0,0);
strncpy(s, message, 32);
s[32] = 0;
OsdWrite(2, s, 0,0);
s[0] = 0;
if (code)
sprintf(s, " #%d", code);
OsdWrite(3, "", 0,0);
OsdWrite(4, s, 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
OsdEnable(0); // do not disable KEYBOARD
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void InfoMessage(char *message)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
OsdWaitVBL();
if (menustate != MENU_INFO)
{
// OsdClear();
OsdSetTitle("Message",0);
OsdEnable(0); // do not disable keyboard
}
OsdWrite(0, "", 0,0);
OsdWrite(1, message, 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, "", 0,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menu_timer = GetTimer(1000);
menustate = MENU_INFO;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void DebugMessage(char *message)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
strncpy(&debuglines[debugptr*32],message,31);
debuglines[debugptr*32+31]=0;
debugptr=(debugptr+1)&7;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
| Java |
<?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',
];
| Java |
/*
* This file is part of Cleanflight.
*
* Cleanflight is free software. You can redistribute
* this software and/or modify this software 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.
*
* Cleanflight 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 software.
*
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdint.h>
#include <math.h>
#include "platform.h"
#if defined(USE_MAG_AK8963) || defined(USE_MAG_SPI_AK8963)
#include "build/debug.h"
#include "common/axis.h"
#include "common/maths.h"
#include "common/utils.h"
#include "drivers/bus.h"
#include "drivers/bus_i2c.h"
#include "drivers/bus_i2c_busdev.h"
#include "drivers/bus_spi.h"
#include "drivers/io.h"
#include "drivers/sensor.h"
#include "drivers/time.h"
#include "drivers/compass/compass.h"
#include "drivers/accgyro/accgyro.h"
#include "drivers/accgyro/accgyro_mpu.h"
#include "drivers/accgyro/accgyro_mpu6500.h"
#include "drivers/accgyro/accgyro_spi_mpu6500.h"
#include "drivers/accgyro/accgyro_spi_mpu9250.h"
#include "drivers/compass/compass_ak8963.h"
#include "scheduler/scheduler.h"
// This sensor is also available also part of the MPU-9250 connected to the secondary I2C bus.
// AK8963, mag sensor address
#define AK8963_MAG_I2C_ADDRESS 0x0C
#define AK8963_DEVICE_ID 0x48
// Registers
#define AK8963_MAG_REG_WIA 0x00
#define AK8963_MAG_REG_INFO 0x01
#define AK8963_MAG_REG_ST1 0x02
#define AK8963_MAG_REG_HXL 0x03
#define AK8963_MAG_REG_HXH 0x04
#define AK8963_MAG_REG_HYL 0x05
#define AK8963_MAG_REG_HYH 0x06
#define AK8963_MAG_REG_HZL 0x07
#define AK8963_MAG_REG_HZH 0x08
#define AK8963_MAG_REG_ST2 0x09
#define AK8963_MAG_REG_CNTL1 0x0A
#define AK8963_MAG_REG_CNTL2 0x0B
#define AK8963_MAG_REG_ASCT 0x0C // self test
#define AK8963_MAG_REG_I2CDIS 0x0F
#define AK8963_MAG_REG_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value
#define AK8963_MAG_REG_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value
#define AK8963_MAG_REG_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value
#define READ_FLAG 0x80
#define I2C_SLV0_EN 0x80
#define ST1_DATA_READY 0x01
#define ST1_DATA_OVERRUN 0x02
#define ST2_MAG_SENSOR_OVERFLOW 0x08
#define CNTL1_MODE_POWER_DOWN 0x00
#define CNTL1_MODE_ONCE 0x01
#define CNTL1_MODE_CONT1 0x02
#define CNTL1_MODE_CONT2 0x06
#define CNTL1_MODE_SELF_TEST 0x08
#define CNTL1_MODE_FUSE_ROM 0x0F
#define CNTL1_BIT_14_BIT 0x00
#define CNTL1_BIT_16_BIT 0x10
#define CNTL2_SOFT_RESET 0x01
#define I2CDIS_DISABLE_MASK 0x1D
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
static bool ak8963SpiWriteRegisterDelay(const busDevice_t *bus, uint8_t reg, uint8_t data)
{
spiBusWriteRegister(bus, reg, data);
delayMicroseconds(10);
return true;
}
static bool ak8963SlaveReadRegisterBuffer(const busDevice_t *slavedev, uint8_t reg, uint8_t *buf, uint8_t len)
{
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address | READ_FLAG); // set I2C slave address for read
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (len & 0x0F) | I2C_SLV0_EN); // read number of bytes
delay(4);
__disable_irq();
bool ack = spiBusReadRegisterBuffer(bus, MPU_RA_EXT_SENS_DATA_00, buf, len); // read I2C
__enable_irq();
return ack;
}
static bool ak8963SlaveWriteRegister(const busDevice_t *slavedev, uint8_t reg, uint8_t data)
{
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address); // set I2C slave address for write
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_DO, data); // set I2C sLave value
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (1 & 0x0F) | I2C_SLV0_EN); // write 1 byte
return true;
}
typedef struct queuedReadState_s {
bool waiting;
uint8_t len;
uint32_t readStartedAt; // time read was queued in micros.
} queuedReadState_t;
static queuedReadState_t queuedRead = { false, 0, 0};
static bool ak8963SlaveStartRead(const busDevice_t *slavedev, uint8_t reg, uint8_t len)
{
if (queuedRead.waiting) {
return false;
}
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
queuedRead.len = len;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address | READ_FLAG); // set I2C slave address for read
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (len & 0x0F) | I2C_SLV0_EN); // read number of bytes
queuedRead.readStartedAt = micros();
queuedRead.waiting = true;
return true;
}
static uint32_t ak8963SlaveQueuedReadTimeRemaining(void)
{
if (!queuedRead.waiting) {
return 0;
}
int32_t timeSinceStarted = micros() - queuedRead.readStartedAt;
int32_t timeRemaining = 8000 - timeSinceStarted;
if (timeRemaining < 0) {
return 0;
}
return timeRemaining;
}
static bool ak8963SlaveCompleteRead(const busDevice_t *slavedev, uint8_t *buf)
{
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
if (timeRemaining > 0) {
delayMicroseconds(timeRemaining);
}
queuedRead.waiting = false;
spiBusReadRegisterBuffer(bus, MPU_RA_EXT_SENS_DATA_00, buf, queuedRead.len); // read I2C buffer
return true;
}
static bool ak8963SlaveReadData(const busDevice_t *busdev, uint8_t *buf)
{
typedef enum {
CHECK_STATUS = 0,
WAITING_FOR_STATUS,
WAITING_FOR_DATA
} ak8963ReadState_e;
static ak8963ReadState_e state = CHECK_STATUS;
bool ack = false;
// we currently need a different approach for the MPU9250 connected via SPI.
// we cannot use the ak8963SlaveReadRegisterBuffer() method for SPI, it is to slow and blocks for far too long.
bool retry = true;
restart:
switch (state) {
case CHECK_STATUS: {
ak8963SlaveStartRead(busdev, AK8963_MAG_REG_ST1, 1);
state = WAITING_FOR_STATUS;
return false;
}
case WAITING_FOR_STATUS: {
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
if (timeRemaining) {
return false;
}
ack = ak8963SlaveCompleteRead(busdev, &buf[0]);
uint8_t status = buf[0];
if (!ack || (status & ST1_DATA_READY) == 0) {
// too early. queue the status read again
state = CHECK_STATUS;
if (retry) {
retry = false;
goto restart;
}
return false;
}
// read the 6 bytes of data and the status2 register
ak8963SlaveStartRead(busdev, AK8963_MAG_REG_HXL, 7);
state = WAITING_FOR_DATA;
return false;
}
case WAITING_FOR_DATA: {
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
if (timeRemaining) {
return false;
}
ack = ak8963SlaveCompleteRead(busdev, &buf[0]);
state = CHECK_STATUS;
}
}
return ack;
}
#endif
static bool ak8963ReadRegisterBuffer(const busDevice_t *busdev, uint8_t reg, uint8_t *buf, uint8_t len)
{
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
if (busdev->bustype == BUSTYPE_MPU_SLAVE) {
return ak8963SlaveReadRegisterBuffer(busdev, reg, buf, len);
}
#endif
return busReadRegisterBuffer(busdev, reg, buf, len);
}
static bool ak8963WriteRegister(const busDevice_t *busdev, uint8_t reg, uint8_t data)
{
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
if (busdev->bustype == BUSTYPE_MPU_SLAVE) {
return ak8963SlaveWriteRegister(busdev, reg, data);
}
#endif
return busWriteRegister(busdev, reg, data);
}
static bool ak8963DirectReadData(const busDevice_t *busdev, uint8_t *buf)
{
uint8_t status;
bool ack = ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST1, &status, 1);
if (!ack || (status & ST1_DATA_READY) == 0) {
return false;
}
return ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_HXL, buf, 7);
}
static int16_t parseMag(uint8_t *raw, int16_t gain) {
int ret = (int16_t)(raw[1] << 8 | raw[0]) * gain / 256;
return constrain(ret, INT16_MIN, INT16_MAX);
}
static bool ak8963Read(magDev_t *mag, int16_t *magData)
{
bool ack = false;
uint8_t buf[7];
const busDevice_t *busdev = &mag->busdev;
switch (busdev->bustype) {
#if defined(USE_MAG_SPI_AK8963) || defined(USE_MAG_AK8963)
case BUSTYPE_I2C:
case BUSTYPE_SPI:
ack = ak8963DirectReadData(busdev, buf);
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
ack = ak8963SlaveReadData(busdev, buf);
break;
#endif
default:
break;
}
uint8_t status2 = buf[6];
if (!ack) {
return false;
}
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_BIT_16_BIT | CNTL1_MODE_ONCE); // start reading again uint8_t status2 = buf[6];
if (status2 & ST2_MAG_SENSOR_OVERFLOW) {
return false;
}
magData[X] = parseMag(buf + 0, mag->magGain[X]);
magData[Y] = parseMag(buf + 2, mag->magGain[Y]);
magData[Z] = parseMag(buf + 4, mag->magGain[Z]);
return true;
}
static bool ak8963Init(magDev_t *mag)
{
uint8_t asa[3];
uint8_t status;
const busDevice_t *busdev = &mag->busdev;
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_POWER_DOWN); // power down before entering fuse mode
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_FUSE_ROM); // Enter Fuse ROM access mode
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ASAX, asa, sizeof(asa)); // Read the x-, y-, and z-axis calibration values
mag->magGain[X] = asa[X] + 128;
mag->magGain[Y] = asa[Y] + 128;
mag->magGain[Z] = asa[Z] + 128;
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_POWER_DOWN); // power down after reading.
// Clear status registers
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST1, &status, 1);
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST2, &status, 1);
// Trigger first measurement
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_BIT_16_BIT | CNTL1_MODE_ONCE);
return true;
}
void ak8963BusInit(busDevice_t *busdev)
{
switch (busdev->bustype) {
#ifdef USE_MAG_AK8963
case BUSTYPE_I2C:
UNUSED(busdev);
break;
#endif
#ifdef USE_MAG_SPI_AK8963
case BUSTYPE_SPI:
IOHi(busdev->busdev_u.spi.csnPin); // Disable
IOInit(busdev->busdev_u.spi.csnPin, OWNER_COMPASS_CS, 0);
IOConfigGPIO(busdev->busdev_u.spi.csnPin, IOCFG_OUT_PP);
#ifdef USE_SPI_TRANSACTION
spiBusTransactionInit(busdev, SPI_MODE3_POL_HIGH_EDGE_2ND, SPI_CLOCK_STANDARD);
#else
spiBusSetDivisor(busdev, SPI_CLOCK_STANDARD);
#endif
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
rescheduleTask(TASK_COMPASS, TASK_PERIOD_HZ(40));
// initialze I2C master via SPI bus
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_INT_PIN_CFG, MPU6500_BIT_INT_ANYRD_2CLEAR | MPU6500_BIT_BYPASS_EN);
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_I2C_MST_CTRL, 0x0D); // I2C multi-master / 400kHz
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_USER_CTRL, 0x30); // I2C master mode, SPI mode only
break;
#endif
default:
break;
}
}
void ak8963BusDeInit(const busDevice_t *busdev)
{
switch (busdev->bustype) {
#ifdef USE_MAG_AK8963
case BUSTYPE_I2C:
UNUSED(busdev);
break;
#endif
#ifdef USE_MAG_SPI_AK8963
case BUSTYPE_SPI:
spiPreinitByIO(busdev->busdev_u.spi.csnPin);
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_INT_PIN_CFG, MPU6500_BIT_INT_ANYRD_2CLEAR);
break;
#endif
default:
break;
}
}
bool ak8963Detect(magDev_t *mag)
{
uint8_t sig = 0;
busDevice_t *busdev = &mag->busdev;
if ((busdev->bustype == BUSTYPE_I2C || busdev->bustype == BUSTYPE_MPU_SLAVE) && busdev->busdev_u.mpuSlave.address == 0) {
busdev->busdev_u.mpuSlave.address = AK8963_MAG_I2C_ADDRESS;
}
ak8963BusInit(busdev);
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL2, CNTL2_SOFT_RESET); // reset MAG
delay(4);
bool ack = ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_WIA, &sig, 1); // check for AK8963
if (ack && sig == AK8963_DEVICE_ID) // 0x48 / 01001000 / 'H'
{
mag->init = ak8963Init;
mag->read = ak8963Read;
return true;
}
ak8963BusDeInit(busdev);
return false;
}
#endif
| Java |
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* gimpuiconfigurer.c
* Copyright (C) 2009 Martin Nordholts <[email protected]>
*
* 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 "config.h"
#include <gtk/gtk.h>
#include "gui-types.h"
#include "core/gimp.h"
#include "core/gimpcontext.h"
#include "widgets/gimpdialogfactory.h"
#include "widgets/gimpdock.h"
#include "widgets/gimpdockcolumns.h"
#include "widgets/gimpdockcontainer.h"
#include "widgets/gimpdockwindow.h"
#include "widgets/gimptoolbox.h"
#include "display/gimpdisplay.h"
#include "display/gimpdisplayshell.h"
#include "display/gimpdisplayshell-appearance.h"
#include "display/gimpimagewindow.h"
#include "menus/menus.h"
#include "gimpuiconfigurer.h"
enum
{
PROP_0,
PROP_GIMP
};
struct _GimpUIConfigurerPrivate
{
Gimp *gimp;
};
static void gimp_ui_configurer_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec);
static void gimp_ui_configurer_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec);
static void gimp_ui_configurer_move_docks_to_columns (GimpUIConfigurer *ui_configurer,
GimpImageWindow *uber_image_window);
static void gimp_ui_configurer_move_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window,
GimpImageWindow *target_image_window);
static void gimp_ui_configurer_separate_docks (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window);
static void gimp_ui_configurer_move_docks_to_window (GimpUIConfigurer *ui_configurer,
GimpDockColumns *dock_columns,
GimpAlignmentType screen_side_destination);
static void gimp_ui_configurer_separate_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window);
static void gimp_ui_configurer_configure_for_single_window (GimpUIConfigurer *ui_configurer);
static void gimp_ui_configurer_configure_for_multi_window (GimpUIConfigurer *ui_configurer);
static GimpImageWindow * gimp_ui_configurer_get_uber_window (GimpUIConfigurer *ui_configurer);
G_DEFINE_TYPE (GimpUIConfigurer, gimp_ui_configurer, GIMP_TYPE_OBJECT)
#define parent_class gimp_ui_configurer_parent_class
static void
gimp_ui_configurer_class_init (GimpUIConfigurerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->set_property = gimp_ui_configurer_set_property;
object_class->get_property = gimp_ui_configurer_get_property;
g_object_class_install_property (object_class, PROP_GIMP,
g_param_spec_object ("gimp", NULL, NULL,
GIMP_TYPE_GIMP,
GIMP_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass,
sizeof (GimpUIConfigurerPrivate));
}
static void
gimp_ui_configurer_init (GimpUIConfigurer *ui_configurer)
{
ui_configurer->p = G_TYPE_INSTANCE_GET_PRIVATE (ui_configurer,
GIMP_TYPE_UI_CONFIGURER,
GimpUIConfigurerPrivate);
}
static void
gimp_ui_configurer_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
GimpUIConfigurer *ui_configurer = GIMP_UI_CONFIGURER (object);
switch (property_id)
{
case PROP_GIMP:
ui_configurer->p->gimp = g_value_get_object (value); /* don't ref */
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gimp_ui_configurer_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GimpUIConfigurer *ui_configurer = GIMP_UI_CONFIGURER (object);
switch (property_id)
{
case PROP_GIMP:
g_value_set_object (value, ui_configurer->p->gimp);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gimp_ui_configurer_get_window_center_pos (GtkWindow *window,
gint *out_x,
gint *out_y)
{
gint x, y, w, h;
gtk_window_get_position (window, &x, &y);
gtk_window_get_size (window, &w, &h);
if (out_x)
*out_x = x + w / 2;
if (out_y)
*out_y = y + h / 2;
}
/**
* gimp_ui_configurer_get_relative_window_pos:
* @window_a:
* @window_b:
*
* Returns: At what side @window_b is relative to @window_a. Either
* GIMP_ALIGN_LEFT or GIMP_ALIGN_RIGHT.
**/
static GimpAlignmentType
gimp_ui_configurer_get_relative_window_pos (GtkWindow *window_a,
GtkWindow *window_b)
{
gint a_x, b_x;
gimp_ui_configurer_get_window_center_pos (window_a, &a_x, NULL);
gimp_ui_configurer_get_window_center_pos (window_b, &b_x, NULL);
return b_x < a_x ? GIMP_ALIGN_LEFT : GIMP_ALIGN_RIGHT;
}
static void
gimp_ui_configurer_move_docks_to_columns (GimpUIConfigurer *ui_configurer,
GimpImageWindow *uber_image_window)
{
GList *dialogs = NULL;
GList *dialog_iter = NULL;
dialogs =
g_list_copy (gimp_dialog_factory_get_open_dialogs (gimp_dialog_factory_get_singleton ()));
for (dialog_iter = dialogs; dialog_iter; dialog_iter = dialog_iter->next)
{
GimpDockWindow *dock_window;
GimpDockContainer *dock_container;
GimpDockColumns *dock_columns;
GList *docks;
GList *dock_iter;
if (!GIMP_IS_DOCK_WINDOW (dialog_iter->data))
continue;
dock_window = GIMP_DOCK_WINDOW (dialog_iter->data);
/* If the dock window is on the left side of the image window,
* move the docks to the left side. If the dock window is on the
* right side, move the docks to the right side of the image
* window.
*/
if (gimp_ui_configurer_get_relative_window_pos (GTK_WINDOW (uber_image_window),
GTK_WINDOW (dock_window)) == GIMP_ALIGN_LEFT)
dock_columns = gimp_image_window_get_left_docks (uber_image_window);
else
dock_columns = gimp_image_window_get_right_docks (uber_image_window);
dock_container = GIMP_DOCK_CONTAINER (dock_window);
g_object_add_weak_pointer (G_OBJECT (dock_window),
(gpointer) &dock_window);
docks = gimp_dock_container_get_docks (dock_container);
for (dock_iter = docks; dock_iter; dock_iter = dock_iter->next)
{
GimpDock *dock = GIMP_DOCK (dock_iter->data);
/* Move the dock from the image window to the dock columns
* widget. Note that we need a ref while the dock is parentless
*/
g_object_ref (dock);
gimp_dock_window_remove_dock (dock_window, dock);
gimp_dock_columns_add_dock (dock_columns, dock, -1);
g_object_unref (dock);
}
g_list_free (docks);
if (dock_window)
g_object_remove_weak_pointer (G_OBJECT (dock_window),
(gpointer) &dock_window);
/* Kill the window if removing the dock didn't destroy it
* already. This will be the case for the toolbox dock window
*/
if (GTK_IS_WIDGET (dock_window))
{
guint docks_len;
docks = gimp_dock_container_get_docks (dock_container);
docks_len = g_list_length (docks);
if (docks_len == 0)
{
gimp_dialog_factory_remove_dialog (gimp_dialog_factory_get_singleton (),
GTK_WIDGET (dock_window));
gtk_widget_destroy (GTK_WIDGET (dock_window));
}
g_list_free (docks);
}
}
g_list_free (dialogs);
}
/**
* gimp_ui_configurer_move_shells:
* @ui_configurer:
* @source_image_window:
* @target_image_window:
*
* Move all display shells from one image window to the another.
**/
static void
gimp_ui_configurer_move_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window,
GimpImageWindow *target_image_window)
{
while (gimp_image_window_get_n_shells (source_image_window) > 0)
{
GimpDisplayShell *shell;
shell = gimp_image_window_get_shell (source_image_window, 0);
g_object_ref (shell);
gimp_image_window_remove_shell (source_image_window, shell);
gimp_image_window_add_shell (target_image_window, shell);
g_object_unref (shell);
}
}
/**
* gimp_ui_configurer_separate_docks:
* @ui_configurer:
* @image_window:
*
* Move out the docks from the image window.
**/
static void
gimp_ui_configurer_separate_docks (GimpUIConfigurer *ui_configurer,
GimpImageWindow *image_window)
{
GimpDockColumns *left_docks = NULL;
GimpDockColumns *right_docks = NULL;
left_docks = gimp_image_window_get_left_docks (image_window);
right_docks = gimp_image_window_get_right_docks (image_window);
gimp_ui_configurer_move_docks_to_window (ui_configurer, left_docks, GIMP_ALIGN_LEFT);
gimp_ui_configurer_move_docks_to_window (ui_configurer, right_docks, GIMP_ALIGN_RIGHT);
}
/**
* gimp_ui_configurer_move_docks_to_window:
* @dock_columns:
* @screen_side_destination: At what side of the screen the dock window
* should be put.
*
* Moves docks in @dock_columns into a new #GimpDockWindow and
* position it on the screen in a non-overlapping manner.
*/
static void
gimp_ui_configurer_move_docks_to_window (GimpUIConfigurer *ui_configurer,
GimpDockColumns *dock_columns,
GimpAlignmentType screen_side_destination)
{
GdkScreen *screen = gtk_widget_get_screen (GTK_WIDGET (dock_columns));
GList *docks = g_list_copy (gimp_dock_columns_get_docks (dock_columns));
GList *iter = NULL;
gboolean contains_toolbox = FALSE;
GtkWidget *dock_window = NULL;
GtkAllocation original_size = { 0, 0, 0, 0 };
/* Are there docks to move at all? */
if (! docks)
return;
/* Remember the size so we can set the new dock window to the same
* size
*/
gtk_widget_get_allocation (GTK_WIDGET (dock_columns), &original_size);
/* Do we need a toolbox window? */
for (iter = docks; iter; iter = iter->next)
{
GimpDock *dock = GIMP_DOCK (iter->data);
if (GIMP_IS_TOOLBOX (dock))
{
contains_toolbox = TRUE;
break;
}
}
/* Create a dock window to put the dock in. Checking for
* GIMP_IS_TOOLBOX() is kind of ugly but not a disaster. We need
* the dock window correctly configured if we create it for the
* toolbox
*/
dock_window =
gimp_dialog_factory_dialog_new (gimp_dialog_factory_get_singleton (),
screen,
NULL /*ui_manager*/,
(contains_toolbox ?
"gimp-toolbox-window" :
"gimp-dock-window"),
-1 /*view_size*/,
FALSE /*present*/);
for (iter = docks; iter; iter = iter->next)
{
GimpDock *dock = GIMP_DOCK (iter->data);
/* Move the dock to the window */
g_object_ref (dock);
gimp_dock_columns_remove_dock (dock_columns, dock);
gimp_dock_window_add_dock (GIMP_DOCK_WINDOW (dock_window), dock, -1);
g_object_unref (dock);
}
/* Position the window */
if (screen_side_destination == GIMP_ALIGN_LEFT)
gtk_window_parse_geometry (GTK_WINDOW (dock_window), "+0+0");
else if (screen_side_destination == GIMP_ALIGN_RIGHT)
gtk_window_parse_geometry (GTK_WINDOW (dock_window), "-0+0");
else
g_assert_not_reached ();
/* Try to keep the same size */
gtk_window_set_default_size (GTK_WINDOW (dock_window),
original_size.width,
original_size.height);
/* Don't forget to show the window */
gtk_widget_show (dock_window);
g_list_free (docks);
}
/**
* gimp_ui_configurer_separate_shells:
* @ui_configurer:
* @source_image_window:
*
* Create one image window per display shell and move it there.
**/
static void
gimp_ui_configurer_separate_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window)
{
/* The last display shell remains in its window */
while (gimp_image_window_get_n_shells (source_image_window) > 1)
{
GimpImageWindow *new_image_window;
GimpDisplayShell *shell;
/* Create a new image window */
new_image_window = gimp_image_window_new (ui_configurer->p->gimp,
NULL,
global_menu_factory,
gimp_dialog_factory_get_singleton ());
/* Move the shell there */
shell = gimp_image_window_get_shell (source_image_window, 1);
g_object_ref (shell);
gimp_image_window_remove_shell (source_image_window, shell);
gimp_image_window_add_shell (new_image_window, shell);
g_object_unref (shell);
/* FIXME: If we don't set a size request here the window will be
* too small. Get rid of this hack and fix it the proper way
*/
gtk_widget_set_size_request (GTK_WIDGET (new_image_window), 640, 480);
/* Show after we have added the shell */
gtk_widget_show (GTK_WIDGET (new_image_window));
}
}
/**
* gimp_ui_configurer_configure_for_single_window:
* @ui_configurer:
*
* Move docks and display shells into a single window.
**/
static void
gimp_ui_configurer_configure_for_single_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *iter = NULL;
GimpImageWindow *uber_image_window = NULL;
/* Get and setup the window to put everything in */
uber_image_window = gimp_ui_configurer_get_uber_window (ui_configurer);
/* Mve docks to the left and right side of the image window */
gimp_ui_configurer_move_docks_to_columns (ui_configurer,
uber_image_window);
/* Move image shells from other windows to the uber image window */
for (iter = windows; iter; iter = g_list_next (iter))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (iter->data);
/* Don't move stuff to itself */
if (image_window == uber_image_window)
continue;
/* Put the displays in the rest of the image windows into
* the uber image window
*/
gimp_ui_configurer_move_shells (ui_configurer,
image_window,
uber_image_window);
/* Destroy the window */
gimp_image_window_destroy (image_window);
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_configure_for_multi_window:
* @ui_configurer:
*
* Moves all display shells into their own image window.
**/
static void
gimp_ui_configurer_configure_for_multi_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *iter = NULL;
for (iter = windows; iter; iter = g_list_next (iter))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (iter->data);
gimp_ui_configurer_separate_docks (ui_configurer, image_window);
gimp_ui_configurer_separate_shells (ui_configurer, image_window);
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_get_uber_window:
* @ui_configurer:
*
* Returns: The window to be used as the main window for single-window
* mode.
**/
static GimpImageWindow *
gimp_ui_configurer_get_uber_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GimpDisplay *display = gimp_get_display_iter (gimp)->data;
GimpDisplayShell *shell = gimp_display_get_shell (display);
GimpImageWindow *image_window = gimp_display_shell_get_window (shell);
return image_window;
}
/**
* gimp_ui_configurer_update_appearance:
* @ui_configurer:
*
* Updates the appearance of all shells in all image windows, so they
* do whatever they deem neccessary to fit the new UI mode mode.
**/
static void
gimp_ui_configurer_update_appearance (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *list;
for (list = windows; list; list = g_list_next (list))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (list->data);
gint n_shells;
gint i;
n_shells = gimp_image_window_get_n_shells (image_window);
for (i = 0; i < n_shells; i++)
{
GimpDisplayShell *shell;
shell = gimp_image_window_get_shell (image_window, i);
gimp_display_shell_appearance_update (shell);
}
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_configure:
* @ui_configurer:
* @single_window_mode:
*
* Configure the UI.
**/
void
gimp_ui_configurer_configure (GimpUIConfigurer *ui_configurer,
gboolean single_window_mode)
{
if (single_window_mode)
gimp_ui_configurer_configure_for_single_window (ui_configurer);
else
gimp_ui_configurer_configure_for_multi_window (ui_configurer);
gimp_ui_configurer_update_appearance (ui_configurer);
}
| Java |
<?php
namespace AfriCC\Tests\EPP\DOM;
use AfriCC\EPP\DOM\DOMElement;
use DOMDocument;
use PHPUnit\Framework\TestCase;
class DOMElementTest extends TestCase
{
public function testHasChildNodes()
{
$dom = new DOMDocument('1.0', 'utf-8');
$parent = new DOMElement('foo');
$dom->appendChild($parent);
$this->assertFalse($parent->hasChildNodes());
$child = new DOMElement('bar');
$parent->appendChild($child);
$this->assertTrue($parent->hasChildNodes());
}
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template customize_stream<Ch, Traits, signed char, void></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp" title="Header <boost/property_tree/stream_translator.hpp>">
<link rel="prev" href="customiz_idm45507095445648.html" title="Struct template customize_stream<Ch, Traits, F, typename boost::enable_if< detail::is_inexact< F > >::type>">
<link rel="next" href="customiz_idm45507101050960.html" title="Struct template customize_stream<Ch, Traits, unsigned char, void>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="customiz_idm45507095445648.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="customiz_idm45507101050960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.property_tree.customiz_idm45507087332800"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template customize_stream<Ch, Traits, signed char, void></span></h2>
<p>boost::property_tree::customize_stream<Ch, Traits, signed char, void></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp" title="Header <boost/property_tree/stream_translator.hpp>">boost/property_tree/stream_translator.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Ch<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="customiz_idm45507087332800.html" title="Struct template customize_stream<Ch, Traits, signed char, void>">customize_stream</a><span class="special"><</span><span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span><span class="special">,</span> <span class="keyword">void</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// <a class="link" href="customiz_idm45507087332800.html#idm45507087329712-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="customiz_idm45507087332800.html#idm45507087329152-bb"><span class="identifier">insert</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="customiz_idm45507087332800.html#idm45507101053632-bb"><span class="identifier">extract</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm45555209708384"></a><h2>Description</h2>
<div class="refsect2">
<a name="idm45555209707968"></a><h3>
<a name="idm45507087329712-bb"></a><code class="computeroutput">customize_stream</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idm45507087329152-bb"></a><span class="identifier">insert</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> s<span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> e<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idm45507101053632-bb"></a><span class="identifier">extract</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> s<span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> <span class="special">&</span> e<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2008-2010 Marcin Kalicinski<br>Copyright © 2010-2013 Sebastian
Redl<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="customiz_idm45507095445648.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="customiz_idm45507101050960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
// 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;
}
}
| Java |
//-----------------------------------------------------------------------
//
// mod parser::atom TEST
//
//-----------------------------------------------------------------------
use super::Status;
use super::{parse_dot, parse_eof, parse_literal, parse_match, MatchRules};
#[test]
fn test_parse_literal_ok() {
let rules = rules!{};
let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules);
let (status_end, _) = parse_literal(status_init, "aaa").ok().unwrap();
assert!(status_end.pos.col == 3);
assert!(status_end.pos.n == 3);
assert!(status_end.pos.row == 0);
}
#[test]
fn test_parse_literal_ok2() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
let (status_end, _) = parse_literal(status_init, "abc").ok().unwrap();
assert_eq!(status_end.pos.col, 3);
assert_eq!(status_end.pos.n, 3);
assert_eq!(status_end.pos.row, 0);
}
#[test]
fn test_parse_literal_fail() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
assert!(parse_literal(status_init, "bbb").is_err());
}
#[test]
fn test_parse_literal_fail2() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
assert!(parse_literal(status_init, "abd").is_err());
}
#[test]
fn test_parse_literal_fail_short_text2parse() {
let rules = rules!{};
let status_init = Status::init("abcd", &rules);
assert!(parse_literal(status_init, "abcdefghij").is_err());
}
#[test]
fn test_parse_literal_with_new_line() {
let rules = rules!{};
let status_init = Status::init(
"aa
aaaaaaaaaaaaaa",
&rules,
);
let (status_end, _) = parse_literal(
status_init,
"aa
a",
).ok()
.unwrap();
assert!(status_end.pos.col == 1);
assert!(status_end.pos.row == 1);
}
#[test]
fn test_parse_dot() {
let rules = rules!{};
let status = Status::init("ab", &rules);
let (status, _) = parse_dot(status).ok().unwrap();
assert!(status.pos.col == 1);
assert!(status.pos.n == 1);
assert!(status.pos.row == 0);
let (status, _) = parse_dot(status).ok().unwrap();
assert!(status.pos.col == 2);
assert!(status.pos.n == 2);
assert!(status.pos.row == 0);
assert!(parse_dot(status).is_err());
}
#[test]
fn test_parse_match_ok() {
let rules = rules!{};
let status = Status::init("a f0ghi", &rules);
let match_rules = MatchRules::new().with_chars("54321ed_cba");
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 1);
assert_eq!(status.pos.n, 1);
assert_eq!(status.pos.row, 0);
let (status, _) = parse_dot(status).ok().unwrap();
let match_rules = MatchRules::new().with_bound_chars(vec![('f', 'g'), ('h', 'j')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 3);
assert_eq!(status.pos.n, 3);
assert_eq!(status.pos.row, 0);
assert!(parse_match(status, &match_rules).is_err());
}
#[test]
fn test_parse_match_err() {
let rules = rules!{};
let status = Status::init("a9", &rules);
let match_rules = MatchRules::new().with_chars("ed_cba");
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 1);
assert_eq!(status.pos.n, 1);
assert_eq!(status.pos.row, 0);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '8')]);
assert!(parse_match(status, &match_rules).is_err());
}
#[test]
fn test_parse_match_eof_ok() {
let rules = rules!{};
let status = Status::init("a", &rules);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert!(parse_eof(status).is_ok());
}
#[test]
fn test_parse_match_eof_error() {
let rules = rules!{};
let status = Status::init("ab", &rules);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert!(parse_eof(status).is_err());
}
| Java |
/*
* Copyright (C) 2006 by Martin J. Muench <[email protected]>
*
* Part of mpd - mobile phone dumper
*
* Some code stolen from btxml.c by Andreas Oberritter
*
*/
#include "wrap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Simple malloc() wrapper */
void *Malloc(size_t size) {
void *buffer;
buffer = malloc(size);
if(buffer == NULL) {
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
memset(buffer, 0, size);
return(buffer);
}
| Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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 <[email protected]>
* @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;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.