prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>extension_toolbar_model_factory.cc<|end_file_name|><|fim▁begin|><|fim▁hole|>// Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_toolbar_model_factory.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/profiles/profile.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_factory.h" #include "extensions/browser/extensions_browser_client.h" // static ExtensionToolbarModel* ExtensionToolbarModelFactory::GetForProfile( Profile* profile) { return static_cast<ExtensionToolbarModel*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static ExtensionToolbarModelFactory* ExtensionToolbarModelFactory::GetInstance() { return Singleton<ExtensionToolbarModelFactory>::get(); } ExtensionToolbarModelFactory::ExtensionToolbarModelFactory() : BrowserContextKeyedServiceFactory( "ExtensionToolbarModel", BrowserContextDependencyManager::GetInstance()) { DependsOn(extensions::ExtensionPrefsFactory::GetInstance()); } ExtensionToolbarModelFactory::~ExtensionToolbarModelFactory() {} BrowserContextKeyedService* ExtensionToolbarModelFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new ExtensionToolbarModel( Profile::FromBrowserContext(context), extensions::ExtensionPrefsFactory::GetForBrowserContext(context)); } content::BrowserContext* ExtensionToolbarModelFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return extensions::ExtensionsBrowserClient::Get()-> GetOriginalContext(context); } bool ExtensionToolbarModelFactory::ServiceIsCreatedWithBrowserContext() const { return true; } bool ExtensionToolbarModelFactory::ServiceIsNULLWhileTesting() const { return true; }<|fim▁end|>
// Copyright 2013 The Chromium Authors. All rights reserved.
<|file_name|>Uuid.cpp<|end_file_name|><|fim▁begin|>/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * * 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. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here.<|fim▁hole|> * 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 "PrecompiledHeaders.h" #include "Uuid.h" // http://stackoverflow.com/a/1626302 extern "C" { #ifdef WIN32 #include <rpc.h> #else #include <uuid/uuid.h> #endif } #include <boost/filesystem.hpp> namespace Orthanc { namespace Toolbox { std::string GenerateUuid() { #ifdef WIN32 UUID uuid; UuidCreate ( &uuid ); unsigned char * str; UuidToStringA ( &uuid, &str ); std::string s( ( char* ) str ); RpcStringFreeA ( &str ); #else uuid_t uuid; uuid_generate_random ( uuid ); char s[37]; uuid_unparse ( uuid, s ); #endif return s; } bool IsUuid(const std::string& str) { if (str.size() != 36) { return false; } for (size_t i = 0; i < str.length(); i++) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (str[i] != '-') return false; } else { if (!isalnum(str[i])) return false; } } return true; } bool StartsWithUuid(const std::string& str) { if (str.size() < 36) { return false; } if (str.size() == 36) { return IsUuid(str); } assert(str.size() > 36); if (!isspace(str[36])) { return false; } return IsUuid(str.substr(0, 36)); } static std::string CreateTemporaryPath(const char* extension) { #if BOOST_HAS_FILESYSTEM_V3 == 1 boost::filesystem::path tmpDir = boost::filesystem::temp_directory_path(); #elif defined(__linux__) boost::filesystem::path tmpDir("/tmp"); #else #error Support your platform here #endif // We use UUID to create unique path to temporary files std::string filename = "Orthanc-" + Orthanc::Toolbox::GenerateUuid(); if (extension != NULL) { filename.append(extension); } tmpDir /= filename; return tmpDir.string(); } TemporaryFile::TemporaryFile() : path_(CreateTemporaryPath(NULL)) { } TemporaryFile::TemporaryFile(const char* extension) : path_(CreateTemporaryPath(extension)) { } TemporaryFile::~TemporaryFile() { boost::filesystem::remove(path_); } } }<|fim▁end|>
* * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open('readme.rst') as reader: long_description = reader.read() setup(name='theape', long_description=long_description, version= '2014.11.10', description="The All-Purpose Experimenter.",<|fim▁hole|> license = "MIT", install_requires = 'pudb numpy paramiko configobj docopt'.split(), packages = find_packages(), include_package_data = True, package_data = {"theape":["*.txt", "*.rst", "*.ini"]}, entry_points = """ [console_scripts] theape=theape.main:main [theape.subcommands] subcommands=theape.infrastructure.arguments [theape.plugins] plugins = theape.plugins """ ) # an example last line would be cpm= cpm.main: main # If you want to require other packages add (to setup parameters): # install_requires = [<package>], #version=datetime.today().strftime("%Y.%m.%d"), # if you have an egg somewhere other than PyPi that needs to be installed as a dependency, point to a page where you can download it: # dependency_links = ["http://<url>"]<|fim▁end|>
author="russell", platforms=['linux'], url = '', author_email="[email protected]",
<|file_name|>Rectangle.py<|end_file_name|><|fim▁begin|>#################################################################################################### # # Patro - A Python library to make patterns for fashion design # Copyright (C) 2017 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # #################################################################################################### """Module to implement rectangle. """ #################################################################################################### __all__ = ['Rectangle2D'] #################################################################################################### import math from .Path import Path2D from .Primitive import Primitive2P, ClosedPrimitiveMixin, PathMixin, PolygonMixin, Primitive2DMixin from .Segment import Segment2D #################################################################################################### class Rectangle2D(Primitive2DMixin, ClosedPrimitiveMixin, PathMixin, PolygonMixin, Primitive2P): """Class to implements 2D Rectangle.""" ############################################## def __init__(self, p0, p1): # if p1 == p0: # raise ValueError('Rectangle reduced to a point') Primitive2P.__init__(self, p0, p1) ############################################## @classmethod def from_point_and_offset(self, p0, v): return cls(p0, p0+v) @classmethod def from_point_and_radius(self, p0, v): return cls(p0-v, p0+v) ############################################## @property def is_closed(self): return True ############################################## @property def p01(self): return self.__vector_cls__(self._p0.x, self._p1.y) @property def p10(self): return self.__vector_cls__(self._p1.x, self._p0.y) @property def edges(self): p0 = self._p0 p1 = self.p01 p2 = self._p1 p3 = self.p10 return ( Segment2D(p0, p1), Segment2D(p1, p2),<|fim▁hole|> ############################################## @property def diagonal(self): return self._p1 - self._p0 ############################################## @property def perimeter(self): d = self.diagonal return 2*(abs(d.x) + abs(d.y)) ############################################## @property def area(self): d = self.diagonal return abs(d.x * d.y) ############################################## def is_point_inside(self, point): bounding_box = self.bounding_box return (point.x in bounding_box.x and point.y in bounding_box.y) ############################################## def distance_to_point(self, point): raise NotImplementedError<|fim▁end|>
Segment2D(p2, p3), Segment2D(p3, p0), )
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::callback::ExceptionHandling; use dom::bindings::codegen::Bindings::EventHandlerBinding::{OnErrorEventHandlerNonNull, EventHandlerNonNull}; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::codegen::Bindings::WindowBinding::{self, WindowMethods, FrameRequestCallback}; use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast, WindowDerived}; use dom::bindings::global::global_object_for_js_object; use dom::bindings::error::{report_pending_exception, Fallible}; use dom::bindings::error::Error::InvalidCharacter; use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root, MutNullableHeap}; use dom::bindings::js::RootedReference; use dom::bindings::num::Finite; use dom::bindings::utils::{GlobalStaticData, Reflectable, WindowProxyHandler}; use dom::browsercontext::BrowsingContext; use dom::console::Console; use dom::crypto::Crypto; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration}; use dom::document::{Document, DocumentHelpers}; use dom::element::Element; use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::location::Location; use dom::navigator::Navigator; use dom::node::{window_from_node, TrustedNodeAddress, NodeHelpers, from_untrusted_node_address}; use dom::performance::Performance; use dom::screen::Screen; use dom::storage::Storage; use layout_interface::{ReflowGoal, ReflowQueryType, LayoutRPC, LayoutChan, Reflow, Msg}; use layout_interface::{ContentBoxResponse, ContentBoxesResponse, ResolvedStyleResponse, ScriptReflow}; use page::Page; use script_task::{TimerSource, ScriptChan, ScriptPort, NonWorkerScriptChan}; use script_task::ScriptMsg; use script_traits::ScriptControlChan; use timers::{IsInterval, TimerId, TimerManager, TimerCallback}; use webdriver_handlers::jsval_to_webdriver; use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType}; use devtools_traits::{TracingMetadata}; use msg::compositor_msg::ScriptListener; use msg::constellation_msg::{LoadData, PipelineId, SubpageId, ConstellationChan, WindowSizeData, WorkerId}; use msg::webdriver_msg::{WebDriverJSError, WebDriverJSResult}; use net_traits::ResourceTask; use net_traits::image_cache_task::{ImageCacheChan, ImageCacheTask}; use net_traits::storage_task::{StorageTask, StorageType}; use profile_traits::mem; use string_cache::Atom; use util::geometry::{self, Au, MAX_RECT}; use util::{breakpoint, opts}; use util::str::{DOMString,HTML_SPACE_CHARACTERS}; use euclid::{Point2D, Rect, Size2D}; use ipc_channel::ipc::IpcSender; use js::jsapi::{Evaluate2, MutableHandleValue}; use js::jsapi::{JSContext, HandleValue}; use js::jsapi::{JS_GC, JS_GetRuntime, JSAutoCompartment, JSAutoRequest}; use js::rust::Runtime; use js::rust::CompileOptionsWrapper; use selectors::parser::PseudoElement; use url::Url; use libc; use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD}; use std::ascii::AsciiExt; use std::borrow::ToOwned; use std::cell::{Cell, Ref, RefMut, RefCell}; use std::collections::HashSet; use std::default::Default; use std::ffi::CString; use std::io::{stdout, stderr, Write}; use std::mem as std_mem; use std::rc::Rc; use std::sync::Arc; use std::sync::mpsc::TryRecvError::{Empty, Disconnected}; use std::sync::mpsc::{channel, Receiver}; use time; /// Current state of the window object #[derive(JSTraceable, Copy, Clone, Debug, PartialEq, HeapSizeOf)] enum WindowState { Alive, Zombie, // Pipeline is closed, but the window hasn't been GCed yet. } /// Extra information concerning the reason for reflowing. #[derive(Debug)] pub enum ReflowReason { CachedPageNeededReflow, RefreshTick, FirstLoad, KeyEvent, MouseEvent, Query, Timer, Viewport, WindowResize, DOMContentLoaded, DocumentLoaded, ImageLoaded, RequestAnimationFrame, } #[dom_struct] #[derive(HeapSizeOf)] pub struct Window { eventtarget: EventTarget, #[ignore_heap_size_of = "trait objects are hard"] script_chan: Box<ScriptChan+Send>, #[ignore_heap_size_of = "channels are hard"] control_chan: ScriptControlChan, console: MutNullableHeap<JS<Console>>, crypto: MutNullableHeap<JS<Crypto>>, navigator: MutNullableHeap<JS<Navigator>>, #[ignore_heap_size_of = "channels are hard"] image_cache_task: ImageCacheTask, #[ignore_heap_size_of = "channels are hard"] image_cache_chan: ImageCacheChan, #[ignore_heap_size_of = "TODO(#6911) newtypes containing unmeasurable types are hard"] compositor: DOMRefCell<ScriptListener>, browsing_context: DOMRefCell<Option<BrowsingContext>>, page: Rc<Page>, performance: MutNullableHeap<JS<Performance>>, navigation_start: u64, navigation_start_precise: f64, screen: MutNullableHeap<JS<Screen>>, session_storage: MutNullableHeap<JS<Storage>>, local_storage: MutNullableHeap<JS<Storage>>, timers: TimerManager, next_worker_id: Cell<WorkerId>, /// For sending messages to the memory profiler. #[ignore_heap_size_of = "channels are hard"] mem_profiler_chan: mem::ProfilerChan, /// For providing instructions to an optional devtools server. #[ignore_heap_size_of = "channels are hard"] devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// For sending timeline markers. Will be ignored if /// no devtools server #[ignore_heap_size_of = "TODO(#6909) need to measure HashSet"] devtools_markers: RefCell<HashSet<TimelineMarkerType>>, #[ignore_heap_size_of = "channels are hard"] devtools_marker_sender: RefCell<Option<IpcSender<TimelineMarker>>>, /// A flag to indicate whether the developer tools have requested live updates of /// page changes. devtools_wants_updates: Cell<bool>, next_subpage_id: Cell<SubpageId>, /// Pending resize event, if any. resize_event: Cell<Option<WindowSizeData>>, /// Pipeline id associated with this page. id: PipelineId, /// Subpage id associated with this page, if any. parent_info: Option<(PipelineId, SubpageId)>, /// Unique id for last reflow request; used for confirming completion reply. last_reflow_id: Cell<u32>, /// Global static data related to the DOM. dom_static: GlobalStaticData, /// The JavaScript runtime. #[ignore_heap_size_of = "Rc<T> is hard"] js_runtime: DOMRefCell<Option<Rc<Runtime>>>, /// A handle for communicating messages to the layout task. #[ignore_heap_size_of = "channels are hard"] layout_chan: LayoutChan, /// A handle to perform RPC calls into the layout, quickly. #[ignore_heap_size_of = "trait objects are hard"] layout_rpc: Box<LayoutRPC+'static>, /// The port that we will use to join layout. If this is `None`, then layout is not running. #[ignore_heap_size_of = "channels are hard"] layout_join_port: DOMRefCell<Option<Receiver<()>>>, /// The current size of the window, in pixels. window_size: Cell<Option<WindowSizeData>>, /// Associated resource task for use by DOM objects like XMLHttpRequest #[ignore_heap_size_of = "channels are hard"] resource_task: Arc<ResourceTask>, /// A handle for communicating messages to the storage task. #[ignore_heap_size_of = "channels are hard"] storage_task: StorageTask, /// A handle for communicating messages to the constellation task. #[ignore_heap_size_of = "channels are hard"] constellation_chan: ConstellationChan, /// Pending scroll to fragment event, if any fragment_name: DOMRefCell<Option<String>>, /// An enlarged rectangle around the page contents visible in the viewport, used /// to prevent creating display list items for content that is far away from the viewport. page_clip_rect: Cell<Rect<Au>>, /// A counter of the number of pending reflows for this window. pending_reflow_count: Cell<u32>, /// A channel for communicating results of async scripts back to the webdriver server #[ignore_heap_size_of = "channels are hard"] webdriver_script_chan: RefCell<Option<IpcSender<WebDriverJSResult>>>, /// The current state of the window object current_state: Cell<WindowState>, } impl Window { #[allow(unsafe_code)] pub fn clear_js_runtime_for_script_deallocation(&self) { unsafe { *self.js_runtime.borrow_for_script_deallocation() = None; *self.browsing_context.borrow_for_script_deallocation() = None; self.current_state.set(WindowState::Zombie); } } pub fn get_cx(&self) -> *mut JSContext { self.js_runtime.borrow().as_ref().unwrap().cx() } pub fn script_chan(&self) -> Box<ScriptChan+Send> { self.script_chan.clone() } pub fn image_cache_chan(&self) -> ImageCacheChan { self.image_cache_chan.clone() } pub fn get_next_worker_id(&self) -> WorkerId { let worker_id = self.next_worker_id.get(); let WorkerId(id_num) = worker_id; self.next_worker_id.set(WorkerId(id_num + 1)); worker_id } pub fn pipeline(&self) -> PipelineId { self.id } pub fn subpage(&self) -> Option<SubpageId> { self.parent_info.map(|p| p.1) } pub fn parent_info(&self) -> Option<(PipelineId, SubpageId)> { self.parent_info } pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) { let (tx, rx) = channel(); (box NonWorkerScriptChan(tx), box rx) } pub fn control_chan<'a>(&'a self) -> &'a ScriptControlChan { &self.control_chan } pub fn image_cache_task<'a>(&'a self) -> &'a ImageCacheTask { &self.image_cache_task } pub fn compositor<'a>(&'a self) -> RefMut<'a, ScriptListener> { self.compositor.borrow_mut() } pub fn browsing_context<'a>(&'a self) -> Ref<'a, Option<BrowsingContext>> { self.browsing_context.borrow() } pub fn page<'a>(&'a self) -> &'a Page { &*self.page } pub fn storage_task(&self) -> StorageTask { self.storage_task.clone() } } // https://www.whatwg.org/html/#atob pub fn base64_btoa(input: DOMString) -> Fallible<DOMString> { // "The btoa() method must throw an InvalidCharacterError exception if // the method's first argument contains any character whose code point // is greater than U+00FF." if input.chars().any(|c: char| c > '\u{FF}') { Err(InvalidCharacter) } else { // "Otherwise, the user agent must convert that argument to a // sequence of octets whose nth octet is the eight-bit // representation of the code point of the nth character of // the argument," let octets = input.chars().map(|c: char| c as u8).collect::<Vec<u8>>(); // "and then must apply the base64 algorithm to that sequence of // octets, and return the result. [RFC4648]" Ok(octets.to_base64(STANDARD)) } } // https://www.whatwg.org/html/#atob pub fn base64_atob(input: DOMString) -> Fallible<DOMString> { // "Remove all space characters from input." // serialize::base64::from_base64 ignores \r and \n, // but it treats the other space characters as // invalid input. fn is_html_space(c: char) -> bool { HTML_SPACE_CHARACTERS.iter().any(|&m| m == c) } let without_spaces = input.chars() .filter(|&c| ! is_html_space(c)) .collect::<String>(); let mut input = &*without_spaces; // "If the length of input divides by 4 leaving no remainder, then: // if input ends with one or two U+003D EQUALS SIGN (=) characters, // remove them from input." if input.len() % 4 == 0 { if input.ends_with("==") { input = &input[..input.len() - 2] } else if input.ends_with("=") { input = &input[..input.len() - 1] } } // "If the length of input divides by 4 leaving a remainder of 1, // throw an InvalidCharacterError exception and abort these steps." if input.len() % 4 == 1 { return Err(InvalidCharacter) } // "If input contains a character that is not in the following list of // characters and character ranges, throw an InvalidCharacterError // exception and abort these steps: // // U+002B PLUS SIGN (+) // U+002F SOLIDUS (/) // Alphanumeric ASCII characters" if input.chars().any(|c| c != '+' && c != '/' && !c.is_alphanumeric()) { return Err(InvalidCharacter) } match input.from_base64() { Ok(data) => Ok(data.iter().map(|&b| b as char).collect::<String>()), Err(..) => Err(InvalidCharacter) } } impl<'a> WindowMethods for &'a Window { // https://html.spec.whatwg.org/#dom-alert fn Alert(self, s: DOMString) { // Right now, just print to the console // Ensure that stderr doesn't trample through the alert() we use to // communicate test results. let stderr = stderr(); let mut stderr = stderr.lock(); let stdout = stdout(); let mut stdout = stdout.lock(); writeln!(&mut stdout, "ALERT: {}", s).unwrap(); stdout.flush().unwrap(); stderr.flush().unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-window-close fn Close(self) { self.script_chan.send(ScriptMsg::ExitWindow(self.id.clone())).unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-document-0 fn Document(self) -> Root<Document> { self.browsing_context().as_ref().unwrap().active_document() } // https://html.spec.whatwg.org/#dom-location fn Location(self) -> Root<Location> { self.Document().r().Location() } // https://html.spec.whatwg.org/#dom-sessionstorage fn SessionStorage(self) -> Root<Storage> { self.session_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Session)) } // https://html.spec.whatwg.org/#dom-localstorage fn LocalStorage(self) -> Root<Storage> { self.local_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Local)) } // https://developer.mozilla.org/en-US/docs/Web/API/Console fn Console(self) -> Root<Console> { self.console.or_init(|| Console::new(GlobalRef::Window(self))) } // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto fn Crypto(self) -> Root<Crypto> { self.crypto.or_init(|| Crypto::new(GlobalRef::Window(self))) } // https://html.spec.whatwg.org/#dom-frameelement fn GetFrameElement(self) -> Option<Root<Element>> { self.browsing_context().as_ref().unwrap().frame_element() } // https://html.spec.whatwg.org/#dom-navigator fn Navigator(self) -> Root<Navigator> { self.navigator.or_init(|| Navigator::new(self)) } // https://html.spec.whatwg.org/#dom-windowtimers-settimeout fn SetTimeout(self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, IsInterval::NonInterval, TimerSource::FromWindow(self.id.clone()), self.script_chan.clone()) } // https://html.spec.whatwg.org/#dom-windowtimers-settimeout fn SetTimeout_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, IsInterval::NonInterval, TimerSource::FromWindow(self.id.clone()), self.script_chan.clone()) } // https://html.spec.whatwg.org/#dom-windowtimers-cleartimeout fn ClearTimeout(self, handle: i32) { self.timers.clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/#dom-windowtimers-setinterval fn SetInterval(self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::FunctionTimerCallback(callback), args, timeout, IsInterval::Interval, TimerSource::FromWindow(self.id.clone()), self.script_chan.clone()) } // https://html.spec.whatwg.org/#dom-windowtimers-setinterval fn SetInterval_(self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec<HandleValue>) -> i32 { self.timers.set_timeout_or_interval(TimerCallback::StringTimerCallback(callback), args, timeout, IsInterval::Interval, TimerSource::FromWindow(self.id.clone()), self.script_chan.clone()) } // https://html.spec.whatwg.org/#dom-windowtimers-clearinterval fn ClearInterval(self, handle: i32) { self.ClearTimeout(handle); } // https://html.spec.whatwg.org/multipage/#dom-window fn Window(self) -> Root<Window> { Root::from_ref(self) } // https://html.spec.whatwg.org/multipage/#dom-self fn Self_(self) -> Root<Window> { self.Window() } // https://www.whatwg.org/html/#dom-frames fn Frames(self) -> Root<Window> { self.Window() } // https://html.spec.whatwg.org/multipage/#dom-parent fn Parent(self) -> Root<Window> { self.parent().unwrap_or(self.Window()) } // https://html.spec.whatwg.org/multipage/#dom-top fn Top(self) -> Root<Window> { let mut window = self.Window(); while let Some(parent) = window.parent() { window = parent; } window } // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/ // NavigationTiming/Overview.html#sec-window.performance-attribute fn Performance(self) -> Root<Performance> { self.performance.or_init(|| { Performance::new(self, self.navigation_start, self.navigation_start_precise) }) } global_event_handlers!(); event_handler!(unload, GetOnunload, SetOnunload); error_event_handler!(error, GetOnerror, SetOnerror); // https://developer.mozilla.org/en-US/docs/Web/API/Window/screen fn Screen(self) -> Root<Screen> { self.screen.or_init(|| Screen::new(self)) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa fn Btoa(self, btoa: DOMString) -> Fallible<DOMString> { base64_btoa(btoa) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob fn Atob(self, atob: DOMString) -> Fallible<DOMString> { base64_atob(atob) } /// https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe fn RequestAnimationFrame(self, callback: Rc<FrameRequestCallback>) -> i32 { let doc = self.Document(); let callback = move |now: f64| { // TODO: @jdm The spec says that any exceptions should be suppressed; callback.Call__(Finite::wrap(now), ExceptionHandling::Report).unwrap(); }; doc.r().request_animation_frame(Box::new(callback)) } /// https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe fn CancelAnimationFrame(self, ident: i32) { let doc = self.Document(); doc.r().cancel_animation_frame(ident); } // check-tidy: no specs after this line fn Debug(self, message: DOMString) { debug!("{}", message); } #[allow(unsafe_code)] fn Gc(self) { unsafe { JS_GC(JS_GetRuntime(self.get_cx())); } } fn Trap(self) { breakpoint(); } fn WebdriverCallback(self, cx: *mut JSContext, val: HandleValue) { let rv = jsval_to_webdriver(cx, val); let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { chan.send(rv).unwrap(); } } fn WebdriverTimeout(self) { let opt_chan = self.webdriver_script_chan.borrow_mut().take(); if let Some(chan) = opt_chan { chan.send(Err(WebDriverJSError::Timeout)).unwrap(); } } // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle fn GetComputedStyle(self, element: &HTMLElement, pseudo: Option<DOMString>) -> Root<CSSStyleDeclaration> { // Steps 1-4. let pseudo = match pseudo.map(|s| s.to_ascii_lowercase()) { Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => Some(PseudoElement::Before), Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => Some(PseudoElement::After), _ => None }; // Step 5. CSSStyleDeclaration::new(self, element, pseudo, CSSModificationAccess::Readonly) } } pub trait WindowHelpers { fn clear_js_runtime(self); fn init_browsing_context(self, doc: &Document, frame_element: Option<&Element>); fn load_url(self, url: Url); fn handle_fire_timer(self, timer_id: TimerId); fn force_reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason); fn reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason); fn join_layout(self); fn layout(&self) -> &LayoutRPC; fn content_box_query(self, content_box_request: TrustedNodeAddress) -> Rect<Au>; fn content_boxes_query(self, content_boxes_request: TrustedNodeAddress) -> Vec<Rect<Au>>; fn client_rect_query(self, node_geometry_request: TrustedNodeAddress) -> Rect<i32>; fn resolved_style_query(self, element: TrustedNodeAddress, pseudo: Option<PseudoElement>, property: &Atom) -> Option<String>; fn offset_parent_query(self, node: TrustedNodeAddress) -> (Option<Root<Element>>, Rect<Au>); fn handle_reflow_complete_msg(self, reflow_id: u32); fn set_fragment_name(self, fragment: Option<String>); fn steal_fragment_name(self) -> Option<String>; fn set_window_size(self, size: WindowSizeData); fn window_size(self) -> Option<WindowSizeData>; fn get_url(self) -> Url; fn resource_task(self) -> ResourceTask; fn mem_profiler_chan(self) -> mem::ProfilerChan; fn devtools_chan(self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>>; fn layout_chan(self) -> LayoutChan; fn constellation_chan(self) -> ConstellationChan; fn windowproxy_handler(self) -> WindowProxyHandler; fn get_next_subpage_id(self) -> SubpageId; fn layout_is_idle(self) -> bool; fn get_pending_reflow_count(self) -> u32; fn add_pending_reflow(self); fn set_resize_event(self, event: WindowSizeData); fn steal_resize_event(self) -> Option<WindowSizeData>; fn set_page_clip_rect_with_new_viewport(self, viewport: Rect<f32>) -> bool; fn set_devtools_wants_updates(self, value: bool); fn IndexedGetter(self, _index: u32, _found: &mut bool) -> Option<Root<Window>>; fn thaw(self); fn freeze(self); fn need_emit_timeline_marker(self, timeline_type: TimelineMarkerType) -> bool; fn emit_timeline_marker(self, marker: TimelineMarker); fn set_devtools_timeline_marker(self, marker: TimelineMarkerType, reply: IpcSender<TimelineMarker>); fn drop_devtools_timeline_markers(self); fn set_webdriver_script_chan(self, chan: Option<IpcSender<WebDriverJSResult>>); fn is_alive(self) -> bool; fn parent(self) -> Option<Root<Window>>; } pub trait ScriptHelpers { fn evaluate_js_on_global_with_result(self, code: &str, rval: MutableHandleValue); fn evaluate_script_on_global_with_result(self, code: &str, filename: &str, rval: MutableHandleValue); } impl<'a, T: Reflectable> ScriptHelpers for &'a T { fn evaluate_js_on_global_with_result(self, code: &str, rval: MutableHandleValue) { self.evaluate_script_on_global_with_result(code, "", rval) } #[allow(unsafe_code)] fn evaluate_script_on_global_with_result(self, code: &str, filename: &str, rval: MutableHandleValue) { let this = self.reflector().get_jsobject(); let global = global_object_for_js_object(this.get()); let cx = global.r().get_cx(); let _ar = JSAutoRequest::new(cx); let globalhandle = global.r().reflector().get_jsobject(); let code: Vec<u16> = code.utf16_units().collect(); let filename = CString::new(filename).unwrap(); let _ac = JSAutoCompartment::new(cx, globalhandle.get()); let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), 0); unsafe { if Evaluate2(cx, options.ptr, code.as_ptr() as *const i16, code.len() as libc::size_t, rval) == 0 { debug!("error evaluating JS string"); report_pending_exception(cx, globalhandle.get()); } } } } impl<'a> WindowHelpers for &'a Window { fn clear_js_runtime(self) { let document = self.Document(); NodeCast::from_ref(document.r()).teardown(); // The above code may not catch all DOM objects // (e.g. DOM objects removed from the tree that haven't // been collected yet). Forcing a GC here means that // those DOM objects will be able to call dispose() // to free their layout data before the layout task<|fim▁hole|> // send a message to free their layout data to the // layout task when the script task is dropped, // which causes a panic! self.Gc(); self.current_state.set(WindowState::Zombie); *self.js_runtime.borrow_mut() = None; *self.browsing_context.borrow_mut() = None; } /// Reflows the page unconditionally. This method will wait for the layout thread to complete /// (but see the `TODO` below). If there is no window size yet, the page is presumed invisible /// and no reflow is performed. /// /// TODO(pcwalton): Only wait for style recalc, since we have off-main-thread layout. fn force_reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { let document = self.Document(); let root = document.r().GetDocumentElement(); let root = match root.r() { Some(root) => root, None => return, }; let root = NodeCast::from_ref(root); let window_size = match self.window_size.get() { Some(window_size) => window_size, None => return, }; debug!("script: performing reflow for goal {:?} reason {:?}", goal, reason); if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) { let marker = TimelineMarker::new("Reflow".to_owned(), TracingMetadata::IntervalStart); self.emit_timeline_marker(marker); } // Layout will let us know when it's done. let (join_chan, join_port) = channel(); { let mut layout_join_port = self.layout_join_port.borrow_mut(); *layout_join_port = Some(join_port); } let last_reflow_id = &self.last_reflow_id; last_reflow_id.set(last_reflow_id.get() + 1); // On debug mode, print the reflow event information. if opts::get().relayout_event { debug_reflow_events(&goal, &query_type, &reason); } // Send new document and relevant styles to layout. let reflow = box ScriptReflow { reflow_info: Reflow { goal: goal, page_clip_rect: self.page_clip_rect.get(), }, document_root: root.to_trusted_node_address(), window_size: window_size, script_chan: self.control_chan.clone(), script_join_chan: join_chan, id: last_reflow_id.get(), query_type: query_type, }; let LayoutChan(ref chan) = self.layout_chan; chan.send(Msg::Reflow(reflow)).unwrap(); debug!("script: layout forked"); self.join_layout(); self.pending_reflow_count.set(0); if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) { let marker = TimelineMarker::new("Reflow".to_owned(), TracingMetadata::IntervalEnd); self.emit_timeline_marker(marker); } } /// Reflows the page if it's possible to do so and the page is dirty. This method will wait /// for the layout thread to complete (but see the `TODO` below). If there is no window size /// yet, the page is presumed invisible and no reflow is performed. /// /// TODO(pcwalton): Only wait for style recalc, since we have off-main-thread layout. fn reflow(self, goal: ReflowGoal, query_type: ReflowQueryType, reason: ReflowReason) { let document = self.Document(); let root = document.r().GetDocumentElement(); let root = match root.r() { Some(root) => root, None => return, }; let root = NodeCast::from_ref(root); if query_type == ReflowQueryType::NoQuery && !root.get_has_dirty_descendants() { debug!("root has no dirty descendants; avoiding reflow (reason {:?})", reason); return } self.force_reflow(goal, query_type, reason) } // FIXME(cgaebel): join_layout is racey. What if the compositor triggers a // reflow between the "join complete" message and returning from this // function? /// Sends a ping to layout and waits for the response. The response will arrive when the /// layout task has finished any pending request messages. fn join_layout(self) { let mut layout_join_port = self.layout_join_port.borrow_mut(); if let Some(join_port) = std_mem::replace(&mut *layout_join_port, None) { match join_port.try_recv() { Err(Empty) => { info!("script: waiting on layout"); join_port.recv().unwrap(); } Ok(_) => {} Err(Disconnected) => { panic!("Layout task failed while script was waiting for a result."); } } debug!("script: layout joined") } } fn layout(&self) -> &LayoutRPC { &*self.layout_rpc } fn content_box_query(self, content_box_request: TrustedNodeAddress) -> Rect<Au> { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::ContentBoxQuery(content_box_request), ReflowReason::Query); self.join_layout(); //FIXME: is this necessary, or is layout_rpc's mutex good enough? let ContentBoxResponse(rect) = self.layout_rpc.content_box(); rect } fn content_boxes_query(self, content_boxes_request: TrustedNodeAddress) -> Vec<Rect<Au>> { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::ContentBoxesQuery(content_boxes_request), ReflowReason::Query); self.join_layout(); //FIXME: is this necessary, or is layout_rpc's mutex good enough? let ContentBoxesResponse(rects) = self.layout_rpc.content_boxes(); rects } fn client_rect_query(self, node_geometry_request: TrustedNodeAddress) -> Rect<i32> { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::NodeGeometryQuery(node_geometry_request), ReflowReason::Query); self.layout_rpc.node_geometry().client_rect } fn resolved_style_query(self, element: TrustedNodeAddress, pseudo: Option<PseudoElement>, property: &Atom) -> Option<String> { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::ResolvedStyleQuery(element, pseudo, property.clone()), ReflowReason::Query); let ResolvedStyleResponse(resolved) = self.layout_rpc.resolved_style(); resolved } fn offset_parent_query(self, node: TrustedNodeAddress) -> (Option<Root<Element>>, Rect<Au>) { self.reflow(ReflowGoal::ForScriptQuery, ReflowQueryType::OffsetParentQuery(node), ReflowReason::Query); let response = self.layout_rpc.offset_parent(); let js_runtime = self.js_runtime.borrow(); let js_runtime = js_runtime.as_ref().unwrap(); let element = match response.node_address { Some(parent_node_address) => { let node = from_untrusted_node_address(js_runtime.rt(), parent_node_address); let element = ElementCast::to_ref(node.r()); element.map(Root::from_ref) } None => { None } }; (element, response.rect) } fn handle_reflow_complete_msg(self, reflow_id: u32) { let last_reflow_id = self.last_reflow_id.get(); if last_reflow_id == reflow_id { *self.layout_join_port.borrow_mut() = None; } } fn init_browsing_context(self, doc: &Document, frame_element: Option<&Element>) { let mut browsing_context = self.browsing_context.borrow_mut(); *browsing_context = Some(BrowsingContext::new(doc, frame_element)); (*browsing_context).as_mut().unwrap().create_window_proxy(); } /// Commence a new URL load which will either replace this window or scroll to a fragment. fn load_url(self, url: Url) { match url.fragment { Some(fragment) => { self.script_chan.send(ScriptMsg::TriggerFragment(self.id, fragment)).unwrap(); }, None => { self.script_chan.send(ScriptMsg::Navigate(self.id, LoadData::new(url))).unwrap(); } } } fn handle_fire_timer(self, timer_id: TimerId) { self.timers.fire_timer(timer_id, self); self.reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::Timer); } fn set_fragment_name(self, fragment: Option<String>) { *self.fragment_name.borrow_mut() = fragment; } fn steal_fragment_name(self) -> Option<String> { self.fragment_name.borrow_mut().take() } fn set_window_size(self, size: WindowSizeData) { self.window_size.set(Some(size)); } fn window_size(self) -> Option<WindowSizeData> { self.window_size.get() } fn get_url(self) -> Url { let doc = self.Document(); doc.r().url() } fn resource_task(self) -> ResourceTask { (*self.resource_task).clone() } fn mem_profiler_chan(self) -> mem::ProfilerChan { self.mem_profiler_chan.clone() } fn devtools_chan(self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { self.devtools_chan.clone() } fn layout_chan(self) -> LayoutChan { self.layout_chan.clone() } fn constellation_chan(self) -> ConstellationChan { self.constellation_chan.clone() } fn windowproxy_handler(self) -> WindowProxyHandler { WindowProxyHandler(self.dom_static.windowproxy_handler.0) } fn get_next_subpage_id(self) -> SubpageId { let subpage_id = self.next_subpage_id.get(); let SubpageId(id_num) = subpage_id; self.next_subpage_id.set(SubpageId(id_num + 1)); subpage_id } fn layout_is_idle(self) -> bool { self.layout_join_port.borrow().is_none() } fn get_pending_reflow_count(self) -> u32 { self.pending_reflow_count.get() } fn add_pending_reflow(self) { self.pending_reflow_count.set(self.pending_reflow_count.get() + 1); } fn set_resize_event(self, event: WindowSizeData) { self.resize_event.set(Some(event)); } fn steal_resize_event(self) -> Option<WindowSizeData> { let event = self.resize_event.get(); self.resize_event.set(None); event } fn set_page_clip_rect_with_new_viewport(self, viewport: Rect<f32>) -> bool { // We use a clipping rectangle that is five times the size of the of the viewport, // so that we don't collect display list items for areas too far outside the viewport, // but also don't trigger reflows every time the viewport changes. static VIEWPORT_EXPANSION: f32 = 2.0; // 2 lengths on each side plus original length is 5 total. let proposed_clip_rect = geometry::f32_rect_to_au_rect( viewport.inflate(viewport.size.width * VIEWPORT_EXPANSION, viewport.size.height * VIEWPORT_EXPANSION)); let clip_rect = self.page_clip_rect.get(); if proposed_clip_rect == clip_rect { return false; } let had_clip_rect = clip_rect != MAX_RECT; if had_clip_rect && !should_move_clip_rect(clip_rect, viewport) { return false; } self.page_clip_rect.set(proposed_clip_rect); // If we didn't have a clip rect, the previous display doesn't need rebuilding // because it was built for infinite clip (MAX_RECT). had_clip_rect } fn set_devtools_wants_updates(self, value: bool) { self.devtools_wants_updates.set(value); } // https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts fn IndexedGetter(self, _index: u32, _found: &mut bool) -> Option<Root<Window>> { None } fn thaw(self) { self.timers.resume(); // Push the document title to the compositor since we are // activating this document due to a navigation. let document = self.Document(); document.r().title_changed(); } fn freeze(self) { self.timers.suspend(); } fn need_emit_timeline_marker(self, timeline_type: TimelineMarkerType) -> bool { let markers = self.devtools_markers.borrow(); markers.contains(&timeline_type) } fn emit_timeline_marker(self, marker: TimelineMarker) { let sender = self.devtools_marker_sender.borrow(); let sender = sender.as_ref().expect("There is no marker sender"); sender.send(marker).unwrap(); } fn set_devtools_timeline_marker(self, marker: TimelineMarkerType, reply: IpcSender<TimelineMarker>) { *self.devtools_marker_sender.borrow_mut() = Some(reply); self.devtools_markers.borrow_mut().insert(marker); } fn drop_devtools_timeline_markers(self) { self.devtools_markers.borrow_mut().clear(); *self.devtools_marker_sender.borrow_mut() = None; } fn set_webdriver_script_chan(self, chan: Option<IpcSender<WebDriverJSResult>>) { *self.webdriver_script_chan.borrow_mut() = chan; } fn is_alive(self) -> bool { self.current_state.get() == WindowState::Alive } fn parent(self) -> Option<Root<Window>> { let browsing_context = self.browsing_context(); let browsing_context = browsing_context.as_ref().unwrap(); browsing_context.frame_element().map(|frame_element| { let window = window_from_node(frame_element.r()); // FIXME(https://github.com/rust-lang/rust/issues/23338) let r = window.r(); let context = r.browsing_context(); context.as_ref().unwrap().active_window() }) } } impl Window { pub fn new(runtime: Rc<Runtime>, page: Rc<Page>, script_chan: Box<ScriptChan+Send>, image_cache_chan: ImageCacheChan, control_chan: ScriptControlChan, compositor: ScriptListener, image_cache_task: ImageCacheTask, resource_task: Arc<ResourceTask>, storage_task: StorageTask, mem_profiler_chan: mem::ProfilerChan, devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, constellation_chan: ConstellationChan, layout_chan: LayoutChan, id: PipelineId, parent_info: Option<(PipelineId, SubpageId)>, window_size: Option<WindowSizeData>) -> Root<Window> { let layout_rpc: Box<LayoutRPC> = { let (rpc_send, rpc_recv) = channel(); let LayoutChan(ref lchan) = layout_chan; lchan.send(Msg::GetRPC(rpc_send)).unwrap(); rpc_recv.recv().unwrap() }; let win = box Window { eventtarget: EventTarget::new_inherited(EventTargetTypeId::Window), script_chan: script_chan, image_cache_chan: image_cache_chan, control_chan: control_chan, console: Default::default(), crypto: Default::default(), compositor: DOMRefCell::new(compositor), page: page, navigator: Default::default(), image_cache_task: image_cache_task, mem_profiler_chan: mem_profiler_chan, devtools_chan: devtools_chan, browsing_context: DOMRefCell::new(None), performance: Default::default(), navigation_start: time::get_time().sec as u64, navigation_start_precise: time::precise_time_ns() as f64, screen: Default::default(), session_storage: Default::default(), local_storage: Default::default(), timers: TimerManager::new(), next_worker_id: Cell::new(WorkerId(0)), id: id, parent_info: parent_info, dom_static: GlobalStaticData::new(), js_runtime: DOMRefCell::new(Some(runtime.clone())), resource_task: resource_task, storage_task: storage_task, constellation_chan: constellation_chan, page_clip_rect: Cell::new(MAX_RECT), fragment_name: DOMRefCell::new(None), last_reflow_id: Cell::new(0), resize_event: Cell::new(None), next_subpage_id: Cell::new(SubpageId(0)), layout_chan: layout_chan, layout_rpc: layout_rpc, layout_join_port: DOMRefCell::new(None), window_size: Cell::new(window_size), pending_reflow_count: Cell::new(0), current_state: Cell::new(WindowState::Alive), devtools_marker_sender: RefCell::new(None), devtools_markers: RefCell::new(HashSet::new()), devtools_wants_updates: Cell::new(false), webdriver_script_chan: RefCell::new(None), }; WindowBinding::Wrap(runtime.cx(), win) } } fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool{ let clip_rect = Rect::new(Point2D::new(clip_rect.origin.x.to_f32_px(), clip_rect.origin.y.to_f32_px()), Size2D::new(clip_rect.size.width.to_f32_px(), clip_rect.size.height.to_f32_px())); // We only need to move the clip rect if the viewport is getting near the edge of // our preexisting clip rect. We use half of the size of the viewport as a heuristic // for "close." static VIEWPORT_SCROLL_MARGIN_SIZE: f32 = 0.5; let viewport_scroll_margin = new_viewport.size * VIEWPORT_SCROLL_MARGIN_SIZE; (clip_rect.origin.x - new_viewport.origin.x).abs() <= viewport_scroll_margin.width || (clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width || (clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height || (clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height } fn debug_reflow_events(goal: &ReflowGoal, query_type: &ReflowQueryType, reason: &ReflowReason) { let mut debug_msg = "****".to_owned(); debug_msg.push_str(match *goal { ReflowGoal::ForDisplay => "\tForDisplay", ReflowGoal::ForScriptQuery => "\tForScriptQuery", }); debug_msg.push_str(match *query_type { ReflowQueryType::NoQuery => "\tNoQuery", ReflowQueryType::ContentBoxQuery(_n) => "\tContentBoxQuery", ReflowQueryType::ContentBoxesQuery(_n) => "\tContentBoxesQuery", ReflowQueryType::NodeGeometryQuery(_n) => "\tNodeGeometryQuery", ReflowQueryType::ResolvedStyleQuery(_, _, _) => "\tResolvedStyleQuery", ReflowQueryType::OffsetParentQuery(_n) => "\tOffsetParentQuery", }); debug_msg.push_str(match *reason { ReflowReason::CachedPageNeededReflow => "\tCachedPageNeededReflow", ReflowReason::RefreshTick => "\tRefreshTick", ReflowReason::FirstLoad => "\tFirstLoad", ReflowReason::KeyEvent => "\tKeyEvent", ReflowReason::MouseEvent => "\tMouseEvent", ReflowReason::Query => "\tQuery", ReflowReason::Timer => "\tTimer", ReflowReason::Viewport => "\tViewport", ReflowReason::WindowResize => "\tWindowResize", ReflowReason::DOMContentLoaded => "\tDOMContentLoaded", ReflowReason::DocumentLoaded => "\tDocumentLoaded", ReflowReason::ImageLoaded => "\tImageLoaded", ReflowReason::RequestAnimationFrame => "\tRequestAnimationFrame", }); println!("{}", debug_msg); } impl WindowDerived for EventTarget { fn is_window(&self) -> bool { self.type_id() == &EventTargetTypeId::Window } }<|fim▁end|>
// exits. Without this, those remaining objects try to
<|file_name|>CommonConstants.java<|end_file_name|><|fim▁begin|>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package king.flow.common; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.File; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import king.flow.action.business.ShowClockAction; import king.flow.data.TLSResult; import king.flow.view.Action; import king.flow.view.Action.CleanAction; import king.flow.view.Action.EjectCardAction; import king.flow.view.Action.WithdrawCardAction; import king.flow.view.Action.EncryptKeyboardAction; import king.flow.view.Action.HideAction; import king.flow.view.Action.InsertICardAction; import king.flow.view.Action.LimitInputAction; import king.flow.view.Action.MoveCursorAction; import king.flow.view.Action.NumericPadAction; import king.flow.view.Action.OpenBrowserAction; import king.flow.view.Action.PlayMediaAction; import king.flow.view.Action.PlayVideoAction; import king.flow.view.Action.PrintPassbookAction; import king.flow.view.Action.RunCommandAction; import king.flow.view.Action.RwFingerPrintAction; import king.flow.view.Action.SetFontAction; import king.flow.view.Action.SetPrinterAction; import king.flow.view.Action.ShowComboBoxAction; import king.flow.view.Action.ShowGridAction; import king.flow.view.Action.ShowTableAction; import king.flow.view.Action.Swipe2In1CardAction; import king.flow.view.Action.SwipeCardAction; import king.flow.view.Action.UploadFileAction; import king.flow.view.Action.UseTipAction; import king.flow.view.Action.VirtualKeyboardAction; import king.flow.view.Action.WriteICardAction; import king.flow.view.ComponentEnum; import king.flow.view.DefinedAction; import king.flow.view.DeviceEnum; import king.flow.view.JumpAction; import king.flow.view.MsgSendAction; /** * * @author LiuJin */ public class CommonConstants { public static final String APP_STARTUP_ENTRY = "bank.exe"; public static final Charset UTF8 = Charset.forName("UTF-8"); static final File[] SYS_ROOTS = File.listRoots(); public static final int DRIVER_COUNT = SYS_ROOTS.length; public static final String XML_NODE_PREFIX = "N_"; public static final String REVERT = "re_"; public static final String BID = "bid"; public static final String UID_PREFIX = "<" + TLSResult.UID + ">"; public static final String UID_AFFIX = "</" + TLSResult.UID + ">"; public static final String DEFAULT_DATE_FORMATE = "yyyy-MM-dd"; public static final String VALID_BANK_CARD = "validBankCard"; public static final String BALANCED_PAY_MAC = "balancedPayMAC"; public static final String CANCEL_ENCRYPTION_KEYBOARD = "[CANCEL]"; public static final String QUIT_ENCRYPTION_KEYBOARD = "[QUIT]"; public static final String INVALID_ENCRYPTION_LENGTH = "encryption.keyboard.type.length.prompt"; public static final String TIMEOUT_ENCRYPTION_TYPE = "encryption.keyboard.type.timeout.prompt"; public static final String ERROR_ENCRYPTION_TYPE = "encryption.keyboard.type.fail.prompt"; public static final int CONTAINER_KEY = Integer.MAX_VALUE; public static final int NORMAL = 0; public static final int ABNORMAL = 1; public static final int BALANCE = 12345; public static final int RESTART_SIGNAL = 1; public static final int DOWNLOAD_KEY_SIGNAL = 1; public static final int UPDATE_SIGNAL = 1; public static final int WATCHDOG_CHECK_INTERVAL = 5; public static final String VERSION; public static final long DEBUG_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(3); public static final long RUN_MODE_PROGRESS_TIME = TimeUnit.SECONDS.toMillis(1); // public static final String VERSION = Paths.get(".").toAbsolutePath().normalize().toString(); static { String workingPath = System.getProperty("user.dir"); final int lastIndexOf = workingPath.lastIndexOf('_'); if (lastIndexOf != -1 && lastIndexOf < workingPath.length() - 1) { VERSION = workingPath.substring(lastIndexOf + 1); } else { VERSION = "Unknown"; } } /* JMX configuration */ private static String getJmxRmiUrl(int port) { return "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi"; } public static final int APP_JMX_RMI_PORT = 9998; public static final String APP_JMX_RMI_URL = getJmxRmiUrl(APP_JMX_RMI_PORT); public static final int WATCHDOG_JMX_RMI_PORT = 9999; public static final String WATCHDOG_JMX_RMI_URL = getJmxRmiUrl(WATCHDOG_JMX_RMI_PORT); /* system variable pattern */ public static final String SYSTEM_VAR_PATTERN = "\\$\\{(_?\\p{Alpha}+_\\p{Alpha}+)+\\}"; public static final String TEXT_MINGLED_SYSTEM_VAR_PATTERN = ".*" + SYSTEM_VAR_PATTERN + ".*"; public static final String TERMINAL_ID_SYS_VAR = "TERMINAL_ID"; /* swing default config */ public static final int DEFAULT_TABLE_ROW_COUNT = 15; public static final int TABLE_ROW_HEIGHT = 25; public static final int DEFAULT_VIDEO_REPLAY_INTERVAL_SECOND = 20; /* packet header ID */ public static final int GENERAL_MSG_CODE = 0; //common message public static final int REGISTRY_MSG_CODE = 1; //terminal registration message public static final int KEY_DOWNLOAD_MSG_CODE = 2; //download secret key message public static final int MANAGER_MSG_CODE = 100; //management message /*MAX_MESSAGES_PER_READ refers to DefaultChannelConfig, AdaptiveRecvByteBufAllocator, FixedRecvByteBufAllocator */ public static final int MAX_MESSAGES_PER_READ = 64; //how many read actions in one message conversation public static final int MIN_RECEIVED_BUFFER_SIZE = 1024; //1024 bytes public static final int RECEIVED_BUFFER_SIZE = 32 * 1024; //32k bytes public static final int MAX_RECEIVED_BUFFER_SIZE = 64 * 1024; //64k bytes /* keyboard cipher key */ public static final String WORK_SECRET_KEY = "workSecretKey"; public static final String MA_KEY = "maKey"; public static final String MASTER_KEY = "masterKey"; /* packet result flag */ public static final int SUCCESSFUL_MSG_CODE = 0; /* xml jaxb context */ public static final String NET_CONF_PACKAGE_CONTEXT = "king.flow.net"; public static final String TLS_PACKAGE_CONTEXT = "king.flow.data"; public static final String UI_CONF_PACKAGE_CONTEXT = "king.flow.view"; public static final String KING_FLOW_BACKGROUND = "king.flow.background"; public static final String KING_FLOW_PROGRESS = "king.flow.progress"; public static final String TEXT_TYPE_TOOL_CONFIG = "chinese.text.type.config"; public static final String COMBOBOX_ITEMS_PROPERTY_PATTERN = "([^,/]*/[^,/]*,)*+([^,/]*/[^,/]*){1}+"; public static final String ADVANCED_TABLE_TOTAL_PAGES = "total"; public static final String ADVANCED_TABLE_VALUE = "value"; public static final String ADVANCED_TABLE_CURRENT_PAGE = "current"; /* card-reading state */ public static final int INVALID_CARD_STATE = -1; public static final int MAGNET_CARD_STATE = 2; public static final int IC_CARD_STATE = 3; /* union-pay transaction type */ public static final String UNION_PAY_REGISTRATION = "1"; public static final String UNION_PAY_TRANSACTION = "3"; public static final String UNION_PAY_TRANSACTION_BALANCE = "4"; /* card affiliation type */ public static final String CARD_AFFILIATION_INTERNAL = "1"; public static final String CARD_AFFILIATION_EXTERNAL = "2"; /* supported driver types */ static final ImmutableSet<DeviceEnum> SUPPORTED_DEVICES = new ImmutableSet.Builder<DeviceEnum>() .add(DeviceEnum.IC_CARD) .add(DeviceEnum.CASH_SAVER) .add(DeviceEnum.GZ_CARD) .add(DeviceEnum.HIS_CARD) .add(DeviceEnum.KEYBOARD) .add(DeviceEnum.MAGNET_CARD) .add(DeviceEnum.MEDICARE_CARD) .add(DeviceEnum.PATIENT_CARD) .add(DeviceEnum.PID_CARD) .add(DeviceEnum.PKG_8583) .add(DeviceEnum.PRINTER) .add(DeviceEnum.SENSOR_CARD) .add(DeviceEnum.TWO_IN_ONE_CARD) .build(); /* action-component relationship map */ public static final String JUMP_ACTION = JumpAction.class.getSimpleName(); public static final String SET_FONT_ACTION = SetFontAction.class.getSimpleName(); public static final String CLEAN_ACTION = CleanAction.class.getSimpleName(); public static final String HIDE_ACTION = HideAction.class.getSimpleName(); public static final String USE_TIP_ACTION = UseTipAction.class.getSimpleName(); public static final String PLAY_MEDIA_ACTION = PlayMediaAction.class.getSimpleName(); public static final String SEND_MSG_ACTION = MsgSendAction.class.getSimpleName(); public static final String MOVE_CURSOR_ACTION = MoveCursorAction.class.getSimpleName(); public static final String LIMIT_INPUT_ACTION = LimitInputAction.class.getSimpleName(); public static final String SHOW_COMBOBOX_ACTION = ShowComboBoxAction.class.getSimpleName(); public static final String SHOW_TABLE_ACTION = ShowTableAction.class.getSimpleName(); public static final String SHOW_CLOCK_ACTION = ShowClockAction.class.getSimpleName(); public static final String OPEN_BROWSER_ACTION = OpenBrowserAction.class.getSimpleName(); public static final String RUN_COMMAND_ACTION = RunCommandAction.class.getSimpleName(); public static final String OPEN_VIRTUAL_KEYBOARD_ACTION = VirtualKeyboardAction.class.getSimpleName(); public static final String PRINT_RECEIPT_ACTION = SetPrinterAction.class.getSimpleName(); public static final String INSERT_IC_ACTION = InsertICardAction.class.getSimpleName(); public static final String WRITE_IC_ACTION = WriteICardAction.class.getSimpleName(); public static final String BALANCE_TRANS_ACTION = "BalanceTransAction"; public static final String PRINT_PASSBOOK_ACTION = PrintPassbookAction.class.getSimpleName(); public static final String UPLOAD_FILE_ACTION = UploadFileAction.class.getSimpleName(); public static final String SWIPE_CARD_ACTION = SwipeCardAction.class.getSimpleName(); public static final String SWIPE_TWO_IN_ONE_CARD_ACTION = Swipe2In1CardAction.class.getSimpleName(); public static final String EJECT_CARD_ACTION = EjectCardAction.class.getSimpleName(); public static final String WITHDRAW_CARD_ACTION = WithdrawCardAction.class.getSimpleName(); public static final String READ_WRITE_FINGERPRINT_ACTION = RwFingerPrintAction.class.getSimpleName(); public static final String PLAY_VIDEO_ACTION = PlayVideoAction.class.getSimpleName(); public static final String CUSTOMIZED_ACTION = DefinedAction.class.getSimpleName(); public static final String ENCRYPT_KEYBORAD_ACTION = EncryptKeyboardAction.class.getSimpleName(); public static final String SHOW_GRID_ACTION = ShowGridAction.class.getSimpleName(); public static final String TYPE_NUMERIC_PAD_ACTION = NumericPadAction.class.getSimpleName(); public static final String WEB_LOAD_ACTION = Action.WebLoadAction.class.getSimpleName(); static final Map<ComponentEnum, List<String>> ACTION_COMPONENT_MAP = new ImmutableMap.Builder<ComponentEnum, List<String>>() .put(ComponentEnum.BUTTON, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(JUMP_ACTION) .add(SET_FONT_ACTION) .add(CLEAN_ACTION) .add(HIDE_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(OPEN_BROWSER_ACTION) .add(RUN_COMMAND_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(PRINT_RECEIPT_ACTION) .add(SEND_MSG_ACTION) .add(INSERT_IC_ACTION) .add(WRITE_IC_ACTION) .add(MOVE_CURSOR_ACTION) .add(PRINT_PASSBOOK_ACTION) .add(UPLOAD_FILE_ACTION) .add(BALANCE_TRANS_ACTION) .add(EJECT_CARD_ACTION) .add(WITHDRAW_CARD_ACTION) .add(WEB_LOAD_ACTION) .build()) .put(ComponentEnum.COMBO_BOX, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_COMBOBOX_ACTION)<|fim▁hole|> .add(SWIPE_CARD_ACTION) .add(SWIPE_TWO_IN_ONE_CARD_ACTION) .add(PLAY_MEDIA_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.LABEL, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_CLOCK_ACTION) .build()) .put(ComponentEnum.TEXT_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(OPEN_VIRTUAL_KEYBOARD_ACTION) .add(MOVE_CURSOR_ACTION) .build()) .put(ComponentEnum.PASSWORD_FIELD, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(LIMIT_INPUT_ACTION) .add(USE_TIP_ACTION) .add(PLAY_MEDIA_ACTION) .add(READ_WRITE_FINGERPRINT_ACTION) .add(MOVE_CURSOR_ACTION) .add(ENCRYPT_KEYBORAD_ACTION) .build()) .put(ComponentEnum.TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(USE_TIP_ACTION) .add(SHOW_TABLE_ACTION) .build()) .put(ComponentEnum.ADVANCED_TABLE, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(SET_FONT_ACTION) .add(SHOW_TABLE_ACTION) .add(SEND_MSG_ACTION) .build()) .put(ComponentEnum.VIDEO_PLAYER, new ImmutableList.Builder<String>() .add(CUSTOMIZED_ACTION) .add(PLAY_VIDEO_ACTION) .build()) .put(ComponentEnum.GRID, new ImmutableList.Builder<String>() .add(SHOW_GRID_ACTION) .build()) .put(ComponentEnum.NUMERIC_PAD, new ImmutableList.Builder<String>() .add(TYPE_NUMERIC_PAD_ACTION) .build()) .build(); }<|fim▁end|>
<|file_name|>LineBrushComponent.cpp<|end_file_name|><|fim▁begin|>#include "gamelib/components/editor/LineBrushComponent.hpp" #include "gamelib/components/geometry/Polygon.hpp" #include "gamelib/components/rendering/MeshRenderer.hpp" #include "gamelib/core/ecs/Entity.hpp" #include "gamelib/properties/PropComponent.hpp" namespace gamelib { LineBrushComponent::LineBrushComponent() : _linewidth(32) { auto cb = +[](const ComponentReference<PolygonCollider>* val, LineBrushComponent* self) { self->_line = *val; self->regenerate(); }; _props.registerProperty("linewidth", _linewidth, PROP_METHOD(_linewidth, setWidth), this); registerProperty(_props, "line", _line, *this, cb); } void LineBrushComponent::setWidth(int width) { if (_linewidth == width) return; _linewidth = width; regenerate(); } int LineBrushComponent::getWidth() const {<|fim▁hole|> PolygonCollider* LineBrushComponent::getBrushPolygon() const { return _line.get(); } void LineBrushComponent::regenerate() const { if (!_shape || !_pol || !_line || _line->size() == 0) return; math::Vec2f lastd, dir; bool start = true; auto cb = [&](const math::Line2f& seg) { float area = 0; auto norm = seg.d.normalized(); if (start) { start = false; lastd = seg.d; } else { // Compute if the line turns clockwise or counter clockwise // Total hours wasted here because I didn't google the // problem / didn't knew what exactly to google for: 11 auto p1 = seg.p - lastd; auto p3 = seg.p + seg.d; // Break if the direction hasn't changed if (lastd.normalized() == norm) return false; area = (seg.p.x - p1.x) * (seg.p.y + p1.y) + (p3.x - seg.p.x) * (p3.y + seg.p.y) + (p1.x - p3.x) * (p1.y + p3.y); } dir = (norm + lastd.normalized()).right().normalized(); dir *= (_linewidth / 2.0) / dir.angle_cos(lastd.right()); _pol->add(seg.p - dir); _pol->add(seg.p + dir); // depending on clockwise or counter clockwise line direction, // different vertices have to be added. if (area != 0) { auto len = norm.right() * _linewidth; if (area > 0) // clockwise { _pol->add(seg.p - dir); _pol->add(seg.p - dir + len); } else // counter clockwise { _pol->add(seg.p + dir - len); _pol->add(seg.p + dir); } } lastd = seg.d; return false; }; auto& linepol = _line->getLocal(); _pol->clear(); linepol.foreachSegment(cb); dir = lastd.right().normalized() * (_linewidth / 2.0); _pol->add(linepol.get(linepol.size() - 1) - dir); _pol->add(linepol.get(linepol.size() - 1) + dir); _shape->fetch(_pol->getLocal(), sf::TriangleStrip); } }<|fim▁end|>
return _linewidth; }
<|file_name|>createorganization.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('angularPHP') .controller('CreateorganizationCtrl', function ($scope, Session, Organizations, $timeout, $location) { Session.require(); $scope.name = ""; $scope.msg = ""; $scope.error = ""; $scope.create = function() { $scope.error = ""; $scope.msg = ""; Organizations.create($scope.name,function(){ $scope.msg = "The organization was created successfully"; $scope.$apply;<|fim▁hole|> $location.path("/organizations"); },2000); },function(error){ $scope.error = error; $scope.$apply; }); }; });<|fim▁end|>
$timeout(function(){
<|file_name|>decorator_utils.py<|end_file_name|><|fim▁begin|># Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Utility functions for writing decorators (which modify docstrings).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function <|fim▁hole|> # Python 3 if hasattr(function, '__qualname__'): return function.__qualname__ # Python 2 if hasattr(function, 'im_class'): return function.im_class.__name__ + '.' + function.__name__ return function.__name__ def _normalize_docstring(docstring): """Normalizes the docstring. Replaces tabs with spaces, removes leading and trailing blanks lines, and removes any indentation. Copied from PEP-257: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation Args: docstring: the docstring to normalize Returns: The normalized docstring """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): # (we use sys.maxsize because sys.maxint doesn't exist in Python 3) indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def add_notice_to_docstring( doc, instructions, no_doc_str, suffix_str, notice): """Adds a deprecation notice to a docstring.""" if not doc: lines = [no_doc_str] else: lines = _normalize_docstring(doc).splitlines() lines[0] += ' ' + suffix_str notice = [''] + notice + ([instructions] if instructions else []) if len(lines) > 1: # Make sure that we keep our distance from the main body if lines[1].strip(): notice.append('') lines[1:1] = notice else: lines += notice return '\n'.join(lines) def validate_callable(func, decorator_name): if not hasattr(func, '__call__'): raise ValueError( '%s is not a function. If this is a property, make sure' ' @property appears before @%s in your source code:' '\n\n@property\n@%s\ndef method(...)' % ( func, decorator_name, decorator_name)) class classproperty(object): # pylint: disable=invalid-name """Class property decorator. Example usage: class MyClass(object): @classproperty def value(cls): return '123' > print MyClass.value 123 """ def __init__(self, func): self._func = func def __get__(self, owner_self, owner_cls): return self._func(owner_cls)<|fim▁end|>
import sys def get_qualified_name(function):
<|file_name|>tasks.js<|end_file_name|><|fim▁begin|>import axios from 'axios' import pipelineApi from './api' import { addMessage } from '../../../client/utils/flash-messages' import { transformValueForAPI } from '../../../client/utils/date' function transformValuesForApi(values, oldValues = {}) { const data = { name: values.name, status: values.category, } function addValue(key, value) { const existingValue = oldValues[key] const hasExistingValue = Array.isArray(existingValue)<|fim▁hole|> data[key] = value || null } } addValue('likelihood_to_win', parseInt(values.likelihood, 10)) addValue('sector', values.sector?.value) addValue( 'contacts', values.contacts ? values.contacts.map(({ value }) => value) : [] ) addValue('potential_value', values.export_value) addValue('expected_win_date', transformValueForAPI(values.expected_win_date)) return data } export async function getPipelineByCompany({ companyId }) { const { data } = await pipelineApi.list({ company_id: companyId }) return { companyId, count: data.count, results: data.results, } } export async function addCompanyToPipeline({ values, companyId }) { const { data } = await pipelineApi.create({ company: companyId, ...transformValuesForApi(values), }) addMessage('success', `You added ${values.name} to your pipeline`) return data } export async function getPipelineItem({ pipelineItemId }) { const { data } = await pipelineApi.get(pipelineItemId) return data } export async function getCompanyContacts({ companyId, features }) { const contactEndpointVersion = features['address-area-contact-required-field'] ? 'v4' : 'v3' const { data } = await axios.get( `/api-proxy/${contactEndpointVersion}/contact`, { params: { company_id: companyId, limit: 500 }, } ) return data.results } export async function editPipelineItem({ values, pipelineItemId, currentPipelineItem, }) { const { data } = await pipelineApi.update( pipelineItemId, transformValuesForApi(values, currentPipelineItem) ) addMessage('success', `You saved changes to ${values.name}`) return data } export async function archivePipelineItem({ values, pipelineItemId, projectName, }) { const { data } = await pipelineApi.archive(pipelineItemId, { reason: values.reason, }) addMessage('success', `You archived ${projectName}`) return data } export async function unarchivePipelineItem({ projectName, pipelineItemId }) { const { data } = await pipelineApi.unarchive(pipelineItemId) addMessage('success', `You unarchived ${projectName}`) return data } export async function deletePipelineItem({ projectName, pipelineItemId }) { const { status } = await pipelineApi.delete(pipelineItemId) addMessage('success', `You deleted ${projectName} from your pipeline`) return status }<|fim▁end|>
? !!existingValue.length : !!existingValue if (hasExistingValue || (Array.isArray(value) ? value.length : value)) {
<|file_name|>email_nag.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ A script for automated nagging emails based on passed in queries These can be collated into several 'queries' through the use of multiple query files with a 'query_name' param set eg: 'Bugs tracked for Firefox Beta (13)' Once the bugs have been collected from Bugzilla they are sorted into buckets cc: assignee manager and to the assignee(s) or need-info? for each query """ import sys import os import smtplib import subprocess import tempfile import collections from datetime import datetime from argparse import ArgumentParser from auto_nag.bugzilla.agents import BMOAgent import phonebook from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates')) REPLY_TO_EMAIL = '[email protected]' DEFAULT_CC = ['[email protected]'] EMAIL_SUBJECT = '' SMTP = 'smtp.mozilla.org' # TODO - Sort by who a bug is blocked on (thanks @dturner) # TODO - write tests! # TODO - look into knocking out duplicated bugs in queries -- perhaps print out if there are dupes in queries when queries > 1 # TODO - should compare bugmail from API results to phonebook bugmail in to_lower() def get_last_manager_comment(comments, manager, person): # go through in reverse order to get most recent for comment in comments[::-1]: if person is not None: if comment.creator.name == manager['mozillaMail'] or comment.creator.name == manager['bugzillaEmail']: return comment.creation_time.replace(tzinfo=None) return None def get_last_assignee_comment(comments, person): # go through in reverse order to get most recent for comment in comments[::-1]: if person is not None: if comment.creator.name == person['mozillaMail'] or comment.creator.name == person['bugzillaEmail']: return comment.creation_time.replace(tzinfo=None) return None def query_url_to_dict(url): if (';')in url: fields_and_values = url.split("?")[1].split(";") else: fields_and_values = url.split("?")[1].split("&") d = collections.defaultdict(list) for pair in fields_and_values: (key, val) = pair.split("=") if key != "list_id": d[key].append(val) return d def generateEmailOutput(subject, queries, template, people, show_comment=False, manager_email=None, rollup=False, rollupEmail=None): cclist = [] toaddrs = [] template_params = {} # stripping off the templates dir, just in case it gets passed in the args template = env.get_template(template.replace('templates/', '', 1)) def addToAddrs(bug): if bug.assigned_to.name in people.people_by_bzmail: person = dict(people.people_by_bzmail[bug.assigned_to.name]) if person['mozillaMail'] not in toaddrs: toaddrs.append(person['mozillaMail']) for query in queries.keys(): # Avoid dupes in the cclist from several queries query_cc = queries[query].get('cclist', []) for qcc in query_cc: if qcc not in cclist: cclist.append(qcc) if query not in template_params: template_params[query] = {'buglist': []} if len(queries[query]['bugs']) != 0: for bug in queries[query]['bugs']: if 'show_summary' in queries[query]: if queries[query]['show_summary'] == '1': summary = bug.summary else: summary = "" else: summary = "" template_params[query]['buglist'].append( { 'id': bug.id, 'summary': summary, # 'comment': bug.comments[-1].creation_time.replace(tzinfo=None), 'assignee': bug.assigned_to.real_name, 'flags': bug.flags } ) # more hacking for JS special casing if bug.assigned_to.name == '[email protected]' and '[email protected]' not in toaddrs: toaddrs.append('[email protected]') # if needinfo? in flags, add the flag.requestee to the toaddrs instead of bug assignee if bug.flags: for flag in bug.flags: if 'needinfo' in flag.name and flag.status == '?': try: person = dict(people.people_by_bzmail[str(flag.requestee)]) if person['mozillaMail'] not in toaddrs: toaddrs.append(person['mozillaMail']) except: if str(flag.requestee) not in toaddrs: toaddrs.append(str(flag.requestee)) else: addToAddrs(bug) else: addToAddrs(bug) message_body = template.render(queries=template_params, show_comment=show_comment) if manager_email is not None and manager_email not in cclist: cclist.append(manager_email) # no need to and cc the manager if more than one email if len(toaddrs) > 1: for email in toaddrs: if email in cclist: toaddrs.remove(email) if cclist == ['']: cclist = None if rollup: joined_to = ",".join(rollupEmail) else: joined_to = ",".join(toaddrs) message = ( "From: %s\r\n" % REPLY_TO_EMAIL + "To: %s\r\n" % joined_to + "CC: %s\r\n" % ",".join(cclist) + "Subject: %s\r\n" % subject + "\r\n" + message_body) toaddrs = toaddrs + cclist return toaddrs, message def sendMail(toaddrs, msg, username, password, dryrun=False): if dryrun: print "\n****************************\n* DRYRUN: not sending mail *\n****************************\n" print msg else: server = smtplib.SMTP_SSL(SMTP, 465) server.set_debuglevel(1) server.login(username, password) # note: toaddrs is required for transport agents, the msg['To'] header is not modified server.sendmail(username, toaddrs, msg) server.quit() if __name__ == '__main__': parser = ArgumentParser(__doc__) parser.set_defaults( dryrun=False, username=None, password=None, roll_up=False, show_comment=False, email_cc_list=None, queries=[], days_since_comment=-1, verbose=False, keywords=None, email_subject=None, no_verification=False, ) parser.add_argument("-d", "--dryrun", dest="dryrun", action="store_true", help="just do the query, and print emails to console without emailing anyone") parser.add_argument("-m", "--mozilla-email", dest="mozilla_mail", help="specify a specific address for sending email"), parser.add_argument("-p", "--email-password", dest="email_password", help="specify a specific password for sending email") parser.add_argument("-b", "--bz-api-key", dest="bz_api_key", help="Bugzilla API key") parser.add_argument("-t", "--template", dest="template", required=True, help="template to use for the buglist output")<|fim▁hole|> action="append", required=True, help="a file containing a dictionary of a bugzilla query") parser.add_argument("-k", "--keyword", dest="keywords", action="append", help="keywords to collate buglists") parser.add_argument("-s", "--subject", dest="email_subject", required=True, help="The subject of the email being sent") parser.add_argument("-r", "--roll-up", dest="roll_up", action="store_true", help="flag to get roll-up output in one email instead of creating multiple emails") parser.add_argument("--show-comment", dest="show_comment", action="store_true", help="flag to display last comment on a bug in the message output") parser.add_argument("--days-since-comment", dest="days_since_comment", help="threshold to check comments against to take action based on days since comment") parser.add_argument("--verbose", dest="verbose", action="store_true", help="turn on verbose output") parser.add_argument("--no-verification", dest="no_verification", action="store_true", help="don't wait for human verification of every email") options, args = parser.parse_known_args() people = phonebook.PhonebookDirectory(dryrun=options.dryrun) try: int(options.days_since_comment) except: if options.days_since_comment is not None: parser.error("Need to provide a number for days \ since last comment value") if options.email_cc_list is None: options.email_cc_list = DEFAULT_CC # Load our agent for BMO bmo = BMOAgent(options.bz_api_key) # Get the buglist(s) collected_queries = {} for query in options.queries: # import the query if os.path.exists(query): info = {} execfile(query, info) query_name = info['query_name'] if query_name not in collected_queries: collected_queries[query_name] = { 'channel': info.get('query_channel', ''), 'bugs': [], 'show_summary': info.get('show_summary', 0), 'cclist': options.email_cc_list, } if 'cc' in info: for c in info.get('cc').split(','): collected_queries[query_name]['cclist'].append(c) if 'query_params' in info: print "Gathering bugs from query_params in %s" % query collected_queries[query_name]['bugs'] = bmo.get_bug_list(info['query_params']) elif 'query_url' in info: print "Gathering bugs from query_url in %s" % query collected_queries[query_name]['bugs'] = bmo.get_bug_list(query_url_to_dict(info['query_url'])) # print "DEBUG: %d bug(s) found for query %s" % \ # (len(collected_queries[query_name]['bugs']), info['query_url']) else: print "Error - no valid query params or url in the config file" sys.exit(1) else: print "Not a valid path: %s" % query total_bugs = 0 for channel in collected_queries.keys(): total_bugs += len(collected_queries[channel]['bugs']) print "Found %s bugs total for %s queries" % (total_bugs, len(collected_queries.keys())) print "Queries to collect: %s" % collected_queries.keys() managers = people.managers manual_notify = {} counter = 0 def add_to_managers(manager_email, query, info={}): if manager_email not in managers: managers[manager_email] = {} managers[manager_email]['nagging'] = {query: {'bugs': [bug], 'show_summary': info.get('show_summary', 0), 'cclist': info.get('cclist', [])}, } return if 'nagging' in managers[manager_email]: if query in managers[manager_email]['nagging']: managers[manager_email]['nagging'][query]['bugs'].append(bug) if options.verbose: print "Adding %s to %s in nagging for %s" % \ (bug.id, query, manager_email) else: managers[manager_email]['nagging'][query] = { 'bugs': [bug], 'show_summary': info.get('show_summary', 0), 'cclist': info.get('cclist', []) } if options.verbose: print "Adding new query key %s for bug %s in nagging \ and %s" % (query, bug.id, manager_email) else: managers[manager_email]['nagging'] = {query: {'bugs': [bug], 'show_summary': info.get('show_summary', 0), 'cclist': info.get('cclist', [])}, } if options.verbose: print "Creating query key %s for bug %s in nagging and \ %s" % (query, bug.id, manager_email) for query, info in collected_queries.items(): if len(collected_queries[query]['bugs']) != 0: manual_notify[query] = {'bugs': [], 'show_summary': info.get('show_summary', 0)} for b in collected_queries[query]['bugs']: counter = counter + 1 send_mail = True bug = bmo.get_bug(b.id) manual_notify[query]['bugs'].append(bug) assignee = bug.assigned_to.name if "@" not in assignee: print "Error - email address expect. Found '" + assignee + "' instead" print "Check that the authentication worked correctly" sys.exit(1) if assignee in people.people_by_bzmail: person = dict(people.people_by_bzmail[assignee]) else: person = None # kick bug out if days since comment check is on if options.days_since_comment != -1: # try to get last_comment by assignee & manager if person is not None: last_comment = get_last_assignee_comment(bug.comments, person) if 'manager' in person and person['manager'] is not None: manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0] manager = people.people[manager_email] last_manager_comment = get_last_manager_comment(bug.comments, people.people_by_bzmail[manager['bugzillaEmail']], person) # set last_comment to the most recent of last_assignee and last_manager if last_manager_comment is not None and last_comment is not None and last_manager_comment > last_comment: last_comment = last_manager_comment # otherwise just get the last comment else: last_comment = bug.comments[-1].creation_time.replace(tzinfo=None) if last_comment is not None: timedelta = datetime.now() - last_comment if timedelta.days <= int(options.days_since_comment): if options.verbose: print "Skipping bug %s since it's had an assignee or manager comment within the past %s days" % (bug.id, options.days_since_comment) send_mail = False counter = counter - 1 manual_notify[query]['bugs'].remove(bug) else: if options.verbose: print "This bug needs notification, it's been %s since last comment of note" % timedelta.days if send_mail: if 'nobody' in assignee: if options.verbose: print "No one assigned to: %s, will be in the manual notification list..." % bug.id # TODO - get rid of this, SUCH A HACK! elif '[email protected]' in assignee: if options.verbose: print "No one assigned to JS bug: %s, adding to Naveed's list..." % bug.id add_to_managers('[email protected]', query, info) else: if bug.assigned_to.real_name is not None: if person is not None: # check if assignee is already a manager, add to their own list if 'mozillaMail' in managers: add_to_managers(person['mozillaMail'], query, info) # otherwise we search for the assignee's manager else: # check for manager key first, a few people don't have them if 'manager' in person and person['manager'] is not None: manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0] if manager_email in managers: add_to_managers(manager_email, query, info) elif manager_email in people.vices: # we're already at the highest level we'll go if assignee in managers: add_to_managers(assignee, query, info) else: if options.verbose: print "%s has a V-level for a manager, and is not in the manager list" % assignee managers[person['mozillaMail']] = {} add_to_managers(person['mozillaMail'], query, info) else: # try to go up one level and see if we find a manager if manager_email in people.people: person = dict(people.people[manager_email]) manager_email = person['manager']['dn'].split('mail=')[1].split(',')[0] if manager_email in managers: add_to_managers(manager_email, query, info) else: print "Manager could not be found: %s" % manager_email # if you don't have a manager listed, but are an employee, we'll nag you anyway else: add_to_managers(person['mozillaMail'], query, info) print "%s's entry doesn't list a manager! Let's ask them to update phonebook but in the meantime they get the email directly." % person['name'] if options.roll_up: # only send one email toaddrs, msg = generateEmailOutput(subject=options.email_subject, queries=manual_notify, template=options.template, people=people, show_comment=options.show_comment, rollup=options.roll_up, rollupEmail=options.email_cc_list) if options.email_password is None or options.mozilla_mail is None: print "Please supply a username/password (-m, -p) for sending email" sys.exit(1) if not options.dryrun: print "SENDING EMAIL" sendMail(toaddrs, msg, options.mozilla_mail, options.email_password, options.dryrun) else: # Get yr nag on! for email, info in managers.items(): inp = '' if 'nagging' in info: toaddrs, msg = generateEmailOutput( subject=options.email_subject, manager_email=email, queries=info['nagging'], people=people, template=options.template, show_comment=options.show_comment) while True and not options.no_verification: print "\nRelMan Nag is ready to send the following email:\n<------ MESSAGE BELOW -------->" print msg print "<------- END MESSAGE -------->\nWould you like to send now?" inp = raw_input('\n Please select y/Y to send, v/V to edit, or n/N to skip and continue to next email: ') if inp != 'v' and inp != 'V': break tempfilename = tempfile.mktemp() temp_file = open(tempfilename, 'w') temp_file.write(msg) temp_file.close() subprocess.call(['vi', tempfilename]) temp_file = open(tempfilename, 'r') msg = temp_file.read() toaddrs = msg.split("To: ")[1].split("\r\n")[0].split(',') + msg.split("CC: ")[1].split("\r\n")[0].split(',') os.remove(tempfilename) if inp == 'y' or inp == 'Y' or options.no_verification: if options.email_password is None or options.mozilla_mail is None: print "Please supply a username/password (-m, -p) for sending email" sys.exit(1) if not options.dryrun: print "SENDING EMAIL" sendMail(toaddrs, msg, options.mozilla_mail, options.email_password, options.dryrun) sent_bugs = 0 for query, info in info['nagging'].items(): sent_bugs += len(info['bugs']) # take sent bugs out of manual notification list for bug in info['bugs']: manual_notify[query]['bugs'].remove(bug) counter = counter - sent_bugs if not options.roll_up: emailed_bugs = [] # Send RelMan the manual notification list only when there are bugs that didn't go out msg_body = """\n******************************************\nNo nag emails were generated for these bugs because they are either assigned to no one or to non-employees (though ni? on non-employees will get nagged). \nYou will need to look at the following bugs:\n******************************************\n\n""" for k, v in manual_notify.items(): if len(v['bugs']) != 0: for bug in v['bugs']: if bug.id not in emailed_bugs: if k not in msg_body: msg_body += "\n=== %s ===\n" % k emailed_bugs.append(bug.id) msg_body += "http://bugzil.la/" + "%s -- assigned to: %s\n -- Last commented on: %s\n" % (bug.id, bug.assigned_to.real_name, bug.comments[-1].creation_time.replace(tzinfo=None)) msg = ("From: %s\r\n" % REPLY_TO_EMAIL + "To: %s\r\n" % REPLY_TO_EMAIL + "Subject: RelMan Attention Needed: %s\r\n" % options.email_subject + "\r\n" + msg_body) sendMail(['[email protected]'], msg, options.mozilla_mail, options.email_password, options.dryrun)<|fim▁end|>
parser.add_argument("-e", "--email-cc-list", dest="email_cc_list", action="append", help="email addresses to include in cc when sending mail") parser.add_argument("-q", "--query", dest="queries",
<|file_name|>CT_When.go<|end_file_name|><|fim▁begin|>// Copyright 2017 Baliance. All rights reserved. // // DO NOT EDIT: generated by gooxml ECMA-376 generator // // Use of this source code is governed by the terms of the Affero GNU General // Public License version 3.0 as published by the Free Software Foundation and // appearing in the file LICENSE included in the packaging of this file. A // commercial license can be purchased by contacting [email protected]. package diagram import ( "encoding/xml" "fmt" "log" "baliance.com/gooxml/schema/soo/dml" ) type CT_When struct { NameAttr *string FuncAttr ST_FunctionType ArgAttr *ST_FunctionArgument OpAttr ST_FunctionOperator ValAttr ST_FunctionValue Alg []*CT_Algorithm Shape []*CT_Shape PresOf []*CT_PresentationOf ConstrLst []*CT_Constraints RuleLst []*CT_Rules ForEach []*CT_ForEach LayoutNode []*CT_LayoutNode Choose []*CT_Choose ExtLst []*dml.CT_OfficeArtExtensionList AxisAttr *ST_AxisTypes PtTypeAttr *ST_ElementTypes HideLastTransAttr *ST_Booleans StAttr *ST_Ints CntAttr *ST_UnsignedInts StepAttr *ST_Ints } func NewCT_When() *CT_When { ret := &CT_When{} ret.FuncAttr = ST_FunctionType(1) ret.OpAttr = ST_FunctionOperator(1) return ret } func (m *CT_When) MarshalXML(e *xml.Encoder, start xml.StartElement) error { if m.NameAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "name"}, Value: fmt.Sprintf("%v", *m.NameAttr)}) } attr, err := m.FuncAttr.MarshalXMLAttr(xml.Name{Local: "func"}) if err != nil { return err } start.Attr = append(start.Attr, attr) if m.ArgAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "arg"}, Value: fmt.Sprintf("%v", *m.ArgAttr)}) } attr, err = m.OpAttr.MarshalXMLAttr(xml.Name{Local: "op"}) if err != nil { return err } start.Attr = append(start.Attr, attr) start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "val"}, Value: fmt.Sprintf("%v", m.ValAttr)}) if m.AxisAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "axis"}, Value: fmt.Sprintf("%v", *m.AxisAttr)}) } if m.PtTypeAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "ptType"}, Value: fmt.Sprintf("%v", *m.PtTypeAttr)}) } if m.HideLastTransAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "hideLastTrans"}, Value: fmt.Sprintf("%v", *m.HideLastTransAttr)}) } if m.StAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "st"}, Value: fmt.Sprintf("%v", *m.StAttr)}) } if m.CntAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "cnt"}, Value: fmt.Sprintf("%v", *m.CntAttr)}) } if m.StepAttr != nil { start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "step"}, Value: fmt.Sprintf("%v", *m.StepAttr)}) } e.EncodeToken(start) if m.Alg != nil { sealg := xml.StartElement{Name: xml.Name{Local: "alg"}} for _, c := range m.Alg { e.EncodeElement(c, sealg) } } if m.Shape != nil { seshape := xml.StartElement{Name: xml.Name{Local: "shape"}} for _, c := range m.Shape { e.EncodeElement(c, seshape) } } if m.PresOf != nil { sepresOf := xml.StartElement{Name: xml.Name{Local: "presOf"}} for _, c := range m.PresOf { e.EncodeElement(c, sepresOf) } } if m.ConstrLst != nil { seconstrLst := xml.StartElement{Name: xml.Name{Local: "constrLst"}} for _, c := range m.ConstrLst { e.EncodeElement(c, seconstrLst) } } if m.RuleLst != nil { seruleLst := xml.StartElement{Name: xml.Name{Local: "ruleLst"}} for _, c := range m.RuleLst { e.EncodeElement(c, seruleLst) } } if m.ForEach != nil { seforEach := xml.StartElement{Name: xml.Name{Local: "forEach"}} for _, c := range m.ForEach { e.EncodeElement(c, seforEach) } } if m.LayoutNode != nil { selayoutNode := xml.StartElement{Name: xml.Name{Local: "layoutNode"}} for _, c := range m.LayoutNode { e.EncodeElement(c, selayoutNode) } } if m.Choose != nil { sechoose := xml.StartElement{Name: xml.Name{Local: "choose"}} for _, c := range m.Choose { e.EncodeElement(c, sechoose) } } if m.ExtLst != nil { seextLst := xml.StartElement{Name: xml.Name{Local: "extLst"}} for _, c := range m.ExtLst { e.EncodeElement(c, seextLst) } } e.EncodeToken(xml.EndElement{Name: start.Name}) return nil } func (m *CT_When) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { // initialize to default m.FuncAttr = ST_FunctionType(1) m.OpAttr = ST_FunctionOperator(1) for _, attr := range start.Attr { if attr.Name.Local == "name" { parsed, err := attr.Value, error(nil) if err != nil { return err } m.NameAttr = &parsed } if attr.Name.Local == "func" { m.FuncAttr.UnmarshalXMLAttr(attr) } if attr.Name.Local == "arg" { parsed, err := ParseUnionST_FunctionArgument(attr.Value) if err != nil { return err } m.ArgAttr = &parsed } if attr.Name.Local == "op" { m.OpAttr.UnmarshalXMLAttr(attr) } if attr.Name.Local == "val" { parsed, err := ParseUnionST_FunctionValue(attr.Value) if err != nil { return err } m.ValAttr = parsed } if attr.Name.Local == "axis" { parsed, err := ParseSliceST_AxisTypes(attr.Value) if err != nil { return err } m.AxisAttr = &parsed } if attr.Name.Local == "ptType" { parsed, err := ParseSliceST_ElementTypes(attr.Value) if err != nil { return err } m.PtTypeAttr = &parsed } if attr.Name.Local == "hideLastTrans" { parsed, err := ParseSliceST_Booleans(attr.Value) if err != nil { return err } m.HideLastTransAttr = &parsed } if attr.Name.Local == "st" { parsed, err := ParseSliceST_Ints(attr.Value) if err != nil { return err } m.StAttr = &parsed } if attr.Name.Local == "cnt" { parsed, err := ParseSliceST_UnsignedInts(attr.Value) if err != nil { return err } m.CntAttr = &parsed } if attr.Name.Local == "step" { parsed, err := ParseSliceST_Ints(attr.Value) if err != nil { return err } m.StepAttr = &parsed } } lCT_When: for { tok, err := d.Token() if err != nil { return err } switch el := tok.(type) { case xml.StartElement: switch el.Name { case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "alg"}: tmp := NewCT_Algorithm() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.Alg = append(m.Alg, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "shape"}: tmp := NewCT_Shape() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.Shape = append(m.Shape, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "presOf"}: tmp := NewCT_PresentationOf() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.PresOf = append(m.PresOf, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "constrLst"}: tmp := NewCT_Constraints() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.ConstrLst = append(m.ConstrLst, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "ruleLst"}: tmp := NewCT_Rules() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.RuleLst = append(m.RuleLst, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "forEach"}: tmp := NewCT_ForEach() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.ForEach = append(m.ForEach, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "layoutNode"}: tmp := NewCT_LayoutNode() if err := d.DecodeElement(tmp, &el); err != nil { return err }<|fim▁hole|> if err := d.DecodeElement(tmp, &el); err != nil { return err } m.Choose = append(m.Choose, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "extLst"}: tmp := dml.NewCT_OfficeArtExtensionList() if err := d.DecodeElement(tmp, &el); err != nil { return err } m.ExtLst = append(m.ExtLst, tmp) default: log.Printf("skipping unsupported element on CT_When %v", el.Name) if err := d.Skip(); err != nil { return err } } case xml.EndElement: break lCT_When case xml.CharData: } } return nil } // Validate validates the CT_When and its children func (m *CT_When) Validate() error { return m.ValidateWithPath("CT_When") } // ValidateWithPath validates the CT_When and its children, prefixing error messages with path func (m *CT_When) ValidateWithPath(path string) error { if m.FuncAttr == ST_FunctionTypeUnset { return fmt.Errorf("%s/FuncAttr is a mandatory field", path) } if err := m.FuncAttr.ValidateWithPath(path + "/FuncAttr"); err != nil { return err } if m.ArgAttr != nil { if err := m.ArgAttr.ValidateWithPath(path + "/ArgAttr"); err != nil { return err } } if m.OpAttr == ST_FunctionOperatorUnset { return fmt.Errorf("%s/OpAttr is a mandatory field", path) } if err := m.OpAttr.ValidateWithPath(path + "/OpAttr"); err != nil { return err } if err := m.ValAttr.ValidateWithPath(path + "/ValAttr"); err != nil { return err } for i, v := range m.Alg { if err := v.ValidateWithPath(fmt.Sprintf("%s/Alg[%d]", path, i)); err != nil { return err } } for i, v := range m.Shape { if err := v.ValidateWithPath(fmt.Sprintf("%s/Shape[%d]", path, i)); err != nil { return err } } for i, v := range m.PresOf { if err := v.ValidateWithPath(fmt.Sprintf("%s/PresOf[%d]", path, i)); err != nil { return err } } for i, v := range m.ConstrLst { if err := v.ValidateWithPath(fmt.Sprintf("%s/ConstrLst[%d]", path, i)); err != nil { return err } } for i, v := range m.RuleLst { if err := v.ValidateWithPath(fmt.Sprintf("%s/RuleLst[%d]", path, i)); err != nil { return err } } for i, v := range m.ForEach { if err := v.ValidateWithPath(fmt.Sprintf("%s/ForEach[%d]", path, i)); err != nil { return err } } for i, v := range m.LayoutNode { if err := v.ValidateWithPath(fmt.Sprintf("%s/LayoutNode[%d]", path, i)); err != nil { return err } } for i, v := range m.Choose { if err := v.ValidateWithPath(fmt.Sprintf("%s/Choose[%d]", path, i)); err != nil { return err } } for i, v := range m.ExtLst { if err := v.ValidateWithPath(fmt.Sprintf("%s/ExtLst[%d]", path, i)); err != nil { return err } } return nil }<|fim▁end|>
m.LayoutNode = append(m.LayoutNode, tmp) case xml.Name{Space: "http://schemas.openxmlformats.org/drawingml/2006/diagram", Local: "choose"}: tmp := NewCT_Choose()
<|file_name|>api.go<|end_file_name|><|fim▁begin|>package ram /* ringtail 2016/1/19 All RAM apis provided */ type RamClientInterface interface { //ram user CreateUser(user UserRequest) (UserResponse, error) GetUser(userQuery UserQueryRequest) (UserResponse, error) UpdateUser(newUser UpdateUserRequest) (UserResponse, error) DeleteUser(userQuery UserQueryRequest) (RamCommonResponse, error) ListUsers(listParams ListUserRequest) (ListUserResponse, error) //ram login profile CreateLoginProfile(req ProfileRequest) (ProfileResponse, error) GetLoginProfile(req UserQueryRequest) (ProfileResponse, error) DeleteLoginProfile(req UserQueryRequest) (RamCommonResponse, error) UpdateLoginProfile(req ProfileRequest) (ProfileResponse, error) //ram ak CreateAccessKey(userQuery UserQueryRequest) (AccessKeyResponse, error) UpdateAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) DeleteAccessKey(accessKeyRequest UpdateAccessKeyRequest) (RamCommonResponse, error) ListAccessKeys(userQuery UserQueryRequest) (AccessKeyListResponse, error) //ram mfa CreateVirtualMFADevice(req MFARequest) (MFAResponse, error) ListVirtualMFADevices() (MFAListResponse, error) DeleteVirtualMFADevice(req MFADeleteRequest) (RamCommonResponse, error) BindMFADevice(req MFABindRequest) (RamCommonResponse, error) UnbindMFADevice(req UserQueryRequest) (MFAUserResponse, error) GetUserMFAInfo(req UserQueryRequest) (MFAUserResponse, error) //ram group CreateGroup(req GroupRequest) (GroupResponse, error) GetGroup(req GroupQueryRequest) (GroupResponse, error) UpdateGroup(req GroupUpdateRequest) (GroupResponse, error) ListGroup(req GroupListRequest) (GroupListResponse, error) DeleteGroup(req GroupQueryRequest) (RamCommonResponse, error) AddUserToGroup(req UserRelateGroupRequest) (RamCommonResponse, error) RemoveUserFromGroup(req UserRelateGroupRequest) (RamCommonResponse, error) ListGroupsForUser(req UserQueryRequest) (GroupListResponse, error) ListUsersForGroup(req GroupQueryRequest) (ListUserResponse, error) CreateRole(role RoleRequest) (RoleResponse, error) GetRole(roleQuery RoleQueryRequest) (RoleResponse, error) UpdateRole(newRole UpdateRoleRequest) (RoleResponse, error) ListRoles() (ListRoleResponse, error) DeleteRole(roleQuery RoleQueryRequest) (RamCommonResponse, error) //DONE policy CreatePolicy(policyReq PolicyRequest) (PolicyResponse, error) GetPolicy(policyReq PolicyRequest) (PolicyResponse, error) DeletePolicy(policyReq PolicyRequest) (RamCommonResponse, error) ListPolicies(policyQuery PolicyQueryRequest) (PolicyQueryResponse, error) ListPoliciesForUser(userQuery UserQueryRequest) (PolicyListResponse, error) //ram policy version CreatePolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) GetPolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) GetPolicyVersionNew(policyReq PolicyRequest) (PolicyVersionResponseNew, error) DeletePolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) ListPolicyVersions(policyReq PolicyRequest) (PolicyVersionResponse, error) ListPolicyVersionsNew(policyReq PolicyRequest) (PolicyVersionsResponse, error) AttachPolicyToUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) DetachPolicyFromUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) ListEntitiesForPolicy(policyReq PolicyRequest) (PolicyListEntitiesResponse, error) SetDefaultPolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) ListPoliciesForGroup(groupQuery GroupQueryRequest) (PolicyListResponse, error) AttachPolicyToGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) DetachPolicyFromGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) AttachPolicyToRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) DetachPolicyFromRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) ListPoliciesForRole(roleQuery RoleQueryRequest) (PolicyListResponse, error) //ram security SetAccountAlias(accountAlias AccountAliasRequest) (RamCommonResponse, error) GetAccountAlias() (AccountAliasResponse, error) ClearAccountAlias() (RamCommonResponse, error)<|fim▁hole|> GetPasswordPolicy() (PasswordPolicyResponse, error) // Common Client Methods SetUserAgent(userAgent string) }<|fim▁end|>
SetPasswordPolicy(passwordPolicy PasswordPolicyRequest) (PasswordPolicyResponse, error)
<|file_name|>future.py<|end_file_name|><|fim▁begin|><|fim▁hole|> class FuturePricer(EquityPricer): def __init__(self): super(FuturePricer,self).__init__()<|fim▁end|>
from equity import EquityPricer
<|file_name|>namespace.py<|end_file_name|><|fim▁begin|><|fim▁hole|>LEXINFO = Namespace("http://www.lexinfo.net/ontology/2.0/lexinfo#") DECOMP = Namespace("http://www.w3.org/ns/lemon/decomp#") ISOCAT = Namespace("http://www.isocat.org/datcat/") LIME = Namespace("http://www.w3.org/ns/lemon/lime#")<|fim▁end|>
# -*- coding: utf-8 -*- from rdflib import Namespace ONTOLEX = Namespace("http://www.w3.org/ns/lemon/ontolex#")
<|file_name|>xmlgen.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************** * * Copyright (C) 1997-2013 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #include <stdlib.h> #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <qintdict.h> #include "xmlgen.h" #include "doxygen.h" #include "message.h" #include "config.h" #include "classlist.h" #include "util.h" #include "defargs.h" #include "outputgen.h" #include "dot.h" #include "pagedef.h" #include "filename.h" #include "version.h" #include "xmldocvisitor.h" #include "docparser.h" #include "language.h" #include "parserintf.h" #include "arguments.h" #include "memberlist.h" #include "groupdef.h" #include "memberdef.h" #include "namespacedef.h" #include "membername.h" #include "membergroup.h" #include "dirdef.h" #include "section.h" // no debug info #define XML_DB(x) do {} while(0) // debug to stdout //#define XML_DB(x) printf x // debug inside output //#define XML_DB(x) QCString __t;__t.sprintf x;m_t << __t //------------------ static const char index_xsd[] = #include "index_xsd.h" ; //------------------ // static const char compound_xsd[] = #include "compound_xsd.h" ; //------------------ /** Helper class mapping MemberList::ListType to a string representing */ class XmlSectionMapper : public QIntDict<char> { public: XmlSectionMapper() : QIntDict<char>(47) { insert(MemberListType_pubTypes,"public-type"); insert(MemberListType_pubMethods,"public-func"); insert(MemberListType_pubAttribs,"public-attrib"); insert(MemberListType_pubSlots,"public-slot"); insert(MemberListType_signals,"signal"); insert(MemberListType_dcopMethods,"dcop-func"); insert(MemberListType_properties,"property"); insert(MemberListType_events,"event"); insert(MemberListType_pubStaticMethods,"public-static-func"); insert(MemberListType_pubStaticAttribs,"public-static-attrib"); insert(MemberListType_proTypes,"protected-type"); insert(MemberListType_proMethods,"protected-func"); insert(MemberListType_proAttribs,"protected-attrib"); insert(MemberListType_proSlots,"protected-slot"); insert(MemberListType_proStaticMethods,"protected-static-func"); insert(MemberListType_proStaticAttribs,"protected-static-attrib"); insert(MemberListType_pacTypes,"package-type"); insert(MemberListType_pacMethods,"package-func"); insert(MemberListType_pacAttribs,"package-attrib"); insert(MemberListType_pacStaticMethods,"package-static-func"); insert(MemberListType_pacStaticAttribs,"package-static-attrib"); insert(MemberListType_priTypes,"private-type"); insert(MemberListType_priMethods,"private-func"); insert(MemberListType_priAttribs,"private-attrib"); insert(MemberListType_priSlots,"private-slot"); insert(MemberListType_priStaticMethods,"private-static-func"); insert(MemberListType_priStaticAttribs,"private-static-attrib"); insert(MemberListType_friends,"friend"); insert(MemberListType_related,"related"); insert(MemberListType_decDefineMembers,"define"); insert(MemberListType_decProtoMembers,"prototype"); insert(MemberListType_decTypedefMembers,"typedef"); insert(MemberListType_decEnumMembers,"enum"); insert(MemberListType_decFuncMembers,"func"); insert(MemberListType_decVarMembers,"var"); } }; static XmlSectionMapper g_xmlSectionMapper; inline void writeXMLString(FTextStream &t,const char *s) { t << convertToXML(s); } inline void writeXMLCodeString(FTextStream &t,const char *s, int &col) { char c; while ((c=*s++)) { switch(c) { case '\t': { static int tabSize = Config_getInt("TAB_SIZE"); int spacesToNextTabStop = tabSize - (col%tabSize); col+=spacesToNextTabStop; while (spacesToNextTabStop--) t << "<sp/>"; break; } case ' ': t << "<sp/>"; col++; break; case '<': t << "&lt;"; col++; break; case '>': t << "&gt;"; col++; break; case '&': t << "&amp;"; col++; break; case '\'': t << "&apos;"; col++; break; case '"': t << "&quot;"; col++; break; default: t << c; col++; break; } } } static void writeXMLHeader(FTextStream &t) { t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;; t << "<doxygen xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; t << "xsi:noNamespaceSchemaLocation=\"compound.xsd\" "; t << "version=\"" << versionString << "\">" << endl; } static void writeCombineScript() { QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/combine.xslt"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); t << "<!-- XSLT script to combine the generated output into a single file. \n" " If you have xsltproc you could use:\n" " xsltproc combine.xslt index.xml >all.xml\n" "-->\n" "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n" " <xsl:output method=\"xml\" version=\"1.0\" indent=\"no\" standalone=\"yes\" />\n" " <xsl:template match=\"/\">\n" " <doxygen version=\"{doxygenindex/@version}\">\n" " <!-- Load all doxgen generated xml files -->\n" " <xsl:for-each select=\"doxygenindex/compound\">\n" " <xsl:copy-of select=\"document( concat( @refid, '.xml' ) )/doxygen/*\" />\n" " </xsl:for-each>\n" " </doxygen>\n" " </xsl:template>\n" "</xsl:stylesheet>\n"; } void writeXMLLink(FTextStream &t,const char *extRef,const char *compoundId, const char *anchorId,const char *text,const char *tooltip) { t << "<ref refid=\"" << compoundId; if (anchorId) t << "_1" << anchorId; t << "\" kindref=\""; if (anchorId) t << "member"; else t << "compound"; t << "\""; if (extRef) t << " external=\"" << extRef << "\""; if (tooltip) t << " tooltip=\"" << convertToXML(tooltip) << "\""; t << ">"; writeXMLString(t,text); t << "</ref>"; } /** Implements TextGeneratorIntf for an XML stream. */ class TextGeneratorXMLImpl : public TextGeneratorIntf { public: TextGeneratorXMLImpl(FTextStream &t): m_t(t) {} void writeString(const char *s,bool /*keepSpaces*/) const { writeXMLString(m_t,s); } void writeBreak(int) const {} void writeLink(const char *extRef,const char *file, const char *anchor,const char *text ) const { writeXMLLink(m_t,extRef,file,anchor,text,0); } private: FTextStream &m_t; }; /** Helper class representing a stack of objects stored by value */ template<class T> class ValStack { public: ValStack() : m_values(10), m_sp(0), m_size(10) {} virtual ~ValStack() {} ValStack(const ValStack<T> &s) { m_values=s.m_values.copy(); m_sp=s.m_sp; m_size=s.m_size; } ValStack &operator=(const ValStack<T> &s) { m_values=s.m_values.copy(); m_sp=s.m_sp; m_size=s.m_size; return *this; } void push(T v) { m_sp++; if (m_sp>=m_size) { m_size+=10; m_values.resize(m_size); } m_values[m_sp]=v; } T pop() { ASSERT(m_sp!=0); return m_values[m_sp--]; } T& top() { ASSERT(m_sp!=0); return m_values[m_sp]; } bool isEmpty() { return m_sp==0; } uint count() const { return m_sp; } private: QArray<T> m_values; int m_sp; int m_size; }; /** Generator for producing XML formatted source code. */ class XMLCodeGenerator : public CodeOutputInterface { public: XMLCodeGenerator(FTextStream &t) : m_t(t), m_lineNumber(-1), m_insideCodeLine(FALSE), m_normalHLNeedStartTag(TRUE), m_insideSpecialHL(FALSE) {} virtual ~XMLCodeGenerator() { } void codify(const char *text) { XML_DB(("(codify \"%s\")\n",text)); if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag) { m_t << "<highlight class=\"normal\">"; m_normalHLNeedStartTag=FALSE; } writeXMLCodeString(m_t,text,col); } void writeCodeLink(const char *ref,const char *file, const char *anchor,const char *name, const char *tooltip) { XML_DB(("(writeCodeLink)\n")); if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag) { m_t << "<highlight class=\"normal\">"; m_normalHLNeedStartTag=FALSE; } writeXMLLink(m_t,ref,file,anchor,name,tooltip); col+=qstrlen(name); } void startCodeLine(bool) { XML_DB(("(startCodeLine)\n")); m_t << "<codeline"; if (m_lineNumber!=-1) { m_t << " lineno=\"" << m_lineNumber << "\""; if (!m_refId.isEmpty()) { m_t << " refid=\"" << m_refId << "\""; if (m_isMemberRef) { m_t << " refkind=\"member\""; } else { m_t << " refkind=\"compound\""; } } if (!m_external.isEmpty()) { m_t << " external=\"" << m_external << "\""; } } m_t << ">"; m_insideCodeLine=TRUE; col=0; } void endCodeLine() { XML_DB(("(endCodeLine)\n")); if (!m_insideSpecialHL && !m_normalHLNeedStartTag) { m_t << "</highlight>"; m_normalHLNeedStartTag=TRUE; } m_t << "</codeline>" << endl; // non DocBook m_lineNumber = -1; m_refId.resize(0); m_external.resize(0); m_insideCodeLine=FALSE; } void startCodeAnchor(const char *id) { XML_DB(("(startCodeAnchor)\n")); if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag) { m_t << "<highlight class=\"normal\">"; m_normalHLNeedStartTag=FALSE; } m_t << "<anchor id=\"" << id << "\">"; } void endCodeAnchor() { XML_DB(("(endCodeAnchor)\n")); m_t << "</anchor>"; } void startFontClass(const char *colorClass) { XML_DB(("(startFontClass)\n")); if (m_insideCodeLine && !m_insideSpecialHL && !m_normalHLNeedStartTag) { m_t << "</highlight>"; m_normalHLNeedStartTag=TRUE; } m_t << "<highlight class=\"" << colorClass << "\">"; // non DocBook m_insideSpecialHL=TRUE; } void endFontClass() { XML_DB(("(endFontClass)\n")); m_t << "</highlight>"; // non DocBook m_insideSpecialHL=FALSE; } void writeCodeAnchor(const char *) { XML_DB(("(writeCodeAnchor)\n")); } void writeLineNumber(const char *extRef,const char *compId, const char *anchorId,int l) { XML_DB(("(writeLineNumber)\n")); // we remember the information provided here to use it // at the <codeline> start tag. m_lineNumber = l; if (compId) { m_refId=compId; if (anchorId) m_refId+=(QCString)"_1"+anchorId; m_isMemberRef = anchorId!=0; if (extRef) m_external=extRef; } } void linkableSymbol(int, const char *,Definition *,Definition *) { } void setCurrentDoc(Definition *,const char *,bool) { } void addWord(const char *,bool) { } void finish() { if (m_insideCodeLine) endCodeLine(); } private: FTextStream &m_t; QCString m_refId; QCString m_external; int m_lineNumber; bool m_isMemberRef; int col; bool m_insideCodeLine; bool m_normalHLNeedStartTag; bool m_insideSpecialHL; }; static void writeTemplateArgumentList(ArgumentList *al, FTextStream &t, Definition *scope, FileDef *fileScope, int indent) { QCString indentStr; indentStr.fill(' ',indent); if (al) { t << indentStr << "<templateparamlist>" << endl; ArgumentListIterator ali(*al); Argument *a; for (ali.toFirst();(a=ali.current());++ali) { t << indentStr << " <param>" << endl; if (!a->type.isEmpty()) { t << indentStr << " <type>"; linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->type); t << "</type>" << endl; } if (!a->name.isEmpty()) { t << indentStr << " <declname>" << a->name << "</declname>" << endl; t << indentStr << " <defname>" << a->name << "</defname>" << endl; } if (!a->defval.isEmpty()) { t << indentStr << " <defval>"; linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->defval); t << "</defval>" << endl; } t << indentStr << " </param>" << endl; } t << indentStr << "</templateparamlist>" << endl; } } static void writeMemberTemplateLists(MemberDef *md,FTextStream &t) { LockingPtr<ArgumentList> templMd = md->templateArguments(); if (templMd!=0) // function template prefix { writeTemplateArgumentList(templMd.pointer(),t,md->getClassDef(),md->getFileDef(),8); } } static void writeTemplateList(ClassDef *cd,FTextStream &t) { writeTemplateArgumentList(cd->templateArguments(),t,cd,0,4); } static void writeXMLDocBlock(FTextStream &t, const QCString &fileName, int lineNr, Definition *scope, MemberDef * md, const QCString &text) { QCString stext = text.stripWhiteSpace(); if (stext.isEmpty()) return; // convert the documentation string into an abstract syntax tree DocNode *root = validatingParseDoc(fileName,lineNr,scope,md,text+"\n",FALSE,FALSE); // create a code generator XMLCodeGenerator *xmlCodeGen = new XMLCodeGenerator(t); // create a parse tree visitor for XML XmlDocVisitor *visitor = new XmlDocVisitor(t,*xmlCodeGen); // visit all nodes root->accept(visitor); // clean up delete visitor; delete xmlCodeGen; delete root; } void writeXMLCodeBlock(FTextStream &t,FileDef *fd) { ParserInterface *pIntf=Doxygen::parserManager->getParser(fd->getDefFileExtension()); pIntf->resetCodeParserState(); XMLCodeGenerator *xmlGen = new XMLCodeGenerator(t); pIntf->parseCode(*xmlGen, // codeOutIntf 0, // scopeName fileToString(fd->absFilePath(),Config_getBool("FILTER_SOURCE_FILES")), FALSE, // isExampleBlock 0, // exampleName fd, // fileDef -1, // startLine -1, // endLine FALSE, // inlineFragement 0, // memberDef TRUE // showLineNumbers ); xmlGen->finish(); delete xmlGen; } static void writeMemberReference(FTextStream &t,Definition *def,MemberDef *rmd,const char *tagName) { QCString scope = rmd->getScopeString(); QCString name = rmd->name(); if (!scope.isEmpty() && scope!=def->name()) { name.prepend(scope+getLanguageSpecificSeparator(rmd->getLanguage())); } t << " <" << tagName << " refid=\""; t << rmd->getOutputFileBase() << "_1" << rmd->anchor() << "\""; if (rmd->getStartBodyLine()!=-1 && rmd->getBodyDef()) { t << " compoundref=\"" << rmd->getBodyDef()->getOutputFileBase() << "\""; t << " startline=\"" << rmd->getStartBodyLine() << "\""; if (rmd->getEndBodyLine()!=-1) { t << " endline=\"" << rmd->getEndBodyLine() << "\""; } } t << ">" << convertToXML(name) << "</" << tagName << ">" << endl; } static void stripQualifiers(QCString &typeStr) { bool done=FALSE; while (!done) { if (typeStr.stripPrefix("static ")); else if (typeStr.stripPrefix("virtual ")); else if (typeStr.stripPrefix("volatile ")); else if (typeStr=="virtual") typeStr=""; else done=TRUE; } } static QCString classOutputFileBase(ClassDef *cd) { //static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES"); //if (inlineGroupedClasses && cd->partOfGroups()!=0) return cd->getOutputFileBase(); //else // return cd->getOutputFileBase(); } static QCString memberOutputFileBase(MemberDef *md) { //static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES"); //if (inlineGroupedClasses && md->getClassDef() && md->getClassDef()->partOfGroups()!=0) // return md->getClassDef()->getXmlOutputFileBase(); //else // return md->getOutputFileBase(); return md->getOutputFileBase(); } static void generateXMLForMember(MemberDef *md,FTextStream &ti,FTextStream &t,Definition *def) { // + declaration/definition arg lists // + reimplements // + reimplementedBy // + exceptions // + const/volatile specifiers // - examples // + source definition // + source references // + source referenced by // - body code // + template arguments // (templateArguments(), definitionTemplateParameterLists()) // - call graph // enum values are written as part of the enum if (md->memberType()==MemberType_EnumValue) return; if (md->isHidden()) return; //if (md->name().at(0)=='@') return; // anonymous member // group members are only visible in their group //if (def->definitionType()!=Definition::TypeGroup && md->getGroupDef()) return; QCString memType; bool isFunc=FALSE; switch (md->memberType()) { case MemberType_Define: memType="define"; break; case MemberType_EnumValue: ASSERT(0); break; case MemberType_Property: memType="property"; break; case MemberType_Event: memType="event"; break; case MemberType_Variable: memType="variable"; break; case MemberType_Typedef: memType="typedef"; break; case MemberType_Enumeration: memType="enum"; break; case MemberType_Function: memType="function"; isFunc=TRUE; break; case MemberType_Signal: memType="signal"; isFunc=TRUE; break; case MemberType_Friend: memType="friend"; isFunc=TRUE; break; case MemberType_DCOP: memType="dcop"; isFunc=TRUE; break; case MemberType_Slot: memType="slot"; isFunc=TRUE; break; } ti << " <member refid=\"" << memberOutputFileBase(md) << "_1" << md->anchor() << "\" kind=\"" << memType << "\"><name>" << convertToXML(md->name()) << "</name></member>" << endl; QCString scopeName; if (md->getClassDef()) scopeName=md->getClassDef()->name(); else if (md->getNamespaceDef()) scopeName=md->getNamespaceDef()->name(); t << " <memberdef kind=\""; //enum { define_t,variable_t,typedef_t,enum_t,function_t } xmlType = function_t; t << memType << "\" id=\""; if (md->getGroupDef() && def->definitionType()==Definition::TypeGroup) { t << md->getGroupDef()->getOutputFileBase(); } else { t << memberOutputFileBase(md); } t << "_1" // encoded `:' character (see util.cpp:convertNameToFile) << md->anchor(); t << "\" prot=\""; switch(md->protection()) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: t << "package"; break; } t << "\""; t << " static=\""; if (md->isStatic()) t << "yes"; else t << "no"; t << "\""; if (isFunc) { LockingPtr<ArgumentList> al = md->argumentList(); t << " const=\""; if (al!=0 && al->constSpecifier) t << "yes"; else t << "no"; t << "\""; t << " explicit=\""; if (md->isExplicit()) t << "yes"; else t << "no"; t << "\""; t << " inline=\""; if (md->isInline()) t << "yes"; else t << "no"; t << "\""; if (md->isFinal()) { t << " final=\"yes\""; } if (md->isSealed()) { t << " sealed=\"yes\""; } if (md->isNew()) { t << " new=\"yes\""; } if (md->isOptional()) { t << " optional=\"yes\""; } if (md->isRequired()) { t << " required=\"yes\""; } t << " virt=\""; switch (md->virtualness()) { case Normal: t << "non-virtual"; break; case Virtual: t << "virtual"; break; case Pure: t << "pure-virtual"; break; default: ASSERT(0); } t << "\""; } if (md->memberType() == MemberType_Variable) { //ArgumentList *al = md->argumentList(); //t << " volatile=\""; //if (al && al->volatileSpecifier) t << "yes"; else t << "no"; t << " mutable=\""; if (md->isMutable()) t << "yes"; else t << "no"; t << "\""; if (md->isInitonly()) { t << " initonly=\"yes\""; } } else if (md->memberType() == MemberType_Property) { t << " readable=\""; if (md->isReadable()) t << "yes"; else t << "no"; t << "\""; t << " writable=\""; if (md->isWritable()) t << "yes"; else t << "no"; t << "\""; t << " gettable=\""; if (md->isGettable()) t << "yes"; else t << "no"; t << "\""; t << " settable=\""; if (md->isSettable()) t << "yes"; else t << "no"; t << "\""; if (md->isAssign() || md->isCopy() || md->isRetain() || md->isStrong() || md->isWeak()) { t << " accessor=\""; if (md->isAssign()) t << "assign"; else if (md->isCopy()) t << "copy"; else if (md->isRetain()) t << "retain"; else if (md->isStrong()) t << "strong"; else if (md->isWeak()) t << "weak"; t << "\""; } } else if (md->memberType() == MemberType_Event) { t << " add=\""; if (md->isAddable()) t << "yes"; else t << "no"; t << "\""; t << " remove=\""; if (md->isRemovable()) t << "yes"; else t << "no"; t << "\""; t << " raise=\""; if (md->isRaisable()) t << "yes"; else t << "no"; t << "\""; } t << ">" << endl; if (md->memberType()!=MemberType_Define && md->memberType()!=MemberType_Enumeration ) { if (md->memberType()!=MemberType_Typedef) { writeMemberTemplateLists(md,t); } QCString typeStr = md->typeString(); //replaceAnonymousScopes(md->typeString()); stripQualifiers(typeStr); t << " <type>"; linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,typeStr); t << "</type>" << endl; t << " <definition>" << convertToXML(md->definition()) << "</definition>" << endl; t << " <argsstring>" << convertToXML(md->argsString()) << "</argsstring>" << endl; } t << " <name>" << convertToXML(md->name()) << "</name>" << endl; if (md->memberType() == MemberType_Property) { if (md->isReadable()) t << " <read>" << convertToXML(md->getReadAccessor()) << "</read>" << endl; if (md->isWritable()) t << " <write>" << convertToXML(md->getWriteAccessor()) << "</write>" << endl; } if (md->memberType()==MemberType_Variable && md->bitfieldString()) { QCString bitfield = md->bitfieldString(); if (bitfield.at(0)==':') bitfield=bitfield.mid(1); t << " <bitfield>" << bitfield << "</bitfield>" << endl; } MemberDef *rmd = md->reimplements(); if (rmd) { t << " <reimplements refid=\"" << memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">" << convertToXML(rmd->name()) << "</reimplements>" << endl; } LockingPtr<MemberList> rbml = md->reimplementedBy(); if (rbml!=0) { MemberListIterator mli(*rbml); for (mli.toFirst();(rmd=mli.current());++mli) { t << " <reimplementedby refid=\"" << memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">" << convertToXML(rmd->name()) << "</reimplementedby>" << endl; } } if (isFunc) //function { LockingPtr<ArgumentList> declAl = md->declArgumentList(); LockingPtr<ArgumentList> defAl = md->argumentList(); if (declAl!=0 && declAl->count()>0) { ArgumentListIterator declAli(*declAl); ArgumentListIterator defAli(*defAl); Argument *a; for (declAli.toFirst();(a=declAli.current());++declAli) { Argument *defArg = defAli.current(); t << " <param>" << endl; if (!a->attrib.isEmpty()) { t << " <attributes>"; writeXMLString(t,a->attrib); t << "</attributes>" << endl; } if (!a->type.isEmpty()) { t << " <type>"; linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->type); t << "</type>" << endl; } if (!a->name.isEmpty()) { t << " <declname>"; writeXMLString(t,a->name); t << "</declname>" << endl; } if (defArg && !defArg->name.isEmpty() && defArg->name!=a->name) { t << " <defname>"; writeXMLString(t,defArg->name); t << "</defname>" << endl; } if (!a->array.isEmpty()) { t << " <array>"; writeXMLString(t,a->array); t << "</array>" << endl; } if (!a->defval.isEmpty()) { t << " <defval>"; linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->defval); t << "</defval>" << endl; } if (defArg && defArg->hasDocumentation()) { t << " <briefdescription>"; writeXMLDocBlock(t,md->getDefFileName(),md->getDefLine(), md->getOuterScope(),md,defArg->docs); t << "</briefdescription>" << endl; } t << " </param>" << endl; if (defArg) ++defAli; } } } else if (md->memberType()==MemberType_Define && md->argsString()) // define { if (md->argumentList()->count()==0) // special case for "foo()" to // disguish it from "foo". { t << " <param></param>" << endl; } else { ArgumentListIterator ali(*md->argumentList()); Argument *a; for (ali.toFirst();(a=ali.current());++ali) { t << " <param><defname>" << a->type << "</defname></param>" << endl; } } } // avoid that extremely large tables are written to the output. // todo: it's better to adhere to MAX_INITIALIZER_LINES. if (!md->initializer().isEmpty() && md->initializer().length()<2000) { t << " <initializer>"; linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->initializer()); t << "</initializer>" << endl; } if (md->excpString()) { t << " <exceptions>"; linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->excpString()); t << "</exceptions>" << endl; } if (md->memberType()==MemberType_Enumeration) // enum { LockingPtr<MemberList> enumFields = md->enumFieldList(); if (enumFields!=0) { MemberListIterator emli(*enumFields); MemberDef *emd; for (emli.toFirst();(emd=emli.current());++emli) { ti << " <member refid=\"" << memberOutputFileBase(emd) << "_1" << emd->anchor() << "\" kind=\"enumvalue\"><name>" << convertToXML(emd->name()) << "</name></member>" << endl; t << " <enumvalue id=\"" << memberOutputFileBase(emd) << "_1" << emd->anchor() << "\" prot=\""; switch (emd->protection()) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: t << "package"; break; } t << "\">" << endl; t << " <name>"; writeXMLString(t,emd->name()); t << "</name>" << endl; if (!emd->initializer().isEmpty()) { t << " <initializer>"; writeXMLString(t,emd->initializer()); t << "</initializer>" << endl; } t << " <briefdescription>" << endl; writeXMLDocBlock(t,emd->briefFile(),emd->briefLine(),emd->getOuterScope(),emd,emd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,emd->docFile(),emd->docLine(),emd->getOuterScope(),emd,emd->documentation()); t << " </detaileddescription>" << endl; t << " </enumvalue>" << endl; } } } t << " <briefdescription>" << endl; writeXMLDocBlock(t,md->briefFile(),md->briefLine(),md->getOuterScope(),md,md->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,md->docFile(),md->docLine(),md->getOuterScope(),md,md->documentation()); t << " </detaileddescription>" << endl; t << " <inbodydescription>" << endl; writeXMLDocBlock(t,md->docFile(),md->inbodyLine(),md->getOuterScope(),md,md->inbodyDocumentation()); t << " </inbodydescription>" << endl; if (md->getDefLine()!=-1) { t << " <location file=\"" << md->getDefFileName() << "\" line=\"" << md->getDefLine() << "\""; if (md->getStartBodyLine()!=-1) { FileDef *bodyDef = md->getBodyDef(); if (bodyDef) { t << " bodyfile=\"" << bodyDef->absFilePath() << "\""; } t << " bodystart=\"" << md->getStartBodyLine() << "\" bodyend=\"" << md->getEndBodyLine() << "\""; } t << "/>" << endl; } //printf("md->getReferencesMembers()=%p\n",md->getReferencesMembers()); LockingPtr<MemberSDict> mdict = md->getReferencesMembers(); if (mdict!=0) { MemberSDict::Iterator mdi(*mdict); MemberDef *rmd; for (mdi.toFirst();(rmd=mdi.current());++mdi) { writeMemberReference(t,def,rmd,"references"); } } mdict = md->getReferencedByMembers(); if (mdict!=0) { MemberSDict::Iterator mdi(*mdict); MemberDef *rmd; for (mdi.toFirst();(rmd=mdi.current());++mdi) { writeMemberReference(t,def,rmd,"referencedby"); } } t << " </memberdef>" << endl; } static void generateXMLSection(Definition *d,FTextStream &ti,FTextStream &t, MemberList *ml,const char *kind,const char *header=0, const char *documentation=0) { if (ml==0) return; MemberListIterator mli(*ml); MemberDef *md; int count=0; for (mli.toFirst();(md=mli.current());++mli) { // namespace members are also inserted in the file scope, but // to prevent this duplication in the XML output, we filter those here. if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0) { count++; } } if (count==0) return; // empty list t << " <sectiondef kind=\"" << kind << "\">" << endl; if (header) { t << " <header>" << convertToXML(header) << "</header>" << endl; } if (documentation) { t << " <description>"; writeXMLDocBlock(t,d->docFile(),d->docLine(),d,0,documentation); t << "</description>" << endl; } for (mli.toFirst();(md=mli.current());++mli) { // namespace members are also inserted in the file scope, but // to prevent this duplication in the XML output, we filter those here. if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0) { generateXMLForMember(md,ti,t,d); } } t << " </sectiondef>" << endl; } static void writeListOfAllMembers(ClassDef *cd,FTextStream &t) { t << " <listofallmembers>" << endl; if (cd->memberNameInfoSDict()) { MemberNameInfoSDict::Iterator mnii(*cd->memberNameInfoSDict()); MemberNameInfo *mni; for (mnii.toFirst();(mni=mnii.current());++mnii) { MemberNameInfoIterator mii(*mni); MemberInfo *mi; for (mii.toFirst();(mi=mii.current());++mii) { MemberDef *md=mi->memberDef; if (md->name().at(0)!='@') // skip anonymous members { Protection prot = mi->prot; Specifier virt=md->virtualness(); t << " <member refid=\"" << memberOutputFileBase(md) << "_1" << md->anchor() << "\" prot=\""; switch (prot) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: t << "package"; break; } t << "\" virt=\""; switch(virt) { case Normal: t << "non-virtual"; break; case Virtual: t << "virtual"; break; case Pure: t << "pure-virtual"; break; } t << "\""; if (!mi->ambiguityResolutionScope.isEmpty()) { t << " ambiguityscope=\"" << convertToXML(mi->ambiguityResolutionScope) << "\""; } t << "><scope>" << convertToXML(cd->name()) << "</scope><name>" << convertToXML(md->name()) << "</name></member>" << endl; } } } } t << " </listofallmembers>" << endl; } static void writeInnerClasses(const ClassSDict *cl,FTextStream &t) { if (cl) { ClassSDict::Iterator cli(*cl); ClassDef *cd; for (cli.toFirst();(cd=cli.current());++cli) { if (!cd->isHidden() && cd->name().find('@')==-1) // skip anonymous scopes { t << " <innerclass refid=\"" << classOutputFileBase(cd) << "\" prot=\""; switch(cd->protection()) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: t << "package"; break; } t << "\">" << convertToXML(cd->name()) << "</innerclass>" << endl; } } } } static void writeInnerNamespaces(const NamespaceSDict *nl,FTextStream &t) { if (nl) { NamespaceSDict::Iterator nli(*nl); NamespaceDef *nd; for (nli.toFirst();(nd=nli.current());++nli) { if (!nd->isHidden() && nd->name().find('@')==-1) // skip anonymouse scopes { t << " <innernamespace refid=\"" << nd->getOutputFileBase() << "\">" << convertToXML(nd->name()) << "</innernamespace>" << endl; } } } } static void writeInnerFiles(const FileList *fl,FTextStream &t) { if (fl) { QListIterator<FileDef> fli(*fl); FileDef *fd; for (fli.toFirst();(fd=fli.current());++fli) { t << " <innerfile refid=\"" << fd->getOutputFileBase() << "\">" << convertToXML(fd->name()) << "</innerfile>" << endl; } } } static void writeInnerPages(const PageSDict *pl,FTextStream &t) { if (pl) { PageSDict::Iterator pli(*pl); PageDef *pd; for (pli.toFirst();(pd=pli.current());++pli) { t << " <innerpage refid=\"" << pd->getOutputFileBase(); if (pd->getGroupDef()) { t << "_" << pd->name(); } t << "\">" << convertToXML(pd->title()) << "</innerpage>" << endl; } } } static void writeInnerGroups(const GroupList *gl,FTextStream &t) { if (gl) { GroupListIterator gli(*gl); GroupDef *sgd; for (gli.toFirst();(sgd=gli.current());++gli) { t << " <innergroup refid=\"" << sgd->getOutputFileBase() << "\">" << convertToXML(sgd->groupTitle()) << "</innergroup>" << endl; } } } static void writeInnerDirs(const DirList *dl,FTextStream &t) { if (dl) { QListIterator<DirDef> subdirs(*dl); DirDef *subdir; for (subdirs.toFirst();(subdir=subdirs.current());++subdirs) { t << " <innerdir refid=\"" << subdir->getOutputFileBase() << "\">" << convertToXML(subdir->displayName()) << "</innerdir>" << endl; } } } static void generateXMLForClass(ClassDef *cd,FTextStream &ti) { // + brief description // + detailed description // + template argument list(s) // - include file // + member groups // + inheritance diagram // + list of direct super classes // + list of direct sub classes // + list of inner classes // + collaboration diagram // + list of all members // + user defined member sections // + standard member sections // + detailed member documentation // - examples using the class if (cd->isReference()) return; // skip external references. if (cd->isHidden()) return; // skip hidden classes. if (cd->name().find('@')!=-1) return; // skip anonymous compounds. if (cd->templateMaster()!=0) return; // skip generated template instances. if (cd->isArtificial()) return; // skip artificially created classes msg("Generating XML output for class %s\n",cd->name().data()); ti << " <compound refid=\"" << classOutputFileBase(cd) << "\" kind=\"" << cd->compoundTypeString() << "\"><name>" << convertToXML(cd->name()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+ classOutputFileBase(cd)+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << classOutputFileBase(cd) << "\" kind=\"" << cd->compoundTypeString() << "\" prot=\""; switch (cd->protection()) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: t << "package"; break; } if (cd->isFinal()) t << "\" final=\"yes"; if (cd->isSealed()) t << "\" sealed=\"yes"; if (cd->isAbstract()) t << "\" abstract=\"yes"; t << "\">" << endl; t << " <compoundname>"; writeXMLString(t,cd->name()); t << "</compoundname>" << endl; if (cd->baseClasses()) { BaseClassListIterator bcli(*cd->baseClasses()); BaseClassDef *bcd; for (bcli.toFirst();(bcd=bcli.current());++bcli) { t << " <basecompoundref "; if (bcd->classDef->isLinkable()) { t << "refid=\"" << classOutputFileBase(bcd->classDef) << "\" "; } t << "prot=\""; switch (bcd->prot) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: ASSERT(0); break; } t << "\" virt=\""; switch(bcd->virt) { case Normal: t << "non-virtual"; break; case Virtual: t << "virtual"; break; case Pure: t <<"pure-virtual"; break; } t << "\">"; if (!bcd->templSpecifiers.isEmpty()) { t << convertToXML( insertTemplateSpecifierInScope( bcd->classDef->name(),bcd->templSpecifiers) ); } else { t << convertToXML(bcd->classDef->displayName()); } t << "</basecompoundref>" << endl; } } if (cd->subClasses()) { BaseClassListIterator bcli(*cd->subClasses()); BaseClassDef *bcd; for (bcli.toFirst();(bcd=bcli.current());++bcli) { t << " <derivedcompoundref refid=\"" << classOutputFileBase(bcd->classDef) << "\" prot=\""; switch (bcd->prot) { case Public: t << "public"; break; case Protected: t << "protected"; break; case Private: t << "private"; break; case Package: ASSERT(0); break; } t << "\" virt=\""; switch(bcd->virt) { case Normal: t << "non-virtual"; break; case Virtual: t << "virtual"; break; case Pure: t << "pure-virtual"; break; } t << "\">" << convertToXML(bcd->classDef->displayName()) << "</derivedcompoundref>" << endl; } } IncludeInfo *ii=cd->includeInfo(); if (ii) { QCString nm = ii->includeName; if (nm.isEmpty() && ii->fileDef) nm = ii->fileDef->docName(); if (!nm.isEmpty()) { t << " <includes"; if (ii->fileDef && !ii->fileDef->isReference()) // TODO: support external references { t << " refid=\"" << ii->fileDef->getOutputFileBase() << "\""; } t << " local=\"" << (ii->local ? "yes" : "no") << "\">"; t << nm; t << "</includes>" << endl; } } writeInnerClasses(cd->getClassSDict(),t); writeTemplateList(cd,t); if (cd->getMemberGroupSDict()) { MemberGroupSDict::Iterator mgli(*cd->getMemberGroupSDict()); MemberGroup *mg; for (;(mg=mgli.current());++mgli) { generateXMLSection(cd,ti,t,mg->members(),"user-defined",mg->header(), mg->documentation()); } } QListIterator<MemberList> mli(cd->getMemberLists()); MemberList *ml; for (mli.toFirst();(ml=mli.current());++mli) { if ((ml->listType()&MemberListType_detailedLists)==0) { generateXMLSection(cd,ti,t,ml,g_xmlSectionMapper.find(ml->listType())); } } #if 0 generateXMLSection(cd,ti,t,cd->pubTypes,"public-type"); generateXMLSection(cd,ti,t,cd->pubMethods,"public-func"); generateXMLSection(cd,ti,t,cd->pubAttribs,"public-attrib"); generateXMLSection(cd,ti,t,cd->pubSlots,"public-slot"); generateXMLSection(cd,ti,t,cd->signals,"signal"); generateXMLSection(cd,ti,t,cd->dcopMethods,"dcop-func"); generateXMLSection(cd,ti,t,cd->properties,"property"); generateXMLSection(cd,ti,t,cd->events,"event"); generateXMLSection(cd,ti,t,cd->pubStaticMethods,"public-static-func"); generateXMLSection(cd,ti,t,cd->pubStaticAttribs,"public-static-attrib"); generateXMLSection(cd,ti,t,cd->proTypes,"protected-type"); generateXMLSection(cd,ti,t,cd->proMethods,"protected-func"); generateXMLSection(cd,ti,t,cd->proAttribs,"protected-attrib"); generateXMLSection(cd,ti,t,cd->proSlots,"protected-slot"); generateXMLSection(cd,ti,t,cd->proStaticMethods,"protected-static-func"); generateXMLSection(cd,ti,t,cd->proStaticAttribs,"protected-static-attrib"); generateXMLSection(cd,ti,t,cd->pacTypes,"package-type"); generateXMLSection(cd,ti,t,cd->pacMethods,"package-func"); generateXMLSection(cd,ti,t,cd->pacAttribs,"package-attrib"); generateXMLSection(cd,ti,t,cd->pacStaticMethods,"package-static-func"); generateXMLSection(cd,ti,t,cd->pacStaticAttribs,"package-static-attrib"); generateXMLSection(cd,ti,t,cd->priTypes,"private-type"); generateXMLSection(cd,ti,t,cd->priMethods,"private-func"); generateXMLSection(cd,ti,t,cd->priAttribs,"private-attrib"); generateXMLSection(cd,ti,t,cd->priSlots,"private-slot"); generateXMLSection(cd,ti,t,cd->priStaticMethods,"private-static-func"); generateXMLSection(cd,ti,t,cd->priStaticAttribs,"private-static-attrib"); generateXMLSection(cd,ti,t,cd->friends,"friend"); generateXMLSection(cd,ti,t,cd->related,"related"); #endif t << " <briefdescription>" << endl; writeXMLDocBlock(t,cd->briefFile(),cd->briefLine(),cd,0,cd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,cd->docFile(),cd->docLine(),cd,0,cd->documentation()); t << " </detaileddescription>" << endl; DotClassGraph inheritanceGraph(cd,DotNode::Inheritance); if (!inheritanceGraph.isTrivial()) { t << " <inheritancegraph>" << endl; inheritanceGraph.writeXML(t); t << " </inheritancegraph>" << endl; } DotClassGraph collaborationGraph(cd,DotNode::Collaboration); if (!collaborationGraph.isTrivial()) { t << " <collaborationgraph>" << endl; collaborationGraph.writeXML(t); t << " </collaborationgraph>" << endl; } t << " <location file=\"" << cd->getDefFileName() << "\" line=\"" << cd->getDefLine() << "\""; if (cd->getStartBodyLine()!=-1) { FileDef *bodyDef = cd->getBodyDef(); if (bodyDef) { t << " bodyfile=\"" << bodyDef->absFilePath() << "\""; }<|fim▁hole|> t << "/>" << endl; writeListOfAllMembers(cd,t); t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } static void generateXMLForNamespace(NamespaceDef *nd,FTextStream &ti) { // + contained class definitions // + contained namespace definitions // + member groups // + normal members // + brief desc // + detailed desc // + location // - files containing (parts of) the namespace definition if (nd->isReference() || nd->isHidden()) return; // skip external references ti << " <compound refid=\"" << nd->getOutputFileBase() << "\" kind=\"namespace\"" << "><name>" << convertToXML(nd->name()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+nd->getOutputFileBase()+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << nd->getOutputFileBase() << "\" kind=\"namespace\">" << endl; t << " <compoundname>"; writeXMLString(t,nd->name()); t << "</compoundname>" << endl; writeInnerClasses(nd->getClassSDict(),t); writeInnerNamespaces(nd->getNamespaceSDict(),t); if (nd->getMemberGroupSDict()) { MemberGroupSDict::Iterator mgli(*nd->getMemberGroupSDict()); MemberGroup *mg; for (;(mg=mgli.current());++mgli) { generateXMLSection(nd,ti,t,mg->members(),"user-defined",mg->header(), mg->documentation()); } } QListIterator<MemberList> mli(nd->getMemberLists()); MemberList *ml; for (mli.toFirst();(ml=mli.current());++mli) { if ((ml->listType()&MemberListType_declarationLists)!=0) { generateXMLSection(nd,ti,t,ml,g_xmlSectionMapper.find(ml->listType())); } } #if 0 generateXMLSection(nd,ti,t,&nd->decDefineMembers,"define"); generateXMLSection(nd,ti,t,&nd->decProtoMembers,"prototype"); generateXMLSection(nd,ti,t,&nd->decTypedefMembers,"typedef"); generateXMLSection(nd,ti,t,&nd->decEnumMembers,"enum"); generateXMLSection(nd,ti,t,&nd->decFuncMembers,"func"); generateXMLSection(nd,ti,t,&nd->decVarMembers,"var"); #endif t << " <briefdescription>" << endl; writeXMLDocBlock(t,nd->briefFile(),nd->briefLine(),nd,0,nd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,nd->docFile(),nd->docLine(),nd,0,nd->documentation()); t << " </detaileddescription>" << endl; t << " <location file=\"" << nd->getDefFileName() << "\" line=\"" << nd->getDefLine() << "\"/>" << endl; t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } static void generateXMLForFile(FileDef *fd,FTextStream &ti) { // + includes files // + includedby files // + include graph // + included by graph // + contained class definitions // + contained namespace definitions // + member groups // + normal members // + brief desc // + detailed desc // + source code // + location // - number of lines if (fd->isReference()) return; // skip external references ti << " <compound refid=\"" << fd->getOutputFileBase() << "\" kind=\"file\"><name>" << convertToXML(fd->name()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+fd->getOutputFileBase()+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << fd->getOutputFileBase() << "\" kind=\"file\">" << endl; t << " <compoundname>"; writeXMLString(t,fd->name()); t << "</compoundname>" << endl; IncludeInfo *inc; if (fd->includeFileList()) { QListIterator<IncludeInfo> ili1(*fd->includeFileList()); for (ili1.toFirst();(inc=ili1.current());++ili1) { t << " <includes"; if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references { t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\""; } t << " local=\"" << (inc->local ? "yes" : "no") << "\">"; t << inc->includeName; t << "</includes>" << endl; } } if (fd->includedByFileList()) { QListIterator<IncludeInfo> ili2(*fd->includedByFileList()); for (ili2.toFirst();(inc=ili2.current());++ili2) { t << " <includedby"; if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references { t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\""; } t << " local=\"" << (inc->local ? "yes" : "no") << "\">"; t << inc->includeName; t << "</includedby>" << endl; } } DotInclDepGraph incDepGraph(fd,FALSE); if (!incDepGraph.isTrivial()) { t << " <incdepgraph>" << endl; incDepGraph.writeXML(t); t << " </incdepgraph>" << endl; } DotInclDepGraph invIncDepGraph(fd,TRUE); if (!invIncDepGraph.isTrivial()) { t << " <invincdepgraph>" << endl; invIncDepGraph.writeXML(t); t << " </invincdepgraph>" << endl; } if (fd->getClassSDict()) { writeInnerClasses(fd->getClassSDict(),t); } if (fd->getNamespaceSDict()) { writeInnerNamespaces(fd->getNamespaceSDict(),t); } if (fd->getMemberGroupSDict()) { MemberGroupSDict::Iterator mgli(*fd->getMemberGroupSDict()); MemberGroup *mg; for (;(mg=mgli.current());++mgli) { generateXMLSection(fd,ti,t,mg->members(),"user-defined",mg->header(), mg->documentation()); } } QListIterator<MemberList> mli(fd->getMemberLists()); MemberList *ml; for (mli.toFirst();(ml=mli.current());++mli) { if ((ml->listType()&MemberListType_declarationLists)!=0) { generateXMLSection(fd,ti,t,ml,g_xmlSectionMapper.find(ml->listType())); } } #if 0 generateXMLSection(fd,ti,t,fd->decDefineMembers,"define"); generateXMLSection(fd,ti,t,fd->decProtoMembers,"prototype"); generateXMLSection(fd,ti,t,fd->decTypedefMembers,"typedef"); generateXMLSection(fd,ti,t,fd->decEnumMembers,"enum"); generateXMLSection(fd,ti,t,fd->decFuncMembers,"func"); generateXMLSection(fd,ti,t,fd->decVarMembers,"var"); #endif t << " <briefdescription>" << endl; writeXMLDocBlock(t,fd->briefFile(),fd->briefLine(),fd,0,fd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,fd->docFile(),fd->docLine(),fd,0,fd->documentation()); t << " </detaileddescription>" << endl; if (Config_getBool("XML_PROGRAMLISTING")) { t << " <programlisting>" << endl; writeXMLCodeBlock(t,fd); t << " </programlisting>" << endl; } t << " <location file=\"" << fd->getDefFileName() << "\"/>" << endl; t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } static void generateXMLForGroup(GroupDef *gd,FTextStream &ti) { // + members // + member groups // + files // + classes // + namespaces // - packages // + pages // + child groups // - examples // + brief description // + detailed description if (gd->isReference()) return; // skip external references ti << " <compound refid=\"" << gd->getOutputFileBase() << "\" kind=\"group\"><name>" << convertToXML(gd->name()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+gd->getOutputFileBase()+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << gd->getOutputFileBase() << "\" kind=\"group\">" << endl; t << " <compoundname>" << convertToXML(gd->name()) << "</compoundname>" << endl; t << " <title>" << convertToXML(gd->groupTitle()) << "</title>" << endl; writeInnerFiles(gd->getFiles(),t); writeInnerClasses(gd->getClasses(),t); writeInnerNamespaces(gd->getNamespaces(),t); writeInnerPages(gd->getPages(),t); writeInnerGroups(gd->getSubGroups(),t); if (gd->getMemberGroupSDict()) { MemberGroupSDict::Iterator mgli(*gd->getMemberGroupSDict()); MemberGroup *mg; for (;(mg=mgli.current());++mgli) { generateXMLSection(gd,ti,t,mg->members(),"user-defined",mg->header(), mg->documentation()); } } QListIterator<MemberList> mli(gd->getMemberLists()); MemberList *ml; for (mli.toFirst();(ml=mli.current());++mli) { if ((ml->listType()&MemberListType_declarationLists)!=0) { generateXMLSection(gd,ti,t,ml,g_xmlSectionMapper.find(ml->listType())); } } #if 0 generateXMLSection(gd,ti,t,&gd->decDefineMembers,"define"); generateXMLSection(gd,ti,t,&gd->decProtoMembers,"prototype"); generateXMLSection(gd,ti,t,&gd->decTypedefMembers,"typedef"); generateXMLSection(gd,ti,t,&gd->decEnumMembers,"enum"); generateXMLSection(gd,ti,t,&gd->decFuncMembers,"func"); generateXMLSection(gd,ti,t,&gd->decVarMembers,"var"); #endif t << " <briefdescription>" << endl; writeXMLDocBlock(t,gd->briefFile(),gd->briefLine(),gd,0,gd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,gd->docFile(),gd->docLine(),gd,0,gd->documentation()); t << " </detaileddescription>" << endl; t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } static void generateXMLForDir(DirDef *dd,FTextStream &ti) { if (dd->isReference()) return; // skip external references ti << " <compound refid=\"" << dd->getOutputFileBase() << "\" kind=\"dir\"><name>" << convertToXML(dd->displayName()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+dd->getOutputFileBase()+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << dd->getOutputFileBase() << "\" kind=\"dir\">" << endl; t << " <compoundname>" << convertToXML(dd->displayName()) << "</compoundname>" << endl; writeInnerDirs(&dd->subDirs(),t); writeInnerFiles(dd->getFiles(),t); t << " <briefdescription>" << endl; writeXMLDocBlock(t,dd->briefFile(),dd->briefLine(),dd,0,dd->briefDescription()); t << " </briefdescription>" << endl; t << " <detaileddescription>" << endl; writeXMLDocBlock(t,dd->docFile(),dd->docLine(),dd,0,dd->documentation()); t << " </detaileddescription>" << endl; t << " <location file=\"" << dd->name() << "\"/>" << endl; t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } static void generateXMLForPage(PageDef *pd,FTextStream &ti,bool isExample) { // + name // + title // + documentation const char *kindName = isExample ? "example" : "page"; if (pd->isReference()) return; QCString pageName = pd->getOutputFileBase(); if (pd->getGroupDef()) { pageName+=(QCString)"_"+pd->name(); } if (pageName=="index") pageName="indexpage"; // to prevent overwriting the generated index page. ti << " <compound refid=\"" << pageName << "\" kind=\"" << kindName << "\"><name>" << convertToXML(pd->name()) << "</name>" << endl; QCString outputDirectory = Config_getString("XML_OUTPUT"); QCString fileName=outputDirectory+"/"+pageName+".xml"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); writeXMLHeader(t); t << " <compounddef id=\"" << pageName; t << "\" kind=\"" << kindName << "\">" << endl; t << " <compoundname>" << convertToXML(pd->name()) << "</compoundname>" << endl; if (pd==Doxygen::mainPage) // main page is special { QCString title; if (!pd->title().isEmpty() && pd->title().lower()!="notitle") { title = filterTitle(Doxygen::mainPage->title()); } else { title = Config_getString("PROJECT_NAME"); } t << " <title>" << convertToXML(title) << "</title>" << endl; } else { SectionInfo *si = Doxygen::sectionDict->find(pd->name()); if (si) { t << " <title>" << convertToXML(si->title) << "</title>" << endl; } } writeInnerPages(pd->getSubPages(),t); t << " <detaileddescription>" << endl; if (isExample) { writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0, pd->documentation()+"\n\\include "+pd->name()); } else { writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0, pd->documentation()); } t << " </detaileddescription>" << endl; t << " </compounddef>" << endl; t << "</doxygen>" << endl; ti << " </compound>" << endl; } void generateXML() { // + classes // + namespaces // + files // + groups // + related pages // - examples QCString outputDirectory = Config_getString("XML_OUTPUT"); if (outputDirectory.isEmpty()) { outputDirectory=QDir::currentDirPath().utf8(); } else { QDir dir(outputDirectory); if (!dir.exists()) { dir.setPath(QDir::currentDirPath()); if (!dir.mkdir(outputDirectory)) { err("error: tag XML_OUTPUT: Output directory `%s' does not " "exist and cannot be created\n",outputDirectory.data()); exit(1); } else if (!Config_getBool("QUIET")) { err("notice: Output directory `%s' does not exist. " "I have created it for you.\n", outputDirectory.data()); } dir.cd(outputDirectory); } outputDirectory=dir.absPath().utf8(); } QDir dir(outputDirectory); if (!dir.exists()) { dir.setPath(QDir::currentDirPath()); if (!dir.mkdir(outputDirectory)) { err("Cannot create directory %s\n",outputDirectory.data()); return; } } QDir xmlDir(outputDirectory); createSubDirs(xmlDir); QCString fileName=outputDirectory+"/index.xsd"; QFile f(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } f.writeBlock(index_xsd,qstrlen(index_xsd)); f.close(); fileName=outputDirectory+"/compound.xsd"; f.setName(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } f.writeBlock(compound_xsd,qstrlen(compound_xsd)); f.close(); fileName=outputDirectory+"/index.xml"; f.setName(fileName); if (!f.open(IO_WriteOnly)) { err("Cannot open file %s for writing!\n",fileName.data()); return; } FTextStream t(&f); //t.setEncoding(FTextStream::UnicodeUTF8); // write index header t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;; t << "<doxygenindex xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; t << "xsi:noNamespaceSchemaLocation=\"index.xsd\" "; t << "version=\"" << versionString << "\">" << endl; { ClassSDict::Iterator cli(*Doxygen::classSDict); ClassDef *cd; for (cli.toFirst();(cd=cli.current());++cli) { generateXMLForClass(cd,t); } } //{ // ClassSDict::Iterator cli(Doxygen::hiddenClasses); // ClassDef *cd; // for (cli.toFirst();(cd=cli.current());++cli) // { // msg("Generating XML output for class %s\n",cd->name().data()); // generateXMLForClass(cd,t); // } //} NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict); NamespaceDef *nd; for (nli.toFirst();(nd=nli.current());++nli) { msg("Generating XML output for namespace %s\n",nd->name().data()); generateXMLForNamespace(nd,t); } FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; for (;(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (;(fd=fni.current());++fni) { msg("Generating XML output for file %s\n",fd->name().data()); generateXMLForFile(fd,t); } } GroupSDict::Iterator gli(*Doxygen::groupSDict); GroupDef *gd; for (;(gd=gli.current());++gli) { msg("Generating XML output for group %s\n",gd->name().data()); generateXMLForGroup(gd,t); } { PageSDict::Iterator pdi(*Doxygen::pageSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { msg("Generating XML output for page %s\n",pd->name().data()); generateXMLForPage(pd,t,FALSE); } } { DirDef *dir; DirSDict::Iterator sdi(*Doxygen::directories); for (sdi.toFirst();(dir=sdi.current());++sdi) { msg("Generate XML output for dir %s\n",dir->name().data()); generateXMLForDir(dir,t); } } { PageSDict::Iterator pdi(*Doxygen::exampleSDict); PageDef *pd=0; for (pdi.toFirst();(pd=pdi.current());++pdi) { msg("Generating XML output for example %s\n",pd->name().data()); generateXMLForPage(pd,t,TRUE); } } if (Doxygen::mainPage) { msg("Generating XML output for the main page\n"); generateXMLForPage(Doxygen::mainPage,t,FALSE); } //t << " </compoundlist>" << endl; t << "</doxygenindex>" << endl; writeCombineScript(); }<|fim▁end|>
t << " bodystart=\"" << cd->getStartBodyLine() << "\" bodyend=\"" << cd->getEndBodyLine() << "\""; }
<|file_name|>textdecoder.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::TextDecoderBinding; use crate::dom::bindings::codegen::Bindings::TextDecoderBinding::{ TextDecodeOptions, TextDecoderMethods, }; use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; use crate::dom::bindings::error::{Error, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; use encoding_rs::{Decoder, DecoderResult, Encoding}; use std::borrow::ToOwned; use std::cell::{Cell, RefCell}; #[dom_struct] #[allow(non_snake_case)] pub struct TextDecoder { reflector_: Reflector, encoding: &'static Encoding, fatal: bool, ignoreBOM: bool, #[ignore_malloc_size_of = "defined in encoding_rs"] decoder: RefCell<Decoder>, in_stream: RefCell<Vec<u8>>, do_not_flush: Cell<bool>, } #[allow(non_snake_case)] impl TextDecoder { fn new_inherited(encoding: &'static Encoding, fatal: bool, ignoreBOM: bool) -> TextDecoder { TextDecoder { reflector_: Reflector::new(), encoding: encoding, fatal: fatal, ignoreBOM: ignoreBOM, decoder: RefCell::new(if ignoreBOM { encoding.new_decoder() } else { encoding.new_decoder_without_bom_handling() }), in_stream: RefCell::new(Vec::new()), do_not_flush: Cell::new(false), } } fn make_range_error() -> Fallible<DomRoot<TextDecoder>> { Err(Error::Range( "The given encoding is not supported.".to_owned(), )) } pub fn new( global: &GlobalScope, encoding: &'static Encoding, fatal: bool, ignoreBOM: bool, ) -> DomRoot<TextDecoder> { reflect_dom_object( Box::new(TextDecoder::new_inherited(encoding, fatal, ignoreBOM)), global, ) } /// <https://encoding.spec.whatwg.org/#dom-textdecoder> pub fn Constructor( global: &GlobalScope,<|fim▁hole|> None => return TextDecoder::make_range_error(), Some(enc) => enc, }; Ok(TextDecoder::new( global, encoding, options.fatal, options.ignoreBOM, )) } } impl TextDecoderMethods for TextDecoder { // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding fn Encoding(&self) -> DOMString { DOMString::from(self.encoding.name().to_ascii_lowercase()) } // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal fn Fatal(&self) -> bool { self.fatal } // https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom fn IgnoreBOM(&self) -> bool { self.ignoreBOM } // https://encoding.spec.whatwg.org/#dom-textdecoder-decode fn Decode( &self, input: Option<ArrayBufferViewOrArrayBuffer>, options: &TextDecodeOptions, ) -> Fallible<USVString> { // Step 1. if !self.do_not_flush.get() { if self.ignoreBOM { self.decoder .replace(self.encoding.new_decoder_without_bom_handling()); } else { self.decoder.replace(self.encoding.new_decoder()); } self.in_stream.replace(Vec::new()); } // Step 2. self.do_not_flush.set(options.stream); // Step 3. match input { Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref a)) => { self.in_stream.borrow_mut().extend_from_slice(&a.to_vec()); }, Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref a)) => { self.in_stream.borrow_mut().extend_from_slice(&a.to_vec()); }, None => {}, }; let mut decoder = self.decoder.borrow_mut(); let (remaining, s) = { let mut in_stream = self.in_stream.borrow_mut(); let (remaining, s) = if self.fatal { // Step 4. let mut out_stream = String::with_capacity( decoder .max_utf8_buffer_length_without_replacement(in_stream.len()) .unwrap(), ); // Step 5: Implemented by encoding_rs::Decoder. match decoder.decode_to_string_without_replacement( &in_stream, &mut out_stream, !options.stream, ) { (DecoderResult::InputEmpty, read) => (in_stream.split_off(read), out_stream), // Step 5.3.3. _ => return Err(Error::Type("Decoding failed".to_owned())), } } else { // Step 4. let mut out_stream = String::with_capacity(decoder.max_utf8_buffer_length(in_stream.len()).unwrap()); // Step 5: Implemented by encoding_rs::Decoder. let (_result, read, _replaced) = decoder.decode_to_string(&in_stream, &mut out_stream, !options.stream); (in_stream.split_off(read), out_stream) }; (remaining, s) }; self.in_stream.replace(remaining); Ok(USVString(s)) } }<|fim▁end|>
label: DOMString, options: &TextDecoderBinding::TextDecoderOptions, ) -> Fallible<DomRoot<TextDecoder>> { let encoding = match Encoding::for_label_no_replacement(label.as_bytes()) {
<|file_name|>test_VerticalPerspective.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Unit tests for the :class:`iris.coord_systems.VerticalPerspective` class.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests # isort:skip import cartopy.crs as ccrs from iris.coord_systems import GeogCS, VerticalPerspective <|fim▁hole|> self.perspective_point_height = 38204820000.0 self.false_easting = 0.0 self.false_northing = 0.0 self.semi_major_axis = 6377563.396 self.semi_minor_axis = 6356256.909 self.ellipsoid = GeogCS(self.semi_major_axis, self.semi_minor_axis) self.globe = ccrs.Globe( semimajor_axis=self.semi_major_axis, semiminor_axis=self.semi_minor_axis, ellipse=None, ) # Actual and expected coord system can be re-used for # VerticalPerspective.test_crs_creation and test_projection_creation. self.expected = ccrs.NearsidePerspective( central_longitude=self.longitude_of_projection_origin, central_latitude=self.latitude_of_projection_origin, satellite_height=self.perspective_point_height, false_easting=self.false_easting, false_northing=self.false_northing, globe=self.globe, ) self.vp_cs = VerticalPerspective( self.latitude_of_projection_origin, self.longitude_of_projection_origin, self.perspective_point_height, self.false_easting, self.false_northing, self.ellipsoid, ) def test_crs_creation(self): res = self.vp_cs.as_cartopy_crs() self.assertEqual(res, self.expected) def test_projection_creation(self): res = self.vp_cs.as_cartopy_projection() self.assertEqual(res, self.expected) def test_set_optional_args(self): # Check that setting the optional (non-ellipse) args works. crs = VerticalPerspective( 0, 0, 1000, false_easting=100, false_northing=-203.7 ) self.assertEqualAndKind(crs.false_easting, 100.0) self.assertEqualAndKind(crs.false_northing, -203.7) def _check_crs_defaults(self, crs): # Check for property defaults when no kwargs options were set. # NOTE: except ellipsoid, which is done elsewhere. self.assertEqualAndKind(crs.false_easting, 0.0) self.assertEqualAndKind(crs.false_northing, 0.0) def test_no_optional_args(self): # Check expected defaults with no optional args. crs = VerticalPerspective(0, 0, 1000) self._check_crs_defaults(crs) def test_optional_args_None(self): # Check expected defaults with optional args=None. crs = VerticalPerspective( 0, 0, 1000, false_easting=None, false_northing=None ) self._check_crs_defaults(crs) if __name__ == "__main__": tests.main()<|fim▁end|>
class Test(tests.IrisTest): def setUp(self): self.latitude_of_projection_origin = 0.0 self.longitude_of_projection_origin = 0.0
<|file_name|>_CommandFemMaterialMechanicalNonlinear.py<|end_file_name|><|fim▁begin|># *************************************************************************** # * * # * Copyright (c) 2016 - Bernd Hahnebach <[email protected]> * # * * # * This program is free software; you can redistribute it and/or modify * # * it under the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * * # * 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 Library General Public License for more details. * # * * # * You should have received a copy of the GNU Library 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 * # * * # *************************************************************************** __title__ = "Command nonlinear mechanical material" __author__ = "Bernd Hahnebach" __url__ = "http://www.freecadweb.org" ## @package CommandFemMaterialMechanicalNonLinear # \ingroup FEM import FreeCAD from FemCommands import FemCommands import FreeCADGui import FemGui from PySide import QtCore class _CommandFemMaterialMechanicalNonlinear(FemCommands): "The FEM_MaterialMechanicalNonlinear command definition" def __init__(self): super(_CommandFemMaterialMechanicalNonlinear, self).__init__() self.resources = {'Pixmap': 'fem-material-nonlinear', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialMechanicalNonlinear", "Nonlinear mechanical material"), 'Accel': "C, W", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialMechanicalNonlinear", "Creates a nonlinear mechanical material")} self.is_active = 'with_material' def Activated(self): sel = FreeCADGui.Selection.getSelection() if len(sel) == 1 and sel[0].isDerivedFrom("App::MaterialObjectPython"): lin_mat_obj = sel[0] # check if an nonlinear material exists which is based on the selected material already allow_nonlinear_material = True<|fim▁hole|> FreeCAD.Console.PrintError(o.Name + ' is based on the selected material: ' + lin_mat_obj.Name + '. Only one nonlinear object for each material allowed.\n') allow_nonlinear_material = False break if allow_nonlinear_material: string_lin_mat_obj = "App.ActiveDocument.getObject('" + lin_mat_obj.Name + "')" command_to_run = "FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [ObjectsFem.makeMaterialMechanicalNonlinear(" + string_lin_mat_obj + ")]" FreeCAD.ActiveDocument.openTransaction("Create FemMaterialMechanicalNonlinear") FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand(command_to_run) # set the material nonlinear property of the solver to nonlinear if only one solver is available and if this solver is a CalculiX solver solver_object = None for m in FemGui.getActiveAnalysis().Member: if m.isDerivedFrom('Fem::FemSolverObjectPython'): if not solver_object: solver_object = m else: # we do not change the material nonlinear attribut if we have more than one solver solver_object = None break if solver_object and solver_object.SolverType == 'FemSolverCalculix': solver_object.MaterialNonlinearity = "nonlinear" FreeCADGui.addCommand('FEM_MaterialMechanicalNonlinear', _CommandFemMaterialMechanicalNonlinear())<|fim▁end|>
for o in FreeCAD.ActiveDocument.Objects: if hasattr(o, "Proxy") and o.Proxy is not None and o.Proxy.Type == "FemMaterialMechanicalNonlinear" and o.LinearBaseMaterial == lin_mat_obj:
<|file_name|>google_analytics.go<|end_file_name|><|fim▁begin|>package collectors import ( "bytes" "encoding/base64" "encoding/gob" "fmt" "net/http" "strconv" "time" analytics "google.golang.org/api/analytics/v3" "bosun.org/cmd/scollector/conf" "bosun.org/metadata" "bosun.org/opentsdb" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" ) const descActiveUsers = "Number of unique users actively visiting the site." type multiError []error func (m multiError) Error() string { var fullErr string for _, err := range m { fullErr = fmt.Sprintf("%s\n%s", fullErr, err) } return fullErr } func init() { registerInit(func(c *conf.Conf) { for _, g := range c.GoogleAnalytics { collectors = append(collectors, &IntervalCollector{ F: func() (opentsdb.MultiDataPoint, error) { return c_google_analytics(g.ClientID, g.Secret, g.Token, g.Sites) }, name: "c_google_analytics", Interval: time.Minute * 1, }) } }) } func c_google_analytics(clientid string, secret string, tokenstr string, sites []conf.GoogleAnalyticsSite) (opentsdb.MultiDataPoint, error) { var md opentsdb.MultiDataPoint var mErr multiError c, err := analyticsClient(clientid, secret, tokenstr) if err != nil { return nil, err } svc, err := analytics.New(c) if err != nil { return nil, err } dimensions := []string{"browser", "trafficType", "deviceCategory", "operatingSystem"} for _, site := range sites { getPageviews(&md, svc, site) if site.Detailed { if err = getActiveUsers(&md, svc, site); err != nil { mErr = append(mErr, err) } for _, dimension := range dimensions { if err = getActiveUsersByDimension(&md, svc, site, dimension); err != nil { mErr = append(mErr, err) } } } } if len(mErr) == 0 { return md, nil } else { return md, mErr } } func getActiveUsersByDimension(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite, dimension string) error { call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:activeusers").Dimensions("rt:" + dimension) data, err := call.Do() if err != nil { return err } tags := opentsdb.TagSet{"site": site.Name}<|fim▁hole|> key, _ := opentsdb.Clean(row[0]) if key == "" { key = "__blank__" } value, err := strconv.Atoi(row[1]) if err != nil { return fmt.Errorf("Error parsing GA data: %s", err) } Add(md, "google.analytics.realtime.activeusers.by_"+dimension, value, opentsdb.TagSet{dimension: key}.Merge(tags), metadata.Gauge, metadata.ActiveUsers, descActiveUsers) } return nil } func getActiveUsers(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite) error { call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:activeusers") data, err := call.Do() if err != nil { return err } tags := opentsdb.TagSet{"site": site.Name} value, err := strconv.Atoi(data.Rows[0][0]) if err != nil { return fmt.Errorf("Error parsing GA data: %s", err) } Add(md, "google.analytics.realtime.activeusers", value, tags, metadata.Gauge, metadata.ActiveUsers, descActiveUsers) return nil } func getPageviews(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite) error { call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:pageviews").Dimensions("rt:minutesAgo") data, err := call.Do() if err != nil { return err } // If no offset was specified, the minute we care about is '1', or the most // recently gathered, completed datapoint. Minute '0' is the current minute, // and as such is incomplete. offset := site.Offset if offset == 0 { offset = 1 } time := time.Now().Add(time.Duration(-1*offset) * time.Minute).Unix() pageviews := 0 // Iterates through the response data and returns the time slice we // actually care about when we find it. for _, row := range data.Rows { // row == [2]string{"0", "123"} // First item is the minute, second is the data (pageviews in this case) minute, err := strconv.Atoi(row[0]) if err != nil { return fmt.Errorf("Error parsing GA data: %s", err) } if minute == offset { if pageviews, err = strconv.Atoi(row[1]); err != nil { return fmt.Errorf("Error parsing GA data: %s", err) } break } } AddTS(md, "google.analytics.realtime.pageviews", time, pageviews, opentsdb.TagSet{"site": site.Name}, metadata.Gauge, metadata.Count, "Number of pageviews tracked by GA in one minute") return nil } // analyticsClient() takes in a clientid, secret, and a base64'd gob representing the cached oauth token. // Generating the token is left as an exercise to the reader. (TODO) func analyticsClient(clientid string, secret string, tokenstr string) (*http.Client, error) { ctx := context.Background() config := &oauth2.Config{ ClientID: clientid, ClientSecret: secret, Endpoint: google.Endpoint, Scopes: []string{analytics.AnalyticsScope}, } token := new(oauth2.Token) // Decode the base64'd gob by, err := base64.StdEncoding.DecodeString(tokenstr) if err != nil { return nil, err } b := bytes.Buffer{} b.Write(by) d := gob.NewDecoder(&b) err = d.Decode(&token) return config.Client(ctx, token), nil }<|fim▁end|>
for _, row := range data.Rows { // key will always be an string of the dimension we care about. // For example, 'Chrome' would be a key for the 'browser' dimension.
<|file_name|>netutils_test.go<|end_file_name|><|fim▁begin|>package netutils import ( . "launchpad.net/gocheck" "net/http" "net/url" "testing" ) func TestUtils(t *testing.T) { TestingT(t) } type NetUtilsSuite struct{} var _ = Suite(&NetUtilsSuite{}) // Make sure parseUrl is strict enough not to accept total garbage func (s *NetUtilsSuite) TestParseBadUrl(c *C) { badUrls := []string{ "", " some random text ", "http---{}{\\bad bad url", } for _, badUrl := range badUrls { _, err := ParseUrl(badUrl) c.Assert(err, NotNil) } } //Just to make sure we don't panic, return err and not //username and pass and cover the function func (s *NetUtilsSuite) TestParseBadHeaders(c *C) { headers := []string{ //just empty string "", //missing auth type "justplainstring", //unknown auth type "Whut justplainstring", //invalid base64 "Basic Shmasic", //random encoded string "Basic YW55IGNhcm5hbCBwbGVhcw==", } for _, h := range headers { _, err := ParseAuthHeader(h) c.Assert(err, NotNil) } } //Just to make sure we don't panic, return err and not //username and pass and cover the function func (s *NetUtilsSuite) TestParseSuccess(c *C) { headers := []struct { Header string Expected BasicAuth }{ { "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", BasicAuth{Username: "Aladdin", Password: "open sesame"}, }, // Make sure that String() produces valid header<|fim▁hole|> { (&BasicAuth{Username: "Alice", Password: "Here's bob"}).String(), BasicAuth{Username: "Alice", Password: "Here's bob"}, }, //empty pass { "Basic QWxhZGRpbjo=", BasicAuth{Username: "Aladdin", Password: ""}, }, } for _, h := range headers { request, err := ParseAuthHeader(h.Header) c.Assert(err, IsNil) c.Assert(request.Username, Equals, h.Expected.Username) c.Assert(request.Password, Equals, h.Expected.Password) } } // Make sure copy does it right, so the copied url // is safe to alter without modifying the other func (s *NetUtilsSuite) TestCopyUrl(c *C) { urlA := &url.URL{ Scheme: "http", Host: "localhost:5000", Path: "/upstream", Opaque: "opaque", RawQuery: "a=1&b=2", Fragment: "#hello", User: &url.Userinfo{}, } urlB := CopyUrl(urlA) c.Assert(urlB, DeepEquals, urlB) urlB.Scheme = "https" c.Assert(urlB, Not(DeepEquals), urlA) } // Make sure copy headers is not shallow and copies all headers func (s *NetUtilsSuite) TestCopyHeaders(c *C) { source, destination := make(http.Header), make(http.Header) source.Add("a", "b") source.Add("c", "d") CopyHeaders(destination, source) c.Assert(destination.Get("a"), Equals, "b") c.Assert(destination.Get("c"), Equals, "d") // make sure that altering source does not affect the destination source.Del("a") c.Assert(source.Get("a"), Equals, "") c.Assert(destination.Get("a"), Equals, "b") } func (s *NetUtilsSuite) TestHasHeaders(c *C) { source := make(http.Header) source.Add("a", "b") source.Add("c", "d") c.Assert(HasHeaders([]string{"a", "f"}, source), Equals, true) c.Assert(HasHeaders([]string{"i", "j"}, source), Equals, false) } func (s *NetUtilsSuite) TestRemoveHeaders(c *C) { source := make(http.Header) source.Add("a", "b") source.Add("a", "m") source.Add("c", "d") RemoveHeaders([]string{"a"}, source) c.Assert(source.Get("a"), Equals, "") c.Assert(source.Get("c"), Equals, "d") }<|fim▁end|>
<|file_name|>ruleset.ts<|end_file_name|><|fim▁begin|>export class Ruleset { constructor(private movesPerTurn: number) {}<|fim▁hole|> public getMovesPerTurn = (): number => this.movesPerTurn; }<|fim▁end|>
<|file_name|>pair_lj_cut_coul_cut_omp.cpp<|end_file_name|><|fim▁begin|>/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) ------------------------------------------------------------------------- */ #include "math.h" #include "pair_lj_cut_coul_cut_omp.h" #include "atom.h" #include "comm.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "suffix.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ PairLJCutCoulCutOMP::PairLJCutCoulCutOMP(LAMMPS *lmp) : PairLJCutCoulCut(lmp), ThrOMP(lmp, THR_PAIR) { suffix_flag |= Suffix::OMP; respa_enable = 0; } /* ---------------------------------------------------------------------- */ void PairLJCutCoulCutOMP::compute(int eflag, int vflag) { if (eflag || vflag) { ev_setup(eflag,vflag); } else evflag = vflag_fdotr = 0; const int nall = atom->nlocal + atom->nghost; const int nthreads = comm->nthreads; const int inum = list->inum; #if defined(_OPENMP) #pragma omp parallel default(none) shared(eflag,vflag) #endif { int ifrom, ito, tid; loop_setup_thr(ifrom, ito, tid, inum, nthreads); ThrData *thr = fix->get_thr(tid); thr->timer(Timer::START); ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr); if (evflag) { if (eflag) { if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr);<|fim▁hole|> } } else { if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr); else eval<0,0,0>(ifrom, ito, thr); } thr->timer(Timer::PAIR); reduce_thr(this, eflag, vflag, thr); } // end of omp parallel region } /* ---------------------------------------------------------------------- */ template <int EVFLAG, int EFLAG, int NEWTON_PAIR> void PairLJCutCoulCutOMP::eval(int iifrom, int iito, ThrData * const thr) { int i,j,ii,jj,jnum,itype,jtype; double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair; double rsq,rinv,r2inv,r6inv,forcecoul,forcelj,factor_coul,factor_lj; int *ilist,*jlist,*numneigh,**firstneigh; evdwl = ecoul = 0.0; const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; const double * _noalias const q = atom->q; const int * _noalias const type = atom->type; const int nlocal = atom->nlocal; const double * _noalias const special_coul = force->special_coul; const double * _noalias const special_lj = force->special_lj; const double qqrd2e = force->qqrd2e; double fxtmp,fytmp,fztmp; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; // loop over neighbors of my atoms for (ii = iifrom; ii < iito; ++ii) { i = ilist[ii]; qtmp = q[i]; xtmp = x[i].x; ytmp = x[i].y; ztmp = x[i].z; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; fxtmp=fytmp=fztmp=0.0; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; factor_lj = special_lj[sbmask(j)]; factor_coul = special_coul[sbmask(j)]; j &= NEIGHMASK; delx = xtmp - x[j].x; dely = ytmp - x[j].y; delz = ztmp - x[j].z; rsq = delx*delx + dely*dely + delz*delz; jtype = type[j]; if (rsq < cutsq[itype][jtype]) { r2inv = 1.0/rsq; if (rsq < cut_coulsq[itype][jtype]) { rinv = sqrt(r2inv); forcecoul = qqrd2e * qtmp*q[j]*rinv; forcecoul *= factor_coul; } else forcecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { r6inv = r2inv*r2inv*r2inv; forcelj = r6inv * (lj1[itype][jtype]*r6inv - lj2[itype][jtype]); forcelj *= factor_lj; } else forcelj = 0.0; fpair = (forcecoul + forcelj) * r2inv; fxtmp += delx*fpair; fytmp += dely*fpair; fztmp += delz*fpair; if (NEWTON_PAIR || j < nlocal) { f[j].x -= delx*fpair; f[j].y -= dely*fpair; f[j].z -= delz*fpair; } if (EFLAG) { if (rsq < cut_coulsq[itype][jtype]) ecoul = factor_coul * qqrd2e * qtmp*q[j]*rinv; else ecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { evdwl = r6inv*(lj3[itype][jtype]*r6inv-lj4[itype][jtype]) - offset[itype][jtype]; evdwl *= factor_lj; } else evdwl = 0.0; } if (EVFLAG) ev_tally_thr(this, i,j,nlocal,NEWTON_PAIR, evdwl,ecoul,fpair,delx,dely,delz,thr); } } f[i].x += fxtmp; f[i].y += fytmp; f[i].z += fztmp; } } /* ---------------------------------------------------------------------- */ double PairLJCutCoulCutOMP::memory_usage() { double bytes = memory_usage_thr(); bytes += PairLJCutCoulCut::memory_usage(); return bytes; }<|fim▁end|>
else eval<1,1,0>(ifrom, ito, thr); } else { if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr); else eval<1,0,0>(ifrom, ito, thr);
<|file_name|>bug4337.js<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // Annex E: Completion reform changes // https://bugs.ecmascript.org/show_bug.cgi?id=4337 // If-Statement completion value assertSame(undefined, eval(`0; if (false) ;`)); assertSame(undefined, eval(`0; if (true) ;`)); assertSame(undefined, eval(`0; if (false) ; else ;`)); assertSame(undefined, eval(`0; if (true) ; else ;`));<|fim▁hole|>assertSame(1, eval(`switch (0) { case 0: 1; default: }`)); // Try-Statement completion value assertSame(1, eval(`L: try { throw null } catch (e) { ; } finally { 1; break L; }`));<|fim▁end|>
// Switch-Statement completion value assertSame(1, eval(`switch (0) { case 0: 1; case 1: }`));
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod random_player; mod legal_player; mod comp_delib_player; mod minimax_player; mod alpha_beta_player; mod mcs_player; <|fim▁hole|>pub use self::legal_player::LegalPlayer; pub use self::comp_delib_player::CompDelibPlayer; pub use self::minimax_player::MinimaxPlayer; pub use self::alpha_beta_player::AlphaBetaPlayer; pub use self::mcs_player::McsPlayer;<|fim▁end|>
pub use self::random_player::RandomPlayer;
<|file_name|>post_to_twitter.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright (c) 2009 Arthur Furlan <[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 2 of the License, or # (at your option) any later version. # # On Debian systems, you can find the full text of the license in # /usr/share/common-licenses/GPL-2 import os import twitter import urllib, urllib2 from django.conf import settings from django.contrib.sites.models import Site TWITTER_MAXLENGTH = getattr(settings, 'TWITTER_MAXLENGTH', 140) def post_to_twitter(sender, instance, *args, **kwargs): """ Post new saved objects to Twitter. Example: from django.db import models class MyModel(models.Model): text = models.CharField(max_length=255) link = models.CharField(max_length=255) def __unicode__(self): return u'%s' % self.text def get_absolute_url(self): return self.link # the following method is optional def get_twitter_message(self): return u'my-custom-twitter-message: %s - %s' \ % (self.text, self.link) models.signals.post_save.connect(post_to_twitter, sender=MyModel) """ # avoid to post the same object twice if not kwargs.get('created'): return False # check if there's a twitter account configured try: username = settings.TWITTER_USERNAME password = settings.TWITTER_PASSWORD except AttributeError: print 'WARNING: Twitter account not configured.' return False # if the absolute url wasn't a real absolute url and doesn't contains the # protocol and domain defineds, then append this relative url to the domain # of the current site, emulating the browser's behaviour url = instance.get_absolute_url() if not url.startswith('http://') and not url.startswith('https://'): domain = Site.objects.get_current().domain url = u'http://%s%s' % (domain, url) # tinyurl'ze the object's link create_api = 'http://tinyurl.com/api-create.php' data = urllib.urlencode(dict(url=url)) link = urllib2.urlopen(create_api, data=data).read().strip() # create the twitter message try: text = instance.get_twitter_message()<|fim▁hole|> mesg = u'%s - %s' % (text, link) if len(mesg) > TWITTER_MAXLENGTH: size = len(mesg + '...') - TWITTER_MAXLENGTH mesg = u'%s... - %s' % (text[:-size], link) try: twitter_api = twitter.Api(username, password) twitter_api.PostUpdate(mesg) except urllib2.HTTPError, ex: print 'ERROR:', str(ex) return False<|fim▁end|>
except AttributeError: text = unicode(instance)
<|file_name|>listadapter.py<|end_file_name|><|fim▁begin|>''' ListAdapter ================= .. versionadded:: 1.5 .. warning:: This code is still experimental, and its API is subject to change in a future version. A :class:`ListAdapter` is an adapter around a python list. Selection operations are a main concern for the class. From an :class:`Adapter`, a :class:`ListAdapter` gets cls, template, and args_converter properties and adds others that control selection behaviour: * *selection*, a list of selected items. * *selection_mode*, 'single', 'multiple', 'none' * *allow_empty_selection*, a boolean -- If False, a selection is forced. If True, and only user or programmatic action will change selection, it can be empty. If you wish to have a bare-bones list adapter, without selection, use a :class:`~kivy.adapters.simplelistadapter.SimpleListAdapter`. A :class:`~kivy.adapters.dictadapter.DictAdapter` is a subclass of a :class:`~kivy.adapters.listadapter.ListAdapter`. They both dispatch the *on_selection_change* event. :Events: `on_selection_change`: (view, view list ) Fired when selection changes .. versionchanged:: 1.6.0 Added data = ListProperty([]), which was proably inadvertently deleted at some point. This means that whenever data changes an update will fire, instead of having to reset the data object (Adapter has data defined as an ObjectProperty, so we need to reset it here to ListProperty). See also DictAdapter and its set of data = DictProperty(). ''' __all__ = ('ListAdapter', ) import inspect from kivy.event import EventDispatcher from kivy.adapters.adapter import Adapter from kivy.adapters.models import SelectableDataItem from kivy.properties import ListProperty from kivy.properties import DictProperty from kivy.properties import BooleanProperty from kivy.properties import OptionProperty from kivy.properties import NumericProperty from kivy.lang import Builder class ListAdapter(Adapter, EventDispatcher): ''' A base class for adapters interfacing with lists, dictionaries or other collection type data, adding selection, view creation and management functonality. ''' data = ListProperty([]) '''The data list property is redefined here, overriding its definition as an ObjectProperty in the Adapter class. We bind to data so that any changes will trigger updates. See also how the :class:`~kivy.adapters.DictAdapter` redefines data as a :class:`~kivy.properties.DictProperty`. :attr:`data` is a :class:`~kivy.properties.ListProperty` and defaults to []. ''' selection = ListProperty([]) '''The selection list property is the container for selected items. :attr:`selection` is a :class:`~kivy.properties.ListProperty` and defaults to []. ''' selection_mode = OptionProperty('single', options=('none', 'single', 'multiple')) '''Selection modes: * *none*, use the list as a simple list (no select action). This option is here so that selection can be turned off, momentarily or permanently, for an existing list adapter. A :class:`~kivy.adapters.listadapter.ListAdapter` is not meant to be used as a primary no-selection list adapter. Use a :class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` for that. * *single*, multi-touch/click ignored. Single item selection only. * *multiple*, multi-touch / incremental addition to selection allowed; may be limited to a count by selection_limit :attr:`selection_mode` is an :class:`~kivy.properties.OptionProperty` and defaults to 'single'. ''' propagate_selection_to_data = BooleanProperty(False) '''Normally, data items are not selected/deselected because the data items might not have an is_selected boolean property -- only the item view for a given data item is selected/deselected as part of the maintained selection list. However, if the data items do have an is_selected property, or if they mix in :class:`~kivy.adapters.models.SelectableDataItem`, the selection machinery can propagate selection to data items. This can be useful for storing selection state in a local database or backend database for maintaining state in game play or other similar scenarios. It is a convenience function. To propagate selection or not? Consider a shopping list application for shopping for fruits at the market. The app allows for the selection of fruits to buy for each day of the week, presenting seven lists: one for each day of the week. Each list is loaded with all the available fruits, but the selection for each is a subset. There is only one set of fruit data shared between the lists, so it would not make sense to propagate selection to the data because selection in any of the seven lists would clash and mix with that of the others. However, consider a game that uses the same fruits data for selecting fruits available for fruit-tossing. A given round of play could have a full fruits list, with fruits available for tossing shown selected. If the game is saved and rerun, the full fruits list, with selection marked on each item, would be reloaded correctly if selection is always propagated to the data. You could accomplish the same functionality by writing code to operate on list selection, but having selection stored in the data ListProperty might prove convenient in some cases. :attr:`propagate_selection_to_data` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' allow_empty_selection = BooleanProperty(True) '''The allow_empty_selection may be used for cascading selection between several list views, or between a list view and an observing view. Such automatic maintenance of the selection is important for all but simple list displays. Set allow_empty_selection to False and the selection is auto-initialized and always maintained, so any observing views may likewise be updated to stay in sync. :attr:`allow_empty_selection` is a :class:`~kivy.properties.BooleanProperty` and defaults to True. ''' selection_limit = NumericProperty(-1) '''When the selection_mode is multiple and the selection_limit is non-negative, this number will limit the number of selected items. It can be set to 1, which is equivalent to single selection. If selection_limit is<|fim▁hole|> ''' cached_views = DictProperty({}) '''View instances for data items are instantiated and managed by the adapter. Here we maintain a dictionary containing the view instances keyed to the indices in the data. This dictionary works as a cache. get_view() only asks for a view from the adapter if one is not already stored for the requested index. :attr:`cached_views` is a :class:`~kivy.properties.DictProperty` and defaults to {}. ''' __events__ = ('on_selection_change', ) def __init__(self, **kwargs): super(ListAdapter, self).__init__(**kwargs) self.bind(selection_mode=self.selection_mode_changed, allow_empty_selection=self.check_for_empty_selection, data=self.update_for_new_data) self.update_for_new_data() def delete_cache(self, *args): self.cached_views = {} def get_count(self): return len(self.data) def get_data_item(self, index): if index < 0 or index >= len(self.data): return None return self.data[index] def selection_mode_changed(self, *args): if self.selection_mode == 'none': for selected_view in self.selection: self.deselect_item_view(selected_view) else: self.check_for_empty_selection() def get_view(self, index): if index in self.cached_views: return self.cached_views[index] item_view = self.create_view(index) if item_view: self.cached_views[index] = item_view return item_view def create_view(self, index): '''This method is more complicated than the one in :class:`kivy.adapters.adapter.Adapter` and :class:`kivy.adapters.simplelistadapter.SimpleListAdapter`, because here we create bindings for the data item and its children back to self.handle_selection(), and do other selection-related tasks to keep item views in sync with the data. ''' item = self.get_data_item(index) if item is None: return None item_args = self.args_converter(index, item) item_args['index'] = index if self.cls: view_instance = self.cls(**item_args) else: view_instance = Builder.template(self.template, **item_args) if self.propagate_selection_to_data: # The data item must be a subclass of SelectableDataItem, or must # have an is_selected boolean or function, so it has is_selected # available. If is_selected is unavailable on the data item, an # exception is raised. # if isinstance(item, SelectableDataItem): if item.is_selected: self.handle_selection(view_instance) elif type(item) == dict and 'is_selected' in item: if item['is_selected']: self.handle_selection(view_instance) elif hasattr(item, 'is_selected'): if (inspect.isfunction(item.is_selected) or inspect.ismethod(item.is_selected)): if item.is_selected(): self.handle_selection(view_instance) else: if item.is_selected: self.handle_selection(view_instance) else: msg = "ListAdapter: unselectable data item for {0}" raise Exception(msg.format(index)) view_instance.bind(on_release=self.handle_selection) for child in view_instance.children: child.bind(on_release=self.handle_selection) return view_instance def on_selection_change(self, *args): '''on_selection_change() is the default handler for the on_selection_change event. ''' pass def handle_selection(self, view, hold_dispatch=False, *args): if view not in self.selection: if self.selection_mode in ['none', 'single'] and \ len(self.selection) > 0: for selected_view in self.selection: self.deselect_item_view(selected_view) if self.selection_mode != 'none': if self.selection_mode == 'multiple': if self.allow_empty_selection: # If < 0, selection_limit is not active. if self.selection_limit < 0: self.select_item_view(view) else: if len(self.selection) < self.selection_limit: self.select_item_view(view) else: self.select_item_view(view) else: self.select_item_view(view) else: self.deselect_item_view(view) if self.selection_mode != 'none': # If the deselection makes selection empty, the following call # will check allows_empty_selection, and if False, will # select the first item. If view happens to be the first item, # this will be a reselection, and the user will notice no # change, except perhaps a flicker. # self.check_for_empty_selection() if not hold_dispatch: self.dispatch('on_selection_change') def select_data_item(self, item): self.set_data_item_selection(item, True) def deselect_data_item(self, item): self.set_data_item_selection(item, False) def set_data_item_selection(self, item, value): if isinstance(item, SelectableDataItem): item.is_selected = value elif type(item) == dict: item['is_selected'] = value elif hasattr(item, 'is_selected'): if (inspect.isfunction(item.is_selected) or inspect.ismethod(item.is_selected)): item.is_selected() else: item.is_selected = value def select_item_view(self, view): view.select() view.is_selected = True self.selection.append(view) # [TODO] sibling selection for composite items # Needed? Or handled from parent? # (avoid circular, redundant selection) #if hasattr(view, 'parent') and hasattr(view.parent, 'children'): #siblings = [child for child in view.parent.children if child != view] #for sibling in siblings: #if hasattr(sibling, 'select'): #sibling.select() if self.propagate_selection_to_data: data_item = self.get_data_item(view.index) self.select_data_item(data_item) def select_list(self, view_list, extend=True): '''The select call is made for the items in the provided view_list. Arguments: view_list: the list of item views to become the new selection, or to add to the existing selection extend: boolean for whether or not to extend the existing list ''' if not extend: self.selection = [] for view in view_list: self.handle_selection(view, hold_dispatch=True) self.dispatch('on_selection_change') def deselect_item_view(self, view): view.deselect() view.is_selected = False self.selection.remove(view) # [TODO] sibling deselection for composite items # Needed? Or handled from parent? # (avoid circular, redundant selection) #if hasattr(view, 'parent') and hasattr(view.parent, 'children'): #siblings = [child for child in view.parent.children if child != view] #for sibling in siblings: #if hasattr(sibling, 'deselect'): #sibling.deselect() if self.propagate_selection_to_data: item = self.get_data_item(view.index) self.deselect_data_item(item) def deselect_list(self, l): for view in l: self.handle_selection(view, hold_dispatch=True) self.dispatch('on_selection_change') # [TODO] Could easily add select_all() and deselect_all(). def update_for_new_data(self, *args): self.delete_cache() self.initialize_selection() def initialize_selection(self, *args): if len(self.selection) > 0: self.selection = [] self.dispatch('on_selection_change') self.check_for_empty_selection() def check_for_empty_selection(self, *args): if not self.allow_empty_selection: if len(self.selection) == 0: # Select the first item if we have it. v = self.get_view(0) if v is not None: self.handle_selection(v) # [TODO] Also make methods for scroll_to_sel_start, scroll_to_sel_end, # scroll_to_sel_middle. def trim_left_of_sel(self, *args): '''Cut list items with indices in sorted_keys that are less than the index of the first selected item if there is a selection. ''' if len(self.selection) > 0: first_sel_index = min([sel.index for sel in self.selection]) self.data = self.data[first_sel_index:] def trim_right_of_sel(self, *args): '''Cut list items with indices in sorted_keys that are greater than the index of the last selected item if there is a selection. ''' if len(self.selection) > 0: last_sel_index = max([sel.index for sel in self.selection]) print('last_sel_index', last_sel_index) self.data = self.data[:last_sel_index + 1] def trim_to_sel(self, *args): '''Cut list items with indices in sorted_keys that are les than or greater than the index of the last selected item if there is a selection. This preserves intervening list items within the selected range. ''' if len(self.selection) > 0: sel_indices = [sel.index for sel in self.selection] first_sel_index = min(sel_indices) last_sel_index = max(sel_indices) self.data = self.data[first_sel_index:last_sel_index + 1] def cut_to_sel(self, *args): '''Same as trim_to_sel, but intervening list items within the selected range are also cut, leaving only list items that are selected. ''' if len(self.selection) > 0: self.data = self.selection<|fim▁end|>
not set, the default value is -1, meaning that no limit will be enforced. :attr:`selection_limit` is a :class:`~kivy.properties.NumericProperty` and defaults to -1 (no limit).
<|file_name|>CategorySelect.js<|end_file_name|><|fim▁begin|>import React from 'react' import { Component } from 'react' import Select from 'react-select' import './CategorySelect.scss' export default class CategorySelect extends Component { render() { const {categories, value, onChange, handleBeingTouched, touched, error} = this.props var options = categories.map(function(category) { return {label: category.display_name, value: category.id} }) return (<|fim▁hole|> className={((touched && error) ? 'category-select select-container-error' : 'category-select select-container')} onChange = {(v) => { handleBeingTouched(); onChange(v)} } onBlur={() => { handleBeingTouched() }} placeholder="Choose a Category" value={value} options={options} /> {touched && error && <div className='select-error-msg'>{error}</div>} </div> ) } }<|fim▁end|>
<div className='category-select-container'> <label className='category-select-label ncss-label'>Category</label> <Select
<|file_name|>vec-res-add.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.<|fim▁hole|>} fn r(i:int) -> r { r { i: i } } impl Drop for r { fn drop(&mut self) {} } fn main() { // This can't make sense as it would copy the classes let i = vec!(r(0)); let j = vec!(r(1)); let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type println!("{}", j); }<|fim▁end|>
#[deriving(Show)] struct r { i:int
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate px8; extern crate sdl2; extern crate time; extern crate rand; #[macro_use] extern crate log; extern crate fern; extern crate nalgebra; use std::sync::{Arc, Mutex}; use px8::px8::math; use px8::frontend; use px8::gfx; use px8::cartridge; use px8::px8::RustPlugin; use px8::config::Players; use nalgebra::Vector2; pub struct Fighter { pub pos: Vector2<u32>, } impl Fighter { fn new(x: u32, y: u32) -> Fighter { Fighter { pos: Vector2::new(x, y) } } fn update(&mut self) { } fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) { screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8); } } pub struct FourmisWar { pub sprite_filename: String, pub fighters: Vec<Fighter>, } impl FourmisWar { pub fn new(sprite_filename: String) -> FourmisWar { FourmisWar { sprite_filename: sprite_filename, fighters: Vec::new(), } } } impl RustPlugin for FourmisWar { fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 { self.fighters.push(Fighter::new(40, 50)); match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) { Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites), Err(e) => panic!("Impossible to load the assets {:?}", e), } return 0.; } fn update(&mut self, players: Arc<Mutex<Players>>) -> f64 { let mouse_x = players.lock().unwrap().mouse_coordinate(0); let mouse_y = players.lock().unwrap().mouse_coordinate(1); if players.lock().unwrap().mouse_state() == 1 { info!("CLICK {:?} {:?}", mouse_x, mouse_y); } for fighter in self.fighters.iter_mut() { fighter.update(); } return 0.;<|fim▁hole|> for fighter in self.fighters.iter_mut() { fighter.draw(screen.clone()); } return 0.; } } fn main() { let logger_config = fern::DispatchConfig { format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| { format!("[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(), level, msg) }), output: vec![fern::OutputConfig::stdout(), fern::OutputConfig::file("output.log")], level: log::LogLevelFilter::Trace, }; if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Info) { panic!("Failed to initialize global logger: {}", e); } let war = FourmisWar::new("./fourmiswar.dpx8".to_string()); let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) { Err(error) => panic!("{:?}", error), Ok(frontend) => frontend, }; frontend.px8.register(war); frontend.start("./gamecontrollerdb.txt".to_string()); frontend.run_native_cartridge(); }<|fim▁end|>
} fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 { screen.lock().unwrap().cls();
<|file_name|>promise-separate.js<|end_file_name|><|fim▁begin|>'use strict'; const Q = require('q'); function getPromise(){ let deferred = Q.defer(); //Resolve the promise after a second setTimeout(() => { deferred.resolve('final value'); }, 1000); return deferred.promise; } let promise = getPromise(); promise.then((val) => { console.log('done with:', val);<|fim▁hole|><|fim▁end|>
});
<|file_name|>t.js<|end_file_name|><|fim▁begin|>/* */ define(['exports', './i18n', 'aurelia-event-aggregator', 'aurelia-templating', './utils'], function (exports, _i18n, _aureliaEventAggregator, _aureliaTemplating, _utils) { 'use strict'; exports.__esModule = true; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TValueConverter = (function () { TValueConverter.inject = function inject() { return [_i18n.I18N]; }; function TValueConverter(i18n) { _classCallCheck(this, TValueConverter); this.service = i18n; } TValueConverter.prototype.toView = function toView(value, options) { return this.service.tr(value, options); }; return TValueConverter; })(); exports.TValueConverter = TValueConverter; var TParamsCustomAttribute = (function () { _createClass(TParamsCustomAttribute, null, [{ key: 'inject', value: [Element], enumerable: true }]); function TParamsCustomAttribute(element) { _classCallCheck(this, _TParamsCustomAttribute); this.element = element; } TParamsCustomAttribute.prototype.valueChanged = function valueChanged() {}; var _TParamsCustomAttribute = TParamsCustomAttribute; TParamsCustomAttribute = _aureliaTemplating.customAttribute('t-params')(TParamsCustomAttribute) || TParamsCustomAttribute; return TParamsCustomAttribute; })(); exports.TParamsCustomAttribute = TParamsCustomAttribute; var TCustomAttribute = (function () { _createClass(TCustomAttribute, null, [{ key: 'inject', value: [Element, _i18n.I18N, _aureliaEventAggregator.EventAggregator, _utils.LazyOptional.of(TParamsCustomAttribute)], enumerable: true }]); function TCustomAttribute(element, i18n, ea, tparams) { _classCallCheck(this, _TCustomAttribute); this.element = element; this.service = i18n; this.ea = ea; this.lazyParams = tparams; } TCustomAttribute.prototype.bind = function bind() { var _this = this; this.params = this.lazyParams(); setTimeout(function () { if (_this.params) { _this.params.valueChanged = function (newParams, oldParams) { _this.paramsChanged(_this.value, newParams, oldParams); }; } var p = _this.params !== null ? _this.params.value : undefined; _this.subscription = _this.ea.subscribe('i18n:locale:changed', function () { _this.service.updateValue(_this.element, _this.value, p); });<|fim▁hole|> _this.service.updateValue(_this.element, _this.value, p); }); }); }; TCustomAttribute.prototype.paramsChanged = function paramsChanged(newValue, newParams) { this.service.updateValue(this.element, newValue, newParams); }; TCustomAttribute.prototype.valueChanged = function valueChanged(newValue) { var p = this.params !== null ? this.params.value : undefined; this.service.updateValue(this.element, newValue, p); }; TCustomAttribute.prototype.unbind = function unbind() { this.subscription.dispose(); }; var _TCustomAttribute = TCustomAttribute; TCustomAttribute = _aureliaTemplating.customAttribute('t')(TCustomAttribute) || TCustomAttribute; return TCustomAttribute; })(); exports.TCustomAttribute = TCustomAttribute; });<|fim▁end|>
setTimeout(function () {
<|file_name|>last_added_table.js<|end_file_name|><|fim▁begin|><script> $(document).ready(function() { $("#jobs_table").DataTable({ "ajax": { 'type': 'POST',<|fim▁hole|> {"data": "name"}, {"data": "last_build.status", "defaultContent": "None" }, {"data": "release", "defaultContent": "None" }, {"data": "last_build.timestamp", "defaultContent": "None" }, {"data": "name"}, {"data": "name"}, ], "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { status = aData.last_build.status; {% include "tables/color_result.js" -%} columnDefs: [ { targets:0, render: function ( data, type, row, meta ) { if(type === 'display'){ return $('<a>') .attr('href', data) .text(data) .wrap('<div></div>') .parent() .html(); } else { return data; } } }, { targets:[1], render: function ( data, type, row, meta ) { data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '">' + row['last_build']['status'] + '</a>'; return data; } }, { targets:4, render: function ( data, type, row, meta ) { if(type === 'display' && row[1] != 0 && (row['last_build']['status'] == 'SUCCESS' || row['last_build']['status'] == 'UNSTABLE')){ data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/testReport' + '">Tests</a>'; } else { data = 'No Tests'; } return data; } }, { targets:5, render: function ( data, type, row, meta ) { {% if current_user.is_anonymous %} data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}">'; {% else %} data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/build"><img src="{{ url_for('static' , filename='images/clock.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/configure"><img src="{{ url_for('static', filename='images/gear.png') }}"> '; {% endif %} return data; } } ], processing: true, search: { "regex": true }, "lengthChange": false, deferRender: true, }); }); </script><|fim▁end|>
'url': "{{ url_for('api.jobs', query_str=query_str) }}", }, "columns": [
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate chrono; #[macro_use] extern crate hyper; extern crate hyper_native_tls; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; pub mod account;<|fim▁hole|>pub mod client; pub mod instrument;<|fim▁end|>
<|file_name|>btn.js<|end_file_name|><|fim▁begin|>/** * 指示按钮 */ Banner.prototype.btn = function() { var s = this, o = this.option, $banner = this.$banner, $btn; for (var i = 0, item = ''; i < s.len; i++) { item += '<a></a>'; } $banner.append($('<div class="tb-btn"/>').append(item)); s.$btn = $btn = $('.tb-btn a', $banner); $btn.first().addClass('active'); setTimeout(function() { $btn.parent().css({ marginLeft: -($btn.outerWidth(true) * $btn.length / 2)<|fim▁hole|> $btn.on('click.terseBanner', function() { if (s.isAnimated) return; o.before.call(s, s.currentIndex); s.currentIndex = $(this).index(); s.play(); }); } };<|fim▁end|>
}); }, 0); if (!Util.IS_MOBILE) {
<|file_name|>test_db_types.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright 2015 Simone Campagna # # 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. # __author__ = "Simone Campagna" __all__ = [ 'TestInvoiceProgram', ] import os import datetime import unittest from invoice.database.db_types import Str, StrList, StrTuple, \ Int, IntList, IntTuple, \ Float, FloatList, FloatTuple, \ Date, DateList, DateTuple, \ DateTime, DateTimeList, DateTimeTuple, \ Path, PathList, PathTuple, \ Bool, BoolList, BoolTuple, \ OptionType, BaseSequence class TestStr(unittest.TestCase): def test_db_from(self): self.assertIs(Str.db_from(None), None) self.assertEqual(Str.db_from("alpha"), "alpha") def test_db_to(self): self.assertIs(Str.db_to(None), None) self.assertEqual(Str.db_to("alpha"), "alpha") class TestStrList(unittest.TestCase): def test_db_from(self): self.assertIs(StrList.db_from(None), None) self.assertEqual(StrList.db_from("alpha, beta, 10.3, gamma "), ["alpha", "beta", "10.3", "gamma"]) def test_db_to(self):<|fim▁hole|>class TestStrTuple(unittest.TestCase): def test_db_from(self): self.assertIs(StrTuple.db_from(None), None) self.assertEqual(StrTuple.db_from("alpha, beta, 10.3, gamma "), ("alpha", "beta", "10.3", "gamma")) def test_db_to(self): self.assertIs(StrTuple.db_to(None), None) self.assertEqual(StrTuple.db_to(("alpha", "beta", "10.3", "gamma")), "alpha,beta,10.3,gamma") class TestInt(unittest.TestCase): def test_db_from(self): self.assertIs(Int.db_from(None), None) self.assertEqual(Int.db_from("10"), 10) def test_db_to(self): self.assertIs(Int.db_to(None), None) self.assertEqual(Int.db_to(10), "10") class TestIntList(unittest.TestCase): def test_db_from(self): self.assertIs(IntList.db_from(None), None) self.assertEqual(IntList.db_from("10, 20"), [10, 20]) def test_db_to(self): self.assertIs(IntList.db_to(None), None) self.assertEqual(IntList.db_to([10, 20]), "10,20") class TestIntTuple(unittest.TestCase): def test_db_from(self): self.assertIs(IntTuple.db_from(None), None) self.assertEqual(IntTuple.db_from("10, 20"), (10, 20)) def test_db_to(self): self.assertIs(IntTuple.db_to(None), None) self.assertEqual(IntTuple.db_to((10, 20)), "10,20") class TestFloat(unittest.TestCase): def test_db_from(self): self.assertIs(Float.db_from(None), None) self.assertEqual(Float.db_from("10.5"), 10.5) def test_db_to(self): self.assertIs(Float.db_to(None), None) self.assertEqual(Float.db_to(10.5), "10.5") class TestFloatList(unittest.TestCase): def test_db_from(self): self.assertIs(FloatList.db_from(None), None) self.assertEqual(FloatList.db_from("10.5,23.32"), [10.5, 23.32]) def test_db_to(self): self.assertIs(FloatList.db_to(None), None) self.assertEqual(FloatList.db_to([10.5, 23.32]), "10.5,23.32") class TestFloatTuple(unittest.TestCase): def test_db_from(self): self.assertIs(FloatTuple.db_from(None), None) self.assertEqual(FloatTuple.db_from("10.5,23.32"), (10.5, 23.32)) def test_db_to(self): self.assertIs(FloatTuple.db_to(None), None) self.assertEqual(FloatTuple.db_to((10.5, 23.32)), "10.5,23.32") class TestDate(unittest.TestCase): def test_db_from(self): self.assertIs(Date.db_from(None), None) self.assertEqual(Date.db_from("2015-01-04"), datetime.date(2015, 1, 4)) def test_db_to(self): self.assertIs(Date.db_to(None), None) self.assertEqual(Date.db_to(datetime.date(2015, 1, 4)), "2015-01-04") class TestDateList(unittest.TestCase): def test_db_from(self): self.assertIs(DateList.db_from(None), None) self.assertEqual(DateList.db_from(" 2015-01-04 , 2014-04-05 "), [datetime.date(2015, 1, 4), datetime.date(2014, 4, 5)]) def test_db_to(self): self.assertIs(DateList.db_to(None), None) self.assertEqual(DateList.db_to([datetime.date(2015, 1, 4), datetime.date(2014, 4, 5)]), "2015-01-04,2014-04-05") class TestDateTuple(unittest.TestCase): def test_db_from(self): self.assertIs(DateTuple.db_from(None), None) self.assertEqual(DateTuple.db_from(" 2015-01-04 , 2014-04-05 "), (datetime.date(2015, 1, 4), datetime.date(2014, 4, 5))) def test_db_to(self): self.assertIs(DateTuple.db_to(None), None) self.assertEqual(DateTuple.db_to((datetime.date(2015, 1, 4), datetime.date(2014, 4, 5))), "2015-01-04,2014-04-05") class TestDateTime(unittest.TestCase): def test_db_from(self): self.assertIs(DateTime.db_from(None), None) self.assertEqual(DateTime.db_from("2015-01-04 13:34:45"), datetime.datetime(2015, 1, 4, 13, 34, 45)) def test_db_to(self): self.assertIs(DateTime.db_to(None), None) self.assertEqual(DateTime.db_to(datetime.datetime(2015, 1, 4, 13, 34, 45)), "2015-01-04 13:34:45") class TestDateTimeList(unittest.TestCase): def test_db_from(self): self.assertIs(DateTimeList.db_from(None), None) self.assertEqual(DateTimeList.db_from("2015-01-04 13:34:45,2014-04-05 02:22:01"), [datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1)]) def test_db_to(self): self.assertIs(DateTimeList.db_to(None), None) self.assertEqual(DateTimeList.db_to([datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1)]), "2015-01-04 13:34:45,2014-04-05 02:22:01") class TestDateTimeTuple(unittest.TestCase): def test_db_from(self): self.assertIs(DateTimeTuple.db_from(None), None) self.assertEqual(DateTimeTuple.db_from("2015-01-04 13:34:45,2014-04-05 02:22:01"), (datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1))) def test_db_to(self): self.assertIs(DateTimeTuple.db_to(None), None) self.assertEqual(DateTimeTuple.db_to((datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1))), "2015-01-04 13:34:45,2014-04-05 02:22:01") class TestPath(unittest.TestCase): def test_db_from(self): self.assertIs(Path.db_from(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(Path.db_from("{}".format(f("alpha"))), f("alpha")) def test_db_to(self): self.assertIs(Path.db_to(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(Path.db_to("alpha"), f("alpha")) class TestPathList(unittest.TestCase): def test_db_from(self): self.assertIs(PathList.db_from(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(PathList.db_from("{},/b/c,{}".format(f("alpha"), f("d/e"))), [f("alpha"), "/b/c", f("d/e")]) def test_db_to(self): self.assertIs(PathList.db_to(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(PathList.db_to(["alpha", "/b/c", "d/e"]), "{},/b/c,{}".format(f("alpha"), f("d/e"))) class TestPathTuple(unittest.TestCase): def test_db_from(self): self.assertIs(PathTuple.db_from(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(PathTuple.db_from("{},/b/c,{}".format(f("alpha"), f("d/e"))), (f("alpha"), "/b/c", f("d/e"))) def test_db_to(self): self.assertIs(PathTuple.db_to(None), None) f = lambda x: os.path.normpath(os.path.abspath(x)) self.assertEqual(PathTuple.db_to(("alpha", "/b/c", "d/e")), "{},/b/c,{}".format(f("alpha"), f("d/e"))) class TestBool(unittest.TestCase): def test_db_from(self): self.assertIs(Bool.db_from(None), None) self.assertEqual(Bool.db_from(True), True) self.assertEqual(Bool.db_from(1), True) self.assertEqual(Bool.db_from(False), False) self.assertEqual(Bool.db_from(0), False) def test_db_to(self): self.assertIs(Bool.db_to(None), None) self.assertEqual(Bool.db_to("True"), True) self.assertEqual(Bool.db_to(1), True) self.assertEqual(Bool.db_to("False"), False) self.assertEqual(Bool.db_to(0), False) with self.assertRaises(ValueError): Bool.db_to("alpha") class TestBoolList(unittest.TestCase): def test_db_from(self): self.assertIs(BoolList.db_from(None), None) self.assertEqual(BoolList.db_from("True,True,False,False"), [True, True, False, False]) def test_db_to(self): self.assertIs(BoolList.db_to(None), None) self.assertEqual(BoolList.db_to([True, True, False, False]), "True,True,False,False") with self.assertRaises(ValueError): BoolList.db_to("True,alpha") class TestBoolTuple(unittest.TestCase): def test_db_from(self): self.assertIs(BoolTuple.db_from(None), None) self.assertEqual(BoolTuple.db_from("True,True,False,False"), (True, True, False, False)) def test_db_to(self): self.assertIs(BoolTuple.db_to(None), None) self.assertEqual(BoolTuple.db_to((True, True, False, False)), "True,True,False,False") with self.assertRaises(ValueError): BoolTuple.db_to("True,alpha") class MyOption(OptionType): OPTIONS = ("alpha", "beta", "gamma") class MyOptionTuple(BaseSequence): SCALAR_TYPE = MyOption SEQUENCE_TYPE = tuple class TestMyOption(unittest.TestCase): def test_db_from(self): self.assertIs(MyOption.db_from(None), None) self.assertEqual(MyOption.db_from("alpha"), "alpha") with self.assertRaises(ValueError) as cm: self.assertEqual(MyOption.db_from("x"), "x") def test_db_to(self): self.assertIs(MyOption.db_to(None), None) self.assertEqual(MyOption.db_to("alpha"), "alpha") with self.assertRaises(ValueError) as cm: self.assertEqual(MyOption.db_to("x"), "x") class TestMyOptionTuple(unittest.TestCase): def test_db_from(self): self.assertIs(MyOptionTuple.db_from(None), None) self.assertEqual(MyOptionTuple.db_from("alpha, beta, gamma "), ("alpha", "beta", "gamma")) with self.assertRaises(ValueError) as cm: self.assertEqual(MyOptionTuple.db_from("alpha, x, gamma "), ("alpha", "x", "gamma")) def test_db_to(self): self.assertIs(MyOptionTuple.db_to(None), None) self.assertEqual(MyOptionTuple.db_to(("alpha", "beta", "gamma")), "alpha,beta,gamma") with self.assertRaises(ValueError) as cm: self.assertEqual(MyOptionTuple.db_to(("alpha", "x", "gamma")), "alpha,x,gamma")<|fim▁end|>
self.assertIs(StrList.db_to(None), None) self.assertEqual(StrList.db_to(["alpha", "beta", "10.3", "gamma"]), "alpha,beta,10.3,gamma")
<|file_name|>choose-file.js<|end_file_name|><|fim▁begin|>(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["choose_file"] = factory(); else root["choose_file"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // __webpack_hash__ /******/ __webpack_require__.h = "05ce0eff1b9563477190"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var assign = __webpack_require__(4); var is_function = __webpack_require__(2); var is_presto = !!window.opera; var is_trident = document.all && !is_presto; var defaults = { multiple: false, accept: '*/*', success: function (input) {} }; var on = function (event, element, callback) { if (element.addEventListener) { element.addEventListener(event, callback, false); } else if (element.attachEvent) { element.attachEvent('on' + event, callback); } }; var input_remove = function (input) { is_trident || input.parentNode && input.parentNode.removeChild(input); // input.removeAttribute('accept'); // input.removeAttribute('style'); }; module.exports = function (params) { var input; var options; options = assign({}, defaults, is_function(params) ? { success: params } : params || {}); options.success = is_function(options.success) ? options.success : defaults.success; input = document.createElement('input'); input.setAttribute('style', 'position: absolute; clip: rect(0, 0, 0, 0);'); input.setAttribute('accept', options.accept); input.setAttribute('type', 'file'); input.multiple = !!options.multiple; on(is_trident ? 'input' : 'change', input, function (e) { if (is_presto) { input_remove(input); } if (input.value) { options.success(input); } }); (document.body || document.documentElement).appendChild(input); if (is_presto) { setTimeout(function () { input.click(); }, 0); } else { input.click(); input_remove(input); } }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var isObject = __webpack_require__(3); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = global.Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array constructors, and // PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 3 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 4 */ /***/ function(module, exports) { /* eslint-disable no-unused-vars */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; }<|fim▁hole|> return to; }; /***/ } /******/ ]) }); ;<|fim▁end|>
} } }
<|file_name|>oauth.py<|end_file_name|><|fim▁begin|>from rauth import OAuth1Service, OAuth2Service from flask import current_app, url_for, request, redirect, session import json class OAuthSignIn(object): providers = None def __init__(self, provider_name): self.provider_name = provider_name credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name] self.consumer_id = credentials['id'] self.consumer_secret = credentials['secret'] def authorize(self): pass def callback(self): pass def get_callback_url(self): return url_for('oauth_callback', provider=self.provider_name, _external=True) @classmethod def get_provider(self, provider_name): if self.providers is None: self.providers = {} for provider_class in self.__subclasses__(): provider = provider_class() self.providers[provider.provider_name] = provider return self.providers[provider_name]<|fim▁hole|> def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) class FacebookSignIn(OAuthSignIn): def __init__(self): super(FacebookSignIn, self).__init__('facebook') self.service = OAuth2Service( name='facebook', client_id=self.consumer_id, client_secret=self.consumer_secret, authorize_url='https://graph.facebook.com/oauth/authorize', access_token_url='https://graph.facebook.com/oauth/access_token', base_url='https://graph.facebook.com/' ) def authorize(self): return redirect(self.service.get_authorize_url( scope='email', response_type='code', redirect_uri=self.get_callback_url()) ) def callback(self): if 'code' not in request.args: return None, None, None , None , None, None,None oauth_session = self.service.get_auth_session( data={'code': request.args['code'], 'grant_type': 'authorization_code', 'redirect_uri': self.get_callback_url()} ) me = oauth_session.get('me').json() picture = oauth_session.get('me/picture') dump(me.get('bio')) return ( 'facebook$' + me['id'], me.get('email').split('@')[0], # Facebook does not provide # username, so the email's user # is used instead me.get('email'), me.get('gender'), me.get('timezone'), picture.url, me.get('locale') ) class GoogleSignIn(OAuthSignIn): def __init__(self): super(GoogleSignIn, self).__init__('google') self.service = OAuth2Service( name='google', base_url='https://www.googleapis.com/plus/v1/people/', authorize_url='https://accounts.google.com/o/oauth2/auth', access_token_url='https://accounts.google.com/o/oauth2/token', client_id=self.consumer_id, client_secret=self.consumer_secret ) def authorize(self): return redirect(self.service.get_authorize_url( scope='email', response_type='code', redirect_uri=self.get_callback_url()) ) def callback(self): if 'code' not in request.args: return None, None, None , None , None, None,None oauth_session = self.service.get_auth_session( data={'code': request.args['code'], 'grant_type': 'authorization_code', 'redirect_uri': self.get_callback_url()}, decoder=json.loads ) print dump(oauth_session.get('me')) me = oauth_session.get('me').json() #picture = oauth_session.get('me/picture') dump(me) return ( 'google$' + me['id'], me['emails'][0]['value'].split('@')[0], # Facebook does not provide # username, so the email's user # is used instead me['emails'][0]['value'], me['gender'], None, me['image']['url'], None ) class TwitterSignIn(OAuthSignIn): def __init__(self): super(TwitterSignIn, self).__init__('twitter') self.service = OAuth1Service( name='twitter', consumer_key=self.consumer_id, consumer_secret=self.consumer_secret, request_token_url='https://api.twitter.com/oauth/request_token', authorize_url='https://api.twitter.com/oauth/authorize', access_token_url='https://api.twitter.com/oauth/access_token', base_url='https://api.twitter.com/1.1/' ) def authorize(self): request_token = self.service.get_request_token( params={'oauth_callback': self.get_callback_url()} ) session['request_token'] = request_token return redirect(self.service.get_authorize_url(request_token[0])) def callback(self): request_token = session.pop('request_token') if 'oauth_verifier' not in request.args: return None, None, None , None , None,None,None oauth_session = self.service.get_auth_session( request_token[0], request_token[1], data={'oauth_verifier': request.args['oauth_verifier']} ) me = oauth_session.get('account/verify_credentials.json').json() social_id = 'twitter$' + str(me.get('id')) username = me.get('screen_name') return social_id, username, None , None , None , None,None # Twitter does not provide email<|fim▁end|>
<|file_name|>api.js<|end_file_name|><|fim▁begin|>import Telescope from 'meteor/nova:lib'; import Posts from "meteor/nova:posts"; import Comments from "meteor/nova:comments"; import Users from 'meteor/nova:users'; serveAPI = function(terms){ var posts = []; var parameters = Posts.parameters.get(terms); const postsCursor = Posts.find(parameters.selector, parameters.options); postsCursor.forEach(function(post) { var url = Posts.getLink(post); var postOutput = { title: post.title, headline: post.title, // for backwards compatibility author: post.author, date: post.postedAt, url: url, pageUrl: Posts.getPageUrl(post, true), guid: post._id }; if(post.body) postOutput.body = post.body; if(post.url) postOutput.domain = Telescope.utils.getDomain(url); if (post.thumbnailUrl) { postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl); } var twitterName = Users.getTwitterNameById(post.userId); if(twitterName) postOutput.twitterName = twitterName; <|fim▁hole|> Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) { var commentProperties = { body: comment.body, author: comment.author, date: comment.postedAt, guid: comment._id, parentCommentId: comment.parentCommentId }; comments.push(commentProperties); }); var commentsToDelete = []; comments.forEach(function(comment, index) { if (comment.parentCommentId) { var parent = comments.filter(function(obj) { return obj.guid === comment.parentCommentId; })[0]; if (parent) { parent.replies = parent.replies || []; parent.replies.push(JSON.parse(JSON.stringify(comment))); commentsToDelete.push(index); } } }); commentsToDelete.reverse().forEach(function(index) { comments.splice(index,1); }); postOutput.comments = comments; posts.push(postOutput); }); return JSON.stringify(posts); };<|fim▁end|>
var comments = [];
<|file_name|>multiple-macro-registrars.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //<|fim▁hole|>// except according to those terms. // error-pattern: multiple macro registration functions found #[feature(macro_registrar)]; // the registration function isn't typechecked yet #[macro_registrar] pub fn one() {} #[macro_registrar] pub fn two() {} fn main() {}<|fim▁end|>
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
<|file_name|>service.py<|end_file_name|><|fim▁begin|><|fim▁hole|> # Panopticon 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. # Panopticon 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 Panopticon. If not, see <http://www.gnu.org/licenses/>. from panopticon.core.base import ServiceAttribute from panopticon.core.actions.base import (ManagerDependantActionLauncher, DependantAction, DecoratorAction, ActionManager) class ServiceAction(ServiceAttribute, DependantAction): _excluded_values_names = ["manager"] def __init__(self, name=None, service=None, launcher=None): super(ServiceAction, self).__init__(name=name, service=service) DependantAction.__init__(self, launcher=launcher) def check_required(self, action): return action.service in self.service.required_services def set_running_env(self, running_env): running_env.action = self running_env.service = self.service def __repr__(self): fields = [] if self.service is not None: fields.append("service:'%s'" % self.service) if self.name is not None: fields.append("name:'%s'" % self.name) return "<%s %s>" % (self.__class__.__name__, " ".join(fields)) def __str__(self): if self.service is None: return self.name else: return ".".join((str(self.service), self.name)) class ServiceDecoratorAction(DecoratorAction, ServiceAction): def __init__(self, function, name=None, service=None, launcher=None): super(ServiceDecoratorAction, self).__init__(function) ServiceAction.__init__(self, name=name, service=service, launcher=launcher) service_action = ServiceDecoratorAction class ServiceActionLauncher(ManagerDependantActionLauncher, ServiceAction): def __init__(self, name=None, service=None, launcher=None): super(ServiceActionLauncher, self).__init__(name, service.roles) ServiceAction.__init__(self, name=name, service=service, launcher=launcher) def launch(self, *args, **kwargs): super(ServiceActionLauncher, self).launch(*args, **kwargs) class ServiceActionManager(ActionManager): action_launcher_class = ServiceActionLauncher _managed_obj_name = "service" _manager_attribute_class = ServiceAction def _get_base_dict(self): service_action_class = self.action_launcher_class actions = {} defined_action_names = [] for aname, action in self.service._meta["actions"]: defined_action_names.append(aname) actions[aname] = action for rname, role in self.service.roles: for raname, action in role.actions: if not raname in defined_action_names: new_action = service_action_class(name=raname, service=self.service) actions[raname] = new_action defined_action_names.append(raname) return actions<|fim▁end|>
# service.py is part of Panopticon.
<|file_name|>unknown_user_apply_for_membership_unit.py<|end_file_name|><|fim▁begin|>from rest_framework import generics from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from aklub.models import UserProfile, AdministrativeUnit from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope from rest_framework import serializers from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework import status from interactions.models import Interaction from interactions.interaction_types import * from ..serializers import GetOrCreateUserprofile, get_or_create_user_profile_fields class ApplyForMembershipSerializer( GetOrCreateUserprofile, ): administrative_unit = serializers.SlugRelatedField( required=True, queryset=AdministrativeUnit.objects.filter(), slug_field="id", ) skills = serializers.CharField(required=False, allow_blank=True) class Meta: model = UserProfile fields = get_or_create_user_profile_fields + [ "administrative_unit", "skills", ] class ApplyForMembershipView(generics.CreateAPIView): permission_classes = [TokenHasReadWriteScope | IsAuthenticated] required_scopes = ["can_create_userprofile_interaction"] serializer_class = ApplyForMembershipSerializer def post(self, request, *args, **kwargs): serializer = ApplyForMembershipSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) user, created = serializer.get_or_create_user_profile() administrative_unit = serializer.validated_data.get("administrative_unit") user.administrative_units.add(administrative_unit), interaction_type = membership_application_interaction_type() Interaction.objects.create(<|fim▁hole|> user=user, type=interaction_type, administrative_unit=administrative_unit, date_from=timezone.now(), subject=interaction_type.name, ) return Response( {"user_id": user.pk}, status=status.HTTP_200_OK, ) def test_apply_for_membership(administrative_unit_1, app_request): from rest_framework.reverse import reverse from freezegun import freeze_time url = reverse("unknown_user_apply_for_membership") post_data = { "first_name": "John", "last_name": "Dock", "telephone": "720000000", "email": "[email protected]", "note": "iam alergic to bees", "age_group": 2012, "birth_month": 12, "birth_day": 12, "street": "Belmont Avenue 2414", "city": "New York", "zip_code": "10458", "administrative_unit": administrative_unit_1.pk, "skills": "cooking", } current_date = timezone.now() with freeze_time(current_date): response = app_request.post(url, post_data) assert response.status_code == 200 new_user = UserProfile.objects.get(profileemail__email=post_data["email"]) assert new_user.pk == response.json()["user_id"] assert new_user.first_name == post_data["first_name"] assert new_user.last_name == post_data["last_name"] assert new_user.age_group == post_data["age_group"] assert new_user.birth_month == post_data["birth_month"] assert new_user.birth_day == post_data["birth_day"] assert new_user.street == post_data["street"] assert new_user.city == post_data["city"] assert new_user.zip_code == post_data["zip_code"] assert new_user.administrative_units.first() == administrative_unit_1 assert new_user.interaction_set.count() == 1 interaction = new_user.interaction_set.first() assert interaction.administrative_unit == administrative_unit_1 assert interaction.subject == "Žadost o Členství" assert interaction.date_from == current_date # second registration => user recognized and only new interaction is created! post_data["skills"] = "drawing" response = app_request.post(url, post_data) assert response.status_code == 200 assert new_user.interaction_set.count() == 2<|fim▁end|>
<|file_name|>text_input.ts<|end_file_name|><|fim▁begin|>import {InputWidget, InputWidgetView} from "./input_widget" import {input} from "core/dom" import * as p from "core/properties" import {bk_input} from "styles/widgets/inputs" export class TextInputView extends InputWidgetView { model: TextInput protected input_el: HTMLInputElement connect_signals(): void { super.connect_signals() this.connect(this.model.properties.name.change, () => this.input_el.name = this.model.name || "") this.connect(this.model.properties.value.change, () => this.input_el.value = this.model.value) this.connect(this.model.properties.disabled.change, () => this.input_el.disabled = this.model.disabled) this.connect(this.model.properties.placeholder.change, () => this.input_el.placeholder = this.model.placeholder) } render(): void { super.render() this.input_el = input({ type: "text", class: bk_input, name: this.model.name, value: this.model.value, disabled: this.model.disabled, placeholder: this.model.placeholder, }) this.input_el.addEventListener("change", () => this.change_input()) this.group_el.appendChild(this.input_el) } change_input(): void { this.model.value = this.input_el.value super.change_input() } } export namespace TextInput { export type Attrs = p.AttrsOf<Props> export type Props = InputWidget.Props & { value: p.Property<string> placeholder: p.Property<string> } } export interface TextInput extends TextInput.Attrs {} export class TextInput extends InputWidget { properties: TextInput.Props constructor(attrs?: Partial<TextInput.Attrs>) { super(attrs) } static initClass(): void { this.prototype.default_view = TextInputView this.define<TextInput.Props>({ value: [ p.String, "" ],<|fim▁hole|>TextInput.initClass()<|fim▁end|>
placeholder: [ p.String, "" ], }) } }
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>/* Periodically crawl web pages and alert the user of changes * Copyright (C) 2016 Owen Stenson * * 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/>. * * More information in the enclosed `LICENSE' file */ /* BS: * The biggest thing that a Command object needs to do is, given its * internal data and the current time, return the next time it should run. * There seem to be two ways of approaching this. * 1. each vector of Values is consolidated into a hash set of valid times: * this would be slightly costly in terms of initial construction and * memory usage, but fetching the 'next' valid value would be very fast. * 5 hash tables large enough to store `*****` is 263 bytes (134 u8s) * 2. fetch the 'next' valid value for each Value in the vector. that would * require implementing 'next' for Asterisk, Range, Constant, and Skip. * This would require less memory but maybe a little more cpu to find * 'next' an arbitrary (though effectively like 1 or 2) number of times. * It might be in our best interest to consolidate values also (e.g. * `2,1-3` and `1-3,3-4` are redundant), but I'm not sure how I'd do that. * (1) would probably be simpler, cleaner, and less interesting. * In hindsight, (1) involved a lot of redundant checks, so it is * certainly not an optimal use of cpu. It also makes spaghetti code * because the Gregorian calendar is awful. (2) is not an optimal use of * ram, but firing an event requires calling .contains() on a BTreeSet * of u8s instead of calling .next() on an arbitrary number of values. * 3. Populate (2)'s set of valid options and check once per minute. <|fim▁hole|> * Negligibly more expensive than (2), and probably more reliable. * It should probably have a test suite anyway, though smaller than what * (2) would require (and WAY smaller than what (1) would require). */ /* mod.rs * This file will eventually house framework to tie in functionality for * Calendar and Action and maybe Schedule. It shouldn't be hefty. */ pub mod value_itr; pub mod calendar;<|fim▁end|>
* Checks frequently, but there's not a lot there to mess up.
<|file_name|>presidentielcoin_sv.ts<|end_file_name|><|fim▁begin|><TS language="sv" version="2.1"> <context> <name>AcceptandPayOfferListPage</name> <message> <source>Pay Offer</source> <translation>pay erbjudande</translation> </message> <message> <source>Offer ID:</source> <translation>Erbjudandet ID:</translation> </message> <message> <source>The value associated with this offer.</source> <translation>Värdet associerat med detta erbjudande.</translation> </message> <message> <source>Lookup the OfferID from the blockchain DB</source> <translation>Slå upp OfferID från blockchain DB</translation> </message> <message> <source>Lookup Offer</source> <translation>lookup Erbjudandet</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Alias:</source> <translation>Alias:</translation> </message> <message> <source>Notes:</source> <translation>Anmärkningar:</translation> </message> <message> <source>Offer Details</source> <translation>Erbjudande Detaljer</translation> </message> <message> <source>Merchant:</source> <translation>Handelsfartyg:</translation> </message> <message> <source>Merchant Rating:</source> <translation>Butiksbetyg:</translation> </message> <message> <source>Title:</source> <translation>Titel:</translation> </message> <message> <source>Category:</source> <translation>Kategori:</translation> </message> <message> <source>Price:</source> <translation>Pris:</translation> </message> <message> <source>Currency:</source> <translation>Valuta:</translation> </message> <message> <source>Alias for Exchange Rate Peg:</source> <translation>Alias ​​för växelkurs:</translation> </message> <message> <source>Quantity Remaining:</source> <translation>Antal återstod:</translation> </message> <message> <source>Quantity Sold:</source> <translation>Kvantitet Sålt:</translation> </message> <message> <source>Description:</source> <translation>Beskrivning:</translation> </message> <message> <source>Purchase this offer</source> <translation>Köp detta erbjudande</translation> </message> <message> <source>Accept Offer</source> <translation>Acceptera erbjudande</translation> </message> <message> <source>Purchase an offer, coins will be used from your balance to complete the transaction</source> <translation>Köp ett erbjudande, kommer mynt användas från ditt saldo för att slutföra transaktionen</translation> </message> <message> <source>Select an Alias. You may right-click on the notes section and include your public or private profile information from this alias for the merchant</source> <translation>Välj ett Alias. Du kan högerklicka på avsnittet anteckningar och inkluderar din offentliga eller privata profilinformation från detta alias för handlaren</translation> </message> <message> <source>Click to open image in browser...</source> <translation>Klicka för att öppna bilden i webbläsare ...</translation> </message> <message> <source>Use Public Profile</source> <translation>Använd allmän profil</translation> </message> <message> <source>Use Private Profile</source> <translation>Använd Privat profil</translation> </message> <message> <source>Confirm Public Profile Inclusion</source> <translation>Bekräfta allmän profil Inclusion</translation> </message> <message> <source>Warning: You have already appended profile information to the notes for this purchase!</source> <translation>Varning: Du har redan bifogade profilinformation till noterna för detta köp!</translation> </message> <message> <source>Are you sure you wish to continue?</source> <translation>Är du säker på att du vill fortsätta?</translation> </message> <message> <source>Confirm Private Profile Inclusion</source> <translation>Bekräfta Privat profil integration</translation> </message> <message> <source>Could get alias profile data: </source> <translation>Kunde få alias profildata:</translation> </message> <message> <source>Couldn't find alias in the database: </source> <translation>Kunde inte hitta alias i databasen:</translation> </message> <message> <source>Could not refresh alias list: </source> <translation>Det gick inte att uppdatera alias lista:</translation> </message> <message> <source>You have successfully paid for this offer!</source> <translation>Du har betalat för detta erbjudande!</translation> </message> <message> <source>Could not find currency in the rates peg for this offer. Currency: </source> <translation>Det gick inte att hitta valuta i priset peg för detta erbjudande. Valuta:</translation> </message> <message> <source>Please enter pertinent information required to the offer in the 'Notes' field (address, e-mail address, shipping notes, etc).</source> <translation>Ange relevant information som krävs för att erbjudandet i "Notes" fältet (adress, e-postadress, sjöfart anteckningar, etc).</translation> </message> <message> <source>Stars</source> <translation>stjärnor</translation> </message> <message> <source>There was an exception trying to get the alias profile data: </source> <translation>Det fanns ett undantag försöka få alias profildata:</translation> </message> <message> <source>There was an exception trying to refresh the alias list: </source> <translation>Det var ett undantag som försöker uppdatera alias lista:</translation> </message> <message> <source>Purchase this offer, coins will be used from your balance to complete the transaction</source> <translation>Köp detta erbjudande, kommer mynt användas från ditt saldo för att slutföra transaktionen</translation> </message> <message> <source>Invalid quantity when trying to accept this offer!</source> <translation>Ogiltig mängd när man försöker att acceptera detta erbjudande!</translation> </message> <message> <source>Please choose an alias before purchasing this offer.</source> <translation>Välj ett alias innan du köper detta erbjudande.</translation> </message> <message> <source>Waiting for confirmation on the purchase of this offer</source> <translation>Väntar på bekräftelse på inköp av detta erbjudande</translation> </message> <message> <source>Could not find this offer, please ensure the offer has been confirmed by the blockchain: </source> <translation>Det gick inte att hitta detta erbjudande, vänligen se till att erbjudandet har bekräftats av blockchain:</translation> </message> <message> <source>There was an exception trying to locate this offer, please ensure the offer has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande, vänligen se till att erbjudandet har bekräftats av blockchain:</translation> </message> <message> <source>URI has been already handled</source> <translation>URI har redan hanterat</translation> </message> <message> <source>unlimited</source> <translation>obegränsat</translation> </message> </context> <context> <name>AcceptedOfferListPage</name> <message> <source>Accepted Offers</source> <translation>Godkända erbjudanden</translation> </message> <message> <source>Refresh accepted offer list</source> <translation>Uppdatera accepterad erbjudande lista</translation> </message> <message> <source>Copy the currently selected offer to the system clipboard</source> <translation>Kopiera valda erbjudande till systemets Urklipp</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Details of the selected accepted offer</source> <translation>Detaljer för den valda accepterade erbjudandet</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Send message to the seller</source> <translation>Skicka meddelande till säljaren</translation> </message> <message> <source>Send Msg To Seller</source> <translation>Skicka msg till Säljare</translation> </message> <message> <source>Leave Feedback</source> <translation>Lämna feedback</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are offers you have purchased. Offer operations take 2-5 minutes to become active. Right click on an offer to view more info such as the message you sent to the seller, quantity, date, etc. You can choose which aliases to view sales information for using the dropdown to the right.</source> <translation>Dessa är erbjudanden du har köpt. Erbjudande operationer tar 2-5 minuter för att bli aktiva. Högerklicka på ett erbjudande om att visa mer information såsom det meddelande som du skickas till säljaren, kvantitet, datum, etc. Du kan välja vilka alias för att visa försäljningsinformation för att använda rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy OfferAccept ID</source> <translation>Kopiera OfferAccept ID</translation> </message> <message> <source>Message Merchant</source> <translation>meddelande Merchant</translation> </message> <message> <source>Leave Feedback For Merchant</source> <translation>Lämna feedback För Merchant</translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>Export Offer Data</source> <translation>Export erbjudande Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Offer ID</source> <translation>erbjudandet ID</translation> </message> <message> <source>Accept ID</source> <translation>acceptera ID</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Height</source> <translation>Höjd</translation> </message> <message> <source>Price</source> <translation>Pris</translation> </message> <message> <source>Currency</source> <translation>Valuta</translation> </message> <message> <source>Qty</source> <translation>st</translation> </message> <message> <source>Total</source> <translation>Total</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Högerklicka för att ändra adressen eller etiketten.</translation> </message> <message> <source>Create a new address</source> <translation>Skapa ny adress</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Ny</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiera den markerade adressen till systemets Urklipp</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopiera</translation> </message> <message> <source>C&amp;lose</source> <translation>S&amp;täng</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Ta bort den valda adressen från listan</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportera</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Radera</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Välj en adress att sända betalning till</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Välj en adress att ta emot betalning till</translation> </message> <message> <source>C&amp;hoose</source> <translation>V&amp;älj</translation> </message> <message> <source>Sending addresses</source> <translation>Avsändaradresser</translation> </message> <message> <source>Receiving addresses</source> <translation>Mottagaradresser</translation> </message> <message> <source>These are your Presidentielcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Detta är dina Presidentielcoin-adresser för att skicka betalningar. Kolla alltid summan och den mottagande adressen innan du skickar Presidentielcoins.</translation> </message> <message> <source>These are your Presidentielcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Detta är dina Presidentielcoin-adresser för att ta emot betalningar. Det rekommenderas att använda en ny mottagningsadress för varje transaktion.</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Kopiera adress</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Kopiera &amp;etikett</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Ändra</translation> </message> <message> <source>Export Address List</source> <translation>Exportera adresslistan</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>(no label)</source> <translation>(ingen etikett)</translation> </message> </context> <context> <name>AliasListPage</name> <message> <source>Aliases</source> <translation>alias</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> <message> <source>Copy the currently selected alias to the system clipboard</source> <translation>Kopiera markerade alias till Urklipp</translation> </message> <message> <source>Copy Alias ID</source> <translation>Kopia Alias ​​ID</translation> </message> <message> <source>Send Msg</source> <translation>Skicka Msg</translation> </message> <message> <source>Sign Multisig Tx</source> <translation>Underteckna Multisig Tx</translation> </message> <message> <source>&lt;&lt;</source> <translation>&lt;&lt;</translation> </message> <message> <source>&gt;&gt;</source> <translation>&gt;&gt;</translation> </message> <message> <source>Search for Presidentielcoin Aliases. Select Safe Search from wallet options if you wish to omit potentially offensive Aliases(On by default)</source> <translation>Sök efter Presidentielcoin Alias. Välj Safesearch från plånbok alternativ om du vill utelämna potentiellt stötande Alias ​​(On standard)</translation> </message> <message> <source>Error searching alias: </source> <translation>Fel söka alias:</translation> </message> <message> <source>General exception when searching alias</source> <translation>Allmänt undantag när du söker alias</translation> </message> <message> <source>Current Page: </source> <translation>Nuvarande sida:</translation> </message> <message> <source>Enter search term, regex accepted (ie: ^name returns all Aliases starting with 'name'). Empty will search for all.</source> <translation>Ange sökord, regex accepteras (dvs. ^ namn returnerar alla Alias ​​börjar med "namn"). Tom kommer att söka efter alla.</translation> </message> <message> <source>Error: Invalid response from aliasfilter command</source> <translation>Fel: Ogiltigt svar från aliasfilter kommandot</translation> </message> </context> <context> <name>AliasTableModel</name> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Multisignature</source> <translation>Multisignature</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> <message> <source>Alias Status</source> <translation>alias Status</translation> </message> <message> <source>Buyer Rating</source> <translation>köparen Betyg</translation> </message> <message> <source>Seller Rating</source> <translation>säljaren betyg</translation> </message> <message> <source>Arbiter Rating</source> <translation>Arbiter Betyg</translation> </message> </context> <context> <name>AliasView</name> <message> <source>My Aliases</source> <translation>mina Alias</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Lösenordsdialog</translation> </message> <message> <source>Enter passphrase</source> <translation>Ange lösenord</translation> </message> <message> <source>New passphrase</source> <translation>Nytt lösenord</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Upprepa nytt lösenord</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Ange plånbokens nya lösenord. &lt;br/&gt; Använd ett lösenord på &lt;b&gt;tio eller fler slumpmässiga tecken,&lt;/b&gt; eller &lt;b&gt;åtta eller fler ord.&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Kryptera plånbok</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att låsa upp plånboken.</translation> </message> <message> <source>Unlock wallet</source> <translation>Lås upp plånbok</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att dekryptera plånboken.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Dekryptera plånbok</translation> </message> <message> <source>Change passphrase</source> <translation>Ändra lösenord</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Ge det gamla lösenordet och det nya lösenordet för plånboken.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Bekräfta kryptering av plånbok</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR PRESIDENTIELCOINS&lt;/b&gt;!</source> <translation>VARNING: Om du krypterar din plånbok och glömmer ditt lösenord, kommer du att &lt;b&gt;FÖRLORA ALLA DINA TILLGÅNGAR&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Är du säker på att du vill kryptera din plånbok?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Plånboken är krypterad</translation> </message> <message> <source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your presidentielcoins from being stolen by malware infecting your computer.</source> <translation>%1 stängs nu att avsluta krypteringsprocessen. Kom ihåg att kryptera din plånbok inte helt kan skydda dina presidentielcoins från stulna av malware infekterar datorn.</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>VIKTIGT: Alla tidigare säkerhetskopior du har gjort av plånbokens fil ska ersättas med den nya genererade, krypterade plånboks filen. Av säkerhetsskäl kommer tidigare säkerhetskopior av den okrypterade plånboks filen blir oanvändbara när du börjar använda en ny, krypterad plånbok.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Kryptering av plånbok misslyckades</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Kryptering av plånbok misslyckades på grund av ett internt fel. Din plånbok blev inte krypterad.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>De angivna lösenorden överensstämmer inte.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Upplåsning av plånbok misslyckades</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lösenordet för dekryptering av plånbok var felaktig.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Dekryptering av plånbok misslyckades</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Plånbokens lösenord har ändrats.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Varning: Caps Lock är påslaget!</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/nätmask</translation> </message> <message> <source>Banned Until</source> <translation>Bannad tills</translation> </message> </context> <context> <name>CertListPage</name> <message> <source>Certificates</source> <translation>certifikat</translation> </message> <message> <source>All Certificates</source> <translation>alla certifikat</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> <message> <source>Copy the currently selected cert to the system clipboard</source> <translation>Kopiera valda cert till Urklipp</translation> </message> <message> <source>Copy Certificate ID</source> <translation>Kopiera Certifikat-ID</translation> </message> <message> <source>&lt;&lt;</source> <translation>&lt;&lt;</translation> </message> <message> <source>&gt;&gt;</source> <translation>&gt;&gt;</translation> </message> <message> <source>Search for Presidentielcoin Certificates. Select Safe Search from wallet options if you wish to omit potentially offensive Certificates(On by default)</source> <translation>Sök efter Presidentielcoin certifikat. Välj Safesearch från plånbok alternativ om du vill utelämna potentiellt stötande certifikat (On standard)</translation> </message> <message> <source>Copy Value</source> <translation>Kopiera Värde</translation> </message> <message> <source>Enter search term, regex accepted (ie: ^name returns all Certificates starting with 'name'). Empty will search for all.</source> <translation>Ange sökord, regex accepteras (dvs. ^ namn returnerar alla certifikat som börjar med "namn"). Tom kommer att söka efter alla.</translation> </message> <message> <source>certificates</source> <translation>certifikat</translation> </message> <message> <source>Error searching Certificate: </source> <translation>Error söka Certifikat:</translation> </message> <message> <source>Current Page: </source> <translation>Nuvarande sida:</translation> </message> <message> <source>General exception when searching certficiates</source> <translation>Allmänt undantag när du söker certficiates</translation> </message> <message> <source>Error: Invalid response from certfilter command</source> <translation>Fel: Ogiltigt svar från certfilter kommandot</translation> </message> </context> <context> <name>CertTableModel</name> <message> <source>Cert</source> <translation>cert</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Private Data</source> <translation>Private Data</translation> </message> <message> <source>Public Data</source> <translation>Public Data</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Category</source> <translation>Kategori</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> <message> <source>Owner</source> <translation>Ägare</translation> </message> </context> <context> <name>CertView</name> <message> <source>My Certificates</source> <translation>Mina certifikat</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Myntval</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Bytes:</source> <translation>Antal byte:</translation> </message> <message> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <source>Dust:</source> <translation>Damm:</translation> </message> <message> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <source>Change:</source> <translation>Växel:</translation> </message> <message> <source>(un)select all</source> <translation>(av)markera allt</translation> </message> <message> <source>Tree mode</source> <translation>Trädvy</translation> </message> <message> <source>List mode</source> <translation>Listvy</translation> </message> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>Received with label</source> <translation>Mottagen med etikett</translation> </message> <message> <source>Received with address</source> <translation>Mottagen med adress</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Confirmations</source> <translation>Bekräftelser</translation> </message> <message> <source>Confirmed</source> <translation>Bekräftad</translation> </message> <message> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>Copy transaction ID</source> <translation>Kopiera transaktions ID</translation> </message> <message> <source>Lock unspent</source> <translation>Lås ospenderat</translation> </message> <message> <source>Unlock unspent</source> <translation>Lås upp ospenderat</translation> </message> <message> <source>Copy quantity</source> <translation>Kopiera kvantitet</translation> </message> <message> <source>Copy fee</source> <translation>Kopiera avgift</translation> </message> <message> <source>Copy after fee</source> <translation>Kopiera efter avgift</translation> </message> <message> <source>Copy bytes</source> <translation>Kopiera byte</translation> </message> <message> <source>Copy dust</source> <translation>Kopiera damm</translation> </message> <message> <source>Copy change</source> <translation>Kopiera växel</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 låst)</translation> </message> <message> <source>yes</source> <translation>ja</translation> </message> <message> <source>no</source> <translation>nej</translation> </message> <message> <source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source> <translation>Denna etikett blir röd om någon mottagaren får ett belopp som är mindre än den aktuella dammgränsen.</translation> </message> <message> <source>Can vary +/- %1 satoshi(s) per input.</source> <translation>Kan variera +/- %1 satoshi per inmatning.</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>växel från %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(växel)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Redigera adress</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etikett</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>Etiketten associerad med denna adresslistas post</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>Adressen associerad med denna adresslistas post. Detta kan bara ändras för sändningsadresser.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adress</translation> </message> <message> <source>New receiving address</source> <translation>Ny mottagaradress</translation> </message> <message> <source>New sending address</source> <translation>Ny avsändaradress</translation> </message> <message> <source>Edit receiving address</source> <translation>Redigera mottagaradress</translation> </message> <message> <source>Edit sending address</source> <translation>Redigera avsändaradress</translation> </message> <message> <source>The entered address "%1" is not a valid Presidentielcoin address.</source> <translation>Den angivna adressen "%1" är inte en giltig Presidentielcoin-adress.</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>Den angivna adressen "%1" finns redan i adressboken.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> <message> <source>New key generation failed.</source> <translation>Misslyckades med generering av ny nyckel.</translation> </message> </context> <context> <name>EditAliasDialog</name> <message> <source>Edit Alias</source> <translation>Redigera Alias</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>The alias name.</source> <translation>Aliasnamnet.</translation> </message> <message> <source>Public Profile:</source> <translation>Offentlig profil:</translation> </message> <message> <source>Safe Search:</source> <translation>Säker sökning:</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Expiry:</source> <translation>Upphörande:</translation> </message> <message> <source>Expire Time:</source> <translation>Löpa ut Tid:</translation> </message> <message> <source>Use Custom Expire Time</source> <translation>Använd Anpassad Upphör Tid</translation> </message> <message> <source>Miscellaneous</source> <translation>Diverse</translation> </message> <message> <source>Private Profile:</source> <translation>Privat profil:</translation> </message> <message> <source>Transfer To (Public Key):</source> <translation>Transfer till (Public Key):</translation> </message> <message> <source>Accept Certificate Transfers:</source> <translation>Acceptera certifikat Transfer:</translation> </message> <message> <source>Password:</source> <translation>Lösenord:</translation> </message> <message> <source>Alias Rate Peg:</source> <translation>Alias ​​Rate Peg:</translation> </message> <message> <source>Multi-Signature</source> <translation>Multi-signatur</translation> </message> <message> <source>Number of Required Signatures: </source> <translation>Antalet nödvändiga signaturer:</translation> </message> <message> <source>Add</source> <translation>Lägg till</translation> </message> <message> <source>Delete</source> <translation>Radera</translation> </message> <message> <source>OK</source> <translation>ok</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Choose an alias which has peg information. Consumers will pay conversion amounts and network fees based on this peg.</source> <translation>Välj ett alias som har peg information. Konsumenterna kommer att betala konvertering uppgår och nätavgifter baserade på denna pinne.</translation> </message> <message> <source>Choose a standard expiration time(in UTC) for this alias from 1 to 5 years or check the 'Use Custom Expire Time' check box to enter an expiration timestamp. It is exponentially more expensive per year, calculation is FEERATE*(2.88^years). FEERATE is the dynamic satoshi per byte fee set in the rate peg alias used for this alias.</source> <translation>Välj en standardförfallotid (i UTC) för detta alias från ett till fem år eller kontrollera "Använd anpassad Tid Löper" kryssrutan för att ange ett utgångstidsstämpel. Det är exponentiellt dyrare per år, är beräkningen FEERATE * (2,88 ^ år). FEERATE är den dynamiska satoshi per byte avgift som i takt peg alias som används för detta alias.</translation> </message> <message> <source>Warning: transferring your alias will transfer ownership all of your presidentielcoin services that use this alias.</source> <translation>Varning: överföra dina alias kommer att överföra äganderätten alla dina presidentielcoin tjänster som använder detta alias.</translation> </message> <message> <source>Is this alias safe to search? Anything that can be considered offensive to someone should be set to 'No' here. If you do create an alias that is offensive and do not set this option to 'No' your alias will be banned!</source> <translation>Är detta alias säkert att söka? Något som kan anses stötande för någon ska vara inställd på "Nej" här. Om du skapar ett alias som är stötande och inte ställa in det här alternativet till "nej" ditt alias kommer att förbjudas!</translation> </message> <message> <source>1 Year</source> <translation>1 år</translation> </message> <message> <source>2 Years</source> <translation>2 år</translation> </message> <message> <source>3 Years</source> <translation>3 år</translation> </message> <message> <source>4 Years</source> <translation>4 år</translation> </message> <message> <source>5 Years</source> <translation>5 år</translation> </message> <message> <source>This is to private profile information which is encrypted and only available to you. This is useful for when sending notes to a merchant through the payment screen so you don't have to type it out everytime.</source> <translation>Detta för att privata profilinformation som är krypterad och endast tillgänglig för dig. Detta är användbart när du skickar anteckningar till en köpman genom betalning skärmen så att du inte behöver skriva ut varje gång.</translation> </message> <message> <source>Enter a password or passphrase that will be used to unlock this alias via webservices such as BlockMarket. Important: Do not forget or misplace this password, it is the lock to your alias.</source> <translation>Ange ett lösenord eller lösenord som ska användas för att låsa upp detta alias via webservices som BlockMarket. Viktigt: Glöm inte eller tappar detta lösenord är det låset till ditt alias.</translation> </message> <message> <source>This is public profile information that anyone on the network can see. Fill this in with things you would like others to know about you.</source> <translation>Detta är allmän profilinformation som alla i nätverket kan se. Fyll detta med saker som du vill att andra ska veta om dig.</translation> </message> <message> <source>The number of required signatures ensures that not one person can control this alias and anything service that this alias uses (certificates, messages, offers, escrows).</source> <translation>Antalet nödvändiga underskrifter säkerställer att inte en person kan styra detta alias och något service som detta alias använda (intyg, meddelanden, erbjudanden, escrows).</translation> </message> <message> <source>Would you like to accept certificates transferred to this alias? Select 'Yes' otherwise if you want to block others from sending certificates to this alias select 'No'.</source> <translation>Vill du ta emot certifikat överförs till detta alias? Välj "Ja" på annat sätt om du vill blockera andra från att skicka certifikat till detta alias välj "Nej".</translation> </message> <message> <source>Set up your multisig alias here with the required number of signatures and the aliases that are capable of signing when this alias is updated. A user from this list can request an update to the alias and the other signers must sign the raw multisig transaction using the 'Sign Multisig Tx' button in order for the alias to complete the update. Services that use this alias require alias updates prior to updating those services which allows all services to benefit from alias multisig technology.</source> <translation>Ställ dina multisig alias här med erforderligt antal underskrifter och alias som kan undertecknandet när detta alias uppdateras. En användare från denna lista kan begära en uppdatering av alias och de andra undertecknarna måste underteckna den råa multisig transaktionen med hjälp av "Skriv Multisig Tx" -knappen för att alias för att slutföra uppdateringen. Tjänster som använder detta alias kräver alias uppdateras innan du uppdaterar de tjänster som gör att alla tjänster att dra nytta av alias multisig teknik.</translation> </message> <message> <source>This is a</source> <translation>Det här är en</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>multisig alias.</source> <translation>multisig alias.</translation> </message> <message> <source>Confirm Alias with large expiration</source> <translation>Bekräfta Alias ​​med stor utgångs</translation> </message> <message> <source>Warning: Using creating an alias expiring later than 5 years increases costs exponentially, you may spend a large amount of coins in doing so!</source> <translation>Varning: Med skapa ett alias löper senast 5 år ökar kostnaderna exponentiellt, du kan tillbringa en stor mängd mynt med detta!</translation> </message> <message> <source>Are you sure you wish to continue?</source> <translation>Är du säker på att du vill fortsätta?</translation> </message> <message> <source>Error creating new Alias: </source> <translation>Fel vid skapande av nya Alias:</translation> </message> <message> <source>Error updating Alias: </source> <translation>Fel vid uppdatering av Alias:</translation> </message> <message> <source>Error transferring Alias: </source> <translation>Fel överföra Alias:</translation> </message> <message> <source>The entered alias is not a valid Presidentielcoin alias. Alias: </source> <translation>Den angivna alias är inte en giltig Presidentielcoin alias. Alias:</translation> </message> <message> <source>New Alias</source> <translation>nytt Alias</translation> </message> <message> <source>Edit Data Alias</source> <translation>Redigera data Alias</translation> </message> <message> <source>Transfer Alias</source> <translation>överföra Alias</translation> </message> <message> <source>Enter an alias</source> <translation>Ange ett alias</translation> </message> <message> <source>Alias:</source> <translation>Alias:</translation> </message> <message> <source>Empty name for Alias not allowed. Please try again</source> <translation>Tom namn Alias ​​inte tillåtet. Var god försök igen</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>General exception creating new Alias</source> <translation>Allmänt undantag skapa nya Alias</translation> </message> <message> <source>General exception updating Alias</source> <translation>Allmänt undantag uppdatering Alias</translation> </message> <message> <source>General exception transferring Alias</source> <translation>Allmänt undantag överföra Alias</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> </context> <context> <name>EditCertDialog</name> <message> <source>Edit Cert</source> <translation>Redigera Cert</translation> </message> <message> <source>Alias:</source> <translation>Alias:</translation> </message> <message> <source>Certificate:</source> <translation>Certifikat:</translation> </message> <message> <source>The value associated with this certificate.</source> <translation>Värdet associerat med detta certifikat.</translation> </message> <message> <source>Title:</source> <translation>Titel:</translation> </message> <message> <source>The certificate name.</source> <translation>Certifikatet namn.</translation> </message> <message> <source>Transfer To:</source> <translation>Överföra till:</translation> </message> <message> <source>Public Data:</source> <translation>Public Data:</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Private Data:</source> <translation>Private Data:</translation> </message> <message> <source>Safe Search:</source> <translation>Säker sökning:</translation> </message> <message> <source>Category:</source> <translation>Kategori:</translation> </message> <message> <source>View Alias:</source> <translation>Visa Alias:</translation> </message> <message> <source>View-Only After Transfer:</source> <translation>Visa-Only Efter Transfer:</translation> </message> <message> <source>New Cert</source> <translation>nytt Cert</translation> </message> <message> <source>Transfer Cert</source> <translation>överföra Cert</translation> </message> <message> <source>certificates</source> <translation>certifikat</translation> </message> <message> <source>Enter the alias of the recipient of this certificate</source> <translation>Ange alias för mottagaren av detta intyg</translation> </message> <message> <source>Select Yes if you do not want this certificate to be editable/transferable by the recipient</source> <translation>Välj Ja om du inte vill att detta certifikat ska redigeras / överlåtas av mottagaren</translation> </message> <message> <source>This alias has expired, please choose another one</source> <translation>Detta alias har löpt ut, välj en annan</translation> </message> <message> <source>Select an alias to own this certificate</source> <translation>Välj ett alias att äga detta certifikat</translation> </message> <message> <source> is not safe to search so this setting can only be set to 'No'</source> <translation> är inte säkert att söka så här inställningen kan endast ställas in på 'Nej'</translation> </message> <message> <source>Is this cert safe to search? Anything that can be considered offensive to someone should be set to 'No' here. If you do create a cert that is offensive and do not set this option to 'No' your cert will be banned!</source> <translation>Är detta cert säkert att söka? Något som kan anses stötande för någon ska vara inställd på "Nej" här. Om du skapar en cert som är stötande och inte ställa in det här alternativet till "Nej" din cert kommer att förbjudas!</translation> </message> <message> <source>Could not refresh alias list: </source> <translation>Det gick inte att uppdatera alias lista:</translation> </message> <message> <source>There was an exception trying to refresh the alias list: </source> <translation>Det var ett undantag som försöker uppdatera alias lista:</translation> </message> <message> <source>Confirm Certificate Renewal</source> <translation>Bekräfta Certificate Förnyelse</translation> </message> <message> <source>Warning: This certificate is already expired!</source> <translation>Varning: Detta intyg är redan gått ut!</translation> </message> <message> <source>Do you want to create a new one with the same information?</source> <translation>Vill du skapa en ny med samma information?</translation> </message> <message> <source>Empty name for Cert not allowed. Please try again</source> <translation>Tom namn för Cert inte tillåtet. Var god försök igen</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error creating new Cert: </source> <translation>Fel vid skapande av nya Cert:</translation> </message> <message> <source>Error updating Cert: </source> <translation>Fel uppdatering Cert:</translation> </message> <message> <source>Error transferring Cert: </source> <translation>Error överföra Cert:</translation> </message> <message> <source>The entered cert is not a valid Presidentielcoin cert.</source> <translation>Den angivna cert är inte en giltig Presidentielcoin cert.</translation> </message> <message> <source>General exception creating new Cert</source> <translation>Allmänt undantag skapa nya Cert</translation> </message> <message> <source>General exception updating Cert</source> <translation>Allmänt undantag uppdatering Cert</translation> </message> <message> <source>General exception transferring Cert</source> <translation>Allmänt undantag överföra Cert</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> </context> <context> <name>EditOfferDialog</name> <message> <source>Edit Offer</source> <translation>Redigera erbjudande</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>Offer:</source> <translation>Erbjudande:</translation> </message> <message> <source>Title:</source> <translation>Titel:</translation> </message> <message> <source>Category:</source> <translation>Kategori:</translation> </message> <message> <source>Price:</source> <translation>Pris:</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Description:</source> <translation>Beskrivning:</translation> </message> <message> <source>Payment Options:</source> <translation>Betalningsalternativ:</translation> </message> <message> <source>Currency:</source> <translation>Valuta:</translation> </message> <message> <source>Certificate:</source> <translation>Certifikat:</translation> </message> <message> <source>Root Offer:</source> <translation>Root Erbjudande:</translation> </message> <message> <source>Miscellaneous</source> <translation>Diverse</translation> </message> <message> <source>Seller Alias:</source> <translation>Säljare Alias:</translation> </message> <message> <source>Alias Rate Peg:</source> <translation>Alias ​​Rate Peg:</translation> </message> <message> <source>Private:</source> <translation>Privat:</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>Safe Search:</source> <translation>Säker sökning:</translation> </message> <message> <source>Geolocation:</source> <translation>Geolocation:</translation> </message> <message> <source>Commission:</source> <translation>Provision:</translation> </message> <message> <source>OK</source> <translation>ok</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Select Certificate (optional)</source> <translation>Välj certifikat (tillval)</translation> </message> <message> <source>New Offer</source> <translation>nytt erbjudande</translation> </message> <message> <source>Edit Linked Offer</source> <translation>Redigera kombinationserbjudande</translation> </message> <message> <source>New Offer(Certificate)</source> <translation>Nytt erbjudande (Certificate)</translation> </message> <message> <source>certificates</source> <translation>certifikat</translation> </message> <message> <source>Could not find this offer, please ensure offer has been confirmed by the blockchain</source> <translation>Det gick inte att hitta detta erbjudande, har du se erbjudande bekräftats av blockchain</translation> </message> <message> <source>There was an exception trying to locate this offer, please ensure offer has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande, vänligen se erbjudandet har bekräftats av blockchain:</translation> </message> <message> <source>There was an exception trying to refresh the cert list: </source> <translation>Det var ett undantag som försöker uppdatera cert lista:</translation> </message> <message> <source>You may change the alias rate peg through your alias settings</source> <translation>Du kan ändra alias hastigheten peg genom ditt alias inställningar</translation> </message> <message> <source>Choose if you would like the offer to be private or publicly listed on the marketplace</source> <translation>Välj om du vill erbjudandet att vara privat eller offentligt noterade på marknaden</translation> </message> <message> <source>If you wish you may enter your merchant geolocation (latitude and longitude coordinates) to help track shipping rates and other logistics information</source> <translation>Om du vill kan du ange din handlare geografisk (latitud och longitud) för att spåra fraktkostnader och andra informationslogistik</translation> </message> <message> <source>You will receive payment in Presidentielcoin equivalent to the Market-value of the currency you have selected</source> <translation>Du kommer att få betalt i Presidentielcoin motsvarande marknadsvärdet av den valuta du har valt</translation> </message> <message> <source>Choose which crypto-currency you want to allow as a payment method for this offer. Your choices are any combination of PRC, BTC or ZEC. An example setting for all three: 'PRC+BTC+ZEC'. For PRC and ZEC: 'PRC+ZEC'. Please note that in order spend coins paid to you via Presidentielcoin Marketplace, you will need to import your Presidentielcoin private key in external wallet(s) if BTC or ZEC are chosen.</source> <translation>Välj vilken krypto valuta du vill tillåta en betalningsmetod för detta erbjudande. Dina val är någon kombination av PRC, BTC eller ZEC. Ett exempel inställning för alla tre: "PRC + BTC + ZEC". För PRC och ZEC: 'PRC + ZEC'. Observera att för spendera mynt som betalas till dig via Presidentielcoin Marketplace, måste du importera din Presidentielcoin privata nyckel i yttre plånbok (s) om BTC eller ZEC väljs.</translation> </message> <message> <source>Enter the 'percentage' amount(without the % sign) that you would like to mark-up the price to</source> <translation>Ange "procent" belopp (utan% tecken) som du vill markera upp priset till</translation> </message> <message> <source>Warning: alias peg not found. No currency information available for </source> <translation>Varning: alias nypa hittades inte. Ingen valuta angiven för</translation> </message> <message> <source> is not safe to search so this setting can only be set to 'No'</source> <translation> är inte säkert att söka så här inställningen kan endast ställas in på 'Nej'</translation> </message> <message> <source>Is this offer safe to search? Anything that can be considered offensive to someone should be set to 'No' here. If you do create an offer that is offensive and do not set this option to 'No' your offer will be banned aswell as possibly your store alias!</source> <translation>Är detta erbjudande säkert att söka? Något som kan anses stötande för någon ska vara inställd på "Nej" här. Om du skapar ett erbjudande som är stötande och inte ställa in det här alternativet till "Nej" ditt erbjudande kommer att förbjudas också som möjligen din butik alias!</translation> </message> <message> <source>This alias has expired, please choose another one</source> <translation>Detta alias har löpt ut, välj en annan</translation> </message> <message> <source>Select an alias to own this offer</source> <translation>Välj ett alias att äga detta erbjudande</translation> </message> <message> <source>This will automatically use the alias which owns the certificate you are selling</source> <translation>Detta kommer automatiskt att använda alias som äger certifikatet du säljer</translation> </message> <message> <source>Could not refresh cert list: </source> <translation>Det gick inte att uppdatera cert lista:</translation> </message> <message> <source>Could not refresh alias list: </source> <translation>Det gick inte att uppdatera alias lista:</translation> </message> <message> <source>There was an exception trying to refresh the alias list: </source> <translation>Det var ett undantag som försöker uppdatera alias lista:</translation> </message> <message> <source>unlimited</source> <translation>obegränsat</translation> </message> <message> <source>Confirm Offer Renewal</source> <translation>Bekräfta erbjudande Förnyelse</translation> </message> <message> <source>Warning: This offer is already expired!</source> <translation>Varning: Detta erbjudande redan gått ut!</translation> </message> <message> <source>Do you want to create a new one with the same information?</source> <translation>Vill du skapa en ny med samma information?</translation> </message> <message> <source>Empty name for Offer not allowed. Please try again</source> <translation>Tom namn för Erbjudandet inte tillåtet. Var god försök igen</translation> </message> <message> <source>Confirm Alias Peg</source> <translation>Bekräfta Alias ​​Peg</translation> </message> <message> <source>Warning: Are you sure you wish to choose this alias as your offer peg? By default the system peg is</source> <translation>Varning: Är du säker på att du vill välja detta alias som ditt erbjudande peg? Som standard system PEG</translation> </message> <message> <source>Error creating new Offer: </source> <translation>Fel vid skapande av nya erbjudande:</translation> </message> <message> <source>General exception creating new Offer: </source> <translation>Allmänt undantag skapar nytt erbjudande:</translation> </message> <message> <source>Error updating Offer: </source> <translation>Fel vid uppdatering av Bud:</translation> </message> <message> <source>General exception updating Offer: </source> <translation>Allmänt undantag uppdatering Erbjudande:</translation> </message> <message> <source>The entered offer is not a valid Presidentielcoin offer</source> <translation>Den angivna Erbjudandet är inte ett giltigt Presidentielcoin erbjudande</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> </context> <context> <name>EditWhitelistOfferDialog</name> <message> <source>Manage Affiliates</source> <translation>hantera Affiliates</translation> </message> <message> <source>Refresh affiliate list</source> <translation>Uppdatera affiliate lista</translation> </message> <message> <source>Add a new affiliate</source> <translation>Lägg till en ny affiliate</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Add</source> <translation>Lägg till</translation> </message> <message> <source>Remove an affiliate</source> <translation>Ta bort en affiliate</translation> </message> <message> <source>Remove</source> <translation>Ta bort</translation> </message> <message> <source>Remove all affiliates</source> <translation>Ta bort alla medlemsförbund</translation> </message> <message> <source>Remove All</source> <translation>Ta bort allt</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are the affiliates for your offer. Affiliate operations take 2-5 minutes to become active. You may specify discount levels for each affiliate or control who may resell your offer.</source> <translation>Dessa är dotterbolag för ditt erbjudande. Affiliate verksamhet tar 2-5 minuter för att bli aktiva. Du kan ange rabattnivåer för varje dotterbolag eller kontroll som kan sälja ditt erbjudande.</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Entry removed successfully!</source> <translation>Entry bort framgångsrikt!</translation> </message> <message> <source>There was an exception trying to remove this entry: </source> <translation>Det fanns ett undantag att försöka ta bort denna post:</translation> </message> <message> <source>Affiliate list cleared successfully!</source> <translation>Affiliate lista rensas med framgång!</translation> </message> <message> <source>There was an exception trying to clear the affiliate list: </source> <translation>Det var ett undantag som försöker rensa affiliate lista:</translation> </message> <message> <source>Copy Alias</source> <translation>kopia Alias</translation> </message> <message> <source>Could not remove this entry: </source> <translation>Det gick inte att ta bort denna post:</translation> </message> <message> <source>Could not clear the affiliate list: </source> <translation>Det gick inte att ta bort affiliate lista:</translation> </message> <message> <source>Could not refresh the affiliate list: </source> <translation>Det gick inte att uppdatera affiliate lista:</translation> </message> <message> <source>There was an exception trying to refresh the affiliate list: </source> <translation>Det var ett undantag som försöker uppdatera affiliate lista:</translation> </message> <message> <source>Export Affiliate Data</source> <translation>Export Affiliate Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> <message> <source>Discount</source> <translation>Rabatt</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>EscrowInfoDialog</name> <message> <source>Escrow Info</source> <translation>depositions info</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>Escrow Details</source> <translation>depositions Detaljer</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Offer ID:</source> <translation>Erbjudandet ID:</translation> </message> <message> <source>TXID:</source> <translation>TXID:</translation> </message> <message> <source>Offer Title:</source> <translation>Erbjudandet Titel:</translation> </message> <message> <source>Height:</source> <translation>Höjd:</translation> </message> <message> <source>Time:</source> <translation>Tid:</translation> </message> <message> <source>Price:</source> <translation>Pris:</translation> </message> <message> <source>Escrow Fee:</source> <translation>Escrow Fee:</translation> </message> <message> <source>Total:</source> <translation>Totalt:</translation> </message> <message> <source>Average Rating:</source> <translation>Betyg i genomsnitt:</translation> </message> <message> <source>Shipping Contact Information:</source> <translation>Frakt Kontaktuppgifter:</translation> </message> <message> <source>Redeem TXID:</source> <translation>Återlösa TXID:</translation> </message> <message> <source>Buyer Feedback</source> <translation>köparen Feedback</translation> </message> <message> <source>Seller Feedback</source> <translation>säljare Feedback</translation> </message> <message> <source>Arbiter Feedback</source> <translation>arbiter Feedback</translation> </message> <message> <source>OK</source> <translation>ok</translation> </message> <message> <source>External TXID:</source> <translation>Extern TXID:</translation> </message> <message> <source>No Feedback Found</source> <translation>Ingen Feedback Hittat</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Arbiter</source> <translation>Arbiter</translation> </message> <message> <source>Feedback #</source> <translation>Återkoppling #</translation> </message> <message> <source>(Buyer)</source> <translation>(Köpare)</translation> </message> <message> <source>(Merchant)</source> <translation>(Handelsfartyg)</translation> </message> <message> <source>(Arbiter)</source> <translation>(Arbiter)</translation> </message> <message> <source>Stars</source> <translation>stjärnor</translation> </message> <message> <source>No Rating</source> <translation>Ingen Betyg</translation> </message> <message> <source>No Feedback</source> <translation>Ingen feedback</translation> </message> <message> <source>From:</source> <translation>Från:</translation> </message> <message> <source>Rating:</source> <translation>Betyg:</translation> </message> <message> <source>PRC</source> <translation>PRC</translation> </message> <message> <source>Could not find this escrow, please ensure the escrow has been confirmed by the blockchain</source> <translation>Det gick inte att hitta denna spärrade, se till det spärrade har bekräftats av blockchain</translation> </message> <message> <source>There was an exception trying to locate this escrow, please ensure the escrow has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta spärrade, se till det spärrade har bekräftats av blockchain:</translation> </message> </context> <context> <name>EscrowListPage</name> <message> <source>Escrows</source> <translation>escrows</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> <message> <source>Copy the currently selected escrow to the system clipboard</source> <translation>Kopiera valda spärrade till Urklipp</translation> </message> <message> <source>Copy Escrow ID</source> <translation>Kopiera Escrow ID</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Manage Escrow</source> <translation>hantera Escrow</translation> </message> <message> <source>Acknowledge Payment</source> <translation>erkänna Betalning</translation> </message> <message> <source>&lt;&lt;</source> <translation>&lt;&lt;</translation> </message> <message> <source>&gt;&gt;</source> <translation>&gt;&gt;</translation> </message> <message> <source>Search for Presidentielcoin Escrows.</source> <translation>Sök efter Presidentielcoin escrows.</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Enter search term. Search for arbiter/seller or escrow GUID. Empty will search for all.</source> <translation>Ange sökord. Sök efter domaren / säljare eller spärrade GUID. Tom kommer att söka efter alla.</translation> </message> <message> <source>Confirm Escrow Acknowledgement</source> <translation>Bekräfta Escrow Bekräftelse</translation> </message> <message> <source>Warning: You are about to acknowledge this payment from the buyer. If you are shipping an item, please communicate a tracking number to the buyer via a Presidentielcoin message.</source> <translation>Varning: Du är på väg att erkänna denna betalning från köparen. Om du skickar ett objekt, vänligen meddela ett spårningsnummer till köparen via ett Presidentielcoin meddelande.</translation> </message> <message> <source>Are you sure you wish to acknowledge this payment?</source> <translation>Är du säker på att du vill bekräfta denna betalning?</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error acknowledging escrow payment: </source> <translation>Fel erkänna spärrade betalning:</translation> </message> <message> <source>Error searching Escrow: </source> <translation>Error söka Escrow:</translation> </message> <message> <source>Current Page: </source> <translation>Nuvarande sida:</translation> </message> <message> <source>General exception acknowledging escrow payment</source> <translation>Allmänt undantag erkänner depositions betalning</translation> </message> <message> <source>General exception when searching escrow</source> <translation>Allmänt undantag när du söker spärrade</translation> </message> <message> <source>Error: Invalid response from escrowfilter command</source> <translation>Fel: Ogiltigt svar från escrowfilter kommandot</translation> </message> </context> <context> <name>EscrowTableModel</name> <message> <source>Escrow</source> <translation>spärrade</translation> </message> <message> <source>Time</source> <translation>Tid</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Arbiter</source> <translation>Arbiter</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Total</source> <translation>Total</translation> </message> <message> <source>Rating</source> <translation>Betyg</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> </context> <context> <name>EscrowView</name> <message> <source>My Escrows</source> <translation>mina escrows</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>En ny datakatalog kommer att skapas.</translation> </message> <message> <source>name</source> <translation>namn</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Katalogen finns redan. Läggtill %1 om du vill skapa en ny katalog här.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Sökvägen finns redan, och är inte en katalog.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Kan inte skapa datakatalog här.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>version</translation> </message> <message> <source>Presidentielcoin Client</source> <translation>Presidentielcoin Klient</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About %1</source> <translation>Om %1</translation> </message> <message> <source>Command-line options</source> <translation>Kommandoradsalternativ</translation> </message> <message> <source>Usage:</source> <translation>Användning:</translation> </message> <message> <source>command-line options</source> <translation>kommandoradsalternativ</translation> </message> <message> <source>UI Options:</source> <translation>UI-inställningar:</translation> </message> <message> <source>Choose data directory on startup (default: %u)</source> <translation>Välj datakatalog vid uppstart (standard: %u)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Ange språk, till exempel "de_DE" (standard: systemspråk)</translation> </message> <message> <source>Start minimized</source> <translation>Starta minimerad</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Ange SSL rotcertifikat för betalningsansökan (standard: -system-)</translation> </message> <message> <source>Show splash screen on startup (default: %u)</source> <translation>Visa startbild vid uppstart (standard: %u)</translation> </message> <message> <source>Reset all settings changed in the GUI</source> <translation>Återställ alla inställningar som gjorts i GUI</translation> </message> </context> <context> <name>InMessageListPage</name> <message> <source>These are Presidentielcoin messages you have received. You can choose which aliases to view related messages using the dropdown to the right.</source> <translation>Dessa är Presidentielcoin meddelanden som du har tagit emot. Du kan välja vilka alias för att visa relaterade meddelanden med hjälp av rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy Subject</source> <translation>Kopiera Ämne</translation> </message> <message> <source>Copy Msg</source> <translation>kopiera Msg</translation> </message> <message> <source>New Msg</source> <translation>nya Msg</translation> </message> <message> <source>Reply Msg</source> <translation>Svara Msg</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Export Message Data</source> <translation>Export meddelandedata</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>GUID</source> <translation>GUID</translation> </message> <message> <source>Time</source> <translation>Tid</translation> </message> <message> <source>From</source> <translation>Från</translation> </message> <message> <source>To</source> <translation>Till</translation> </message> <message> <source>Subject</source> <translation>Ämne</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Välkommen</translation> </message> <message> <source>Welcome to %1.</source> <translation>Välkommen till %1.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where %1 will store its data.</source> <translation>Eftersom detta är första gången programmet startas får du välja var %1 skall lagra sitt data.</translation> </message> <message> <source>%1 will download and store a copy of the Presidentielcoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>%1 kommer att ladda ner och spara en kopia av Presidentielcoin blockkedjan. Åtminstone %2GB av data kommer att sparas i denna katalog, och den kommer att växa över tiden. Plånboken kommer också att sparas i denna katalog.</translation> </message> <message> <source>Use the default data directory</source> <translation>Använd den förvalda datakatalogen</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Använd en anpassad datakatalog:</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Fel: Den angivna datakatalogen "%1" kan inte skapas.</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB fritt utrymme kvar</numerusform><numerusform>%n GB fritt utrymme kvar</numerusform></translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(av %n GB behövs)</numerusform><numerusform>(av %n GB behövs)</numerusform></translation> </message> </context> <context> <name>ManageEscrowDialog</name> <message> <source>Manage Your Escrow</source> <translation>Hantera din Escrow</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Release this escrow to the seller</source> <translation>Släpp denna depositions till säljaren</translation> </message> <message> <source>Release Escrow</source> <translation>frisättning Escrow</translation> </message> <message> <source>Refund this escrow back to the buyer</source> <translation>Återbetala denna depositions tillbaka till köparen</translation> </message> <message> <source>Refund Escrow</source> <translation>återbetalning Escrow</translation> </message> <message> <source> Stars</source> <translation>stjärnor</translation> </message> <message> <source>Cannot find this escrow on the network, please try again later.</source> <translation>Det går inte att hitta denna spärrade på nätet, försök igen senare.</translation> </message> <message> <source>You cannot manage this escrow because you do not own one of either the buyer, merchant or arbiter aliases.</source> <translation>Du kan inte hantera detta spärrade eftersom du inte äger en av antingen köparen, säljaren eller skiljedomare alias.</translation> </message> <message> <source>Claim Payment</source> <translation>anspråk Betalning</translation> </message> <message> <source>Warning: Payment has already been released, are you sure you wish to re-release payment to the merchant?</source> <translation>Varning: Betalning har redan släppts, är du säker på att du vill återutgivning betalning till handlaren?</translation> </message> <message> <source>Claim Refund</source> <translation>krav återbetalning</translation> </message> <message> <source>You are managing escrow ID</source> <translation>Du hanterar spärrade ID</translation> </message> <message> <source>Offer:</source> <translation>Erbjudande:</translation> </message> <message> <source>totalling</source> <translation>totalt</translation> </message> <message> <source>The buyer:</source> <translation>Köparen:</translation> </message> <message> <source>merchant:</source> <translation>handelsfartyg:</translation> </message> <message> <source>arbiter:</source> <translation>arbiter:</translation> </message> <message> <source>You are the 'buyer' of the offer held in escrow, you may release the coins to the merchant once you have confirmed that you have recieved the item as per the description of the offer.</source> <translation>Du är "köpare" av erbjudandet hållas i deposition, kan du släpper mynten till handlaren när du har bekräftat att du har fått varan enligt beskrivningen av erbjudandet.</translation> </message> <message> <source>You are the 'merchant' of the offer held in escrow, you may refund the coins back to the buyer.</source> <translation>Du är "köpman" av erbjudandet hållas i deposition, kan du återbetala mynten tillbaka till köparen.</translation> </message> <message> <source>You are the 'arbiter' of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the merchant did not honour the agreement to ship the offer item. You may also release the coins to the merchant if the buyer has not released in a timely manor. You may use Presidentielcoin messages to communicate with the buyer and merchant to ensure you have adequate proof for your decision.</source> <translation>Du är "domare" av erbjudandet hållas i deposition, kan du återbetala mynten tillbaka till köparen om du har bevis för att handlaren inte hedra avtalet att leverera erbjudandet objektet. Du kan också släppa mynten till handlaren om köparen inte har släppt i en tid herrgård. Du kan använda Presidentielcoin meddelanden för att kommunicera med köparen och handlaren för att du har tillräckliga bevis för ditt beslut.</translation> </message> <message> <source>You are the 'buyer' of the offer held in escrow. The escrow has been released to the merchant. You may communicate with your arbiter or merchant via Presidentielcoin messages. You may leave feedback after the money is claimed by the merchant.</source> <translation>Du är "köpare" av erbjudandet hållas i deposition. Spärr har lämnats till handlaren. Du kan kommunicera med din domare eller handelsfartyg via Presidentielcoin meddelanden. Du kan lämna feedback efter de pengar begärs av säljaren.</translation> </message> <message> <source>You are the 'merchant' of the offer held in escrow. The payment of coins have been released to you, you may claim them now. After claiming, please return to this dialog and provide feedback for this escrow transaction.</source> <translation>Du är "köpman" av erbjudandet hållas i deposition. Betalningen av mynt har släppts till dig, du kan göra anspråk på dem nu. Efter anspråk, gå tillbaka till denna dialog och ge återkoppling för denna spärrade transaktion.</translation> </message> <message> <source>You are the 'arbiter' of the offer held in escrow. The escrow has been released to the merchant. You may re-release this escrow if there are any problems claiming the coins by the merchant. If you were the one to release the coins you will recieve a commission as soon as the merchant claims his payment. You may leave feedback after the money is claimed by the merchant.</source> <translation>Du är "domare" av erbjudandet hållas i deposition. Spärr har lämnats till handlaren. Du kan återutgivning detta spärrade om det finns några problem som hävdar mynten av handlaren. Om du var en att släppa mynt kommer du att få en provision så snart handlaren hävdar hans betalning. Du kan lämna feedback efter de pengar begärs av säljaren.</translation> </message> <message> <source>You are the 'buyer' of the offer held in escrow. The coins have been refunded back to you, you may claim them now. After claiming, please return to this dialog and provide feedback for this escrow transaction.</source> <translation>Du är "köpare" av erbjudandet hållas i deposition. Mynten har betalas tillbaka till dig, du kan göra anspråk på dem nu. Efter anspråk, gå tillbaka till denna dialog och ge återkoppling för denna spärrade transaktion.</translation> </message> <message> <source>You are the 'merchant' of the offer held in escrow. The escrow has been refunded back to the buyer. You may leave feedback after the money is claimed by the buyer.</source> <translation>Du är "köpman" av erbjudandet hållas i deposition. Depositions har betalas tillbaka till köparen. Du kan lämna feedback efter de pengar begärs av köparen.</translation> </message> <message> <source>You are the 'arbiter' of the offer held in escrow. The escrow has been refunded back to the buyer. You may re-issue a refund if there are any problems claiming the coins by the buyer. If you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund. You may leave feedback after the money is claimed by the buyer.</source> <translation>Du är "domare" av erbjudandet hållas i deposition. Depositions har betalas tillbaka till köparen. Du kan åter utfärda en återbetalning om det finns några problem som hävdar mynten av köparen. Om du var en att återbetala mynten kommer du att få en provision så snart som köparen hävdar sin återbetalning. Du kan lämna feedback efter de pengar begärs av köparen.</translation> </message> <message> <source>Warning: Payment has already been refunded, are you sure you wish to re-refund payment back to the buyer?</source> <translation>Varning: Betalning har redan återbetalats, är du säker på att du vill åter återbetalning betalning tillbaka till köparen?</translation> </message> <message> <source>The escrow has been successfully claimed by the merchant. The escrow is complete.</source> <translation>Depositions har framgångsrikt hävdat handlaren. Det spärrade är klar.</translation> </message> <message> <source>Leave Feedback</source> <translation>Lämna feedback</translation> </message> <message> <source>The escrow has been successfully refunded to the buyer. The escrow is complete.</source> <translation>Depositions har framgångsrikt återbetalas till köparen. Det spärrade är klar.</translation> </message> <message> <source>The escrow status was not recognized. Please contact the Presidentielcoin team.</source> <translation>Depositions status kunde inte identifieras. Vänligen kontakta Presidentielcoin laget.</translation> </message> <message> <source>arbiter</source> <translation>arbiter</translation> </message> <message> <source>seller</source> <translation>säljare</translation> </message> <message> <source>reseller</source> <translation>återförsäljare</translation> </message> <message> <source>buyer</source> <translation>köpare</translation> </message> <message> <source>none</source> <translation>ingen</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Thank you for your feedback!</source> <translation>Tack för din feedback!</translation> </message> <message> <source>Error sending feedback: </source> <translation>Fel att skicka feedback:</translation> </message> <message> <source>Error completing release: </source> <translation>Error fullborda release:</translation> </message> <message> <source>Error completing refund: </source> <translation>Fel att fylla återbetalning:</translation> </message> <message> <source>Could not send raw escrow transaction to the blockchain. Chain: </source> <translation>Det gick inte att skicka rå spärrade transaktion till blockchain. Kedja:</translation> </message> <message> <source>Could not send raw escrow transaction to the blockchain, error: </source> <translation>Det gick inte att skicka rå spärrade transaktionen till blockchain, fel:</translation> </message> <message> <source>Could not find escrow payment on the blockchain, please ensure that the payment transaction has been confirmed on the network. Payment ID has been copied to your clipboard for your reference. error: </source> <translation>Kunde inte hitta spärrade betalning på blockchain, se till att betalningstransaktionen har bekräftats i nätverket. Betalning ID har kopierats till Urklipp som referens. fel:</translation> </message> <message> <source>Escrow payment found in the blockchain but it has not been confirmed yet. Please try again later. Payment ID has been copied to your clipboard for your reference. Chain: </source> <translation>Spärrade betalning finns i blockchain men det har inte bekräftats ännu. Försök igen senare. Betalning ID har kopierats till Urklipp som referens. Kedja:</translation> </message> <message> <source>Error releasing escrow: </source> <translation>Error frigördepositions:</translation> </message> <message> <source>Error refunding escrow: </source> <translation>Fel återbetalning depositions:</translation> </message> <message> <source>Could not get alias information: </source> <translation>Det gick inte att få alias information:</translation> </message> <message> <source>There was an exception trying to get alias information: </source> <translation>Det fanns ett undantag försöker få alias information:</translation> </message> <message> <source>General exception sending feedbackescrow</source> <translation>Allmänt undantag sändande feedbackescrow</translation> </message> <message> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <source>ZCash</source> <translation>ZCash</translation> </message> <message> <source>Escrow release completed successfully! Escrow spending payment was found on the blockchain. You may click on the 'Check External Payment' button to check to see if it has confirmed. Chain: </source> <translation>Escrow frigivning slutförts! Spärrade utgifterna betalningen finns på blockchain. Du kan klicka på knappen "Kontrollera extern betalning" för att kontrollera om det har bekräftats. Kedja:</translation> </message> <message> <source>Escrow release completed successfully! </source> <translation>Escrow frigivning slutförts!</translation> </message> <message> <source>General exception completing release</source> <translation>Allmänt undantag fullborda frigöring</translation> </message> <message> <source>Escrow refund completed successfully! Escrow spending payment was found on the blockchain. You may click on the 'Check External Payment' button to check to see if the payment has confirmed. Chain: </source> <translation>Escrow återbetalning slutförts! Spärrade utgifterna betalningen finns på blockchain. Du kan klicka på knappen "Kontrollera extern betalning" för att kontrollera om betalningen har bekräftats. Kedja:</translation> </message> <message> <source>Escrow refund completed successfully!</source> <translation>Escrow återbetalning slutförts!</translation> </message> <message> <source>General exception completing refund</source> <translation>Allmänt undantag slutföra återbetalning</translation> </message> <message> <source>Cannot parse JSON results</source> <translation>Det går inte att tolka JSON resultat</translation> </message> <message> <source>Cannot parse JSON response: </source> <translation>Det går inte att tolka JSON svar:</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>Escrow released successfully!</source> <translation>Spärrade släppt framgångsrikt!</translation> </message> <message> <source>General exception releasing escrow</source> <translation>Allmänt undantag frigördepositions</translation> </message> <message> <source>Confirm Escrow Release</source> <translation>Bekräfta Escrow Release</translation> </message> <message> <source>Escrow refunded successfully!</source> <translation>Spärrade betalas framgångsrikt!</translation> </message> <message> <source>General exception refunding escrow</source> <translation>Allmänt undantag återbetalning depositions</translation> </message> <message> <source>Confirm Escrow Refund</source> <translation>Bekräfta Escrow återbetalning</translation> </message> </context> <context> <name>MessageInfoDialog</name> <message> <source>Message Info</source> <translation>meddelande info</translation> </message> <message> <source>From:</source> <translation>Från:</translation> </message> <message> <source>The value associated with this message.</source> <translation>Värdet associerat med detta meddelande.</translation> </message> <message> <source>To:</source> <translation>Till:</translation> </message> <message> <source>The message name.</source> <translation>Meddelandet namn.</translation> </message> <message> <source>Topic:</source> <translation>Ämne:</translation> </message> <message> <source>Message:</source> <translation>Meddelande:</translation> </message> <message> <source>Time:</source> <translation>Tid:</translation> </message> </context> <context> <name>MessageListPage</name> <message> <source>Message List</source> <translation>meddelande~~POS=TRUNC</translation> </message> <message> <source>Refresh message list</source> <translation>Uppdatera meddelandelista</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Send a new message</source> <translation>Skicka ett nytt meddelande</translation> </message> <message> <source>New Msg</source> <translation>nya Msg</translation> </message> <message> <source>Copy the currently selected message to the system clipboard</source> <translation>Kopiera valda meddelandet till systemets Urklipp</translation> </message> <message> <source>Copy Msg ID</source> <translation>Kopiera Msg ID</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>Get message details</source> <translation>Få meddelandeinformation</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> </context> <context> <name>MessageTableModel</name> <message> <source>GUID</source> <translation>GUID</translation> </message> <message> <source>Time</source> <translation>Tid</translation> </message> <message> <source>From</source> <translation>Från</translation> </message> <message> <source>To</source> <translation>Till</translation> </message> <message> <source>Subject</source> <translation>Ämne</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> </context> <context> <name>MessageView</name> <message> <source>Inbox</source> <translation>Inkorg</translation> </message> <message> <source>Outbox</source> <translation>utkorgen</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulär</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Presidentielcoin network after a connection is established, but this process has not completed yet. This means that recent transactions will not be visible, and the balance will not be up-to-date until this process has completed.</source> <translation>Informationen som visas kan vara föråldrad. Plånboken synkroniseras automatiskt med Presidentielcoin nätverket efter en anslutning har upprättats, men denna process har inte slutfört ännu. Detta innebär att nyligen genomförda transaktioner inte kommer att vara synlig, och balansen kommer att vara up-to-date förrän denna process har slutförts.</translation> </message> <message> <source>Spending presidentielcoins may not be possible during that phase!</source> <translation>Utgifterna presidentielcoins får inte vara möjligt under denna fas!</translation> </message> <message> <source>Amount of blocks left</source> <translation>Mängd block kvar</translation> </message> <message> <source>unknown...</source> <translation>okänd...</translation> </message> <message> <source>Last block time</source> <translation>Sista blocktid</translation> </message> <message> <source>Progress</source> <translation>Framsteg</translation> </message> <message> <source>~</source> <translation>~</translation> </message> <message> <source>Progress increase per Hour</source> <translation>Framsteg ökning per timme</translation> </message> <message> <source>calculating...</source> <translation>beräknande...</translation> </message> <message> <source>Estimated time left until synced</source> <translation>Beräknad tid kvar tills synkroniseras</translation> </message> <message> <source>Hide</source> <translation>Göm</translation> </message> <message> <source>Unknown. Syncing Headers...</source> <translation>Okänd. Synkronisera Headers ...</translation> </message> </context> <context> <name>MyAcceptedOfferListPage</name> <message> <source>My Accepted Offers</source> <translation>Mina Godkända erbjudanden</translation> </message> <message> <source>Refresh your accepted offer list</source> <translation>Uppdatera din accepterade listan erbjudande</translation> </message> <message> <source>Copy the currently selected offer to the system clipboard</source> <translation>Kopiera valda erbjudande till systemets Urklipp</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Details of the currently accepted offer</source> <translation>Uppgifter om den nuvarande accepterade erbjudandet</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Acknowledge Payment</source> <translation>erkänna Betalning</translation> </message> <message> <source>Send message to buyer</source> <translation>Skicka meddelande till köparen</translation> </message> <message> <source>Send Msg To Buyer</source> <translation>Skicka msg till köparen</translation> </message> <message> <source>Leave Feedback</source> <translation>Lämna feedback</translation> </message> <message> <source>Check payment for this offer from an external chain</source> <translation>Kontrollera betalning för detta erbjudande från en extern kedja</translation> </message> <message> <source>Check External Payment</source> <translation>Kontrollera extern Betalning</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are offers you have sold to others. Offer operations take 2-5 minutes to become active. Right click on an offer for more info including buyer message, quantity, date, etc. You can choose which aliases to view sales information for using the dropdown to the right.</source> <translation>Dessa är erbjudanden du har sålt till andra. Erbjudande operationer tar 2-5 minuter för att bli aktiva. Högerklicka på ett erbjudande för mer info inklusive köpare meddelande, kvantitet, datum, etc. Du kan välja vilka alias för att visa försäljningsinformation för att använda rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy OfferAccept ID</source> <translation>Kopiera OfferAccept ID</translation> </message> <message> <source>Message Buyer</source> <translation>meddelande köparen</translation> </message> <message> <source>Leave Feedback For Buyer</source> <translation>Lämna feedback för köparen</translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>Could not find this offer purchase, please ensure it has been confirmed by the blockchain: </source> <translation>Det gick inte att hitta detta erbjudande köp, se till att det har bekräftats av blockchain:</translation> </message> <message> <source>There was an exception trying to locate this offer purchase, please ensure it has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande köp, se till att det har bekräftats av blockchain:</translation> </message> <message> <source>Could not find this offer, please ensure the offer has been confirmed by the blockchain: </source> <translation>Det gick inte att hitta detta erbjudande, vänligen se till att erbjudandet har bekräftats av blockchain:</translation> </message> <message> <source>There was an exception trying to locate this offer, please ensure the has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande, vänligen se till att har bekräftats av blockchain:</translation> </message> <message> <source>Failed to generate ZCash address, please close this screen and try again</source> <translation>Det gick inte att generera ZCash adress, vänligen stänga den här skärmen och försök igen</translation> </message> <message> <source>There was an exception trying to generate ZCash address, please close this screen and try again: </source> <translation>Det fanns ett undantag försöker generera ZCash adress, vänligen stänga den här skärmen och försök igen:</translation> </message> <message> <source>Confirm Payment Acknowledgement</source> <translation>Bekräfta betalningen Bekräftelse</translation> </message> <message> <source>Warning: You are about to acknowledge this payment from the buyer. If you are shipping an item, please communicate a tracking number to the buyer via a Presidentielcoin message.</source> <translation>Varning: Du är på väg att erkänna denna betalning från köparen. Om du skickar ett objekt, vänligen meddela ett spårningsnummer till köparen via ett Presidentielcoin meddelande.</translation> </message> <message> <source>Are you sure you wish to acknowledge this payment?</source> <translation>Är du säker på att du vill bekräfta denna betalning?</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>General exception acknowledging offer payment</source> <translation>Allmänt undantag erkänner erbjudande betalning</translation> </message> <message> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <source>ZCash</source> <translation>ZCash</translation> </message> <message> <source>Error making request: </source> <translation>Fel att göra begäran:</translation> </message> <message> <source>Cannot parse JSON results</source> <translation>Det går inte att tolka JSON resultat</translation> </message> <message> <source>Cannot parse JSON response: </source> <translation>Det går inte att tolka JSON svar:</translation> </message> <message> <source>Error acknowledging offer payment: </source> <translation>Fel erkänna erbjuda betalning:</translation> </message> <message> <source>Payment transaction found but it has not been confirmed by the blockchain yet! Please try again later. Chain: </source> <translation>Betalningstransaktion hittades men det har inte bekräftats av blockchain ännu! Försök igen senare. Kedja:</translation> </message> <message> <source>Transaction was found in the blockchain! Full payment has been detected. It is recommended that you confirm payment by opening your wallet and seeing the funds in your account. Chain: </source> <translation>Transaktionen hittades i blockchain! Full betalning har upptäckts. Det rekommenderas att du bekräfta betalningen genom att öppna plånboken och ser pengarna på ditt konto. Kedja:</translation> </message> <message> <source>Payment not found in the blockchain! Please try again later. Chain: </source> <translation>Betalning hittades inte i blockchain! Försök igen senare. Kedja:</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>This payment was not done using another coin, please select an offer that was accepted by paying with another blockchain.</source> <translation>Denna betalning gjordes inte med en annan mynt, välj ett erbjudande som accepterades genom att betala med en annan blockchain.</translation> </message> <message> <source>Export Offer Data</source> <translation>Export erbjudande Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Offer ID</source> <translation>erbjudandet ID</translation> </message> <message> <source>Accept ID</source> <translation>acceptera ID</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Height</source> <translation>Höjd</translation> </message> <message> <source>Price</source> <translation>Pris</translation> </message> <message> <source>Currency</source> <translation>Valuta</translation> </message> <message> <source>Qty</source> <translation>st</translation> </message> <message> <source>Total</source> <translation>Total</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>MyAliasListPage</name> <message> <source>My Aliases</source> <translation>mina Alias</translation> </message> <message> <source>Refresh alias list</source> <translation>Refresh alias lista</translation> </message> <message> <source>Create a new alias</source> <translation>Skapa ett nytt alias</translation> </message> <message> <source>Copy the currently selected alias to the system clipboard</source> <translation>Kopiera markerade alias till Urklipp</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>New Alias</source> <translation>nytt Alias</translation> </message> <message> <source>Copy Alias ID</source> <translation>Kopia Alias ​​ID</translation> </message> <message> <source>Edit selected alias</source> <translation>Redigera valda alias</translation> </message> <message> <source>Edit</source> <translation>Redigera</translation> </message> <message> <source>Transfer selected alias</source> <translation>Överför valda alias</translation> </message> <message> <source>Transfer</source> <translation>Överföring</translation> </message> <message> <source>Create a new public key used for transferring aliases</source> <translation>Skapa en ny publik nyckel som används för överföring av alias</translation> </message> <message> <source>New Public Key</source> <translation>New Public Key</translation> </message> <message> <source>Open list of affiliates associated with this alias</source> <translation>Öppna listan över dotterbolag i samband med detta alias</translation> </message> <message> <source>Affiliations</source> <translation>anknytningar</translation> </message> <message> <source>Sign Multisig Tx</source> <translation>Underteckna Multisig Tx</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are your registered Presidentielcoin Aliases. Alias operations (create, update, transfer) take 2-5 minutes to become active.</source> <translation>Dessa är dina registrerade Presidentielcoin Alias. Alias ​​operationer (skapa, uppdatera, överföring) tar 2-5 minuter för att bli aktiva.</translation> </message> <message> <source>You cannot edit this alias because it has expired</source> <translation>Du kan inte redigera alias eftersom det har gått ut</translation> </message> <message> <source>This alias is still pending, click the refresh button once the alias confirms and try again</source> <translation>Detta alias är ännu inte avgjort, klicka på uppdateringsknappen när alias bekräftar och försök igen</translation> </message> <message> <source>You cannot transfer this alias because it has expired</source> <translation>Du kan inte överföra detta alias, eftersom det har gått ut</translation> </message> <message> <source>New Public Key For Alias Transfer</source> <translation>New Public Key för Alias ​​Transfer</translation> </message> <message> <source> has been copied to your clipboard! IMPORTANT: This key is for one-time use only! Do not re-use public keys for multiple aliases or transfers.</source> <translation>har kopierats till Urklipp! VIKTIGT: Denna knapp är endast engångsbruk! Återanvänd inte använda publika nycklar för flera alias eller överföringar.</translation> </message> <message> <source>Could not generate a new public key!</source> <translation>Det gick inte att generera en ny publik nyckel!</translation> </message> <message> <source>Export Alias Data</source> <translation>Export Alias ​​Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Multisignature</source> <translation>Multisignature</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> <message> <source>Expired</source> <translation>Utgånget</translation> </message> <message> <source>Buyer Rating</source> <translation>köparen Betyg</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> <message> <source>Seller Rating</source> <translation>säljaren betyg</translation> </message> <message> <source>Arbiter Rating</source> <translation>Arbiter Betyg</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> </context> <context> <name>MyCertListPage</name> <message> <source>My Certificates</source> <translation>Mina certifikat</translation> </message> <message> <source>Refresh certificate list</source> <translation>Uppdatera certifikatlistan</translation> </message> <message> <source>Create a new certificate</source> <translation>Skapa ett nytt certifikat</translation> </message> <message> <source>Copy the currently selected certificate to the system clipboard</source> <translation>Kopiera valda certifikatet till Urklipp</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>New Certificate</source> <translation>nya certifikatet</translation> </message> <message> <source>Copy Certificate ID</source> <translation>Kopiera Certifikat-ID</translation> </message> <message> <source>Edit selected certificate</source> <translation>Redigera valt certifikat</translation> </message> <message> <source>Edit</source> <translation>Redigera</translation> </message> <message> <source>Transfer selected certificate</source> <translation>Transfer valt certifikat</translation> </message> <message> <source>Transfer</source> <translation>Överföring</translation> </message> <message> <source>Sell selected certificate</source> <translation>Sälja valt certifikat</translation> </message> <message> <source>Sell</source> <translation>Sälja</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are your registered Presidentielcoin Certificates. Certificate operations (create, update, transfer) take 2-5 minutes to become active. You can choose which aliases to view related certificates using the dropdown to the right.</source> <translation>Dessa är dina registrerade Presidentielcoin certifikat. Certifikatåtgärder (skapa, uppdatera, överföring) tar 2-5 minuter att bli aktiva. Du kan välja vilka alias för att visa relaterade certifikat med hjälp av rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy Title</source> <translation>Kopiera Titel</translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>You cannot sell this certificate because it has expired</source> <translation>Du kan inte sälja detta certifikat eftersom det har gått ut</translation> </message> <message> <source>You cannot edit this certificate because it has expired</source> <translation>Du kan inte redigera detta certifikat eftersom det har gått ut</translation> </message> <message> <source>You cannot transfer this certificate because it has expired</source> <translation>Du kan inte överföra detta certifikat eftersom det har gått ut</translation> </message> <message> <source>Export Certificate Data</source> <translation>Exportcertifikat Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Cert</source> <translation>cert</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Private Data</source> <translation>Private Data</translation> </message> <message> <source>Public Data</source> <translation>Public Data</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Owner</source> <translation>Ägare</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> <message> <source>Category</source> <translation>Kategori</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> </context> <context> <name>MyEscrowListPage</name> <message> <source>My Escrow List</source> <translation>Min Escrow Lista</translation> </message> <message> <source>Show Completed/ Refunded/Expired Escrows</source> <translation>Show completed / återbetalas / passerat escrows</translation> </message> <message> <source>Refresh your list of escrows</source> <translation>Uppdatera listan över escrows</translation> </message> <message> <source>Copy the currently selected escrow to the system clipboard</source> <translation>Kopiera valda spärrade till Urklipp</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Copy Escrow ID</source> <translation>Kopiera Escrow ID</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Release selected escrow to merchant</source> <translation>Frigöra valda spärrade till handlaren</translation> </message> <message> <source>Manage Escrow</source> <translation>hantera Escrow</translation> </message> <message> <source>Acknowledge Payment</source> <translation>erkänna Betalning</translation> </message> <message> <source>Check External Payment</source> <translation>Kontrollera extern Betalning</translation> </message> <message> <source>Send message to buyer</source> <translation>Skicka meddelande till köparen</translation> </message> <message> <source>Send Msg To Buyer</source> <translation>Skicka msg till köparen</translation> </message> <message> <source>Send message to seller</source> <translation>Skicka meddelande till säljaren</translation> </message> <message> <source>Send Msg To Seller</source> <translation>Skicka msg till Säljare</translation> </message> <message> <source>Send message to arbiter</source> <translation>Skicka meddelande till Arbiter</translation> </message> <message> <source>Send Msg To Arbiter</source> <translation>Skicka msg till Arbiter</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>These are your registered Presidentielcoin Escrows. Escrow operations (create, release, refund, complete) take 2-5 minutes to become active. You can choose which aliases to view related escrows using the dropdown to the right.</source> <translation>Dessa är dina registrerade Presidentielcoin escrows. Spärrade operationer (skapa, release, återbetalning, komplett) tar 2-5 minuter för att bli aktiva. Du kan välja vilka alias för att visa relaterade escrows hjälp av rullgardinsmenyn till höger.</translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>Bitcoin</source> <translation>Bitcoin</translation> </message> <message> <source>ZCash</source> <translation>ZCash</translation> </message> <message> <source>Error making request: </source> <translation>Fel att göra begäran:</translation> </message> <message> <source>Cannot parse JSON results</source> <translation>Det går inte att tolka JSON resultat</translation> </message> <message> <source>Transaction was found in the blockchain! Escrow funding payment has been detected. Chain: </source> <translation>Transaktionen hittades i blockchain! Spärrade medel betalning har upptäckts. Kedja:</translation> </message> <message> <source>Transaction was found in the blockchain! Escrow payment has been detected. It is recommended that you confirm payment by opening your wallet and seeing the funds in your account. Chain: </source> <translation>Transaktionen hittades i blockchain! Spärrade betalning har upptäckts. Det rekommenderas att du bekräfta betalningen genom att öppna plånboken och ser pengarna på ditt konto. Kedja:</translation> </message> <message> <source>Cannot parse JSON response: </source> <translation>Det går inte att tolka JSON svar:</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Payment transaction found but it has not been confirmed by the blockchain yet! Please try again later. Chain: </source> <translation>Betalningstransaktion hittades men det har inte bekräftats av blockchain ännu! Försök igen senare. Kedja:</translation> </message> <message> <source>Payment not found in the blockchain! Please try again later. Chain: </source> <translation>Betalning hittades inte i blockchain! Försök igen senare. Kedja:</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>Could not find this escrow, please ensure the escrow has been confirmed by the blockchain: </source> <translation>Det gick inte att hitta denna spärrade, se till det spärrade har bekräftats av blockchain:</translation> </message> <message> <source>This payment was not done using another coin, please select an escrow that was created by paying with another blockchain.</source> <translation>Denna betalning gjordes inte med en annan mynt, välj en depositions som skapades genom att betala med en annan blockchain.</translation> </message> <message> <source>Confirm Escrow Acknowledgement</source> <translation>Bekräfta Escrow Bekräftelse</translation> </message> <message> <source>Warning: You are about to acknowledge this payment from the buyer. If you are shipping an item, please communicate a tracking number to the buyer via a Presidentielcoin message.</source> <translation>Varning: Du är på väg att erkänna denna betalning från köparen. Om du skickar ett objekt, vänligen meddela ett spårningsnummer till köparen via ett Presidentielcoin meddelande.</translation> </message> <message> <source>Are you sure you wish to acknowledge this payment?</source> <translation>Är du säker på att du vill bekräfta denna betalning?</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error acknowledging escrow payment: </source> <translation>Fel erkänna spärrade betalning:</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> <message> <source>General exception acknowledging escrow payment</source> <translation>Allmänt undantag erkänner depositions betalning</translation> </message> <message> <source>Export Escrow Data</source> <translation>Export Escrow Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> </context> <context> <name>MyOfferListPage</name> <message> <source>My Offers</source> <translation>Mina erbjudanden</translation> </message> <message> <source>Show Sold Out/ Expired Offers</source> <translation>Visa Slutsåld / Utgångna erbjudanden</translation> </message> <message> <source>Show Digital Offers Only</source> <translation>Visa Digital erbjuder endast</translation> </message> <message> <source>Refresh your list of offers</source> <translation>Uppdatera listan över erbjudanden</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>New Offer</source> <translation>nytt erbjudande</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>Create a new offer</source> <translation>Skapa ett nytt erbjudande</translation> </message> <message> <source>Copy the currently selected offer to the system clipboard</source> <translation>Kopiera valda erbjudande till systemets Urklipp</translation> </message> <message> <source>Edit selected offer</source> <translation>Redigera utvalda erbjudande</translation> </message> <message> <source>Edit</source> <translation>Redigera</translation> </message> <message> <source>Manage affiliates for this offer</source> <translation>Hantera dotterbolag för detta erbjudande</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>These are your registered Presidentielcoin Offers. Offer operations (create, update) take 2-5 minutes to become active. You can choose which aliases to view related offers using the dropdown to the right.</source> <translation>Dessa är dina registrerade Presidentielcoin erbjudanden. Erbjudande operationer (skapa, uppdatera) tar 2-5 minuter för att bli aktiva. Du kan välja vilka alias för att visa relaterade erbjudanden med hjälp av rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy Title</source> <translation>Kopiera Titel</translation> </message> <message> <source>Copy Description</source> <translation>Kopiera Beskrivning</translation> </message> <message> <source>Manage Affiliates</source> <translation>hantera Affiliates</translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>You cannot edit this offer because it has expired</source> <translation>Du kan inte redigera detta erbjudande eftersom det har gått ut</translation> </message> <message> <source>Export Offer Data</source> <translation>Export erbjudande Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Cert</source> <translation>cert</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Description</source> <translation>Beskrivning</translation> </message> <message> <source>Category</source> <translation>Kategori</translation> </message> <message><|fim▁hole|> </message> <message> <source>Currency</source> <translation>Valuta</translation> </message> <message> <source>Qty</source> <translation>st</translation> </message> <message> <source>Sold</source> <translation>Såld</translation> </message> <message> <source>Private</source> <translation>Privat</translation> </message> <message> <source>Expired</source> <translation>Utgånget</translation> </message> <message> <source>Seller Alias</source> <translation>säljaren Alias</translation> </message> <message> <source>Seller Rating</source> <translation>säljaren betyg</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> <message> <source>Payment Options</source> <translation>betalnings~~POS=TRUNC</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> </context> <context> <name>MyOfferWhitelistTableModel</name> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Discount</source> <translation>Rabatt</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> </context> <context> <name>MyWhitelistOfferDialog</name> <message> <source>My Offer Affiliates</source> <translation>Mitt erbjudande Affiliates</translation> </message> <message> <source>Refresh your affiliate list for this offer</source> <translation>Uppdatera din affiliate lista för detta erbjudande</translation> </message> <message> <source>Refresh</source> <translation>refresh</translation> </message> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>You are an affiliate for these offers. Affiliate operations take 2-5 minutes to become active. The owner of the offer may add you as to his affiliate list and your affiliate entry will show up here.</source> <translation>Du är en affiliate för dessa erbjudanden. Affiliate verksamhet tar 2-5 minuter för att bli aktiva. Ägaren av erbjudandet kan lägga till dig som sin affiliate lista och din affiliate inträde kommer att dyka upp här.</translation> </message> <message> <source>Copy Alias</source> <translation>kopia Alias</translation> </message> <message> <source>Could not refresh the affiliate list: </source> <translation>Det gick inte att uppdatera affiliate lista:</translation> </message> <message> <source>There was an exception trying to refresh the affiliate list: </source> <translation>Det var ett undantag som försöker uppdatera affiliate lista:</translation> </message> <message> <source>Export Affiliate Data</source> <translation>Export Affiliate Data</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Expires</source> <translation>Utgår</translation> </message> <message> <source>Discount</source> <translation>Rabatt</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>NewMessageDialog</name> <message> <source>New Message</source> <translation>Nytt meddelande</translation> </message> <message> <source>From:</source> <translation>Från:</translation> </message> <message> <source>To:</source> <translation>Till:</translation> </message> <message> <source>The message name.</source> <translation>Meddelandet namn.</translation> </message> <message> <source>Topic:</source> <translation>Ämne:</translation> </message> <message> <source>Original Message:</source> <translation>Ursprungligt meddelande:</translation> </message> <message> <source>Your Message:</source> <translation>Ditt meddelande:</translation> </message> <message> <source>Hex Data:</source> <translation>Hex Data:</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>Reply Message</source> <translation>svarsmeddelande</translation> </message> <message> <source>Choose 'Yes' if you are sending a Hex string as a message such as a raw transaction for multisignature signing purposes. To compress the message this will convert the message data from hex to binary and send it to the recipient. The outgoing message field will not be utilized to save space.</source> <translation>Välj "Ja" om du skickar ett Hex sträng som ett meddelande som en rå transaktion för multisignature signering ändamål. Att komprimera meddelandet detta kommer att konvertera meddelandedata från hex till binärt och skicka det till mottagaren. Den utgående meddelandefältet kommer inte att användas för att spara utrymme.</translation> </message> <message> <source>Select an Alias</source> <translation>Välj en Alias</translation> </message> <message> <source>Could not refresh alias list: </source> <translation>Det gick inte att uppdatera alias lista:</translation> </message> <message> <source>There was an exception trying to refresh the alias list: </source> <translation>Det var ett undantag som försöker uppdatera alias lista:</translation> </message> <message> <source>Empty message not allowed. Please try again</source> <translation>Tomt meddelande inte tillåtet. Var god försök igen</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error creating new message: </source> <translation>Fel vid skapande av ett nytt meddelande:</translation> </message> <message> <source>Error replying to message: </source> <translation>Fel svar på meddelande:</translation> </message> <message> <source>The entered message is not a valid Presidentielcoin message</source> <translation>Det angivna meddelandet inte är ett giltigt Presidentielcoin meddelande</translation> </message> <message> <source>General exception creating new message</source> <translation>Allmänt undantag skapa nytt meddelande</translation> </message> <message> <source>General exception replying to message</source> <translation>Allmänt undantag svara på meddelandet</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> </context> <context> <name>NewWhitelistDialog</name> <message> <source>Add Affiliate</source> <translation>lägga Affiliate</translation> </message> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Discount</source> <translation>Rabatt</translation> </message> <message> <source>Enter the alias and discount level of your affiliate. This is a percentage of price for your offer you want to allow your affiliate to purchase your offer for. Typically given to wholesalers or for special arrangements with an affiliate.</source> <translation>Ange alias och rabattnivå på din partner. Detta är en procentsats av priset för ditt erbjudande du vill tillåta din affiliate att köpa ditt erbjudande för. Vanligtvis ges till grossister eller för speciella arrangemang med en affiliate.</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>New affiliate added successfully!</source> <translation>Nya affiliate lagts till!</translation> </message> <message> <source>Error creating new affiliate: </source> <translation>Fel vid skapande av nya affiliate:</translation> </message> <message> <source>General exception creating new affiliate: </source> <translation>Allmänt undantag skapa nya affiliate:</translation> </message> <message> <source>The entered entry is not a valid affiliate</source> <translation>Den angivna posten är inte en giltig affiliate</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> </context> <context> <name>OfferAcceptDialog</name> <message> <source>Accept Presidentielcoin Offer</source> <translation>Acceptera Presidentielcoin Offer</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Pay With ZEC</source> <translation>Betala med ZEC</translation> </message> <message> <source>Pay with Bitcoin</source> <translation>Betala med Bitcoin</translation> </message> <message> <source>Pay with BTC</source> <translation>Betala med BTC</translation> </message> <message> <source>Pay with Presidentielcoin</source> <translation>Betala med Presidentielcoin</translation> </message> <message> <source>Pay with PRC</source> <translation>Betala med PRC</translation> </message> <message> <source>Use Escrow</source> <translation>användning Escrow</translation> </message> <message> <source>Could not find currency in the rates peg for this offer. Currency: </source> <translation>Det gick inte att hitta valuta i priset peg för detta erbjudande. Valuta:</translation> </message> <message> <source>Enter a Presidentielcoin arbiter that is mutally trusted between yourself and the merchant</source> <translation>Ange en Presidentielcoin medlare som mutally är betrodd mellan dig och handlaren</translation> </message> <message> <source>Are you sure you want to purchase</source> <translation>Är du säker på att du vill köpa</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>from merchant</source> <translation>från försäljaren</translation> </message> <message> <source>You will be charged</source> <translation>du kommer att få betala</translation> </message> <message> <source>Pay Escrow</source> <translation>pay Escrow</translation> </message> <message> <source>Pay For Item</source> <translation>Betala för punkt</translation> </message> <message> <source>Invalid quantity when trying to accept offer!</source> <translation>Ogiltig mängd när man försöker att acceptera erbjudandet!</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error accepting offer: </source> <translation>Fel acceptera erbjudandet:</translation> </message> <message> <source>Error creating escrow: </source> <translation>Fel skapa spärrade:</translation> </message> <message> <source>General exception when accepting offer</source> <translation>Allmänt undantag när de tar emot erbjudandet</translation> </message> <message> <source>Invalid quantity when trying to create escrow!</source> <translation>Ogiltig mängd när man försöker skapa spärrade!</translation> </message> <message> <source>General exception when creating escrow</source> <translation>Allmänt undantag när du skapar spärrade</translation> </message> </context> <context> <name>OfferAcceptDialogBTC</name> <message> <source>Accept Presidentielcoin Offer</source> <translation>Acceptera Presidentielcoin Offer</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Open your local Bitcoin client</source> <translation>Öppna din lokala Bitcoin klient</translation> </message> <message> <source>Open BTC Wallet</source> <translation>Öppen BTC Wallet</translation> </message> <message> <source>Confirm this payment on the Bitcoin blockchain</source> <translation>Bekräfta betalning på Bitcoin blockchain</translation> </message> <message> <source>Confirm Payment</source> <translation>bekräfta betalningen</translation> </message> <message> <source>Bitcoin TXID:</source> <translation>Bitcoin TXID:</translation> </message> <message> <source>Use Escrow</source> <translation>användning Escrow</translation> </message> <message> <source>Could not find BTC currency in the rates peg for this offer</source> <translation>Kunde inte hitta BTC valuta i priset peg för detta erbjudande</translation> </message> <message> <source>After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below.</source> <translation>Efter att ha betalat för denna post, ange Bitcoin transaktions-ID och klicka på bekräftelseknappen nedan.</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI:n är för lång, försöka minska texten för etikett / meddelande.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Fel vid skapande av QR-kod från URI.</translation> </message> <message> <source>Error making request: </source> <translation>Fel att göra begäran:</translation> </message> <message> <source>Cannot parse JSON results</source> <translation>Det går inte att tolka JSON resultat</translation> </message> <message> <source>Enter a Presidentielcoin arbiter that is mutally trusted between yourself and the merchant. Then enable the 'Use Escrow' checkbox</source> <translation>Ange en Presidentielcoin medlare som mutally är betrodd mellan dig och handlaren. Sedan aktivera "Använd Escrow kryssrutan</translation> </message> <message> <source>Payment on Presidentielcoin Decentralized Marketplace. Offer ID: </source> <translation>Betalning på Presidentielcoin Decentraliserad Marketplace. Erbjudandet ID:</translation> </message> <message> <source>Failed to generate multisig address: </source> <translation>Det gick inte att generera multisig adress:</translation> </message> <message> <source>Could not generate escrow multisig address: Invalid response from generateescrowmultisig</source> <translation>Det gick inte att generera spärrade multisig adress: Ogiltigt svar från generateescrowmultisig</translation> </message> <message> <source>Could not create escrow transaction: could not find redeem script in response</source> <translation>Det gick inte att skapa spärrade transaktion: kunde inte hitta lösa skript som svar</translation> </message> <message> <source>Could not create escrow transaction: could not find multisig address in response</source> <translation>Det gick inte att skapa spärrade transaktion: kunde inte hitta multisig adress som svar</translation> </message> <message> <source>Are you sure you want to purchase</source> <translation>Är du säker på att du vill köpa</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>from merchant</source> <translation>från försäljaren</translation> </message> <message> <source>Follow the steps below to successfully pay via Bitcoin:</source> <translation>Följ stegen nedan för att framgångsrikt betala via Bitcoin:</translation> </message> <message> <source>1. If you are using escrow, please enter your escrow arbiter in the input box below and check the 'Use Escrow' checkbox. Leave the escrow checkbox unchecked if you do not wish to use escrow.</source> <translation>1. Om du använder spärrade, ange din spärrade skiljedomare i rutan nedan och kontrollera "Använd Escrow kryssrutan. Låt spärrade rutan avmarkerat om du inte vill använda spärrade.</translation> </message> <message> <source>2. Open your Bitcoin wallet. You may use the QR Code to the left to scan the payment request into your wallet or click on 'Open BTC Wallet' if you are on the desktop and have Bitcoin Core installed.</source> <translation>2. Öppna din Bitcoin plånbok. Du kan använda QR Code till vänster för att skanna ansökan om utbetalning i din plånbok eller klicka på "Öppna BTC plånbok" om du är på skrivbordet och har Bitcoin Kärna installerat.</translation> </message> <message> <source>3. Pay</source> <translation>3. Betala</translation> </message> <message> <source>to</source> <translation>till</translation> </message> <message> <source>using your Bitcoin wallet. Please enable dynamic fees in your BTC wallet upon payment for confirmation in a timely manner.</source> <translation>med hjälp av din Bitcoin plånbok. Vänligen aktivera dynamiska avgifter i BTC plånbok vid betalning för bekräftelse i tid.</translation> </message> <message> <source>4. Enter the Transaction ID and then click on the 'Confirm Payment' button once you have paid.</source> <translation>4. Ange transaktions-ID och klicka sedan på "Bekräfta betalning" knappen när du har betalat.</translation> </message> <message> <source>Escrow created successfully! Please fund using BTC address </source> <translation>Spärrade skapats! Vänligen finansiera användning av BTC adress</translation> </message> <message> <source>Transaction was found in the Bitcoin blockchain! Full payment has been detected. TXID: </source> <translation>Transaktionen hittades i Bitcoin blockchain! Full betalning har upptäckts. TXID:</translation> </message> <message> <source>Cannot parse JSON response: </source> <translation>Det går inte att tolka JSON svar:</translation> </message> <message> <source>Payment not found in the Bitcoin blockchain! Please try again later</source> <translation>Betalning inte i Bitcoin blockchain! Försök igen senare</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>Please enter a valid Bitcoin Transaction ID into the input box and try again</source> <translation>Ange ett giltigt Bitcoin transaktions-id i rutan och försök igen</translation> </message> <message> <source>Invalid quantity when trying to accept offer!</source> <translation>Ogiltig mängd när man försöker att acceptera erbjudandet!</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error accepting offer: </source> <translation>Fel acceptera erbjudandet:</translation> </message> <message> <source>Error creating escrow: </source> <translation>Fel skapa spärrade:</translation> </message> <message> <source>General exception when accepting offer</source> <translation>Allmänt undantag när de tar emot erbjudandet</translation> </message> <message> <source>Invalid quantity when trying to create escrow!</source> <translation>Ogiltig mängd när man försöker skapa spärrade!</translation> </message> <message> <source>General exception when creating escrow</source> <translation>Allmänt undantag när du skapar spärrade</translation> </message> </context> <context> <name>OfferAcceptDialogZEC</name> <message> <source>Accept Presidentielcoin Offer</source> <translation>Acceptera Presidentielcoin Offer</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Open your local Bitcoin client</source> <translation>Öppna din lokala Bitcoin klient</translation> </message> <message> <source>Open ZEC Wallet</source> <translation>Öppen ZEC Wallet</translation> </message> <message> <source>Confirm this payment on the Bitcoin blockchain</source> <translation>Bekräfta betalning på Bitcoin blockchain</translation> </message> <message> <source>Confirm Payment</source> <translation>bekräfta betalningen</translation> </message> <message> <source>ZCash TXID:</source> <translation>ZCash TXID:</translation> </message> <message> <source>Use Escrow</source> <translation>användning Escrow</translation> </message> <message> <source>Could not find ZEC currency in the rates peg for this offer</source> <translation>Kunde inte hitta ZEC valuta i priset peg för detta erbjudande</translation> </message> <message> <source>After paying for this item, please enter the ZCash Transaction ID and click on the confirm button below.</source> <translation>Efter att ha betalat för denna post, ange ZCash transaktions-ID och klicka på bekräftelseknappen nedan.</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI:n är för lång, försöka minska texten för etikett / meddelande.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Fel vid skapande av QR-kod från URI.</translation> </message> <message> <source>Failed to generate ZCash address, please close this screen and try again</source> <translation>Det gick inte att generera ZCash adress, vänligen stänga den här skärmen och försök igen</translation> </message> <message> <source>There was an exception trying to generate ZCash address, please close this screen and try again: </source> <translation>Det fanns ett undantag försöker generera ZCash adress, vänligen stänga den här skärmen och försök igen:</translation> </message> <message> <source>Error making request: </source> <translation>Fel att göra begäran:</translation> </message> <message> <source>Cannot parse JSON results</source> <translation>Det går inte att tolka JSON resultat</translation> </message> <message> <source>Enter a Presidentielcoin arbiter that is mutally trusted between yourself and the merchant. Then enable the 'Use Escrow' checkbox</source> <translation>Ange en Presidentielcoin medlare som mutally är betrodd mellan dig och handlaren. Sedan aktivera "Använd Escrow kryssrutan</translation> </message> <message> <source>Payment on Presidentielcoin Decentralized Marketplace. Offer ID: </source> <translation>Betalning på Presidentielcoin Decentraliserad Marketplace. Erbjudandet ID:</translation> </message> <message> <source>Failed to generate multisig address: </source> <translation>Det gick inte att generera multisig adress:</translation> </message> <message> <source>Could not generate escrow multisig address: Invalid response from generateescrowmultisig</source> <translation>Det gick inte att generera spärrade multisig adress: Ogiltigt svar från generateescrowmultisig</translation> </message> <message> <source>Could not create escrow transaction: could not find redeem script in response</source> <translation>Det gick inte att skapa spärrade transaktion: kunde inte hitta lösa skript som svar</translation> </message> <message> <source>Could not create escrow transaction: could not find multisig address in response</source> <translation>Det gick inte att skapa spärrade transaktion: kunde inte hitta multisig adress som svar</translation> </message> <message> <source>Are you sure you want to purchase</source> <translation>Är du säker på att du vill köpa</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>from merchant</source> <translation>från försäljaren</translation> </message> <message> <source>Follow the steps below to successfully pay via ZCash:</source> <translation>Följ stegen nedan för att framgångsrikt betala via ZCash:</translation> </message> <message> <source>1. If you are using escrow, please enter your escrow arbiter in the input box below and check the 'Use Escrow' checkbox. Leave the escrow checkbox unchecked if you do not wish to use escrow.</source> <translation>1. Om du använder spärrade, ange din spärrade skiljedomare i rutan nedan och kontrollera "Använd Escrow kryssrutan. Låt spärrade rutan avmarkerat om du inte vill använda spärrade.</translation> </message> <message> <source>2. Open your ZCash wallet. You may use the QR Code to the left to scan the payment request into your wallet or click on 'Open ZEC Wallet' if you are on the desktop and have ZCash Core installed.</source> <translation>2. Öppna ZCash plånbok. Du kan använda QR Code till vänster för att skanna ansökan om utbetalning i din plånbok eller klicka på "Öppna ZEC plånbok" om du är på skrivbordet och har ZCash Kärna installerat.</translation> </message> <message> <source>3. Pay</source> <translation>3. Betala</translation> </message> <message> <source>to</source> <translation>till</translation> </message> <message> <source>using your ZCash wallet. Please enable dynamic fees in your ZEC wallet upon payment for confirmation in a timely manner.</source> <translation>med hjälp av din ZCash plånbok. Vänligen aktivera dynamiska avgifter i ZEC plånbok vid betalning för bekräftelse i tid.</translation> </message> <message> <source>4. Enter the Transaction ID and then click on the 'Confirm Payment' button once you have paid.</source> <translation>4. Ange transaktions-ID och klicka sedan på "Bekräfta betalning" knappen när du har betalat.</translation> </message> <message> <source>Escrow created successfully! Please fund using ZEC address </source> <translation>Spärrade skapats! Vänligen finansiera med användning ZEC adress</translation> </message> <message> <source>Transaction was found in the ZCash blockchain! Full payment has been detected. TXID: </source> <translation>Transaktionen hittades i ZCash blockchain! Full betalning har upptäckts. TXID:</translation> </message> <message> <source>Cannot parse JSON response: </source> <translation>Det går inte att tolka JSON svar:</translation> </message> <message> <source>Payment not found in the ZCash blockchain! Please try again later</source> <translation>Betalning som inte finns i ZCash blockchain! Försök igen senare</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>Please enter a valid ZCash Transaction ID into the input box and try again</source> <translation>Ange ett giltigt ZCash transaktions-id i rutan och försök igen</translation> </message> <message> <source>Invalid quantity when trying to accept offer!</source> <translation>Ogiltig mängd när man försöker att acceptera erbjudandet!</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error accepting offer: </source> <translation>Fel acceptera erbjudandet:</translation> </message> <message> <source>Error creating escrow: </source> <translation>Fel skapa spärrade:</translation> </message> <message> <source>General exception when accepting offer</source> <translation>Allmänt undantag när de tar emot erbjudandet</translation> </message> <message> <source>Invalid quantity when trying to create escrow!</source> <translation>Ogiltig mängd när man försöker skapa spärrade!</translation> </message> <message> <source>General exception when creating escrow</source> <translation>Allmänt undantag när du skapar spärrade</translation> </message> </context> <context> <name>OfferAcceptInfoDialog</name> <message> <source>Offer Accept Info</source> <translation>Erbjuda Acceptera Info</translation> </message> <message> <source>Payment Information</source> <translation>Betalningsinformation</translation> </message> <message> <source>Payment Details</source> <translation>Betalningsinformation</translation> </message> <message> <source>Buyer:</source> <translation>Köpare:</translation> </message> <message> <source>Payment ID:</source> <translation>Betalning ID:</translation> </message> <message> <source>External TXID:</source> <translation>Extern TXID:</translation> </message> <message> <source>TXID:</source> <translation>TXID:</translation> </message> <message> <source>Height:</source> <translation>Höjd:</translation> </message> <message> <source>Time:</source> <translation>Tid:</translation> </message> <message> <source>Price:</source> <translation>Pris:</translation> </message> <message> <source>Discount:</source> <translation>Rabatt:</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Total:</source> <translation>Totalt:</translation> </message> <message> <source>Payment Status:</source> <translation>Betalningsstatus:</translation> </message> <message> <source>Average Rating:</source> <translation>Betyg i genomsnitt:</translation> </message> <message> <source>Shipping Contact Information:</source> <translation>Frakt Kontaktuppgifter:</translation> </message> <message> <source>OK</source> <translation>ok</translation> </message> <message> <source>Offer Information</source> <translation>erbjuda information</translation> </message> <message> <source>Offer Details</source> <translation>Erbjudande Detaljer</translation> </message> <message> <source>Offer Title:</source> <translation>Erbjudandet Titel:</translation> </message> <message> <source>Commission:</source> <translation>Provision:</translation> </message> <message> <source>Offer ID:</source> <translation>Erbjudandet ID:</translation> </message> <message> <source>Root Offer ID:</source> <translation>Root erbjudande ID:</translation> </message> <message> <source>Merchant:</source> <translation>Handelsfartyg:</translation> </message> <message> <source>Certificate:</source> <translation>Certifikat:</translation> </message> <message> <source>Buyer Feedback</source> <translation>köparen Feedback</translation> </message> <message> <source>Seller Feedback</source> <translation>säljare Feedback</translation> </message> <message> <source>No Feedback Found</source> <translation>Ingen Feedback Hittat</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Feedback #</source> <translation>Återkoppling #</translation> </message> <message> <source>(Buyer)</source> <translation>(Köpare)</translation> </message> <message> <source>(Merchant)</source> <translation>(Handelsfartyg)</translation> </message> <message> <source>Stars</source> <translation>stjärnor</translation> </message> <message> <source>No Rating</source> <translation>Ingen Betyg</translation> </message> <message> <source>No Feedback</source> <translation>Ingen feedback</translation> </message> <message> <source>&lt;b&gt;%1&lt;/b&gt;</source> <translation>&lt;b&gt;%1&lt;/b&gt;</translation> </message> <message> <source>From:</source> <translation>Från:</translation> </message> <message> <source>Rating:</source> <translation>Betyg:</translation> </message> <message> <source>Could not find this offer, please ensure offer has been confirmed by the blockchain</source> <translation>Det gick inte att hitta detta erbjudande, har du se erbjudande bekräftats av blockchain</translation> </message> <message> <source>There was an exception trying to locate this offer, please ensure offer has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande, vänligen se erbjudandet har bekräftats av blockchain:</translation> </message> <message> <source>Could not find this offer purchase, please ensure it has been confirmed by the blockchain</source> <translation>Det gick inte att hitta detta erbjudande köp, se till att det har bekräftats av blockchain</translation> </message> <message> <source>There was an exception trying to locate this offer purchase, please ensure it has been confirmed by the blockchain: </source> <translation>Det fanns ett undantag försöker hitta detta erbjudande köp, se till att det har bekräftats av blockchain:</translation> </message> </context> <context> <name>OfferAcceptTableModel</name> <message> <source>Offer ID</source> <translation>erbjudandet ID</translation> </message> <message> <source>Accept ID</source> <translation>acceptera ID</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Height</source> <translation>Höjd</translation> </message> <message> <source>Price</source> <translation>Pris</translation> </message> <message> <source>Currency</source> <translation>Valuta</translation> </message> <message> <source>Qty</source> <translation>st</translation> </message> <message> <source>Total</source> <translation>Total</translation> </message> <message> <source>Seller</source> <translation>Säljare</translation> </message> <message> <source>Buyer</source> <translation>Köpare</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> </context> <context> <name>OfferEscrowDialog</name> <message> <source>Payment In Escrow</source> <translation>Betalning I Escrow</translation> </message> <message> <source>Please wait...</source> <translation>Vänta...</translation> </message> <message> <source>Finish</source> <translation>Yta</translation> </message> <message> <source>You've created an escrow for</source> <translation>Du har skapat ett spärrat för</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>for</source> <translation>för</translation> </message> <message> <source>(includes a 0.05% escrow arbiter fee which is returned to you if the arbiter is not involved in the escrow)</source> <translation>(Inkluderar en 0,05% spärrat skiljedomare avgift som går tillbaka till dig om domaren inte är inblandad i det spärrade)</translation> </message> <message> <source>Your payment is in escrow!</source> <translation>Din betalning är i spärrat!</translation> </message> <message> <source>The merchant and arbiter have been sent an escrow notification. The merchant may follow-up with further information.</source> <translation>Handlaren och skiljedomare har skickat ett depositions anmälan. Handlaren kan följa upp med ytterligare information.</translation> </message> <message> <source>Please click Finish</source> <translation>Klicka på Slutför</translation> </message> </context> <context> <name>OfferFeedbackDialog</name> <message> <source>Leave Offer Feedback</source> <translation>Lämna ett anbud Feedback</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>Leave feedback on this offer purchase</source> <translation>Lämna synpunkter på detta erbjudande köp</translation> </message> <message> <source>Leave Feedback</source> <translation>Lämna feedback</translation> </message> <message> <source> Stars</source> <translation>stjärnor</translation> </message> <message> <source>Cannot find this offer purchase on the network, please try again later.</source> <translation>Det går inte att hitta detta erbjudande köp på nätet, försök igen senare.</translation> </message> <message> <source>This offer payment was for Offer ID</source> <translation>Detta erbjudande betalningen för Erbjudandet ID</translation> </message> <message> <source>for</source> <translation>för</translation> </message> <message> <source>totalling</source> <translation>totalt</translation> </message> <message> <source>Buyer:</source> <translation>Köpare:</translation> </message> <message> <source>merchant:</source> <translation>handelsfartyg:</translation> </message> <message> <source>You are the 'buyer' of this offer, please send feedback and rate the merchant once you have confirmed that you have recieved the item as per the description of the offer.</source> <translation>Du är "köpare" av detta erbjudande, vänligen skicka feedback och betygsätta handlaren när du har bekräftat att du har fått varan enligt beskrivningen av erbjudandet.</translation> </message> <message> <source>You are the 'merchant' of this offer, you may leave feedback and rate the buyer once you confirmed you have recieved full payment from buyer and you have ship the goods (if its for a physical good).</source> <translation>Du är "köpman" av detta erbjudande, kan du lämna synpunkter och betygsätta köparen när du har bekräftat att du har fått full betalning från köpare och du har skickar varorna (om dess för en fysisk bra).</translation> </message> <message> <source>Error sending feedback: </source> <translation>Fel att skicka feedback:</translation> </message> <message> <source>Could find alias: </source> <translation>Kunde hitta alias:</translation> </message> <message> <source>You cannot leave feedback this offer purchase because you do not own either the buyer or merchant aliases.</source> <translation>Du kan inte lämna feedback detta erbjudande köpet eftersom du inte äger antingen köparen eller handelsfartyg alias.</translation> </message> <message> <source>Thank you for your feedback!</source> <translation>Tack för din feedback!</translation> </message> <message> <source>General exception sending offeracceptfeedback</source> <translation>Allmänt undantag skickar offeracceptfeedback</translation> </message> <message> <source>There was an exception trying to refresh get alias: </source> <translation>Det fanns ett undantag försöker uppdatera get alias:</translation> </message> </context> <context> <name>OfferListPage</name> <message> <source>Search Offers</source> <translation>Search erbjuder</translation> </message> <message> <source>All Categories</source> <translation>alla kategorier</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> <message> <source>Copy the currently selected offer to the system clipboard</source> <translation>Kopiera valda erbjudande till systemets Urklipp</translation> </message> <message> <source>Copy Offer ID</source> <translation>Kopiera erbjudande ID</translation> </message> <message> <source>Resell this offer for a commission</source> <translation>Sälja detta erbjudande för en provision</translation> </message> <message> <source>Resell</source> <translation>sälja</translation> </message> <message> <source>Purchase this offer</source> <translation>Köp detta erbjudande</translation> </message> <message> <source>Purchase</source> <translation>Inköp</translation> </message> <message> <source>Send message to seller</source> <translation>Skicka meddelande till säljaren</translation> </message> <message> <source>Send Msg To Seller</source> <translation>Skicka msg till Säljare</translation> </message> <message> <source>&lt;&lt;</source> <translation>&lt;&lt;</translation> </message> <message> <source>&gt;&gt;</source> <translation>&gt;&gt;</translation> </message> <message> <source>Search for Presidentielcoin Offers (double click on one to purchase). Select Safe Search from wallet options if you wish to omit potentially offensive Offers(On by default)</source> <translation>Sök efter Presidentielcoin erbjudanden (dubbelklicka på en att köpa). Välj Safesearch från plånbok alternativ om du vill utelämna potentiellt stötande erbjudanden (On standard)</translation> </message> <message> <source>Copy Title</source> <translation>Kopiera Titel</translation> </message> <message> <source>Copy Description</source> <translation>Kopiera Beskrivning</translation> </message> <message> <source>Message Seller</source> <translation>meddelande Säljare</translation> </message> <message> <source>Enter search term, regex accepted (ie: ^name returns all Offer's starting with 'name'). Empty will search for all.</source> <translation>Ange sökord, regex accepteras (dvs. ^ namn åter alla Erbjudandets börjar med "namn"). Tom kommer att söka efter alla.</translation> </message> <message> <source>unlimited</source> <translation>obegränsat</translation> </message> <message> <source>Sorry, you cannot not resell this offer, it is sold out!</source> <translation>Tyvärr kan du inte inte sälja detta erbjudande är det slutsålt!</translation> </message> <message> <source>Sorry, you cannot not purchase this offer, it is sold out!</source> <translation>Tyvärr kan du inte inte köpa detta erbjudande är det slutsålt!</translation> </message> <message> <source>Error searching Offer: </source> <translation>Fel söka Erbjudande:</translation> </message> <message> <source>Current Page: </source> <translation>Nuvarande sida:</translation> </message> <message> <source>General exception when searching offer</source> <translation>Allmänt undantag när du söker erbjudande</translation> </message> <message> <source>Error: Invalid response from offerfilter command</source> <translation>Fel: Ogiltigt svar från offerfilter kommandot</translation> </message> </context> <context> <name>OfferPayDialog</name> <message> <source>Pay For Item</source> <translation>Betala för punkt</translation> </message> <message> <source>Please wait...</source> <translation>Vänta...</translation> </message> <message> <source>Finish</source> <translation>Yta</translation> </message> <message> <source>of</source> <translation>av</translation> </message> <message> <source>for</source> <translation>för</translation> </message> <message> <source>The merchant has been sent your delivery information and your item should arrive shortly. The merchant may follow-up with further information through a private message (please check your inbox regularly).</source> <translation>Handlaren har skickats leveransinformation och ditt objekt ska komma inom kort. Handlaren kan följa upp med ytterligare information genom ett privat meddelande (kolla din inkorg regelbundet).</translation> </message> <message> <source>You've purchased</source> <translation>Du har köpt</translation> </message> <message> <source>Your payment is complete!</source> <translation>Din betalning är klar!</translation> </message> <message> <source>Please click Finish</source> <translation>Klicka på Slutför</translation> </message> </context> <context> <name>OfferTableModel</name> <message> <source>Offer</source> <translation>Erbjudande</translation> </message> <message> <source>Certificate</source> <translation>Certifikat</translation> </message> <message> <source>Title</source> <translation>Titel</translation> </message> <message> <source>Description</source> <translation>Beskrivning</translation> </message> <message> <source>Category</source> <translation>Kategori</translation> </message> <message> <source>Price</source> <translation>Pris</translation> </message> <message> <source>Currency</source> <translation>Valuta</translation> </message> <message> <source>Qty</source> <translation>st</translation> </message> <message> <source>Sold</source> <translation>Såld</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Private</source> <translation>Privat</translation> </message> <message> <source>Seller Alias</source> <translation>säljaren Alias</translation> </message> <message> <source>Rating</source> <translation>Betyg</translation> </message> <message> <source>Payment Options</source> <translation>betalnings~~POS=TRUNC</translation> </message> </context> <context> <name>OfferView</name> <message> <source>Selling</source> <translation>Försäljning</translation> </message> <message> <source>Sold</source> <translation>Såld</translation> </message> <message> <source>My Purchases</source> <translation>Mina Inköp</translation> </message> <message> <source>Search</source> <translation>Sök</translation> </message> <message> <source>Buy</source> <translation>Köpa</translation> </message> </context> <context> <name>OfferWhitelistTableModel</name> <message> <source>Alias</source> <translation>Alias</translation> </message> <message> <source>Discount</source> <translation>Rabatt</translation> </message> <message> <source>Expires On</source> <translation>Går ut den</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Öppna URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Öppna betalningsbegäran från URI eller fil</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Välj betalningsbegäransfil</translation> </message> <message> <source>Select payment request file to open</source> <translation>Välj betalningsbegäransfil att öppna</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Alternativ</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Allmänt</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Storleken på &amp;databascache</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Antalet skript&amp;verifikationstrådar</translation> </message> <message> <source>Accept connections from outside</source> <translation>Acceptera anslutningar utifrån</translation> </message> <message> <source>Allow incoming connections</source> <translation>Acceptera inkommande anslutningar</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Proxyns IP-adress (t.ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source> <translation>Minimera istället för att stänga programmet när fönstret stängs. När detta alternativ är aktiverat stängs programmet endast genom att välja Stäng i menyn.</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Presidentielcoin Core.</source> <translation>Gränssnittets språk kan väljas här. Denna inställning träder i kraft efter omstart av Presidentielcoin Core.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>Tredjeparts URL:er (t.ex. en blockutforskare) som finns i transaktionstabben som ett menyval i sammanhanget. %s i URL:en ersätts med tansaktionshashen. Flera URL:er är separerade med vertikala streck |.</translation> </message> <message> <source>Third party transaction URLs</source> <translation>Tredjeparts transaktions-URL:er</translation> </message> <message> <source>&amp;Preferences</source> <translation>&amp;Inställningar</translation> </message> <message> <source>User Interface Theme:</source> <translation>Användargränssnitt Tema:</translation> </message> <message> <source>The user interface theme can be set here. This setting will take effect after restarting Presidentielcoin Core.</source> <translation>Användargränssnittet tema kan ställas in här. Denna inställning träder i kraft när du startar Presidentielcoin kärnan.</translation> </message> <message> <source>Default Alias:</source> <translation>Standard Alias:</translation> </message> <message> <source>Default Peg Alias:</source> <translation>Standard Peg Alias:</translation> </message> <message> <source>Safe Search:</source> <translation>Säker sökning:</translation> </message> <message> <source>On</source> <translation>På</translation> </message> <message> <source>Off</source> <translation>Av</translation> </message> <message> <source>DirectBTC</source> <translation>DirectBTC</translation> </message> <message> <source>BTC End Point:</source> <translation>BTC Slutpunkt</translation> </message> <message> <source>BTC RPC Login:</source> <translation>BTC RPC inloggning:</translation> </message> <message> <source>BTC RPC Password:</source> <translation>BTC RPC Lösenord:</translation> </message> <message> <source>Test Connection</source> <translation>Testa anslutning</translation> </message> <message> <source>DirectZEC</source> <translation>DirectZEC</translation> </message> <message> <source>ZEC End Point:</source> <translation>ZEC Slutpunkt</translation> </message> <message> <source>ZEC RPC Login:</source> <translation>ZEC RPC inloggning:</translation> </message> <message> <source>ZEC RPC Password:</source> <translation>ZEC RPC Lösenord:</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Aktiva kommandoradsalternativ som ersätter alternativen ovan:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Återställ alla klientinställningar till förvalen.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Återställ alternativ</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Nätverk</translation> </message> <message> <source>Automatically start Presidentielcoin Core after logging in to the system.</source> <translation>Kör Presidentielcoin Core automatiskt vid systeminloggning.</translation> </message> <message> <source>&amp;Start Presidentielcoin Core on system login</source> <translation>&amp;Kör Presidentielcoin Core vid systeminloggning</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = auto, &lt;0 = lämna så många kärnor lediga)</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;Plånbok</translation> </message> <message> <source>Expert</source> <translation>Expert</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Aktivera mynt&amp;kontrollfunktioner</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>Om du avaktiverar betalning med obekräftad växel, kan inte växeln från en transaktion användas förrän den transaktionen har minst en bekräftelse.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Spendera obekräftad växel</translation> </message> <message> <source>Automatically open the Presidentielcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Öppna automatiskt Presidentielcoin-klientens port på routern. Detta fungerar endast om din router har UPnP aktiverat.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Tilldela port med hjälp av &amp;UPnP</translation> </message> <message> <source>Connect to the Presidentielcoin network through a SOCKS5 proxy.</source> <translation>Anslut till Presidentielcoin-nätverket genom en SOCKS5-proxy.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Anslut genom SOCKS5-proxy (förvald proxy):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy-&amp;IP: </translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port: </translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyns port (t.ex. 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Används för att nå noder via:</translation> </message> <message> <source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Visas, om den angivna standard-SOCKS5-proxyn används för att nå noder via den här nätverkstypen.</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the Presidentielcoin network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Anslut till Presidentielcoin-nätverket genom en separat SOCKS5-proxy för dolda tjänster i Tor.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source> <translation>Använd separat SOCKS5-proxy för att nå noder via dolda tjänster i Tor:</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Fönster</translation> </message> <message> <source>&amp;Hide the icon from the system tray.</source> <translation>&amp;Göm ikonen från systemfältet.</translation> </message> <message> <source>Hide tray icon</source> <translation>Göm systemfältsikonen</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Visa endast en systemfältsikon vid minimering.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimera till systemfältet istället för aktivitetsfältet</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimera vid stängning</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Visa</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>Användargränssnittets &amp;språk: </translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Måttenhet att visa belopp i: </translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Välj en måttenhet att visa i gränssnittet och när du skickar mynt.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Om myntkontrollfunktioner skall visas eller inte</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Avbryt</translation> </message> <message> <source>shade</source> <translation>skugga</translation> </message> <message> <source>solid</source> <translation>fast form</translation> </message> <message> <source>white</source> <translation>vit</translation> </message> <message> <source>default</source> <translation>standard</translation> </message> <message> <source>Please Wait...</source> <translation>Vänta...</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Kommunikationsfel med %1: %2</translation> </message> <message> <source>Connection successfully established!</source> <translation>Anslutning framgångsrikt etablerat!</translation> </message> <message> <source>none</source> <translation>ingen</translation> </message> <message> <source>Confirm options reset</source> <translation>Bekräfta att alternativen ska återställs</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Klientomstart är nödvändig för att aktivera ändringarna.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>Programmet kommer att stängas. Vill du fortsätta?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Denna ändring kräver en klientomstart.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>Den angivna proxy-adressen är ogiltig.</translation> </message> </context> <context> <name>OptionsModel</name> <message> <source>All</source> <translation>Alla</translation> </message> </context> <context> <name>OutMessageListPage</name> <message> <source>These are Presidentielcoin messages you have sent. You can choose which aliases to view related messages using the dropdown to the right.</source> <translation>Dessa är Presidentielcoin meddelanden som du har skickat. Du kan välja vilka alias för att visa relaterade meddelanden med hjälp av rullgardinsmenyn till höger.</translation> </message> <message> <source>Copy Subject</source> <translation>Kopiera Ämne</translation> </message> <message> <source>Copy Msg</source> <translation>kopiera Msg</translation> </message> <message> <source>New Msg</source> <translation>nya Msg</translation> </message> <message> <source>Details</source> <translation>detaljer</translation> </message> <message> <source>Export Message Data</source> <translation>Export meddelandedata</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>GUID</source> <translation>GUID</translation> </message> <message> <source>Time</source> <translation>Tid</translation> </message> <message> <source>From</source> <translation>Från</translation> </message> <message> <source>To</source> <translation>Till</translation> </message> <message> <source>Subject</source> <translation>Ämne</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>Error exporting</source> <translation>error exporterar</translation> </message> <message> <source>Could not write to file: </source> <translation>Det gick inte att skriva till filen:</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulär</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Presidentielcoin network after a connection is established, but this process has not completed yet.</source> <translation>Den visade informationen kan vara inaktuell. Plånboken synkroniseras automatiskt med Presidentielcoin-nätverket efter att anslutningen är upprättad, men denna process har inte slutförts ännu.</translation> </message> <message> <source>Watch-only:</source> <translation>Granska-bara:</translation> </message> <message> <source>Available:</source> <translation>Tillgängligt:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Ditt tillgängliga saldo</translation> </message> <message> <source>Pending:</source> <translation>Pågående:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Totalt antal transaktioner som ännu inte bekräftats, och som ännu inte räknas med i aktuellt saldo</translation> </message> <message> <source>Immature:</source> <translation>Omogen:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Den genererade balansen som ännu inte har mognat</translation> </message> <message> <source>Balances</source> <translation>Balanser</translation> </message> <message> <source>Total:</source> <translation>Totalt:</translation> </message> <message> <source>Your current total balance</source> <translation>Ditt nuvarande totala saldo</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Ditt nuvarande saldo i granska-bara adresser</translation> </message> <message> <source>Spendable:</source> <translation>Spenderbar:</translation> </message> <message> <source>Recent transactions</source> <translation>Nyligen genomförda transaktioner</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Okonfirmerade transaktioner till granska-bara adresser</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Den genererade balansen i granska-bara adresser som ännu inte har mognat</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Nuvarande total balans i granska-bara adresser</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>Payment request error</source> <translation>Fel vid betalningsbegäran</translation> </message> <message> <source>Cannot start presidentielcoin: click-to-pay handler</source> <translation>Kan inte starta presidentielcoin: klicka-och-betala handhavare</translation> </message> <message> <source>URI handling</source> <translation>URI hantering</translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation>Betalningsbegärans hämta URL är felaktig: %1</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Felaktig betalningsadress %1</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid Presidentielcoin address or malformed URI parameters.</source> <translation>URI går inte att tolkas! Detta kan orsakas av en ogiltig Presidentielcoin-adress eller felaktiga URI parametrar.</translation> </message> <message> <source>Payment request file handling</source> <translation>Hantering av betalningsbegäransfil</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>Betalningsbegäransfilen kan inte läsas! Detta kan orsakas av en felaktig betalningsbegäransfil.</translation> </message> <message> <source>Payment request rejected</source> <translation>Betalningsbegäran avslogs</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>Betalningsbegärans nätverk matchar inte klientens nätverk.</translation> </message> <message> <source>Payment request expired.</source> <translation>Betalningsbegäran löpte ut.</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>Betalningsbegäran är inte initierad.</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Overifierade betalningsbegärningar till specialbetalningsskript stöds inte.</translation> </message> <message> <source>Invalid payment request.</source> <translation>Ogiltig betalningsbegäran.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>Begärd betalning av %1 är för liten (betraktas som damm).</translation> </message> <message> <source>Refund from %1</source> <translation>Återbetalning från %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>Betalningsbegäran %1 är för stor (%2 bytes, tillåten %3 bytes)</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Kommunikationsfel med %1: %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>Betalningsbegäran kan inte behandlas!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Dåligt svar från server %1</translation> </message> <message> <source>Network request error</source> <translation>Fel vid närverksbegäran</translation> </message> <message> <source>Payment acknowledged</source> <translation>Betalningen bekräftad</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>Användaragent</translation> </message> <message> <source>Node/Service</source> <translation>Nod/Tjänst</translation> </message> <message> <source>Ping Time</source> <translation>Pingtid</translation> </message> <message> <source>NodeId</source> <translation>NodeId</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>Enter a Presidentielcoin address e.g. johnsmith or </source> <translation>Ange en Presidentielcoin adress t.ex. johnsmith eller</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>None</source> <translation>Ingen</translation> </message> <message> <source>N/A</source> <translation>ej tillgänglig</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> <message numerus="yes"> <source>%n seconds(s)</source> <translation><numerusform>%n sekunder(s)</numerusform><numerusform>%n sekunder(s)</numerusform></translation> </message> <message numerus="yes"> <source>%n minutes(s)</source> <translation><numerusform>%n minut (er)</numerusform><numerusform>%n minut(er)</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n timme</numerusform><numerusform>%n timmar</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagar</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n vecka</numerusform><numerusform>%n veckor</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 och %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n år</numerusform><numerusform>%n år</numerusform></translation> </message> <message> <source>All</source> <translation>Alla</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Spara Bild...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;Kopiera Bild</translation> </message> <message> <source>Save QR Code</source> <translation>Spara QR-kod</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>PNG-bild (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>ej tillgänglig</translation> </message> <message> <source>Client version</source> <translation>Klient-version</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <source>Debug window</source> <translation>Debug fönster</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Använder BerkeleyDB versionen</translation> </message> <message> <source>Datadir</source> <translation>Datakatalog</translation> </message> <message> <source>Startup time</source> <translation>Uppstartstid</translation> </message> <message> <source>Network</source> <translation>Nätverk</translation> </message> <message> <source>Name</source> <translation>Namn</translation> </message> <message> <source>Number of connections</source> <translation>Antalet anslutningar</translation> </message> <message> <source>Block chain</source> <translation>Blockkedja</translation> </message> <message> <source>Current number of blocks</source> <translation>Aktuellt antal block</translation> </message> <message> <source>Memory Pool</source> <translation>Minnespool</translation> </message> <message> <source>Current number of transactions</source> <translation>Nuvarande antal transaktioner</translation> </message> <message> <source>Memory usage</source> <translation>Minnesåtgång</translation> </message> <message> <source>Received</source> <translation>Mottagen</translation> </message> <message> <source>Sent</source> <translation>Skickad</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Klienter</translation> </message> <message> <source>Banned peers</source> <translation>Bannade noder</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Välj en klient för att se detaljerad information.</translation> </message> <message> <source>Whitelisted</source> <translation>Vitlistad</translation> </message> <message> <source>Direction</source> <translation>Riktning</translation> </message> <message> <source>Version</source> <translation>Version</translation> </message> <message> <source>Starting Block</source> <translation>Startblock</translation> </message> <message> <source>Synced Headers</source> <translation>Synkade huvuden</translation> </message> <message> <source>Synced Blocks</source> <translation>Synkade block</translation> </message> <message> <source>User Agent</source> <translation>Användaragent</translation> </message> <message> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Öppna %1 debug-loggfilen från aktuell datakatalog. Detta kan ta några sekunder för stora loggfiler.</translation> </message> <message> <source>Decrease font size</source> <translation>Minska fontstorleken</translation> </message> <message> <source>Increase font size</source> <translation>Öka fontstorleken</translation> </message> <message> <source>Services</source> <translation>Tjänster</translation> </message> <message> <source>Ban Score</source> <translation>Banpoäng</translation> </message> <message> <source>Connection Time</source> <translation>Anslutningstid</translation> </message> <message> <source>Last Send</source> <translation>Senast sänt</translation> </message> <message> <source>Last Receive</source> <translation>Senast mottagen</translation> </message> <message> <source>Ping Time</source> <translation>Pingtid</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>Tidsåtgången för en nuvarande utestående ping.</translation> </message> <message> <source>Ping Wait</source> <translation>Pingväntetid</translation> </message> <message> <source>Time Offset</source> <translation>Tidsförskjutning</translation> </message> <message> <source>Last block time</source> <translation>Sista blocktid</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Öppna</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Konsol</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Nätverkstrafik</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Rensa</translation> </message> <message> <source>Totals</source> <translation>Totalt:</translation> </message> <message> <source>In:</source> <translation>In:</translation> </message> <message> <source>Out:</source> <translation>Ut:</translation> </message> <message> <source>Debug log file</source> <translation>Debugloggfil</translation> </message> <message> <source>Clear console</source> <translation>Rensa konsollen</translation> </message> <message> <source>&amp;Disconnect Node</source> <translation>&amp;Koppla från nod</translation> </message> <message> <source>Ban Node for</source> <translation>Banna nod i</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;timme</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;dag</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;vecka</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;år</translation> </message> <message> <source>&amp;Unban Node</source> <translation>&amp;Ta bort ban från nod</translation> </message> <message> <source>Welcome to the %1 RPC console.</source> <translation>Välkommen till %1 RPC-konsolen.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Använd upp- och ner-pilarna för att navigera i historiken, och &lt;b&gt;Ctrl-L&lt;/b&gt; för att rensa skärmen.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Skriv &lt;b&gt;help&lt;/b&gt; för en översikt av alla kommandon.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>(node id: %1)</source> <translation>(nod-id: %1)</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>aldrig</translation> </message> <message> <source>Inbound</source> <translation>Inkommande</translation> </message> <message> <source>Outbound</source> <translation>Utgående</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Unknown</source> <translation>Okänd</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Belopp:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etikett:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Meddelande:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Återanvänd en av tidigare använda mottagningsadresser. Återanvändning av adresser har både säkerhets och integritetsbrister. Använd inte samma mottagningsadress om du inte gör om samma betalningsbegäran.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>Åt&amp;eranvänd en existerande mottagningsadress (rekommenderas inte)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Presidentielcoin network.</source> <translation>Ett frivilligt meddelande att bifoga betalningsbegäran, vilket visas när begäran öppnas. NB: Meddelandet kommer inte att sändas med betalningen över Presidentielcoinnätverket.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>En frivillig etikett att associera med den nya mottagningsadressen.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Använd detta formulär för att begära betalningar. Alla fält är &lt;b&gt;frivilliga&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>En valfri summa att begära. Lämna denna tom eller noll för att inte begära en specifik summa.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Rensa alla formulärfälten</translation> </message> <message> <source>Clear</source> <translation>Rensa</translation> </message> <message> <source>Requested payments history</source> <translation>Historik för begärda betalningar</translation> </message> <message> <source>&amp;Request payment</source> <translation>Begä&amp;r betalning</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Visa valda begäranden (gör samma som att dubbelklicka på en post)</translation> </message> <message> <source>Show</source> <translation>Visa</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Ta bort valda poster från listan</translation> </message> <message> <source>Remove</source> <translation>Ta bort</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy message</source> <translation>Kopiera meddelande</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR-kod</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Kopiera &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Kopiera &amp;Adress</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Spara Bild...</translation> </message> <message> <source>Request payment to %1</source> <translation>Begär betalning till %1</translation> </message> <message> <source>Payment information</source> <translation>Betalningsinformation</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI:n är för lång, försöka minska texten för etikett / meddelande.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Fel vid skapande av QR-kod från URI.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <source>(no message)</source> <translation>(inget meddelande)</translation> </message> <message> <source>(no amount requested)</source> <translation>(Ingen begärda beloppet)</translation> </message> <message> <source>Requested</source> <translation>Begärda</translation> </message> </context> <context> <name>ResellOfferDialog</name> <message> <source>Resell Offer</source> <translation>sälja ett anbud</translation> </message> <message> <source>Offer:</source> <translation>Erbjudande:</translation> </message> <message> <source>Affiliate Markup:</source> <translation>Affiliate Markup:</translation> </message> <message> <source>Enter Markup or Markdown(negative amount) percentage amount(without the % sign). You cannot give more of a discount than the rebate you were provided to Re-sell.</source> <translation>Ange Markup eller Wiki (negativt belopp) procentbelopp (utan% tecken). Du kan inte ge mer av en rabatt än rabatten du lämnades att sälja.</translation> </message> <message> <source>Description:</source> <translation>Beskrivning:</translation> </message> <message> <source>Alias:</source> <translation>Alias:</translation> </message> <message> <source>Enter the 'percentage' amount(without the % sign) that you would like to mark-up the price to</source> <translation>Ange "procent" belopp (utan% tecken) som du vill markera upp priset till</translation> </message> <message> <source>Offer resold successfully! Check the 'Selling' tab to see it after it has confirmed.</source> <translation>Erbjudandet säljas framgångsrikt! Kontrollera "sälja" fliken för att se den när den har bekräftats.</translation> </message> <message> <source>Error creating new linked offer: </source> <translation>Fel skapa nya kombinationserbjudande:</translation> </message> <message> <source>General exception creating new linked offer: </source> <translation>Allmänt undantag skapa nya kombinationserbjudande:</translation> </message> <message> <source>Could not refresh alias list: </source> <translation>Det gick inte att uppdatera alias lista:</translation> </message> <message> <source>There was an exception trying to refresh the alias list: </source> <translation>Det var ett undantag som försöker uppdatera alias lista:</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Skicka pengar</translation> </message> <message> <source>Coin Control Features</source> <translation>Myntkontrollfunktioner</translation> </message> <message> <source>Inputs...</source> <translation>Inmatningar...</translation> </message> <message> <source>automatically selected</source> <translation>automatiskt vald</translation> </message> <message> <source>Insufficient funds!</source> <translation>Otillräckliga medel!</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Bytes:</source> <translation>Antal Byte:</translation> </message> <message> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <source>Change:</source> <translation>Växel:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Om denna är aktiverad men växeladressen är tom eller felaktig kommer växeln att sändas till en nygenererad adress.</translation> </message> <message> <source>Custom change address</source> <translation>Specialväxeladress</translation> </message> <message> <source>Transaction Fee:</source> <translation>Transaktionsavgift:</translation> </message> <message> <source>Choose...</source> <translation>Välj...</translation> </message> <message> <source>collapse fee-settings</source> <translation>Fäll ihop avgiftsinställningarna</translation> </message> <message> <source>per kilobyte</source> <translation>per kilobyte</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Om den anpassad avgiften är satt till 1000 satoshi och transaktionen bara är 250 byte, betalar "per kilobyte" bara 250 satoshi i avgift, medans "totalt minst" betalar 1000 satoshi. För transaktioner större än en kilobyte betalar både per kilobyte.</translation> </message> <message> <source>Hide</source> <translation>Göm</translation> </message> <message> <source>total at least</source> <translation>totalt minst</translation> </message> <message> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for presidentielcoin transactions than the network can process.</source> <translation>Att betala endast den minsta avgiften är bara bra så länge det är mindre transaktionsvolym än utrymme i blocken. Men tänk på att det kan hamna i en aldrig bekräftar transaktion när det finns mer efterfrågan på presidentielcoin transaktioner än nätverket kan bearbeta.</translation> </message> <message> <source>(read the tooltip)</source> <translation>(läs verktygstips)</translation> </message> <message> <source>Recommended:</source> <translation>Rekommenderad:</translation> </message> <message> <source>Custom:</source> <translation>Anpassad:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Smartavgiften är inte initierad än. Detta tar vanligen några block...)</translation> </message> <message> <source>Confirmation time:</source> <translation>Bekräftelsetid:</translation> </message> <message> <source>normal</source> <translation>normal</translation> </message> <message> <source>fast</source> <translation>snabb</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Skicka till flera mottagare samtidigt</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Lägg till &amp;mottagare</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Rensa alla formulärfälten</translation> </message> <message> <source>Dust:</source> <translation>Damm:</translation> </message> <message> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <source>Balance:</source> <translation>Balans:</translation> </message> <message> <source>Confirm the send action</source> <translation>Bekräfta sändordern</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Skicka</translation> </message> <message> <source>Copy quantity</source> <translation>Kopiera kvantitet</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>Copy fee</source> <translation>Kopiera avgift</translation> </message> <message> <source>Copy after fee</source> <translation>Kopiera efter avgift</translation> </message> <message> <source>Copy bytes</source> <translation>Kopiera byte</translation> </message> <message> <source>Copy dust</source> <translation>Kopiera damm</translation> </message> <message> <source>Copy change</source> <translation>Kopiera växel</translation> </message> <message> <source>%1 to %2</source> <translation>%1 till %2</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Är du säker på att du vill skicka?</translation> </message> <message> <source>added as transaction fee</source> <translation>adderad som transaktionsavgift</translation> </message> <message> <source>Total Amount %1</source> <translation>Total summa %1</translation> </message> <message> <source>or</source> <translation>eller</translation> </message> <message> <source>Confirm send coins</source> <translation>Bekräfta skickade mynt</translation> </message> <message> <source>The recipient address is not valid. Please recheck.</source> <translation>Mottagarens adress är ogiltig. Kontrollera igen.</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>Det betalade beloppet måste vara större än 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>Värdet överstiger ditt saldo.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalvärdet överstiger ditt saldo när transaktionsavgiften %1 är pålagd.</translation> </message> <message> <source>Duplicate address found: addresses should only be used once each.</source> <translation>Duplicerad adress upptäckt: adresser skall endast användas en gång var.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>Transaktionen gick inte att skapa!</translation> </message> <message> <source>The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Transaktionen avslogs! Detta kan hända om några av mynten i plånboken redan spenderats, t.ex om du använt en kopia av wallet.dat och mynt spenderades i kopian men inte markerats som spenderade här.</translation> </message> <message> <source>A fee higher than %1 is considered an absurdly high fee.</source> <translation>En avgift som är högre än %1 anses vara en orimligt hög avgift.</translation> </message> <message> <source>Payment request expired.</source> <translation>Betalningsbegäran löpte ut.</translation> </message> <message> <source>Pay only the required fee of %1</source> <translation>Betala endast den nödvändiga avgiften på %1</translation> </message> <message numerus="yes"> <source>Estimated to begin confirmation within %n block(s).</source> <translation><numerusform>Beräknas börja bekräftelse inom %n blocket (s).</numerusform><numerusform>Beräknas börja bekräftelse inom %n blocket (s).</numerusform></translation> </message> <message> <source>Warning: Invalid Presidentielcoin address</source> <translation>Varning: Felaktig Presidentielcoinadress</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Varning: Okänd växeladress</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Belopp:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Betala &amp;Till:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etikett:</translation> </message> <message> <source>Choose previously used address</source> <translation>Välj tidigare använda adresser</translation> </message> <message> <source>This is a normal payment.</source> <translation>Detta är en normal betalning.</translation> </message> <message> <source>The Presidentielcoin address to send the payment to</source> <translation>Presidentielcoinadress att sända betalning till</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Radera denna post</translation> </message> <message> <source>The fee will be deducted from the amount being sent. The recipient will receive less presidentielcoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source> <translation>Avgiften dras från beloppet som skickas. Mottagaren kommer att få mindre presidentielcoins än du angivit i belopp-fältet. Om flera mottagare valts kommer avgiften delas jämt.</translation> </message> <message> <source>S&amp;ubtract fee from amount</source> <translation>S&amp;ubtrahera avgiften från beloppet</translation> </message> <message> <source>Message:</source> <translation>Meddelande:</translation> </message> <message> <source>This is an unauthenticated payment request.</source> <translation>Detta är en oautentiserad betalningsbegäran.</translation> </message> <message> <source>This is an authenticated payment request.</source> <translation>Detta är en autentiserad betalningsbegäran.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Ange en etikett för denna adress att adderas till listan över använda adresser</translation> </message> <message> <source>A message that was attached to the presidentielcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Presidentielcoin network.</source> <translation>Ett meddelande som bifogades presidentielcoin-URI, vilket lagras med transaktionen som referens. NB: Meddelandet kommer inte att sändas över Presidentielcoinnätverket.</translation> </message> <message> <source>Pay To:</source> <translation>Betala Till:</translation> </message> <message> <source>Memo:</source> <translation>PM:</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Ange ett namn för den här adressen och lägg till den i din adressbok</translation> </message> </context> <context> <name>SendConfirmationDialog</name> <message> <source>Yes</source> <translation>Ja</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>%1 is shutting down...</source> <translation>%1 stängs av...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Stäng inte av datorn förrän denna ruta försvinner.</translation> </message> </context> <context> <name>SignRawTxDialog</name> <message> <source>Sign Raw Transaction</source> <translation>Underteckna Raw transaktion</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>Decode</source> <translation>Avkoda</translation> </message> <message> <source>OK</source> <translation>ok</translation> </message> <message> <source>Cancel</source> <translation>Annullera</translation> </message> <message> <source>General exception decoding raw transaction</source> <translation>Allmänt undantag avkodning rå transaktion</translation> </message> <message> <source>Sign a raw presidentielcoin transaction and send it to the network if it is complete with all required signatures. Enter the raw hex encoded transaction below</source> <translation>Underteckna en rå presidentielcoin transaktion och sända den till nätverket om det är komplett med alla erforderliga signaturer. Ange rå hex kodade transaktions nedan</translation> </message> <message> <source>Once you enter a valid raw transaction in the general section this area will become populated with the raw transaction information including any presidentielcoin related service information so you will know what the transaction is doing before signing and potentially sending it to the network.</source> <translation>När du anger en giltig rå transaktion i den allmänna delen detta område kommer att bli befolkat med råtransaktionsinformation inklusive presidentielcoin relaterad serviceinformation så att du vet vad affären gör innan du skriver och eventuellt skicka den till nätverket.</translation> </message> <message> <source>The area below is to display presidentielcoin specific information regarding this transaction. Currently there is nothing to display</source> <translation>Området nedanför är att visa presidentielcoin specifik information om denna transaktion. För närvarande finns det inget att visa</translation> </message> <message> <source>Error creating decoding raw transaction: </source> <translation>Fel skapa avkodning rå transaktion:</translation> </message> <message> <source>The area below is to display presidentielcoin specific information regarding this transaction</source> <translation>Området nedanför är att visa presidentielcoin specifik information om denna transaktion</translation> </message> <message> <source>Error creating decoding raw presidentielcoin transaction: </source> <translation>Fel skapa avkodning rå presidentielcoin transaktion:</translation> </message> <message> <source>General exception decoding raw presidentielcoin transaction</source> <translation>Allmänt undantag avkodning rå presidentielcoin transaktion</translation> </message> <message> <source>Transaction was completed successfully!</source> <translation>Affären slutfördes framgångsrikt!</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that has not yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Error creating updating multisig alias: </source> <translation>Fel skapa uppdatera multisig alias:</translation> </message> <message> <source>General exception creating sending raw alias update transaction</source> <translation>Allmänt undantag skapar skicka rå alias uppdateringstransaktion</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturer - Signera / Verifiera ett Meddelande</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Signera Meddelande</translation> </message> <message> <source>You can sign messages/agreements with your addresses to prove you can receive presidentielcoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Du kan underteckna meddelanden/avtal med dina adresser för att bevisa att du kan ta emot presidentielcoins som skickats till dem. Var försiktig så du inte undertecknar något oklart eller konstigt, eftersom phishing-angrepp kan försöka få dig att underteckna din identitet till dem. Underteckna endast väldetaljerade meddelanden som du godkänner.</translation> </message> <message> <source>The Presidentielcoin address to sign the message with</source> <translation>Presidentielcoinadress att signera meddelandet med</translation> </message> <message> <source>Choose previously used address</source> <translation>Välj tidigare använda adresser</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Skriv in meddelandet du vill signera här</translation> </message> <message> <source>Signature</source> <translation>Signatur</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Kopiera signaturen till systemets Urklipp</translation> </message> <message> <source>Sign the message to prove you own this Presidentielcoin address</source> <translation>Signera meddelandet för att bevisa att du äger denna adress</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Signera &amp;Meddelande</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Rensa alla fält</translation> </message> <message> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verifiera Meddelande</translation> </message> <message> <source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source> <translation>Ange mottagarens adress, meddelande (kopiera radbrytningar, mellanrum, flikar, etc. exakt) och signatur nedan för att verifiera meddelandet. Undvik att läsa in mera information i signaturen än vad som stod i själva undertecknade meddelandet, för att undvika ett man-in-the-middle-angrepp. Notera att detta endast bevisar att undertecknad tar emot med adressen, det bevisar inte vem som skickat transaktionen!</translation> </message> <message> <source>The Presidentielcoin address the message was signed with</source> <translation>Presidentielcoinadressen som meddelandet signerades med</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Presidentielcoin address</source> <translation>Verifiera meddelandet för att vara säker på att den var signerad med den angivna Presidentielcoin-adressen</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verifiera &amp;Meddelande</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Rensa alla fält</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>Klicka "Signera Meddelande" för att få en signatur</translation> </message> <message> <source>The entered address is invalid.</source> <translation>Den angivna adressen är ogiltig.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Vad god kontrollera adressen och försök igen.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>Den angivna adressen refererar inte till en nyckel.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>Upplåsningen av plånboken avbröts.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>Privata nyckel för den angivna adressen är inte tillgänglig.</translation> </message> <message> <source>Message signing failed.</source> <translation>Signeringen av meddelandet misslyckades.</translation> </message> <message> <source>Message signed.</source> <translation>Meddelandet är signerat.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>Signaturen kunde inte avkodas.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Kontrollera signaturen och försök igen.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>Signaturen matchade inte meddelandesammanfattningen.</translation> </message> <message> <source>Message verification failed.</source> <translation>Meddelandet verifikation misslyckades.</translation> </message> <message> <source>Message verified.</source> <translation>Meddelandet är verifierad.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>PresidentielcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Signera &amp;meddelande...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synkroniserar med nätverk...</translation> </message> <message> <source>Node</source> <translation>Nod</translation> </message> <message> <source>Overview</source> <translation>Översikt</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Visa generell översikt av plånboken</translation> </message> <message> <source>Send</source> <translation>Skicka</translation> </message> <message> <source>Receive</source> <translation>Motta</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaktioner</translation> </message> <message> <source>Browse transaction history</source> <translation>Bläddra i transaktionshistorik</translation> </message> <message> <source>Aliases</source> <translation>alias</translation> </message> <message> <source>Marketplace</source> <translation>Marknad</translation> </message> <message> <source>Certificates</source> <translation>certifikat</translation> </message> <message> <source>Escrow</source> <translation>spärrade</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Avsluta</translation> </message> <message> <source>Quit application</source> <translation>Avsluta programmet</translation> </message> <message> <source>Show information about %1</source> <translation>Visa information om %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>Om &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Visa information om Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Alternativ...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>Ändra konfigurationsalternativ för %1</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Kryptera plånbok...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Säkerhetskopiera plånbok...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Byt lösenord...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>Av&amp;sändaradresser...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Mottaga&amp;radresser...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Öppna &amp;URI...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Återindexerar block på disken...</translation> </message> <message> <source>Send coins to a Presidentielcoin address</source> <translation>Skicka presidentielcoins till en Presidentielcoin-adress</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Säkerhetskopiera plånboken till en annan plats</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Byt lösenfras för kryptering av plånbok</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Debug-fönster</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Öppna debug- och diagnostikkonsolen</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verifiera meddelande...</translation> </message> <message> <source>Presidentielcoin</source> <translation>Presidentielcoin</translation> </message> <message> <source>Wallet</source> <translation>Plånbok</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Visa / Göm</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Visa eller göm huvudfönstret</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Kryptera de privata nycklar som tillhör din plånbok</translation> </message> <message> <source>Sign messages with your Presidentielcoin addresses to prove you own them</source> <translation>Signera meddelanden med din Presidentielcoin-adress för att bevisa att du äger dem</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Presidentielcoin addresses</source> <translation>Verifiera meddelanden för att vara säker på att de var signerade med specificerade Presidentielcoin-adresser</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Arkiv</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Inställningar</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Hjälp</translation> </message> <message> <source>Tabs toolbar</source> <translation>Verktygsfält för tabbar</translation> </message> <message> <source>Request payments (generates QR codes and presidentielcoin: URIs)</source> <translation>Begär betalning (genererar QR-koder och presidentielcoin-URI)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Visa listan av använda avsändaradresser och etiketter</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Visa listan av använda mottagningsadresser och etiketter</translation> </message> <message> <source>Open a presidentielcoin: URI or payment request</source> <translation>Öppna en presidentielcoin: URI eller betalningsbegäran</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Kommandoradsalternativ</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Presidentielcoin network</source> <translation><numerusform>%n aktiva anslutningar till Presidentielcoin-nätverket.</numerusform><numerusform>%n aktiva anslutningar till Presidentielcoin-nätverket.</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>Indexerar block på disken...</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>Bearbetar block på disken...</translation> </message> <message> <source>No block source available...</source> <translation>Ingen block-källa tillgänglig...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>Bearbetade %n block av transaktionshistoriken.</numerusform><numerusform>Bearbetade %n block av transaktionshistoriken.</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 efter</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Senast mottagna block genererades för %1 sen.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Transaktioner efter denna kommer inte ännu vara synliga.</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> <message> <source>Warning</source> <translation>Varning</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Up to date</source> <translation>Uppdaterad</translation> </message> <message> <source>Manage aliases</source> <translation>hantera alias</translation> </message> <message> <source>Messages</source> <translation>meddelanden</translation> </message> <message> <source>Manage offers</source> <translation>Hantera erbjudanden</translation> </message> <message> <source>Manage Certificates</source> <translation>Hantera certifikat</translation> </message> <message> <source>Escrows with offers</source> <translation>Escrows med erbjudanden</translation> </message> <message> <source>&amp;About Presidentielcoin Core</source> <translation>&amp;Om Presidentielcoin Core</translation> </message> <message> <source>Show the %1 help message to get a list with possible Presidentielcoin command-line options</source> <translation>Visa %1 hjälpmeddelande för att få en lista med möjliga Presidentielcoin kommandoradsalternativ.</translation> </message> <message> <source>%1 client</source> <translation>%1-klient</translation> </message> <message> <source>Catching up...</source> <translation>Hämtar senaste...</translation> </message> <message> <source>Date: %1 </source> <translation>Datum: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Belopp: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Typ: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Etikett: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Adress: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Transaktion skickad</translation> </message> <message> <source>Incoming transaction</source> <translation>Inkommande transaktion</translation> </message> <message> <source>HD key generation is &lt;b&gt;enabled&lt;/b&gt;</source> <translation>HD nyckelgenerering är &lt;b&gt; aktiverade &lt;/b&gt;</translation> </message> <message> <source>HD key generation is &lt;b&gt;disabled&lt;/b&gt;</source> <translation>HD nyckelgenerering är &lt;b&gt; avaktiverad &lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;olåst&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;låst&lt;/b&gt;</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Öppet för %n mer blocket (s)</numerusform><numerusform>Öppet för %n mer blocket(s)</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Öppet till %1</translation> </message> <message> <source>conflicted with a transaction with %1 confirmations</source> <translation>konflikt med en transaktion med %1 bekräftelser</translation> </message> <message> <source>%1/offline</source> <translation>%1/nerkopplad</translation> </message> <message> <source>0/unconfirmed, %1</source> <translation>0 / obekräftad, %1</translation> </message> <message> <source>in memory pool</source> <translation>i minne pool</translation> </message> <message> <source>not in memory pool</source> <translation>inte finns i minnet pool</translation> </message> <message> <source>abandoned</source> <translation>övergiven</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/obekräftade</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 bekräftelser</translation> </message> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, har inte lyckats skickas ännu</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>, Sänds via %n nod(er)</numerusform><numerusform>, Sänds via %n nod(er)</numerusform></translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Source</source> <translation>Källa</translation> </message> <message> <source>Generated</source> <translation>Genererad</translation> </message> <message> <source>From</source> <translation>Från</translation> </message> <message> <source>unknown</source> <translation>okänd</translation> </message> <message> <source>To</source> <translation>Till</translation> </message> <message> <source>own address</source> <translation>egen adress</translation> </message> <message> <source>watch-only</source> <translation>granska-bara</translation> </message> <message> <source>label</source> <translation>etikett</translation> </message> <message> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>mognar i %n mer blocket(s)</numerusform><numerusform>mognar i %n mer blocket(s)</numerusform></translation> </message> <message> <source>not accepted</source> <translation>inte accepterad</translation> </message> <message> <source>Debit</source> <translation>Belasta</translation> </message> <message> <source>Total debit</source> <translation>Total skuld</translation> </message> <message> <source>Total credit</source> <translation>Total kredit</translation> </message> <message> <source>Transaction fee</source> <translation>Transaktionsavgift</translation> </message> <message> <source>Net amount</source> <translation>Nettobelopp</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <source>Transaction ID</source> <translation>Transaktions-ID</translation> </message> <message> <source>Transaction total size</source> <translation>Transaktion totala storleken</translation> </message> <message> <source>Output index</source> <translation>output index</translation> </message> <message> <source>Merchant</source> <translation>Handlare</translation> </message> <message> <source>Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Genererade mynt måste vänta %1 block innan de kan användas. När du skapade detta block sändes det till nätverket för att läggas till i blockkedjan. Om blocket inte kommer in i kedjan kommer dess status att ändras till "accepteras inte" och kommer ej att gå att spendera. Detta kan ibland hända om en annan nod genererar ett block nästan samtidigt som dig.</translation> </message> <message> <source>Debug information</source> <translation>Debug information</translation> </message> <message> <source>Transaction</source> <translation>Transaktion</translation> </message> <message> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>true</source> <translation>sant</translation> </message> <message> <source>false</source> <translation>falsk</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Transaktionsdetaljer</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Den här panelen visar en detaljerad beskrivning av transaktionen</translation> </message> <message> <source>Details for %1</source> <translation>Mer information om %1</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Typ</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Öppet för %n mer blocket(s)</numerusform><numerusform>Öppet för %n mer blocket(s)</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Öppet till %1</translation> </message> <message> <source>Offline</source> <translation>Nerkopplad</translation> </message> <message> <source>Unconfirmed</source> <translation>Okonfirmerade</translation> </message> <message> <source>Abandoned</source> <translation>Övergiven</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Konfirmerar (%1 of %2 konfirmeringar)</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Bekräftad (%1 bekräftelser)</translation> </message> <message> <source>Conflicted</source> <translation>Konflikterade</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Omogen (%1 konfirmeringar, blir tillgänglig efter %2)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Det här blocket togs inte emot av några andra noder och kommer antagligen inte att bli godkänt.</translation> </message> <message> <source>Generated but not accepted</source> <translation>Genererad men inte accepterad</translation> </message> <message> <source>Received with</source> <translation>Mottagen med</translation> </message> <message> <source>Received from</source> <translation>Mottaget från</translation> </message> <message> <source>Sent to</source> <translation>Skickad till</translation> </message> <message> <source>Payment to yourself</source> <translation>Betalning till dig själv</translation> </message> <message> <source>Mined</source> <translation>Genererade</translation> </message> <message> <source>Alias Activated</source> <translation>alias Aktiverad</translation> </message> <message> <source>Alias Payment Sent</source> <translation>Alias ​​betalning skickas</translation> </message> <message> <source>Alias Payment Received</source> <translation>Alias ​​Betalning mottagen</translation> </message> <message> <source>Alias Transferred</source> <translation>alias Överfört</translation> </message> <message> <source>Alias Updated</source> <translation>alias Uppdaterad</translation> </message> <message> <source>Alias Received</source> <translation>alias emot</translation> </message> <message> <source>Offer Activated</source> <translation>erbjudandet Aktiverad</translation> </message> <message> <source>Offer Updated</source> <translation>erbjudandet Uppdaterad</translation> </message> <message> <source>Offer Accepted</source> <translation>Erbjudandet Godkända</translation> </message> <message> <source>Offer Accept Acknowledged</source> <translation>Erbjudandet emot Bekräftat</translation> </message> <message> <source>Offer Accept Received</source> <translation>Erbjuder Acceptera mottagen</translation> </message> <message> <source>Offer Accept Feedback</source> <translation>Erbjuda Acceptera Feedback</translation> </message> <message> <source>Offer Accept Feedback Received</source> <translation>Erbjudandet emot omdömmen mottagna</translation> </message> <message> <source>Cert. Activated</source> <translation>Cert. aktiverad</translation> </message> <message> <source>Cert. Updated</source> <translation>Cert. Uppdaterad</translation> </message> <message> <source>Cert. Transferred</source> <translation>Cert. Överförd</translation> </message> <message> <source>Cert. Received</source> <translation>Cert. Fick</translation> </message> <message> <source>Escrow Activated</source> <translation>spärrade Aktiverad</translation> </message> <message> <source>Escrow Acknowledged</source> <translation>spärrade Bekräftade</translation> </message> <message> <source>Escrow Released</source> <translation>spärrade Släppt</translation> </message> <message> <source>Escrow Release Received</source> <translation>Depositions Release emot</translation> </message> <message> <source>Escrow Refunded</source> <translation>Escrow återbetalas</translation> </message> <message> <source>Escrow Feedback</source> <translation>spärrade Feedback</translation> </message> <message> <source>Escrow Feedback Received</source> <translation>Spärrade omdömmen mottagna</translation> </message> <message> <source>Escrow Refund Received</source> <translation>Depositions återbetalning emot</translation> </message> <message> <source>Escrow Refund Complete</source> <translation>Depositions återbetalning Komplett</translation> </message> <message> <source>Escrow Release Complete</source> <translation>Escrow Release Complete</translation> </message> <message> <source>Message Sent</source> <translation>Meddelande skickat</translation> </message> <message> <source>Message Received</source> <translation>Meddelande mottaget</translation> </message> <message> <source>watch-only</source> <translation>granska-bara</translation> </message> <message> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaktionsstatus. Håll muspekaren över för att se antal bekräftelser.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Tidpunkt då transaktionen mottogs.</translation> </message> <message> <source>Type of transaction.</source> <translation>Transaktionstyp.</translation> </message> <message> <source>Whether or not a watch-only address is involved in this transaction.</source> <translation>Anger om granska-bara--adresser är involverade i denna transaktion.</translation> </message> <message> <source>User-defined intent/purpose of the transaction.</source> <translation>Användardefinierat syfte/ändamål för transaktionen.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Belopp draget eller tillagt till balans.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Alla</translation> </message> <message> <source>Today</source> <translation>Idag</translation> </message> <message> <source>This week</source> <translation>Denna vecka</translation> </message> <message> <source>This month</source> <translation>Denna månad</translation> </message> <message> <source>Last month</source> <translation>Föregående månad</translation> </message> <message> <source>This year</source> <translation>Det här året</translation> </message> <message> <source>Range...</source> <translation>Period...</translation> </message> <message> <source>Received with</source> <translation>Mottagen med</translation> </message> <message> <source>Sent to</source> <translation>Skickad till</translation> </message> <message> <source>To yourself</source> <translation>Till dig själv</translation> </message> <message> <source>Mined</source> <translation>Genererade</translation> </message> <message> <source>Other</source> <translation>Övriga</translation> </message> <message> <source>Alias Activated</source> <translation>alias Aktiverad</translation> </message> <message> <source>Alias Payment Sent</source> <translation>Alias ​​betalning skickas</translation> </message> <message> <source>Alias Payment Received</source> <translation>Alias ​​Betalning mottagen</translation> </message> <message> <source>Alias Updated</source> <translation>alias Uppdaterad</translation> </message> <message> <source>Alias Transferred</source> <translation>alias Överfört</translation> </message> <message> <source>Alias Received</source> <translation>alias emot</translation> </message> <message> <source>Offer Activated</source> <translation>erbjudandet Aktiverad</translation> </message> <message> <source>Offer Updated</source> <translation>erbjudandet Uppdaterad</translation> </message> <message> <source>Offer Accepted</source> <translation>Erbjudandet Godkända</translation> </message> <message> <source>Offer Accept Acknowledged</source> <translation>Erbjudandet emot Bekräftat</translation> </message> <message> <source>Offer Accept Received</source> <translation>Erbjuder Acceptera mottagen</translation> </message> <message> <source>Offer Accept Feedback</source> <translation>Erbjuda Acceptera Feedback</translation> </message> <message> <source>Offer Accept Feedback Received</source> <translation>Erbjudandet emot omdömmen mottagna</translation> </message> <message> <source>Certificate Activated</source> <translation>certifikat Aktiverad</translation> </message> <message> <source>Certificate Updated</source> <translation>certifikat Uppdaterad</translation> </message> <message> <source>Certificate Transferred</source> <translation>certifikat Överfört</translation> </message> <message> <source>Certificate Received</source> <translation>certifikat mottagna</translation> </message> <message> <source>Escrow Activated</source> <translation>spärrade Aktiverad</translation> </message> <message> <source>Escrow Acknowledged</source> <translation>spärrade Bekräftade</translation> </message> <message> <source>Escrow Released</source> <translation>spärrade Släppt</translation> </message> <message> <source>Escrow Release Received</source> <translation>Depositions Release emot</translation> </message> <message> <source>Escrow Refunded</source> <translation>Escrow återbetalas</translation> </message> <message> <source>Escrow Refund Complete</source> <translation>Depositions återbetalning Komplett</translation> </message> <message> <source>Escrow Refund Received</source> <translation>Depositions återbetalning emot</translation> </message> <message> <source>Escrow Feedback</source> <translation>spärrade Feedback</translation> </message> <message> <source>Escrow Feedback Received</source> <translation>Spärrade omdömmen mottagna</translation> </message> <message> <source>Escrow Release Complete</source> <translation>Escrow Release Complete</translation> </message> <message> <source>Message Sent</source> <translation>Meddelande skickat</translation> </message> <message> <source>Message Received</source> <translation>Meddelande mottaget</translation> </message> <message> <source>Enter address or label to search</source> <translation>Sök efter adress eller etikett </translation> </message> <message> <source>Min amount</source> <translation>Minsta mängd</translation> </message> <message> <source>Abandon transaction</source> <translation>överge transaktionen</translation> </message> <message> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>Copy transaction ID</source> <translation>Kopiera transaktions ID</translation> </message> <message> <source>Copy raw transaction</source> <translation>Kopiera rå transaktion</translation> </message> <message> <source>Copy full transaction details</source> <translation>Kopiera hela transaktionsuppgifter</translation> </message> <message> <source>Edit label</source> <translation>Ändra etikett</translation> </message> <message> <source>Show transaction details</source> <translation>Visa transaktionsdetaljer</translation> </message> <message> <source>Export Transaction History</source> <translation>Exportera Transaktionshistoriken</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Bekräftad</translation> </message> <message> <source>Watch-only</source> <translation>Granska-bara</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Type</source> <translation>Typ</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Exporting Failed</source> <translation>Exporteringen misslyckades</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Det inträffade ett fel när transaktionshistoriken skulle sparas till %1.</translation> </message> <message> <source>Exporting Successful</source> <translation>Exporteringen lyckades</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>Transaktionshistoriken sparades utan problem till %1.</translation> </message> <message> <source>Range:</source> <translation>Intervall:</translation> </message> <message> <source>to</source> <translation>till</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>&amp;Enhet att visa belopp i. Klicka för att välja annan enhet.</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>Ingen plånbok har laddats in.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Skicka pengar</translation> </message> <message> <source>Could not sign multisig transaction: Invalid response from signrawtransaction</source> <translation>Det gick inte att logga multisig transaktion: Ogiltigt svar från signrawtransaction</translation> </message> <message> <source>This transaction requires more signatures. Transaction hex has been copied to your clipboard for your reference. Please provide it to a signee that hasn't yet signed.</source> <translation>Denna transaktion kräver mer signaturer. Transaktions hex har kopierats till Urklipp som referens. Ange den till en signee som ännu inte har undertecknat.</translation> </message> <message> <source>Could not decode signed transaction!</source> <translation>Det gick inte att avkoda signerade transaktions!</translation> </message> </context> <context> <name>WalletView</name> <message> <source>Export</source> <translation>Exportera</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>Backup Wallet</source> <translation>Säkerhetskopiera Plånbok</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Plånboks-data (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Säkerhetskopiering misslyckades</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Det inträffade ett fel när plånbokens data skulle sparas till %1.</translation> </message> <message> <source>Backup Successful</source> <translation>Säkerhetskopiering lyckades</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Plånbokens data sparades utan problem till %1.</translation> </message> </context> <context> <name>presidentielcoin-core</name> <message> <source>Options:</source> <translation>Inställningar:</translation> </message> <message> <source>Specify data directory</source> <translation>Ange katalog för data</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Anslut till en nod för att hämta klientadresser, och koppla från</translation> </message> <message> <source>Specify your own public address</source> <translation>Ange din egen publika adress</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Tillåt kommandon från kommandotolken och JSON-RPC-kommandon</translation> </message> <message> <source>If &lt;category&gt; is not supplied or if &lt;category&gt; = 1, output all debugging information.</source> <translation>Om &lt;kategori&gt; inte anges eller om &lt;category&gt; = 1, visa all avlusningsinformation.</translation> </message> <message> <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation>Beskärning konfigurerad under miniminivån %d MiB. Vänligen använd ett högre värde.</translation> </message> <message> <source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source> <translation>Beskärning: sista plånbokssynkroniseringen ligger utanför beskuren data. Du måste använda -reindex (ladda ner hela blockkedjan igen eftersom noden beskurits)</translation> </message> <message> <source>Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, &gt;%u = target size in MiB to use for block files)</source> <translation>Minska lagringsbehovet genom att beskära (ta bort) gamla block. Detta läge är inkompatibelt med -txindex och -rescan. Varning: Ändras denna inställning måste hela blockkedjan laddas ner igen. (förvalt: 0 = inaktivera beskärning av block, &gt;%u = målstorlek i MiB att använda för blockfiler)</translation> </message> <message> <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation>Omskanningar kan inte göras i beskuret läge. Du måste använda -reindex vilket kommer ladda ner hela blockkedjan igen.</translation> </message> <message> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation>Fel: Ett kritiskt internt fel uppstod, se debug.log för detaljer</translation> </message> <message> <source>Fee (in %s/kB) to add to transactions you send (default: %s)</source> <translation>Avgift (i %s/kB) att lägga till på transaktioner du skickar (förvalt: %s)</translation> </message> <message> <source>Pruning blockstore...</source> <translation>Rensar blockstore...</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Kör i bakgrunden som tjänst och acceptera kommandon</translation> </message> <message> <source>Unable to start HTTP server. See debug log for details.</source> <translation>Kunde inte starta HTTP-server. Se avlusningsloggen för detaljer.</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Acceptera anslutningar utifrån (förvalt: 1 om ingen -proxy eller -connect)</translation> </message> <message> <source>Presidentielcoin Core</source> <translation>Presidentielcoin Core</translation> </message> <message> <source>The %s developers</source> <translation>%s utvecklare</translation> </message> <message> <source>-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available.</source> <translation>-fallbackfee är satt väldigt högt! Detta är avgiften du kan komma att betala om uppskattad avgift inte finns tillgänglig.</translation> </message> <message> <source>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</source> <translation>En avgiftskurs (i %s/kB) som används när det inte finns tillräcklig data för att uppskatta avgiften (förvalt: %s)</translation> </message> <message> <source>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</source> <translation>Acceptera vidarebefodrade transaktioner från vitlistade noder även när transaktioner inte vidarebefodras (förvalt: %d)</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind till given adress och lyssna alltid på den. Använd [värd]:port notation för IPv6</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. %s is probably already running.</source> <translation>Kan inte låsa data-mappen %s. %s körs förmodligen redan.</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Ta bort alla plånbokstransaktioner och återskapa bara dom som är en del av blockkedjan genom att ange -rescan vid uppstart</translation> </message> <message> <source>Distributed under the MIT software license, see the accompanying file COPYING or &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</source> <translation>Distribuerad under MIT mjukvarulicens, se den bifogade filen COPYING eller &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</translation> </message> <message> <source>Error loading %s: You can't enable HD on a already existing non-HD wallet</source> <translation>Fel vid laddning av %s: Du kan inte aktivera HD på en existerande icke-HD plånbok</translation> </message> <message> <source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Fel vid läsning av %s! Alla nycklar lästes korrekt, men transaktionsdatat eller adressbokens poster kanske saknas eller är felaktiga.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Exekvera kommando när en plånbokstransaktion ändras (%s i cmd är ersatt av TxID)</translation> </message> <message> <source>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</source> <translation>Maximalt tillåten median-peer tidsoffset justering. Lokalt perspektiv av tiden kan bli påverkad av partners, framåt eller bakåt denna tidsrymd. (förvalt: %u sekunder)</translation> </message> <message> <source>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</source> <translation>Maximal total avgift (i %s) att använda i en plånbokstransaktion eller råa transaktioner. Sätts denna för lågt kan stora transaktioner avbrytas (förvalt: %s)</translation> </message> <message> <source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source> <translation>Vänligen kolla så att din dators datum och tid är korrekt! Om din klocka går fel kommer %s inte att fungera korrekt.</translation> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Ange antalet skriptkontrolltrådar (%u till %d, 0 = auto, &lt;0 = lämna så många kärnor lediga, förval: %d)</translation> </message> <message> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation>Blockdatabasen innehåller ett block som verkar vara från framtiden. Detta kan vara på grund av att din dators datum och tid är felaktiga. Bygg bara om blockdatabasen om du är säker på att datorns datum och tid är korrekt</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Detta är ett förhands testbygge - använd på egen risk - använd inte för mining eller handels applikationer</translation> </message> <message> <source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source> <translation>Kan inte spola tillbaka databasen till obeskärt läge. Du måste ladda ner blockkedjan igen</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 1 när lyssning aktiverat och utan -proxy)</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Varning: Nätverket verkar inte vara helt överens! Några miners verkar ha problem.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Varning: Vi verkar inte helt överens med våra peers! Du kan behöva uppgradera, eller andra noder kan behöva uppgradera.</translation> </message> <message> <source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source> <translation>Vitlista klienter som ansluter från angivna nätmasker eller IP-adresser. Kan specificeras flera gånger.</translation> </message> <message> <source>You need to rebuild the database using -reindex-chainstate to change -txindex</source> <translation>Du måste återskapa databasen med -reindex-chainstate för att ändra -txindex</translation> </message> <message> <source>%s corrupt, salvage failed</source> <translation>%s är korrupt, räddning misslyckades</translation> </message> <message> <source>-maxmempool must be at least %d MB</source> <translation>-maxmempool måste vara minst %d MB</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;category&gt; Kan vara:</translation> </message> <message> <source>Append comment to the user agent string</source> <translation>Lägg till kommentar till user-agent-strängen</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet on startup</source> <translation>Försök att rädda privata nycklar från en korrupt plånbok vid uppstart</translation> </message> <message> <source>Block creation options:</source> <translation>Block skapande inställningar:</translation> </message> <message> <source>Cannot resolve -%s address: '%s'</source> <translation>Kan inte matcha -%s adress: '%s'</translation> </message> <message> <source>Change index out of range</source> <translation>Förändringsindexet utom räckhåll</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Koppla enbart upp till den/de specificerade noden/noder</translation> </message> <message> <source>Connection options:</source> <translation>Anslutningsalternativ:</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Korrupt blockdatabas har upptäckts</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Avlusnings/Test-alternativ:</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Ladda inte plånboken och stäng av RPC-anrop till plånboken</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Vill du bygga om blockdatabasen nu?</translation> </message> <message> <source>Enable publish hash block in &lt;address&gt;</source> <translation>Aktivera publicering av hashblock i &lt;adress&gt;</translation> </message> <message> <source>Enable publish hash transaction in &lt;address&gt;</source> <translation>Aktivera publicering av hashtransaktion i &lt;adress&gt;</translation> </message> <message> <source>Enable publish raw block in &lt;address&gt;</source> <translation>Aktivera publicering av råa block i &lt;adress&gt;</translation> </message> <message> <source>Enable publish raw transaction in &lt;address&gt;</source> <translation>Aktivera publicering av råa transaktioner i &lt;adress&gt;</translation> </message> <message> <source>Enable transaction replacement in the memory pool (default: %u)</source> <translation>Aktivera byte av transaktioner i minnespoolen (förvalt: %u)</translation> </message> <message> <source>Error initializing block database</source> <translation>Fel vid initiering av blockdatabasen</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Fel vid initiering av plånbokens databasmiljö %s!</translation> </message> <message> <source>Error loading %s</source> <translation>Fel vid inläsning av %s</translation> </message> <message> <source>Error loading %s: Wallet corrupted</source> <translation>Fel vid inläsningen av %s: Plånboken är koruppt</translation> </message> <message> <source>Error loading %s: Wallet requires newer version of %s</source> <translation>Fel vid inläsningen av %s: Plånboken kräver en senare version av %s</translation> </message> <message> <source>Error loading %s: You can't disable HD on a already existing HD wallet</source> <translation>Fel vid laddning av %s: Du kan inte avaktivera HD på en redan existerande HD plånbok</translation> </message> <message> <source>Error loading block database</source> <translation>Fel vid inläsning av blockdatabasen</translation> </message> <message> <source>Error opening block database</source> <translation>Fel vid öppning av blockdatabasen</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Fel: Hårddiskutrymme är lågt!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Misslyckades att lyssna på någon port. Använd -listen=0 om du vill detta.</translation> </message> <message> <source>Importing...</source> <translation>Importerar...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Felaktig eller inget genesisblock hittades. Fel datadir för nätverket?</translation> </message> <message> <source>Initialization sanity check failed. %s is shutting down.</source> <translation>Initieringschecken fallerade. %s stängs av.</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Ogiltig -onion adress:'%s'</translation> </message> <message> <source>Invalid amount for -%s=&lt;amount&gt;: '%s'</source> <translation>Ogiltigt belopp för -%s=&lt;belopp&gt;:'%s'</translation> </message> <message> <source>Invalid amount for -fallbackfee=&lt;amount&gt;: '%s'</source> <translation>Ogiltigt belopp för -fallbackfee=&lt;belopp&gt;: '%s'</translation> </message> <message> <source>Keep the transaction memory pool below &lt;n&gt; megabytes (default: %u)</source> <translation>Håll minnespoolen över transaktioner under &lt;n&gt; megabyte (förvalt: %u)</translation> </message> <message> <source>Loading banlist...</source> <translation>Laddar svarta listan...</translation> </message> <message> <source>Location of the auth cookie (default: data dir)</source> <translation>Plats för authcookie (förvalt: datamapp)</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Inte tillräckligt med filbeskrivningar tillgängliga.</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <translation>Anslut enbart till noder i nätverket &lt;net&gt; (IPv4, IPv6 eller onion)</translation> </message> <message> <source>Print this help message and exit</source> <translation>Visa denna hjälptext och avsluta</translation> </message> <message> <source>Print version and exit</source> <translation>Visa version och avsluta</translation> </message> <message> <source>Prune cannot be configured with a negative value.</source> <translation>Beskärning kan inte konfigureras med ett negativt värde.</translation> </message> <message> <source>Prune mode is incompatible with -txindex.</source> <translation>Beskärningsläge är inkompatibel med -txindex.</translation> </message> <message> <source>Rebuild chain state and block index from the blk*.dat files on disk</source> <translation>Återskapa blockkedjans status och index från blk*.dat filer på disken</translation> </message> <message> <source>Rebuild chain state from the currently indexed blocks</source> <translation>Återskapa blockkedjans status från aktuella indexerade block</translation> </message> <message> <source>Rewinding blocks...</source> <translation>Spolar tillbaka blocken...</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Sätt databasens cachestorlek i megabyte (%d till %d, förvalt: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Sätt maximal blockstorlek i byte (förvalt: %d)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Ange plånboksfil (inom datakatalogen)</translation> </message> <message> <source>Unable to bind to %s on this computer. %s is probably already running.</source> <translation>Det går inte att binda till %s på den här datorn. %s är förmodligen redan igång.</translation> </message> <message> <source>Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation>Argumentet -benchmark stöds inte och ignoreras, använd -debug=bench.</translation> </message> <message> <source>Unsupported argument -debugnet ignored, use -debug=net.</source> <translation>Argumentet -debugnet stöds inte och ignoreras, använd -debug=net.</translation> </message> <message> <source>Unsupported argument -tor found, use -onion.</source> <translation>Argumentet -tor hittades men stöds inte, använd -onion.</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: %u)</translation> </message> <message> <source>User Agent comment (%s) contains unsafe characters.</source> <translation>Kommentaren i användaragent (%s) innehåller osäkra tecken.</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verifierar block...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verifierar plånboken...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>Plånbok %s ligger utanför datakatalogen %s</translation> </message> <message> <source>Wallet debugging/testing options:</source> <translation>Plånbokens Avlusnings/Testnings optioner:</translation> </message> <message> <source>Wallet needed to be rewritten: restart %s to complete</source> <translation>Plånboken behöver sparas om: Starta om %s för att fullfölja</translation> </message> <message> <source>Wallet options:</source> <translation>Plånboksinställningar:</translation> </message> <message> <source>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> <translation>Tillåt JSON-RPC-anslutningar från specifik källa. Tillåtna &lt;ip&gt; är enkel IP (t.ex 1.2.3.4), en nätverk/nätmask (t.ex. 1.2.3.4/255.255.255.0) eller ett nätverk/CIDR (t.ex. 1.2.3.4/24). Detta alternativ anges flera gånger</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Bind till given adress och vitlista klienter som ansluter till den. Använd [värd]:port notation för IPv6</translation> </message> <message> <source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source> <translation>Bind till angiven adress för att lyssna på JSON-RPC-anslutningar. Använd [värd]:port-format for IPv6. Detta alternativ kan anges flera gånger (förvalt: bind till alla gränssnitt)</translation> </message> <message> <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> <translation>Skapa nya filer med systemets förvalda rättigheter, istället för umask 077 (bara effektivt med avaktiverad plånboks funktionalitet)</translation> </message> <message> <source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source> <translation>Upptäck egna IP adresser (standard: 1 vid lyssning ingen -externalip eller -proxy)</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Fel: Avlyssning av inkommande anslutningar misslyckades (Avlyssningen returnerade felkod %s)</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Exekvera kommando när ett relevant meddelande är mottagen eller när vi ser en väldigt lång förgrening (%s i cmd är utbytt med ett meddelande)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source> <translation>Avgifter (i %s/kB) mindre än detta betraktas som nollavgift för vidarebefordran, mining och transaktionsskapande (förvalt: %s)</translation> </message> <message> <source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source> <translation>Om paytxfee inte är satt, inkludera tillräcklig avgift så att transaktionen börjar att konfirmeras inom n blocks (förvalt: %u)</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation>Otillåtet belopp för -maxtxfee=&lt;belopp&gt;: '%s' (måste åtminstånde vara minrelay avgift %s för att förhindra stoppade transkationer)</translation> </message> <message> <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> <translation>Maximal storlek på data i databärartransaktioner som vi reläar och bryter (förvalt: %u) </translation> </message> <message> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation>Sök efter klientadresser med DNS sökningen, om det finns otillräckligt med adresser (förvalt: 1 om inte -connect)</translation> </message> <message> <source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source> <translation>Slumpa autentiseringen för varje proxyanslutning. Detta möjliggör Tor ström-isolering (förvalt: %u)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Sätt den maximala storleken av hög-prioriterade/låg-avgifts transaktioner i byte (förvalt: %d)</translation> </message> <message> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation>Transaktionen är för liten att skicka efter det att avgiften har dragits</translation> </message> <message> <source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit &lt;https://www.openssl.org/&gt; and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source> <translation>Denna produkten innehåller mjukvara utvecklad av OpenSSL Project för användning i OpenSSL Toolkit &lt;https://www.openssl.org/&gt; och kryptografisk mjukvara utvecklad av Eric Young samt UPnP-mjukvara skriven av Thomas Bernard.</translation> </message> <message> <source>Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start</source> <translation>Använd hierarkisk deterministisk nyckel generering (HD) efter BIP32. Har bara effekt under plånbokens skapande/första användning.</translation> </message> <message> <source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source> <translation>Vitlistade klienter kan inte bli DoS-bannade och deras transaktioner reläas alltid, även om dom redan är i mempoolen, användbart för t.ex en gateway </translation> </message> <message> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation>Du måste bygga om databasen genom att använda -reindex för att återgå till obeskärt läge. Detta kommer att ladda ner hela blockkedjan.</translation> </message> <message> <source>(default: %u)</source> <translation>(förvalt: %u)</translation> </message> <message> <source>Accept public REST requests (default: %u)</source> <translation>Acceptera publika REST förfrågningar (förvalt: %u)</translation> </message> <message> <source>Automatically create Tor hidden service (default: %d)</source> <translation>Skapa automatiskt dold tjänst i Tor (förval: %d)</translation> </message> <message> <source>Connect through SOCKS5 proxy</source> <translation>Anslut genom SOCKS5 proxy</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Fel vid läsning från databas, avslutar.</translation> </message> <message> <source>Imports blocks from external blk000??.dat file on startup</source> <translation>Importera block från extern blk000??.dat-fil vid uppstart</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Ogiltigt belopp för -paytxfee=&lt;belopp&gt;:'%s' (måste vara minst %s)</translation> </message> <message> <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Ogiltig nätmask angiven i -whitelist: '%s'</translation> </message> <message> <source>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</source> <translation>Håll som mest &lt;n&gt; oanslutningsbara transaktioner i minnet (förvalt: %u)</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>Port måste anges med -whitelist: '%s'</translation> </message> <message> <source>Node relay options:</source> <translation>Nodreläalternativ:</translation> </message> <message> <source>RPC server options:</source> <translation>RPC-serveralternativ:</translation> </message> <message> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation>Minskar -maxconnections från %d till %d, på grund av systembegränsningar.</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions on startup</source> <translation>Sök i blockkedjan efter saknade plånbokstransaktioner vid uppstart</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Skicka trace-/debuginformation till terminalen istället för till debug.log</translation> </message> <message> <source>Send transactions as zero-fee transactions if possible (default: %u)</source> <translation>Sänd transaktioner som nollavgiftstransaktioner om möjligt (förvalt: %u)</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Visa alla avlusningsalternativ (använd: --help -help-debug)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Krymp debug.log filen vid klient start (förvalt: 1 vid ingen -debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Signering av transaktion misslyckades</translation> </message> <message> <source>The transaction amount is too small to pay the fee</source> <translation>Transaktionen är för liten för att betala avgiften</translation> </message> <message> <source>This is experimental software.</source> <translation>Detta är experimentmjukvara.</translation> </message> <message> <source>Tor control port password (default: empty)</source> <translation>Lösenord för Tor-kontrollport (förval: inget)</translation> </message> <message> <source>Tor control port to use if onion listening enabled (default: %s)</source> <translation>Tor-kontrollport att använda om onion är aktiverat (förval: %s)</translation> </message> <message> <source>Transaction amount too small</source> <translation>Transaktions belopp för liten</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Transaktionens belopp måste vara positiva</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>Transaktionen är för stor för avgiftspolicyn</translation> </message> <message> <source>Transaction too large</source> <translation>Transaktionen är för stor</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>Det går inte att binda till %s på den här datorn (bind returnerade felmeddelande %s)</translation> </message> <message> <source>Updating an offer with a cert that does not exist</source> <translation>Uppdatering ett erbjudande med en cert som inte finns</translation> </message> <message> <source>Upgrade wallet to latest format on startup</source> <translation>Uppgradera plånbok till senaste formatet vid uppstart</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Användarnamn för JSON-RPC-anslutningar</translation> </message> <message> <source>Warning</source> <translation>Varning</translation> </message> <message> <source>Warning: unknown new rules activated (versionbit %i)</source> <translation>Varning: okända nya regler aktiverade (versionsbit %i)</translation> </message> <message> <source>Whether to operate in a blocks only mode (default: %u)</source> <translation>Ska allt göras i endast block-läge (förval: %u)</translation> </message> <message> <source>Whitelist entries were added or removed</source> <translation>Vitlista poster till eller tas bort</translation> </message> <message> <source>Whitelist is already empty</source> <translation>Vitlista är redan tom</translation> </message> <message> <source>Whitelist was cleared</source> <translation>Vitlista rensades</translation> </message> <message> <source>Wrong alias input provided in this certificate transaction</source> <translation>Fel alias ingång i detta intyg transaktion</translation> </message> <message> <source>You are not the owner of this alias</source> <translation>Du är inte ägaren av detta alias</translation> </message> <message> <source>You must own the arbiter alias to complete this transaction</source> <translation>Du måste äga Arbiter alias för att slutföra denna transaktion</translation> </message> <message> <source>You must own the buyer alias to complete this transaction</source> <translation>Du måste äga köparen alias för att slutföra denna transaktion</translation> </message> <message> <source>You must own the reseller alias to complete this transaction</source> <translation>Du måste äga återförsäljare alias för att slutföra denna transaktion</translation> </message> <message> <source>You must own the seller alias to complete this transaction</source> <translation>Du måste äga säljaren alias för att slutföra denna transaktion</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Töm plånboken på alla transaktioner...</translation> </message> <message> <source>ZeroMQ notification options:</source> <translation>ZeroMQ-alternativ för notiser:</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Lösenord för JSON-RPC-anslutningar</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Exekvera kommando när det bästa blocket ändras (%s i cmd är utbytt av blockhash)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillåt DNS-sökningar för -addnode, -seednode och -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Laddar adresser...</translation> </message> <message> <source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source> <translation>(1 = spara tx metadata t.ex. kontoägare och betalningsbegäransinformation, 2 = släng tx metadata)</translation> </message> <message> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>-maxtxfee är väldigt högt satt! Så höga avgifter kan komma att betalas för en enstaka transaktion.</translation> </message> <message> <source>-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>-paytxfee är väldigt högt satt! Det här är avgiften du kommer betala om du skickar en transaktion.</translation> </message> <message> <source>Alias multisig too big, reduce the number of signatures required for this alias and try again</source> <translation>Alias ​​multisig alltför stor, minska antalet underskrifter som krävs för detta alias och försök igen</translation> </message> <message> <source>Cannot create this offer because the certificate alias does not match the offer alias</source> <translation>Det går inte att skapa detta erbjudande eftersom certifikatet alias inte matchar erbjudande alias</translation> </message> <message> <source>Cannot find the alias you are trying to offer affiliate list. It may be expired</source> <translation>Det går inte att hitta det alias du försöker erbjuda affiliate listan. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot purchase this linked offer because the certificate has been transferred or it is linked to another offer</source> <translation>Det går inte att köpa denna kombinationserbjudande eftersom certifikatet har överförts eller det är kopplat till ett annat erbjudande</translation> </message> <message> <source>Cannot purchase this offer because the certificate has been transferred or it is linked to another offer</source> <translation>Det går inte att köpa detta erbjudande eftersom certifikatet har överförts eller det är kopplat till ett annat erbjudande</translation> </message> <message> <source>Cannot unserialize data inside of this transaction relating to a certificate</source> <translation>Kan inte unserialize uppgifter insidan av denna transaktion om ett certifikat</translation> </message> <message> <source>Cannot unserialize data inside of this transaction relating to a message</source> <translation>Kan inte unserialize uppgifter insidan av denna transaktion om ett meddelande</translation> </message> <message> <source>Cannot unserialize data inside of this transaction relating to an escrow</source> <translation>Kan inte unserialize data i denna transaktion som avser ett spärrat</translation> </message> <message> <source>Cannot update multisig alias because required signatures is greator than the amount of signatures provided</source> <translation>Kan inte uppdatera multisig alias eftersom krävs underskrifter är greator än mängden underskrifter tillhandahålls</translation> </message> <message> <source>Cannot update this offer because the certificate alias does not match the linked offer alias</source> <translation>Kan inte uppdatera detta erbjudande eftersom certifikatet alias inte matchar kombinationserbjudande alias</translation> </message> <message> <source>Cannot update this offer because the certificate alias does not match the offer alias</source> <translation>Kan inte uppdatera detta erbjudande eftersom certifikatet alias inte matchar erbjudande alias</translation> </message> <message> <source>Could not create escrow transaction: Invalid response from createrawtransaction</source> <translation>Det gick inte att skapa spärrade transaktion: Ogiltigt svar från createrawtransaction</translation> </message> <message> <source>Could not create escrow transaction: could not find redeem script in response</source> <translation>Det gick inte att skapa spärrade transaktion: kunde inte hitta lösa skript som svar</translation> </message> <message> <source>Could not decode escrow transaction: Invalid response from decoderawtransaction</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltigt svar från decoderawtransaction</translation> </message> <message> <source>Could not decode escrow transaction: One or more of the multisig addresses do not refer to an alias</source> <translation>Det gick inte att avkoda spärrade transaktionen: En eller flera av de multisig adresser inte hänvisa till ett alias</translation> </message> <message> <source>Could not generate escrow multisig address: Invalid response from generateescrowmultisig</source> <translation>Det gick inte att generera spärrade multisig adress: Ogiltigt svar från generateescrowmultisig</translation> </message> <message> <source>Could not send raw transaction: Invalid response from sendrawtransaction</source> <translation>Det gick inte att skicka rå transaktion: Ogiltigt svar från sendrawtransaction</translation> </message> <message> <source>Could not sign escrow transaction: Invalid response from signrawtransaction</source> <translation>Det gick inte att logga spärrade transaktion: Ogiltigt svar från signrawtransaction</translation> </message> <message> <source>Could not sign multisig transaction: Invalid response from signrawtransaction</source> <translation>Det gick inte att logga multisig transaktion: Ogiltigt svar från signrawtransaction</translation> </message> <message> <source>Do not keep transactions in the mempool longer than &lt;n&gt; hours (default: %u)</source> <translation>Håll inte transaktioner i minnespoolen längre än &lt;n&gt; timmar (förvalt: %u)</translation> </message> <message> <source>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</source> <translation>Motsvarande byte per sigop i transaktioner för relä och utvinning (standard: %u)</translation> </message> <message> <source>Expected amount of escrow does not match what is held in escrow. Expected amount: </source> <translation>Förväntade mängden spärrade matchar inte vad hålls i depositionsavtal. Förväntade mängden:</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source> <translation>Avgifter (i %s/kB) mindre än detta anses vara nollavgifter vid skapande av transaktion (standard: %s)</translation> </message> <message> <source>Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)</source> <translation>Kraft relä transaktioner från vitlistade kamrater, även om de bryter mot lokala reläpolitik (standard: %d)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> <translation>Hur grundlig blockverifikationen vid -checkblocks är (0-4, förvalt: %u)</translation> </message> <message> <source>Invalid Presidentielcoin Identity. Must follow the domain name spec of 3 to 64 characters with no preceding or trailing dashes and a TLD of 2 to 6 characters</source> <translation>Ogiltig Presidentielcoin identitet. Måste följa domännamnet spec 3 till 64 tecken utan föregående eller efterföljande streck och en toppdomän på 2 till 6 tecken</translation> </message> <message> <source>Invalid Presidentielcoin Identity. Must follow the domain name spec of 3 to 64 characters with no preceding or trailing dashes</source> <translation>Ogiltig Presidentielcoin identitet. Måste följa domännamnet spec 3 till 64 tecken utan föregående eller efterföljande streck</translation> </message> <message> <source>Invalid Presidentielcoin Identity. Please enter a password atleast 4 characters long</source> <translation>Ogiltig Presidentielcoin identitet. Ange ett lösenord minst 4 tecken långt</translation> </message> <message> <source>Invalid price and/or quantity values. Quantity must be less than 4294967296 and greater than or equal to -1</source> <translation>Ogiltig pris- och / eller kvantitetsvärden. Kvantitet måste vara mindre än 4294967296 och större än eller lika med -1</translation> </message> <message> <source>Invalid quantity value, must be less than 4294967296 and greater than or equal to -1</source> <translation>Ogiltigt storhetsvärde, måste vara mindre än 4294967296 och större än eller lika med -1</translation> </message> <message> <source>Invalid rating value, must be less than or equal to 5 and greater than or equal to 0</source> <translation>Ogiltigt rating värde, måste vara mindre än eller lika med 5 och större än eller lika med 0</translation> </message> <message> <source>Invalid rating, must be less than or equal to 5 and greater than or equal to 0</source> <translation>Ogiltig rating, måste vara mindre än eller lika med 5 och större än eller lika med 0</translation> </message> <message> <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> <translation>Upprätthåll ett fullständigt transaktionsindex, som används av getrawtransaction rpc-anrop (förval: %u)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> <translation>Antal sekunder att hindra klienter som missköter sig från att ansluta (förvalt: %u)</translation> </message> <message> <source>Offer guid in the data output does not match the guid in the transaction</source> <translation>Erbjudandet guid i utdata matchar inte guid i transaktionen</translation> </message> <message> <source>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</source> <translation>Skriv ut avlusningsinformation (förvalt: %u, att ange &lt;category&gt; är frivilligt)</translation> </message> <message> <source>Support filtering of blocks and transaction with bloom filters (default: %u)</source> <translation>Stöd filtrering av block och transaktioner med bloomfilter (standard: %u)</translation> </message> <message> <source>Presidentielcoin is open source software produced by a global network of developers. By downloading, distributing and using Presidentielcoin and the Presidentielcoin network you release the developers involved in the Presidentielcoin Project past, present, and future from any and all liability. You are responsible for your creations on the Presidentielcoin network. You agree that the developers of the Presidentielcoin Project carry no responsibility for the actions/data or entities of *any* definition created on the network by yourself or others on the network to which you may be exposed.</source> <translation>Presidentielcoin är öppen källkod som produceras av ett globalt nätverk av utvecklare. Genom att ladda ner, distribuera och använda Presidentielcoin och Presidentielcoin nätverk du släpper utvecklarna involverade i Presidentielcoin Project dåtid, nutid och framtid från allt ansvar. Du är ansvarig för dina skapelser på Presidentielcoin nätverket. Du samtycker till att utvecklarna av Presidentielcoin Project bär inget ansvar för de åtgärder / data eller enheter * alla * definition skapas på nätet själv eller andra på nätet som du kan utsättas för.</translation> </message> <message> <source>The Presidentielcoin alias you are trying to use for this transaction is invalid or has been updated and not confirmed yet! Please wait a block and try again...</source> <translation>Den Presidentielcoin alias du försöker använda för den här transaktionen är ogiltig eller har uppdaterats och inte bekräftat ännu! Vänta ett block och försök igen ...</translation> </message> <message> <source>The developers of the Presidentielcoin Project do not have the power to modify data on the Presidentielcoin network, it is backed by an immutable blockchain, which you further acknowledge through use of Presidentielcoin, the Presidentielcoin network, and Presidentielcoin services. If you do not agree to these terms, please refrain from using Presidentielcoin and its related services.</source> <translation>Utvecklarna av Presidentielcoin Project har inte befogenhet att ändra data på Presidentielcoin nätverket, är det backas upp av en oföränderlig blockchain, som du ytterligare bekräfta genom att använda Presidentielcoin, den Presidentielcoin nätverket och Presidentielcoin tjänster. Om du inte accepterar dessa villkor, vänligen avstå från att använda Presidentielcoin och dess relaterade tjänster.</translation> </message> <message> <source>This resold offer must be of higher price than the original offer including any discount</source> <translation>Detta säljs vidare erbjudande måste vara högre pris än det ursprungliga erbjudandet inklusive rabatt</translation> </message> <message> <source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source> <translation>Total längd på strängen för nätverksversion (%i) överskrider maxlängden (%i). Minska numret eller storleken på uacomments.</translation> </message> <message> <source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source> <translation>Försöker hålla utgående trafik under givet mål (i MiB per 24 timmar), 0 = ingen gräns (förvalt: %d)</translation> </message> <message> <source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation>Argumentet -socks hittades och stöds inte. Det är inte längre möjligt att sätta SOCKS-version längre, bara SOCKS5-proxy stöds.</translation> </message> <message> <source>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</source> <translation>Argumentet -whitelistalwaysrelay stöds inte utan ignoreras, använd -whitelistrelay och/eller -whitelistforcerelay.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> <translation>Använd separat SOCKS5 proxy för att nå kollegor via dolda tjänster i Tor (förvalt: -%s)</translation> </message> <message> <source>User selected payment option not found in list of accepted offer payment options</source> <translation>Användaren väljer betalningsalternativ som inte finns i listan över godkända erbjuda betalningsalternativ</translation> </message> <message> <source>Username and hashed password for JSON-RPC connections. The field &lt;userpw&gt; comes in the format: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. A canonical python script is included in share/rpcuser. This option can be specified multiple times</source> <translation>Användarnamn och hashat lösenord för JSON-RPC-anslutningar. Fältet &lt;userpw&gt; kommer i formatet: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. Ett kanoniskt pythonskript finns inkluderat i share/rpcuser. Detta alternativ kan anges flera gånger</translation> </message> <message> <source>Warning: This transaction sends coins to an address or alias you do not own</source> <translation>Varning: Denna transaktion sänder mynt till en adress eller alias som du inte äger</translation> </message> <message> <source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source> <translation>Varning: Okända blockversioner bryts! Det är möjligt att okända regler används</translation> </message> <message> <source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Varning: Plånboksfilen var korrupt, datat har räddats! Den ursprungliga %s har sparas som %s i %s. Om ditt saldo eller transaktioner är felaktiga bör du återställa från en säkerhetskopia.</translation> </message> <message> <source>You must be either the arbiter, buyer or seller to leave feedback on this escrow</source> <translation>Du måste vara antingen domaren, köpare eller säljare att lämna feedback på den här depositions</translation> </message> <message> <source>You must be either the buyer or seller to leave feedback on this offer purchase</source> <translation>Du måste vara antingen köparen eller säljaren att lämna synpunkter på detta erbjudande köp</translation> </message> <message> <source>(default: %s)</source> <translation>(förvalt: %s)</translation> </message> <message> <source>&lt;No Difference Detected&gt;</source> <translation>&lt;Ingen skillnad upptäckt&gt;</translation> </message> <message> <source>Alias Guid input mismatch</source> <translation>Alias ​​Guid ingångsobalans</translation> </message> <message> <source>Alias address does not refer to a key</source> <translation>Aliasadress refererar inte till en nyckel</translation> </message> <message> <source>Alias arguments incorrect size</source> <translation>Alias ​​argument felaktig storlek</translation> </message> <message> <source>Alias input guid mismatch</source> <translation>Alias ​​ingångs guid mismatch</translation> </message> <message> <source>Alias input mismatch</source> <translation>Aliasingångsobalans</translation> </message> <message> <source>Alias input to this transaction not found</source> <translation>Alias ​​bidrag till denna transaktion inte hittas</translation> </message> <message> <source>Alias name does not follow the domain name specification</source> <translation>Alias ​​följer inte domännamnet specifikation</translation> </message> <message> <source>Alias not found when trying to update</source> <translation>Alias ​​hittades inte när man försöker uppdatera</translation> </message> <message> <source>Alias not provided as input</source> <translation>Alias ​​inte som indata</translation> </message> <message> <source>Alias password too long</source> <translation>Alias ​​lösenord för lång</translation> </message> <message> <source>Alias peg too long</source> <translation>Alias ​​peg för lång</translation> </message> <message> <source>Alias private value too big</source> <translation>Alias ​​privat värde för stort</translation> </message> <message> <source>Alias public value too big</source> <translation>Alias ​​offentligt värde för stort</translation> </message> <message> <source>Alias transaction has unknown op</source> <translation>Alias ​​transaktionen har okänd op</translation> </message> <message> <source>Always query for peer addresses via DNS lookup (default: %u)</source> <translation>Sök alltid efter klientadresser med DNS sökningen (förvalt: %u)</translation> </message> <message> <source>An alias already exists with that address, try another public key</source> <translation>Ett alias finns redan med den adressen, prova en annan publik nyckel</translation> </message> <message> <source>BTC Transaction ID specified was already used to pay for an offer</source> <translation>BTC transaktions-ID anges redan används för att betala för en offert</translation> </message> <message> <source>Bad alias height</source> <translation>Dålig alias höjd</translation> </message> <message> <source>Buyer address does not refer to a key</source> <translation>Köparen adress refererar inte till en nyckel</translation> </message> <message> <source>Buyer alias is not in your wallet</source> <translation>Köparen alias är inte i din plånbok</translation> </message> <message> <source>Can only claim a refunded escrow</source> <translation>Kan bara göra anspråk på en återbetalas depositions</translation> </message> <message> <source>Can only claim a released escrow</source> <translation>Kan bara göra anspråk på en släppt spärrade</translation> </message> <message> <source>Can only refund an active escrow</source> <translation>Kan bara återbetala en aktiv spärrat</translation> </message> <message> <source>Can only release an active escrow</source> <translation>Kan bara släppa en aktiv spärrat</translation> </message> <message> <source>Can't determine type of alias input into presidentielcoin service transaction</source> <translation>Det går inte att avgöra typ av alias bidrag till presidentielcoin tjänstetransaktion</translation> </message> <message> <source>Cannot change category to wanted</source> <translation>Det går inte att ändra kategori till önskad</translation> </message> <message> <source>Cannot edit or transfer this certificate. It is view-only.</source> <translation>Det går inte att redigera eller överföra detta certifikat. Det är skrivskyddad.</translation> </message> <message> <source>Cannot edit this alias, guid mismatch</source> <translation>Det går inte att ändra detta alias, guid mismatch</translation> </message> <message> <source>Cannot exceed 10 arbiter feedbacks</source> <translation>Får inte överstiga 10 skiljedomare kopplingar</translation> </message> <message> <source>Cannot exceed 10 buyer feedbacks</source> <translation>Får inte överstiga 10 köparen återkopplingar</translation> </message> <message> <source>Cannot exceed 10 seller feedbacks</source> <translation>Får inte överstiga 10 säljare kopplingar</translation> </message> <message> <source>Cannot extract destination from output script</source> <translation>Det går inte att extrahera destination från utgångs script</translation> </message> <message> <source>Cannot extract destination of alias input</source> <translation>Det går inte att extrahera destination alias ingång</translation> </message> <message> <source>Cannot find alias for the recipient of this message. It may be expired</source> <translation>Kan inte hitta alias för mottagaren av detta meddelande. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find alias for the sender of this message. It may be expired</source> <translation>Kan inte hitta alias för avsändaren av brevet. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find alias for this certificate. It may be expired</source> <translation>Kan inte hitta alias för detta certifikat. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find alias for this linked offer. It may be expired</source> <translation>Kan inte hitta alias för detta kombinationserbjudande. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find alias for this offer. It may be expired</source> <translation>Kan inte hitta alias för detta erbjudande. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find alias you are transfering to. It may be expired</source> <translation>Det går inte att hitta alias du överföra till. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find arbiter alias. It may be expired</source> <translation>Det går inte att hitta domaren alias. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find buyer alias. It may be expired</source> <translation>Det går inte att hitta köpare alias. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find linked offer for this escrow</source> <translation>Kan inte hitta kombinationserbjudande för denna spärrade</translation> </message> <message> <source>Cannot find offer for this escrow. It may be expired</source> <translation>Kan inte hitta bud på detta spärrade. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find seller alias. It may be expired</source> <translation>Det går inte att hitta säljare alias. Det kan ha upphört att gälla</translation> </message> <message> <source>Cannot find this alias in the parent offer affiliate list</source> <translation>Det går inte att hitta detta alias i moder erbjudandet affiliate lista</translation> </message> <message> <source>Cannot have accept information on offer activation</source> <translation>Det går inte att ha acceptera information om erbjudandet aktivering</translation> </message> <message> <source>Cannot have accept information on offer update</source> <translation>Det går inte att ha acceptera information om erbjudandet uppdatering</translation> </message> <message> <source>Cannot leave empty feedback</source> <translation>Det går inte att lämna tomt återkoppling</translation> </message> <message> <source>Cannot leave feedback in escrow activation</source> <translation>Det går inte att lämna feedback i depositions aktivering</translation> </message> <message> <source>Cannot leave feedback in escrow refund</source> <translation>Det går inte att lämna feedback i deposition återbetalning</translation> </message> <message> <source>Cannot leave feedback in escrow release</source> <translation>Det går inte att lämna feedback i depositions frisättning</translation> </message> <message> <source>Cannot link to a wanted offer</source> <translation>Det går inte att länka till en önskad erbjudande</translation> </message> <message> <source>Cannot link to an offer that is already linked to another offer</source> <translation>Det går inte att länka till ett erbjudande som redan är kopplad till ett annat erbjudande</translation> </message> <message> <source>Cannot only leave one feedback per transaction</source> <translation>Kan inte bara lämna en återkoppling per transaktion</translation> </message> <message> <source>Cannot purchase a wanted offer</source> <translation>Det går inte att köpa en önskad erbjudande</translation> </message> <message> <source>Cannot purchase certificates with Bitcoins</source> <translation>Det går inte att köpa certifikat med Bitcoins</translation> </message> <message> <source>Cannot purchase this private offer, must purchase through an affiliate</source> <translation>Det går inte att köpa denna privata erbjudande måste köpa via en affiliate</translation> </message> <message> <source>Cannot read payments from alias DB</source> <translation>Kan inte läsa betalningar från alias DB</translation> </message> <message> <source>Cannot refund an escrow that is already released</source> <translation>Det går inte att återbetala en depositions som redan är släppt</translation> </message> <message> <source>Cannot release an escrow that is already refunded</source> <translation>Det går inte att släppa en depositions som redan återbetalas</translation> </message> <message> <source>Cannot sell an expired certificate</source> <translation>Det går inte att sälja ett utgånget certifikat</translation> </message> <message> <source>Cannot send yourself feedback</source> <translation>Det går inte att skicka dig återkoppling</translation> </message> <message> <source>Cannot unserialize data inside of this transaction relating to an offer</source> <translation>Kan inte unserialize data i denna transaktion som avser ett erbjudande</translation> </message> <message> <source>Certificate already exists</source> <translation>Certifikat finns redan</translation> </message> <message> <source>Certificate arguments incorrect size</source> <translation>Certifikat argument felaktig storlek</translation> </message> <message> <source>Certificate category too big</source> <translation>Certifikat kategori för stort</translation> </message> <message> <source>Certificate data too big</source> <translation>Certifikatdata för stor</translation> </message> <message> <source>Certificate guid mismatch</source> <translation>guid mismatch certifikat</translation> </message> <message> <source>Certificate hex guid too long</source> <translation>Certifikat hex guid för lång</translation> </message> <message> <source>Certificate linked alias not allowed in activate</source> <translation>Certifikat kopplade alias som inte är tillåtna i aktivera</translation> </message> <message> <source>Certificate title too big or is empty</source> <translation>Certifikat titel för stor eller är tom</translation> </message> <message> <source>Certificate title too big</source> <translation>Certifikat titel för stor</translation> </message> <message> <source>Certificate transaction has unknown op</source> <translation>Certifikat transaktionen har okänd op</translation> </message> <message> <source>Commission destination does not match affiliate address</source> <translation>Kommissionens destination matchar inte affiliate-adress</translation> </message> <message> <source>Commission must between -90 and 100</source> <translation>Kommissionen måste mellan -90 och 100</translation> </message> <message> <source>Copyright (C) 2009-%i The Presidentielcoin Core Developers</source> <translation>Copyright (C) 2009-%i Presidentielcoin Core Utvecklarna</translation> </message> <message> <source>Could not create escrow transaction: Invalid response from createescrow</source> <translation>Det gick inte att skapa spärrade transaktion: Ogiltigt svar från createescrow</translation> </message> <message> <source>Could not decode escrow transaction: Cannot find VOUT from transaction</source> <translation>Det gick inte att avkoda spärrade transaktion: Kan inte hitta VOUT från transaktions</translation> </message> <message> <source>Could not decode escrow transaction: Invalid VOUT value</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltigt VOUT värde</translation> </message> <message> <source>Could not decode escrow transaction: Invalid address</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltig adress</translation> </message> <message> <source>Could not decode escrow transaction: Invalid addresses</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltiga adresser</translation> </message> <message> <source>Could not decode escrow transaction: Invalid number of signatures</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltigt antal underskrifter</translation> </message> <message> <source>Could not decode escrow transaction: Invalid scriptPubKey value</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltigt scriptPubKey värde</translation> </message> <message> <source>Could not decode escrow transaction: Invalid type</source> <translation>Det gick inte att avkoda spärrade transaktion: Ogiltig typ</translation> </message> <message> <source>Could not decode external payment transaction</source> <translation>Det gick inte att avkoda externa betalningstransaktion</translation> </message> <message> <source>Could not decode transaction</source> <translation>Det gick inte att avkoda transaktion</translation> </message> <message> <source>Could not decrypt certificate data</source> <translation>Det gick inte att dekryptera certifikatdata</translation> </message> <message> <source>Could not determine key from password</source> <translation>Det gick inte att avgöra nyckeln från lösenord</translation> </message> <message> <source>Could not encrypt alias password</source> <translation>Det gick inte att kryptera alias lösenord</translation> </message> <message> <source>Could not encrypt alias private data</source> <translation>Det gick inte att kryptera alias privata uppgifter</translation> </message> <message> <source>Could not encrypt certificate data</source> <translation>Det gick inte att kryptera data certifikat</translation> </message> <message> <source>Could not encrypt message data for receiver</source> <translation>Det gick inte att kryptera data meddelande till mottagaren</translation> </message> <message> <source>Could not encrypt message data for sender</source> <translation>Det gick inte att kryptera data meddelande till avsändaren</translation> </message> <message> <source>Could not encrypt message to seller</source> <translation>Det gick inte att kryptera meddelande till säljaren</translation> </message> <message> <source>Could not encrypt private alias value!</source> <translation>Det gick inte att kryptera privata alias värde!</translation> </message> <message> <source>Could not extract commission destination from scriptPubKey</source> <translation>Det gick inte att extrahera provision destination från scriptPubKey</translation> </message> <message> <source>Could not extract payment destination from scriptPubKey</source> <translation>Det gick inte att extrahera betalning destination från scriptPubKey</translation> </message> <message> <source>Could not find a certificate with this key</source> <translation>Det gick inte att hitta ett certifikat med denna nyckel</translation> </message> <message> <source>Could not find a escrow with this key</source> <translation>Det gick inte att hitta en depositions med denna nyckel</translation> </message> <message> <source>Could not find a linked offer with this guid</source> <translation>Det gick inte att hitta ett kombinationserbjudande med denna guid</translation> </message> <message> <source>Could not find an alias with this guid</source> <translation>Det gick inte att hitta ett alias med denna guid</translation> </message> <message> <source>Could not find an alias with this identifier</source> <translation>Det gick inte att hitta ett alias med denna identifierare</translation> </message> <message> <source>Could not find an alias with this name</source> <translation>Det gick inte att hitta ett alias med detta namn</translation> </message> <message> <source>Could not find an offer with this guid</source> <translation>Det gick inte att hitta ett erbjudande med denna guid</translation> </message> <message> <source>Could not find an offer with this identifier</source> <translation>Det gick inte att hitta ett erbjudande med denna identifierare</translation> </message> <message> <source>Could not find buyer alias with this name</source> <translation>Det gick inte att hitta köpare alias med detta namn</translation> </message> <message> <source>Could not find currency in the peg alias</source> <translation>Det gick inte att hitta valuta i PEG alias</translation> </message> <message> <source>Could not find multisig alias with the name: </source> <translation>Kunde inte hitta multisig alias med namnet:</translation> </message> <message> <source>Could not find offer accept from mempool or disk</source> <translation>Kunde inte hitta erbjudandet acceptera från mempool eller disk</translation> </message> <message> <source>Could not find seller alias with this identifier</source> <translation>Det gick inte att hitta säljare alias med denna identifierare</translation> </message> <message> <source>Could not find the alias associated with this offer</source> <translation>Kunde inte hitta alias i samband med detta erbjudande</translation> </message> <message> <source>Could not find the certificate alias</source> <translation>Det gick inte att hitta certifikat alias</translation> </message> <message> <source>Could not find this alias</source> <translation>Det gick inte att hitta detta alias</translation> </message> <message> <source>Could not find this escrow</source> <translation>Det gick inte att hitta denna depositions</translation> </message> <message> <source>Could not find this message</source> <translation>Kunde inte hitta meddelandet</translation> </message> <message> <source>Could not find this offer purchase</source> <translation>Det gick inte att hitta detta erbjudande köp</translation> </message> <message> <source>Could not find this offer</source> <translation>Kunde inte hitta detta erbjudande</translation> </message> <message> <source>Could not get linked offer</source> <translation>Det gick inte att få kombinationserbjudande</translation> </message> <message> <source>Could not sign escrow transaction: Signature not added to transaction</source> <translation>Det gick inte att logga spärrade transaktion: Signatur inte lagt till transaktion</translation> </message> <message> <source>Could not sign multisig transaction: </source> <translation>Det gick inte att logga multisig transaktion:</translation> </message> <message> <source>Could not validate payment options string</source> <translation>Det gick inte att validera betalningsalternativ sträng</translation> </message> <message> <source>Could not validate the payment options value</source> <translation>Det gick inte att validera betalningsalternativ värde</translation> </message> <message> <source>Creating an offer with a cert that does not exist</source> <translation>Skapa ett erbjudande med en cert som inte finns</translation> </message> <message> <source>Discount must be between 0 and 99</source> <translation>Rabatt måste vara mellan 0 och 99</translation> </message> <message> <source>Encrypted for alias owner</source> <translation>Krypteras för alias ägare</translation> </message> <message> <source>Encrypted for owner of certificate private data</source> <translation>Krypteras för ägare av certifikat privata data</translation> </message> <message> <source>Encrypted for owner of offer</source> <translation>Krypteras för ägare av erbjudande</translation> </message> <message> <source>Encrypted for recipient of message</source> <translation>Krypteras för mottagaren av meddelandet</translation> </message> <message> <source>Escrow Guid mismatch</source> <translation>Depositions Guid mismatch</translation> </message> <message> <source>Escrow already acknowledged</source> <translation>Spärrade redan erkänt</translation> </message> <message> <source>Escrow already exists</source> <translation>Escrow redan existerar</translation> </message> <message> <source>Escrow arguments incorrect size</source> <translation>Spärrade argument fel storlek</translation> </message> <message> <source>Escrow feedback was given</source> <translation>Spärrade återkoppling gavs</translation> </message> <message> <source>Escrow guid in data output doesn't match guid in transaction</source> <translation>Depositions guid i datautgång inte matchar guid i transaktionen</translation> </message> <message> <source>Escrow guid too big</source> <translation>Depositions guid för stor</translation> </message> <message> <source>Escrow is incomplete</source> <translation>Escrow är ofullständig</translation> </message> <message> <source>Escrow not found when trying to update</source> <translation>Spärrade hittades inte när man försöker uppdatera</translation> </message> <message> <source>Escrow offer guid too long</source> <translation>Depositions erbjudande guid för lång</translation> </message> <message> <source>Escrow redeem script too long</source> <translation>Spärrade lösa skript för lång</translation> </message> <message> <source>Escrow refund status too large</source> <translation>Escrow återbetalning status för stor</translation> </message> <message> <source>Escrow release status too large</source> <translation>Escrow frigör status för stor</translation> </message> <message> <source>Escrow transaction has unknown op</source> <translation>Spärrade transaktionen har okänd op</translation> </message> <message> <source>Expected commission to affiliate not found in escrow</source> <translation>Förväntad provision till affiliate hittades inte i depositions</translation> </message> <message> <source>Expected fee payment to arbiter or buyer not found in escrow</source> <translation>Förväntad avgift betalning till domaren eller köpare hittades inte i depositions</translation> </message> <message> <source>Expected payment amount not found in escrow</source> <translation>Förväntad betalningsbelopp som inte finns i depositions</translation> </message> <message> <source>Expected refund amount not found</source> <translation>Förväntad bidragsbelopp hittades inte</translation> </message> <message> <source>Expiration must be within 1 to 5 years</source> <translation>Utandning måste vara inom ett till fem år</translation> </message> <message> <source>External Transaction ID specified was already used to pay for an offer</source> <translation>Extern transaktions-ID anges redan används för att betala för en offert</translation> </message> <message> <source>External chain payment cannot be made with this offer</source> <translation>Extern kedja betalning kan inte göras med detta erbjudande</translation> </message> <message> <source>External chain payment txid missing</source> <translation>Extern kedja betalning TXID saknas</translation> </message> <message> <source>External payment cannot be paid with PRC</source> <translation>Extern betalning kan inte betalas med PRC</translation> </message> <message> <source>External payment missing transaction ID</source> <translation>Extern betalning saknas transaktions-ID</translation> </message> <message> <source>Failed to BTC Transaction ID to DB</source> <translation>Det gick inte att BTC transaktions-ID till DB</translation> </message> <message> <source>Failed to External Transaction ID to DB</source> <translation>Det gick inte att extern transaktion ID DB</translation> </message> <message> <source>Failed to find escrow transaction</source> <translation>Det gick inte att hitta spärrade transaktion</translation> </message> <message> <source>Failed to read alias from alias DB</source> <translation>Det gick inte att läsa alias från alias DB</translation> </message> <message> <source>Failed to read alias transaction</source> <translation>Det gick inte att läsa alias transaktion</translation> </message> <message> <source>Failed to read arbiter alias from DB</source> <translation>Det gick inte att läsa skiljedomare alias från DB</translation> </message> <message> <source>Failed to read from alias DB</source> <translation>Det gick inte att läsa från alias DB</translation> </message> <message> <source>Failed to read from cert DB</source> <translation>Det gick inte att läsa från cert DB</translation> </message> <message> <source>Failed to read from certificate DB</source> <translation>Det gick inte att läsa från certifikat DB</translation> </message> <message> <source>Failed to read from escrow DB</source> <translation>Det gick inte att läsa från spärrade DB</translation> </message> <message> <source>Failed to read from message DB</source> <translation>Det gick inte att läsa från meddelande DB</translation> </message> <message> <source>Failed to read from offer DB</source> <translation>Det gick inte att läsa från erbjudandet DB</translation> </message> <message> <source>Failed to read offer transaction from disk</source> <translation>Det gick inte att läsa erbjuda transaktion från disk</translation> </message> <message> <source>Failed to read to alias from alias DB</source> <translation>Det gick inte att läsa till alias från alias DB</translation> </message> <message> <source>Failed to read transaction from disk</source> <translation>Det gick inte att läsa transaktion från disk</translation> </message> <message> <source>Failed to read transfer alias from DB</source> <translation>Det gick inte att läsa överföring alias från DB</translation> </message> <message> <source>Failed to read xfer alias from alias DB</source> <translation>Det gick inte att läsa xfer alias från alias DB</translation> </message> <message> <source>Failed to write payment to alias DB</source> <translation>Det gick inte att skriva betalning till alias DB</translation> </message> <message> <source>Failed to write to alias DB</source> <translation>Det gick inte att skriva till alias DB</translation> </message> <message> <source>Failed to write to certifcate DB</source> <translation>Det gick inte att skriva till certifcate DB</translation> </message> <message> <source>Failed to write to escrow DB</source> <translation>Det gick inte att skriva till escrow DB</translation> </message> <message> <source>Failed to write to message DB</source> <translation>Det gick inte att skriva till meddelande DB</translation> </message> <message> <source>Failed to write to offer DB</source> <translation>Det gick inte att skriva att erbjuda DB</translation> </message> <message> <source>Failed to write to offer link to DB</source> <translation>Det gick inte att skriva att erbjuda länkar till DB</translation> </message> <message> <source>Failed to write to offer to DB</source> <translation>Det gick inte att skriva att erbjuda DB</translation> </message> <message> <source>Feedback must leave a message</source> <translation>Återkoppling måste lämna ett meddelande</translation> </message> <message> <source>Feedback too long</source> <translation>Återkoppling för lång</translation> </message> <message> <source>Generated public key not fully valid</source> <translation>Genererade publika nyckeln inte helt giltig</translation> </message> <message> <source>Guid in data output doesn't match guid in transaction</source> <translation>Guid i datautgång inte matchar guid i transaktionen</translation> </message> <message> <source>Guid in data output doesn't match guid in tx</source> <translation>Guid i datautgång inte matchar guid i tx</translation> </message> <message> <source>Guid mismatch</source> <translation>guid mismatch</translation> </message> <message> <source>Hash provided doesn't match the calculated hash of the data</source> <translation>Hash matchar inte den beräknade hash av data</translation> </message> <message> <source>How many blocks to check at startup (default: %u, 0 = all)</source> <translation>Hur många block att kontrollera vid uppstart (förvalt: %u, 0 = alla)</translation> </message> <message> <source>Include IP addresses in debug output (default: %u)</source> <translation>Inkludera IP-adresser i debugutskrift (förvalt: %u)</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Ogiltig -proxy adress: '%s'</translation> </message> <message> <source>Invalid aliases used for escrow transaction</source> <translation>Ogiltiga alias används för spärrade transaktion</translation> </message> <message> <source>Invalid feedback transaction</source> <translation>Ogiltig återkopplingstransaktion</translation> </message> <message> <source>Invalid number of escrow feedbacks provided</source> <translation>Ogiltigt antal spärrade kopplingar tillhandahålls</translation> </message> <message> <source>Invalid offer buyer alias</source> <translation>Ogiltiga erbjudande köparens alias</translation> </message> <message> <source>Invalid op, should be escrow activate</source> <translation>Ogiltig op, bör vara spärrade aktivera</translation> </message> <message> <source>Invalid op, should be escrow complete</source> <translation>Ogiltig op bör spärrade komplett</translation> </message> <message> <source>Invalid op, should be escrow refund</source> <translation>Ogiltig op, bör vara spärrade återbetalning</translation> </message> <message> <source>Invalid op, should be escrow release</source> <translation>Ogiltig op, bör vara spärrade frisättning</translation> </message> <message> <source>Invalid payment option specified</source> <translation>Ogiltig betalningsalternativ som anges</translation> </message> <message> <source>Invalid payment option</source> <translation>Ogiltig betalningsalternativ</translation> </message> <message> <source>Invalid quantity value. Quantity must be less than 4294967296.</source> <translation>Ogiltig mängd värde. Kvantitet måste vara mindre än 4294967296.</translation> </message> <message> <source>Invalid rating value</source> <translation>Ogiltigt rating värde</translation> </message> <message> <source>Invalid redeem script provided in transaction</source> <translation>Ogiltig lösa skript tillhandahålls i transaktionen</translation> </message> <message> <source>Linked offer alias does not exist on the root offer affiliate list</source> <translation>Kombinationserbjudande alias existerar inte på roten erbjudandet affiliate lista</translation> </message> <message> <source>Linked offer not found. It may be expired</source> <translation>Kombinationserbjudande hittades inte. Det kan ha upphört att gälla</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Lyssna på JSON-RPC-anslutningar på &lt;port&gt; (förval: %u eller testnet: %u)</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Lyssna efter anslutningar på &lt;port&gt; (förvalt: %u eller testnet: %u)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: %u)</source> <translation>Ha som mest &lt;n&gt; anslutningar till andra klienter (förvalt: %u)</translation> </message> <message> <source>Make the wallet broadcast transactions</source> <translation>Gör så att plånboken sänder ut transaktionerna</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximal mottagningsbuffert per anslutning, &lt;n&gt;*1000 byte (förvalt: %u)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximal sändningsbuffert per anslutning, &lt;n&gt;*1000 byte (förvalt: %u)</translation> </message> <message> <source>Message arguments incorrect size</source> <translation>Meddelande argument felaktig storlek</translation> </message> <message> <source>Message guid in data output does not match guid in transaction</source> <translation>Meddelande guid i datautgång inte matchar guid i transaktionen</translation> </message> <message> <source>Message guid mismatch</source> <translation>Meddelande guid mismatch</translation> </message> <message> <source>Message subject too long</source> <translation>Ärende för lång</translation> </message> <message> <source>Message too long</source> <translation>Meddelande för lång</translation> </message> <message> <source>Message transaction guid too big</source> <translation>Meddelandetransaktion guid för stor</translation> </message> <message> <source>Message transaction has unknown op</source> <translation>Meddelandetransaktion har okänd op</translation> </message> <message> <source>No private keys found involved in this escrow</source> <translation>Inga privata nycklar hittades inblandade i denna depositions</translation> </message> <message> <source>Non-Presidentielcoin transaction found</source> <translation>Icke-Presidentielcoin transaktion hittades</translation> </message> <message> <source>Not enough quantity left in this offer for this purchase</source> <translation>Inte tillräcklig mängd kvar i detta erbjudande för detta köp</translation> </message> <message> <source>Offer accept hex guid too long</source> <translation>Erbjudandet acceptera hex guid för lång</translation> </message> <message> <source>Offer alias mismatch</source> <translation>Erbjudandet alias mismatch</translation> </message> <message> <source>Offer already exists</source> <translation>Erbjudandet finns redan</translation> </message> <message> <source>Offer arguments incorrect size</source> <translation>Erbjudande argument felaktig storlek</translation> </message> <message> <source>Offer category cannot be empty</source> <translation>Erbjudandet kategori kan inte vara tom</translation> </message> <message> <source>Offer category too long</source> <translation>Erbjudande kategori för lång</translation> </message> <message> <source>Offer curreny too long</source> <translation>Erbjudandet curreny för lång</translation> </message> <message> <source>Offer description too long</source> <translation>Erbjudandet beskrivning för lång</translation> </message> <message> <source>Offer geolocation too long</source> <translation>Erbjudandet geolokalisering för lång</translation> </message> <message> <source>Offer guid too long</source> <translation>Erbjudandet guid för lång</translation> </message> <message> <source>Offer has too many affiliate entries, only one allowed per transaction</source> <translation>Erbjudandet har alltför många affiliate anteckningar, endast en tillåts per transaktion</translation> </message> <message> <source>Offer input and offer guid mismatch</source> <translation>Erbjuda ingång och erbjuda guid mismatch</translation> </message> <message> <source>Offer link guid hash too long</source> <translation>Erbjudandet länk guid hash för lång</translation> </message> <message> <source>Offer payment already acknowledged</source> <translation>Erbjudandet betalning redan erkänt</translation> </message> <message> <source>Offer payment already exists</source> <translation>Erbjudandet betalning redan existerar</translation> </message> <message> <source>Offer payment does not include enough commission to affiliate</source> <translation>Erbjudandet betalning inkluderar inte tillräckligt provision till affiliate</translation> </message> <message> <source>Offer payment does not pay enough according to the offer price</source> <translation>Erbjudandet betalning inte betalar tillräckligt enligt anbudspriset</translation> </message> <message> <source>Offer payment does not specify the correct payment amount</source> <translation>Erbjudandet betalning inte ange korrekta beloppet</translation> </message> <message> <source>Offer payment message cannot be empty</source> <translation>Erbjudandet betalningsmeddelande kan inte vara tom</translation> </message> <message> <source>Offer price must be greater than 0</source> <translation>Anbudspriset måste vara större än 0</translation> </message> <message> <source>Offer purchase transaction of wrong type</source> <translation>Erbjudandet köpet av fel typ</translation> </message> <message> <source>Offer title cannot be empty</source> <translation>Erbjudandet titel kan inte vara tom</translation> </message> <message> <source>Offer title too long</source> <translation>Erbjudandet titel för lång</translation> </message> <message> <source>Offer transaction has unknown op</source> <translation>Erbjudandet transaktionen har okänd op</translation> </message> <message> <source>OfferAccept arguments incorrect size</source> <translation>OfferAccept argument felaktig storlek</translation> </message> <message> <source>Offeraccept object cannot be empty</source> <translation>Offeraccept objekt kan inte vara tom</translation> </message> <message> <source>Offeraccept transaction with guid too big</source> <translation>Offeraccept transaktion med guid för stor</translation> </message> <message> <source>Only arbiter can leave this feedback</source> <translation>Endast domaren kan lämna denna feedback</translation> </message> <message> <source>Only arbiter can refund an escrow after it has already been refunded</source> <translation>Endast domaren kan återbetala ett spärrat efter att den redan har återbetalas</translation> </message> <message> <source>Only arbiter can release an escrow after it has already been released</source> <translation>Endast domaren kan frigöra ett spärrat efter att den redan har släppts</translation> </message> <message> <source>Only arbiter or buyer can initiate an escrow release</source> <translation>Endast domaren eller köparen kan initiera ett spärrat frigör</translation> </message> <message> <source>Only arbiter or seller can initiate an escrow refund</source> <translation>Endast domaren eller säljare kan initiera ett spärrat återbetalning</translation> </message> <message> <source>Only buyer can claim an escrow refund</source> <translation>Endast köparen kan göra anspråk på ett spärrat återbetalning</translation> </message> <message> <source>Only buyer can leave the seller feedback</source> <translation>Endast köparen kan lämna säljaren återkoppling</translation> </message> <message> <source>Only buyer can leave this feedback</source> <translation>Endast köparen kan lämna denna feedback</translation> </message> <message> <source>Only merchant can acknowledge offer payment</source> <translation>Endast köpman kan erkänna erbjuda betalning</translation> </message> <message> <source>Only merchant of this offer can leave feedback for this purchase</source> <translation>Endast köpman av detta erbjudande kan lämna feedback för detta köp</translation> </message> <message> <source>Only root merchant can acknowledge offer payment</source> <translation>Endast root köpman kan erkänna erbjuda betalning</translation> </message> <message> <source>Only seller can acknowledge an escrow payment</source> <translation>Endast säljaren kan erkänna ett spärrat betalning</translation> </message> <message> <source>Only seller can claim an escrow release</source> <translation>Endast säljaren kan göra anspråk på ett spärrat frigör</translation> </message> <message> <source>Only seller can leave the buyer feedback</source> <translation>Endast säljaren kan lämna köparen återkoppling</translation> </message> <message> <source>Only seller can leave this feedback</source> <translation>Endast säljaren kan lämna denna feedback</translation> </message> <message> <source>Password cannot be empty</source> <translation>Lösenord kan inte vara tomt</translation> </message> <message> <source>Password is incorrect</source> <translation>Lösenord är inkorrekt</translation> </message> <message> <source>Payment address does not match merchant address</source> <translation>Betalningsadress matchar inte köpman adress</translation> </message> <message> <source>Payment destination does not match merchant address</source> <translation>Betalning destination matchar inte köpman adress</translation> </message> <message> <source>Payment message length cannot exceed 1024 characters</source> <translation>Betalning meddelandelängd får inte överstiga 1024 tecken</translation> </message> <message> <source>Payment message too long</source> <translation>Betalning meddelande för lång</translation> </message> <message> <source>Please choose a different password</source> <translation>Välj ett annat lösenord</translation> </message> <message> <source>Prepend debug output with timestamp (default: %u)</source> <translation>Skriv ut tidsstämpel i avlusningsinformationen (förvalt: %u)</translation> </message> <message> <source>Private key for buyer address is not known</source> <translation>Privata nyckeln för köparen adress är inte känd</translation> </message> <message> <source>Private key for seller address is not known</source> <translation>Privata nyckeln för säljaren adress är inte känd</translation> </message> <message> <source>Quantity must be 1 for a digital offer</source> <translation>Antal måste vara ett för en digital erbjudande</translation> </message> <message> <source>Quantity must be greater than or equal to -1</source> <translation>Kvantitet måste vara större än eller lika med -1</translation> </message> <message> <source>Quantity must be less than 4294967296</source> <translation>Kvantitet måste vara mindre än 4294967296</translation> </message> <message> <source>Relay and mine data carrier transactions (default: %u)</source> <translation>Reläa och bearbeta databärartransaktioner (förvalt: %u) </translation> </message> <message> <source>Relay non-P2SH multisig (default: %u)</source> <translation>Reläa icke-P2SH multisig (förvalt: %u)</translation> </message> <message> <source>Scan failed</source> <translation>skanna misslyckades</translation> </message> <message> <source>Seller address does not refer to a key</source> <translation>Säljaren adress refererar inte till en nyckel</translation> </message> <message> <source>Seller alias is not in your wallet</source> <translation>Säljaren alias är inte i din plånbok</translation> </message> <message> <source>Send transactions with full-RBF opt-in enabled (default: %u)</source> <translation>Skicka transaktioner med full RBF opt-in aktiverat (standard: %u)</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: %u)</source> <translation>Sätt storleken på nyckelpoolen till &lt;n&gt; (förvalt: %u)</translation> </message> <message> <source>Set maximum BIP141 block weight (default: %d)</source> <translation>Ställa in maximal BIP141 blocket vikt (standard: %d)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: %d)</source> <translation>Ange antalet trådar för att hantera RPC anrop (förvalt: %d)</translation> </message> <message> <source>Specify configuration file (default: %s)</source> <translation>Ange konfigurationsfil (förvalt: %s)</translation> </message> <message> <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> <translation>Ange timeout för uppkoppling i millisekunder (minimum:1, förvalt: %d)</translation> </message> <message> <source>Specify pid file (default: %s)</source> <translation>Ange pid-fil (förvalt: %s)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: %u)</source> <translation>Spendera okonfirmerad växel när transaktioner sänds (förvalt: %u)</translation> </message> <message> <source>Starting network threads...</source> <translation>Utgångsnätverkstrådar ...</translation> </message> <message> <source>The alias you are transferring to does not accept certificate transfers</source> <translation>Alias ​​du överför till accepterar inte överföringar certifikat</translation> </message> <message> <source>This alias entry already exists on affiliate list</source> <translation>Detta alias posten redan finns på affiliate lista</translation> </message> <message> <source>This alias entry was not found on affiliate list</source> <translation>Detta alias post hittades inte på affiliate lista</translation> </message> <message> <source>This alias is not in your wallet</source> <translation>Detta alias är inte i din plånbok</translation> </message> <message> <source>This alias is not yours</source> <translation>Detta alias är inte din</translation> </message> <message> <source>This message already exists</source> <translation>Detta meddelande finns redan</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: %u)</source> <translation>Tröskelvärde för att koppla ifrån klienter som missköter sig (förvalt: %u)</translation> </message> <message> <source>Too many affiliates for this offer</source> <translation>Alltför många affiliates för detta erbjudande</translation> </message> <message> <source>Transaction does not pay enough fees</source> <translation>Transaktionen inte betalar tillräckligt avgifter</translation> </message> <message> <source>Trying to accept a linked offer but could not find parent offer</source> <translation>Att försöka acceptera ett kombinationserbjudande, men kunde inte hitta förälder erbjudande</translation> </message> <message> <source>Trying to renew an alias that isn't expired</source> <translation>Att försöka förnya ett alias som inte har upphört att gälla</translation> </message> <message> <source>Unknown feedback user type</source> <translation>Okänd användarfeedback typ</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Okänt nätverk som anges i -onlynet: '%s'</translation> </message> <message> <source>acknowledged</source> <translation>erkänd</translation> </message> <message> <source>failed to read alias from alias DB</source> <translation>misslyckats med att läsa alias från alias DB</translation> </message> <message> <source>feedback</source> <translation>återkoppling</translation> </message> <message> <source>Insufficient funds</source> <translation>Otillräckligt med presidentielcoins</translation> </message> <message> <source>Loading block index...</source> <translation>Laddar blockindex...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Lägg till en nod att koppla upp mot och försök att hålla anslutningen öppen</translation> </message> <message> <source>Loading wallet...</source> <translation>Laddar plånbok...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Kan inte nedgradera plånboken</translation> </message> <message> <source>Cannot write default address</source> <translation>Kan inte skriva standardadress</translation> </message> <message> <source>Rescanning...</source> <translation>Söker igen...</translation> </message> <message> <source>Done loading</source> <translation>Klar med laddning</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> </context> </TS><|fim▁end|>
<source>Price</source> <translation>Pris</translation>
<|file_name|>ie_history.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright 2011 Google Inc. All Rights Reserved. """Parser for IE index.dat files. Note that this is a very naive and incomplete implementation and should be replaced with a more intelligent one. Do not implement anything based on this code, it is a placeholder for something real. For anyone who wants a useful reference, see this: http://heanet.dl.sourceforge.net/project/libmsiecf/Documentation/MSIE%20Cache%20 File%20format/MSIE%20Cache%20File%20%28index.dat%29%20format.pdf """ import datetime import glob import operator import os import struct import sys import urlparse import logging from grr.lib import parsers from grr.lib import rdfvalue # Difference between 1 Jan 1601 and 1 Jan 1970. WIN_UNIX_DIFF_MSECS = 11644473600 * 1e6 class IEHistoryParser(parsers.FileParser): """Parse IE index.dat files into BrowserHistoryItem objects.""" output_types = ["BrowserHistoryItem"] supported_artifacts = ["InternetExplorerHistory"] def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ie = IEParser(file_object) for dat in ie.Parse(): yield rdfvalue.BrowserHistoryItem( url=dat["url"], domain=urlparse.urlparse(dat["url"]).netloc, access_time=dat.get("mtime"), program_name="Internet Explorer", source_urn=stat.aff4path) class IEParser(object): """Parser object for index.dat files. The file format for IE index.dat files is somewhat poorly documented. The following implementation is based on information from: http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format Returns results in chronological order based on mtime """ FILE_HEADER = "Client UrlCache MMF Ver 5.2" BLOCK_SIZE = 0x80 def __init__(self, input_obj): """Initialize. Args: input_obj: A file like object to read the index.dat from. """ self._file = input_obj self._entries = [] def Parse(self): """Parse the file.""" if not self._file: logging.error("Couldn't open file") return # Limit read size to 5MB. self.input_dat = self._file.read(1024 * 1024 * 5) if not self.input_dat.startswith(self.FILE_HEADER):<|fim▁hole|> # Events aren't time ordered in the history file, so we collect them all # then sort. events = [] for event in self._DoParse(): events.append(event) for event in sorted(events, key=operator.itemgetter("mtime")): yield event def _GetRecord(self, offset, record_size): """Retrieve a single record from the file. Args: offset: offset from start of input_dat where header starts record_size: length of the header according to file (untrusted) Returns: A dict containing a single browser history record. """ record_header = "<4sLQQL" get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0] url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0] if url_offset in [0xFF, 0xFE]: return None data_offset = get4(offset + 68) data_size = get4(offset + 72) start_pos = offset + data_offset data = struct.unpack("{0}s".format(data_size), self.input_dat[start_pos:start_pos + data_size])[0] fmt = record_header unknown_size = url_offset - struct.calcsize(fmt) fmt += "{0}s".format(unknown_size) fmt += "{0}s".format(record_size - struct.calcsize(fmt)) dat = struct.unpack(fmt, self.input_dat[offset:offset+record_size]) header, blocks, mtime, ctime, ftime, _, url = dat url = url.split(chr(0x00))[0] if mtime: mtime = mtime/10 - WIN_UNIX_DIFF_MSECS if ctime: ctime = ctime/10 - WIN_UNIX_DIFF_MSECS return {"header": header, # the header "blocks": blocks, # number of blocks "urloffset": url_offset, # offset of URL in file "data_offset": data_offset, # offset for start of data "data_size": data_size, # size of data "data": data, # actual data "mtime": mtime, # modified time "ctime": ctime, # created time "ftime": ftime, # file time "url": url # the url visited } def _DoParse(self): """Parse a file for history records yielding dicts. Yields: Dicts containing browser history """ get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0] filesize = get4(0x1c) offset = get4(0x20) coffset = offset while coffset < filesize: etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0] if etype == "REDR": pass elif etype in ["URL "]: # Found a valid record reclen = get4(coffset + 4) * self.BLOCK_SIZE yield self._GetRecord(coffset, reclen) coffset += self.BLOCK_SIZE def main(argv): if len(argv) < 2: print "Usage: {0} index.dat".format(os.path.basename(argv[0])) else: files_to_process = [] for input_glob in argv[1:]: files_to_process += glob.glob(input_glob) for input_file in files_to_process: ie = IEParser(open(input_file)) for dat in ie.Parse(): dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6) print "{ctime} {header} {url}".format(**dat) if __name__ == "__main__": main(sys.argv)<|fim▁end|>
logging.error("Invalid index.dat file %s", self._file) return
<|file_name|>query_result_window.py<|end_file_name|><|fim▁begin|>from PyQt4.QtGui import * class QueryResultWindow: def __init__(self): self.__create_window_widget() self.__create_ui() def __create_window_widget(self): self.__qt_widget_object = QWidget() self.__qt_widget_object.resize(800, 600) self.__qt_widget_object.setWindowTitle('Результат запроса')<|fim▁hole|> def __create_ui(self): query_result_table = QTableWidget() layout = QVBoxLayout() self.__qt_widget_object.setLayout(layout) layout.addWidget(query_result_table) self.__query_result_table = query_result_table def show(self): self.__qt_widget_object.show() def set_column_names(self, columns): self.__query_result_table.setColumnCount(len(columns)) self.__query_result_table.setHorizontalHeaderLabels(columns) def set_data(self, data): self.__query_result_table.setRowCount(len(data)) for i, row in enumerate(data): for j in range(0, len(row)): item_value = row[j] item_text = str(item_value) item = QTableWidgetItem(item_text) self.__query_result_table.setItem(i, j, item)<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from os.path import join, isfile from os import walk import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command def read_file(filename): with open(filename) as fp: return fp.read().strip() def read_requirements(filename): return [line.strip() for line in read_file(filename).splitlines() if not line.startswith('#')] NAME = 'gerapy' FOLDER = 'gerapy' DESCRIPTION = 'Distributed Crawler Management Framework Based on Scrapy, Scrapyd, Scrapyd-Client, Scrapyd-API, Django and Vue.js' URL = 'https://github.com/Gerapy/Gerapy' EMAIL = '[email protected]' AUTHOR = 'Germey' REQUIRES_PYTHON = '>=3.5.0' VERSION = None REQUIRED = read_requirements('requirements.txt') here = os.path.abspath(os.path.dirname(__file__)) try: with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = '\n' + f.read() except FileNotFoundError: long_description = DESCRIPTION about = {} if not VERSION: with open(os.path.join(here, FOLDER, '__version__.py')) as f: exec(f.read(), about) else: about['__version__'] = VERSION def package_files(directories): paths = [] for item in directories: if isfile(item): paths.append(join('..', item)) continue for (path, directories, filenames) in walk(item): for filename in filenames: paths.append(join('..', path, filename)) return paths class UploadCommand(Command): description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds…') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution…') os.system( '{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPI via Twine…') os.system('twine upload dist/*') self.status('Pushing git tags…') os.system('git tag v{0}'.format(about['__version__'])) os.system('git push --tags') sys.exit() setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, long_description_content_type='text/markdown', author=AUTHOR, author_email=EMAIL,<|fim▁hole|> include_package_data=True, license='MIT', entry_points={ 'console_scripts': ['gerapy = gerapy.cmd:cmd'] }, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], package_data={ '': package_files([ 'gerapy/server/static', 'gerapy/server/core/templates', 'gerapy/templates', ]) }, # $ setup.py publish support. cmdclass={ 'upload': UploadCommand, }, )<|fim▁end|>
python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=('tests',)), install_requires=REQUIRED,
<|file_name|>theme.js<|end_file_name|><|fim▁begin|>/** * Copyright 2015 IBM Corp. * * 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. **/ var express = require("express"); var util = require("util"); var path = require("path"); var fs = require("fs"); var clone = require("clone"); var defaultContext = { page: { title: "Node-RED", favicon: "favicon.ico" }, header: { title: "Node-RED", image: "red/images/node-red.png" }, asset: { red: (process.env.NODE_ENV == "development")? "red/red.js":"red/red.min.js" } }; var themeContext = clone(defaultContext); var themeSettings = null; function serveFile(app,baseUrl,file) { try { var stats = fs.statSync(file); var url = baseUrl+path.basename(file); //console.log(url,"->",file); app.get(url,function(req, res) { res.sendfile(file); }); return "theme"+url; } catch(err) { //TODO: log filenotfound return null; } } module.exports = { init: function(settings) { var i; var url; themeContext = clone(defaultContext); themeSettings = null;<|fim▁hole|> themeSettings = {}; var themeApp = express(); if (theme.page) { if (theme.page.css) { var styles = theme.page.css; if (!util.isArray(styles)) { styles = [styles]; } themeContext.page.css = []; for (i=0;i<styles.length;i++) { url = serveFile(themeApp,"/css/",styles[i]); if (url) { themeContext.page.css.push(url); } } } if (theme.page.favicon) { url = serveFile(themeApp,"/favicon/",theme.page.favicon) if (url) { themeContext.page.favicon = url; } } themeContext.page.title = theme.page.title || themeContext.page.title; } if (theme.header) { themeContext.header.title = theme.header.title || themeContext.header.title; if (theme.header.hasOwnProperty("url")) { themeContext.header.url = theme.header.url; } if (theme.header.hasOwnProperty("image")) { if (theme.header.image) { url = serveFile(themeApp,"/header/",theme.header.image); if (url) { themeContext.header.image = url; } } else { themeContext.header.image = null; } } } if (theme.deployButton) { if (theme.deployButton.type == "simple") { themeSettings.deployButton = { type: "simple" } if (theme.deployButton.label) { themeSettings.deployButton.label = theme.deployButton.label; } if (theme.deployButton.icon) { url = serveFile(themeApp,"/deploy/",theme.deployButton.icon); if (url) { themeSettings.deployButton.icon = url; } } } } if (theme.hasOwnProperty("userMenu")) { themeSettings.userMenu = theme.userMenu; } if (theme.login) { if (theme.login.image) { url = serveFile(themeApp,"/login/",theme.login.image); if (url) { themeContext.login = { image: url } } } } if (theme.hasOwnProperty("menu")) { themeSettings.menu = theme.menu; } return themeApp; } }, context: function() { return themeContext; }, settings: function() { return themeSettings; } }<|fim▁end|>
if (settings.editorTheme) { var theme = settings.editorTheme;
<|file_name|>kqueue.rs<|end_file_name|><|fim▁begin|>use std::{cmp, fmt, ptr}; use std::os::raw::c_int; use std::os::unix::io::RawFd; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::time::Duration; use libc::{self, time_t}; use {io, Ready, PollOpt, Token}; use event::{self, Event}; use sys::unix::cvt; use sys::unix::io::set_cloexec; /// Each Selector has a globally unique(ish) ID associated with it. This ID /// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first /// registered with the `Selector`. If a type that is previously associated with /// a `Selector` attempts to register itself with a different `Selector`, the /// operation will return with an error. This matches windows behavior. static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; macro_rules! kevent { ($id: expr, $filter: expr, $flags: expr, $data: expr) => { libc::kevent { ident: $id as ::libc::uintptr_t, filter: $filter, flags: $flags, fflags: 0, data: 0, udata: $data as *mut _, } } } pub struct Selector { id: usize, kq: RawFd, } impl Selector { pub fn new() -> io::Result<Selector> { // offset by 1 to avoid choosing 0 as the id of a selector let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; let kq = unsafe { try!(cvt(libc::kqueue())) }; drop(set_cloexec(kq)); Ok(Selector { id: id, kq: kq, }) } pub fn id(&self) -> usize { self.id } pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> { let timeout = timeout.map(|to| { libc::timespec { tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t, tv_nsec: to.subsec_nanos() as libc::c_long, } }); let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut()); unsafe { let cnt = try!(cvt(libc::kevent(self.kq, ptr::null(), 0, evts.sys_events.0.as_mut_ptr(), // FIXME: needs a saturating cast here. evts.sys_events.0.capacity() as c_int, timeout))); evts.sys_events.0.set_len(cnt as usize); Ok(evts.coalesce(awakener)) } } pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { trace!("registering; token={:?}; interests={:?}", token, interests); let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } | if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } | libc::EV_RECEIPT; unsafe { let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE }; let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE }; let mut changes = [ kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)), kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)), ]; try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int, changes.as_mut_ptr(), changes.len() as c_int, ::std::ptr::null()))); for change in changes.iter() { debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR); if change.data != 0 { // there’s some error, but we want to ignore ENOENT error for EV_DELETE let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w }; if !(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0) { return Err(::std::io::Error::from_raw_os_error(change.data as i32)); } } } Ok(()) } } pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { // Just need to call register here since EV_ADD is a mod if already // registered self.register(fd, token, interests, opts) } pub fn deregister(&self, fd: RawFd) -> io::Result<()> { unsafe { // EV_RECEIPT is a nice way to apply changes and get back per-event results while not // draining the actual changes. let filter = libc::EV_DELETE | libc::EV_RECEIPT; let mut changes = [ kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()), kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()), ]; try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int, changes.as_mut_ptr(), changes.len() as c_int, ::std::ptr::null())).map(|_| ())); if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT { return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); } for change in changes.iter() { debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR); if change.data != 0 && change.data as i32 != libc::ENOENT {<|fim▁hole|> } } Ok(()) } } } impl fmt::Debug for Selector { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Selector") .field("id", &self.id) .field("kq", &self.kq) .finish() } } impl Drop for Selector { fn drop(&mut self) { unsafe { let _ = libc::close(self.kq); } } } pub struct Events { sys_events: KeventList, events: Vec<Event>, event_map: HashMap<Token, usize>, } struct KeventList(Vec<libc::kevent>); unsafe impl Send for KeventList {} unsafe impl Sync for KeventList {} impl Events { pub fn with_capacity(cap: usize) -> Events { Events { sys_events: KeventList(Vec::with_capacity(cap)), events: Vec::with_capacity(cap), event_map: HashMap::with_capacity(cap) } } #[inline] pub fn len(&self) -> usize { self.events.len() } #[inline] pub fn capacity(&self) -> usize { self.events.capacity() } #[inline] pub fn is_empty(&self) -> bool { self.events.is_empty() } pub fn get(&self, idx: usize) -> Option<Event> { self.events.get(idx).map(|e| *e) } fn coalesce(&mut self, awakener: Token) -> bool { let mut ret = false; self.events.clear(); self.event_map.clear(); for e in self.sys_events.0.iter() { let token = Token(e.udata as usize); let len = self.events.len(); if token == awakener { // TODO: Should this return an error if event is an error. It // is not critical as spurious wakeups are permitted. ret = true; continue; } let idx = *self.event_map.entry(token) .or_insert(len); if idx == len { // New entry, insert the default self.events.push(Event::new(Ready::none(), token)); } if e.flags & libc::EV_ERROR != 0 { event::kind_mut(&mut self.events[idx]).insert(Ready::error()); } if e.filter == libc::EVFILT_READ { event::kind_mut(&mut self.events[idx]).insert(Ready::readable()); } else if e.filter == libc::EVFILT_WRITE { event::kind_mut(&mut self.events[idx]).insert(Ready::writable()); } if e.flags & libc::EV_EOF != 0 { event::kind_mut(&mut self.events[idx]).insert(Ready::hup()); // When the read end of the socket is closed, EV_EOF is set on // flags, and fflags contains the error if there is one. if e.fflags != 0 { event::kind_mut(&mut self.events[idx]).insert(Ready::error()); } } } ret } pub fn push_event(&mut self, event: Event) { self.events.push(event); } } impl fmt::Debug for Events { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len()) } } #[test] fn does_not_register_rw() { use ::deprecated::{EventLoopBuilder, Handler}; use ::unix::EventedFd; struct Nop; impl Handler for Nop { type Timeout = (); type Message = (); } // registering kqueue fd will fail if write is requested (On anything but some versions of OS // X) let kq = unsafe { libc::kqueue() }; let kqf = EventedFd(&kq); let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds"); evtloop.register(&kqf, Token(1234), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); }<|fim▁end|>
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
<|file_name|>ColumnNames.java<|end_file_name|><|fim▁begin|>package com.xinqihd.sns.gameserver.admin.i18n; import java.util.HashMap; public class ColumnNames { private static HashMap<String, String> map = new HashMap<String, String>(); static { map.put("profile" , "profile"); map.put("vip" , "vip"); map.put("ability" , "ability"); map.put("login" , "登陆"); map.put("config" , "配置"); map.put("wealth" , "wealth"); map.put("loc" , "位置"); map.put("tools" , "便携道具"); map.put("wears" , "wears"); map.put("count" , "count"); map.put("items" , "items"); map.put("class" , "class"); map.put("name" , "名称"); map.put("type" , "类型"); map.put("reqlv" , "reqlv"); map.put("scrollAreaX" , "scrollAreaX"); map.put("scrollAreaY" , "scrollAreaY"); map.put("scrollAreaWidth" , "scrollAreaWidth"); map.put("scrollAreaHeight" , "scrollAreaHeight"); map.put("layers" , "layers"); map.put("bgm" , "bgm"); map.put("damage" , "damage"); map.put("bosses" , "bosses"); map.put("enemies" , "enemies"); map.put("startPoints" , "startPoints"); map.put("index" , "index"); map.put("quality" , "品质"); map.put("qualityColor" , "品质颜色"); map.put("sName" , "名称"); map.put("equipType" , "装备类型"); map.put("addAttack" , "加攻击"); map.put("addDefend" , "加防御"); map.put("addAgility" , "加敏捷"); map.put("addLuck" , "加幸运"); map.put("addBlood" , "加血量"); map.put("addBloodPercent" , "加血量比例"); map.put("addThew" , "加体力"); map.put("addDamage" , "加伤害"); map.put("addSkin" , "加护甲"); map.put("sex" , "性别"); map.put("unused1" , "unused1"); map.put("unused2" , "unused2"); map.put("unused3" , "unused3"); map.put("indate1" , "indate1"); map.put("indate2" , "indate2"); map.put("indate3" , "indate3"); map.put("sign" , "sign"); map.put("lv" , "lv"); map.put("autoDirection" , "自动定位"); map.put("sAutoDirection" , "大招定位"); map.put("specialAction" , "特殊攻击"); map.put("radius" , "攻击半径"); map.put("sRadius" , "大招攻击半径"); map.put("expBlend" , "混合(不用)"); map.put("expSe" , "音效"); map.put("power" , "战斗力(未使用)"); map.put("autoDestory" , "自动伤害"); map.put("bullet" , "子弹标识"); map.put("icon" , "图标"); map.put("info" , "描述"); map.put("bubble" , "bubble"); map.put("slot" , "卡槽"); map.put("avatar" , "形象"); map.put("propInfoId" , "propInfoId"); map.put("level" , "level"); map.put("moneyType" , "货币类型"); map.put("buyPrices" , "购买价格"); map.put("banded" , "是否绑定"); map.put("discount" , "折扣"); map.put("sell" , "出售"); map.put("limitCount" , "limitCount"); map.put("limitGroup" , "limitGroup"); map.put("shopId" , "shopId"); map.put("isItem" , "isItem"); map.put("catalogs" , "商品目录"); map.put("desc" , "描述"); map.put("taskTarget" , "taskTarget"); map.put("step" , "步骤(step)"); map.put("exp" , "经验"); map.put("gold" , "金币"); map.put("ticket" , "礼券"); map.put("gongxun" , "功勋"); map.put("caifu" , "财富"); map.put("seq" , "顺序(seq)"); map.put("userLevel" , "用户等级"); map.put("script" , "脚本"); map.put("awards" , "奖励"); map.put("rival" , "rival"); map.put("typeId" , "typeId"); map.put("q" , "概率q"); map.put("rewards" , "奖励"); map.put("conditions" , "开启条件"); map.put("dayNum" , "天数"); map.put("price" , "价格"); map.put("currency" , "货币"); map.put("yuanbao" , "元宝");<|fim▁hole|> map.put("yuanbaoPrice" , "元宝价格"); map.put("voucherPrice" , "礼券价格"); map.put("medalPrice" , "勋章价格"); } public static String translate(String columnName) { String name = map.get(columnName); if ( name != null ) { return name; } return columnName; } }<|fim▁end|>
map.put("isHotSale" , "是否热卖"); map.put("month" , "月");
<|file_name|>taskTemplate.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\taskTemplate.ui' # # Created: Thu Oct 08 16:48:34 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8<|fim▁hole|>try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(218, 236) self.gridLayout_2 = QtGui.QGridLayout(Form) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.groupBox = QtGui.QGroupBox(Form) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.gridLayout = QtGui.QGridLayout(self.groupBox) self.gridLayout.setSpacing(0) self.gridLayout.setContentsMargins(3, 0, 3, 3) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.powerWaveRadio = QtGui.QRadioButton(self.groupBox) self.powerWaveRadio.setChecked(True) self.powerWaveRadio.setObjectName(_fromUtf8("powerWaveRadio")) self.gridLayout.addWidget(self.powerWaveRadio, 0, 0, 1, 1) self.switchWaveRadio = QtGui.QRadioButton(self.groupBox) self.switchWaveRadio.setObjectName(_fromUtf8("switchWaveRadio")) self.gridLayout.addWidget(self.switchWaveRadio, 1, 0, 1, 1) self.gridLayout_2.addWidget(self.groupBox, 5, 0, 1, 3) self.wavelengthWidget = QtGui.QWidget(Form) self.wavelengthWidget.setObjectName(_fromUtf8("wavelengthWidget")) self.horizontalLayout = QtGui.QHBoxLayout(self.wavelengthWidget) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.setWavelengthCheck = QtGui.QCheckBox(self.wavelengthWidget) self.setWavelengthCheck.setObjectName(_fromUtf8("setWavelengthCheck")) self.horizontalLayout.addWidget(self.setWavelengthCheck) self.wavelengthSpin = QtGui.QSpinBox(self.wavelengthWidget) self.wavelengthSpin.setMaximum(4000) self.wavelengthSpin.setSingleStep(10) self.wavelengthSpin.setProperty("value", 1080) self.wavelengthSpin.setObjectName(_fromUtf8("wavelengthSpin")) self.horizontalLayout.addWidget(self.wavelengthSpin) self.gridLayout_2.addWidget(self.wavelengthWidget, 4, 0, 1, 3) self.label_2 = QtGui.QLabel(Form) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_2.addWidget(self.label_2, 0, 0, 1, 1) self.outputPowerLabel = QtGui.QLabel(Form) self.outputPowerLabel.setObjectName(_fromUtf8("outputPowerLabel")) self.gridLayout_2.addWidget(self.outputPowerLabel, 0, 1, 1, 1) self.checkPowerBtn = QtGui.QPushButton(Form) self.checkPowerBtn.setObjectName(_fromUtf8("checkPowerBtn")) self.gridLayout_2.addWidget(self.checkPowerBtn, 0, 2, 1, 1) self.label_3 = QtGui.QLabel(Form) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_2.addWidget(self.label_3, 1, 0, 1, 1) self.samplePowerLabel = QtGui.QLabel(Form) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.samplePowerLabel.setFont(font) self.samplePowerLabel.setObjectName(_fromUtf8("samplePowerLabel")) self.gridLayout_2.addWidget(self.samplePowerLabel, 1, 1, 1, 1) self.adjustLengthCheck = QtGui.QCheckBox(Form) self.adjustLengthCheck.setChecked(True) self.adjustLengthCheck.setTristate(False) self.adjustLengthCheck.setObjectName(_fromUtf8("adjustLengthCheck")) self.gridLayout_2.addWidget(self.adjustLengthCheck, 3, 0, 1, 3) self.checkPowerCheck = QtGui.QCheckBox(Form) self.checkPowerCheck.setChecked(True) self.checkPowerCheck.setObjectName(_fromUtf8("checkPowerCheck")) self.gridLayout_2.addWidget(self.checkPowerCheck, 2, 0, 1, 3) self.releaseBetweenTasks = QtGui.QRadioButton(Form) self.releaseBetweenTasks.setObjectName(_fromUtf8("releaseBetweenTasks")) self.releaseButtonGroup = QtGui.QButtonGroup(Form) self.releaseButtonGroup.setObjectName(_fromUtf8("releaseButtonGroup")) self.releaseButtonGroup.addButton(self.releaseBetweenTasks) self.gridLayout_2.addWidget(self.releaseBetweenTasks, 6, 0, 1, 3) self.releaseAfterSequence = QtGui.QRadioButton(Form) self.releaseAfterSequence.setChecked(True) self.releaseAfterSequence.setObjectName(_fromUtf8("releaseAfterSequence")) self.releaseButtonGroup.addButton(self.releaseAfterSequence) self.gridLayout_2.addWidget(self.releaseAfterSequence, 7, 0, 1, 3) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.groupBox.setTitle(_translate("Form", "Control Mode:", None)) self.powerWaveRadio.setText(_translate("Form", "Power waveform (W)", None)) self.switchWaveRadio.setText(_translate("Form", "Switch waveform (%)", None)) self.setWavelengthCheck.setText(_translate("Form", "Set wavelength", None)) self.wavelengthSpin.setSuffix(_translate("Form", " nm", None)) self.label_2.setText(_translate("Form", "Output Power:", None)) self.outputPowerLabel.setText(_translate("Form", "0mW", None)) self.checkPowerBtn.setText(_translate("Form", "Check Power", None)) self.label_3.setText(_translate("Form", "Power at Sample:", None)) self.samplePowerLabel.setText(_translate("Form", "0mW", None)) self.adjustLengthCheck.setToolTip(_translate("Form", "If the output power of the laser changes, adjust the length of laser pulses to maintain constant pulse energy.", None)) self.adjustLengthCheck.setText(_translate("Form", "Adjust pulse length if power changes", None)) self.checkPowerCheck.setText(_translate("Form", "Check power before task start", None)) self.releaseBetweenTasks.setText(_translate("Form", "Release between tasks", None)) self.releaseAfterSequence.setText(_translate("Form", "Release after sequence", None))<|fim▁end|>
except AttributeError: def _fromUtf8(s): return s
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for hackathon project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hackathon.settings") <|fim▁hole|><|fim▁end|>
application = get_wsgi_application()
<|file_name|>instr_cmovns.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cmovns_1() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(DI)), operand2: Some(Direct(SP)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 252], OperandSize::Word) } #[test] fn cmovns_2() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(CX)), operand2: Some(IndirectDisplaced(DI, 179, Some(OperandSize::Word), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 141, 179, 0], OperandSize::Word) } #[test] fn cmovns_3() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(SP)), operand2: Some(Direct(DX)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 226], OperandSize::Dword) } #[test] fn cmovns_4() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(BP)), operand2: Some(IndirectDisplaced(ECX, 938056779, Some(OperandSize::Word), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 169, 75, 156, 233, 55], OperandSize::Dword) } #[test] fn cmovns_5() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(SI)), operand2: Some(Direct(BX)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 243], OperandSize::Qword) } #[test] fn cmovns_6() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(SI)), operand2: Some(IndirectDisplaced(RBX, 244739391, Some(OperandSize::Word), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 179, 63, 109, 150, 14], OperandSize::Qword) } #[test] fn cmovns_7() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(ECX)), operand2: Some(Direct(EBP)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 205], OperandSize::Word) } #[test] fn cmovns_8() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(ESI)), operand2: Some(IndirectDisplaced(BP, 12325, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 73, 182, 37, 48], OperandSize::Word) } #[test] fn cmovns_9() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(ESP)), operand2: Some(Direct(EBX)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 227], OperandSize::Dword) } #[test] fn cmovns_10() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(ESP)), operand2: Some(IndirectDisplaced(ECX, 627117704, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 161, 136, 14, 97, 37], OperandSize::Dword) } #[test] fn cmovns_11() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(ESI)), operand2: Some(Direct(EDX)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 242], OperandSize::Qword) } <|fim▁hole|>#[test] fn cmovns_12() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(EDI)), operand2: Some(IndirectScaledIndexedDisplaced(RBX, RSI, Four, 1139354945, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 73, 188, 179, 65, 45, 233, 67], OperandSize::Qword) } #[test] fn cmovns_13() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(RSP)), operand2: Some(Direct(RDX)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[72, 15, 73, 226], OperandSize::Qword) } #[test] fn cmovns_14() { run_test(&Instruction { mnemonic: Mnemonic::CMOVNS, operand1: Some(Direct(RDI)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1727327438, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[72, 15, 73, 188, 95, 206, 236, 244, 102], OperandSize::Qword) }<|fim▁end|>
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import sys import os os.environ['DJANGO_SETTINGS_MODULE'] = 'gae.settings.settings' # =========== # Add any python 3rd party module that doesnt exist at # https://developers.google.com/appengine/docs/python/tools/libraries27 # =========== sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) # =========== # Force Django to reload its settings. from django.conf import settings settings._target = None import django.core.handlers.wsgi import django.core.signals import django.db<|fim▁hole|>import django.dispatch # Log errors. import logging def log_exception(*args, **kwargs): logging.exception('Exception in request:') django.dispatch.Signal.connect( django.core.signals.got_request_exception, log_exception) # Unregister the rollback event handler. #django.dispatch.Signal.disconnect( # django.core.signals.got_request_exception, # django.db._rollback_on_exception) app = django.core.handlers.wsgi.WSGIHandler()<|fim▁end|>
<|file_name|>ze_generated_example_galleryimageversions_client_test.go<|end_file_name|><|fim▁begin|>//go:build go1.16 // +build go1.16 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. package armcompute_test import ( "context" "log" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute" ) // x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-10-01/examples/gallery/CreateOrUpdateASimpleGalleryImageVersionWithVMAsSource.json func ExampleGalleryImageVersionsClient_BeginCreateOrUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err)<|fim▁hole|> } ctx := context.Background() client := armcompute.NewGalleryImageVersionsClient("<subscription-id>", cred, nil) poller, err := client.BeginCreateOrUpdate(ctx, "<resource-group-name>", "<gallery-name>", "<gallery-image-name>", "<gallery-image-version-name>", armcompute.GalleryImageVersion{ Location: to.StringPtr("<location>"), Properties: &armcompute.GalleryImageVersionProperties{ PublishingProfile: &armcompute.GalleryImageVersionPublishingProfile{ TargetRegions: []*armcompute.TargetRegion{ { Name: to.StringPtr("<name>"), Encryption: &armcompute.EncryptionImages{ DataDiskImages: []*armcompute.DataDiskImageEncryption{ { DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), Lun: to.Int32Ptr(0), }, { DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), Lun: to.Int32Ptr(1), }}, OSDiskImage: &armcompute.OSDiskImageEncryption{ DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), }, }, RegionalReplicaCount: to.Int32Ptr(1), }, { Name: to.StringPtr("<name>"), Encryption: &armcompute.EncryptionImages{ DataDiskImages: []*armcompute.DataDiskImageEncryption{ { DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), Lun: to.Int32Ptr(0), }, { DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), Lun: to.Int32Ptr(1), }}, OSDiskImage: &armcompute.OSDiskImageEncryption{ DiskEncryptionSetID: to.StringPtr("<disk-encryption-set-id>"), }, }, RegionalReplicaCount: to.Int32Ptr(2), StorageAccountType: armcompute.StorageAccountType("Standard_ZRS").ToPtr(), }}, }, StorageProfile: &armcompute.GalleryImageVersionStorageProfile{ Source: &armcompute.GalleryArtifactVersionSource{ ID: to.StringPtr("<id>"), }, }, }, }, nil) if err != nil { log.Fatal(err) } res, err := poller.PollUntilDone(ctx, 30*time.Second) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.GalleryImageVersionsClientCreateOrUpdateResult) } // x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-10-01/examples/gallery/UpdateASimpleGalleryImageVersion.json func ExampleGalleryImageVersionsClient_BeginUpdate() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armcompute.NewGalleryImageVersionsClient("<subscription-id>", cred, nil) poller, err := client.BeginUpdate(ctx, "<resource-group-name>", "<gallery-name>", "<gallery-image-name>", "<gallery-image-version-name>", armcompute.GalleryImageVersionUpdate{ Properties: &armcompute.GalleryImageVersionProperties{ PublishingProfile: &armcompute.GalleryImageVersionPublishingProfile{ TargetRegions: []*armcompute.TargetRegion{ { Name: to.StringPtr("<name>"), RegionalReplicaCount: to.Int32Ptr(1), }, { Name: to.StringPtr("<name>"), RegionalReplicaCount: to.Int32Ptr(2), StorageAccountType: armcompute.StorageAccountType("Standard_ZRS").ToPtr(), }}, }, StorageProfile: &armcompute.GalleryImageVersionStorageProfile{ Source: &armcompute.GalleryArtifactVersionSource{ ID: to.StringPtr("<id>"), }, }, }, }, nil) if err != nil { log.Fatal(err) } res, err := poller.PollUntilDone(ctx, 30*time.Second) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.GalleryImageVersionsClientUpdateResult) } // x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-10-01/examples/gallery/GetAGalleryImageVersionWithReplicationStatus.json func ExampleGalleryImageVersionsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armcompute.NewGalleryImageVersionsClient("<subscription-id>", cred, nil) res, err := client.Get(ctx, "<resource-group-name>", "<gallery-name>", "<gallery-image-name>", "<gallery-image-version-name>", &armcompute.GalleryImageVersionsClientGetOptions{Expand: armcompute.ReplicationStatusTypes("ReplicationStatus").ToPtr()}) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.GalleryImageVersionsClientGetResult) } // x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-10-01/examples/gallery/DeleteAGalleryImageVersion.json func ExampleGalleryImageVersionsClient_BeginDelete() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armcompute.NewGalleryImageVersionsClient("<subscription-id>", cred, nil) poller, err := client.BeginDelete(ctx, "<resource-group-name>", "<gallery-name>", "<gallery-image-name>", "<gallery-image-version-name>", nil) if err != nil { log.Fatal(err) } _, err = poller.PollUntilDone(ctx, 30*time.Second) if err != nil { log.Fatal(err) } } // x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-10-01/examples/gallery/ListGalleryImageVersionsInAGalleryImage.json func ExampleGalleryImageVersionsClient_ListByGalleryImage() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armcompute.NewGalleryImageVersionsClient("<subscription-id>", cred, nil) pager := client.ListByGalleryImage("<resource-group-name>", "<gallery-name>", "<gallery-image-name>", nil) for { nextResult := pager.NextPage(ctx) if err := pager.Err(); err != nil { log.Fatalf("failed to advance page: %v", err) } if !nextResult { break } for _, v := range pager.PageResponse().Value { log.Printf("Pager result: %#v\n", v) } } }<|fim▁end|>
<|file_name|>meta.js<|end_file_name|><|fim▁begin|>module.exports = { // meta<|fim▁hole|> /** * The banner is the comment that is placed at the top of our compiled * source files. It is first processed as a Grunt template, where the `<%=` * pairs are evaluated based on this very configuration object. */ banner: '/**\n' + ' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * <%= pkg.homepage %>\n' + ' *\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' + ' */\n' };<|fim▁end|>
<|file_name|>test_agnos_updater.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import json import os import unittest import requests AGNOS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) MANIFEST = os.path.join(AGNOS_DIR, "agnos.json") class TestAgnosUpdater(unittest.TestCase): def test_manifest(self): with open(MANIFEST) as f: m = json.load(f) for img in m: r = requests.head(img['url'])<|fim▁hole|> if not img['sparse']: assert img['hash'] == img['hash_raw'] if __name__ == "__main__": unittest.main()<|fim▁end|>
r.raise_for_status() self.assertEqual(r.headers['Content-Type'], "application/x-xz")
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import os <|fim▁hole|>from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.bcrypt import Bcrypt from flask_sockets import Sockets app = Flask(__name__, static_folder="../static/dist", template_folder="../static") if os.environ.get('PRODUCTION'): app.config.from_object('config.ProductionConfig') else: app.config.from_object('config.TestingConfig') db = SQLAlchemy(app) bcrypt = Bcrypt(app) sockets = Sockets(app)<|fim▁end|>
from flask import Flask
<|file_name|>generic-extern-mangle.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::num::Int; extern "C" fn foo<T: WrappingOps>(a: T, b: T) -> T { a.wrapping_add(b) } <|fim▁hole|>}<|fim▁end|>
fn main() { assert_eq!(99u8, foo(255u8, 100u8)); assert_eq!(99u16, foo(65535u16, 100u16));
<|file_name|>basic.rs<|end_file_name|><|fim▁begin|>#[cfg(all(feature = "std_rng", feature = "default_dictionary"))] use petname::petname; use petname::Petnames; use rand::rngs::mock::StepRng; #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_adjectives() { let petnames = Petnames::default(); assert_ne!(petnames.adjectives.len(), 0); } #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_adverbs() { let petnames = Petnames::default(); assert_ne!(petnames.adverbs.len(), 0); } #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_names() { let petnames = Petnames::default(); assert_ne!(petnames.names.len(), 0); } #[test] fn retain_applies_given_predicate() { let petnames_expected = Petnames::init("bob", "bob", "bob jane"); let mut petnames = Petnames::init("alice bob carol", "alice bob", "bob carol jane"); petnames.retain(|word| word.len() < 5); assert_eq!(petnames_expected, petnames); } <|fim▁hole|>fn default_petnames_has_non_zero_cardinality() { let petnames = Petnames::default(); // This test will need to be adjusted when word lists change. assert_eq!(0, petnames.cardinality(0)); assert_eq!(456, petnames.cardinality(1)); assert_eq!(204744, petnames.cardinality(2)); assert_eq!(53438184, petnames.cardinality(3)); assert_eq!(13947366024, petnames.cardinality(4)); } #[test] fn generate_uses_adverb_adjective_name() { let petnames = Petnames { adjectives: vec!["adjective"], adverbs: vec!["adverb"], names: vec!["name"], }; assert_eq!( petnames.generate(&mut StepRng::new(0, 1), 3, "-"), "adverb-adjective-name" ); } #[test] #[cfg(all(feature = "std_rng", feature = "default_dictionary"))] fn petname_renders_desired_number_of_words() { assert_eq!(petname(7, "-").split('-').count(), 7); } #[test] #[cfg(all(feature = "std_rng", feature = "default_dictionary"))] fn petname_renders_with_desired_separator() { assert_eq!(petname(7, "@").split('@').count(), 7); } #[test] fn petnames_iter_has_cardinality() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a b", "c d e", "f g h i"); let names = petnames.iter(&mut rng, 3, "."); assert_eq!(24u128, names.cardinality()); } #[test] fn petnames_iter_yields_names() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("foo", "bar", "baz"); let names = petnames.iter(&mut rng, 3, "."); // Definintely an Iterator... let mut iter: Box<dyn Iterator<Item = _>> = Box::new(names); assert_eq!(Some("bar.foo.baz".to_string()), iter.next()); } #[test] fn petnames_iter_non_repeating_yields_unique_names() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a1 a2", "b1 b2 b3", "c1 c2"); let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 3, ".").collect(); assert_eq!( vec![ "b2.a2.c2", "b3.a2.c2", "b1.a2.c2", "b2.a1.c2", "b3.a1.c2", "b1.a1.c2", "b2.a2.c1", "b3.a2.c1", "b1.a2.c1", "b2.a1.c1", "b3.a1.c1", "b1.a1.c1" ], names ) } #[test] fn petnames_iter_non_repeating_yields_nothing_when_any_word_list_is_empty() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a1 a2", "", "c1 c2"); let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 3, ".").collect(); assert_eq!(Vec::<String>::new(), names); } #[test] fn petnames_iter_non_repeating_yields_nothing_when_no_word_lists_are_given() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a1 a2", "b1 b2", "c1 c2"); let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 0, ".").collect(); assert_eq!(Vec::<String>::new(), names); }<|fim▁end|>
#[test] #[cfg(feature = "default_dictionary")]
<|file_name|>ssh_connection.py<|end_file_name|><|fim▁begin|># Copyright 2016 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import socket import threading import paramiko from touchdown.tests.fixtures.fixture import Fixture class DummyServer(paramiko.ServerInterface): def get_allowed_auths(self, username): return "publickey,password" def check_auth_password(self, username, password): return paramiko.AUTH_SUCCESSFUL def check_auth_publickey(self, username, key): return paramiko.AUTH_SUCCESSFUL <|fim▁hole|> def check_channel_exec_request(self, channel, command): return True def check_channel_shell_request(self, channel): return True def check_channel_pty_request( self, channel, term, width, height, pixelwidth, pixelheight, modes ): return True class SshConnectionFixture(Fixture): def __enter__(self): self.listen_socket = socket.socket() self.listen_socket.bind(("0.0.0.0", 0)) self.listen_socket.listen(1) self.address, self.port = self.listen_socket.getsockname() self.fixtures.push(lambda *exc_info: self.listen_socket.close()) self.event = threading.Event() self.ssh_connection = self.workspace.add_ssh_connection( name="test-ssh-connection", hostname=self.address, port=self.port ) self.listen_thread = threading.Thread(target=self.server_thread) self.listen_thread.daemon = True self.listen_thread.start() return self def server_thread(self): self.client_socket, addr = self.listen_socket.accept() self.fixtures.push(lambda *exc_info: self.client_socket.close()) self.server_transport = paramiko.Transport(self.client_socket) self.fixtures.push(lambda *exc_info: self.server_transport.close()) self.server_transport.add_server_key( paramiko.RSAKey.from_private_key_file( os.path.join(os.path.dirname(__file__), "..", "assets/id_rsa_test") ) ) self.server = DummyServer() self.server_transport.start_server(self.event, self.server)<|fim▁end|>
def check_channel_request(self, kind, chanid): return paramiko.OPEN_SUCCEEDED
<|file_name|>rpc.go<|end_file_name|><|fim▁begin|>package dcr import ( "context" "io/ioutil" "sync" "time" "github.com/Shopify/sarama" "github.com/decred/dcrd/rpc/jsonrpc/types" "github.com/decred/dcrd/rpcclient/v4" "github.com/golang/glog" ) func rpcGetWork(wg *sync.WaitGroup, client *rpcclient.Client, workCh chan *types.GetWorkResult, errCh chan error) { glog.Info("Calling getwork") defer wg.Done() work, err := client.GetWork() if err != nil { glog.Errorf("Failed to get work: %v", err) errCh <- err } else { glog.Infof("Get work result: %s", *work) workCh <- work } } func rpcLoop(ctx context.Context, wg *sync.WaitGroup, producer sarama.AsyncProducer) error { certs, err := ioutil.ReadFile(rpcCertificate) if err != nil { glog.Fatalf("Failed to load RPC certificate: %v", err) return err } workCh := make(chan *types.GetWorkResult, 16) notifyCh := make(chan bool, 16) errCh := make(chan error) ntfnHandlers := rpcclient.NotificationHandlers{ OnBlockConnected: func(blockHeader []byte, transactions [][]byte) { glog.Infof("Block connected") notifyCh <- true }, } connCfg := &rpcclient.ConnConfig{ Host: rpcAddress, Endpoint: "ws", User: rpcUsername, Pass: rpcPassword, Certificates: certs, DisableConnectOnNew: true, } client, err := rpcclient.New(connCfg, &ntfnHandlers) if err != nil { glog.Errorf("Failed to create RPC client: %v", err) return err } defer client.WaitForShutdown() err = client.Connect(ctx, true) if err != nil { glog.Errorf("Failed to create RPC client: %v", err) return err } network, err := client.GetCurrentNet() if err != nil { glog.Errorf("Failed to get network type: %v", err) return err } else { glog.Infof("DCR network type: %s", network) } err = client.NotifyBlocks() if err != nil { glog.Errorf("Failed to register block notifications: %v", err) return err } intervalTimer := time.NewTimer(rpcInterval)<|fim▁hole|> notifyCh <- true for { select { case work := <-workCh: wg.Add(1) go processWork(wg, network, work, producer) intervalTimer.Stop() intervalTimer.Reset(rpcInterval) case <-intervalTimer.C: wg.Add(1) go rpcGetWork(wg, client, workCh, errCh) case <-notifyCh: wg.Add(1) go rpcGetWork(wg, client, workCh, errCh) case <-errCh: intervalTimer.Stop() intervalTimer.Reset(rpcInterval) case <-ctx.Done(): client.Shutdown() return nil } } }<|fim▁end|>
<|file_name|>XSSHttpServletRequestWrapper.java<|end_file_name|><|fim▁begin|>package org.butioy.framework.security; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * Created with IntelliJ IDEA. * Author butioy * Date 2015-09-18 22:33 */ public class XSSHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest = null; public XSSHttpServletRequestWrapper(HttpServletRequest request) { super(request); orgRequest = request; } /** * 覆盖getParameter方法,将参数名和参数值都做xss过滤。 * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取 * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 */ @Override public String getParameter(String name) { String value = super.getParameter(xssEncode(name)); if(StringUtils.isNotBlank(value)) { value = xssEncode(value); } return value; <|fim▁hole|> /** * 覆盖getHeader方法,将参数名和参数值都做xss过滤。 * 如果需要获得原始的值,则通过super.getHeaders(name)来获取 * getHeaderNames 也可能需要覆盖 */ @Override public String getHeader(String name) { String value = super.getHeader(xssEncode(name)); if( StringUtils.isNotBlank(value) ) { value = xssEncode(value); } return value; } /** * 将容易引起xss漏洞的参数全部使用StringEscapeUtils转义 * @param value * @return */ private static String xssEncode(String value) { if (value == null || value.isEmpty()) { return value; } value = StringEscapeUtils.escapeHtml4(value); value = StringEscapeUtils.escapeEcmaScript(value); return value; } /** * 获取最原始的request * @return */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request的静态方法 * @return */ public static HttpServletRequest getOrgRequest(HttpServletRequest request) { if (request instanceof XSSHttpServletRequestWrapper) { return ((XSSHttpServletRequestWrapper) request).getOrgRequest(); } return request; } }<|fim▁end|>
}
<|file_name|>human_boolean.go<|end_file_name|><|fim▁begin|>package values <|fim▁hole|>const ( YesHumanBoolean HumanBoolean = "yes" NoHumanBoolean = "no" )<|fim▁end|>
type HumanBoolean string
<|file_name|>_backported.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright (c) 2009 Raymond Hettinger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. from UserDict import DictMixin class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') if last: key = reversed(self).next() else: key = iter(self).next() value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): if len(self) != len(other): return False for p, q in zip(self.items(), other.items()): if p != q: return False return True return dict.__eq__(self, other) def __ne__(self, other):<|fim▁hole|><|fim▁end|>
return not self == other
<|file_name|>store.js<|end_file_name|><|fim▁begin|>import lowerCaseFirst from 'lower-case-first'; import {handles} from 'marty'; import Override from 'override-decorator'; function addHandlers(ResourceStore) { const {constantMappings} = this; return class ResourceStoreWithHandlers extends ResourceStore { @Override @handles(constantMappings.getMany.done) getManyDone(payload) { super.getManyDone(payload); this.hasChanged(); } @Override @handles(constantMappings.getSingle.done) getSingleDone(payload) { super.getSingleDone(payload); this.hasChanged(); } @handles( constantMappings.postSingle.done, constantMappings.putSingle.done, constantMappings.patchSingle.done ) changeSingleDone(args) { // These change actions may return the inserted or modified object, so // update that object if possible. if (args.result) { this.getSingleDone(args); } } }; } function addFetch( ResourceStore, { actionsKey = `${lowerCaseFirst(this.name)}Actions`<|fim▁hole|> } ) { const {methodNames, name, plural} = this; const {getMany, getSingle} = methodNames; const refreshMany = `refresh${plural}`; const refreshSingle = `refresh${name}`; return class ResourceStoreWithFetch extends ResourceStore { getActions() { return this.app[actionsKey]; } [getMany](options, {refresh} = {}) { return this.fetch({ id: `c${this.collectionKey(options)}`, locally: () => this.localGetMany(options), remotely: () => this.remoteGetMany(options), refresh }); } [refreshMany](options) { return this[getMany](options, {refresh: true}); } localGetMany(options) { return super[getMany](options); } remoteGetMany(options) { return this.getActions()[getMany](options); } [getSingle](id, options, {refresh} = {}) { return this.fetch({ id: `i${this.itemKey(id, options)}`, locally: () => this.localGetSingle(id, options), remotely: () => this.remoteGetSingle(id, options), refresh }); } [refreshSingle](id, options) { return this[getSingle](id, options, {refresh: true}); } localGetSingle(id, options) { return super[getSingle](id, options); } remoteGetSingle(id, options) { return this.getActions()[getSingle](id, options); } fetch({refresh, ...options}) { if (refresh) { const baseLocally = options.locally; options.locally = function refreshLocally() { if (refresh) { refresh = false; return undefined; } else { return this::baseLocally(); } }; } return super.fetch(options); } }; } export default function extendStore( ResourceStore, { useFetch = true, ...options } ) { ResourceStore = this::addHandlers(ResourceStore, options); if (useFetch) { ResourceStore = this::addFetch(ResourceStore, options); } return ResourceStore; }<|fim▁end|>
<|file_name|>MBSUPR.C<|end_file_name|><|fim▁begin|>/*** *mbsupr.c - Convert string upper case (MBCS) * * Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved. * *Purpose: * Convert string upper case (MBCS) * *******************************************************************************/ #ifdef _MBCS #if defined (_WIN32) #include <awint.h> #endif /* defined (_WIN32) */ #include <mtdll.h> #include <cruntime.h> #include <ctype.h> #include <mbdata.h> #include <mbstring.h> #include <mbctype.h> /*** * _mbsupr - Convert string upper case (MBCS) * *Purpose: * Converts all the lower case characters in a string * to upper case in place. Handles MBCS chars correctly. * *Entry: * unsigned char *string = pointer to string * *Exit: * Returns a pointer to the input string; no error return. * *Exceptions: * *******************************************************************************/ unsigned char * __cdecl _mbsupr( unsigned char *string ) { unsigned char *cp; _mlock(_MB_CP_LOCK); for (cp=string; *cp; cp++) { if (_ISLEADBYTE(*cp)) { <|fim▁hole|> unsigned char ret[4]; if ((retval = __crtLCMapStringA(__mblcid, LCMAP_UPPERCASE, cp, 2, ret, 2, __mbcodepage, TRUE)) == 0) { _munlock(_MB_CP_LOCK); return NULL; } *cp = ret[0]; if (retval > 1) *(++cp) = ret[1]; #else /* defined (_WIN32) */ int mbval = ((*cp) << 8) + *(cp+1); cp++; if ( mbval >= _MBLOWERLOW1 && mbval <= _MBLOWERHIGH1 ) *cp -= _MBCASEDIFF1; else if (mbval >= _MBLOWERLOW2 && mbval <= _MBLOWERHIGH2 ) *cp -= _MBCASEDIFF2; #endif /* defined (_WIN32) */ } else /* single byte, macro version */ *cp = (unsigned char) _mbbtoupper(*cp); } _munlock(_MB_CP_LOCK); return string ; } #endif /* _MBCS */<|fim▁end|>
#if defined (_WIN32) int retval;
<|file_name|>authenticator.js<|end_file_name|><|fim▁begin|>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview An UI component to authenciate to Chrome. The component hosts * IdP web pages in a webview. A client who is interested in monitoring * authentication events should pass a listener object of type * cr.login.GaiaAuthHost.Listener as defined in this file. After initialization, * call {@code load} to start the authentication flow. */ cr.define('cr.login', function() { 'use strict'; // TODO(rogerta): should use gaia URL from GaiaUrls::gaia_url() instead // of hardcoding the prod URL here. As is, this does not work with staging // environments. var IDP_ORIGIN = 'https://accounts.google.com/'; var IDP_PATH = 'ServiceLogin?skipvpage=true&sarp=1&rm=hide'; var CONTINUE_URL = 'chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/success.html'; var SIGN_IN_HEADER = 'google-accounts-signin'; var EMBEDDED_FORM_HEADER = 'google-accounts-embedded'; var SAML_HEADER = 'google-accounts-saml'; var LOCATION_HEADER = 'location'; /** * The source URL parameter for the constrained signin flow. */ var CONSTRAINED_FLOW_SOURCE = 'chrome'; /** * Enum for the authorization mode, must match AuthMode defined in * chrome/browser/ui/webui/inline_login_ui.cc. * @enum {number} */ var AuthMode = { DEFAULT: 0, OFFLINE: 1, DESKTOP: 2 }; /** * Enum for the authorization type. * @enum {number} */ var AuthFlow = { DEFAULT: 0, SAML: 1 }; /** * Initializes the authenticator component. * @param {webview|string} webview The webview element or its ID to host IdP * web pages. * @constructor */ function Authenticator(webview) { this.webview_ = typeof webview == 'string' ? $(webview) : webview; assert(this.webview_); this.email_ = null; this.password_ = null; this.gaiaId_ = null, this.sessionIndex_ = null; this.chooseWhatToSync_ = false; this.skipForNow_ = false; this.authFlow_ = AuthFlow.DEFAULT; this.loaded_ = false; this.idpOrigin_ = null; this.continueUrl_ = null; this.continueUrlWithoutParams_ = null;<|fim▁hole|> this.initialFrameUrl_ = null; this.reloadUrl_ = null; this.trusted_ = true; } // TODO(guohui,xiyuan): no need to inherit EventTarget once we deprecate the // old event-based signin flow. Authenticator.prototype = Object.create(cr.EventTarget.prototype); /** * Loads the authenticator component with the given parameters. * @param {AuthMode} authMode Authorization mode. * @param {Object} data Parameters for the authorization flow. */ Authenticator.prototype.load = function(authMode, data) { this.idpOrigin_ = data.gaiaUrl || IDP_ORIGIN; this.continueUrl_ = data.continueUrl || CONTINUE_URL; this.continueUrlWithoutParams_ = this.continueUrl_.substring(0, this.continueUrl_.indexOf('?')) || this.continueUrl_; this.isConstrainedWindow_ = data.constrained == '1'; this.initialFrameUrl_ = this.constructInitialFrameUrl_(data); this.reloadUrl_ = data.frameUrl || this.initialFrameUrl_; this.authFlow_ = AuthFlow.DEFAULT; this.webview_.src = this.reloadUrl_; this.webview_.addEventListener( 'newwindow', this.onNewWindow_.bind(this)); this.webview_.addEventListener( 'loadstop', this.onLoadStop_.bind(this)); this.webview_.request.onCompleted.addListener( this.onRequestCompleted_.bind(this), {urls: ['*://*/*', this.continueUrlWithoutParams_ + '*'], types: ['main_frame']}, ['responseHeaders']); this.webview_.request.onHeadersReceived.addListener( this.onHeadersReceived_.bind(this), {urls: [this.idpOrigin_ + '*'], types: ['main_frame']}, ['responseHeaders']); window.addEventListener( 'message', this.onMessageFromWebview_.bind(this), false); window.addEventListener( 'focus', this.onFocus_.bind(this), false); window.addEventListener( 'popstate', this.onPopState_.bind(this), false); }; /** * Reloads the authenticator component. */ Authenticator.prototype.reload = function() { this.webview_.src = this.reloadUrl_; this.authFlow_ = AuthFlow.DEFAULT; }; Authenticator.prototype.constructInitialFrameUrl_ = function(data) { var url = this.idpOrigin_ + (data.gaiaPath || IDP_PATH); url = appendParam(url, 'continue', this.continueUrl_); url = appendParam(url, 'service', data.service); if (data.hl) url = appendParam(url, 'hl', data.hl); if (data.email) url = appendParam(url, 'Email', data.email); if (this.isConstrainedWindow_) url = appendParam(url, 'source', CONSTRAINED_FLOW_SOURCE); return url; }; /** * Invoked when a main frame request in the webview has completed. * @private */ Authenticator.prototype.onRequestCompleted_ = function(details) { var currentUrl = details.url; if (currentUrl.lastIndexOf(this.continueUrlWithoutParams_, 0) == 0) { if (currentUrl.indexOf('ntp=1') >= 0) this.skipForNow_ = true; this.onAuthCompleted_(); return; } if (currentUrl.indexOf('https') != 0) this.trusted_ = false; if (this.isConstrainedWindow_) { var isEmbeddedPage = false; if (this.idpOrigin_ && currentUrl.lastIndexOf(this.idpOrigin_) == 0) { var headers = details.responseHeaders; for (var i = 0; headers && i < headers.length; ++i) { if (headers[i].name.toLowerCase() == EMBEDDED_FORM_HEADER) { isEmbeddedPage = true; break; } } } if (!isEmbeddedPage) { this.dispatchEvent(new CustomEvent('resize', {detail: currentUrl})); return; } } this.updateHistoryState_(currentUrl); // Posts a message to IdP pages to initiate communication. if (currentUrl.lastIndexOf(this.idpOrigin_) == 0) this.webview_.contentWindow.postMessage({}, currentUrl); }; /** * Manually updates the history. Invoked upon completion of a webview * navigation. * @param {string} url Request URL. * @private */ Authenticator.prototype.updateHistoryState_ = function(url) { if (history.state && history.state.url != url) history.pushState({url: url}, ''); else history.replaceState({url: url}); }; /** * Invoked when the sign-in page takes focus. * @param {object} e The focus event being triggered. * @private */ Authenticator.prototype.onFocus_ = function(e) { this.webview_.focus(); }; /** * Invoked when the history state is changed. * @param {object} e The popstate event being triggered. * @private */ Authenticator.prototype.onPopState_ = function(e) { var state = e.state; if (state && state.url) this.webview_.src = state.url; }; /** * Invoked when headers are received in the main frame of the webview. It * 1) reads the authenticated user info from a signin header, * 2) signals the start of a saml flow upon receiving a saml header. * @return {!Object} Modified request headers. * @private */ Authenticator.prototype.onHeadersReceived_ = function(details) { var headers = details.responseHeaders; for (var i = 0; headers && i < headers.length; ++i) { var header = headers[i]; var headerName = header.name.toLowerCase(); if (headerName == SIGN_IN_HEADER) { var headerValues = header.value.toLowerCase().split(','); var signinDetails = {}; headerValues.forEach(function(e) { var pair = e.split('='); signinDetails[pair[0].trim()] = pair[1].trim(); }); // Removes "" around. var email = signinDetails['email'].slice(1, -1); if (this.email_ != email) { this.email_ = email; // Clears the scraped password if the email has changed. this.password_ = null; } this.gaiaId_ = signinDetails['obfuscatedid'].slice(1, -1); this.sessionIndex_ = signinDetails['sessionindex']; } else if (headerName == SAML_HEADER) { this.authFlow_ = AuthFlow.SAML; } else if (headerName == LOCATION_HEADER) { // If the "choose what to sync" checkbox was clicked, then the continue // URL will contain a source=3 field. var location = decodeURIComponent(header.value); this.chooseWhatToSync_ = !!location.match(/(\?|&)source=3($|&)/); } } }; /** * Invoked when an HTML5 message is received from the webview element. * @param {object} e Payload of the received HTML5 message. * @private */ Authenticator.prototype.onMessageFromWebview_ = function(e) { // The event origin does not have a trailing slash. if (e.origin != this.idpOrigin_.substring(0, this.idpOrigin_ - 1)) { return; } var msg = e.data; if (msg.method == 'attemptLogin') { this.email_ = msg.email; this.password_ = msg.password; this.chooseWhatToSync_ = msg.chooseWhatToSync; } }; /** * Invoked to process authentication completion. * @private */ Authenticator.prototype.onAuthCompleted_ = function() { if (!this.email_ && !this.skipForNow_) { this.webview_.src = this.initialFrameUrl_; return; } this.dispatchEvent( new CustomEvent('authCompleted', {detail: {email: this.email_, gaiaId: this.gaiaId_, password: this.password_, usingSAML: this.authFlow_ == AuthFlow.SAML, chooseWhatToSync: this.chooseWhatToSync_, skipForNow: this.skipForNow_, sessionIndex: this.sessionIndex_ || '', trusted: this.trusted_}})); }; /** * Invoked when the webview attempts to open a new window. * @private */ Authenticator.prototype.onNewWindow_ = function(e) { this.dispatchEvent(new CustomEvent('newWindow', {detail: e})); }; /** * Invoked when the webview finishes loading a page. * @private */ Authenticator.prototype.onLoadStop_ = function(e) { if (!this.loaded_) { this.loaded_ = true; this.webview_.focus(); this.dispatchEvent(new Event('ready')); } }; Authenticator.AuthFlow = AuthFlow; Authenticator.AuthMode = AuthMode; return { // TODO(guohui, xiyuan): Rename GaiaAuthHost to Authenticator once the old // iframe-based flow is deprecated. GaiaAuthHost: Authenticator }; });<|fim▁end|>
<|file_name|>meg_csar_create.rs<|end_file_name|><|fim▁begin|>extern crate megam_api; extern crate rand; extern crate rustc_serialize; extern crate term_painter; extern crate yaml_rust; extern crate toml; use std::path::Path; use util::parse_csar::CConfig; use self::term_painter::ToStyle; use self::term_painter::Color::*; use megam_api::api::Api; use self::megam_api::util::csars::Csar; use self::megam_api::util::errors::MegResponse; use util::header_hash as head; use self::rustc_serialize::json; use std::str::from_utf8; #[derive(PartialEq, Clone, Debug)] pub struct CsarCoptions {<|fim▁hole|>} impl CsarCoptions { pub fn create(&self) { let file = from_utf8(self.file.as_bytes()).unwrap(); let path = Path::new(file).to_str().unwrap(); let we = CConfig; let data = we.load(path); let mut opts = Csar::new(); let api_call = head::api_call().unwrap(); opts.desc = data.unwrap_or("Error".to_string()); let out = opts.create(json::encode(&api_call).unwrap()); match out { Ok(v) => { let x = json::decode::<MegResponse>(&v).unwrap(); println!("{}", Green.paint("Successfully created your CSAR")); println!("----\n\nCode: {:?}\nMessage: {:?}\n\n----", x.code, x.msg); } Err(e) => { println!("{}", Red.bold().paint("Error: Not able to create CSAR.")); }}; } } impl CreateCSAR for CsarCoptions { fn new() -> CsarCoptions { CsarCoptions { file: "".to_string() } } } pub trait CreateCSAR { fn new() -> Self; }<|fim▁end|>
pub file: String,
<|file_name|>FindDomain.ts<|end_file_name|><|fim▁begin|>// import { Domain } from '../Domain'; // import { GetDomain } from './GetDomain'; // // /** // * Find domain from object or type // */ // export function FindDomain(target: Function | object): Domain | undefined { // let prototype; // if (typeof target === 'function') {<|fim▁hole|>// prototype = target; // } // // while (prototype) { // const domain = GetDomain(prototype); // if (domain) { // // console.log('FOUND'); // return domain; // } // // console.log('NOT FOUND!!!'); // prototype = Reflect.getPrototypeOf(prototype); // } // return; // }<|fim▁end|>
// prototype = target.prototype; // } else {
<|file_name|>basic_types.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 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<|fim▁hole|>use util::hash::H2048; /// Type for a 2048-bit log-bloom, as used by our blocks. pub type LogBloom = H2048; /// Constant 2048-bit datum for 0. Often used as a default. pub static ZERO_LOGBLOOM: LogBloom = H2048([0x00; 256]); #[cfg_attr(feature="dev", allow(enum_variant_names))] /// Semantic boolean for when a seal/signature is included. pub enum Seal { /// The seal/signature is included. With, /// The seal/signature is not included. Without, }<|fim▁end|>
// along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethcore basic typenames.
<|file_name|>ObjectFactory.java<|end_file_name|><|fim▁begin|>package eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Imported"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Manufacturer"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageImportedArticles"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageProducedArticles"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageOwnUser"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateTransporter"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageDirectlyExported"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateOnsite"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesYear_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Year"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6 * */ public ObjectFactory() { } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities } * */ public FLEXIBLERECORDEstimatedQuantities createFLEXIBLERECORDEstimatedQuantities() { return new FLEXIBLERECORDEstimatedQuantities(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection } * */ public FLEXIBLERECORDEstimatedQuantities.DataProtection createFLEXIBLERECORDEstimatedQuantitiesDataProtection() { return new FLEXIBLERECORDEstimatedQuantities.DataProtection(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TotalTonnage } * */ public FLEXIBLERECORDEstimatedQuantities.TotalTonnage createFLEXIBLERECORDEstimatedQuantitiesTotalTonnage() { return new FLEXIBLERECORDEstimatedQuantities.TotalTonnage(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DetailsTonnage } * */ public FLEXIBLERECORDEstimatedQuantities.DetailsTonnage createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnage() { return new FLEXIBLERECORDEstimatedQuantities.DetailsTonnage(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles } * */ public FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticles() { return new FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.AdditionalInformation } * */ public FLEXIBLERECORDEstimatedQuantities.AdditionalInformation createFLEXIBLERECORDEstimatedQuantitiesAdditionalInformation() { return new FLEXIBLERECORDEstimatedQuantities.AdditionalInformation(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation }<|fim▁hole|> } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Imported", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Manufacturer", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageImportedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageProducedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageOwnUser", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateTransporter", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageDirectlyExported", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateOnsite", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Year", scope = FLEXIBLERECORDEstimatedQuantities.class) public JAXBElement<BigInteger> createFLEXIBLERECORDEstimatedQuantitiesYear(BigInteger value) { return new JAXBElement<BigInteger>(_FLEXIBLERECORDEstimatedQuantitiesYear_QNAME, BigInteger.class, FLEXIBLERECORDEstimatedQuantities.class, value); } }<|fim▁end|>
* */ public FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation createFLEXIBLERECORDEstimatedQuantitiesDataProtectionLegislation() { return new FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation();
<|file_name|>BadgeUtils.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2016-2021 David Rubio Escares / Kodehawa * * Mantaro 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. * Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/ */ package net.kodehawa.mantarobot.commands.currency.profile; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class BadgeUtils { public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) { BufferedImage avatar; BufferedImage badge; try {<|fim▁hole|> } WritableRaster raster = badge.getRaster(); if (allWhite) { for (int xx = 0, width = badge.getWidth(); xx < width; xx++) { for (int yy = 0, height = badge.getHeight(); yy < height; yy++) { int[] pixels = raster.getPixel(xx, yy, (int[]) null); pixels[0] = 255; pixels[1] = 255; pixels[2] = 255; pixels[3] = pixels[3] == 255 ? 165 : 0; raster.setPixel(xx, yy, pixels); } } } BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); int circleCenterX = 88, circleCenterY = 88; int width = 32, height = 32; int circleRadius = 40; Graphics2D g2d = res.createGraphics(); g2d.drawImage(avatar, 0, 0, 128, 128, null); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(new Color(0, 0, 165, 165)); g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius); g2d.drawImage(badge, startX, startY, width, height, null); g2d.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(res, "png", baos); } catch (IOException e) { throw new AssertionError(e); } return baos.toByteArray(); } }<|fim▁end|>
avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes)); badge = ImageIO.read(new ByteArrayInputStream(badgeBytes)); } catch (IOException impossible) { throw new AssertionError(impossible);
<|file_name|>inotify.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <[email protected]> # Copyright 2012 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ :module: watchdog.observers.inotify :synopsis: ``inotify(7)`` based emitter implementation. :author: Sebastien Martini <[email protected]> :author: Luke McCarthy <[email protected]> :author: [email protected] (Yesudeep Mangalapilly) :author: Tim Cuthbertson <[email protected]> :platforms: Linux 2.6.13+. .. ADMONITION:: About system requirements Recommended minimum kernel version: 2.6.25. Quote from the inotify(7) man page: "Inotify was merged into the 2.6.13 Linux kernel. The required library interfaces were added to glibc in version 2.4. (IN_DONT_FOLLOW, IN_MASK_ADD, and IN_ONLYDIR were only added in version 2.5.)" Therefore, you must ensure the system is running at least these versions appropriate libraries and the kernel. .. ADMONITION:: About recursiveness, event order, and event coalescing Quote from the inotify(7) man page: If successive output inotify events produced on the inotify file descriptor are identical (same wd, mask, cookie, and name) then they are coalesced into a single event if the older event has not yet been read (but see BUGS). The events returned by reading from an inotify file descriptor form an ordered queue. Thus, for example, it is guaranteed that when renaming from one directory to another, events will be produced in the correct order on the inotify file descriptor. ... Inotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional watches must be created. This emitter implementation therefore automatically adds watches for sub-directories if running in recursive mode. Some extremely useful articles and documentation: .. _inotify FAQ: http://inotify.aiken.cz/?section=inotify&page=faq&lang=en .. _intro to inotify: http://www.linuxjournal.com/article/8478 """ from __future__ import with_statement import os import threading from .inotify_buffer import InotifyBuffer from watchdog.observers.api import ( EventEmitter, BaseObserver, DEFAULT_EMITTER_TIMEOUT, DEFAULT_OBSERVER_TIMEOUT ) from watchdog.events import ( DirDeletedEvent, DirModifiedEvent, DirMovedEvent, DirCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent, FileCreatedEvent, generate_sub_moved_events, generate_sub_created_events, ) from watchdog.utils import unicode_paths class InotifyEmitter(EventEmitter): """<|fim▁hole|> :param event_queue: The event queue to fill with events. :param watch: A watch object representing the directory to monitor. :type watch: :class:`watchdog.observers.api.ObservedWatch` :param timeout: Read events blocking timeout (in seconds). :type timeout: ``float`` """ def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT): EventEmitter.__init__(self, event_queue, watch, timeout) self._lock = threading.Lock() self._inotify = None def on_thread_start(self): path = unicode_paths.encode(self.watch.path) self._inotify = InotifyBuffer(path, self.watch.is_recursive) def on_thread_stop(self): if self._inotify: self._inotify.close() def queue_events(self, timeout, full_events=False): #If "full_events" is true, then the method will report unmatched move events as seperate events #This behavior is by default only called by a InotifyFullEmitter with self._lock: event = self._inotify.read_event() if event is None: return if isinstance(event, tuple): move_from, move_to = event src_path = self._decode_path(move_from.src_path) dest_path = self._decode_path(move_to.src_path) cls = DirMovedEvent if move_from.is_directory else FileMovedEvent self.queue_event(cls(src_path, dest_path)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) self.queue_event(DirModifiedEvent(os.path.dirname(dest_path))) if move_from.is_directory and self.watch.is_recursive: for sub_event in generate_sub_moved_events(src_path, dest_path): self.queue_event(sub_event) return src_path = self._decode_path(event.src_path) if event.is_moved_to: if (full_events): cls = DirMovedEvent if event.is_directory else FileMovedEvent self.queue_event(cls(None, src_path)) else: cls = DirCreatedEvent if event.is_directory else FileCreatedEvent self.queue_event(cls(src_path)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) if event.is_directory and self.watch.is_recursive: for sub_event in generate_sub_created_events(src_path): self.queue_event(sub_event) elif event.is_attrib: cls = DirModifiedEvent if event.is_directory else FileModifiedEvent self.queue_event(cls(src_path)) elif event.is_modify: cls = DirModifiedEvent if event.is_directory else FileModifiedEvent self.queue_event(cls(src_path)) elif event.is_delete or (event.is_moved_from and not full_events): cls = DirDeletedEvent if event.is_directory else FileDeletedEvent self.queue_event(cls(src_path)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) elif event.is_moved_from and full_events: cls = DirMovedEvent if event.is_directory else FileMovedEvent self.queue_event(cls(src_path, None)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) elif event.is_create: cls = DirCreatedEvent if event.is_directory else FileCreatedEvent self.queue_event(cls(src_path)) self.queue_event(DirModifiedEvent(os.path.dirname(src_path))) def _decode_path(self, path): """ Decode path only if unicode string was passed to this emitter. """ if isinstance(self.watch.path, bytes): return path return unicode_paths.decode(path) class InotifyFullEmitter(InotifyEmitter): """ inotify(7)-based event emitter. By default this class produces move events even if they are not matched Such move events will have a ``None`` value for the unmatched part. :param event_queue: The event queue to fill with events. :param watch: A watch object representing the directory to monitor. :type watch: :class:`watchdog.observers.api.ObservedWatch` :param timeout: Read events blocking timeout (in seconds). :type timeout: ``float`` """ def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT): InotifyEmitter.__init__(self, event_queue, watch, timeout) def queue_events(self, timeout, events=True): InotifyEmitter.queue_events(self, timeout, full_events=events) class InotifyObserver(BaseObserver): """ Observer thread that schedules watching directories and dispatches calls to event handlers. """ def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT, generate_full_events=False): if (generate_full_events): BaseObserver.__init__(self, emitter_class=InotifyFullEmitter, timeout=timeout) else: BaseObserver.__init__(self, emitter_class=InotifyEmitter, timeout=timeout)<|fim▁end|>
inotify(7)-based event emitter.
<|file_name|>event_client_impl.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/event_client_impl.h" #include "ash/session/session_state_delegate.h"<|fim▁hole|>#include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ui/aura/window.h" #include "ui/keyboard/keyboard_util.h" namespace ash { EventClientImpl::EventClientImpl() { } EventClientImpl::~EventClientImpl() { } bool EventClientImpl::CanProcessEventsWithinSubtree( const aura::Window* window) const { const aura::Window* root_window = window ? window->GetRootWindow() : NULL; if (!root_window || !Shell::GetInstance()->session_state_delegate()->IsUserSessionBlocked()) { return true; } const aura::Window* lock_screen_containers = Shell::GetContainer( root_window, kShellWindowId_LockScreenContainersContainer); const aura::Window* lock_background_containers = Shell::GetContainer( root_window, kShellWindowId_LockScreenBackgroundContainer); const aura::Window* lock_screen_related_containers = Shell::GetContainer( root_window, kShellWindowId_LockScreenRelatedContainersContainer); bool can_process_events = (window->Contains(lock_screen_containers) && window->Contains(lock_background_containers) && window->Contains(lock_screen_related_containers)) || lock_screen_containers->Contains(window) || lock_background_containers->Contains(window) || lock_screen_related_containers->Contains(window); if (keyboard::IsKeyboardEnabled()) { const aura::Window* virtual_keyboard_container = Shell::GetContainer( root_window, kShellWindowId_VirtualKeyboardContainer); can_process_events |= (window->Contains(virtual_keyboard_container) || virtual_keyboard_container->Contains(window)); } return can_process_events; } ui::EventTarget* EventClientImpl::GetToplevelEventTarget() { return Shell::GetInstance(); } } // namespace ash<|fim▁end|>
<|file_name|>delete_task_parameters.go<|end_file_name|><|fim▁begin|>package tasks // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" ) // NewDeleteTaskParams creates a new DeleteTaskParams object // with the default values initialized. func NewDeleteTaskParams() DeleteTaskParams { var () return DeleteTaskParams{} } // DeleteTaskParams contains all the bound params for the delete task operation // typically these are obtained from a http.Request // // swagger:parameters deleteTask type DeleteTaskParams struct { // HTTP Request Object HTTPRequest *http.Request /*The id of the item Required: true In: path */ ID int64 } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface // for simple values it will use straight method calls func (o *DeleteTaskParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { var res []error o.HTTPRequest = r rID, rhkID, _ := route.Params.GetOK("id") if err := o.bindID(rID, rhkID, route.Formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (o *DeleteTaskParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } value, err := swag.ConvertInt64(raw) if err != nil { return errors.InvalidType("id", "path", "int64", raw) }<|fim▁hole|> return nil }<|fim▁end|>
o.ID = value
<|file_name|>archive.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A helper class for dealing with static archives use std::io::process::{Command, ProcessOutput}; use std::io::{fs, TempDir}; use std::io; use std::os; use std::str; use syntax::abi; use ErrorHandler = syntax::diagnostic::Handler; pub static METADATA_FILENAME: &'static str = "rust.metadata.bin"; pub struct ArchiveConfig<'a> { pub handler: &'a ErrorHandler, pub dst: Path, pub lib_search_paths: Vec<Path>, pub os: abi::Os, pub maybe_ar_prog: Option<String> } pub struct Archive<'a> { handler: &'a ErrorHandler, dst: Path, lib_search_paths: Vec<Path>, os: abi::Os, maybe_ar_prog: Option<String> } fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>,<|fim▁hole|> let ar = match *maybe_ar_prog { Some(ref ar) => ar.as_slice(), None => "ar" }; let mut cmd = Command::new(ar); cmd.arg(args).args(paths); debug!("{}", cmd); match cwd { Some(p) => { cmd.cwd(p); debug!("inside {}", p.display()); } None => {} } match cmd.spawn() { Ok(prog) => { let o = prog.wait_with_output().unwrap(); if !o.status.success() { handler.err(format!("{} failed with: {}", cmd, o.status).as_slice()); handler.note(format!("stdout ---\n{}", str::from_utf8(o.output .as_slice()).unwrap()) .as_slice()); handler.note(format!("stderr ---\n{}", str::from_utf8(o.error .as_slice()).unwrap()) .as_slice()); handler.abort_if_errors(); } o }, Err(e) => { handler.err(format!("could not exec `{}`: {}", ar.as_slice(), e).as_slice()); handler.abort_if_errors(); fail!("rustc::back::archive::run_ar() should not reach this point"); } } } impl<'a> Archive<'a> { /// Initializes a new static archive with the given object file pub fn create<'b>(config: ArchiveConfig<'a>, initial_object: &'b Path) -> Archive<'a> { let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config; run_ar(handler, &maybe_ar_prog, "crus", None, [&dst, initial_object]); Archive { handler: handler, dst: dst, lib_search_paths: lib_search_paths, os: os, maybe_ar_prog: maybe_ar_prog } } /// Opens an existing static archive pub fn open(config: ArchiveConfig<'a>) -> Archive<'a> { let ArchiveConfig { handler, dst, lib_search_paths, os, maybe_ar_prog } = config; assert!(dst.exists()); Archive { handler: handler, dst: dst, lib_search_paths: lib_search_paths, os: os, maybe_ar_prog: maybe_ar_prog } } /// Adds all of the contents of a native library to this archive. This will /// search in the relevant locations for a library named `name`. pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> { let location = self.find_library(name); self.add_archive(&location, name, []) } /// Adds all of the contents of the rlib at the specified path to this /// archive. /// /// This ignores adding the bytecode from the rlib, and if LTO is enabled /// then the object file also isn't added. pub fn add_rlib(&mut self, rlib: &Path, name: &str, lto: bool) -> io::IoResult<()> { let object = format!("{}.o", name); let bytecode = format!("{}.bytecode.deflate", name); let mut ignore = vec!(bytecode.as_slice(), METADATA_FILENAME); if lto { ignore.push(object.as_slice()); } self.add_archive(rlib, name, ignore.as_slice()) } /// Adds an arbitrary file to this archive pub fn add_file(&mut self, file: &Path, has_symbols: bool) { let cmd = if has_symbols {"r"} else {"rS"}; run_ar(self.handler, &self.maybe_ar_prog, cmd, None, [&self.dst, file]); } /// Removes a file from this archive pub fn remove_file(&mut self, file: &str) { run_ar(self.handler, &self.maybe_ar_prog, "d", None, [&self.dst, &Path::new(file)]); } /// Updates all symbols in the archive (runs 'ar s' over it) pub fn update_symbols(&mut self) { run_ar(self.handler, &self.maybe_ar_prog, "s", None, [&self.dst]); } /// Lists all files in an archive pub fn files(&self) -> Vec<String> { let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, [&self.dst]); let output = str::from_utf8(output.output.as_slice()).unwrap(); // use lines_any because windows delimits output with `\r\n` instead of // just `\n` output.lines_any().map(|s| s.to_string()).collect() } fn add_archive(&mut self, archive: &Path, name: &str, skip: &[&str]) -> io::IoResult<()> { let loc = TempDir::new("rsar").unwrap(); // First, extract the contents of the archive to a temporary directory let archive = os::make_absolute(archive); run_ar(self.handler, &self.maybe_ar_prog, "x", Some(loc.path()), [&archive]); // Next, we must rename all of the inputs to "guaranteed unique names". // The reason for this is that archives are keyed off the name of the // files, so if two files have the same name they will override one // another in the archive (bad). // // We skip any files explicitly desired for skipping, and we also skip // all SYMDEF files as these are just magical placeholders which get // re-created when we make a new archive anyway. let files = try!(fs::readdir(loc.path())); let mut inputs = Vec::new(); for file in files.iter() { let filename = file.filename_str().unwrap(); if skip.iter().any(|s| *s == filename) { continue } if filename.contains(".SYMDEF") { continue } let filename = format!("r-{}-{}", name, filename); // LLDB (as mentioned in back::link) crashes on filenames of exactly // 16 bytes in length. If we're including an object file with // exactly 16-bytes of characters, give it some prefix so that it's // not 16 bytes. let filename = if filename.len() == 16 { format!("lldb-fix-{}", filename) } else { filename }; let new_filename = file.with_filename(filename); try!(fs::rename(file, &new_filename)); inputs.push(new_filename); } if inputs.len() == 0 { return Ok(()) } // Finally, add all the renamed files to this archive let mut args = vec!(&self.dst); args.extend(inputs.iter()); run_ar(self.handler, &self.maybe_ar_prog, "r", None, args.as_slice()); Ok(()) } fn find_library(&self, name: &str) -> Path { let (osprefix, osext) = match self.os { abi::OsWin32 => ("", "lib"), _ => ("lib", "a"), }; // On Windows, static libraries sometimes show up as libfoo.a and other // times show up as foo.lib let oslibname = format!("{}{}.{}", osprefix, name, osext); let unixlibname = format!("lib{}.a", name); for path in self.lib_search_paths.iter() { debug!("looking for {} inside {}", name, path.display()); let test = path.join(oslibname.as_slice()); if test.exists() { return test } if oslibname != unixlibname { let test = path.join(unixlibname.as_slice()); if test.exists() { return test } } } self.handler.fatal(format!("could not find native static library `{}`, \ perhaps an -L flag is missing?", name).as_slice()); } }<|fim▁end|>
args: &str, cwd: Option<&Path>, paths: &[&Path]) -> ProcessOutput {
<|file_name|>FiscalService.js<|end_file_name|><|fim▁begin|>(function () { 'use strict'; angular .module('tierraDeColoresApp') .service('fiscalService', fiscalService); fiscalService.$inject = ['$q', '$http', 'cookieService', 'BaseURL', 'toaster', '$rootScope']; function fiscalService($q, $http, cookieService, BaseURL, toaster, $rootScope) { const exec = require('child_process').exec; const http = require('http'); const fs = require('fs'); const path = require('path'); var parser = document.createElement('a'); parser.href = BaseURL; var Auth = { 'usuario': 'AFIP_SMH/P-441F', 'password': 'T13RR4$7j15vker4L-L' }; this.read = function () { var datosRecu = null; var deferred = $q.defer(); var filePath = path.join(__dirname, 'FILE.ans'); fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) { if (!err) { datosRecu = data; deferred.resolve(datosRecu); } }); return deferred.promise; }; function print(tipo) { exec('wspooler.exe -p4 -l -f FILE.200', function (err, stdout, stderr) { if (err !== null) { console.log(err); $rootScope.$broadcast("printState", {tipo: tipo, status: false}); } else { $rootScope.$broadcast("printState", {tipo: tipo, status: true}); } }); } this.cleanFiles = function () { fs.unlink('FILE.200', function (err) { if (err) { console.log(err); } console.log('successfully deleted FILE.200'); });<|fim▁hole|> if (err) { console.log(err); } console.log('successfully deleted FILE.ans'); }); return true; }; this.factura_aOrFactura_b = function (factura, cliente, type) { var options = null; var token = cookieService.get('token'); var tipo; token.then(function (data) { options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (type === 0) { options.path = '/fiscal/factura_a?factura=' + factura + "&cliente=" + cliente; tipo = "Factura A"; } else if (1) { options.path = '/fiscal/factura_b?factura=' + factura + "&cliente=" + cliente; tipo = "Factura B"; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(tipo); } }); }); }; this.ticketOrRegalo = function (factura, serial) { var token = cookieService.get('token'); var type; token.then(function (data) { var options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (serial !== null & typeof serial !== 'undefined') { options.path = '/fiscal/regalo?factura=' + factura + "&serial=" + serial; type = "Regalo"; } else { options.path = '/fiscal/ticket?factura=' + factura; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(); } }); }); }; this.comprobanteZ = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f compZ.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; this.isConnected = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f CONNECTED.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; } })();<|fim▁end|>
fs.unlink('FILE.ans', function (err) {
<|file_name|>translation.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE TS> <TS> <context> <name>design/eziog/comment/view</name> <message> <source>Avatar</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> <message> <source>Delete</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/draft</name> <message> <source>Select all</source> <translation></translation> </message> <message> <source>Deselect all</source> <translation></translation> </message> <message> <source>My drafts</source> <translation></translation> </message> <message> <source>Empty draft</source> <translation></translation> </message> <message> <source>Name</source> <translation></translation> </message> <message> <source>Class</source> <translation></translation> </message> <message> <source>Section</source> <translation></translation> </message> <message> <source>Version</source> <translation></translation> </message> <message> <source>Language</source> <translation></translation> </message> <message> <source>Last modified</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> <message> <source>Remove</source> <translation></translation> </message> <message> <source>You have no drafts</source> <translation></translation> </message> </context> <context> <name>design/eziog/collectedinfo/form</name> <message> <source>You have already submitted this form. The data you entered was:</source> <translation></translation> </message> <message> <source>Return to site</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/history</name> <message> <source>Translations</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/edit_draft</name> <message> <source>Current drafts</source> <translation></translation> </message> <message> <source>Version</source> <translation></translation> </message> <message> <source>Name</source> <translation></translation> </message> <message> <source>Owner</source> <translation></translation> </message> <message> <source>Created</source> <translation></translation> </message> <message> <source>Last modified</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> <message> <source>New draft</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/search</name> <message> <source>Search</source> <translation></translation> </message> <message> <source>The following words were excluded from the search:</source> <translation></translation> </message> <message> <source>Search tips</source> <translation></translation> </message> <message> <source>Check spelling of keywords.</source> <translation></translation> </message> <message> <source>Try changing some keywords (eg, "car" instead of "cars").</source> <translation></translation> </message> <message> <source>Try searching with less specific keywords.</source> <translation></translation> </message> <message> <source>Reduce number of keywords to get more results.</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/advancedsearch</name> <message> <source>Display per page</source> <translation></translation> </message> <message> <source>Search</source> <translation></translation> </message> </context> <context> <name>design/eziog/collectedinfomail/feedback</name> <message> <source>The following feedback was collected</source> <translation></translation> </message> </context> <context> <name>design/eziog/collectedinfomail/form</name> <message> <source>The following information was collected</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/tipafriend</name> <message> <source>Tip a friend</source> <translation></translation> </message> <message> <source>The message was sent.</source> <translation></translation> </message> <message> <source>Click here to return to the original page.</source> <translation></translation> </message> <message> <source>The message was not sent.</source> <translation></translation> </message> <message> <source>The message was not sent due to an unknown error. Please notify the site administrator about this error.</source> <translation></translation> </message> <message> <source>Please correct the following errors:</source> <translation></translation> </message> <message> <source>Your name</source> <translation></translation> </message> <message> <source>Your email address</source> <translation></translation> </message> <message> <source>Recipient's email address</source> <translation></translation> </message> <message> <source>Comment</source> <translation></translation> </message> <message> <source>Send</source> <translation></translation> </message> <message> <source>Cancel</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/pendinglist</name> <message> <source>Name</source> <translation></translation> </message> <message> <source>Class</source> <translation></translation> </message> <message> <source>Section</source> <translation></translation> </message> <message> <source>Version</source> <translation></translation> </message> <message> <source>Last modified</source> <translation></translation> </message> <message> <source>Your pending list is empty</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/browse</name> <message> <source>Select</source> <translation></translation> </message> </context> <context> <name>design/eziog/content/edit_languages</name> <message> <source>Existing languages</source> <translation></translation> </message> <message> <source>Select the language you want to use when editing the object.</source> <translation></translation> </message> <message> <source>New languages</source> <translation></translation> </message> <message> <source>Select the language you want to add to the object.</source> <translation></translation> </message> <message> <source>Select the language the new translation will be based on.</source> <translation></translation> </message> <message> <source>Use an empty, untranslated draft</source> <translation></translation> </message> <message> <source>You do not have permission to create a translation in another language.</source> <translation></translation> </message> <message> <source>However, you can select one of the following languages for editing.</source> <translation></translation> </message> <message> <source>You do not have permission to edit the object in any available languages.</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> <message> <source>Cancel</source> <translation></translation> </message> </context> <context> <name>design/eziog/view/sitemap</name> <message> <source>Site map</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/article</name> <message> <source>Comments</source> <translation></translation> </message> <message> <source>Related content</source> <translation></translation> </message> </context> <context> <name>design/eziog/node/removeobject</name> <message> <source>Are you sure you want to remove these items?</source> <translation></translation> </message> <message> <source>Move to trash</source> <translation></translation> </message> <message> <source>Note</source> <translation></translation> </message> </context> <context> <name>design/eziog/notification/addingresult</name> <message> <source>OK</source> <translation></translation> </message> </context> <context> <name>design/eziog/notification/settings</name> <message> <source>Apply changes</source> <translation></translation> </message> </context> <context> <name>design/eziog/ezodf/browse_place</name> <message> <source>Choose document placement</source> <translation></translation> </message> </context> <context> <name>design/eziog/ezodf/export</name> <message> <source>OpenOffice.org export</source> <translation></translation> </message> <message> <source>Export eZ publish content to OpenOffice.org</source> <translation></translation> </message> <message> <source>Error</source> <translation></translation> </message> <message> <source>Here you can export any eZ publish content object to an OpenOffice.org Writer document format.</source> <translation></translation> </message> <message> <source>Export Object</source> <translation></translation> </message> </context> <context> <name>design/eziog/rss/edit_import</name> <message> <source>Name of the RSS import. This name is used in the Administration Interface only, to distinguish the different imports from each other.</source> <translation></translation> </message> <message> <source>Use this field to enter the source URL of the RSS feed to import.</source> <translation></translation> </message> <message> <source>Click this button to proceed and analyze the import feed.</source> <translation></translation> </message> <message> <source>Click this button to select the destination node where objects created by the import are located.</source> <translation></translation> </message> <message> <source>Click this button to select the user who should own the objects created by the import.</source> <translation></translation> </message> <message> <source>Click this button to load the correct values into the drop-down fields below. Use the drop-down menu on the left to select the class.</source> <translation></translation> </message> <message> <source>Use this drop-down menu to select the attribute that should bet set as information from the RSS stream.</source> <translation></translation> </message> <message> <source>Use this checkbox to control if the RSS feed is active or not. An inactive feed will not be automatically updated.</source> <translation></translation> </message> <message> <source>Apply the changes and return to the RSS overview.</source> <translation></translation> </message> <message> <source>Cancel the changes and return to the RSS overview.</source> <translation></translation> </message> </context> <context> <name>design/eziog/rss/edit_export</name> <message> <source>Name of the RSS export. This name is used in the Administration Interface only, to distinguish the different exports from each other.</source> <translation></translation> </message> <message> <source>Use the description field to write a text explaining what users can expect from the RSS export.</source> <translation></translation> </message> <message> <source>Click this button to select an image for the RSS export. Note that images only work with RSS version 2.0</source> <translation></translation> </message> <message> <source>Click to remove image from RSS export.</source> <translation></translation> </message> <message> <source>Use this drop-down menu to select the RSS version to use for the export. You must select RSS 2.0 in order to export the image selected above.</source> <translation></translation> </message> <message> <source>Use this drop-down to select the maximum number of objects included in the RSS feed.</source> <translation></translation> </message> <message> <source>Use this checkbox to control if the RSS export is active or not. An inactive export will not be automatically updated.</source> <translation></translation> </message> <message> <source>Check if you want to only feed the object from the main node.</source> <translation></translation> </message> <message> <source>Click this button to select the source node for the RSS export source. Objects of the type selected in the drop-down below published as sub items of the selected node will be included in the RSS export.</source> <translation></translation> </message> <message> <source>Activate this checkbox if objects from the subnodes of the source should also be fed.</source> <translation></translation> </message> <message> <source>Click this button to load the correct values into the drop-down fields below. Use the drop-down menu on the left to select the class.</source> <translation></translation> </message> <message> <source>Use this drop-down to select the attribute that should be exported as the title of the RSS export entry.</source> <translation></translation> </message> <message> <source>Use this drop-down to select the attribute that should be exported as the description of the RSS export entry.</source> <translation></translation> </message> <message> <source>Skip</source> <translation></translation> </message> <message> <source>Use this drop-down to select the attribute that should be exported as the category of the RSS export entry.</source> <translation></translation> </message> <message> <source>Click to remove this source from the RSS export.</source> <translation></translation> </message> <message> <source>Click to add a new source to the RSS export.</source> <translation></translation> </message> <message> <source>Apply the changes and return to the RSS overview.</source> <translation></translation> </message> <message> <source>Cancel the changes and return to the RSS overview.</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/password</name> <message> <source>Change password for user</source> <translation></translation> </message> <message> <source>Please retype your old password.</source> <translation></translation> </message> <message> <source>Password didn't match, please retype your new password.</source> <translation></translation> </message> <message> <source>Password successfully updated.</source> <translation></translation> </message> <message> <source>Old password</source> <translation></translation> </message> <message> <source>New password</source> <translation></translation> </message> <message> <source>Retype password</source> <translation></translation> </message> <message> <source>OK</source> <translation></translation> </message> <message> <source>Cancel</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/activate</name> <message> <source>Activate account</source> <translation></translation> </message> </context> <context> <name>design/standard/user</name> <message> <source>Your email address has been confirmed. An administrator needs to approve your sign up request, before your login becomes valid.</source> <translation></translation> </message> <message> <source>Your account is now activated.</source> <translation></translation> </message> <message> <source>Your account is already active.</source> <translation></translation> </message> <message> <source>Sorry, the key submitted was not a valid key. Account was not activated.</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/success</name> <message> <source>User registered</source> <translation></translation> </message> <message> <source>Your account was successfully created. An email will be sent to the specified address. Follow the instructions in that email to activate your account.</source> <translation></translation> </message> <message> <source>Your account was successfully created.</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/edit</name> <message> <source>User profile</source> <translation></translation> </message> <message> <source>Username</source> <translation></translation> </message> <message> <source>Email</source> <translation></translation> </message> <message> <source>Name</source> <translation></translation> </message> <message> <source>My drafts</source> <translation></translation> </message> <message> <source>My orders</source> <translation></translation> </message> <message> <source>My pending items</source> <translation></translation> </message> <message> <source>My notification settings</source> <translation></translation> </message> <message> <source>My wish list</source> <translation></translation> </message> <message> <source>Edit profile</source> <translation></translation> </message> <message> <source>Change password</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/login</name> <message> <source>Login</source> <translation></translation> </message> <message> <source>Could not login</source> <translation></translation> </message> <message> <source>A valid username and password is required to login.</source> <translation></translation> </message> <message> <source>Access not allowed</source> <translation></translation> </message> <message> <source>Password</source> <translation></translation> </message> <message> <source>Log in to the eZ Publish Administration Interface</source> <translation></translation> </message> <message> <source>Remember me</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/login",'User name</name> <message> <source>Username</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/login','Button</name> <message> <source>Login</source> <translation></translation> </message> <message> <source>Sign up</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/forgotpassword</name> <message> <source>There is no registered user with that email address.</source> <translation></translation> </message> <message> <source>The key is invalid or has been used. </source> <translation></translation> </message> <message> <source>Have you forgotten your password?</source> <translation></translation> </message> <message> <source>If you have forgotten your password, enter your email address and we will create a new password and send it to you.</source> <translation></translation> </message> <message> <source>Email</source> <translation></translation> </message> <message> <source>Generate new password</source> <translation></translation> </message> </context> <context> <name>design/eziog/user/register</name> <message> <source>Register user</source> <translation></translation> </message> <message> <source>Input did not validate</source> <translation></translation> </message> <message> <source>Input was stored successfully</source> <translation></translation> </message> <message> <source>Register</source> <translation></translation> </message> <message> <source>Discard</source> <translation></translation> </message> <message> <source>Unable to register new user</source> <translation></translation> </message> <message> <source>Back</source> <translation></translation> </message> </context> <context> <name>design/eziog/article/comments</name> <message> <source>Comments</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/image</name> <message> <source>Related content</source> <translation></translation> </message> </context> <context> <name>design/eziog/blog/calendar</name> <message> <source>Previous month</source> <translation></translation> </message> <message> <source>Next month</source> <translation></translation> </message> <message> <source>Calendar</source> <translation></translation> </message> <message> <source>Mon</source> <translation></translation> </message> <message> <source>Tue</source> <translation></translation> </message> <message> <source>Wed</source> <translation></translation> </message> <message> <source>Thu</source> <translation></translation> </message> <message> <source>Fri</source> <translation></translation> </message> <message> <source>Sat</source> <translation></translation> </message> <message> <source>Sun</source> <translation></translation> </message> </context> <context> <name>design/eziog/blog/extra_info</name> <message> <source>Tag cloud</source> <translation></translation> </message> <message> <source>Description</source> <translation></translation> </message> <message> <source>Tags</source> <translation></translation> </message> <message> <source>Archive</source> <translation></translation> </message> </context> <context> <name>design/eziog/ezinfo/about</name> <message> <source>Third-Party Software</source> <translation></translation> </message> <message> <source>Extensions</source> <translation></translation> </message> </context> <context> <name>design/eziog/footer/latest_news</name> <message> <source>Latest News</source> <translation></translation> </message> </context> <context> <name>design/eziog/footer/address</name> <message> <source>Get in touch</source> <translation></translation> </message> </context> <context> <name>design/eziog/footer/impressum</name> <message> <source>eZ Links</source> <translation></translation> </message> </context> <context> <name>design/eziog/footer/links</name> <message> <source>eZ Links</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/event_view_program</name> <message> <source>Past events</source> <translation></translation> </message> <message> <source>Future events</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/event_view_calendar</name> <message> <source>Mon</source> <translation></translation> </message> <message> <source>Tue</source> <translation></translation> </message> <message> <source>Wed</source> <translation></translation> </message> <message> <source>Thu</source> <translation></translation> </message> <message> <source>Fri</source> <translation></translation> </message> <message> <source>Sat</source> <translation></translation> </message> <message> <source>Sun</source> <translation></translation> </message> <message> <source>Today</source> <translation></translation> </message> <message> <source>Category</source> <translation></translation> </message> <message> <source>Show All Events..</source> <translation></translation> </message> </context> <context> <name>design/eziog/pagelayout</name> <message> <source>Tag cloud</source> <translation></translation> </message> <message> <source>Site map</source> <translation></translation> </message> <message> <source>Shopping basket</source> <translation></translation> </message> <message> <source>My profile</source> <translation></translation> </message> <message> <source>Logout</source> <translation></translation> </message> <message> <source>Register</source> <translation></translation> </message> <message> <source>Login</source> <translation></translation> </message> <message> <source>Username</source> <translation></translation> </message> <message> <source>Password</source> <translation></translation> </message> <message> <source>Forgot your password?</source> <translation></translation> </message> <message> <source>Search</source> <translation></translation> </message> <message> <source>Search text</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/wishlist</name> <message> <source>Wish list</source> <translation></translation> </message> <message> <source>Product</source> <translation></translation> </message> <message> <source>Count</source> <translation></translation> </message> <message> <source>Selected options</source> <translation></translation> </message> <message> <source>Store</source> <translation></translation> </message> <message> <source>Remove items</source> <translation></translation> </message> <message> <source>Empty wish list</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/confirmorder</name> <message> <source>Shopping basket</source> <translation></translation> </message> <message> <source>Account information</source> <translation></translation> </message> <message> <source>Confirm order</source> <translation></translation> </message> <message> <source>Product items</source> <translation></translation> </message> <message> <source>Count</source> <translation></translation> </message> <message> <source>VAT</source> <translation></translation> </message> <message> <source>Price inc. VAT</source> <translation></translation> </message> <message> <source>Discount</source> <translation></translation> </message> <message> <source>Total price ex. VAT</source> <translation></translation> </message> <message> <source>Total price inc. VAT</source> <translation></translation> </message> <message> <source>Selected options</source> <translation></translation> </message> <message> <source>Order summary</source> <translation></translation> </message> <message> <source>Summary</source> <translation></translation> </message> <message> <source>Total ex. VAT</source> <translation></translation> </message> <message> <source>Total inc. VAT</source> <translation></translation> </message> <message> <source>Subtotal of items</source> <translation></translation> </message> <message> <source>Order total</source> <translation></translation> </message> <message> <source>Cancel</source> <translation></translation> </message> <message> <source>Confirm</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/customerorderview</name> <message> <source>Customer information</source> <translation></translation> </message> <message> <source>Order list</source> <translation></translation> </message> <message> <source>ID</source> <translation></translation> </message> <message> <source>Date</source> <translation></translation> </message> <message> <source>Total ex. VAT</source> <translation></translation> </message> <message> <source>Total inc. VAT</source> <translation></translation> </message> <message> <source>Purchase list</source> <translation></translation> </message> <message> <source>Product</source> <translation></translation> </message> <message> <source>Amount</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/orderlist</name> <message> <source>Order list</source> <translation></translation> </message> <message> <source>Sort result by</source> <translation></translation> </message> <message> <source>Order time</source> <translation></translation> </message> <message> <source>User name</source> <translation></translation> </message> <message> <source>Order ID</source> <translation></translation> </message> <message> <source>Ascending</source> <translation></translation> </message> <message> <source>Sort ascending</source> <translation></translation> </message> <message> <source>Descending</source> <translation></translation> </message> <message> <source>Sort descending</source> <translation></translation> </message> <message> <source>ID</source> <translation></translation> </message> <message> <source>Date</source> <translation></translation> </message> <message> <source>Customer</source> <translation></translation> </message> <message> <source>Total ex. VAT</source> <translation></translation> </message> <message> <source>Total inc. VAT</source> <translation></translation> </message> <message> <source>The order list is empty</source> <translation></translation> </message> <message> <source>Archive</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/userregister</name> <message> <source>Shopping basket</source> <translation></translation> </message> <message> <source>Account information</source> <translation></translation> </message> <message> <source>Confirm order</source> <translation></translation> </message> <message> <source>Your account information</source> <translation></translation> </message> <message> <source>Input did not validate. All fields marked with * must be filled in.</source> <translation></translation> </message> <message> <source>First name</source> <translation></translation> </message> <message> <source>Last name</source> <translation></translation> </message> <message> <source>Email</source> <translation></translation> </message> <message> <source>Company</source> <translation></translation> </message> <message> <source>Street</source> <translation></translation> </message> <message> <source>Zip</source> <translation></translation> </message> <message> <source>Place</source> <translation></translation> </message> <message> <source>State</source> <translation></translation> </message> <message> <source>Country</source> <translation></translation> </message> <message> <source>Comment</source> <translation></translation> </message> <message> <source>Cancel</source> <translation></translation> </message> <message> <source>All fields marked with * must be filled in.</source> <translation></translation> </message> </context> <context> <name>design/eziog/shop/basket</name> <message> <source>Shopping basket</source> <translation></translation> </message> <message> <source>Account information</source> <translation></translation> </message> <message> <source>Confirm order</source> <translation></translation> </message> <message> <source>Basket</source> <translation></translation> </message> <message> <source>Count</source> <translation></translation> </message> <message> <source>VAT</source> <translation></translation> </message> <message> <source>Price inc. VAT</source> <translation></translation> </message> <message> <source>Discount</source> <translation></translation> </message> <message> <source>Total price ex. VAT</source> <translation></translation> </message> <message> <source>Total price inc. VAT</source> <translation></translation> </message> <message> <source>Update</source> <translation></translation> </message> <message> <source>Remove</source> <translation></translation> </message> <message> <source>Selected options</source> <translation></translation> </message> <message> <source>Subtotal ex. VAT</source> <translation></translation> </message> <message> <source>Subtotal inc. VAT</source> <translation></translation> </message> <message> <source>Continue shopping</source> <translation></translation> </message> <message> <source>Checkout</source> <translation></translation> </message> <message> <source>You have no products in your basket.</source> <translation></translation> </message> </context> <context> <name>design/eziog/link</name> <message> <source>Printable version</source> <translation></translation> </message> </context> <context> <name>design/eziog/simplified_treemenu/show_simplified_menu</name> <message> <source>Fold/Unfold</source> <translation></translation> </message> </context> <context> <name>design/eziog/embed/forum</name> <message> <source>Latest from</source> <translation></translation> </message> </context> <context> <name>design/eziog/embed/poll</name> <message> <source>Vote</source> <translation></translation> </message> </context> <context> <name>design/eziog/colledtedinfomail</name> <message> <source>The following information was collected</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/product</name> <message> <source>Amount</source> <translation></translation> </message> <message> <source>Add to basket</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/feedback_form</name> <message> <source>Send form</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/poll</name> <message> <source>Vote</source> <translation></translation> </message> <message> <source>Result</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/forum_topic</name> <message> <source>Author</source> <translation></translation> </message> <message> <source>Message</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/event</name> <message> <source>Category</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/forum_reply</name> <message> <source>Message preview</source> <translation></translation> </message> <message> <source>Author</source> <translation></translation> </message> <message> <source>Topic</source> <translation></translation> </message> <message> <source>Location</source> <translation></translation> </message> <message> <source>Moderated by</source> <translation></translation> </message> <message> <source>Edit</source> <translation></translation> </message> </context> <context> <name>design/eziog/full/call_to_action</name> <message> <source>Submit</source> <translation></translation> </message> </context> <context> <name>design/eziog/block/feedback_form</name> <message> <source>Send form</source> <translation></translation> </message> </context> <context> <name>design/ezflow/embed/poll</name> <message> <source>Vote</source> <translation></translation> </message> </context> <context> <name>design/eziog/block_item/product</name> <message> <source>Amount</source> <translation></translation> </message> <message> <source>Buy</source> <translation></translation> </message> </context> <context> <name>design/eziog/edit/file</name> <message> <source>Send for publishing</source> <translation></translation> </message> <message> <source>Discard</source> <translation></translation> </message> </context> <context> <name>design/eziog/edit/forum_topic</name> <message> <source>Send for publishing</source> <translation></translation> </message> <message> <source>Discard</source> <translation></translation> </message> </context> <context><|fim▁hole|> <message> <source>Send for publishing</source> <translation></translation> </message> <message> <source>Discard</source> <translation></translation> </message> </context> <context> <name>design/eziog/edit/forum_reply</name> <message> <source>Send for publishing</source> <translation></translation> </message> <message> <source>Discard</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/blog_post</name> <message> <source>Tags:</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/silverlight</name> <message> <source>View</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/forum</name> <message> <source>Number of topics</source> <translation></translation> </message> <message> <source>Number of posts</source> <translation></translation> </message> <message> <source>Enter forum</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/product</name> <message> <source>Amount</source> <translation></translation> </message> <message> <source>Buy</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/windows_media</name> <message> <source>View movie</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/real_video</name> <message> <source>View movie</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/flash</name> <message> <source>View flash</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/quicktime</name> <message> <source>View movie</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/poll</name> <message> <source>Vote</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/event</name> <message> <source>Category</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/forum_reply</name> <message> <source>Reply to:</source> <translation></translation> </message> </context> <context> <name>design/eziog/line/event_calendar</name> <message> <source>Next events</source> <translation></translation> </message> </context> </TS><|fim▁end|>
<name>design/eziog/edit/comment</name>
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A windowing implementation using glutin. use compositing::compositor_task::{self, CompositorProxy, CompositorReceiver}; use compositing::windowing::{WindowEvent, WindowMethods}; use euclid::scale_factor::ScaleFactor; use euclid::size::{Size2D, TypedSize2D}; use gleam::gl; use glutin; use layers::geometry::DevicePixel; use layers::platform::surface::NativeGraphicsMetadata; use msg::constellation_msg; use msg::constellation_msg::Key; use net::net_error_list::NetError; use std::rc::Rc; use std::sync::mpsc::{channel, Sender}; use url::Url; use util::cursor::Cursor; use util::geometry::ScreenPx; use NestedEventLoopListener; #[cfg(feature = "window")] use compositing::windowing::{MouseWindowEvent, WindowNavigateMsg}; #[cfg(feature = "window")] use euclid::point::Point2D; #[cfg(feature = "window")] use glutin::{Api, ElementState, Event, GlRequest, MouseButton, VirtualKeyCode, MouseScrollDelta}; #[cfg(feature = "window")] use msg::constellation_msg::{KeyState, CONTROL, SHIFT, ALT}; #[cfg(feature = "window")] use std::cell::{Cell, RefCell}; #[cfg(feature = "window")] use util::opts; #[cfg(all(feature = "headless", target_os="linux"))] use std::ptr; #[cfg(feature = "window")] static mut g_nested_event_loop_listener: Option<*mut (NestedEventLoopListener + 'static)> = None; #[cfg(feature = "window")] bitflags! { flags KeyModifiers: u8 { const LEFT_CONTROL = 1, const RIGHT_CONTROL = 2, const LEFT_SHIFT = 4, const RIGHT_SHIFT = 8, const LEFT_ALT = 16, const RIGHT_ALT = 32, } } /// The type of a window. #[cfg(feature = "window")] pub struct Window { window: glutin::Window, mouse_down_button: Cell<Option<glutin::MouseButton>>, mouse_down_point: Cell<Point2D<i32>>, event_queue: RefCell<Vec<WindowEvent>>, mouse_pos: Cell<Point2D<i32>>, key_modifiers: Cell<KeyModifiers>, } #[cfg(feature = "window")] impl Window { pub fn new(is_foreground: bool, window_size: TypedSize2D<DevicePixel, u32>, parent: glutin::WindowID) -> Rc<Window> { let mut glutin_window = glutin::WindowBuilder::new() .with_title("Servo".to_string()) .with_dimensions(window_size.to_untyped().width, window_size.to_untyped().height) .with_gl(Window::gl_version()) .with_visibility(is_foreground) .with_parent(parent) .build() .unwrap(); unsafe { glutin_window.make_current() }; glutin_window.set_window_resize_callback(Some(Window::nested_window_resize as fn(u32, u32))); Window::load_gl_functions(&glutin_window); let window = Window { window: glutin_window, event_queue: RefCell::new(vec!()), mouse_down_button: Cell::new(None), mouse_down_point: Cell::new(Point2D::new(0, 0)), mouse_pos: Cell::new(Point2D::new(0, 0)), key_modifiers: Cell::new(KeyModifiers::empty()), }; gl::clear_color(0.6, 0.6, 0.6, 1.0); gl::clear(gl::COLOR_BUFFER_BIT); gl::finish(); window.present(); Rc::new(window) } pub fn platform_window(&self) -> glutin::WindowID { unsafe { self.window.platform_window() } } fn nested_window_resize(width: u32, height: u32) { unsafe { match g_nested_event_loop_listener { None => {} Some(listener) => { (*listener).handle_event_from_nested_event_loop( WindowEvent::Resize(Size2D::typed(width, height))); } } } } #[cfg(not(target_os="android"))] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGl, (3, 0)) } #[cfg(target_os="android")] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGlEs, (2, 0)) } #[cfg(not(target_os="android"))] fn load_gl_functions(window: &glutin::Window) { gl::load_with(|s| window.get_proc_address(s)); } #[cfg(target_os="android")] fn load_gl_functions(_: &glutin::Window) { } fn handle_window_event(&self, event: glutin::Event) -> bool { match event { Event::KeyboardInput(element_state, _scan_code, virtual_key_code) => { if virtual_key_code.is_some() { let virtual_key_code = virtual_key_code.unwrap(); match (element_state, virtual_key_code) { (_, VirtualKeyCode::LControl) => self.toggle_modifier(LEFT_CONTROL), (_, VirtualKeyCode::RControl) => self.toggle_modifier(RIGHT_CONTROL), (_, VirtualKeyCode::LShift) => self.toggle_modifier(LEFT_SHIFT), (_, VirtualKeyCode::RShift) => self.toggle_modifier(RIGHT_SHIFT), (_, VirtualKeyCode::LAlt) => self.toggle_modifier(LEFT_ALT), (_, VirtualKeyCode::RAlt) => self.toggle_modifier(RIGHT_ALT), (ElementState::Pressed, VirtualKeyCode::Escape) => return true, (_, key_code) => { match Window::glutin_key_to_script_key(key_code) { Ok(key) => { let state = match element_state { ElementState::Pressed => KeyState::Pressed, ElementState::Released => KeyState::Released, }; let modifiers = Window::glutin_mods_to_script_mods(self.key_modifiers.get()); self.event_queue.borrow_mut().push(WindowEvent::KeyEvent(key, state, modifiers)); } _ => {} } } } } } Event::Resized(width, height) => { self.event_queue.borrow_mut().push(WindowEvent::Resize(Size2D::typed(width, height))); } Event::MouseInput(element_state, mouse_button) => { if mouse_button == MouseButton::Left || mouse_button == MouseButton::Right { let mouse_pos = self.mouse_pos.get(); self.handle_mouse(mouse_button, element_state, mouse_pos.x, mouse_pos.y); } } Event::MouseMoved((x, y)) => { self.mouse_pos.set(Point2D::new(x, y)); self.event_queue.borrow_mut().push( WindowEvent::MouseWindowMoveEventClass(Point2D::typed(x as f32, y as f32))); } Event::MouseWheel(delta) => { if self.ctrl_pressed() { // Ctrl-Scrollwheel simulates a "pinch zoom" gesture. let dy = match delta { MouseScrollDelta::LineDelta(_, dy) => dy, MouseScrollDelta::PixelDelta(_, dy) => dy }; if dy < 0.0 { self.event_queue.borrow_mut().push(WindowEvent::PinchZoom(1.0/1.1)); } else if dy > 0.0 { self.event_queue.borrow_mut().push(WindowEvent::PinchZoom(1.1)); } } else { match delta { MouseScrollDelta::LineDelta(dx, dy) => { // this should use the actual line height // of the frame under the mouse let line_height = 57.0; self.scroll_window(dx, dy * line_height); } MouseScrollDelta::PixelDelta(dx, dy) => self.scroll_window(dx, dy) } } }, Event::Refresh => { self.event_queue.borrow_mut().push(WindowEvent::Refresh); } _ => {} } false } #[inline] fn ctrl_pressed(&self) -> bool { self.key_modifiers.get().intersects(LEFT_CONTROL | RIGHT_CONTROL) } fn toggle_modifier(&self, modifier: KeyModifiers) { let mut modifiers = self.key_modifiers.get(); modifiers.toggle(modifier); self.key_modifiers.set(modifiers); } /// Helper function to send a scroll event. fn scroll_window(&self, dx: f32, dy: f32) { let mouse_pos = self.mouse_pos.get(); let event = WindowEvent::Scroll(Point2D::typed(dx as f32, dy as f32), Point2D::typed(mouse_pos.x as i32, mouse_pos.y as i32)); self.event_queue.borrow_mut().push(event); } /// Helper function to handle a click fn handle_mouse(&self, button: glutin::MouseButton, action: glutin::ElementState, x: i32, y: i32) { use script_traits::MouseButton; // FIXME(tkuehn): max pixel dist should be based on pixel density let max_pixel_dist = 10f64; let event = match action { ElementState::Pressed => { self.mouse_down_point.set(Point2D::new(x, y)); self.mouse_down_button.set(Some(button)); MouseWindowEvent::MouseDown(MouseButton::Left, Point2D::typed(x as f32, y as f32)) } ElementState::Released => { let mouse_up_event = MouseWindowEvent::MouseUp(MouseButton::Left, Point2D::typed(x as f32, y as f32)); match self.mouse_down_button.get() { None => mouse_up_event, Some(but) if button == but => { let pixel_dist = self.mouse_down_point.get() - Point2D::new(x, y); let pixel_dist = ((pixel_dist.x * pixel_dist.x + pixel_dist.y * pixel_dist.y) as f64).sqrt(); if pixel_dist < max_pixel_dist { self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(mouse_up_event)); MouseWindowEvent::Click(MouseButton::Left, Point2D::typed(x as f32, y as f32)) } else { mouse_up_event } }, Some(_) => mouse_up_event, } } }; self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(event)); } #[cfg(target_os="macos")] fn handle_next_event(&self) -> bool { let event = self.window.wait_events().next().unwrap(); let mut close = self.handle_window_event(event); if !close { while let Some(event) = self.window.poll_events().next() { if self.handle_window_event(event) { close = true; break } } } close } #[cfg(any(target_os="linux", target_os="android"))] fn handle_next_event(&self) -> bool { use std::thread::sleep_ms; // TODO(gw): This is an awful hack to work around the // broken way we currently call X11 from multiple threads. // // On some (most?) X11 implementations, blocking here // with XPeekEvent results in the paint task getting stuck // in XGetGeometry randomly. When this happens the result // is that until you trigger the XPeekEvent to return // (by moving the mouse over the window) the paint task // never completes and you don't see the most recent // results. // // For now, poll events and sleep for ~1 frame if there // are no events. This means we don't spin the CPU at // 100% usage, but is far from ideal! // // See https://github.com/servo/servo/issues/5780 // let first_event = self.window.poll_events().next(); match first_event { Some(event) => { self.handle_window_event(event) } None => { sleep_ms(16); false } } } pub fn wait_events(&self) -> Vec<WindowEvent> { use std::mem; let mut events = mem::replace(&mut *self.event_queue.borrow_mut(), Vec::new()); let mut close_event = false; // When writing to a file then exiting, use event // polling so that we don't block on a GUI event // such as mouse click. if opts::get().output_file.is_some() { while let Some(event) = self.window.poll_events().next() { close_event = self.handle_window_event(event) || close_event; } } else { close_event = self.handle_next_event(); } if close_event || self.window.is_closed() { events.push(WindowEvent::Quit) } events.extend(mem::replace(&mut *self.event_queue.borrow_mut(), Vec::new()).into_iter()); events } pub unsafe fn set_nested_event_loop_listener( &self, listener: *mut (NestedEventLoopListener + 'static)) { g_nested_event_loop_listener = Some(listener) } pub unsafe fn remove_nested_event_loop_listener(&self) { g_nested_event_loop_listener = None } fn glutin_key_to_script_key(key: glutin::VirtualKeyCode) -> Result<constellation_msg::Key, ()> { // TODO(negge): add more key mappings match key { VirtualKeyCode::A => Ok(Key::A), VirtualKeyCode::B => Ok(Key::B), VirtualKeyCode::C => Ok(Key::C), VirtualKeyCode::D => Ok(Key::D), VirtualKeyCode::E => Ok(Key::E), VirtualKeyCode::F => Ok(Key::F), VirtualKeyCode::G => Ok(Key::G), VirtualKeyCode::H => Ok(Key::H), VirtualKeyCode::I => Ok(Key::I), VirtualKeyCode::J => Ok(Key::J), VirtualKeyCode::K => Ok(Key::K), VirtualKeyCode::L => Ok(Key::L), VirtualKeyCode::M => Ok(Key::M), VirtualKeyCode::N => Ok(Key::N), VirtualKeyCode::O => Ok(Key::O), VirtualKeyCode::P => Ok(Key::P), VirtualKeyCode::Q => Ok(Key::Q), VirtualKeyCode::R => Ok(Key::R), VirtualKeyCode::S => Ok(Key::S), VirtualKeyCode::T => Ok(Key::T), VirtualKeyCode::U => Ok(Key::U), VirtualKeyCode::V => Ok(Key::V), VirtualKeyCode::W => Ok(Key::W), VirtualKeyCode::X => Ok(Key::X), VirtualKeyCode::Y => Ok(Key::Y), VirtualKeyCode::Z => Ok(Key::Z), VirtualKeyCode::Numpad0 => Ok(Key::Kp0), VirtualKeyCode::Numpad1 => Ok(Key::Kp1), VirtualKeyCode::Numpad2 => Ok(Key::Kp2), VirtualKeyCode::Numpad3 => Ok(Key::Kp3), VirtualKeyCode::Numpad4 => Ok(Key::Kp4), VirtualKeyCode::Numpad5 => Ok(Key::Kp5), VirtualKeyCode::Numpad6 => Ok(Key::Kp6), VirtualKeyCode::Numpad7 => Ok(Key::Kp7), VirtualKeyCode::Numpad8 => Ok(Key::Kp8), VirtualKeyCode::Numpad9 => Ok(Key::Kp9), VirtualKeyCode::Key0 => Ok(Key::Num0), VirtualKeyCode::Key1 => Ok(Key::Num1), VirtualKeyCode::Key2 => Ok(Key::Num2), VirtualKeyCode::Key3 => Ok(Key::Num3), VirtualKeyCode::Key4 => Ok(Key::Num4), VirtualKeyCode::Key5 => Ok(Key::Num5), VirtualKeyCode::Key6 => Ok(Key::Num6), VirtualKeyCode::Key7 => Ok(Key::Num7), VirtualKeyCode::Key8 => Ok(Key::Num8), VirtualKeyCode::Key9 => Ok(Key::Num9), VirtualKeyCode::Return => Ok(Key::Enter), VirtualKeyCode::Space => Ok(Key::Space), VirtualKeyCode::Escape => Ok(Key::Escape), VirtualKeyCode::Equals => Ok(Key::Equal), VirtualKeyCode::Minus => Ok(Key::Minus), VirtualKeyCode::Back => Ok(Key::Backspace), VirtualKeyCode::PageDown => Ok(Key::PageDown), VirtualKeyCode::PageUp => Ok(Key::PageUp), VirtualKeyCode::Insert => Ok(Key::Insert), VirtualKeyCode::Home => Ok(Key::Home), VirtualKeyCode::Delete => Ok(Key::Delete), VirtualKeyCode::End => Ok(Key::End), VirtualKeyCode::Left => Ok(Key::Left), VirtualKeyCode::Up => Ok(Key::Up), VirtualKeyCode::Right => Ok(Key::Right), VirtualKeyCode::Down => Ok(Key::Down), VirtualKeyCode::Apostrophe => Ok(Key::Apostrophe), VirtualKeyCode::Backslash => Ok(Key::Backslash), VirtualKeyCode::Comma => Ok(Key::Comma), VirtualKeyCode::Grave => Ok(Key::GraveAccent), VirtualKeyCode::LBracket => Ok(Key::LeftBracket), VirtualKeyCode::Period => Ok(Key::Period), VirtualKeyCode::RBracket => Ok(Key::RightBracket), VirtualKeyCode::Semicolon => Ok(Key::Semicolon), VirtualKeyCode::Slash => Ok(Key::Slash), VirtualKeyCode::Tab => Ok(Key::Tab), VirtualKeyCode::Subtract => Ok(Key::Minus), _ => Err(()), } } fn glutin_mods_to_script_mods(modifiers: KeyModifiers) -> constellation_msg::KeyModifiers { let mut result = constellation_msg::KeyModifiers::from_bits(0).unwrap(); if modifiers.intersects(LEFT_SHIFT | RIGHT_SHIFT) { result.insert(SHIFT); } if modifiers.intersects(LEFT_CONTROL | RIGHT_CONTROL) { result.insert(CONTROL); } if modifiers.intersects(LEFT_ALT | RIGHT_ALT) { result.insert(ALT); } result } } // WindowProxy is not implemented for android yet #[cfg(all(feature = "window", target_os="android"))] fn create_window_proxy(_: &Rc<Window>) -> Option<glutin::WindowProxy> { None } #[cfg(all(feature = "window", not(target_os="android")))] fn create_window_proxy(window: &Rc<Window>) -> Option<glutin::WindowProxy> { Some(window.window.create_window_proxy()) } #[cfg(feature = "window")] impl WindowMethods for Window { fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, u32> { let scale_factor = self.window.hidpi_factor() as u32; let (width, height) = self.window.get_inner_size().unwrap(); Size2D::typed(width * scale_factor, height * scale_factor) } fn size(&self) -> TypedSize2D<ScreenPx, f32> { let (width, height) = self.window.get_inner_size().unwrap(); Size2D::typed(width as f32, height as f32) } fn present(&self) { self.window.swap_buffers() } fn create_compositor_channel(window: &Option<Rc<Window>>) -> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) { let (sender, receiver) = channel(); let window_proxy = match window { &Some(ref window) => create_window_proxy(window), &None => None, }; (box GlutinCompositorProxy { sender: sender, window_proxy: window_proxy, } as Box<CompositorProxy+Send>, box receiver as Box<CompositorReceiver>) } fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> { ScaleFactor::new(self.window.hidpi_factor()) } fn set_page_title(&self, title: Option<String>) { let title = match title { Some(ref title) if title.len() > 0 => &**title, _ => "untitled", }; let title = format!("{} - Servo", title); self.window.set_title(&title); } fn set_page_url(&self, _: Url) { } fn load_start(&self, _: bool, _: bool) { } fn load_end(&self, _: bool, _: bool) { } fn load_error(&self, _: NetError, _: String) { } fn head_parsed(&self) { } /// Has no effect on Android. fn set_cursor(&self, c: Cursor) { use glutin::MouseCursor; let glutin_cursor = match c { Cursor::NoCursor => MouseCursor::NoneCursor, Cursor::DefaultCursor => MouseCursor::Default, Cursor::PointerCursor => MouseCursor::Hand, Cursor::ContextMenuCursor => MouseCursor::ContextMenu, Cursor::HelpCursor => MouseCursor::Help, Cursor::ProgressCursor => MouseCursor::Progress, Cursor::WaitCursor => MouseCursor::Wait, Cursor::CellCursor => MouseCursor::Cell, Cursor::CrosshairCursor => MouseCursor::Crosshair, Cursor::TextCursor => MouseCursor::Text, Cursor::VerticalTextCursor => MouseCursor::VerticalText, Cursor::AliasCursor => MouseCursor::Alias, Cursor::CopyCursor => MouseCursor::Copy, Cursor::MoveCursor => MouseCursor::Move, Cursor::NoDropCursor => MouseCursor::NoDrop, Cursor::NotAllowedCursor => MouseCursor::NotAllowed, Cursor::GrabCursor => MouseCursor::Grab, Cursor::GrabbingCursor => MouseCursor::Grabbing, Cursor::EResizeCursor => MouseCursor::EResize, Cursor::NResizeCursor => MouseCursor::NResize, Cursor::NeResizeCursor => MouseCursor::NeResize, Cursor::NwResizeCursor => MouseCursor::NwResize, Cursor::SResizeCursor => MouseCursor::SResize, Cursor::SeResizeCursor => MouseCursor::SeResize, Cursor::SwResizeCursor => MouseCursor::SwResize, Cursor::WResizeCursor => MouseCursor::WResize, Cursor::EwResizeCursor => MouseCursor::EwResize, Cursor::NsResizeCursor => MouseCursor::NsResize, Cursor::NeswResizeCursor => MouseCursor::NeswResize, Cursor::NwseResizeCursor => MouseCursor::NwseResize, Cursor::ColResizeCursor => MouseCursor::ColResize, Cursor::RowResizeCursor => MouseCursor::RowResize, Cursor::AllScrollCursor => MouseCursor::AllScroll, Cursor::ZoomInCursor => MouseCursor::ZoomIn, Cursor::ZoomOutCursor => MouseCursor::ZoomOut, }; self.window.set_cursor(glutin_cursor); } fn set_favicon(&self, _: Url) { } fn prepare_for_composite(&self, _width: usize, _height: usize) -> bool { true } #[cfg(target_os="linux")] fn native_metadata(&self) -> NativeGraphicsMetadata { use x11::xlib; NativeGraphicsMetadata { display: unsafe { self.window.platform_display() as *mut xlib::Display } } } #[cfg(target_os="macos")] fn native_metadata(&self) -> NativeGraphicsMetadata { use cgl::{CGLGetCurrentContext, CGLGetPixelFormat}; unsafe { NativeGraphicsMetadata { pixel_format: CGLGetPixelFormat(CGLGetCurrentContext()), } } } #[cfg(target_os="android")] fn native_metadata(&self) -> NativeGraphicsMetadata { use egl::egl::GetCurrentDisplay; NativeGraphicsMetadata { display: GetCurrentDisplay(), } } /// Helper function to handle keyboard events. fn handle_key(&self, key: Key, mods: constellation_msg::KeyModifiers) { match key { Key::Equal if mods.contains(CONTROL) => { // Ctrl-+ self.event_queue.borrow_mut().push(WindowEvent::Zoom(1.1)); } Key::Minus if mods.contains(CONTROL) => { // Ctrl-- self.event_queue.borrow_mut().push(WindowEvent::Zoom(1.0/1.1)); } Key::Backspace if mods.contains(SHIFT) => { // Shift-Backspace self.event_queue.borrow_mut().push(WindowEvent::Navigation(WindowNavigateMsg::Forward)); } Key::Backspace => { // Backspace self.event_queue.borrow_mut().push(WindowEvent::Navigation(WindowNavigateMsg::Back)); } Key::PageDown => { self.scroll_window(0.0, -self.framebuffer_size().as_f32().to_untyped().height); } Key::PageUp => { self.scroll_window(0.0, self.framebuffer_size().as_f32().to_untyped().height); } _ => {} } } fn supports_clipboard(&self) -> bool { true } } /// The type of a window. #[cfg(feature = "headless")] pub struct Window { #[allow(dead_code)] context: glutin::HeadlessContext, width: u32, height: u32, } #[cfg(feature = "headless")] impl Window { pub fn new(_is_foreground: bool, window_size: TypedSize2D<DevicePixel, u32>, _parent: glutin::WindowID) -> Rc<Window> { let window_size = window_size.to_untyped(); let headless_builder = glutin::HeadlessRendererBuilder::new(window_size.width, window_size.height); let headless_context = headless_builder.build().unwrap(); unsafe { headless_context.make_current() }; gl::load_with(|s| headless_context.get_proc_address(s)); let window = Window { context: headless_context, width: window_size.width, height: window_size.height, }; Rc::new(window) } pub fn wait_events(&self) -> Vec<WindowEvent> { vec![WindowEvent::Idle] } pub unsafe fn set_nested_event_loop_listener( &self, _listener: *mut (NestedEventLoopListener + 'static)) { } pub unsafe fn remove_nested_event_loop_listener(&self) { } } #[cfg(feature = "headless")] impl WindowMethods for Window { fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, u32> { Size2D::typed(self.width, self.height) } fn size(&self) -> TypedSize2D<ScreenPx, f32> { Size2D::typed(self.width as f32, self.height as f32) } fn present(&self) { } fn create_compositor_channel(_: &Option<Rc<Window>>) -> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) { let (sender, receiver) = channel(); (box GlutinCompositorProxy { sender: sender, window_proxy: None, } as Box<CompositorProxy+Send>, box receiver as Box<CompositorReceiver>) } fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> { ScaleFactor::new(1.0) } fn set_page_title(&self, _: Option<String>) { } fn set_page_url(&self, _: Url) { } fn load_start(&self, _: bool, _: bool) { } fn load_end(&self, _: bool, _: bool) { } fn load_error(&self, _: NetError, _: String) { } fn head_parsed(&self) { } fn set_cursor(&self, _: Cursor) { }<|fim▁hole|> } fn prepare_for_composite(&self, _width: usize, _height: usize) -> bool { true } #[cfg(target_os="linux")] fn native_metadata(&self) -> NativeGraphicsMetadata { NativeGraphicsMetadata { display: ptr::null_mut() } } /// Helper function to handle keyboard events. fn handle_key(&self, _: Key, _: constellation_msg::KeyModifiers) { } fn supports_clipboard(&self) -> bool { false } } struct GlutinCompositorProxy { sender: Sender<compositor_task::Msg>, window_proxy: Option<glutin::WindowProxy>, } // TODO: Should this be implemented here or upstream in glutin::WindowProxy? unsafe impl Send for GlutinCompositorProxy {} impl CompositorProxy for GlutinCompositorProxy { fn send(&mut self, msg: compositor_task::Msg) { // Send a message and kick the OS event loop awake. self.sender.send(msg).unwrap(); if let Some(ref window_proxy) = self.window_proxy { window_proxy.wakeup_event_loop() } } fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> { box GlutinCompositorProxy { sender: self.sender.clone(), window_proxy: self.window_proxy.clone(), } as Box<CompositorProxy+Send> } } // These functions aren't actually called. They are here as a link // hack because Skia references them. #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glBindVertexArrayOES(_array: usize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glDeleteVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glGenVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glRenderbufferStorageMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glFramebufferTexture2DMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize, _: isize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glDiscardFramebufferEXT(_: isize, _: isize, _: *const ()) { unimplemented!() }<|fim▁end|>
fn set_favicon(&self, _: Url) {
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use std::str::FromStr; use std::collections::HashMap; use std::ops::{BitAnd, BitOr, Shl, Shr, Not}; const DATA: &'static str = include_str!("input.txt"); pub fn main() -> Vec<String> { let s1 = run_circuit(DATA, "a").unwrap(); let s2 = part2(DATA, "a", "b", 956).unwrap(); vec![s1.to_string(), s2.to_string()] } #[derive(PartialEq, Eq, Hash, Clone)] enum Source { Pattern(u16), Wire(String), } impl FromStr for Source { type Err = &'static str; fn from_str(s: &str) -> Result<Source, Self::Err> { match s { s if s.is_empty() => Err("empty identifier"), s if (|s: &str| s.chars().all(|c| c.is_digit(10)))(s) => { s.parse::<u16>().map_err(|_| "parse error").map(Source::Pattern) } s if (|s: &str| s.chars().all(|c| c.is_alphabetic()))(s) => { Ok(Source::Wire(s.to_owned())) } _ => Err("unknown identifier format"), } } } #[derive(PartialEq, Eq, Hash, Clone)] enum Gate { UnaryOp { src: Source, out: Source, f: fn(u16) -> u16, }, BinaryOp { a: Source, b: Source, out: Source, f: fn(u16, u16) -> u16, }, } impl FromStr for Gate { type Err = &'static str; fn from_str(s: &str) -> Result<Gate, Self::Err> { fn id<T>(x: T) -> T { x }; fn unary_from_str(a: &str, o: &str, f: fn(u16) -> u16) -> Result<Gate, &'static str> { a.parse::<Source>().and_then(|a| { o.parse::<Source>().map(|o| { Gate::UnaryOp { src: a, out: o, f: f, } }) }) } fn binary_from_str(a: &str, b: &str, o: &str, f: fn(u16, u16) -> u16) -> Result<Gate, &'static str> { a.parse::<Source>().and_then(|a| { b.parse::<Source>().and_then(|b| { o.parse::<Source>().map(|o| { Gate::BinaryOp { a: a, b: b, out: o, f: f, } }) }) }) } match &s.split_whitespace().collect::<Vec<_>>()[..] { [a, "->", o] => unary_from_str(a, o, id), ["NOT", a, "->", o] => unary_from_str(a, o, Not::not), [a, "AND", b, "->", o] => binary_from_str(a, b, o, BitAnd::bitand), [a, "OR", b, "->", o] => binary_from_str(a, b, o, BitOr::bitor), [a, "LSHIFT", b, "->", o] => binary_from_str(a, b, o, Shl::shl), [a, "RSHIFT", b, "->", o] => binary_from_str(a, b, o, Shr::shr), _ => Err("bad input"), } } } impl Gate { fn out(&self) -> Source { match *self { Gate::UnaryOp{ ref out, ..} => out, Gate::BinaryOp{ ref out, ..} => out, } .clone() } fn eval(&self, c: &mut Circuit) -> Option<u16> { match *self { Gate::UnaryOp{ ref src, ref f, .. } => c.eval(src).map(f), Gate::BinaryOp{ ref a, ref b, ref f, .. } => { c.eval(a).and_then(|a| c.eval(b).map(|b| f(a, b))) } } } } struct Circuit { gates: HashMap<Source, Gate>, cache: HashMap<Source, u16>, } impl FromStr for Circuit { type Err = &'static str; fn from_str(input: &str) -> Result<Circuit, Self::Err> { let mut circuit = HashMap::new(); let cache = HashMap::new(); for line in input.lines() { if let Ok(gate) = line.parse::<Gate>() { circuit.insert(gate.out(), gate); } else { return Err("gate parse error"); } } Ok(Circuit { gates: circuit, cache: cache, }) } } impl Circuit { fn eval(&mut self, wire: &Source) -> Option<u16> { match *wire { Source::Pattern(p) => Some(p), ref s @ Source::Wire(_) => { if self.cache.contains_key(s) { self.cache.get(s).cloned() } else { if let Some(v) = self.gates.get(s).cloned().and_then(|g| g.eval(self)) { self.cache.insert(s.clone(), v); Some(v) } else { None } } }<|fim▁hole|> fn force(&mut self, s: &Source, v: u16) { self.cache.clear(); self.cache.insert(s.clone(), v); } } fn run_circuit(input: &str, target: &str) -> Option<u16> { if let Ok(mut c) = input.parse::<Circuit>() { c.eval(&Source::Wire(target.to_owned())) } else { None } } fn part2(input: &str, target: &str, force: &str, v: u16) -> Option<u16> { if let Ok(mut c) = input.parse::<Circuit>() { c.force(&Source::Wire(force.to_owned()), v); c.eval(&Source::Wire(target.to_owned())) } else { None } } #[cfg(test)] mod test { use super::{Circuit, Source}; #[test] fn examples() { let cs = ["123 -> x", "456 -> y", "x AND y -> d", "x OR y -> e", "x LSHIFT 2 -> f", "y RSHIFT 2 -> g", "NOT x -> h", "NOT y -> i"] .join("\n"); let mut c = cs.parse::<Circuit>().unwrap(); assert_eq!(c.eval(&Source::Wire("d".to_owned())), Some(72)); assert_eq!(c.eval(&Source::Wire("e".to_owned())), Some(507)); assert_eq!(c.eval(&Source::Wire("f".to_owned())), Some(492)); assert_eq!(c.eval(&Source::Wire("g".to_owned())), Some(114)); assert_eq!(c.eval(&Source::Wire("h".to_owned())), Some(65412)); assert_eq!(c.eval(&Source::Wire("i".to_owned())), Some(65079)); assert_eq!(c.eval(&Source::Wire("x".to_owned())), Some(123)); assert_eq!(c.eval(&Source::Wire("y".to_owned())), Some(456)); } }<|fim▁end|>
} }
<|file_name|>SelfDefendingRule.ts<|end_file_name|><|fim▁begin|>import { TOptionsNormalizerRule } from '../../types/options/TOptionsNormalizerRule'; import { IOptions } from '../../interfaces/options/IOptions'; /** * @param {IOptions} options * @returns {IOptions} */ export const SelfDefendingRule: TOptionsNormalizerRule = (options: IOptions): IOptions => { if (options.selfDefending) { options = { ...options, compact: true,<|fim▁hole|> return options; };<|fim▁end|>
selfDefending: true }; }
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp'); var to5 = require('gulp-6to5'); var concat = require('gulp-concat'); var order = require('gulp-order'); var watch = require('gulp-watch'); var connect = require('gulp-connect'); gulp.task('6to5', function () { return gulp.src('src/js/**/*.js') .pipe(order([ 'core/**/*.js', 'components/**/*.js', 'app/**/*.js', 'main.js' ])) .pipe(to5()) .pipe(concat('app.js')) .pipe(gulp.dest('build')) .pipe(connect.reload()); });<|fim▁hole|>gulp.task('webserver', function() { connect.server({ root: 'build', livereload: true }); }); gulp.task('watch', function() { gulp.watch('src/js/**/*.js', ['6to5']); }); gulp.task('serve', ['webserver', 'watch']);<|fim▁end|>
<|file_name|>process.cc<|end_file_name|><|fim▁begin|>// Copyright 2006-2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #include "omaha/mi_exe_stub/process.h" namespace omaha { namespace { bool run_and_wait(const CString& command_line, DWORD* exit_code, bool wait, int cmd_show) { CString cmd_line(command_line); STARTUPINFO si = {}; PROCESS_INFORMATION pi = {}; GetStartupInfo(&si); si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW; si.wShowWindow = static_cast<WORD>(cmd_show); BOOL create_process_result = CreateProcess(NULL, cmd_line.GetBuffer(), NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi); if (!create_process_result) { *exit_code = GetLastError(); return false; } if (wait) { WaitForSingleObject(pi.hProcess, INFINITE); } bool result = true; if (exit_code) { result = !!GetExitCodeProcess(pi.hProcess, exit_code); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return result; } } // namespace bool RunAndWaitHidden(const CString& command_line, DWORD *exit_code) { return run_and_wait(command_line, exit_code, true, SW_HIDE); } bool RunAndWait(const CString& command_line, DWORD *exit_code) { return run_and_wait(command_line, exit_code, true, SW_SHOWNORMAL); } bool Run(const CString& command_line) { return run_and_wait(command_line, NULL, false, SW_SHOWNORMAL); } <|fim▁hole|><|fim▁end|>
} // namespace omaha
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate rand;<|fim▁hole|>use std::cmp::Ordering; fn main() { let secret_number: u32 = rand::thread_rng().gen_range(1, 101); //println!("The secret number is {}", secret_number); println!("Guess the number!"); loop { println!("Please enter your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line."); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("Correct!"); break; } } } }<|fim▁end|>
use std::io; use rand::Rng;
<|file_name|>UDP.py<|end_file_name|><|fim▁begin|># UDP code taken from < https://pymotw.com/2/socket/udp.html > import socket, time, fcntl, struct def udpBeacon(): # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_ip = getIP('wlan0') spliced_subnet = my_ip[:my_ip.rfind('.')] + ".255" # Define broadcasting address and message server_address = (spliced_subnet, 5001) message = 'Hello, I am a minibot!' # Send message and resend every 9 seconds while True:<|fim▁hole|> sent = sock.sendto(bytes(message, 'utf8'), server_address) except Exception as err: print(err) time.sleep(9) def getIP(ifname): """ Returns the IP of the device """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', bytes(ifname[:15],'utf8')) )[20:24])<|fim▁end|>
try: # Send data print('sending broadcast: "%s"' % message)
<|file_name|>facebook.js<|end_file_name|><|fim▁begin|>'use strict'; module.exports = config => [{ name: 'facebook-app_id',<|fim▁hole|> when: require('./when')('facebook', config) }, { name: 'facebook_api-api_version', message: 'version of facebook api', store: true, when: require('./when')('facebook_api', config) }];<|fim▁end|>
message: 'app id of facebook', store: true,
<|file_name|>PortletMoveStatisticsController.java<|end_file_name|><|fim▁begin|>/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file<|fim▁hole|> * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.portlets.statistics; import java.util.Collections; import java.util.List; import org.jasig.portal.events.aggr.portletlayout.PortletLayoutAggregation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.annotation.RenderMapping; import org.springframework.web.portlet.bind.annotation.ResourceMapping; import com.google.visualization.datasource.base.TypeMismatchException; import com.google.visualization.datasource.datatable.value.NumberValue; import com.google.visualization.datasource.datatable.value.Value; /** * @author Chris Waymire <[email protected]> */ @Controller @RequestMapping(value="VIEW") public class PortletMoveStatisticsController extends BasePortletLayoutStatisticsController<PortletMoveReportForm> { private static final String DATA_TABLE_RESOURCE_ID = "portletMoveData"; private static final String REPORT_NAME = "portletMove.totals"; @RenderMapping(value="MAXIMIZED", params="report=" + REPORT_NAME) public String getLoginView() throws TypeMismatchException { return super.getLoginView(); } @ResourceMapping(DATA_TABLE_RESOURCE_ID) public ModelAndView renderPortletAddAggregationReport(PortletMoveReportForm form) throws TypeMismatchException { return super.renderPortletAddAggregationReport(form); } @Override public String getReportName() { return REPORT_NAME; } @Override public String getReportDataResourceId() { return DATA_TABLE_RESOURCE_ID; } @Override protected List<Value> createRowValues(PortletLayoutAggregation aggr, PortletMoveReportForm form) { int count = aggr != null ? aggr.getMoveCount() : 0; return Collections.<Value>singletonList(new NumberValue(count)); } }<|fim▁end|>
<|file_name|>odometry.cpp<|end_file_name|><|fim▁begin|>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, PAL Robotics, S.L. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the PAL Robotics nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* * Author: Luca Marchionni * Author: Bence Magyar * Author: Enrique Fernández * Author: Paul Mathieu */ #include <mecanum_drive_controller/odometry.h> #include <tf/transform_datatypes.h> #include <boost/bind.hpp> namespace mecanum_drive_controller { namespace bacc = boost::accumulators; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Odometry::Odometry(size_t velocity_rolling_window_size) : timestamp_(0.0) , x_(0.0) , y_(0.0)<|fim▁hole|>, wheels_k_(0.0) , wheels_radius_(0.0) , velocity_rolling_window_size_(velocity_rolling_window_size) , linearX_acc_(RollingWindow::window_size = velocity_rolling_window_size) , linearY_acc_(RollingWindow::window_size = velocity_rolling_window_size) , angular_acc_(RollingWindow::window_size = velocity_rolling_window_size) , integrate_fun_(boost::bind(&Odometry::integrateExact, this, _1, _2, _3)) { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Odometry::init(const ros::Time& time) { // Reset accumulators: linearX_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); linearY_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); angular_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); // Reset timestamp: timestamp_ = time; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Odometry::update(double wheel0_vel, double wheel1_vel, double wheel2_vel, double wheel3_vel, const ros::Time &time) { /// We cannot estimate the speed with very small time intervals: const double dt = (time - timestamp_).toSec(); if (dt < 0.0001) return false; // Interval too small to integrate with timestamp_ = time; /// Compute forward kinematics (i.e. compute mobile robot's body twist out of its wheels velocities): /// NOTE: we use the IK of the mecanum wheels which we invert using a pseudo-inverse. /// NOTE: in the diff drive the velocity is filtered out, but we prefer to return it raw and let the user perform /// post-processing at will. We prefer this way of doing as filtering introduces delay (which makes it /// difficult to interpret and compare behavior curves). linearX_ = 0.25 * wheels_radius_ * ( wheel0_vel + wheel1_vel + wheel2_vel + wheel3_vel); linearY_ = 0.25 * wheels_radius_ * (-wheel0_vel + wheel1_vel - wheel2_vel + wheel3_vel); angular_ = 0.25 * wheels_radius_ / wheels_k_ * (-wheel0_vel - wheel1_vel + wheel2_vel + wheel3_vel); /// Integrate odometry. integrate_fun_(linearX_ * dt, linearY_ * dt, angular_ * dt); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Odometry::updateOpenLoop(double linearX, double linearY, double angular, const ros::Time &time) { /// Save last linear and angular velocity: linearX_ = linearX; linearY_ = linearY; angular_ = angular; /// Integrate odometry: const double dt = (time - timestamp_).toSec(); timestamp_ = time; integrate_fun_(linearX * dt, linearY * dt, angular * dt); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Odometry::setWheelsParams(double wheels_k, double wheels_radius) { wheels_k_ = wheels_k; wheels_radius_ = wheels_radius; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Odometry::integrateExact(double linearX, double linearY, double angular) { /// Integrate angular velocity. heading_ += angular; /// The odometry pose should be published in the /odom frame (unlike the odometry twist which is a body twist). /// Project the twist in the odometry basis (we cannot integrate linearX, linearY, angular 'as are' because they correspond to a body twist). tf::Matrix3x3 R_m_odom = tf::Matrix3x3(tf::createQuaternionFromYaw(heading_)); tf::Vector3 vel_inOdom = R_m_odom * tf::Vector3(linearX, linearY, 0.0); /// Integrate linear velocity. x_ += vel_inOdom.x(); y_ += vel_inOdom.y(); } } // namespace mecanum_drive_controller<|fim▁end|>
, heading_(0.0) , linearX_(0.0) , linearY_(0.0) , angular_(0.0)
<|file_name|>01 Environment Setup.js<|end_file_name|><|fim▁begin|>scaffolder: https://github.com/coryhouse/react-slingshot ^we wont use this though well use: https://github.com/coryhouse/pluralsight-redux-starter Our dev environment: 1. Automated Testign 2. Linting 3. Minification 4. Bundling 5. JSXCompilation 6. ES6 Transpilation Babel-Polyfill: few things babel cant do and babel-polyfill can do for es6->5 array.from, set, map, promise, generator functions etc. Downsides: Its too large 50K but we can pull out whatever particula polyfill we want babel-preset-react-hmre<|fim▁hole|>Proxies are classes that act just like your classes but they provide hooks for injectin new implementiaton So when you hit save, your changes are immd8ly applied without requiring a reload WARNINGS: experimental and doesnt reload functional components and container functions like mapStateTOprops (I think this is embedded into react now) npm scripts replaced gulp! cool right! https://medium.freecodecamp.com/why-i-left-gulp-and-grunt-for-npm-scripts-3d6853dd22b8#.scjzloi78<|fim▁end|>
its a babel preset that wraps up a number of other libraries and settings in a single prest It works by wrapping your components in a custom proxy using Babel.
<|file_name|>NetworkManagerMixin.java<|end_file_name|><|fim▁begin|>/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy<|fim▁hole|> * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.network; import io.netty.channel.Channel; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.local.LocalAddress; import net.minecraft.network.NetworkManager; import org.spongepowered.api.MinecraftVersion; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeMinecraftVersion; import org.spongepowered.common.bridge.network.NetworkManagerBridge; import org.spongepowered.common.util.Constants; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import javax.annotation.Nullable; @SuppressWarnings("rawtypes") @Mixin(NetworkManager.class) public abstract class NetworkManagerMixin extends SimpleChannelInboundHandler implements NetworkManagerBridge { @Shadow private Channel channel; @Shadow public abstract SocketAddress getRemoteAddress(); @Nullable private InetSocketAddress impl$virtualHost; @Nullable private MinecraftVersion impl$version; @Override public InetSocketAddress bridge$getAddress() { final SocketAddress remoteAddress = getRemoteAddress(); if (remoteAddress instanceof LocalAddress) { // Single player return Constants.Networking.LOCALHOST; } return (InetSocketAddress) remoteAddress; } @Override public InetSocketAddress bridge$getVirtualHost() { if (this.impl$virtualHost != null) { return this.impl$virtualHost; } final SocketAddress local = this.channel.localAddress(); if (local instanceof LocalAddress) { return Constants.Networking.LOCALHOST; } return (InetSocketAddress) local; } @Override public void bridge$setVirtualHost(final String host, final int port) { try { this.impl$virtualHost = new InetSocketAddress(InetAddress.getByAddress(host, ((InetSocketAddress) this.channel.localAddress()).getAddress().getAddress()), port); } catch (UnknownHostException e) { this.impl$virtualHost = InetSocketAddress.createUnresolved(host, port); } } @Override public MinecraftVersion bridge$getVersion() { return this.impl$version; } @Override public void bridge$setVersion(final int version) { this.impl$version = new SpongeMinecraftVersion(String.valueOf(version), version); } }<|fim▁end|>
* of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<|file_name|>Concator.java<|end_file_name|><|fim▁begin|>package railo.runtime.search.lucene2.query; import railo.commons.lang.StringUtil; public final class Concator implements Op {<|fim▁hole|> private Op left; private Op right; public Concator(Op left,Op right) { this.left=left; this.right=right; } @Override public String toString() { if(left instanceof Literal && right instanceof Literal) { String str=((Literal)left).literal+" "+((Literal)right).literal; return "\""+StringUtil.replace(str, "\"", "\"\"", false)+"\""; } return left+" "+right; } }<|fim▁end|>
<|file_name|>rhnAuthPAM.py<|end_file_name|><|fim▁begin|># # Copyright (c) 2008--2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.<|fim▁hole|># granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # import PAM import sys from spacewalk.common.rhnLog import log_error from spacewalk.common.rhnException import rhnException __username = None __password = None def __pam_conv(auth, query_list): global __username, __password # Build a list of responses to be passed back to PAM resp = [] for query, type in query_list: if type == PAM.PAM_PROMPT_ECHO_ON: # Prompt for a username resp.append((__username, 0)) elif type == PAM.PAM_PROMPT_ECHO_OFF: # Prompt for a password resp.append((__password, 0)) else: # Unknown PAM type log_error("Got unknown PAM type %s (query=%s)" % (type, query)) return None return resp def check_password(username, password, service): global __username, __password auth = PAM.pam() auth.start(service, username, __pam_conv) # Save the username and passwords in the globals, the conversation # function needs access to them __username = username __password = password try: try: auth.authenticate() auth.acct_mgmt() finally: # Something to be always executed - cleanup __username = __password = None except PAM.error, e: resp, code = e.args[:2] log_error("Password check failed (%s): %s" % (code, resp)) return 0 except: raise rhnException('Internal PAM error'), None, sys.exc_info()[2] else: # Good password return 1<|fim▁end|>
# # Red Hat trademarks are not licensed under GPLv2. No permission is
<|file_name|>bitv.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_doc)] use std::cmp; use std::iter::RandomAccessIterator; use std::iter::{Rev, Enumerate, Repeat, Map, Zip}; use std::ops; use std::slice; use std::strbuf::StrBuf; use std::uint; #[deriving(Clone)] struct SmallBitv { /// only the lowest nbits of this value are used. the rest is undefined. bits: uint } /// a mask that has a 1 for each defined bit in a small_bitv, assuming n bits #[inline] fn small_mask(nbits: uint) -> uint { (1 << nbits) - 1 } impl SmallBitv { pub fn new(bits: uint) -> SmallBitv { SmallBitv {bits: bits} } #[inline] pub fn bits_op(&mut self, right_bits: uint, nbits: uint, f: |uint, uint| -> uint) -> bool { let mask = small_mask(nbits); let old_b: uint = self.bits; let new_b = f(old_b, right_bits); self.bits = new_b; mask & old_b != mask & new_b } #[inline] pub fn union(&mut self, s: &SmallBitv, nbits: uint) -> bool { self.bits_op(s.bits, nbits, |u1, u2| u1 | u2) } #[inline] pub fn intersect(&mut self, s: &SmallBitv, nbits: uint) -> bool { self.bits_op(s.bits, nbits, |u1, u2| u1 & u2) } #[inline] pub fn become(&mut self, s: &SmallBitv, nbits: uint) -> bool { self.bits_op(s.bits, nbits, |_u1, u2| u2) } #[inline] pub fn difference(&mut self, s: &SmallBitv, nbits: uint) -> bool { self.bits_op(s.bits, nbits, |u1, u2| u1 & !u2) } #[inline] pub fn get(&self, i: uint) -> bool { (self.bits & (1 << i)) != 0 } #[inline] pub fn set(&mut self, i: uint, x: bool) { if x { self.bits |= 1<<i; } else { self.bits &= !(1<<i); } } #[inline] pub fn equals(&self, b: &SmallBitv, nbits: uint) -> bool { let mask = small_mask(nbits); mask & self.bits == mask & b.bits } #[inline] pub fn clear(&mut self) { self.bits = 0; } #[inline] pub fn set_all(&mut self) { self.bits = !0; } #[inline] pub fn all(&self, nbits: uint) -> bool { small_mask(nbits) & !self.bits == 0 } #[inline] pub fn none(&self, nbits: uint) -> bool { small_mask(nbits) & self.bits == 0 } #[inline] pub fn negate(&mut self) { self.bits = !self.bits; } } #[deriving(Clone)] struct BigBitv { storage: Vec<uint> } /** * A mask that has a 1 for each defined bit in the n'th element of a `BigBitv`, * assuming n bits. */ #[inline] fn big_mask(nbits: uint, elem: uint) -> uint { let rmd = nbits % uint::BITS; let nelems = nbits/uint::BITS + if rmd == 0 {0} else {1}; if elem < nelems - 1 || rmd == 0 { !0 } else { (1 << rmd) - 1 } } impl BigBitv { pub fn new(storage: Vec<uint>) -> BigBitv { BigBitv {storage: storage} } #[inline] pub fn process(&mut self, b: &BigBitv, nbits: uint, op: |uint, uint| -> uint) -> bool { let len = b.storage.len(); assert_eq!(self.storage.len(), len); let mut changed = false; for (i, (a, b)) in self.storage.mut_iter() .zip(b.storage.iter()) .enumerate() { let mask = big_mask(nbits, i); let w0 = *a & mask; let w1 = *b & mask; let w = op(w0, w1) & mask; if w0 != w { changed = true; *a = w; } } changed } #[inline] pub fn each_storage(&mut self, op: |v: &mut uint| -> bool) -> bool { self.storage.mut_iter().advance(|elt| op(elt)) } #[inline] pub fn negate(&mut self) { self.each_storage(|w| { *w = !*w; true }); } #[inline] pub fn union(&mut self, b: &BigBitv, nbits: uint) -> bool { self.process(b, nbits, |w1, w2| w1 | w2) } #[inline] pub fn intersect(&mut self, b: &BigBitv, nbits: uint) -> bool { self.process(b, nbits, |w1, w2| w1 & w2) } #[inline] pub fn become(&mut self, b: &BigBitv, nbits: uint) -> bool { self.process(b, nbits, |_, w| w) } #[inline] pub fn difference(&mut self, b: &BigBitv, nbits: uint) -> bool { self.process(b, nbits, |w1, w2| w1 & !w2) } #[inline] pub fn get(&self, i: uint) -> bool { let w = i / uint::BITS; let b = i % uint::BITS; let x = 1 & self.storage.get(w) >> b; x == 1 } #[inline] pub fn set(&mut self, i: uint, x: bool) { let w = i / uint::BITS; let b = i % uint::BITS; let flag = 1 << b; *self.storage.get_mut(w) = if x { *self.storage.get(w) | flag } else { *self.storage.get(w) & !flag }; } #[inline] pub fn equals(&self, b: &BigBitv, nbits: uint) -> bool { for (i, elt) in b.storage.iter().enumerate() { let mask = big_mask(nbits, i); if mask & *self.storage.get(i) != mask & *elt { return false; } } true } } #[deriving(Clone)] enum BitvVariant { Big(BigBitv), Small(SmallBitv) } enum Op {Union, Intersect, Assign, Difference} /// The bitvector type /// /// # Example /// /// ```rust /// use collections::bitv::Bitv; /// /// let mut bv = Bitv::new(10, false); /// /// // insert all primes less than 10 /// bv.set(2, true); /// bv.set(3, true); /// bv.set(5, true); /// bv.set(7, true); /// println!("{}", bv.to_str()); /// println!("total bits set to true: {}", bv.iter().count(|x| x)); /// /// // flip all values in bitvector, producing non-primes less than 10 /// bv.negate(); /// println!("{}", bv.to_str()); /// println!("total bits set to true: {}", bv.iter().count(|x| x)); /// /// // reset bitvector to empty /// bv.clear(); /// println!("{}", bv.to_str()); /// println!("total bits set to true: {}", bv.iter().count(|x| x)); /// ``` #[deriving(Clone)] pub struct Bitv { /// Internal representation of the bit vector (small or large) rep: BitvVariant, /// The number of valid bits in the internal representation nbits: uint } fn die() -> ! { fail!("Tried to do operation on bit vectors with different sizes"); } impl Bitv { #[inline] fn do_op(&mut self, op: Op, other: &Bitv) -> bool { if self.nbits != other.nbits { die(); } match self.rep { Small(ref mut s) => match other.rep { Small(ref s1) => match op { Union => s.union(s1, self.nbits), Intersect => s.intersect(s1, self.nbits), Assign => s.become(s1, self.nbits), Difference => s.difference(s1, self.nbits) }, Big(_) => die() }, Big(ref mut s) => match other.rep { Small(_) => die(), Big(ref s1) => match op { Union => s.union(s1, self.nbits), Intersect => s.intersect(s1, self.nbits), Assign => s.become(s1, self.nbits), Difference => s.difference(s1, self.nbits) } } } } } impl Bitv { /// Creates an empty Bitv that holds `nbits` elements, setting each element /// to `init`. pub fn new(nbits: uint, init: bool) -> Bitv { let rep = if nbits < uint::BITS { Small(SmallBitv::new(if init {(1<<nbits)-1} else {0})) } else if nbits == uint::BITS { Small(SmallBitv::new(if init {!0} else {0})) } else { let exact = nbits % uint::BITS == 0; let nelems = nbits/uint::BITS + if exact {0} else {1}; let s = if init { if exact { Vec::from_elem(nelems, !0u) } else { let mut v = Vec::from_elem(nelems-1, !0u); v.push((1<<nbits % uint::BITS)-1); v } } else { Vec::from_elem(nelems, 0u)}; Big(BigBitv::new(s)) }; Bitv {rep: rep, nbits: nbits} } /** * Calculates the union of two bitvectors * * Sets `self` to the union of `self` and `v1`. Both bitvectors must be * the same length. Returns `true` if `self` changed. */ #[inline] pub fn union(&mut self, v1: &Bitv) -> bool { self.do_op(Union, v1) } /** * Calculates the intersection of two bitvectors * * Sets `self` to the intersection of `self` and `v1`. Both bitvectors * must be the same length. Returns `true` if `self` changed. */ #[inline] pub fn intersect(&mut self, v1: &Bitv) -> bool { self.do_op(Intersect, v1) } /** * Assigns the value of `v1` to `self` * * Both bitvectors must be the same length. Returns `true` if `self` was * changed */ #[inline] pub fn assign(&mut self, v: &Bitv) -> bool { self.do_op(Assign, v) } /// Retrieve the value at index `i` #[inline] pub fn get(&self, i: uint) -> bool { assert!((i < self.nbits)); match self.rep { Big(ref b) => b.get(i), Small(ref s) => s.get(i) } } /** * Set the value of a bit at a given index * * `i` must be less than the length of the bitvector. */ #[inline] pub fn set(&mut self, i: uint, x: bool) { assert!((i < self.nbits)); match self.rep { Big(ref mut b) => b.set(i, x), Small(ref mut s) => s.set(i, x) } } /** * Compares two bitvectors * * Both bitvectors must be the same length. Returns `true` if both * bitvectors contain identical elements. */ #[inline] pub fn equal(&self, v1: &Bitv) -> bool { if self.nbits != v1.nbits { return false; } match self.rep { Small(ref b) => match v1.rep { Small(ref b1) => b.equals(b1, self.nbits), _ => false }, Big(ref s) => match v1.rep { Big(ref s1) => s.equals(s1, self.nbits), Small(_) => return false } } } /// Set all bits to 0 #[inline] pub fn clear(&mut self) { match self.rep { Small(ref mut b) => b.clear(), Big(ref mut s) => { s.each_storage(|w| { *w = 0u; true }); } } } /// Set all bits to 1 #[inline] pub fn set_all(&mut self) { match self.rep { Small(ref mut b) => b.set_all(), Big(ref mut s) => { s.each_storage(|w| { *w = !0u; true }); } } } /// Flip all bits #[inline] pub fn negate(&mut self) { match self.rep { Small(ref mut s) => s.negate(), Big(ref mut b) => b.negate(), } } /** * Calculate the difference between two bitvectors * * Sets each element of `v0` to the value of that element minus the * element of `v1` at the same index. Both bitvectors must be the same * length. * * Returns `true` if `v0` was changed. */ #[inline] pub fn difference(&mut self, v: &Bitv) -> bool { self.do_op(Difference, v) } /// Returns `true` if all bits are 1 #[inline] pub fn all(&self) -> bool { match self.rep { Small(ref b) => b.all(self.nbits), _ => self.iter().all(|x| x) } } /// Returns an iterator over the elements of the vector in order. /// /// # Example /// /// ```rust /// use collections::bitv::Bitv; /// let mut bv = Bitv::new(10, false); /// bv.set(1, true); /// bv.set(2, true); /// bv.set(3, true); /// bv.set(5, true); /// bv.set(8, true); /// // Count bits set to 1; result should be 5 /// println!("{}", bv.iter().count(|x| x)); /// ``` #[inline] pub fn iter<'a>(&'a self) -> Bits<'a> { Bits {bitv: self, next_idx: 0, end_idx: self.nbits} } #[inline] #[deprecated = "replaced by .iter().rev()"] pub fn rev_iter<'a>(&'a self) -> Rev<Bits<'a>> { self.iter().rev() } /// Returns `true` if all bits are 0 pub fn none(&self) -> bool { match self.rep { Small(ref b) => b.none(self.nbits), _ => self.iter().all(|x| !x) }<|fim▁hole|> #[inline] /// Returns `true` if any bit is 1 pub fn any(&self) -> bool { !self.none() } /** * Converts `self` to a vector of `uint` with the same length. * * Each `uint` in the resulting vector has either value `0u` or `1u`. */ pub fn to_vec(&self) -> Vec<uint> { Vec::from_fn(self.nbits, |i| if self.get(i) { 1 } else { 0 }) } /** * Organise the bits into bytes, such that the first bit in the * `Bitv` becomes the high-order bit of the first byte. If the * size of the `Bitv` is not a multiple of 8 then trailing bits * will be filled-in with false/0 */ pub fn to_bytes(&self) -> Vec<u8> { fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 { let offset = byte * 8 + bit; if offset >= bitv.nbits { 0 } else { bitv[offset] as u8 << (7 - bit) } } let len = self.nbits/8 + if self.nbits % 8 == 0 { 0 } else { 1 }; Vec::from_fn(len, |i| bit(self, i, 0) | bit(self, i, 1) | bit(self, i, 2) | bit(self, i, 3) | bit(self, i, 4) | bit(self, i, 5) | bit(self, i, 6) | bit(self, i, 7) ) } /** * Transform `self` into a `Vec<bool>` by turning each bit into a `bool`. */ pub fn to_bools(&self) -> Vec<bool> { Vec::from_fn(self.nbits, |i| self[i]) } /** * Converts `self` to a string. * * The resulting string has the same length as `self`, and each * character is either '0' or '1'. */ pub fn to_str(&self) -> ~str { let mut rs = StrBuf::new(); for i in self.iter() { if i { rs.push_char('1'); } else { rs.push_char('0'); } }; rs.into_owned() } /** * Compare a bitvector to a vector of `bool`. * * Both the bitvector and vector must have the same length. */ pub fn eq_vec(&self, v: &[bool]) -> bool { assert_eq!(self.nbits, v.len()); let mut i = 0; while i < self.nbits { if self.get(i) != v[i] { return false; } i = i + 1; } true } pub fn ones(&self, f: |uint| -> bool) -> bool { range(0u, self.nbits).advance(|i| !self.get(i) || f(i)) } } /** * Transform a byte-vector into a `Bitv`. Each byte becomes 8 bits, * with the most significant bits of each byte coming first. Each * bit becomes `true` if equal to 1 or `false` if equal to 0. */ pub fn from_bytes(bytes: &[u8]) -> Bitv { from_fn(bytes.len() * 8, |i| { let b = bytes[i / 8] as uint; let offset = i % 8; b >> (7 - offset) & 1 == 1 }) } /** * Transform a `[bool]` into a `Bitv` by converting each `bool` into a bit. */ pub fn from_bools(bools: &[bool]) -> Bitv { from_fn(bools.len(), |i| bools[i]) } /** * Create a `Bitv` of the specified length where the value at each * index is `f(index)`. */ pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv { let mut bitv = Bitv::new(len, false); for i in range(0u, len) { bitv.set(i, f(i)); } bitv } impl ops::Index<uint,bool> for Bitv { fn index(&self, i: &uint) -> bool { self.get(*i) } } #[inline] fn iterate_bits(base: uint, bits: uint, f: |uint| -> bool) -> bool { if bits == 0 { return true; } for i in range(0u, uint::BITS) { if bits & (1 << i) != 0 { if !f(base + i) { return false; } } } return true; } /// An iterator for `Bitv`. pub struct Bits<'a> { bitv: &'a Bitv, next_idx: uint, end_idx: uint, } impl<'a> Iterator<bool> for Bits<'a> { #[inline] fn next(&mut self) -> Option<bool> { if self.next_idx != self.end_idx { let idx = self.next_idx; self.next_idx += 1; Some(self.bitv.get(idx)) } else { None } } fn size_hint(&self) -> (uint, Option<uint>) { let rem = self.end_idx - self.next_idx; (rem, Some(rem)) } } impl<'a> DoubleEndedIterator<bool> for Bits<'a> { #[inline] fn next_back(&mut self) -> Option<bool> { if self.next_idx != self.end_idx { self.end_idx -= 1; Some(self.bitv.get(self.end_idx)) } else { None } } } impl<'a> ExactSize<bool> for Bits<'a> {} impl<'a> RandomAccessIterator<bool> for Bits<'a> { #[inline] fn indexable(&self) -> uint { self.end_idx - self.next_idx } #[inline] fn idx(&mut self, index: uint) -> Option<bool> { if index >= self.indexable() { None } else { Some(self.bitv.get(index)) } } } /// An implementation of a set using a bit vector as an underlying /// representation for holding numerical elements. /// /// It should also be noted that the amount of storage necessary for holding a /// set of objects is proportional to the maximum of the objects when viewed /// as a `uint`. #[deriving(Clone)] pub struct BitvSet { size: uint, // In theory this is a `Bitv` instead of always a `BigBitv`, but knowing that // there's an array of storage makes our lives a whole lot easier when // performing union/intersection/etc operations bitv: BigBitv } impl BitvSet { /// Creates a new bit vector set with initially no contents pub fn new() -> BitvSet { BitvSet{ size: 0, bitv: BigBitv::new(vec!(0)) } } /// Creates a new bit vector set from the given bit vector pub fn from_bitv(bitv: Bitv) -> BitvSet { let mut size = 0; bitv.ones(|_| { size += 1; true }); let Bitv{rep, ..} = bitv; match rep { Big(b) => BitvSet{ size: size, bitv: b }, Small(SmallBitv{bits}) => BitvSet{ size: size, bitv: BigBitv{ storage: vec!(bits) } }, } } /// Returns the capacity in bits for this bit vector. Inserting any /// element less than this amount will not trigger a resizing. pub fn capacity(&self) -> uint { self.bitv.storage.len() * uint::BITS } /// Consumes this set to return the underlying bit vector pub fn unwrap(self) -> Bitv { let cap = self.capacity(); let BitvSet{bitv, ..} = self; return Bitv{ nbits:cap, rep: Big(bitv) }; } #[inline] fn other_op(&mut self, other: &BitvSet, f: |uint, uint| -> uint) { fn nbits(mut w: uint) -> uint { let mut bits = 0; for _ in range(0u, uint::BITS) { if w == 0 { break; } bits += w & 1; w >>= 1; } return bits; } if self.capacity() < other.capacity() { self.bitv.storage.grow(other.capacity() / uint::BITS, &0); } for (i, &w) in other.bitv.storage.iter().enumerate() { let old = *self.bitv.storage.get(i); let new = f(old, w); *self.bitv.storage.get_mut(i) = new; self.size += nbits(new) - nbits(old); } } /// Union in-place with the specified other bit vector pub fn union_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 | w2); } /// Intersect in-place with the specified other bit vector pub fn intersect_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 & w2); } /// Difference in-place with the specified other bit vector pub fn difference_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 & !w2); } /// Symmetric difference in-place with the specified other bit vector pub fn symmetric_difference_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 ^ w2); } pub fn iter<'a>(&'a self) -> BitPositions<'a> { BitPositions {set: self, next_idx: 0} } pub fn difference(&self, other: &BitvSet, f: |&uint| -> bool) -> bool { for (i, w1, w2) in self.commons(other) { if !iterate_bits(i, w1 & !w2, |b| f(&b)) { return false } }; /* everything we have that they don't also shows up */ self.outliers(other).advance(|(mine, i, w)| !mine || iterate_bits(i, w, |b| f(&b)) ) } pub fn symmetric_difference(&self, other: &BitvSet, f: |&uint| -> bool) -> bool { for (i, w1, w2) in self.commons(other) { if !iterate_bits(i, w1 ^ w2, |b| f(&b)) { return false } }; self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b))) } pub fn intersection(&self, other: &BitvSet, f: |&uint| -> bool) -> bool { self.commons(other).advance(|(i, w1, w2)| iterate_bits(i, w1 & w2, |b| f(&b))) } pub fn union(&self, other: &BitvSet, f: |&uint| -> bool) -> bool { for (i, w1, w2) in self.commons(other) { if !iterate_bits(i, w1 | w2, |b| f(&b)) { return false } }; self.outliers(other).advance(|(_, i, w)| iterate_bits(i, w, |b| f(&b))) } } impl cmp::Eq for BitvSet { fn eq(&self, other: &BitvSet) -> bool { if self.size != other.size { return false; } for (_, w1, w2) in self.commons(other) { if w1 != w2 { return false; } } for (_, _, w) in self.outliers(other) { if w != 0 { return false; } } return true; } fn ne(&self, other: &BitvSet) -> bool { !self.eq(other) } } impl Container for BitvSet { #[inline] fn len(&self) -> uint { self.size } } impl Mutable for BitvSet { fn clear(&mut self) { self.bitv.each_storage(|w| { *w = 0; true }); self.size = 0; } } impl Set<uint> for BitvSet { fn contains(&self, value: &uint) -> bool { *value < self.bitv.storage.len() * uint::BITS && self.bitv.get(*value) } fn is_disjoint(&self, other: &BitvSet) -> bool { self.intersection(other, |_| false) } fn is_subset(&self, other: &BitvSet) -> bool { for (_, w1, w2) in self.commons(other) { if w1 & w2 != w1 { return false; } } /* If anything is not ours, then everything is not ours so we're definitely a subset in that case. Otherwise if there's any stray ones that 'other' doesn't have, we're not a subset. */ for (mine, _, w) in self.outliers(other) { if !mine { return true; } else if w != 0 { return false; } } return true; } fn is_superset(&self, other: &BitvSet) -> bool { other.is_subset(self) } } impl MutableSet<uint> for BitvSet { fn insert(&mut self, value: uint) -> bool { if self.contains(&value) { return false; } let nbits = self.capacity(); if value >= nbits { let newsize = cmp::max(value, nbits * 2) / uint::BITS + 1; assert!(newsize > self.bitv.storage.len()); self.bitv.storage.grow(newsize, &0); } self.size += 1; self.bitv.set(value, true); return true; } fn remove(&mut self, value: &uint) -> bool { if !self.contains(value) { return false; } self.size -= 1; self.bitv.set(*value, false); // Attempt to truncate our storage let mut i = self.bitv.storage.len(); while i > 1 && *self.bitv.storage.get(i - 1) == 0 { i -= 1; } self.bitv.storage.truncate(i); return true; } } impl BitvSet { /// Visits each of the words that the two bit vectors (`self` and `other`) /// both have in common. The three yielded arguments are (bit location, /// w1, w2) where the bit location is the number of bits offset so far, /// and w1/w2 are the words coming from the two vectors self, other. fn commons<'a>(&'a self, other: &'a BitvSet) -> Map<'static, ((uint, &'a uint), &'a Vec<uint>), (uint, uint, uint), Zip<Enumerate<slice::Items<'a, uint>>, Repeat<&'a Vec<uint>>>> { let min = cmp::min(self.bitv.storage.len(), other.bitv.storage.len()); self.bitv.storage.slice(0, min).iter().enumerate() .zip(Repeat::new(&other.bitv.storage)) .map(|((i, &w), o_store)| (i * uint::BITS, w, *o_store.get(i))) } /// Visits each word in `self` or `other` that extends beyond the other. This /// will only iterate through one of the vectors, and it only iterates /// over the portion that doesn't overlap with the other one. /// /// The yielded arguments are a `bool`, the bit offset, and a word. The `bool` /// is true if the word comes from `self`, and `false` if it comes from /// `other`. fn outliers<'a>(&'a self, other: &'a BitvSet) -> Map<'static, ((uint, &'a uint), uint), (bool, uint, uint), Zip<Enumerate<slice::Items<'a, uint>>, Repeat<uint>>> { let slen = self.bitv.storage.len(); let olen = other.bitv.storage.len(); if olen < slen { self.bitv.storage.slice_from(olen).iter().enumerate() .zip(Repeat::new(olen)) .map(|((i, &w), min)| (true, (i + min) * uint::BITS, w)) } else { other.bitv.storage.slice_from(slen).iter().enumerate() .zip(Repeat::new(slen)) .map(|((i, &w), min)| (false, (i + min) * uint::BITS, w)) } } } pub struct BitPositions<'a> { set: &'a BitvSet, next_idx: uint } impl<'a> Iterator<uint> for BitPositions<'a> { #[inline] fn next(&mut self) -> Option<uint> { while self.next_idx < self.set.capacity() { let idx = self.next_idx; self.next_idx += 1; if self.set.contains(&idx) { return Some(idx); } } return None; } fn size_hint(&self) -> (uint, Option<uint>) { (0, Some(self.set.capacity() - self.next_idx)) } } #[cfg(test)] mod tests { extern crate test; use self::test::Bencher; use bitv::{Bitv, SmallBitv, BigBitv, BitvSet, from_bools, from_fn, from_bytes}; use bitv; use std::uint; use rand; use rand::Rng; static BENCH_BITS : uint = 1 << 14; #[test] fn test_to_str() { let zerolen = Bitv::new(0u, false); assert_eq!(zerolen.to_str(), "".to_owned()); let eightbits = Bitv::new(8u, false); assert_eq!(eightbits.to_str(), "00000000".to_owned()); } #[test] fn test_0_elements() { let act = Bitv::new(0u, false); let exp = Vec::from_elem(0u, false); assert!(act.eq_vec(exp.as_slice())); } #[test] fn test_1_element() { let mut act = Bitv::new(1u, false); assert!(act.eq_vec([false])); act = Bitv::new(1u, true); assert!(act.eq_vec([true])); } #[test] fn test_2_elements() { let mut b = bitv::Bitv::new(2, false); b.set(0, true); b.set(1, false); assert_eq!(b.to_str(), "10".to_owned()); } #[test] fn test_10_elements() { let mut act; // all 0 act = Bitv::new(10u, false); assert!((act.eq_vec( [false, false, false, false, false, false, false, false, false, false]))); // all 1 act = Bitv::new(10u, true); assert!((act.eq_vec([true, true, true, true, true, true, true, true, true, true]))); // mixed act = Bitv::new(10u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); assert!((act.eq_vec([true, true, true, true, true, false, false, false, false, false]))); // mixed act = Bitv::new(10u, false); act.set(5u, true); act.set(6u, true); act.set(7u, true); act.set(8u, true); act.set(9u, true); assert!((act.eq_vec([false, false, false, false, false, true, true, true, true, true]))); // mixed act = Bitv::new(10u, false); act.set(0u, true); act.set(3u, true); act.set(6u, true); act.set(9u, true); assert!((act.eq_vec([true, false, false, true, false, false, true, false, false, true]))); } #[test] fn test_31_elements() { let mut act; // all 0 act = Bitv::new(31u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::new(31u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::new(31u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::new(31u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false])); // mixed act = Bitv::new(31u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true])); // mixed act = Bitv::new(31u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true])); } #[test] fn test_32_elements() { let mut act; // all 0 act = Bitv::new(32u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::new(32u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::new(32u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::new(32u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false])); // mixed act = Bitv::new(32u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true])); // mixed act = Bitv::new(32u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true])); } #[test] fn test_33_elements() { let mut act; // all 0 act = Bitv::new(33u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::new(33u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::new(33u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::new(33u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::new(33u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false])); // mixed act = Bitv::new(33u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); act.set(31u, true); act.set(32u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true])); } #[test] fn test_equal_differing_sizes() { let v0 = Bitv::new(10u, false); let v1 = Bitv::new(11u, false); assert!(!v0.equal(&v1)); } #[test] fn test_equal_greatly_differing_sizes() { let v0 = Bitv::new(10u, false); let v1 = Bitv::new(110u, false); assert!(!v0.equal(&v1)); } #[test] fn test_equal_sneaky_small() { let mut a = bitv::Bitv::new(1, false); a.set(0, true); let mut b = bitv::Bitv::new(1, true); b.set(0, true); assert!(a.equal(&b)); } #[test] fn test_equal_sneaky_big() { let mut a = bitv::Bitv::new(100, false); for i in range(0u, 100) { a.set(i, true); } let mut b = bitv::Bitv::new(100, true); for i in range(0u, 100) { b.set(i, true); } assert!(a.equal(&b)); } #[test] fn test_from_bytes() { let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); let str = "10110110".to_owned() + "00000000" + "11111111"; assert_eq!(bitv.to_str(), str); } #[test] fn test_to_bytes() { let mut bv = Bitv::new(3, true); bv.set(1, false); assert_eq!(bv.to_bytes(), vec!(0b10100000)); let mut bv = Bitv::new(9, false); bv.set(2, true); bv.set(8, true); assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000)); } #[test] fn test_from_bools() { assert!(from_bools([true, false, true, true]).to_str() == "1011".to_owned()); } #[test] fn test_to_bools() { let bools = vec!(false, false, true, false, false, true, true, false); assert_eq!(from_bytes([0b00100110]).to_bools(), bools); } #[test] fn test_bitv_iterator() { let bools = [true, false, true, true]; let bitv = from_bools(bools); for (act, &ex) in bitv.iter().zip(bools.iter()) { assert_eq!(ex, act); } } #[test] fn test_bitv_set_iterator() { let bools = [true, false, true, true]; let bitv = BitvSet::from_bitv(from_bools(bools)); let idxs: Vec<uint> = bitv.iter().collect(); assert_eq!(idxs, vec!(0, 2, 3)); } #[test] fn test_bitv_set_frombitv_init() { let bools = [true, false]; let lengths = [10, 64, 100]; for &b in bools.iter() { for &l in lengths.iter() { let bitset = BitvSet::from_bitv(Bitv::new(l, b)); assert_eq!(bitset.contains(&1u), b) assert_eq!(bitset.contains(&(l-1u)), b) assert!(!bitset.contains(&l)) } } } #[test] fn test_small_difference() { let mut b1 = Bitv::new(3, false); let mut b2 = Bitv::new(3, false); b1.set(0, true); b1.set(1, true); b2.set(1, true); b2.set(2, true); assert!(b1.difference(&b2)); assert!(b1[0]); assert!(!b1[1]); assert!(!b1[2]); } #[test] fn test_big_difference() { let mut b1 = Bitv::new(100, false); let mut b2 = Bitv::new(100, false); b1.set(0, true); b1.set(40, true); b2.set(40, true); b2.set(80, true); assert!(b1.difference(&b2)); assert!(b1[0]); assert!(!b1[40]); assert!(!b1[80]); } #[test] fn test_small_clear() { let mut b = Bitv::new(14, true); b.clear(); b.ones(|i| { fail!("found 1 at {:?}", i) }); } #[test] fn test_big_clear() { let mut b = Bitv::new(140, true); b.clear(); b.ones(|i| { fail!("found 1 at {:?}", i) }); } #[test] fn test_bitv_set_basic() { let mut b = BitvSet::new(); assert!(b.insert(3)); assert!(!b.insert(3)); assert!(b.contains(&3)); assert!(b.insert(400)); assert!(!b.insert(400)); assert!(b.contains(&400)); assert_eq!(b.len(), 2); } #[test] fn test_bitv_set_intersection() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(11)); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(77)); assert!(a.insert(103)); assert!(a.insert(5)); assert!(b.insert(2)); assert!(b.insert(11)); assert!(b.insert(77)); assert!(b.insert(5)); assert!(b.insert(3)); let mut i = 0; let expected = [3, 5, 11, 77]; a.intersection(&b, |x| { assert_eq!(*x, expected[i]); i += 1; true }); assert_eq!(i, expected.len()); } #[test] fn test_bitv_set_difference() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(200)); assert!(a.insert(500)); assert!(b.insert(3)); assert!(b.insert(200)); let mut i = 0; let expected = [1, 5, 500]; a.difference(&b, |x| { assert_eq!(*x, expected[i]); i += 1; true }); assert_eq!(i, expected.len()); } #[test] fn test_bitv_set_symmetric_difference() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(b.insert(3)); assert!(b.insert(9)); assert!(b.insert(14)); assert!(b.insert(220)); let mut i = 0; let expected = [1, 5, 11, 14, 220]; a.symmetric_difference(&b, |x| { assert_eq!(*x, expected[i]); i += 1; true }); assert_eq!(i, expected.len()); } #[test] fn test_bitv_set_union() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(a.insert(160)); assert!(a.insert(19)); assert!(a.insert(24)); assert!(b.insert(1)); assert!(b.insert(5)); assert!(b.insert(9)); assert!(b.insert(13)); assert!(b.insert(19)); let mut i = 0; let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160]; a.union(&b, |x| { assert_eq!(*x, expected[i]); i += 1; true }); assert_eq!(i, expected.len()); } #[test] fn test_bitv_remove() { let mut a = BitvSet::new(); assert!(a.insert(1)); assert!(a.remove(&1)); assert!(a.insert(100)); assert!(a.remove(&100)); assert!(a.insert(1000)); assert!(a.remove(&1000)); assert_eq!(a.capacity(), uint::BITS); } #[test] fn test_bitv_clone() { let mut a = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(100)); assert!(a.insert(1000)); let mut b = a.clone(); assert!(a == b); assert!(b.remove(&1)); assert!(a.contains(&1)); assert!(a.remove(&1000)); assert!(b.contains(&1000)); } #[test] fn test_small_bitv_tests() { let v = from_bytes([0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = from_bytes([0b00010100]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = from_bytes([0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); } #[test] fn test_big_bitv_tests() { let v = from_bytes([ // 88 bits 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = from_bytes([ // 88 bits 0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = from_bytes([ // 88 bits 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); } fn rng() -> rand::IsaacRng { let seed = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; rand::SeedableRng::from_seed(seed) } #[bench] fn bench_uint_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = 0 as uint; b.iter(|| { bitv |= 1 << ((r.next_u32() as uint) % uint::BITS); &bitv }) } #[bench] fn bench_small_bitv_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = SmallBitv::new(uint::BITS); b.iter(|| { bitv.set((r.next_u32() as uint) % uint::BITS, true); &bitv }) } #[bench] fn bench_big_bitv_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = BigBitv::new(vec!(0)); b.iter(|| { bitv.set((r.next_u32() as uint) % uint::BITS, true); &bitv }) } #[bench] fn bench_big_bitv_big(b: &mut Bencher) { let mut r = rng(); let mut storage = vec!(); storage.grow(BENCH_BITS / uint::BITS, &0u); let mut bitv = BigBitv::new(storage); b.iter(|| { bitv.set((r.next_u32() as uint) % BENCH_BITS, true); &bitv }) } #[bench] fn bench_bitv_big(b: &mut Bencher) { let mut r = rng(); let mut bitv = Bitv::new(BENCH_BITS, false); b.iter(|| { bitv.set((r.next_u32() as uint) % BENCH_BITS, true); &bitv }) } #[bench] fn bench_bitv_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = Bitv::new(uint::BITS, false); b.iter(|| { bitv.set((r.next_u32() as uint) % uint::BITS, true); &bitv }) } #[bench] fn bench_bitv_set_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = BitvSet::new(); b.iter(|| { bitv.insert((r.next_u32() as uint) % uint::BITS); &bitv }) } #[bench] fn bench_bitv_set_big(b: &mut Bencher) { let mut r = rng(); let mut bitv = BitvSet::new(); b.iter(|| { bitv.insert((r.next_u32() as uint) % BENCH_BITS); &bitv }) } #[bench] fn bench_bitv_big_union(b: &mut Bencher) { let mut b1 = Bitv::new(BENCH_BITS, false); let b2 = Bitv::new(BENCH_BITS, false); b.iter(|| { b1.union(&b2); }) } #[bench] fn bench_btv_small_iter(b: &mut Bencher) { let bitv = Bitv::new(uint::BITS, false); b.iter(|| { let mut _sum = 0; for pres in bitv.iter() { _sum += pres as uint; } }) } #[bench] fn bench_bitv_big_iter(b: &mut Bencher) { let bitv = Bitv::new(BENCH_BITS, false); b.iter(|| { let mut _sum = 0; for pres in bitv.iter() { _sum += pres as uint; } }) } #[bench] fn bench_bitvset_iter(b: &mut Bencher) { let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS, |idx| {idx % 3 == 0})); b.iter(|| { let mut _sum = 0; for idx in bitv.iter() { _sum += idx; } }) } }<|fim▁end|>
}
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use std::path::Path; use std::sync::{Arc, Mutex}; use std::{fs::create_dir_all, path::PathBuf}; use anyhow::{bail, Result}; use crossbeam_channel::{unbounded, Sender}; use log::{error, warn}; use pueue_lib::network::certificate::create_certificates; use pueue_lib::network::message::{Message, Shutdown}; use pueue_lib::network::protocol::socket_cleanup; use pueue_lib::network::secret::init_shared_secret; use pueue_lib::settings::Settings; use pueue_lib::state::State; use self::state_helper::{restore_state, save_state}; use crate::network::socket::accept_incoming; use crate::task_handler::TaskHandler; pub mod cli; mod network; mod pid; mod platform; /// Contains re-usable helper functions, that operate on the pueue-lib state. pub mod state_helper; mod task_handler; /// The main entry point for the daemon logic. /// It's basically the `main`, but publicly exported as a library. /// That way we can properly do integration testing for the daemon. /// /// For the purpose of testing, some things shouldn't be run during tests. /// There are some global operations that crash during tests, such as the ctlc handler. /// This is due to the fact, that tests in the same file are executed in multiple threads. /// Since the threads own the same global space, this would crash. pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> { // Try to read settings from the configuration file. let (mut settings, config_found) = Settings::read(&config_path)?; // We couldn't find a configuration file. // This probably means that Pueue has been started for the first time and we have to create a // default config file once. if !config_found { if let Err(error) = settings.save(&config_path) { bail!("Failed saving config file: {error:?}."); } }; // Load any requested profile. if let Some(profile) = &profile { settings.load_profile(profile)?; } #[allow(deprecated)] if settings.daemon.groups.is_some() { error!( "Please delete the 'daemon.groups' section from your config file. \n\ It is no longer used and groups can now only be edited via the commandline interface. \n\n\ Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!" ) } init_directories(&settings.shared.pueue_directory()); if !settings.shared.daemon_key().exists() && !settings.shared.daemon_cert().exists() { create_certificates(&settings.shared)?; } init_shared_secret(&settings.shared.shared_secret_path())?; pid::create_pid_file(&settings.shared.pueue_directory())?; // Restore the previous state and save any changes that might have happened during this // process. If no previous state exists, just create a new one. // Create a new empty state if any errors occur, but print the error message. let mut state = match restore_state(&settings.shared.pueue_directory()) { Ok(Some(state)) => state, Ok(None) => State::new(&settings, config_path.clone()), Err(error) => { warn!("Failed to restore previous state:\n {error:?}"); warn!("Using clean state instead."); State::new(&settings, config_path.clone()) } }; state.settings = settings.clone(); save_state(&state)?; let state = Arc::new(Mutex::new(state)); let (sender, receiver) = unbounded(); let mut task_handler = TaskHandler::new(state.clone(), receiver); // Don't set ctrlc and panic handlers during testing. // This is necessary for multithreaded integration testing, since multiple listener per process // aren't prophibited. On top of this, ctrlc also somehow breaks test error output. if !test { setup_signal_panic_handling(&settings, &sender)?; } std::thread::spawn(move || { task_handler.run(); }); accept_incoming(sender, state.clone()).await?; Ok(()) } /// Initialize all directories needed for normal operation. fn init_directories(pueue_dir: &Path) { // Pueue base path if !pueue_dir.exists() { if let Err(error) = create_dir_all(&pueue_dir) { panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}"); } } // Task log dir let log_dir = pueue_dir.join("log"); if !log_dir.exists() { if let Err(error) = create_dir_all(&log_dir) { panic!("Failed to create log directory at {log_dir:?} error: {error:?}",); } } // Task certs dir let certs_dir = pueue_dir.join("certs"); if !certs_dir.exists() { if let Err(error) = create_dir_all(&certs_dir) { panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}"); } } // Task log dir let logs_dir = pueue_dir.join("task_logs"); if !logs_dir.exists() { if let Err(error) = create_dir_all(&logs_dir) { panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}"); } } } /// Setup signal handling and panic handling. /// /// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the /// TaskHandler. This is to prevent dangling processes and other weird edge-cases. /// /// On panic, we want to cleanup existing unix sockets and the PID file. fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> { let sender_clone = sender.clone(); // This section handles Shutdown via SigTerm/SigInt process signals // Notify the TaskHandler, so it can shutdown gracefully. // The actual program exit will be done via the TaskHandler. ctrlc::set_handler(move || { // Notify the task handler sender_clone .send(Message::DaemonShutdown(Shutdown::Emergency)) .expect("Failed to send Message to TaskHandler on Shutdown"); })?; // Try to do some final cleanup, even if we panic. let settings_clone = settings.clone(); let orig_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { // invoke the default handler and exit the process<|fim▁hole|> // Cleanup the pid file if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) { println!("Failed to cleanup pid after panic."); println!("{error}"); } // Remove the unix socket. if let Err(error) = socket_cleanup(&settings_clone.shared) { println!("Failed to cleanup socket after panic."); println!("{error}"); } std::process::exit(1); })); Ok(()) }<|fim▁end|>
orig_hook(panic_info);
<|file_name|>errors.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)] pub struct Errors { errors: RefCell<Vec<syn::Error>>, } /// Produce functions to expect particular variants of `syn::Lit` macro_rules! expect_lit_fn { ($(($fn_name:ident, $syn_type:ident, $variant:ident, $lit_name:literal),)*) => { $( pub fn $fn_name<'a>(&self, lit: &'a syn::Lit) -> Option<&'a syn::$syn_type> { if let syn::Lit::$variant(inner) = lit { Some(inner) } else { self.unexpected_lit($lit_name, lit); None } }<|fim▁hole|> )* } } /// Produce functions to expect particular variants of `syn::Meta` macro_rules! expect_meta_fn { ($(($fn_name:ident, $syn_type:ident, $variant:ident, $meta_name:literal),)*) => { $( pub fn $fn_name<'a>(&self, meta: &'a syn::Meta) -> Option<&'a syn::$syn_type> { if let syn::Meta::$variant(inner) = meta { Some(inner) } else { self.unexpected_meta($meta_name, meta); None } } )* } } impl Errors { /// Issue an error like: /// /// Duplicate foo attribute /// First foo attribute here pub fn duplicate_attrs( &self, attr_kind: &str, first: &impl syn::spanned::Spanned, second: &impl syn::spanned::Spanned, ) { self.duplicate_attrs_inner(attr_kind, first.span(), second.span()) } fn duplicate_attrs_inner(&self, attr_kind: &str, first: Span, second: Span) { self.err_span(second, &["Duplicate ", attr_kind, " attribute"].concat()); self.err_span(first, &["First ", attr_kind, " attribute here"].concat()); } /// Error on literals, expecting attribute syntax. pub fn expect_nested_meta<'a>(&self, nm: &'a syn::NestedMeta) -> Option<&'a syn::Meta> { match nm { syn::NestedMeta::Lit(l) => { self.err(l, "Unexpected literal"); None } syn::NestedMeta::Meta(m) => Some(m), } } /// Error on attribute syntax, expecting literals pub fn expect_nested_lit<'a>(&self, nm: &'a syn::NestedMeta) -> Option<&'a syn::Lit> { match nm { syn::NestedMeta::Meta(m) => { self.err(m, "Expected literal"); None } syn::NestedMeta::Lit(l) => Some(l), } } expect_lit_fn![ (expect_lit_str, LitStr, Str, "string"), (expect_lit_char, LitChar, Char, "character"), (expect_lit_int, LitInt, Int, "integer"), ]; expect_meta_fn![ (expect_meta_word, Path, Path, "path"), (expect_meta_list, MetaList, List, "list"), (expect_meta_name_value, MetaNameValue, NameValue, "name-value pair"), ]; fn unexpected_lit(&self, expected: &str, found: &syn::Lit) { fn lit_kind(lit: &syn::Lit) -> &'static str { use syn::Lit::{Bool, Byte, ByteStr, Char, Float, Int, Str, Verbatim}; match lit { Str(_) => "string", ByteStr(_) => "bytestring", Byte(_) => "byte", Char(_) => "character", Int(_) => "integer", Float(_) => "float", Bool(_) => "boolean", Verbatim(_) => "unknown (possibly extra-large integer)", } } self.err( found, &["Expected ", expected, " literal, found ", lit_kind(found), " literal"].concat(), ) } fn unexpected_meta(&self, expected: &str, found: &syn::Meta) { fn meta_kind(meta: &syn::Meta) -> &'static str { use syn::Meta::{List, NameValue, Path}; match meta { Path(_) => "path", List(_) => "list", NameValue(_) => "name-value pair", } } self.err( found, &["Expected ", expected, " attribute, found ", meta_kind(found), " attribute"].concat(), ) } /// Issue an error relating to a particular `Spanned` structure. pub fn err(&self, spanned: &impl syn::spanned::Spanned, msg: &str) { self.err_span(spanned.span(), msg); } /// Issue an error relating to a particular `Span`. pub fn err_span(&self, span: Span, msg: &str) { self.push(syn::Error::new(span, msg)); } /// Push a `syn::Error` onto the list of errors to issue. pub fn push(&self, err: syn::Error) { self.errors.borrow_mut().push(err); } } impl ToTokens for Errors { /// Convert the errors into tokens that, when emit, will cause /// the user of the macro to receive compiler errors. fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.errors.borrow().iter().map(|e| e.to_compile_error())); } }<|fim▁end|>
<|file_name|>slot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- class Slot(object): """ To use comb, you should create a python module file. we named *slot*. A legal slot must be named 'Slot' in your module file and it must be at least contain four method: * `initialize` initial resource, e.g: database handle * `__enter__` get next data to do,you can fetch one or more data. * `slot` user custom code * `__exit__` when slot finished, call this method """ def __init__(self, combd): """Don't override this method unless what you're doing. """ self.threads_num = combd.threads_num self.sleep = combd.sleep self.sleep_max = combd.sleep_max self.debug = combd.debug self.combd = combd self.initialize() def initialize(self): """Hook for subclass initialization.<|fim▁hole|> This block is execute before thread initial Example:: class UserSlot(Slot): def initialize(self): self.threads_num = 10 def slot(self, result): ... """ pass def __enter__(self): """You **MUST** return False when no data to do. The return value will be used in `Slot.slot` """ print("You should override __enter__ method by subclass") return False def __exit__(self, exc_type, exc_val, exc_tb): """When slot done, will call this method. """ print("You should override __exit__ method by subclass") pass def slot(self, msg): """ Add your custom code at here. For example, look at: * `comb.demo.list` * `comb.demo.mongo` * `comb.demo.redis` """ pass # @staticmethod # def options(): # """ # replace this method if you want add user options # :return: # """ # return () # pass<|fim▁end|>
<|file_name|>test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # # # copyright Kevin Walchko # # Basically a rostopic from __future__ import print_function import argparse import time # from pygecko import TopicSub from pygecko.transport import zmqTCP, GeckoCore from pygecko.multiprocessing import GeckoPy from pygecko.test import GeckoSimpleProcess # from pygecko.transport.zmqclass import # def publisher(**kwargs): # geckopy = GeckoPy() # # p = geckopy.Publisher() # # hertz = kwargs.get('rate', 10) # rate = geckopy.Rate(hertz) # # topic = kwargs.get('topic') # msg = kwargs.get('msg') # # cnt = 0 # start = time.time() # while not geckopy.is_shutdown(): # p.pub(topic, msg) # topic msg # if cnt % hertz == 0: # print(">> {}[{:.1f}]: published {} msgs".format(topic, time.time()-start, hertz)) # cnt += 1 # rate.sleep() def subscriber(**kwargs): geckopy = GeckoPy(**kwargs) def f(topic, msg): print(">> {}: {}".format(topic, msg)) topic = kwargs.get('topic') s = geckopy.Subscriber([topic], f) geckopy.spin() if __name__ == '__main__': p = GeckoSimpleProcess() p.start(func=subscriber, name='subscriber', kwargs=args) # while True: # try: # time.sleep(1) # except KeyboardInterrupt: # break #<|fim▁hole|><|fim▁end|>
# # shutdown the processes # p.join(0.1)
<|file_name|>factory.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use std::{slice, ptr}; use {gl, tex}; use core::{self as d, factory as f, texture as t, buffer, mapping}; use core::memory::{self, Bind, SHADER_RESOURCE, UNORDERED_ACCESS, Typed}; use core::format::ChannelType; use core::handle::{self, Producer}; use core::target::{Layer, Level}; use command::{CommandBuffer, COLOR_DEFAULT}; use {Resources as R, Share, OutputMerger}; use {Buffer, BufferElement, FatSampler, NewTexture, PipelineState, ResourceView, TargetView, Fence}; pub fn role_to_target(role: buffer::Role) -> gl::types::GLenum { match role { buffer::Role::Vertex => gl::ARRAY_BUFFER, buffer::Role::Index => gl::ELEMENT_ARRAY_BUFFER, buffer::Role::Constant => gl::UNIFORM_BUFFER, buffer::Role::Staging => gl::ARRAY_BUFFER, } } fn access_to_map_bits(access: memory::Access) -> gl::types::GLenum { let mut r = 0; if access.contains(memory::READ) { r |= gl::MAP_READ_BIT; } if access.contains(memory::WRITE) { r |= gl::MAP_WRITE_BIT; } r } fn access_to_gl(access: memory::Access) -> gl::types::GLenum { match access { memory::RW => gl::READ_WRITE, memory::READ => gl::READ_ONLY, memory::WRITE => gl::WRITE_ONLY, _ => unreachable!(), } } pub fn update_sub_buffer(gl: &gl::Gl, buffer: Buffer, address: *const u8, size: usize, offset: usize, role: buffer::Role) { let target = role_to_target(role); unsafe { gl.BindBuffer(target, buffer); gl.BufferSubData(target, offset as gl::types::GLintptr, size as gl::types::GLsizeiptr, address as *const gl::types::GLvoid ); } } /// GL resource factory. pub struct Factory { share: Rc<Share>, frame_handles: handle::Manager<R>, } impl Clone for Factory { fn clone(&self) -> Factory { Factory::new(self.share.clone()) } } impl Factory { /// Create a new `Factory`. pub fn new(share: Rc<Share>) -> Factory { Factory { share: share, frame_handles: handle::Manager::new(), } } pub fn create_command_buffer(&mut self) -> CommandBuffer { CommandBuffer::new(self.create_fbo_internal()) } fn create_fbo_internal(&mut self) -> gl::types::GLuint { let gl = &self.share.context; let mut name = 0 as ::FrameBuffer; unsafe { gl.GenFramebuffers(1, &mut name); } info!("\tCreated frame buffer {}", name); name } fn create_buffer_internal(&mut self) -> Buffer { let gl = &self.share.context; let mut name = 0 as Buffer; unsafe { gl.GenBuffers(1, &mut name); } info!("\tCreated buffer {}", name); name } fn init_buffer(&mut self, buffer: Buffer, info: &buffer::Info, data_opt: Option<&[u8]>) -> Option<MappingGate> { use core::memory::Usage::*; let gl = &self.share.context; let target = role_to_target(info.role); let mut data_ptr = if let Some(data) = data_opt { debug_assert!(data.len() == info.size); data.as_ptr() as *const gl::types::GLvoid } else { 0 as *const gl::types::GLvoid }; if self.share.private_caps.buffer_storage_supported { let usage = match info.usage { Data => 0, // TODO: we could use mapping instead of glBufferSubData Dynamic => gl::DYNAMIC_STORAGE_BIT, Upload => access_to_map_bits(memory::WRITE) | gl::MAP_PERSISTENT_BIT, Download => access_to_map_bits(memory::READ) | gl::MAP_PERSISTENT_BIT, }; let size = if info.size == 0 { // we are not allowed to pass size=0 into `glBufferStorage` data_ptr = 0 as *const _; 1 } else { info.size as gl::types::GLsizeiptr }; unsafe { gl.BindBuffer(target, buffer); gl.BufferStorage(target, size, data_ptr, usage ); } } else { let usage = match info.usage { Data => gl::STATIC_DRAW, Dynamic => gl::DYNAMIC_DRAW, Upload => gl::STREAM_DRAW, Download => gl::STREAM_READ, }; unsafe { gl.BindBuffer(target, buffer); gl.BufferData(target, info.size as gl::types::GLsizeiptr, data_ptr, usage ); } } if let Err(err) = self.share.check() { panic!("Error {:?} creating buffer: {:?}", err, info) } let mapping_access = match info.usage { Data | Dynamic => None, Upload => Some(memory::WRITE), Download => Some(memory::READ), }; mapping_access.map(|access| { let (kind, ptr) = if self.share.private_caps.buffer_storage_supported { let mut gl_access = access_to_map_bits(access) | gl::MAP_PERSISTENT_BIT; if access.contains(memory::WRITE) { gl_access |= gl::MAP_FLUSH_EXPLICIT_BIT; } let size = info.size as isize; let ptr = unsafe { gl.BindBuffer(target, buffer); gl.MapBufferRange(target, 0, size, gl_access) } as *mut ::std::os::raw::c_void; (MappingKind::Persistent(mapping::Status::clean()), ptr) } else { (MappingKind::Temporary, ptr::null_mut()) }; if let Err(err) = self.share.check() { panic!("Error {:?} mapping buffer: {:?}, with access: {:?}", err, info, access) } MappingGate { kind: kind, pointer: ptr, } }) } fn create_program_raw(&mut self, shader_set: &d::ShaderSet<R>) -> Result<(gl::types::GLuint, d::shade::ProgramInfo), d::shade::CreateProgramError> { use shade::create_program; let frame_handles = &mut self.frame_handles; let mut shaders = [0; 5]; let usage = shader_set.get_usage(); let shader_slice = match shader_set { &d::ShaderSet::Simple(ref vs, ref ps) => { shaders[0] = *vs.reference(frame_handles); shaders[1] = *ps.reference(frame_handles); &shaders[..2] }, &d::ShaderSet::Geometry(ref vs, ref gs, ref ps) => { shaders[0] = *vs.reference(frame_handles); shaders[1] = *gs.reference(frame_handles); shaders[2] = *ps.reference(frame_handles); &shaders[..3] }, &d::ShaderSet::Tessellated(ref vs, ref hs, ref ds, ref ps) => { shaders[0] = *vs.reference(frame_handles); shaders[1] = *hs.reference(frame_handles); shaders[2] = *ds.reference(frame_handles); shaders[3] = *ps.reference(frame_handles); &shaders[..4] }, }; let result = create_program(&self.share.context, &self.share.capabilities, &self.share.private_caps, shader_slice, usage); if let Err(err) = self.share.check() { panic!("Error {:?} creating program: {:?}", err, shader_set) } result } fn view_texture_as_target(&mut self, htex: &handle::RawTexture<R>, level: Level, layer: Option<Layer>) -> Result<TargetView, f::TargetViewError> { match (self.frame_handles.ref_texture(htex), layer) { (&NewTexture::Surface(_), Some(_)) => Err(f::TargetViewError::Unsupported), (&NewTexture::Surface(_), None) if level != 0 => Err(f::TargetViewError::Unsupported), (&NewTexture::Surface(s), None) => Ok(TargetView::Surface(s)), (&NewTexture::Texture(t), Some(l)) => Ok(TargetView::TextureLayer(t, level, l)), (&NewTexture::Texture(t), None) => Ok(TargetView::Texture(t, level)), } } } #[derive(Debug, PartialEq, Eq, Hash)] pub enum MappingKind { Persistent(mapping::Status<R>), Temporary, } #[derive(Debug, Eq, Hash, PartialEq)] #[allow(missing_copy_implementations)] pub struct MappingGate { pub kind: MappingKind, pub pointer: *mut ::std::os::raw::c_void, } unsafe impl Send for MappingGate {} unsafe impl Sync for MappingGate {} impl mapping::Gate<R> for MappingGate { unsafe fn set<T>(&self, index: usize, val: T) { *(self.pointer as *mut T).offset(index as isize) = val; } unsafe fn slice<'a, 'b, T>(&'a self, len: usize) -> &'b [T] { slice::from_raw_parts(self.pointer as *const T, len)<|fim▁hole|> } unsafe fn mut_slice<'a, 'b, T>(&'a self, len: usize) -> &'b mut [T] { slice::from_raw_parts_mut(self.pointer as *mut T, len) } } pub fn temporary_ensure_mapped(pointer: &mut *mut ::std::os::raw::c_void, target: gl::types::GLenum, buffer: Buffer, access: memory::Access, gl: &gl::Gl) { if pointer.is_null() { unsafe { gl.BindBuffer(target, buffer); *pointer = gl.MapBuffer(target, access_to_gl(access)) as *mut ::std::os::raw::c_void; } } } pub fn temporary_ensure_unmapped(pointer: &mut *mut ::std::os::raw::c_void, target: gl::types::GLenum, buffer: Buffer, gl: &gl::Gl) { if !pointer.is_null() { unsafe { gl.BindBuffer(target, buffer); gl.UnmapBuffer(target); } *pointer = ptr::null_mut(); } } impl f::Factory<R> for Factory { fn get_capabilities(&self) -> &d::Capabilities { &self.share.capabilities } fn create_buffer_raw(&mut self, info: buffer::Info) -> Result<handle::RawBuffer<R>, buffer::CreationError> { if !self.share.capabilities.constant_buffer_supported && info.role == buffer::Role::Constant { error!("Constant buffers are not supported by this GL version"); return Err(buffer::CreationError::Other); } let name = self.create_buffer_internal(); let mapping = self.init_buffer(name, &info, None); Ok(self.share.handles.borrow_mut().make_buffer(name, info, mapping)) } fn create_buffer_immutable_raw(&mut self, data: &[u8], stride: usize, role: buffer::Role, bind: Bind) -> Result<handle::RawBuffer<R>, buffer::CreationError> { let name = self.create_buffer_internal(); let info = buffer::Info { role: role, usage: memory::Usage::Data, bind: bind, size: data.len(), stride: stride, }; let mapping = self.init_buffer(name, &info, Some(data)); Ok(self.share.handles.borrow_mut().make_buffer(name, info, mapping)) } fn create_shader(&mut self, stage: d::shade::Stage, code: &[u8]) -> Result<handle::Shader<R>, d::shade::CreateShaderError> { ::shade::create_shader(&self.share.context, stage, code) .map(|sh| self.share.handles.borrow_mut().make_shader(sh)) } fn create_program(&mut self, shader_set: &d::ShaderSet<R>) -> Result<handle::Program<R>, d::shade::CreateProgramError> { self.create_program_raw(shader_set) .map(|(name, info)| self.share.handles.borrow_mut().make_program(name, info)) } fn create_pipeline_state_raw(&mut self, program: &handle::Program<R>, desc: &d::pso::Descriptor) -> Result<handle::RawPipelineState<R>, d::pso::CreationError> { use core::state as s; let caps = &self.share.capabilities; match desc.primitive { d::Primitive::PatchList(num) if num == 0 || (num as usize) > caps.max_patch_size => return Err(d::pso::CreationError), _ => () } let mut output = OutputMerger { draw_mask: 0, stencil: match desc.depth_stencil { Some((_, t)) if t.front.is_some() || t.back.is_some() => Some(s::Stencil { front: t.front.unwrap_or_default(), back: t.back.unwrap_or_default(), }), _ => None, }, depth: desc.depth_stencil.and_then(|(_, t)| t.depth), colors: [COLOR_DEFAULT; d::MAX_COLOR_TARGETS], }; for i in 0 .. d::MAX_COLOR_TARGETS { if let Some((_, ref bi)) = desc.color_targets[i] { output.draw_mask |= 1<<i; output.colors[i].mask = bi.mask; if bi.color.is_some() || bi.alpha.is_some() { output.colors[i].blend = Some(s::Blend { color: bi.color.unwrap_or_default(), alpha: bi.alpha.unwrap_or_default(), }); } } } let mut inputs = [None; d::MAX_VERTEX_ATTRIBUTES]; for i in 0 .. d::MAX_VERTEX_ATTRIBUTES { inputs[i] = desc.attributes[i].map(|at| BufferElement { desc: desc.vertex_buffers[at.0 as usize].unwrap(), elem: at.1, }); } let pso = PipelineState { program: *self.frame_handles.ref_program(program), primitive: desc.primitive, input: inputs, scissor: desc.scissor, rasterizer: desc.rasterizer, output: output, }; Ok(self.share.handles.borrow_mut().make_pso(pso, program)) } fn create_texture_raw(&mut self, desc: t::Info, hint: Option<ChannelType>, data_opt: Option<&[&[u8]]>) -> Result<handle::RawTexture<R>, t::CreationError> { use core::texture::CreationError; let caps = &self.share.private_caps; if desc.levels == 0 { return Err(CreationError::Size(0)) } let dim = desc.kind.get_dimensions(); let max_size = self.share.capabilities.max_texture_size; if dim.0 as usize > max_size { return Err(CreationError::Size(dim.0)); } if dim.1 as usize > max_size { return Err(CreationError::Size(dim.1)); } let cty = hint.unwrap_or(ChannelType::Uint); //careful here let gl = &self.share.context; let object = if desc.bind.intersects(SHADER_RESOURCE | UNORDERED_ACCESS) || data_opt.is_some() { let name = if caps.immutable_storage_supported { try!(tex::make_with_storage(gl, &desc, cty)) } else { try!(tex::make_without_storage(gl, &desc, cty)) }; if let Some(data) = data_opt { try!(tex::init_texture_data(gl, name, desc, cty, data)); } NewTexture::Texture(name) }else { let name = try!(tex::make_surface(gl, &desc, cty)); NewTexture::Surface(name) }; if let Err(err) = self.share.check() { panic!("Error {:?} creating texture: {:?}, hint: {:?}", err, desc, hint) } Ok(self.share.handles.borrow_mut().make_texture(object, desc)) } fn view_buffer_as_shader_resource_raw(&mut self, hbuf: &handle::RawBuffer<R>) -> Result<handle::RawShaderResourceView<R>, f::ResourceViewError> { let gl = &self.share.context; let mut name = 0 as gl::types::GLuint; let buf_name = *self.frame_handles.ref_buffer(hbuf); let format = gl::R8; //TODO: get from the buffer handle unsafe { gl.GenTextures(1, &mut name); gl.BindTexture(gl::TEXTURE_BUFFER, name); gl.TexBuffer(gl::TEXTURE_BUFFER, format, buf_name); } let view = ResourceView::new_buffer(name); if let Err(err) = self.share.check() { panic!("Error {:?} creating buffer SRV: {:?}", err, hbuf.get_info()) } Ok(self.share.handles.borrow_mut().make_buffer_srv(view, hbuf)) } fn view_buffer_as_unordered_access_raw(&mut self, _hbuf: &handle::RawBuffer<R>) -> Result<handle::RawUnorderedAccessView<R>, f::ResourceViewError> { Err(f::ResourceViewError::Unsupported) //TODO } fn view_texture_as_shader_resource_raw(&mut self, htex: &handle::RawTexture<R>, _desc: t::ResourceDesc) -> Result<handle::RawShaderResourceView<R>, f::ResourceViewError> { match self.frame_handles.ref_texture(htex) { &NewTexture::Surface(_) => Err(f::ResourceViewError::NoBindFlag), &NewTexture::Texture(t) => { //TODO: use the view descriptor let view = ResourceView::new_texture(t, htex.get_info().kind); Ok(self.share.handles.borrow_mut().make_texture_srv(view, htex)) }, } } fn view_texture_as_unordered_access_raw(&mut self, _htex: &handle::RawTexture<R>) -> Result<handle::RawUnorderedAccessView<R>, f::ResourceViewError> { Err(f::ResourceViewError::Unsupported) //TODO } fn view_texture_as_render_target_raw(&mut self, htex: &handle::RawTexture<R>, desc: t::RenderDesc) -> Result<handle::RawRenderTargetView<R>, f::TargetViewError> { self.view_texture_as_target(htex, desc.level, desc.layer) .map(|view| { let dim = htex.get_info().kind.get_level_dimensions(desc.level); self.share.handles.borrow_mut().make_rtv(view, htex, dim) }) } fn view_texture_as_depth_stencil_raw(&mut self, htex: &handle::RawTexture<R>, desc: t::DepthStencilDesc) -> Result<handle::RawDepthStencilView<R>, f::TargetViewError> { self.view_texture_as_target(htex, desc.level, desc.layer) .map(|view| { let dim = htex.get_info().kind.get_level_dimensions(0); self.share.handles.borrow_mut().make_dsv(view, htex, dim) }) } fn create_sampler(&mut self, info: t::SamplerInfo) -> handle::Sampler<R> { let name = if self.share.private_caps.sampler_objects_supported { tex::make_sampler(&self.share.context, &info) } else { 0 }; let sam = FatSampler { object: name, info: info.clone(), }; if let Err(err) = self.share.check() { panic!("Error {:?} creating sampler: {:?}", err, info) } self.share.handles.borrow_mut().make_sampler(sam, info) } fn read_mapping<'a, 'b, T>(&'a mut self, buf: &'b handle::Buffer<R, T>) -> Result<mapping::Reader<'b, R, T>, mapping::Error> where T: Copy { let gl = &self.share.context; let handles = &mut self.frame_handles; unsafe { mapping::read(buf.raw(), |mapping| match mapping.kind { MappingKind::Persistent(ref mut status) => status.cpu_access(|fence| wait_fence(&handles.ref_fence(&fence), gl)), MappingKind::Temporary => temporary_ensure_mapped(&mut mapping.pointer, role_to_target(buf.get_info().role), *buf.raw().resource(), memory::READ, gl), }) } } fn write_mapping<'a, 'b, T>(&'a mut self, buf: &'b handle::Buffer<R, T>) -> Result<mapping::Writer<'b, R, T>, mapping::Error> where T: Copy { let gl = &self.share.context; let handles = &mut self.frame_handles; unsafe { mapping::write(buf.raw(), |mapping| match mapping.kind { MappingKind::Persistent(ref mut status) => status.cpu_write_access(|fence| wait_fence(&handles.ref_fence(&fence), gl)), MappingKind::Temporary => temporary_ensure_mapped(&mut mapping.pointer, role_to_target(buf.get_info().role), *buf.raw().resource(), memory::WRITE, gl), }) } } } pub fn wait_fence(fence: &Fence, gl: &gl::Gl) { let timeout = 1_000_000_000_000; // TODO: use the return value of this call // TODO: // This can be called by multiple objects wanting to ensure they have exclusive // access to a resource. How much does this call costs ? The status of the fence // could be cached to avoid calling this more than once (in core or in the backend ?). unsafe { gl.ClientWaitSync(fence.0, gl::SYNC_FLUSH_COMMANDS_BIT, timeout); } }<|fim▁end|>