code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
module.exports = (req, res, next) => { const _registration = req.requestParams.registration const match = { _registration: _registration } return global.models.getAll( global.db.registrations.RegistrationDebaters, match, global.utils.populate.registrationDebaters, res ) }
westoncolemanl/tabbr-api
controllers/registrations/debaters/getAll.js
JavaScript
mit
304
<?php defined('SYSPATH') or die('No direct script access.'); interface Template_Interface extends Kohana_Template_Interface {}
dmitrymomot/kohana-template
classes/Template/Interface.php
PHP
mit
128
<?php namespace Smartbox\Integration\FrameworkBundle\DependencyInjection\Traits; use Smartbox\Integration\FrameworkBundle\Tools\Mapper\MapperInterface; /** * Trait UsesMapper. */ trait UsesMapper { /** @var MapperInterface */ protected $mapper; /** * @return MapperInterface */ public function getMapper() { return $this->mapper; } /** * @param MapperInterface $mapper */ public function setMapper(MapperInterface $mapper) { $this->mapper = $mapper; } }
smartboxgroup/integration-framework-bundle
DependencyInjection/Traits/UsesMapper.php
PHP
mit
537
'use strict' const pkg = require('../package') module.exports = { port: 4000, title: 'slotlist.info - ArmA 3 mission and slotlist management', publicPath: '/', }
MorpheusXAUT/slotlist-frontend
build/config.js
JavaScript
mit
169
require 'rspec' require_relative '../lib/nfe'
PlugaDotCo/nfe_io-ruby
spec/rspec_helper.rb
Ruby
mit
46
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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; }; }(); var get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /* Possible todos: 0. Add XSLT to JML-string stylesheet (or even vice versa) 0. IE problem: Add JsonML code to handle name attribute (during element creation) 0. Element-specific: IE object-param handling Todos inspired by JsonML: https://github.com/mckamey/jsonml/blob/master/jsonml-html.js 0. duplicate attributes? 0. expand ATTR_MAP 0. equivalent of markup, to allow strings to be embedded within an object (e.g., {$value: '<div>id</div>'}); advantage over innerHTML in that it wouldn't need to work as the entire contents (nor destroy any existing content or handlers) 0. More validation? 0. JsonML DOM Level 0 listener 0. Whitespace trimming? JsonML element-specific: 0. table appending 0. canHaveChildren necessary? (attempts to append to script and img) Other Todos: 0. Note to self: Integrate research from other jml notes 0. Allow Jamilih to be seeded with an existing element, so as to be able to add/modify attributes and children 0. Allow array as single first argument 0. Settle on whether need to use null as last argument to return array (or fragment) or other way to allow appending? Options object at end instead to indicate whether returning array, fragment, first element, etc.? 0. Allow building of generic XML (pass configuration object) 0. Allow building content internally as a string (though allowing DOM methods, etc.?) 0. Support JsonML empty string element name to represent fragments? 0. Redo browser testing of jml (including ensuring IE7 can work even if test framework can't work) */ var win = typeof window !== 'undefined' && window; var doc = typeof document !== 'undefined' && document; var XmlSerializer = typeof XMLSerializer !== 'undefined' && XMLSerializer; // STATIC PROPERTIES var possibleOptions = ['$plugins', '$map' // Add any other options here ]; var NS_HTML = 'http://www.w3.org/1999/xhtml', hyphenForCamelCase = /-([a-z])/g; var ATTR_MAP = { 'readonly': 'readOnly' }; // We define separately from ATTR_DOM for clarity (and parity with JsonML) but no current need // We don't set attribute esp. for boolean atts as we want to allow setting of `undefined` // (e.g., from an empty variable) on templates to have no effect var BOOL_ATTS = ['checked', 'defaultChecked', 'defaultSelected', 'disabled', 'indeterminate', 'open', // Dialog elements 'readOnly', 'selected']; var ATTR_DOM = BOOL_ATTS.concat([// From JsonML 'accessKey', // HTMLElement 'async', 'autocapitalize', // HTMLElement 'autofocus', 'contentEditable', // HTMLElement through ElementContentEditable 'defaultValue', 'defer', 'draggable', // HTMLElement 'formnovalidate', 'hidden', // HTMLElement 'innerText', // HTMLElement 'inputMode', // HTMLElement through ElementContentEditable 'ismap', 'multiple', 'novalidate', 'pattern', 'required', 'spellcheck', // HTMLElement 'translate', // HTMLElement 'value', 'willvalidate']); // Todo: Add more to this as useful for templating // to avoid setting through nullish value var NULLABLES = ['dir', // HTMLElement 'lang', // HTMLElement 'max', 'min', 'title' // HTMLElement ]; var $ = function $(sel) { return doc.querySelector(sel); }; var $$ = function $$(sel) { return [].concat(toConsumableArray(doc.querySelectorAll(sel))); }; /** * Retrieve the (lower-cased) HTML name of a node * @static * @param {Node} node The HTML node * @returns {String} The lower-cased node name */ function _getHTMLNodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } /** * Apply styles if this is a style tag * @static * @param {Node} node The element to check whether it is a style tag */ function _applyAnyStylesheet(node) { if (!doc.createStyleSheet) { return; } if (_getHTMLNodeName(node) === 'style') { // IE var ss = doc.createStyleSheet(); // Create a stylesheet to actually do something useful ss.cssText = node.cssText; // We continue to add the style tag, however } } /** * Need this function for IE since options weren't otherwise getting added * @private * @static * @param {DOMElement} parent The parent to which to append the element * @param {DOMNode} child The element or other node to append to the parent */ function _appendNode(parent, child) { var parentName = _getHTMLNodeName(parent); var childName = _getHTMLNodeName(child); if (doc.createStyleSheet) { if (parentName === 'script') { parent.text = child.nodeValue; return; } if (parentName === 'style') { parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents return; } } if (parentName === 'template') { parent.content.appendChild(child); return; } try { parent.appendChild(child); // IE9 is now ok with this } catch (e) { if (parentName === 'select' && childName === 'option') { try { // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first parent.add(child); } catch (err) { // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc. parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok } return; } throw e; } } /** * Attach event in a cross-browser fashion * @static * @param {DOMElement} el DOM element to which to attach the event * @param {String} type The DOM event (without 'on') to attach to the element * @param {Function} handler The event handler to attach to the element * @param {Boolean} [capturing] Whether or not the event should be * capturing (W3C-browsers only); default is false; NOT IN USE */ function _addEvent(el, type, handler, capturing) { el.addEventListener(type, handler, !!capturing); } /** * Creates a text node of the result of resolving an entity or character reference * @param {'entity'|'decimal'|'hexadecimal'} type Type of reference * @param {String} prefix Text to prefix immediately after the "&" * @param {String} arg The body of the reference * @returns {Text} The text node of the resolved reference */ function _createSafeReference(type, prefix, arg) { // For security reasons related to innerHTML, we ensure this string only contains potential entity characters if (!arg.match(/^\w+$/)) { throw new TypeError('Bad ' + type); } var elContainer = doc.createElement('div'); // Todo: No workaround for XML? elContainer.textContent = '&' + prefix + arg + ';'; return doc.createTextNode(elContainer.textContent); } /** * @param {String} n0 Whole expression match (including "-") * @param {String} n1 Lower-case letter match * @returns {String} Uppercased letter */ function _upperCase(n0, n1) { return n1.toUpperCase(); } /** * @private * @static */ function _getType(item) { if (typeof item === 'string') { return 'string'; } if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') { if (item === null) { return 'null'; } if (Array.isArray(item)) { return 'array'; } if ('nodeType' in item) { if (item.nodeType === 1) { return 'element'; } if (item.nodeType === 11) { return 'fragment'; } } return 'object'; } return undefined; } /** * @private * @static */ function _fragReducer(frag, node) { frag.appendChild(node); return frag; } /** * @private * @static */ function _replaceDefiner(xmlnsObj) { return function (n0) { var retStr = xmlnsObj[''] ? ' xmlns="' + xmlnsObj[''] + '"' : n0 || ''; // Preserve XHTML for (var ns in xmlnsObj) { if (xmlnsObj.hasOwnProperty(ns)) { if (ns !== '') { retStr += ' xmlns:' + ns + '="' + xmlnsObj[ns] + '"'; } } } return retStr; }; } function _optsOrUndefinedJML() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return jml.apply(undefined, toConsumableArray(args[0] === undefined ? args.slice(1) : args)); } /** * @private * @static */ function _jmlSingleArg(arg) { return jml(arg); } /** * @private * @static */ function _copyOrderedAtts(attArr) { var obj = {}; // Todo: Fix if allow prefixed attributes obj[attArr[0]] = attArr[1]; // array of ordered attribute-value arrays return obj; } /** * @private * @static */ function _childrenToJML(node) { return function (childNodeJML, i) { var cn = node.childNodes[i]; var j = Array.isArray(childNodeJML) ? jml.apply(undefined, toConsumableArray(childNodeJML)) : jml(childNodeJML); cn.parentNode.replaceChild(j, cn); }; } /** * @private * @static */ function _appendJML(node) { return function (childJML) { node.appendChild(jml.apply(undefined, toConsumableArray(childJML))); }; } /** * @private * @static */ function _appendJMLOrText(node) { return function (childJML) { if (typeof childJML === 'string') { node.appendChild(doc.createTextNode(childJML)); } else { node.appendChild(jml.apply(undefined, toConsumableArray(childJML))); } }; } /** * @private * @static function _DOMfromJMLOrString (childNodeJML) { if (typeof childNodeJML === 'string') { return doc.createTextNode(childNodeJML); } return jml(...childNodeJML); } */ /** * Creates an XHTML or HTML element (XHTML is preferred, but only in browsers that support); * Any element after element can be omitted, and any subsequent type or types added afterwards * @requires polyfill: Array.isArray * @requires polyfill: Array.prototype.reduce For returning a document fragment * @requires polyfill: Element.prototype.dataset For dataset functionality (Will not work in IE <= 7) * @param {String} el The element to create (by lower-case name) * @param {Object} [atts] Attributes to add with the key as the attribute name and value as the * attribute value; important for IE where the input element's type cannot * be added later after already added to the page * @param {DOMElement[]} [children] The optional children of this element (but raw DOM elements * required to be specified within arrays since * could not otherwise be distinguished from siblings being added) * @param {DOMElement} [parent] The optional parent to which to attach the element (always the last * unless followed by null, in which case it is the second-to-last) * @param {null} [returning] Can use null to indicate an array of elements should be returned * @returns {DOMElement} The newly created (and possibly already appended) element or array of elements */ var jml = function jml() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var elem = doc.createDocumentFragment(); function _checkAtts(atts) { var att = void 0; for (att in atts) { if (!atts.hasOwnProperty(att)) { continue; } var attVal = atts[att]; att = att in ATTR_MAP ? ATTR_MAP[att] : att; if (NULLABLES.includes(att)) { if (attVal != null) { elem[att] = attVal; } continue; } else if (ATTR_DOM.includes(att)) { elem[att] = attVal; continue; } switch (att) { /* Todos: 0. JSON mode to prevent event addition 0. {$xmlDocument: []} // doc.implementation.createDocument 0. Accept array for any attribute with first item as prefix and second as value? 0. {$: ['xhtml', 'div']} for prefixed elements case '$': // Element with prefix? nodes[nodes.length] = elem = doc.createElementNS(attVal[0], attVal[1]); break; */ case '#': { // Document fragment nodes[nodes.length] = _optsOrUndefinedJML(opts, attVal); break; }case '$shadow': { var open = attVal.open, closed = attVal.closed; var content = attVal.content, template = attVal.template; var shadowRoot = elem.attachShadow({ mode: closed || open === false ? 'closed' : 'open' }); if (template) { if (Array.isArray(template)) { if (_getType(template[0]) === 'object') { // Has attributes template = jml.apply(undefined, ['template'].concat(toConsumableArray(template), [doc.body])); } else { // Array is for the children template = jml('template', template, doc.body); } } else if (typeof template === 'string') { template = $(template); } jml(template.content.cloneNode(true), shadowRoot); } else { if (!content) { content = open || closed; } if (content && typeof content !== 'boolean') { if (Array.isArray(content)) { jml({ '#': content }, shadowRoot); } else { jml(content, shadowRoot); } } } break; }case 'is': { // Not yet supported in browsers // Handled during element creation break; }case '$custom': { Object.assign(elem, attVal); break; }case '$define': { var _ret = function () { var localName = elem.localName.toLowerCase(); // Note: customized built-ins sadly not working yet var customizedBuiltIn = !localName.includes('-'); var def = customizedBuiltIn ? elem.getAttribute('is') : localName; if (customElements.get(def)) { return 'break'; } var getConstructor = function getConstructor(cb) { var baseClass = options && options.extends ? doc.createElement(options.extends).constructor : customizedBuiltIn ? doc.createElement(localName).constructor : HTMLElement; return cb ? function (_baseClass) { inherits(_class, _baseClass); function _class() { classCallCheck(this, _class); var _this = possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this)); cb.call(_this); return _this; } return _class; }(baseClass) : function (_baseClass2) { inherits(_class2, _baseClass2); function _class2() { classCallCheck(this, _class2); return possibleConstructorReturn(this, (_class2.__proto__ || Object.getPrototypeOf(_class2)).apply(this, arguments)); } return _class2; }(baseClass); }; var constructor = void 0, options = void 0, prototype = void 0; if (Array.isArray(attVal)) { if (attVal.length <= 2) { var _attVal = slicedToArray(attVal, 2); constructor = _attVal[0]; options = _attVal[1]; if (typeof options === 'string') { options = { extends: options }; } else if (!options.hasOwnProperty('extends')) { prototype = options; } if ((typeof constructor === 'undefined' ? 'undefined' : _typeof(constructor)) === 'object') { prototype = constructor; constructor = getConstructor(); } } else { var _attVal2 = slicedToArray(attVal, 3); constructor = _attVal2[0]; prototype = _attVal2[1]; options = _attVal2[2]; if (typeof options === 'string') { options = { extends: options }; } } } else if (typeof attVal === 'function') { constructor = attVal; } else { prototype = attVal; constructor = getConstructor(); } if (!constructor.toString().startsWith('class')) { constructor = getConstructor(constructor); } if (!options && customizedBuiltIn) { options = { extends: localName }; } if (prototype) { Object.assign(constructor.prototype, prototype); } customElements.define(def, constructor, customizedBuiltIn ? options : undefined); return 'break'; }(); if (_ret === 'break') break; }case '$symbol': { var _attVal3 = slicedToArray(attVal, 2), symbol = _attVal3[0], func = _attVal3[1]; if (typeof func === 'function') { var funcBound = func.bind(elem); if (typeof symbol === 'string') { elem[Symbol.for(symbol)] = funcBound; } else { elem[symbol] = funcBound; } } else { var obj = func; obj.elem = elem; if (typeof symbol === 'string') { elem[Symbol.for(symbol)] = obj; } else { elem[symbol] = obj; } } break; }case '$data': { setMap(attVal); break; }case '$attribute': { // Attribute node var node = attVal.length === 3 ? doc.createAttributeNS(attVal[0], attVal[1]) : doc.createAttribute(attVal[0]); node.value = attVal[attVal.length - 1]; nodes[nodes.length] = node; break; }case '$text': { // Todo: Also allow as jml(['a text node']) (or should that become a fragment)? var _node = doc.createTextNode(attVal); nodes[nodes.length] = _node; break; }case '$document': { // Todo: Conditionally create XML document var _node2 = doc.implementation.createHTMLDocument(); if (attVal.childNodes) { attVal.childNodes.forEach(_childrenToJML(_node2)); // Remove any extra nodes created by createHTMLDocument(). var j = attVal.childNodes.length; while (_node2.childNodes[j]) { var cn = _node2.childNodes[j]; cn.parentNode.removeChild(cn); j++; } } else { if (attVal.$DOCTYPE) { var dt = { $DOCTYPE: attVal.$DOCTYPE }; var doctype = jml(dt); _node2.firstChild.replaceWith(doctype); } var html = _node2.childNodes[1]; var head = html.childNodes[0]; var _body = html.childNodes[1]; if (attVal.title || attVal.head) { var meta = doc.createElement('meta'); meta.setAttribute('charset', 'utf-8'); head.appendChild(meta); } if (attVal.title) { _node2.title = attVal.title; // Appends after meta } if (attVal.head) { attVal.head.forEach(_appendJML(head)); } if (attVal.body) { attVal.body.forEach(_appendJMLOrText(_body)); } } nodes[nodes.length] = _node2; break; }case '$DOCTYPE': { /* // Todo: if (attVal.internalSubset) { node = {}; } else */ var _node3 = void 0; if (attVal.entities || attVal.notations) { _node3 = { name: attVal.name, nodeName: attVal.name, nodeValue: null, nodeType: 10, entities: attVal.entities.map(_jmlSingleArg), notations: attVal.notations.map(_jmlSingleArg), publicId: attVal.publicId, systemId: attVal.systemId // internalSubset: // Todo }; } else { _node3 = doc.implementation.createDocumentType(attVal.name, attVal.publicId || '', attVal.systemId || ''); } nodes[nodes.length] = _node3; break; }case '$ENTITY': { /* // Todo: Should we auto-copy another node's properties/methods (like DocumentType) excluding or changing its non-entity node values? const node = { nodeName: attVal.name, nodeValue: null, publicId: attVal.publicId, systemId: attVal.systemId, notationName: attVal.notationName, nodeType: 6, childNodes: attVal.childNodes.map(_DOMfromJMLOrString) }; */ break; }case '$NOTATION': { // Todo: We could add further properties/methods, but unlikely to be used as is. var _node4 = { nodeName: attVal[0], publicID: attVal[1], systemID: attVal[2], nodeValue: null, nodeType: 12 }; nodes[nodes.length] = _node4; break; }case '$on': { // Events for (var p2 in attVal) { if (attVal.hasOwnProperty(p2)) { var val = attVal[p2]; if (typeof val === 'function') { val = [val, false]; } if (typeof val[0] === 'function') { _addEvent(elem, p2, val[0], val[1]); // element, event name, handler, capturing } } } break; }case 'className':case 'class': if (attVal != null) { elem.className = attVal; } break; case 'dataset': { var _ret2 = function () { // Map can be keyed with hyphenated or camel-cased properties var recurse = function recurse(attVal, startProp) { var prop = ''; var pastInitialProp = startProp !== ''; Object.keys(attVal).forEach(function (key) { var value = attVal[key]; if (pastInitialProp) { prop = startProp + key.replace(hyphenForCamelCase, _upperCase).replace(/^([a-z])/, _upperCase); } else { prop = startProp + key.replace(hyphenForCamelCase, _upperCase); } if (value === null || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') { if (value != null) { elem.dataset[prop] = value; } prop = startProp; return; } recurse(value, prop); }); }; recurse(attVal, ''); return 'break'; // Todo: Disable this by default unless configuration explicitly allows (for security) }(); break; } case 'htmlFor':case 'for': if (elStr === 'label') { if (attVal != null) { elem.htmlFor = attVal; } break; } elem.setAttribute(att, attVal); break; case 'xmlns': // Already handled break; default: if (att.match(/^on/)) { elem[att] = attVal; // _addEvent(elem, att.slice(2), attVal, false); // This worked, but perhaps the user wishes only one event break; } if (att === 'style') { if (attVal == null) { break; } if ((typeof attVal === 'undefined' ? 'undefined' : _typeof(attVal)) === 'object') { for (var _p in attVal) { if (attVal.hasOwnProperty(_p) && attVal[_p] != null) { // Todo: Handle aggregate properties like "border" if (_p === 'float') { elem.style.cssFloat = attVal[_p]; elem.style.styleFloat = attVal[_p]; // Harmless though we could make conditional on older IE instead } else { elem.style[_p.replace(hyphenForCamelCase, _upperCase)] = attVal[_p]; } } } break; } // setAttribute unfortunately erases any existing styles elem.setAttribute(att, attVal); /* // The following reorders which is troublesome for serialization, e.g., as used in our testing if (elem.style.cssText !== undefined) { elem.style.cssText += attVal; } else { // Opera elem.style += attVal; } */ break; } var matchingPlugin = opts && opts.$plugins && opts.$plugins.find(function (p) { return p.name === att; }); if (matchingPlugin) { matchingPlugin.set({ element: elem, attribute: { name: att, value: attVal } }); break; } elem.setAttribute(att, attVal); break; } } } var nodes = []; var elStr = void 0; var opts = void 0; var isRoot = false; if (_getType(args[0]) === 'object' && Object.keys(args[0]).some(function (key) { return possibleOptions.includes(key); })) { opts = args[0]; if (opts.state !== 'child') { isRoot = true; opts.state = 'child'; } if (opts.$map && !opts.$map.root && opts.$map.root !== false) { opts.$map = { root: opts.$map }; } if ('$plugins' in opts) { if (!Array.isArray(opts.$plugins)) { throw new Error('$plugins must be an array'); } opts.$plugins.forEach(function (pluginObj) { if (!pluginObj) { throw new TypeError('Plugin must be an object'); } if (!pluginObj.name || !pluginObj.name.startsWith('$_')) { throw new TypeError('Plugin object name must be present and begin with `$_`'); } if (typeof pluginObj.set !== 'function') { throw new TypeError('Plugin object must have a `set` method'); } }); } args = args.slice(1); } var argc = args.length; var defaultMap = opts && opts.$map && opts.$map.root; var setMap = function setMap(dataVal) { var map = void 0, obj = void 0; // Boolean indicating use of default map and object if (dataVal === true) { var _defaultMap = slicedToArray(defaultMap, 2); map = _defaultMap[0]; obj = _defaultMap[1]; } else if (Array.isArray(dataVal)) { // Array of strings mapping to default if (typeof dataVal[0] === 'string') { dataVal.forEach(function (dVal) { setMap(opts.$map[dVal]); }); // Array of Map and non-map data object } else { map = dataVal[0] || defaultMap[0]; obj = dataVal[1] || defaultMap[1]; } // Map } else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) { map = dataVal; obj = defaultMap[1]; // Non-map data object } else { map = defaultMap[0]; obj = dataVal; } map.set(elem, obj); }; for (var i = 0; i < argc; i++) { var arg = args[i]; switch (_getType(arg)) { case 'null': // null always indicates a place-holder (only needed for last argument if want array returned) if (i === argc - 1) { _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them // Todo: Fix to allow application of stylesheets of style tags within fragments? return nodes.length <= 1 ? nodes[0] : nodes.reduce(_fragReducer, doc.createDocumentFragment()); // nodes; } break; case 'string': // Strings indicate elements switch (arg) { case '!': nodes[nodes.length] = doc.createComment(args[++i]); break; case '?': arg = args[++i]; var procValue = args[++i]; var val = procValue; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') { procValue = []; for (var p in val) { if (val.hasOwnProperty(p)) { procValue.push(p + '=' + '"' + // https://www.w3.org/TR/xml-stylesheet/#NT-PseudoAttValue val[p].replace(/"/g, '&quot;') + '"'); } } procValue = procValue.join(' '); } // Firefox allows instructions with ">" in this method, but not if placed directly! try { nodes[nodes.length] = doc.createProcessingInstruction(arg, procValue); } catch (e) { // Getting NotSupportedError in IE, so we try to imitate a processing instruction with a comment // innerHTML didn't work // var elContainer = doc.createElement('div'); // elContainer.textContent = '<?' + doc.createTextNode(arg + ' ' + procValue).nodeValue + '?>'; // nodes[nodes.length] = elContainer.textContent; // Todo: any other way to resolve? Just use XML? nodes[nodes.length] = doc.createComment('?' + arg + ' ' + procValue + '?'); } break; // Browsers don't support doc.createEntityReference, so we just use this as a convenience case '&': nodes[nodes.length] = _createSafeReference('entity', '', args[++i]); break; case '#': // // Decimal character reference - ['#', '01234'] // &#01234; // probably easier to use JavaScript Unicode escapes nodes[nodes.length] = _createSafeReference('decimal', arg, String(args[++i])); break; case '#x': // Hex character reference - ['#x', '123a'] // &#x123a; // probably easier to use JavaScript Unicode escapes nodes[nodes.length] = _createSafeReference('hexadecimal', arg, args[++i]); break; case '![': // '![', ['escaped <&> text'] // <![CDATA[escaped <&> text]]> // CDATA valid in XML only, so we'll just treat as text for mutual compatibility // Todo: config (or detection via some kind of doc.documentType property?) of whether in XML try { nodes[nodes.length] = doc.createCDATASection(args[++i]); } catch (e2) { nodes[nodes.length] = doc.createTextNode(args[i]); // i already incremented } break; case '': nodes[nodes.length] = doc.createDocumentFragment(); break; default: { // An element elStr = arg; var _atts = args[i + 1]; // Todo: Fix this to depend on XML/config, not availability of methods if (_getType(_atts) === 'object' && _atts.is) { var is = _atts.is; if (doc.createElementNS) { elem = doc.createElementNS(NS_HTML, elStr, { is: is }); } else { elem = doc.createElement(elStr, { is: is }); } } else { if (doc.createElementNS) { elem = doc.createElementNS(NS_HTML, elStr); } else { elem = doc.createElement(elStr); } } nodes[nodes.length] = elem; // Add to parent break; } } break; case 'object': // Non-DOM-element objects indicate attribute-value pairs var atts = arg; if (atts.xmlns !== undefined) { // We handle this here, as otherwise may lose events, etc. // As namespace of element already set as XHTML, we need to change the namespace // elem.setAttribute('xmlns', atts.xmlns); // Doesn't work // Can't set namespaceURI dynamically, renameNode() is not supported, and setAttribute() doesn't work to change the namespace, so we resort to this hack var replacer = void 0; if (_typeof(atts.xmlns) === 'object') { replacer = _replaceDefiner(atts.xmlns); } else { replacer = ' xmlns="' + atts.xmlns + '"'; } // try { // Also fix DOMParser to work with text/html elem = nodes[nodes.length - 1] = new DOMParser().parseFromString(new XmlSerializer().serializeToString(elem) // Mozilla adds XHTML namespace .replace(' xmlns="' + NS_HTML + '"', replacer), 'application/xml').documentElement; // }catch(e) {alert(elem.outerHTML);throw e;} } var orderedArr = atts.$a ? atts.$a.map(_copyOrderedAtts) : [atts]; orderedArr.forEach(_checkAtts); break; case 'fragment': case 'element': /* 1) Last element always the parent (put null if don't want parent and want to return array) unless only atts and children (no other elements) 2) Individual elements (DOM elements or sequences of string[/object/array]) get added to parent first-in, first-added */ if (i === 0) { // Allow wrapping of element elem = arg; } if (i === argc - 1 || i === argc - 2 && args[i + 1] === null) { // parent var elsl = nodes.length; for (var k = 0; k < elsl; k++) { _appendNode(arg, nodes[k]); } // Todo: Apply stylesheets if any style tags were added elsewhere besides the first element? _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them } else { nodes[nodes.length] = arg; } break; case 'array': // Arrays or arrays of arrays indicate child nodes var child = arg; var cl = child.length; for (var j = 0; j < cl; j++) { // Go through children array container to handle elements var childContent = child[j]; var childContentType = typeof childContent === 'undefined' ? 'undefined' : _typeof(childContent); if (childContent === undefined) { throw String('Parent array:' + JSON.stringify(args) + '; child: ' + child + '; index:' + j); } switch (childContentType) { // Todo: determine whether null or function should have special handling or be converted to text case 'string':case 'number':case 'boolean': _appendNode(elem, doc.createTextNode(childContent)); break; default: if (Array.isArray(childContent)) { // Arrays representing child elements _appendNode(elem, _optsOrUndefinedJML.apply(undefined, [opts].concat(toConsumableArray(childContent)))); } else if (childContent['#']) { // Fragment _appendNode(elem, _optsOrUndefinedJML(opts, childContent['#'])); } else { // Single DOM element children _appendNode(elem, childContent); } break; } } break; } } var ret = nodes[0] || elem; if (opts && isRoot && opts.$map && opts.$map.root) { setMap(true); } return ret; }; /** * Converts a DOM object or a string of HTML into a Jamilih object (or string) * @param {string|HTMLElement} [dom=document.documentElement] Defaults to converting the current document. * @param {object} [config={stringOutput:false}] Configuration object * @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string. * @returns {array|string} Array containing the elements which represent a Jamilih object, or, if `stringOutput` is true, it will be the stringified version of such an object */ jml.toJML = function (dom, config) { config = config || { stringOutput: false }; if (typeof dom === 'string') { dom = new DOMParser().parseFromString(dom, 'text/html'); // todo: Give option for XML once implemented and change JSDoc to allow for Element } var ret = []; var parent = ret; var parentIdx = 0; function invalidStateError() { // These are probably only necessary if working with text/html function DOMException() { return this; } { // INVALID_STATE_ERR per section 9.3 XHTML 5: http://www.w3.org/TR/html5/the-xhtml-syntax.html // Since we can't instantiate without this (at least in Mozilla), this mimicks at least (good idea?) var e = new DOMException(); e.code = 11; throw e; } } function addExternalID(obj, node) { if (node.systemId.includes('"') && node.systemId.includes("'")) { invalidStateError(); } var publicId = node.publicId; var systemId = node.systemId; if (systemId) { obj.systemId = systemId; } if (publicId) { obj.publicId = publicId; } } function set$$1(val) { parent[parentIdx] = val; parentIdx++; } function setChildren() { set$$1([]); parent = parent[parentIdx - 1]; parentIdx = 0; } function setObj(prop1, prop2) { parent = parent[parentIdx - 1][prop1]; parentIdx = 0; if (prop2) { parent = parent[prop2]; } } function parseDOM(node, namespaces) { // namespaces = clone(namespaces) || {}; // Ensure we're working with a copy, so different levels in the hierarchy can treat it differently /* if ((node.prefix && node.prefix.includes(':')) || (node.localName && node.localName.includes(':'))) { invalidStateError(); } */ var type = 'nodeType' in node ? node.nodeType : null; namespaces = Object.assign({}, namespaces); var xmlChars = /([\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]|[\uD800-\uDBFF][\uDC00-\uDFFF])*$/; // eslint-disable-line no-control-regex if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) { invalidStateError(); } var children = void 0, start = void 0, tmpParent = void 0, tmpParentIdx = void 0; function setTemp() { tmpParent = parent; tmpParentIdx = parentIdx; } function resetTemp() { parent = tmpParent; parentIdx = tmpParentIdx; parentIdx++; // Increment index in parent container of this element } switch (type) { case 1: // ELEMENT setTemp(); var nodeName = node.nodeName.toLowerCase(); // Todo: for XML, should not lower-case setChildren(); // Build child array since elements are, except at the top level, encapsulated in arrays set$$1(nodeName); start = {}; var hasNamespaceDeclaration = false; if (namespaces[node.prefix || ''] !== node.namespaceURI) { namespaces[node.prefix || ''] = node.namespaceURI; if (node.prefix) { start['xmlns:' + node.prefix] = node.namespaceURI; } else if (node.namespaceURI) { start.xmlns = node.namespaceURI; } hasNamespaceDeclaration = true; } if (node.attributes.length) { set$$1(Array.from(node.attributes).reduce(function (obj, att) { obj[att.name] = att.value; // Attr.nodeName and Attr.nodeValue are deprecated as of DOM4 as Attr no longer inherits from Node, so we can safely use name and value return obj; }, start)); } else if (hasNamespaceDeclaration) { set$$1(start); } children = node.childNodes; if (children.length) { setChildren(); // Element children array container Array.from(children).forEach(function (childNode) { parseDOM(childNode, namespaces); }); } resetTemp(); break; case undefined: // Treat as attribute node until this is fixed: https://github.com/tmpvar/jsdom/issues/1641 / https://github.com/tmpvar/jsdom/pull/1822 case 2: // ATTRIBUTE (should only get here if passing in an attribute node) set$$1({ $attribute: [node.namespaceURI, node.name, node.value] }); break; case 3: // TEXT if (config.stripWhitespace && /^\s+$/.test(node.nodeValue)) { return; } set$$1(node.nodeValue); break; case 4: // CDATA if (node.nodeValue.includes(']]' + '>')) { invalidStateError(); } set$$1(['![', node.nodeValue]); break; case 5: // ENTITY REFERENCE (probably not used in browsers since already resolved) set$$1(['&', node.nodeName]); break; case 6: // ENTITY (would need to pass in directly) setTemp(); start = {}; if (node.xmlEncoding || node.xmlVersion) { // an external entity file? start.$ENTITY = { name: node.nodeName, version: node.xmlVersion, encoding: node.xmlEncoding }; } else { start.$ENTITY = { name: node.nodeName }; if (node.publicId || node.systemId) { // External Entity? addExternalID(start.$ENTITY, node); if (node.notationName) { start.$ENTITY.NDATA = node.notationName; } } } set$$1(start); children = node.childNodes; if (children.length) { start.$ENTITY.childNodes = []; // Set position to $ENTITY's childNodes array children setObj('$ENTITY', 'childNodes'); Array.from(children).forEach(function (childNode) { parseDOM(childNode, namespaces); }); } resetTemp(); break; case 7: // PROCESSING INSTRUCTION if (/^xml$/i.test(node.target)) { invalidStateError(); } if (node.target.includes('?>')) { invalidStateError(); } if (node.target.includes(':')) { invalidStateError(); } if (node.data.includes('?>')) { invalidStateError(); } set$$1(['?', node.target, node.data]); // Todo: Could give option to attempt to convert value back into object if has pseudo-attributes break; case 8: // COMMENT if (node.nodeValue.includes('--') || node.nodeValue.length && node.nodeValue.lastIndexOf('-') === node.nodeValue.length - 1) { invalidStateError(); } set$$1(['!', node.nodeValue]); break; case 9: // DOCUMENT setTemp(); var docObj = { $document: { childNodes: [] } }; if (config.xmlDeclaration) { docObj.$document.xmlDeclaration = { version: doc.xmlVersion, encoding: doc.xmlEncoding, standAlone: doc.xmlStandalone }; } set$$1(docObj); // doc.implementation.createHTMLDocument // Set position to fragment's array children setObj('$document', 'childNodes'); children = node.childNodes; if (!children.length) { invalidStateError(); } // set({$xmlDocument: []}); // doc.implementation.createDocument // Todo: use this conditionally Array.from(children).forEach(function (childNode) { // Can't just do documentElement as there may be doctype, comments, etc. // No need for setChildren, as we have already built the container array parseDOM(childNode, namespaces); }); resetTemp(); break; case 10: // DOCUMENT TYPE setTemp(); // Can create directly by doc.implementation.createDocumentType start = { $DOCTYPE: { name: node.name } }; if (node.internalSubset) { start.internalSubset = node.internalSubset; } var pubIdChar = /^(\u0020|\u000D|\u000A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/; // eslint-disable-line no-control-regex if (!pubIdChar.test(node.publicId)) { invalidStateError(); } addExternalID(start.$DOCTYPE, node); // Fit in internal subset along with entities?: probably don't need as these would only differ if from DTD, and we're not rebuilding the DTD set$$1(start); // Auto-generate the internalSubset instead? Avoid entities/notations in favor of array to preserve order? var entities = node.entities; // Currently deprecated if (entities && entities.length) { start.$DOCTYPE.entities = []; setObj('$DOCTYPE', 'entities'); Array.from(entities).forEach(function (entity) { parseDOM(entity, namespaces); }); // Reset for notations parent = tmpParent; parentIdx = tmpParentIdx + 1; } var notations = node.notations; // Currently deprecated if (notations && notations.length) { start.$DOCTYPE.notations = []; setObj('$DOCTYPE', 'notations'); Array.from(notations).forEach(function (notation) { parseDOM(notation, namespaces); }); } resetTemp(); break; case 11: // DOCUMENT FRAGMENT setTemp(); set$$1({ '#': [] }); // Set position to fragment's array children setObj('#'); children = node.childNodes; Array.from(children).forEach(function (childNode) { // No need for setChildren, as we have already built the container array parseDOM(childNode, namespaces); }); resetTemp(); break; case 12: // NOTATION start = { $NOTATION: { name: node.nodeName } }; addExternalID(start.$NOTATION, node); set$$1(start); break; default: throw new TypeError('Not an XML type'); } } parseDOM(dom, {}); if (config.stringOutput) { return JSON.stringify(ret[0]); } return ret[0]; }; jml.toJMLString = function (dom, config) { return jml.toJML(dom, Object.assign(config || {}, { stringOutput: true })); }; jml.toDOM = function () { // Alias for jml() return jml.apply(undefined, arguments); }; jml.toHTML = function () { // Todo: Replace this with version of jml() that directly builds a string var ret = jml.apply(undefined, arguments); // Todo: deal with serialization of properties like 'selected', 'checked', 'value', 'defaultValue', 'for', 'dataset', 'on*', 'style'! (i.e., need to build a string ourselves) return ret.outerHTML; }; jml.toDOMString = function () { // Alias for jml.toHTML for parity with jml.toJMLString return jml.toHTML.apply(jml, arguments); }; jml.toXML = function () { var ret = jml.apply(undefined, arguments); return new XmlSerializer().serializeToString(ret); }; jml.toXMLDOMString = function () { // Alias for jml.toXML for parity with jml.toJMLString return jml.toXML.apply(jml, arguments); }; var JamilihMap = function (_Map) { inherits(JamilihMap, _Map); function JamilihMap() { classCallCheck(this, JamilihMap); return possibleConstructorReturn(this, (JamilihMap.__proto__ || Object.getPrototypeOf(JamilihMap)).apply(this, arguments)); } createClass(JamilihMap, [{ key: 'get', value: function get$$1(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihMap.prototype.__proto__ || Object.getPrototypeOf(JamilihMap.prototype), 'get', this).call(this, elem); } }, { key: 'set', value: function set$$1(elem, value) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihMap.prototype.__proto__ || Object.getPrototypeOf(JamilihMap.prototype), 'set', this).call(this, elem, value); } }, { key: 'invoke', value: function invoke(elem, methodName) { var _get; elem = typeof elem === 'string' ? $(elem) : elem; for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { args[_key3 - 2] = arguments[_key3]; } return (_get = this.get(elem))[methodName].apply(_get, [elem].concat(args)); } }]); return JamilihMap; }(Map); var JamilihWeakMap = function (_WeakMap) { inherits(JamilihWeakMap, _WeakMap); function JamilihWeakMap() { classCallCheck(this, JamilihWeakMap); return possibleConstructorReturn(this, (JamilihWeakMap.__proto__ || Object.getPrototypeOf(JamilihWeakMap)).apply(this, arguments)); } createClass(JamilihWeakMap, [{ key: 'get', value: function get$$1(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihWeakMap.prototype.__proto__ || Object.getPrototypeOf(JamilihWeakMap.prototype), 'get', this).call(this, elem); } }, { key: 'set', value: function set$$1(elem, value) { elem = typeof elem === 'string' ? $(elem) : elem; return get(JamilihWeakMap.prototype.__proto__ || Object.getPrototypeOf(JamilihWeakMap.prototype), 'set', this).call(this, elem, value); } }, { key: 'invoke', value: function invoke(elem, methodName) { var _get2; elem = typeof elem === 'string' ? $(elem) : elem; for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { args[_key4 - 2] = arguments[_key4]; } return (_get2 = this.get(elem))[methodName].apply(_get2, [elem].concat(args)); } }]); return JamilihWeakMap; }(WeakMap); jml.Map = JamilihMap; jml.WeakMap = JamilihWeakMap; jml.weak = function (obj) { var map = new JamilihWeakMap(); for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } var elem = jml.apply(undefined, [{ $map: [map, obj] }].concat(args)); return [map, elem]; }; jml.strong = function (obj) { var map = new JamilihMap(); for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { args[_key6 - 1] = arguments[_key6]; } var elem = jml.apply(undefined, [{ $map: [map, obj] }].concat(args)); return [map, elem]; }; jml.symbol = jml.sym = jml.for = function (elem, sym) { elem = typeof elem === 'string' ? $(elem) : elem; return elem[(typeof sym === 'undefined' ? 'undefined' : _typeof(sym)) === 'symbol' ? sym : Symbol.for(sym)]; }; jml.command = function (elem, symOrMap, methodName) { elem = typeof elem === 'string' ? $(elem) : elem; var func = void 0; for (var _len7 = arguments.length, args = Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) { args[_key7 - 3] = arguments[_key7]; } if (['symbol', 'string'].includes(typeof symOrMap === 'undefined' ? 'undefined' : _typeof(symOrMap))) { var _func; func = jml.sym(elem, symOrMap); if (typeof func === 'function') { return func.apply(undefined, [methodName].concat(args)); // Already has `this` bound to `elem` } return (_func = func)[methodName].apply(_func, args); } else { var _func3; func = symOrMap.get(elem); if (typeof func === 'function') { var _func2; return (_func2 = func).call.apply(_func2, [elem, methodName].concat(args)); } return (_func3 = func)[methodName].apply(_func3, [elem].concat(args)); } // return func[methodName].call(elem, ...args); }; jml.setWindow = function (wind) { win = wind; }; jml.setDocument = function (docum) { doc = docum; if (docum && docum.body) { body = docum.body; } }; jml.setXMLSerializer = function (xmls) { XmlSerializer = xmls; }; jml.getWindow = function () { return win; }; jml.getDocument = function () { return doc; }; jml.getXMLSerializer = function () { return XmlSerializer; }; var body = doc && doc.body; var nbsp = '\xA0'; // Very commonly needed in templates export default jml; export { jml, $, $$, nbsp, body };
brettz9/open-isbn
options/jml.js
JavaScript
mit
66,746
export default from './navigation.component';
sunstorymvp/playground
src/core/navigation/index.js
JavaScript
mit
46
package com.nomeautomation.utility.server; /** * All possible commands the device manager server can respond to * */ public class ServerCommands{ public enum ServerCommand { GET_HOUSE_CONSUMPTION, GET_DAILY_CONSUMPTION, GET_MONTHLY_CONSUMPTION, GET_DEVICE_TOTAL_CONSUMPTION, GET_ALL_DEVICES, GET_DEVICE, SEND_DEVICE_COMMAND, CHANGE_DEVICE_NAME, CHANGE_DEVICE_ROOM, REMOVE_DEVICE, GET_ALL_ROOMS, ADD_ROOM, CHANGE_ROOM_NAME, REMOVE_ROOM, ADD_UPDATE_SCHEDULE, REMOVE_SCHEDULE, GET_ALL_SCHEDULES, ACTIVATE_SCHEDULE, ACCEPT_SUGGESTION, DECLINE_SUGGESTION, HIDE_SUGGESTION, GET_SIMULATED_SCHEDULES_POWER, GET_SUGGESTIONS, PASS, FAIL, UNKNOWN, ; } }
NomeAutomation/NomeAutomation
src/com/nomeautomation/utility/server/ServerCommands.java
Java
mit
737
package main import ( "os" "github.com/kamaln7/karmabot" "github.com/kamaln7/karmabot/ctlcommands" "github.com/aybabtme/log" "github.com/urfave/cli" ) var ( ll *log.Log ) func main() { // logging ll = log.KV("version", karmabot.Version) // commands cc := &ctlcommands.Commands{ Logger: ll, } // app app := cli.NewApp() app.Name = "karmabotctl" app.Version = karmabot.Version app.Usage = "manually manage karmabot" // general flags dbpath := cli.StringFlag{ Name: "db", Value: "./db.sqlite3", Usage: "path to sqlite database", } debug := cli.BoolFlag{ Name: "debug", Usage: "set debug mode", } leaderboardlimit := cli.IntFlag{ Name: "leaderboardlimit", Value: 10, Usage: "the default amount of users to list in the leaderboard", } // webui webuiCommands := []cli.Command{ { Name: "totp", Usage: "generate a TOTP token", Flags: []cli.Flag{ cli.StringFlag{ Name: "totp", Usage: "totp key", }, }, Action: cc.Mktotp, }, { Name: "serve", Usage: "start a webserver", Flags: []cli.Flag{ dbpath, debug, leaderboardlimit, cli.StringFlag{ Name: "totp", Usage: "totp key", }, cli.StringFlag{ Name: "path", Usage: "path to web UI files", }, cli.StringFlag{ Name: "listenaddr", Usage: "address to listen and serve the web ui on", }, cli.StringFlag{ Name: "url", Usage: "url address for accessing the web ui", }, }, Action: cc.Serve, }, } // karma karmaCommands := []cli.Command{ { Name: "add", Usage: "add karma to a user", Flags: []cli.Flag{ dbpath, cli.StringFlag{ Name: "from", }, cli.StringFlag{ Name: "to", }, cli.StringFlag{ Name: "reason", }, cli.IntFlag{ Name: "points", }, }, Action: cc.AddKarma, }, { Name: "migrate", Usage: "move a user's karma to another user", Flags: []cli.Flag{ dbpath, cli.StringFlag{ Name: "from", }, cli.StringFlag{ Name: "to", }, cli.StringFlag{ Name: "reason", }, }, Action: cc.MigrateKarma, }, { Name: "reset", Usage: "reset a user's karma", Flags: []cli.Flag{ dbpath, cli.StringFlag{ Name: "user", }, }, Action: cc.ResetKarma, }, { Name: "set", Usage: "set a user's karma to a specific number", Flags: []cli.Flag{ dbpath, cli.StringFlag{ Name: "user", }, cli.IntFlag{ Name: "points", }, }, Action: cc.SetKarma, }, { Name: "throwback", Usage: "get a karma throwback for a user", Flags: []cli.Flag{ dbpath, cli.StringFlag{ Name: "user", }, }, Action: cc.GetThrowback, }, } // main app app.Commands = []cli.Command{ { Name: "karma", Subcommands: karmaCommands, }, { Name: "webui", Subcommands: webuiCommands, }, } app.Run(os.Args) }
kamaln7/karmabot
cmd/karmabotctl/main.go
GO
mit
2,972
<?php namespace ParkBundle\Twig; /** * Class ComputerStatusExtension * @package ParkBundle\Twig */ class ComputerExtension extends \Twig_Extension { /** * @param \Twig_Environment $env * @param $status * @return string */ public function renderComputerStatus(\Twig_Environment $env, $status) { //return processed template content return $env->render( 'ParkBundle:Computer:Status/index.html.twig', array( 'status' => (bool)$status, ) ); } /** * @param $name * @return string */ public function renderComputerName($name) { //return processed template content return lcfirst(strtoupper($name)); } /** * @return array */ public function getFilters() { return array( new \Twig_SimpleFilter( 'computer_status', array($this, 'renderComputerStatus'), array( 'is_safe' => array('html'), 'needs_environment' => true ) ), new \Twig_SimpleFilter( 'computer_name', array($this, 'renderComputerName'), array( 'is_safe' => array('html') ) ) ); } /** * @return string */ public function getName() { return 'park_computer_status_extension'; } }
ale42/formation-symfony
src/ParkBundle/Twig/ComputerExtension.php
PHP
mit
1,510
package org.example.conf.generated.test; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Properties; import javax.annotation.Generated; import ml.alternet.properties.Binder; /** * Configuration structure for "mail.properties" * * DO NOT EDIT : this class has been generated ! */ @Generated(value="ml.alternet.properties.Generator", date="2017-12-29") public class Mail { public Mail_ mail; public static class Mail_ { public Smtp smtp; public static class Smtp { public Starttls starttls; public static class Starttls { public boolean enable; } public boolean auth; public String host; public int port; public Ssl ssl; public static class Ssl { public String trust; } } } public String username; public char[] password; public Name name; public static class Name { public String expediteur; } public static Mail unmarshall(InputStream properties) throws IOException { return Binder.unmarshall( properties, Mail.class ); } public Mail update(InputStream properties) throws IOException { return Binder.unmarshall( properties, this ); } public static Mail unmarshall(Reader properties) throws IOException { return Binder.unmarshall( properties, Mail.class ); } public Mail update(Reader properties) throws IOException { return Binder.unmarshall( properties, this ); } public static Mail unmarshall(Properties properties) throws IOException { return Binder.unmarshall( properties, Mail.class ); } public Mail update(Properties properties) throws IOException { return Binder.unmarshall( properties, this ); } }
alternet/alternet.ml
tools/src/test/java/org/example/conf/generated/test/Mail.java
Java
mit
2,100
package org.analogweb.servlet; import java.lang.annotation.Annotation; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpSession; import org.analogweb.InvocationMetadata; import org.analogweb.RequestContext; import org.analogweb.RequestValueResolver; import org.analogweb.util.RequestContextResolverUtils; /** * @author y2k2mt */ public class ServletComponentsValueResolver implements RequestValueResolver { @Override public Object resolveValue(RequestContext request, InvocationMetadata metadata, String query, Class<?> requiredType, Annotation[] parameterAnnotations) { ServletRequestContext src = RequestContextResolverUtils .resolveRequestContext(request); if (src == null) { return null; } if (ServletRequest.class.isAssignableFrom(requiredType)) { return src.getServletRequest(); } else if (HttpSession.class.isAssignableFrom(requiredType)) { return src.getServletRequest().getSession(true); } else if (ServletContext.class.isAssignableFrom(requiredType)) { return src.getServletContext(); } return null; } }
analogweb/servlet-plugin
src/main/java/org/analogweb/servlet/ServletComponentsValueResolver.java
Java
mit
1,117
using System; using DynamicExpresso; class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } }
TryItOnline/tiosetup
files/dotnet/code.cs
C#
mit
131
using System; using System.Collections.Generic; using System.Text; public class Person { private int age; private string name; public int Age { get { return this.age; } set { this.age = value; } } public string Name { get { return this.name; } set { this.name = value; } } public Person() { this.name = "No name"; this.age = 1; } public Person(int age) : this() { this.age = age; } public Person(int age, string name) : this() { this.age = age; this.name = name; } public override string ToString() { return $"{this.name} - {this.age}"; } }
delian1986/SoftUni-C-Sharp-repo
Old Courses/OOP Basics/01. Defining Classes/Defining Classes - Exercise/DefiningClassesExercise/DefiningClassesExercise/Person.cs
C#
mit
824
# frozen_string_literal: true # This file monkey patches StreakClient to make testing it easier. module StreakClient module Pipeline end module Box # Have create_in_pipeline return an object with a randomly generated # :streak_key and the name that was passed. def self.create_in_pipeline(_pipeline_key, name) # Random 91 character alphanumeric string range = [*'0'..'9', *'A'..'Z', *'a'..'z'] streak_key = Array.new(91) { range.sample }.join { key: streak_key, name: name } end # TODO: Return the full "updated" box here def self.update(_box_key, _params); end def self.edit_field(_box_key, field_key, value) { key: field_key, value: value } end def self.delete(_box_key) { success: true } end end end
hackclub/api
spec/support/streak_client_monkey_patches.rb
Ruby
mit
851
using System; using System.Collections.Generic; using System.Text; namespace PokemonGoRaidBot.Objects.Interfaces { public interface IStatMapper : IDisposable { TDestination Map<TDestination>(object source); TDestination Map<TSource, TDestination>(TSource source); TDestination Map<TSource, TDestination>(TSource source, TDestination destination); } }
wpatter6/PokemonGoDiscordRaidBot
PokemonGoRaidBot/Objects/Interfaces/IStatMapper.cs
C#
mit
393
export interface MovieSearch { query: string; year?: number; page?: number; }
imba3r/grabber
ui/src/app/core/models/movie-search.interface.ts
TypeScript
mit
84
# Copyright (c) 2016 Code42, Inc. # 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. module Code42 module API module ServerConnectionString def server_connection_string(id) object_from_response(Code42::ServerConnectionString, :get, "serverConnectionString/#{id}") end end end end
code42/code42_api_ruby
lib/code42/api/server_connection_string.rb
Ruby
mit
1,315
package org.zv.fintrack.rest; import java.util.List; import java.text.ParseException; import java.text.SimpleDateFormat; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.FormParam; import javax.ws.rs.Produces; import org.zv.fintrack.pd.Income; import org.zv.fintrack.pd.bean.SummaryBean; import org.zv.fintrack.ejb.api.IncomeDao; import org.zv.fintrack.util.JndiUtil; @Path("/incomes") public class Incomes { private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @POST @Path("/new") @Produces({"application/xml", "application/json"}) public Income addNew(@FormParam("createDate") String createDate, @FormParam("userId") String userId, @FormParam("amount") Float amount, @FormParam("descr") String descr) throws ParseException { IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao"); Income income = new Income(); income.setCreateDate(simpleDateFormat.parse(createDate)); income.setUserId(userId); income.setAmount(amount); income.setDescr(descr); income = incomeDao.save(income); return income; } @GET @Path("/latest-{max}") @Produces({"application/xml", "application/json"}) public List<Income> getLatest(@PathParam("max") int max) { IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao"); return incomeDao.getAll(max); } @POST @Path("/list") @Produces({"application/xml", "application/json"}) public List<Income> getList(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo, @FormParam("userId") String userId) throws ParseException { IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao"); return incomeDao.getPlain(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo), userId); } @POST @Path("/summary/simple") @Produces({"application/xml", "application/json"}) public List<SummaryBean> getSummarySimple(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo) throws ParseException { IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao"); return incomeDao.getSummarySimple(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo)); } @POST @Path("/summary/bymonth") @Produces({"application/xml", "application/json"}) public List<SummaryBean> getSummaryMonth(@FormParam("dateFrom") String dateFrom, @FormParam("dateTo") String dateTo) throws ParseException { IncomeDao incomeDao = (IncomeDao)JndiUtil.lookup("ejb/IncomeDao"); return incomeDao.getSummaryByMonth(simpleDateFormat.parse(dateFrom), simpleDateFormat.parse(dateTo)); } }
arvjus/fintrack-java
fintrack-web/src/main/java/org/zv/fintrack/rest/Incomes.java
Java
mit
2,650
using System.Collections.Generic; using System.Threading.Tasks; using BookFast.Contracts.Search; namespace BookFast.Business.Data { public interface ISearchDataSource { Task<IList<SearchResult>> SearchAsync(string searchText, int page); Task<IList<SuggestResult>> SuggestAsync(string searchText); } }
dzimchuk/book-fast-api
src/BookFast.Business/Data/ISearchDataSource.cs
C#
mit
332
using UnityEngine; using System.Collections; public class NukeSpawner : MonoBehaviour { public GameObject nuke; void Start() { } }
lucasrumney94/JGGJ
JamGameGameJam/Assets/NukeSpawner.cs
C#
mit
154
<TS language="fr" version="2.0"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Faites un clic droit pour modifier l'adresse ou l'étiquette</translation> </message> <message> <source>Create a new address</source> <translation>Créer une nouvelle adresse</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Nouveau</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copier l'adresse courante sélectionnée dans le presse-papier</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copier</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Effacer l'adresse actuellement sélectionnée de la liste</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Supprimer</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exporter les données de l'onglet courant vers un fichier</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exporter</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;Fermer</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Choisir l'adresse à laquelle envoyer de la monnaie</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Choisir l'adresse avec laquelle recevoir de la monnaie</translation> </message> <message> <source>C&amp;hoose</source> <translation>C&amp;hoisir</translation> </message> <message> <source>Sending addresses</source> <translation>Adresses d'envoi</translation> </message> <message> <source>Receiving addresses</source> <translation>Adresses de réception</translation> </message> <message> <source>These are your Mtucicoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Ce sont vos adresses Mtucicoin pour l'envoi de paiements. Vérifiez toujours le montant et l'adresse de réception avant l'envoi de monnaies.</translation> </message> <message> <source>These are your Mtucicoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Ce sont vos adresses Mtucicoin pour la réception de paiements. Il est recommandé d'utiliser une nouvelle adresse de réception pour chaque transaction.</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copier l'adresse</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copier l'é&amp;tiquette</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Modifier</translation> </message> <message> <source>Export Address List</source> <translation>Exporter la liste d'adresses</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Valeurs séparées par des virgules (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>L'exportation a échoué</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Une erreur est survenue lors de l'enregistrement de la liste d'adresses vers %1. Essayez à nouveau.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Étiquette</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>(no label)</source> <translation>(aucune étiquette)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Dialogue de phrase de passe</translation> </message> <message> <source>Enter passphrase</source> <translation>Saisir la phrase de passe</translation> </message> <message> <source>New passphrase</source> <translation>Nouvelle phrase de passe</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Répéter la phrase de passe</translation> </message> <message> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation>Utiliser pour désactiver le mode d'envoi trivial de paiement lorsque le compte système est compromis. N'assure pas une sécurité efficace.</translation> </message> <message> <source>For anonymization only</source> <translation>Pour anonymisation uniquement</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>Saisir la nouvelle phrase de passe pour le portefeuille.&lt;br/&gt;Veuillez utiliser une phrase de passe de &lt;b&gt;dix caractères aléatoires ou plus&lt;/b&gt;, ou de &lt;b&gt;huit mots ou plus&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Chiffrer le portefeuille</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Cette opération nécessite votre phrase de passe pour déverrouiller le portefeuille.</translation> </message> <message> <source>Unlock wallet</source> <translation>Déverrouiller le portefeuille</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Cette opération nécessite votre phrase de passe pour déchiffrer le portefeuille.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Déchiffrer le portefeuille</translation> </message> <message> <source>Change passphrase</source> <translation>Changer le mot de passe</translation> </message> <message> <source>Enter the old and new passphrase to the wallet.</source> <translation>Saisir l’ancienne phrase de passe pour le portefeuille ainsi que la nouvelle.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Confirmer le chiffrement du portefeuille</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR MTUCICOIN&lt;/b&gt;!</source> <translation>Attention : Si vous chiffrez votre portefeuille et perdez votre phrase de passe, vous &lt;b&gt;PERDREZ TOUS VOS MTUCICOIN&lt;/b&gt; !</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Êtes-vous sûr de vouloir chiffrer votre portefeuille ?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Portefeuille chiffré</translation> </message> <message> <source>Mtucicoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your mtucicoins from being stolen by malware infecting your computer.</source> <translation>Mtucicoin va à présent se fermer pour terminer le chiffrement. N'oubliez pas que le chiffrement de votre portefeuille n'est pas une protection totale contre le vol par des logiciels malveillants qui infecteraient votre ordinateur.</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>IMPORTANT : Toute sauvegarde précédente de votre fichier de portefeuille devrait être remplacée par le nouveau fichier de portefeuille chiffré. Pour des raisons de sécurité, les sauvegardes précédentes de votre fichier de portefeuille non chiffré deviendront inutilisables dès que vous commencerez à utiliser le nouveau portefeuille chiffré.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Le chiffrement du portefeuille a échoué</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Le chiffrement du portefeuille a échoué en raison d'une erreur interne. Votre portefeuille n'a pas été chiffré.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Les phrases de passe saisies ne correspondent pas.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Le déverrouillage du portefeuille a échoué</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La phrase de passe saisie pour déchiffrer le portefeuille était incorrecte.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Le déchiffrage du portefeuille a échoué</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>La phrase de passe du portefeuille a été modifiée avec succès.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Attention : la touche Verr. Maj. est activée !</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Mtucicoin Core</source> <translation>Mtucicoin Core</translation> </message> <message> <source>Wallet</source> <translation>Portefeuille</translation> </message> <message> <source>Node</source> <translation>Nœud</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Vue d'ensemble</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Afficher une vue d’ensemble du portefeuille</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Envoyer</translation> </message> <message> <source>Send coins to a Mtucicoin address</source> <translation>Envoyer des pièces sur une adresse Mtucicoin</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Recevoir</translation> </message> <message> <source>Request payments (generates QR codes and mtucicoin: URIs)</source> <translation>Demande de paiements (Générer des QR code et des URIs mtucicoin)</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transactions</translation> </message> <message> <source>Browse transaction history</source> <translation>Parcourir l'historique des transactions</translation> </message> <message> <source>E&amp;xit</source> <translation>Q&amp;uitter</translation> </message> <message> <source>Quit application</source> <translation>Quitter l’application</translation> </message> <message> <source>&amp;About Mtucicoin Core</source> <translation>À propos du noyau Mtucicoin</translation> </message> <message> <source>Show information about Mtucicoin Core</source> <translation>Affichez des informations à propos de Mtucicoin Core</translation> </message> <message> <source>About &amp;Qt</source> <translation>À propos de &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Afficher des informations sur Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Options...</translation> </message> <message> <source>Modify configuration options for Mtucicoin</source> <translation>Modifier les options de configuration pour Mtucicoin</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Afficher / Cacher</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Afficher ou masquer la fenêtre principale</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Chiffrer le portefeuille...</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Chiffrer les clefs privées de votre portefeuille</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>Sauvegarder le &amp;portefeuille...</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Sauvegarder le portefeuille vers un autre emplacement</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Changer la phrase de passe...</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Modifier la phrase de passe utilisée pour le chiffrement du portefeuille</translation> </message> <message> <source>&amp;Unlock Wallet...</source> <translation>&amp;Déverrouiller le portefeuille</translation> </message> <message> <source>Unlock wallet</source> <translation>Déverrouiller le portefeuille</translation> </message> <message> <source>&amp;Lock Wallet</source> <translation>&amp;Vérouiller le portefeuille</translation> </message> <message> <source>Sign &amp;message...</source> <translation>&amp;Signer le message...</translation> </message> <message> <source>Sign messages with your Mtucicoin addresses to prove you own them</source> <translation>Signer les messages avec votre adresses Mtucicoin pour prouver que vous êtes le propriétaire</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Vérifier un message...</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Mtucicoin addresses</source> <translation>Vérifier les messages pour vous assurer qu'ils ont été signés avec les adresses Mtucicoin spécifiées</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Informations</translation> </message> <message> <source>Show diagnostic information</source> <translation>Voir les informaion de diagnostique</translation> </message> <message> <source>&amp;Debug console</source> <translation>&amp;Console de débogage</translation> </message> <message> <source>Open debugging console</source> <translation>Ouvrir la console de débogage</translation> </message> <message> <source>&amp;Network Monitor</source> <translation>&amp;Moniteur réseau</translation> </message> <message> <source>Show network monitor</source> <translation>Voir le moniteur réseau</translation> </message> <message> <source>&amp;Peers list</source> <translation>Et la liste des pairs</translation> </message> <message> <source>Show peers info</source> <translation>Voir les infos des pairs</translation> </message> <message> <source>Wallet &amp;Repair</source> <translation>Portefeuille et Réparation</translation> </message> <message> <source>Show wallet repair options</source> <translation>Afficher les options de réparation du portefeuille</translation> </message> <message> <source>Open &amp;Configuration File</source> <translation>Ouvrir Fichier de &amp;Configuration</translation> </message> <message> <source>Open configuration file</source> <translation>Ouvrir fichier de configuration</translation> </message> <message> <source>Show Automatic &amp;Backups</source> <translation>Afficher les sauvegardes automatiques</translation> </message> <message> <source>Show automatically created wallet backups</source> <translation>Afficher automatiquement les sauvegardes de portefeuille créés </translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>Adresses d'&amp;envoi...</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Afficher la liste d'adresses d'envoi et d'étiquettes utilisées</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Adresses de &amp;réception...</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Afficher la liste d'adresses de réception et d'étiquettes utilisées</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Ouvrir un &amp;URI...</translation> </message> <message> <source>Open a mtucicoin: URI or payment request</source> <translation>Ouvrir une URI ou demande de paiement mtucicoin</translation> </message> <message> <source>&amp;Command-line options</source> <translation>Options de ligne de &amp;commande</translation> </message> <message> <source>Mtucicoin Core client</source> <translation>Client Mtucicoin Core </translation> </message> <message numerus="yes"> <source>Processed %n blocks of transaction history.</source> <translation><numerusform> Traités %n blocs de l'historique des transactions.</numerusform><numerusform> Traités %n blocs de l'historique des transactions.</numerusform></translation> </message> <message> <source>Synchronizing additional data: %p%</source> <translation>Synchronisation des données additionnelles: %p%</translation> </message> <message> <source>Show the Mtucicoin Core help message to get a list with possible Mtucicoin command-line options</source> <translation>Afficher le message d'aide de Mtucicoin Core pour obtenir une liste des options de ligne de commande Bitcoin possibles.</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Fichier</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Réglages</translation> </message> <message> <source>&amp;Tools</source> <translation>&amp;Outils</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Aide</translation> </message> <message> <source>Tabs toolbar</source> <translation>Barre d'outils des onglets</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Mtucicoin network</source> <translation><numerusform>%n connexion active au réseau Mtucicoin </numerusform><numerusform>%n connexions actives au réseau Mtucicoin </numerusform></translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synchronisation avec le réseau en cours...</translation> </message> <message> <source>Importing blocks from disk...</source> <translation>Importation des blocs depuis le disque...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Réindexation des blocs sur le disque...</translation> </message> <message> <source>No block source available...</source> <translation>Aucune source de blocs disponible...</translation> </message> <message> <source>Up to date</source> <translation>À jour</translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n heures</numerusform><numerusform>%n heures</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n jours</numerusform><numerusform>%n jours</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n semaines</numerusform><numerusform>%n semaines</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 et %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n année(s)</numerusform><numerusform>%n années</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 en retard</translation> </message> <message> <source>Catching up...</source> <translation>Rattrapage en cours...</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Le dernier bloc reçu avait été généré il y a %1.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Les transactions après ceci ne sont pas encore visibles.</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> <message> <source>Warning</source> <translation>Avertissement</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Sent transaction</source> <translation>Transaction envoyée</translation> </message> <message> <source>Incoming transaction</source> <translation>Transaction entrante</translation> </message> <message> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Date : %1 Montant : %2 Type : %3 Adresse : %4 </translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Le portefeuille est &lt;b&gt;chiffré&lt;/b&gt; et est actuellement &lt;b&gt;déverrouillé&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; for anonimization only</source> <translation>Le portefeuille est &lt;b&gt;chiffré&lt;/b&gt; et est actuellement &lt;b&gt;déverrouillé&lt;/b&gt; seulement pour l'anonymisation</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Le portefeuille est &lt;b&gt;chiffré&lt;/b&gt; et actuellement &lt;b&gt;verrouillé&lt;/b&gt;</translation> </message> </context> <context> <name>ClientModel</name> <message> <source>Total: %1 (DS compatible: %2 / Enabled: %3)</source> <translation>Total: %1 (Compatible DS: %2 / Actifs: %3)</translation> </message> <message> <source>Network Alert</source> <translation>Alerte réseau</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Quantité :</translation> </message> <message> <source>Bytes:</source> <translation>Octets :</translation> </message> <message> <source>Amount:</source> <translation>Montant :</translation> </message> <message> <source>Priority:</source> <translation>Priorité :</translation> </message> <message> <source>Fee:</source> <translation>Frais :</translation> </message> <message> <source>Coin Selection</source> <translation>Sélection de la Monnaie</translation> </message> <message> <source>Dust:</source> <translation>Poussière:</translation> </message> <message> <source>After Fee:</source> <translation>Après les frais :</translation> </message> <message> <source>Change:</source> <translation>Monnaie :</translation> </message> <message> <source>(un)select all</source> <translation>Tout (dé)sélectionner</translation> </message> <message> <source>Tree mode</source> <translation>Mode arborescence</translation> </message> <message> <source>List mode</source> <translation>Mode liste</translation> </message> <message> <source>(1 locked)</source> <translation>(1 verrouillé)</translation> </message> <message> <source>Amount</source> <translation>Montant</translation> </message> <message> <source>Received with label</source> <translation>Reçu avec étiquette</translation> </message> <message> <source>Received with address</source> <translation>Reçu avec adresse</translation> </message> <message> <source>DS Rounds</source> <translation>Cycles DS</translation> </message> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Confirmations</source> <translation>Confirmations</translation> </message> <message> <source>Confirmed</source> <translation>Confirmée</translation> </message> <message> <source>Priority</source> <translation>Priorité</translation> </message> <message> <source>Copy address</source> <translation>Copier l’adresse</translation> </message> <message> <source>Copy label</source> <translation>Copier l’étiquette</translation> </message> <message> <source>Copy amount</source> <translation>Copier le montant</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copier l'ID de la transaction</translation> </message> <message> <source>Lock unspent</source> <translation>Verrouiller ce qui n'est pas dépensé</translation> </message> <message> <source>Unlock unspent</source> <translation>Déverrouiller ce qui n'est pas dépensé</translation> </message> <message> <source>Copy quantity</source> <translation>Copier la quantité</translation> </message> <message> <source>Copy fee</source> <translation>Copier les frais</translation> </message> <message> <source>Copy after fee</source> <translation>Copier le montant après les frais</translation> </message> <message> <source>Copy bytes</source> <translation>Copier les octets</translation> </message> <message> <source>Copy priority</source> <translation>Copier la priorité</translation> </message> <message> <source>Copy dust</source> <translation>Copier poussière</translation> </message> <message> <source>Copy change</source> <translation>Copier la monnaie</translation> </message> <message> <source>Non-anonymized input selected. &lt;b&gt;Darksend will be disabled.&lt;/b&gt;&lt;br&gt;&lt;br&gt;If you still want to use Darksend, please deselect all non-nonymized inputs first and then check Darksend checkbox again.</source> <translation>Entrée non-anonymisées sélectionnée. &lt;b&gt; Darksend sera désactivé. &lt;/ b&gt; &lt;br&gt; Si vous voulez continuer à utiliser Darksend, veuillez désélectionner toutes les entrées non-anonymisées d'abord, puis vérifier à nouveau la case Darksend.</translation> </message> <message> <source>highest</source> <translation>la plus élevée</translation> </message> <message> <source>higher</source> <translation>plus élevée</translation> </message> <message> <source>high</source> <translation>élevée</translation> </message> <message> <source>medium-high</source> <translation>moyennement-élevée</translation> </message> <message> <source>Can vary +/- %1 duff(s) per input.</source> <translation>Peut varier de +/- %1 duff(s) par entrée.</translation> </message> <message> <source>n/a</source> <translation>n/a</translation> </message> <message> <source>medium</source> <translation>moyenne</translation> </message> <message> <source>low-medium</source> <translation>moyennement-basse</translation> </message> <message> <source>low</source> <translation>basse</translation> </message> <message> <source>lower</source> <translation>plus basse</translation> </message> <message> <source>lowest</source> <translation>la plus basse</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 verrouillé)</translation> </message> <message> <source>none</source> <translation>aucun</translation> </message> <message> <source>yes</source> <translation>oui</translation> </message> <message> <source>no</source> <translation>non</translation> </message> <message> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation>Cette étiquette devient rouge si la taille de la transaction est plus grande que 1 000 octets.</translation> </message> <message> <source>This means a fee of at least %1 per kB is required.</source> <translation>Cela signifie qu'une taxe d'au moins %1 par ko est nécessaire </translation> </message> <message> <source>Can vary +/- 1 byte per input.</source> <translation>Peut varier +/- 1 octet par entrée.</translation> </message> <message> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation>Les transactions à priorité plus haute sont plus à même d'être incluses dans un bloc.</translation> </message> <message> <source>This label turns red, if the priority is smaller than "medium".</source> <translation>Cette étiquette devient rouge si la priorité est plus basse que « moyenne »</translation> </message> <message> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation>Cette étiquette devient rouge si un destinataire reçoit un montant inférieur à %1.</translation> </message> <message> <source>(no label)</source> <translation>(aucune étiquette)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>monnaie de %1 (%2)</translation> </message> <message> <source>(change)</source> <translation>(monnaie)</translation> </message> </context> <context> <name>DarksendConfig</name> <message> <source>Configure Darksend</source> <translation>Configurer Darksend</translation> </message> <message> <source>Basic Privacy</source> <translation>Confidentialité normale</translation> </message> <message> <source>High Privacy</source> <translation>Confidentialité élevée</translation> </message> <message> <source>Maximum Privacy</source> <translation>Confidentialité maximale</translation> </message> <message> <source>Please select a privacy level.</source> <translation>Veuillez choisir un niveau de confidentialité.</translation> </message> <message> <source>Use 2 separate masternodes to mix funds up to 1000 MTUCICOIN</source> <translation>Utiliser 2 masternodes pour mélanger jusqu'à 1000 MTUCICOIN</translation> </message> <message> <source>Use 8 separate masternodes to mix funds up to 1000 MTUCICOIN</source> <translation>Utiliser 8 masternodes pour mélanger jusqu'à 1000 MTUCICOIN</translation> </message> <message> <source>Use 16 separate masternodes</source> <translation>Utiliser 16 masternodes</translation> </message> <message> <source>This option is the quickest and will cost about ~0.025 MTUCICOIN to anonymize 1000 MTUCICOIN</source> <translation>Cette option est la plus rapide et coûtera environ 0,025 MTUCICOIN pour anonymiser 1000 MTUCICOIN</translation> </message> <message> <source>This option is moderately fast and will cost about 0.05 MTUCICOIN to anonymize 1000 MTUCICOIN</source> <translation>Cette option est un peu moins rapide et coûtera environ 0,05 MTUCICOIN pour anonymiser 1000 MTUCICOIN</translation> </message> <message> <source>0.1 MTUCICOIN per 1000 MTUCICOIN you anonymize.</source> <translation>0,1 MTUCICOIN par 1000 MTUCICOIN anonymisés.</translation> </message> <message> <source>This is the slowest and most secure option. Using maximum anonymity will cost</source> <translation>Cette option est le plus lente et la plus sécurisée. Utiliser l'anonymisation maximale coûtera</translation> </message> <message> <source>Darksend Configuration</source> <translation>Configuration de Darksend</translation> </message> <message> <source>Darksend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening Mtucicoin's configuration screen.</source> <translation>Darksend est réglé avec succès sur normal (%1 and 2 rounds). Vous pouvez changer cela à tout moment en ouvrant la fenêtre de configuration du Mtucicoin.</translation> </message> <message> <source>Darksend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening Mtucicoin's configuration screen.</source> <translation>Darksend est réglé avec succès sur haut (%1 and 8 rounds). Vous pouvez changer cela à tout moment en ouvrant la fenêtre de configuration du Mtucicoin.</translation> </message> <message> <source>Darksend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Mtucicoin's configuration screen.</source> <translation>Darksend est réglé avec succès sur maximum (%1 and 16 rounds). Vous pouvez changer cela à tout moment en ouvrant la fenêtre de configuration du Mtucicoin.</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Modifier l'adresse</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Étiquette</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>L'étiquette associée à cette entrée de la liste d'adresses</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresse</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>L'adresse associée à cette entrée de la liste d'adresses. Ceci ne peut être modifié que pour les adresses d'envoi.</translation> </message> <message> <source>New receiving address</source> <translation>Nouvelle adresse de réception</translation> </message> <message> <source>New sending address</source> <translation>Nouvelle adresse d’envoi</translation> </message> <message> <source>Edit receiving address</source> <translation>Modifier l’adresse de réception</translation> </message> <message> <source>Edit sending address</source> <translation>Modifier l’adresse d'envoi</translation> </message> <message> <source>The entered address "%1" is not a valid Mtucicoin address.</source> <translation>L'adresse entrée "%1" est pas une adresse Mtucicoin valide</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>L’adresse fournie « %1 » est déjà présente dans le carnet d'adresses.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Impossible de déverrouiller le portefeuille.</translation> </message> <message> <source>New key generation failed.</source> <translation>Échec de génération de la nouvelle clef.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Un nouveau répertoire de données sera créé.</translation> </message> <message> <source>name</source> <translation>nom</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Le répertoire existe déjà. Ajoutez %1 si vous voulez créer un nouveau répertoire ici.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Le chemin existe déjà et n'est pas un répertoire.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Impossible de créer un répertoire de données ici.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>Mtucicoin Core</source> <translation>Mtucicoin Core</translation> </message> <message> <source>version</source> <translation>version</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About Mtucicoin Core</source> <translation>A propos de Mtucicoin Core</translation> </message> <message> <source>Command-line options</source> <translation>Options de ligne de commande</translation> </message> <message> <source>Usage:</source> <translation>Utilisation :</translation> </message> <message> <source>command-line options</source> <translation>options de ligne de commande</translation> </message> <message> <source>UI options</source> <translation>Options de l'interface utilisateur</translation> </message> <message> <source>Choose data directory on startup (default: 0)</source> <translation>Choisir un répertoire de données au démarrage (par défaut : 0)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Définir la langue, par exemple « fr_CA » (par défaut : la langue du système)</translation> </message> <message> <source>Start minimized</source> <translation>Démarrer minimisé</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Définir les certificats SSL racine pour les requêtes de paiement (par défaut : -système-)</translation> </message> <message> <source>Show splash screen on startup (default: 1)</source> <translation>Afficher l'écran d'accueil au démarrage (par défaut : 1)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Bienvenue</translation> </message> <message> <source>Welcome to Mtucicoin Core.</source> <translation>Bienvenue à Mtucicoin Core</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where Mtucicoin Core will store its data.</source> <translation>Comme il s'agit du premier lancement du logiciel, vous pouvez choisir l'emplacement où Mtucicoin Core sauvegardera ses données.</translation> </message> <message> <source>Mtucicoin Core will download and store a copy of the Mtucicoin block chain. At least %1GB 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>Mtucicoin Core téléchargera et sauvegardera une copie de la chaîne de blocs Mtucicoin. Au moins %1Go de données seront sauvegardées dans ce répertoire, et cette taille augmentera avec le temps. Le portefeuille sera aussi sauvegardé dans ce répertoire.</translation> </message> <message> <source>Use the default data directory</source> <translation>Utiliser le répertoire de données par défaut</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Utiliser un répertoire de données personnalisé :</translation> </message> <message> <source>Mtucicoin Core</source> <translation>Mtucicoin Core</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Erreur: Le répertoire de données spécifié « %1 » ne peut pas être créé.</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> <message> <source>%1 GB of free space available</source> <translation>%1 Go d'espace libre disponible</translation> </message> <message> <source>(of %1 GB needed)</source> <translation>( de %1 Go nécessaire)</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Ouvrir un URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Ouvrir une demande de paiement à partir d'un URI ou d'un fichier</translation> </message> <message> <source>URI:</source> <translation>URI :</translation> </message> <message> <source>Select payment request file</source> <translation>Choisir le fichier de demande de paiement</translation> </message> <message> <source>Select payment request file to open</source> <translation>Choisir le fichier de demande de paiement à ouvrir</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Options</translation> </message> <message> <source>&amp;Main</source> <translation>Réglages &amp;principaux</translation> </message> <message> <source>Automatically start Mtucicoin after logging in to the system.</source> <translation>Démarrer Mtucicoin automatiquement au démarrage du système.</translation> </message> <message> <source>&amp;Start Mtucicoin on system login</source> <translation>&amp;Démarrer Mtucicoin au démarrage du système</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Taille du cache de la base de &amp;données</translation> </message> <message> <source>MB</source> <translation>Mo</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Nombre d'exétrons de &amp;vérification de script</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = auto, &lt; 0 = laisser ce nombre de cœurs inutilisés)</translation> </message> <message> <source>Darksend rounds to use</source> <translation>Nombre de cycles Darksend à effectuer</translation> </message> <message> <source>This amount acts as a threshold to turn off Darksend once it's reached.</source> <translation>Ce montant est le seuil pour désactiver Darksend dès qu'il est atteint.</translation> </message> <message> <source>Amount of Mtucicoin to keep anonymized</source> <translation>Nombre de Mtucicoin à conserver anonymisés</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;Portefeuille</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction&lt;br/&gt;cannot be used until that transaction has at least one confirmation.&lt;br/&gt;This also affects how your balance is computed.</source> <translation>Si vous désactivez la dépense de la monnaie non confirmée, la monnaie d'une transaction&lt;br/&gt;ne peut pas être utilisée tant que cette transaction n'a pas reçu au moins une confirmation.&lt;br/&gt;Ceci affecte aussi comment votre solde est calculé.</translation> </message> <message> <source>Accept connections from outside</source> <translation>Accepter les connexions provenant de l'extérieur</translation> </message> <message> <source>Allow incoming connections</source> <translation>Autoriser les connexions entrantes</translation> </message> <message> <source>Connect to the Mtucicoin network through a SOCKS5 proxy.</source> <translation>Se connecter au réseau Mtucicoin à travers un proxy SOCKS5.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Connectez par SOCKS5 (proxy par défaut):</translation> </message> <message> <source>Expert</source> <translation>Expert</translation> </message> <message> <source>This setting determines the amount of individual masternodes that an input will be anonymized through.&lt;br/&gt;More rounds of anonymization gives a higher degree of privacy, but also costs more in fees.</source> <translation>Ce paramètre détermine le nombre de masternodes uniques par lesquels l'anonymisation sera effectuée.&lt;br/&gt;Plus le nombre de cycles d'anonymisation est important, plus le degré de confidentialité est élevé, mais les frais associés sont d'autant plus importants.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Afficher ou non les fonctions de contrôle des pièces.</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Activer les fonctions de &amp;contrôle des pièces </translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Dépenser la monnaie non confirmée</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Réseau</translation> </message> <message> <source>Automatically open the Mtucicoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Ouvrir automatiquement le port client Mtucicoin sur le routeur. Cela ne fonctionne que sur les routeurs supportant et ayant activé UPnP.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Mapper le port avec l'&amp;UPnP</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>&amp;IP du serveur mandataire :</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Adresse IP du mandataire (par ex. IPv4 : 127.0.0.1 / IPv6 : ::1)</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port :</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Port du serveur mandataire (par ex. 9050)</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Fenêtre</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Afficher uniquement une icône système après minimisation.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimiser dans la barre système au lieu de la barre des tâches</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 Quit in the menu.</source> <translation>Minimiser au lieu de quitter l'application lorsque la fenêtre est fermée. Si cette option est activée, l'application ne pourra être fermée qu'en sélectionnant Quitter dans le menu.</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimiser lors de la fermeture</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Affichage</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>&amp;Langue de l'interface utilisateur :</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting Mtucicoin.</source> <translation>La langue de l'interface utilisateur peut être modifiée ici. Ce paramètre sera pris en compte au redémarrage de Mtucicoin.</translation> </message> <message> <source>Language missing or translation incomplete? Help contributing translations here: https://www.transifex.com/projects/p/mtucicoin/</source> <translation>Langage manquant ou traduction incomplète ? Participez aux traductions ici : https://www.transifex.com/projects/p/mtucicoin/</translation> </message> <message> <source>User Interface Theme:</source> <translation>Thème d'Interface de l'utilisateur :</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unité d'affichage des montants :</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Choisissez la sous-unité par défaut pour l'affichage dans l'interface et lors de l'envoi de pièces.</translation> </message> <message> <source>Decimal digits</source> <translation>Nombre de décimales</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>URL de tiers (par ex. un explorateur de blocs) apparaissant dans l'onglet des transactions comme éléments du menu contextuel. %s dans l'URL est remplacé par le hachage de la transaction. Les URL multiples sont séparées par une barre verticale |.</translation> </message> <message> <source>Third party transaction URLs</source> <translation>URL de transaction d'un tiers</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Options actives de ligne de commande qui annulent les options ci-dessus :</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Réinitialiser toutes les options du client aux valeurs par défaut.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Réinitialisation des options</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>A&amp;nnuler</translation> </message> <message> <source>default</source> <translation>par défaut</translation> </message> <message> <source>none</source> <translation>aucune</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirmer la réinitialisation des options</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Le redémarrage du client est nécessaire pour activer les changements.</translation> </message> <message> <source>Client will be shutdown, do you want to proceed?</source> <translation>Le client sera arrêté, voulez-vous continuer?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Ce changement nécessite un redémarrage du client.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>L'adresse de serveur mandataire fournie est invalide.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulaire</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Mtucicoin network after a connection is established, but this process has not completed yet.</source> <translation>L'information affichée peut être obsolète. Votre portefeuille se synchronise automatiquement avec le réseau Mtucicoin lorsque la connection est établie, mais le process n'est pas encore terminé.</translation> </message> <message> <source>Available:</source> <translation>Disponible :</translation> </message> <message> <source>Your current spendable balance</source> <translation>Votre solde actuel pouvant être dépensé</translation> </message> <message> <source>Pending:</source> <translation>En attente :</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Total des transactions qui doivent encore être confirmées et qu'il n'est pas encore possible de dépenser</translation> </message> <message> <source>Immature:</source> <translation>Immature :</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Le solde généré n'est pas encore mûr</translation> </message> <message> <source>Balances</source> <translation>soldes</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Transactions non confirmés d'adresses en lecture seule</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Solde miné pour les adresses en lecture seule qui n'ont pas encore mûri</translation> </message> <message> <source>Total:</source> <translation>Total :</translation> </message> <message> <source>Your current total balance</source> <translation>Votre solde total actuel</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Solde total actuel pour les adresses en lecture seule</translation> </message> <message> <source>Watch-only:</source> <translation>Lecture seule:</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Votre solde actuel pour adresses en lecture seule</translation> </message> <message> <source>Spendable:</source> <translation>Disponible:</translation> </message> <message> <source>Status:</source> <translation>Status :</translation> </message> <message> <source>Enabled/Disabled</source> <translation>Activé/Désactivé</translation> </message> <message> <source>Completion:</source> <translation>Complétude :</translation> </message> <message> <source>Darksend Balance:</source> <translation>Balance Darksend :</translation> </message> <message> <source>Amount and Rounds:</source> <translation>Montant et Cycles</translation> </message> <message> <source>0 MTUCICOIN / 0 Rounds</source> <translation>0 MTUCICOIN / 0 Cycles</translation> </message> <message> <source>Submitted Denom:</source> <translation>Denom soumis :</translation> </message> <message> <source>n/a</source> <translation>n/a</translation> </message> <message> <source>Darksend</source> <translation>Darksend</translation> </message> <message> <source>Recent transactions</source> <translation>Transactions récentes</translation> </message> <message> <source>Start/Stop Mixing</source> <translation>Démarrer/Arrêtér le mélange</translation> </message> <message> <source>The denominations you submitted to the Masternode.&lt;br&gt;To mix, other users must submit the exact same denominations.</source> <translation>Les dénominations que vous avez soumises à la Masternode.&lt;br&gt;Pour mélanger, d'autres utilisateurs doivent soumettre les mêmes dénominations.</translation> </message> <message> <source>(Last Message)</source> <translation>(Dernier Message)</translation> </message> <message> <source>Try to manually submit a Darksend request.</source> <translation>Essayer de soumettre manuellement une requête Darksend.</translation> </message> <message> <source>Try Mix</source> <translation>Essayer le mélange</translation> </message> <message> <source>Reset the current status of Darksend (can interrupt Darksend if it's in the process of Mixing, which can cost you money!)</source> <translation>Réinitialiser le statut de Darksend (peut interrompre Darksend si le process de mélange est en cours, ce qui peut vous coûter de l'argent !)</translation> </message> <message> <source>Reset</source> <translation>Réinitialiser</translation> </message> <message> <source>out of sync</source> <translation>désynchronisé</translation> </message> <message> <source>Disabled</source> <translation>Désactivé</translation> </message> <message> <source>Start Darksend Mixing</source> <translation>Démarrer le mélange Darksend</translation> </message> <message> <source>Stop Darksend Mixing</source> <translation>Arrêter le mélange Darksend</translation> </message> <message> <source>No inputs detected</source> <translation>Aucune entrée détectée</translation> </message> <message numerus="yes"> <source>%n Rounds</source> <translation><numerusform>%n Cycle</numerusform><numerusform>%n Cycles</numerusform></translation> </message> <message> <source>Not enough compatible inputs to anonymize &lt;span style='color:red;'&gt;%1&lt;/span&gt;,&lt;br&gt;will anonymize &lt;span style='color:red;'&gt;%2&lt;/span&gt; instead</source> <translation>Pas assez d'entrées compatibles pour anonymiser &lt;span style='color:red;'&gt;%1&lt;/span&gt;, &lt;br&gt;nous allons anonymiser &lt;span style='color:red;'&gt;%2&lt;/span&gt; à la place</translation> </message> <message> <source>Overall progress</source> <translation>Progrès global</translation> </message> <message> <source>Denominated</source> <translation>Dénommées</translation> </message> <message> <source>Anonymized</source> <translation>Anonymisés</translation> </message> <message numerus="yes"> <source>Denominated inputs have %5 of %n rounds on average</source> <translation><numerusform>Les entrées dénommées ont %5 sur %n cycles en moyennes</numerusform><numerusform>Les entrées dénommées ont %5 sur %n cycles en moyennes</numerusform></translation> </message> <message> <source>Found enough compatible inputs to anonymize %1</source> <translation>Assez d'entrées compatibles trouvées pour anonymiser %1</translation> </message> <message> <source>Mixed</source> <translation>Mélangés</translation> </message> <message> <source>Enabled</source> <translation>Activé</translation> </message> <message> <source>Last Darksend message: </source> <translation>Dernier message de Darksend: </translation> </message> <message> <source>N/A</source> <translation>N.D.</translation> </message> <message> <source>Darksend was successfully reset.</source> <translation>Darksend est réinitialisé avec succès</translation> </message> <message> <source>If you don't want to see internal Darksend fees/transactions select "Most Common" as Type on the "Transactions" tab.</source> <translation>Pour ne pas voir les transactions/frais Darksend internes sélectionnez "Les plus Communes" comme Type dans l'onglet "Transactions"</translation> </message> <message> <source>Darksend requires at least %1 to use.</source> <translation>Darksend nécessite au moins %1 pour l'utiliser</translation> </message> <message> <source>Wallet is locked and user declined to unlock. Disabling Darksend.</source> <translation>Le portefeuille est vérouillé et l'utilisateur a refusé de le débloquer. Désactivation de Darksend.</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>Payment request error</source> <translation>Erreur de demande de paiement</translation> </message> <message> <source>Cannot start mtucicoin: click-to-pay handler</source> <translation>Impossible de démarrer mtucicoin: click-to-pay le gestionnaire</translation> </message> <message> <source>URI handling</source> <translation>Gestion des URIs</translation> </message> <message> <source>Payment request fetch URL is invalid: %1</source> <translation>L'URL de récupération de la demande de paiement est invalide : %1</translation> </message> <message> <source>Payment request file handling</source> <translation>Gestion des fichiers de demande de paiement</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Adresse de paiement %1 invalide</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid Mtucicoin address or malformed URI parameters.</source> <translation>L'URI ne peut être analysé ! Ceci peut être causé par une adresse Mtucicoin invalide ou par des paramètres d'URI mal composé.</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>Le fichier de demande de paiement ne peut pas être lu ou traité ! Ceci peut être causé par un fichier de demande de paiement invalide.</translation> </message> <message> <source>Payment request rejected</source> <translation>La demande de paiement a été rejetée</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>Le réseau de la demande de paiement ne correspond pas au réseau du client</translation> </message> <message> <source>Payment request has expired.</source> <translation>La demande de paiement a expiré</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>La demande de paiement n'est pas initialisée</translation> </message> <message> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation>Les demandes de paiements non vérifiées à des scripts de paiement personnalisés ne sont pas prises en charge.</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>Le paiement demandé d'un montant de %1 est trop faible (considéré comme de la poussière).</translation> </message> <message> <source>Refund from %1</source> <translation>Remboursement de %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>La demande de paiement %1 est trop volumineuse (%2 octets sur %3 permis)</translation> </message> <message> <source>Payment request DoS protection</source> <translation>Protection DoS de la demande de paiement</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Erreur de communication avec %1 : %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>La demande de paiement ne peux pas être analyzée!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Mauvaise réponse du serveur %1</translation> </message> <message> <source>Network request error</source> <translation>Erreur de demande réseau</translation> </message> <message> <source>Payment acknowledged</source> <translation>Le paiement a été confirmé</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>Address/Hostname</source> <translation>Adresse/Nom d'hôte</translation> </message> <message> <source>User Agent</source> <translation>Agent de l'utilisateur</translation> </message> <message> <source>Ping Time</source> <translation>Temps de Ping</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Montant</translation> </message> <message> <source>Enter a Mtucicoin address (e.g. %1)</source> <translation>Entrez une adresse Mtucicoin (e.g. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 j</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>NETWORK</source> <translation>RÉSEAU</translation> </message> <message> <source>UNKNOWN</source> <translation>INCONNU</translation> </message> <message> <source>None</source> <translation>Aucun</translation> </message> <message> <source>N/A</source> <translation>N.D.</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>&amp;Sauvegarder l'image...</translation> </message> <message> <source>&amp;Copy Image</source> <translation>&amp;Copier l'image</translation> </message> <message> <source>Save QR Code</source> <translation>Sauvegarder le code QR</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>Image PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>Tools window</source> <translation>Fenêtre des outils</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Informations</translation> </message> <message> <source>General</source> <translation>Général</translation> </message> <message> <source>Name</source> <translation>Nom</translation> </message> <message> <source>Client name</source> <translation>Nom du client</translation> </message> <message> <source>N/A</source> <translation>N.D.</translation> </message> <message> <source>Number of connections</source> <translation>Nombre de connexions</translation> </message> <message> <source>Open the Mtucicoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Ouvrir le fichier de debug Mtucicoin depuis le répertoire de données actuel. Ceci peut prendre plusieurs secondes pour un fichier de debug imposant.</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Ouvrir</translation> </message> <message> <source>Startup time</source> <translation>Heure de démarrage</translation> </message> <message> <source>Network</source> <translation>Réseau</translation> </message> <message> <source>Last block time</source> <translation>Horodatage du dernier bloc</translation> </message> <message> <source>Debug log file</source> <translation>Journal de débogage</translation> </message> <message> <source>Using OpenSSL version</source> <translation>Version d'OpenSSL utilisée</translation> </message> <message> <source>Build date</source> <translation>Date de compilation</translation> </message> <message> <source>Current number of blocks</source> <translation>Nombre actuel de blocs</translation> </message> <message> <source>Client version</source> <translation>Version du client</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Version BerkeleyDB utilisée</translation> </message> <message> <source>Block chain</source> <translation>Chaîne de blocs</translation> </message> <message> <source>Number of Masternodes</source> <translation>Nombre de Masternodes</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <source>Clear console</source> <translation>Nettoyer la console</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>Trafic &amp;réseau</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Nettoyer</translation> </message> <message> <source>Totals</source> <translation>Totaux</translation> </message> <message> <source>Received</source> <translation>Reçus</translation> </message> <message> <source>Sent</source> <translation>Envoyés</translation> </message> <message> <source>&amp;Peers</source> <translation>Liste des &amp;Pairs</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Choisir un pair pour voir les informations détaillées.</translation> </message> <message> <source>Direction</source> <translation>Direction</translation> </message> <message> <source>Version</source> <translation>Version</translation> </message> <message> <source>User Agent</source> <translation>Agent de l'utilisateur</translation> </message> <message> <source>Services</source> <translation>Services</translation> </message> <message> <source>Starting Height</source> <translation>Hauteur de Démarrage</translation> </message> <message> <source>Sync Height</source> <translation>Hauteur de Synchro</translation> </message> <message> <source>Ban Score</source> <translation>Score d'interdiction</translation> </message> <message> <source>Connection Time</source> <translation>Temps de Connexion</translation> </message> <message> <source>Last Send</source> <translation>Dernier Envoi</translation> </message> <message> <source>Last Receive</source> <translation>Dernière Reception</translation> </message> <message> <source>Bytes Sent</source> <translation>Octets Envoyés</translation> </message> <message> <source>Bytes Received</source> <translation>Octets Reçus</translation> </message> <message> <source>Ping Time</source> <translation>Temps de Ping</translation> </message> <message> <source>&amp;Wallet Repair</source> <translation>&amp;Réparation de Portefeuille</translation> </message> <message> <source>Salvage wallet</source> <translation>Sauvetage de portefeuille</translation> </message> <message> <source>Rescan blockchain files</source> <translation>Scanner à nouveau les fichiers de la chaîne de blocs</translation> </message> <message> <source>Recover transactions 1</source> <translation>Récupérer les transactions 1</translation> </message> <message> <source>Recover transactions 2</source> <translation>Récupérer les transactions 2</translation> </message> <message> <source>Upgrade wallet format</source> <translation>Mise à jour du format du portefeuille</translation> </message> <message> <source>The buttons below will restart the wallet with command-line options to repair the wallet, fix issues with corrupt blockhain files or missing/obsolete transactions.</source> <translation>Les boutons ci-dessous redémarreront le portefeuille avec des paramètres de ligne de commande pour réparer le portefeuille, corriger des problèmes de fichiers corrompus de chaine de blocs ou de transactions manquantes ou obsolètes</translation> </message> <message> <source>-salvagewallet: Attempt to recover private keys from a corrupt wallet.dat.</source> <translation>-salvagewallet: Tenter de récupérer les clés privées d'un wallet.dat corrompu</translation> </message> <message> <source>-rescan: Rescan the block chain for missing wallet transactions.</source> <translation>-rescan: Réanalyser la chaine de blocs pour les transactions de portefeuille manquantes</translation> </message> <message> <source>-zapwallettxes=1: Recover transactions from blockchain (keep meta-data, e.g. account owner).</source> <translation>-zapwallettxes=1: Récupère les transactions depuis la chaine de blocs (en gardant les méta-données, ex. le nom du compte).</translation> </message> <message> <source>-zapwallettxes=2: Recover transactions from blockchain (drop meta-data).</source> <translation>-zapwallettxes=2: Récupère les transactions depuis la chaine de blocs (sans garder les méta-données).</translation> </message> <message> <source>-upgradewallet: Upgrade wallet to latest format on startup. (Note: this is NOT an update of the wallet itself!)</source> <translation>-upgradewallet: Mise à jour du format du fichier wallet.dat vers la dernière version au démarrage. (Note: ce n'est PAS une mise à jour du logiciel portefeuille!)</translation> </message> <message> <source>Wallet repair options.</source> <translation>Options de réparation du portefeuille.</translation> </message> <message> <source>Rebuild index</source> <translation>Reconstruire l'index</translation> </message> <message> <source>-reindex: Rebuild block chain index from current blk000??.dat files.</source> <translation>-reindex: Reconstruire l'index de la chaine de blocs à partir des fichiers blk000??.dat actuels.</translation> </message> <message> <source>In:</source> <translation>Entrant :</translation> </message> <message> <source>Out:</source> <translation>Sortant :</translation> </message> <message> <source>Welcome to the Mtucicoin RPC console.</source> <translation>Bienvenue sur la console RPC de Mtucicoin.</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>Utiliser les touches de curseur pour naviguer dans l'historique et &lt;b&gt;Ctrl-L&lt;/b&gt; pour effacer l'écran.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Taper &lt;b&gt;help&lt;/b&gt; pour afficher une vue générale des commandes disponibles.</translation> </message> <message> <source>%1 B</source> <translation>%1 o</translation> </message> <message> <source>%1 KB</source> <translation>%1 Ko</translation> </message> <message> <source>%1 MB</source> <translation>%1 Mo</translation> </message> <message> <source>%1 GB</source> <translation>%1 Go</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>jamais</translation> </message> <message> <source>Inbound</source> <translation>Arrivant</translation> </message> <message> <source>Outbound</source> <translation>Sortant</translation> </message> <message> <source>Unknown</source> <translation>Inconnus</translation> </message> <message> <source>Fetching...</source> <translation>Récupération...</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>Reuse one of the previously used receiving addresses.&lt;br&gt;Reusing addresses has security and privacy issues.&lt;br&gt;Do not use this unless re-generating a payment request made before.</source> <translation>Réutilise une adresse de réception précédemment utilisée.&lt;br&gt;Réutiliser une adresse pose des problèmes de sécurité et de vie privée.&lt;br&gt;N'utilisez pas cette option sauf si vous générez à nouveau une demande de paiement déjà faite.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>Ré&amp;utiliser une adresse de réception existante (non recommandé)</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 Mtucicoin network.</source> <translation>Un message optionnel à joindre à la demande de paiement, qui sera affiché quand la demande sera ouverte. Note : Ce message ne sera pas envoyé avec le paiement à travers le réseau Mtucicoin.</translation> </message> <message> <source>&amp;Message:</source> <translation>M&amp;essage :</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Un étiquette optionnelle à associer à la nouvelle adresse de réception</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened.&lt;br&gt;Note: The message will not be sent with the payment over the Mtucicoin network.</source> <translation>Un message optionnel à joindre à la demande de paiement, qui sera affiché quand la demande sera ouverte.&lt;br&gt;Note : Ce message ne sera pas envoyé avec le paiement à travers le réseau Mtucicoin.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Utiliser ce formulaire pour demander des paiements. Tous les champs sont &lt;b&gt;optionnels&lt;/b&gt;.</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Étiquette :</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Un montant optionnel à demander. Laisser ceci vide ou à zéro pour ne pas demander de montant spécifique.</translation> </message> <message> <source>&amp;Amount:</source> <translation>&amp;Montant :</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Demande de paiement</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Effacer tous les champs du formulaire.</translation> </message> <message> <source>Clear</source> <translation>Effacer</translation> </message> <message> <source>Requested payments history</source> <translation>Historique des paiements demandés</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Afficher la demande choisie (identique à un double-clic sur une entrée)</translation> </message> <message> <source>Show</source> <translation>Afficher</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Enlever les entrées sélectionnées de la liste</translation> </message> <message> <source>Remove</source> <translation>Enlever</translation> </message> <message> <source>Copy label</source> <translation>Copier l’étiquette</translation> </message> <message> <source>Copy message</source> <translation>Copier le message</translation> </message> <message> <source>Copy amount</source> <translation>Copier le montant</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>Code QR</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copier l'&amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copier l'&amp;adresse</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Sauvegarder l'image...</translation> </message> <message> <source>Request payment to %1</source> <translation>Demande de paiement à %1</translation> </message> <message> <source>Payment information</source> <translation>Informations de paiement</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>Amount</source> <translation>Montant</translation> </message> <message> <source>Label</source> <translation>Étiquette</translation> </message> <message> <source>Message</source> <translation>Message</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>L'URI résultant est trop long, essayez de réduire le texte d'étiquette / de message.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Erreur d'encodage de l'URI en code QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Label</source> <translation>Étiquette</translation> </message> <message> <source>Message</source> <translation>Message</translation> </message> <message> <source>Amount</source> <translation>Montant</translation> </message> <message> <source>(no label)</source> <translation>(pas d'étiquette)</translation> </message> <message> <source>(no message)</source> <translation>(pas de message)</translation> </message> <message> <source>(no amount)</source> <translation>(aucun montant)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Envoyer des pièces</translation> </message> <message> <source>Coin Control Features</source> <translation>Fonctions de contrôle des pièces</translation> </message> <message> <source>Inputs...</source> <translation>Entrées...</translation> </message> <message> <source>automatically selected</source> <translation>choisi automatiquement</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fonds insuffisants !</translation> </message> <message> <source>Quantity:</source> <translation>Quantité :</translation> </message> <message> <source>Bytes:</source> <translation>Octets :</translation> </message> <message> <source>Amount:</source> <translation>Montant :</translation> </message> <message> <source>Priority:</source> <translation>Priorité :</translation> </message> <message> <source>medium</source> <translation>moyen</translation> </message> <message> <source>Fee:</source> <translation>Frais :</translation> </message> <message> <source>Dust:</source> <translation>Poussière:</translation> </message> <message> <source>no</source> <translation>non</translation> </message> <message> <source>After Fee:</source> <translation>Après les frais :</translation> </message> <message> <source>Change:</source> <translation>Monnaie :</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>Si ceci est actif mais l'adresse de monnaie rendue est vide ou invalide, la monnaie sera envoyée vers une adresse nouvellement générée.</translation> </message> <message> <source>Custom change address</source> <translation>Adresse personnalisée de monnaie rendue</translation> </message> <message> <source>Transaction Fee:</source> <translation>Frais de Transaction:</translation> </message> <message> <source>Choose...</source> <translation>Choisissez...</translation> </message> <message> <source>collapse fee-settings</source> <translation>replier les paramètres de frais</translation> </message> <message> <source>Minimize</source> <translation>Minimiser</translation> </message> <message> <source>If the custom fee is set to 1000 duffs and the transaction is only 250 bytes, then "per kilobyte" only pays 250 duffs in fee,&lt;br /&gt;while "at least" pays 1000 duffs. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Si les frais personnalisés sont à 1000 duffs et que la transaction fait seulement 250 octets, alors "par kilooctet" payera seulement 250 duffs de frais,&lt;br /&gt;alors que "au moins" payera 1000 duffs. Pour les transactions de plus d'un kilooctet les deux payeront par kilooctet.</translation> </message> <message> <source>If the custom fee is set to 1000 duffs and the transaction is only 250 bytes, then "per kilobyte" only pays 250 duffs in fee,&lt;br /&gt;while "total at least" pays 1000 duffs. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Si les frais personnalisés sont à 1000 duffs et que la transaction fait seulement 250 octets, alors "par kilooctet" payera seulement 250 duffs de frais,&lt;br /&gt;alors que "total au moins" payera 1000 duffs. Pour les transactions de plus d'un kilooctet les deux payeront par kilooctet.</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.&lt;br /&gt;But be aware that this can end up in a never confirming transaction once there is more demand for mtucicoin transactions than the network can process.</source> <translation>Payer les frais minimums fonctionne tant qu'il y a moins de volume de transactions que de place dans les blocs.&lt;br/&gt;Mais soyez conscients que ceci peut amener a des transactions qui ne seront jamais confirmées lorsqu'il y aura plus de demande que la capacité du réseau.</translation> </message> <message> <source>per kilobyte</source> <translation>par kilooctet</translation> </message> <message> <source>total at least</source> <translation>total au moins</translation> </message> <message> <source>(read the tooltip)</source> <translation>(lisez l'infobulle)</translation> </message> <message> <source>Recommended:</source> <translation>Recommandé:</translation> </message> <message> <source>Custom:</source> <translation>Personnalisé:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Les frais intelligents ne sont pas encore initialisés . Ceci nécessite quelques blocs généralement...)</translation> </message> <message> <source>Confirmation time:</source> <translation>Temps de Confirmation:</translation> </message> <message> <source>normal</source> <translation>normal</translation> </message> <message> <source>fast</source> <translation>rapide</translation> </message> <message> <source>Send as zero-fee transaction if possible</source> <translation>Envoyé en tant que transaction sans frais si possible</translation> </message> <message> <source>(confirmation may take longer)</source> <translation>(la confirmation pourra prendre plus de temps)</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirmer l’action d'envoi</translation> </message> <message> <source>S&amp;end</source> <translation>E&amp;nvoyer</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Effacer tous les champs du formulaire.</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Tout nettoyer</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Envoyer à plusieurs destinataires à la fois</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Ajouter un &amp;destinataire</translation> </message> <message> <source>Darksend</source> <translation>Darksend</translation> </message> <message> <source>InstantX</source> <translation>InstantX</translation> </message> <message> <source>Balance:</source> <translation>Solde :</translation> </message> <message> <source>Copy quantity</source> <translation>Copier la quantité</translation> </message> <message> <source>Copy amount</source> <translation>Copier le montant</translation> </message> <message> <source>Copy fee</source> <translation>Copier les frais</translation> </message> <message> <source>Copy after fee</source> <translation>Copier le montant après les frais</translation> </message> <message> <source>Copy bytes</source> <translation>Copier les octets</translation> </message> <message> <source>Copy priority</source> <translation>Copier la priorité</translation> </message> <message> <source>Copy dust</source> <translation>Copier poussière</translation> </message> <message> <source>Copy change</source> <translation>Copier la monnaie</translation> </message> <message> <source>using</source> <translation>utiliser</translation> </message> <message> <source>anonymous funds</source> <translation>fonds anonymisés</translation> </message> <message> <source>(darksend requires this amount to be rounded up to the nearest %1).</source> <translation>(darksend nécessite que ce montant soit arrondi au plus proche de %1).</translation> </message> <message> <source>any available funds (not recommended)</source> <translation>tout fonds disponible (non recommandé)</translation> </message> <message> <source>and InstantX</source> <translation>et InstantX</translation> </message> <message> <source>%1 to %2</source> <translation>%1 à %2</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Êtes-vous sûr de vouloir envoyer ?</translation> </message> <message> <source>are added as transaction fee</source> <translation>ajouté en tant que frais de transaction</translation> </message> <message> <source>Total Amount = &lt;b&gt;%1&lt;/b&gt;&lt;br /&gt;= %2</source> <translation>Montant Total = &lt;b&gt;%1&lt;/b&gt;&lt;br /&gt;= %2</translation> </message> <message> <source>Confirm send coins</source> <translation>Confirmer l’envoi des pièces</translation> </message> <message> <source>A fee %1 times higher than %2 per kB is considered an insanely high fee.</source> <translation>Des frais %1 plus grands que %2 par koctets sont considéres comme excessifs.</translation> </message> <message numerus="yes"> <source>Estimated to begin confirmation within %n block(s).</source> <translation><numerusform>Le début de confirmation est estimé dans %n bloc.</numerusform><numerusform>Le début de confirmation est estimé dans les %n blocs.</numerusform></translation> </message> <message> <source>The recipient address is not valid, please recheck.</source> <translation>L'adresse du destinataire n’est pas valide, veuillez la vérifier.</translation> </message> <message> <source>&lt;b&gt;(%1 of %2 entries displayed)&lt;/b&gt;</source> <translation>&lt;b&gt;(%1 sur %2 entrées affichées)&lt;/b&gt;</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>Le montant à payer doit être supérieur à 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>Le montant dépasse votre solde.</translation> </message> <message> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Le montant dépasse votre solde lorsque les frais de transaction de %1 sont inclus.</translation> </message> <message> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Adresse indentique trouvée, il n'est possible d'envoyer qu'une fois à chaque adresse par opération d'envoi.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>La création de la transaction a échoué !</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>La transaction a été rejetée ! Ceci peut arriver si certaines pièces de votre portefeuille étaient déjà dépensées, par exemple si vous avez utilisé une copie de wallet.dat et que des pièces ont été dépensées dans la copie sans être marquées comme telles ici.</translation> </message> <message> <source>Error: The wallet was unlocked only to anonymize coins.</source> <translation>Erreur: Le portefeuille a été déverouillé seulement pour l'anonymisation des pièces.</translation> </message> <message> <source>Pay only the minimum fee of %1</source> <translation>Payer seulement les frais minimum de %1</translation> </message> <message> <source>Warning: Invalid Mtucicoin address</source> <translation>Attention: adresse Mtucicoin invalide</translation> </message> <message> <source>Warning: Unknown change address</source> <translation>Attention : adresse de monnaie rendue inconnue</translation> </message> <message> <source>(no label)</source> <translation>(pas d'étiquette)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>This is a normal payment.</source> <translation>Ceci est un paiement normal.</translation> </message> <message> <source>Pay &amp;To:</source> <translation>&amp;Payer à :</translation> </message> <message> <source>The Mtucicoin address to send the payment to</source> <translation>L'adresse Mtucicoin à laquelle envoyer de la monnaie</translation> </message> <message> <source>Choose previously used address</source> <translation>Choisir une adresse déjà utilisée</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Coller l'adresse depuis le presse-papier</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Enlever cette entrée</translation> </message> <message> <source>&amp;Label:</source> <translation>É&amp;tiquette :</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Saisir une étiquette pour cette adresse afin de l'ajouter à la liste d'adresses utilisées</translation> </message> <message> <source>A&amp;mount:</source> <translation>&amp;Montant :</translation> </message> <message> <source>Message:</source> <translation>Message :</translation> </message> <message> <source>A message that was attached to the mtucicoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Mtucicoin network.</source> <translation>Un message qui était joint au Mtucicoin : URI qui sera sauvegardée avec la transaction pour référence. Note : Ce message ne sera pas envoyé à travers le réseau Mtucicoin.</translation> </message> <message> <source>This is an unverified payment request.</source> <translation>Ceci est une demande de paiement non vérifiée.</translation> </message> <message> <source>Pay To:</source> <translation>Payer à :</translation> </message> <message> <source>Memo:</source> <translation>Mémo :</translation> </message> <message> <source>This is a verified payment request.</source> <translation>Ceci est une demande de paiement vérifiée.</translation> </message> <message> <source>Enter a label for this address to add it to your address book</source> <translation>Saisir une étiquette pour cette adresse afin de l’ajouter à votre carnet d’adresses</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>Mtucicoin Core is shutting down...</source> <translation>Arrêt de Mtucicoin Core...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Ne pas fermer l'ordinateur jusqu'à la disparition de cette fenêtre.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Signatures - Signer / Vérifier un message</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Signer un message</translation> </message> <message> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Vous pouvez signer des messages avec vos adresses pour prouver que vous les détenez. Faites attention de ne pas signer de vague car des attaques d'hameçonnage peuvent essayer d'usurper votre identité par votre signature. Ne signez que des déclarations entièrement détaillées et avec lesquelles vous serez d'accord.</translation> </message> <message> <source>The Mtucicoin address to sign the message with</source> <translation>L'adresse Mtucicoin avec laquelle signer le message</translation> </message> <message> <source>Choose previously used address</source> <translation>Choisir une adresse précédemment utilisée</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Coller une adresse depuis le presse-papier</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Saisir ici le message que vous désirez signer</translation> </message> <message> <source>Signature</source> <translation>Signature</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copier la signature actuelle dans le presse-papier</translation> </message> <message> <source>Sign the message to prove you own this Mtucicoin address</source> <translation>Signer le message pour prouver que vous possédez cette adresse Mtucicoin</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Signer le &amp;message</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Réinitialiser tous les champs de signature de message</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Tout nettoyer</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Vérifier un message</translation> </message> <message> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Saisir ci-dessous l'adresse de signature, le message (assurez-vous d'avoir copié exactement les retours à la ligne, les espaces, tabulations etc.) et la signature pour vérifier le message. Faire attention à ne pas déduire davantage de la signature que ce qui est contenu dans le message signé lui-même pour éviter d'être trompé par une attaque d'homme du milieu.</translation> </message> <message> <source>The Mtucicoin address the message was signed with</source> <translation>L'adresse Mtucicoin avec laquelle le message a été signé</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Mtucicoin address</source> <translation>Vérifier le message pour s'assurer qu'il a été signé avec l'adresse Mtucicoin spécifiée</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Vérifier le &amp;message</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Réinitialiser tous les champs de vérification de message</translation> </message> <message> <source>Click "Sign Message" to generate signature</source> <translation>Cliquez sur « Signer le message » pour générer la signature</translation> </message> <message> <source>The entered address is invalid.</source> <translation>L'adresse saisie est invalide.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Veuillez vérifier l'adresse et réessayer.</translation> </message> <message> <source>The entered address does not refer to a key.</source> <translation>L'adresse saisie ne fait pas référence à une clef.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>Le déverrouillage du portefeuille a été annulé.</translation> </message> <message> <source>Private key for the entered address is not available.</source> <translation>La clef privée pour l'adresse indiquée n'est pas disponible.</translation> </message> <message> <source>Message signing failed.</source> <translation>La signature du message a échoué.</translation> </message> <message> <source>Message signed.</source> <translation>Le message a été signé.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>La signature n'a pu être décodée.</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Veuillez vérifier la signature et réessayer.</translation> </message> <message> <source>The signature did not match the message digest.</source> <translation>La signature ne correspond pas à l'empreinte du message.</translation> </message> <message> <source>Message verification failed.</source> <translation>Échec de la vérification du message.</translation> </message> <message> <source>Message verified.</source> <translation>Message vérifié.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>Mtucicoin Core</source> <translation>Mtucicoin Core</translation> </message> <message> <source>Version %1</source> <translation>Version %1</translation> </message> <message> <source>The Bitcoin Core developers</source> <translation>Les développeurs Bitcoin Core</translation> </message> <message> <source>The Mtucicoin Core developers</source> <translation>Les développeurs Mtucicoin Core</translation> </message> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>Ko/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Ouvert jusqu'à %1</translation> </message> <message> <source>conflicted</source> <translation>en conflit</translation> </message> <message> <source>%1/offline (verified via instantx)</source> <translation>%1/déconnecté (vérifié avec instantx)</translation> </message> <message> <source>%1/confirmed (verified via instantx)</source> <translation>%1/confirmé (verifié avec instantx)</translation> </message> <message> <source>%1 confirmations (verified via instantx)</source> <translation>%1 confirmations (verifié avec instantx)</translation> </message> <message> <source>%1/offline</source> <translation>%1/déconnecté</translation> </message> <message> <source>%1/unconfirmed</source> <translation>%1/non confirmée</translation> </message> <message> <source>%1 confirmations</source> <translation>%1 confirmations</translation> </message> <message> <source>%1/offline (InstantX verification in progress - %2 of %3 signatures)</source> <translation>%1/déconnecté (vérification d'InstantX en cours - %2 sur %3 signatures)</translation> </message> <message> <source>%1/confirmed (InstantX verification in progress - %2 of %3 signatures )</source> <translation>%1/confirmé (vérification d'InstantX en cours - %2 sur %3 signatures)</translation> </message> <message> <source>%1 confirmations (InstantX verification in progress - %2 of %3 signatures)</source> <translation>%1 confirmations (vérification d'InstantX en cours - %2 sur %3 signatures)</translation> </message> <message> <source>%1/offline (InstantX verification failed)</source> <translation>%1/déconnecté (La vérification d'InstantX a échoué)</translation> </message> <message> <source>%1/confirmed (InstantX verification failed)</source> <translation>%1/confirmé (La vérification d'InstantX a échoué)</translation> </message> <message> <source>Status</source> <translation>État</translation> </message> <message> <source>, has not been successfully broadcast yet</source> <translation>, n’a pas encore été diffusée avec succès</translation> </message> <message numerus="yes"> <source>, broadcast through %n node(s)</source> <translation><numerusform>, diffusée à travers %n nœud</numerusform><numerusform>, diffusée à travers %n nœuds</numerusform></translation> </message> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Source</source> <translation>Source</translation> </message> <message> <source>Generated</source> <translation>Généré</translation> </message> <message> <source>From</source> <translation>De</translation> </message> <message> <source>unknown</source> <translation>inconnu</translation> </message> <message> <source>To</source> <translation>À</translation> </message> <message> <source>own address</source> <translation>votre propre adresse</translation> </message> <message> <source>watch-only</source> <translation>lecture seule</translation> </message> <message> <source>label</source> <translation>étiquette</translation> </message> <message> <source>Credit</source> <translation>Crédit</translation> </message> <message numerus="yes"> <source>matures in %n more block(s)</source> <translation><numerusform>arrive à maturité dans %n bloc de plus</numerusform><numerusform>arrive à maturité dans %n blocs de plus</numerusform></translation> </message> <message> <source>not accepted</source> <translation>refusé</translation> </message> <message> <source>Debit</source> <translation>Débit</translation> </message> <message> <source>Total debit</source> <translation>Total débit</translation> </message> <message> <source>Total credit</source> <translation>Total crédit</translation> </message> <message> <source>Transaction fee</source> <translation>Frais de transaction</translation> </message> <message> <source>Net amount</source> <translation>Montant net</translation> </message> <message> <source>Message</source> <translation>Message</translation> </message> <message> <source>Comment</source> <translation>Commentaire</translation> </message> <message> <source>Transaction ID</source> <translation>ID de la transaction</translation> </message> <message> <source>Merchant</source> <translation>Marchand</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>Les pièces générées doivent mûrir pendant %1 blocs avant de pouvoir être dépensées. Lorsque vous avez généré ce bloc, il a été diffusé sur le réseau pour être ajouté à la chaîne de blocs. S’il échoue a intégrer la chaîne, son état sera modifié en « non accepté » et il ne sera pas possible de le dépenser. Ceci peut arriver occasionnellement si un autre nœud génère un bloc à quelques secondes du votre.</translation> </message> <message> <source>Debug information</source> <translation>Informations de débogage</translation> </message> <message> <source>Transaction</source> <translation>Transaction</translation> </message> <message> <source>Inputs</source> <translation>Entrées</translation> </message> <message> <source>Amount</source> <translation>Montant</translation> </message> <message> <source>true</source> <translation>vrai</translation> </message> <message> <source>false</source> <translation>faux</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>Transaction details</source> <translation>Détails de la transaction</translation> </message> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Ce panneau affiche une description détaillée de la transaction</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message numerus="yes"> <source>Open for %n more block(s)</source> <translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation> </message> <message> <source>Open until %1</source> <translation>Ouvert jusqu'à %1</translation> </message> <message> <source>Offline</source> <translation>Déconnecté</translation> </message> <message> <source>Unconfirmed</source> <translation>Non confirmé</translation> </message> <message> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Confirmation (%1 sur %2 confirmations recommandées)</translation> </message> <message> <source>Confirmed (%1 confirmations)</source> <translation>Confirmée (%1 confirmations)</translation> </message> <message> <source>Conflicted</source> <translation>En conflit</translation> </message> <message> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Immature (%1 confirmations, sera disponible après %2)</translation> </message> <message> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation> </message> <message> <source>Generated but not accepted</source> <translation>Généré mais pas accepté</translation> </message> <message> <source>Received with</source> <translation>Reçue avec</translation> </message> <message> <source>Received from</source> <translation>Reçue de</translation> </message> <message> <source>Received via Darksend</source> <translation>Reçu par Darksend</translation> </message> <message> <source>Sent to</source> <translation>Envoyée à</translation> </message> <message> <source>Payment to yourself</source> <translation>Paiement à vous-même</translation> </message> <message> <source>Mined</source> <translation>Miné</translation> </message> <message> <source>Darksend Denominate</source> <translation>Dénomination Darksend</translation> </message> <message> <source>Darksend Collateral Payment</source> <translation>Paiement Darksend Collatéral</translation> </message> <message> <source>Darksend Make Collateral Inputs</source> <translation>Darksend Création d'Entrées Collatérales</translation> </message> <message> <source>Darksend Create Denominations</source> <translation>Darksend Création de Dénominations</translation> </message> <message> <source>Darksent</source> <translation>Darksent</translation> </message> <message> <source>watch-only</source> <translation>lecture seule</translation> </message> <message> <source>(n/a)</source> <translation>(n.d)</translation> </message> <message> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>État de la transaction. Laissez le pointeur de la souris sur ce champ pour voir le nombre de confirmations.</translation> </message> <message> <source>Date and time that the transaction was received.</source> <translation>Date et heure de réception de la transaction.</translation> </message> <message> <source>Type of transaction.</source> <translation>Type de transaction.</translation> </message> <message> <source>Whether or not a watch-only address is involved in this transaction.</source> <translation>Si une adresse en lecture seule est impliquée dans cette transaction.</translation> </message> <message> <source>Destination address of transaction.</source> <translation>L’adresse de destination de la transaction.</translation> </message> <message> <source>Amount removed from or added to balance.</source> <translation>Montant ajouté ou enlevé au solde.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Toutes</translation> </message> <message> <source>Today</source> <translation>Aujourd’hui</translation> </message> <message> <source>This week</source> <translation>Cette semaine</translation> </message> <message> <source>This month</source> <translation>Ce mois-ci</translation> </message> <message> <source>Last month</source> <translation>Le mois dernier</translation> </message> <message> <source>This year</source> <translation>Cette année</translation> </message> <message> <source>Range...</source> <translation>Intervalle...</translation> </message> <message> <source>Most Common</source> <translation>Les Plus Courants</translation> </message> <message> <source>Received with</source> <translation>Reçue avec</translation> </message> <message> <source>Sent to</source> <translation>Envoyée à</translation> </message> <message> <source>Darksent</source> <translation>Darksent</translation> </message> <message> <source>Darksend Make Collateral Inputs</source> <translation>Darksend Création d'Entrées Collatérales</translation> </message> <message> <source>Darksend Create Denominations</source> <translation>Darksend Création de Dénominations</translation> </message> <message> <source>Darksend Denominate</source> <translation>Dénomination Darksend</translation> </message> <message> <source>Darksend Collateral Payment</source> <translation>Paiement Darksend Collatéral</translation> </message> <message> <source>To yourself</source> <translation>À vous-même</translation> </message> <message> <source>Mined</source> <translation>Miné</translation> </message> <message> <source>Other</source> <translation>Autres</translation> </message> <message> <source>Enter address or label to search</source> <translation>Saisir une adresse ou une étiquette à rechercher</translation> </message> <message> <source>Min amount</source> <translation>Montant min.</translation> </message> <message> <source>Copy address</source> <translation>Copier l’adresse</translation> </message> <message> <source>Copy label</source> <translation>Copier l’étiquette</translation> </message> <message> <source>Copy amount</source> <translation>Copier le montant</translation> </message> <message> <source>Copy transaction ID</source> <translation>Copier l'ID de la transaction</translation> </message> <message> <source>Edit label</source> <translation>Modifier l’étiquette</translation> </message> <message> <source>Show transaction details</source> <translation>Afficher les détails de la transaction</translation> </message> <message> <source>Export Transaction History</source> <translation>Exporter l'historique des transactions</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Valeurs séparées par des virgules (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Confirmée</translation> </message> <message> <source>Watch-only</source> <translation>Lecture seule</translation> </message> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Label</source> <translation>Étiquette</translation> </message> <message> <source>Address</source> <translation>Adresse</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Exporting Failed</source> <translation>L'exportation a échoué</translation> </message> <message> <source>There was an error trying to save the transaction history to %1.</source> <translation>Une erreur est survenue lors de l'enregistrement de l'historique des transactions vers %1.</translation> </message> <message> <source>Exporting Successful</source> <translation>Exportation réussie</translation> </message> <message> <source>The transaction history was successfully saved to %1.</source> <translation>L'historique des transactions a été sauvegardée avec succès vers %1.</translation> </message> <message> <source>Range:</source> <translation>Intervalle :</translation> </message> <message> <source>to</source> <translation>à</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>Unité utilisée pour montrer les montants. Cliquez pour choisir une autre unité.</translation> </message> </context> <context> <name>WalletFrame</name> <message> <source>No wallet has been loaded.</source> <translation>Aucun portefeuille de chargé.</translation> </message> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Envoyer des pièces</translation> </message> <message> <source>InstantX doesn't support sending values that high yet. Transactions are currently limited to %1 MTUCICOIN.</source> <translation>InstantX ne supporte pas des transferts aussi élevés. Les transactions sont pour le moment limitées à %11 MTUCICOIN.</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Exporter</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exporter les données de l'onglet courant vers un fichier</translation> </message> <message> <source>Selected amount:</source> <translation>Montant sélectionné:</translation> </message> <message> <source>Backup Wallet</source> <translation>Sauvegarder le portefeuille</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Données de portefeuille (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Échec de la sauvegarde</translation> </message> <message> <source>There was an error trying to save the wallet data to %1.</source> <translation>Une erreur est survenue lors de l'enregistrement des données de portefeuille vers %1.</translation> </message> <message> <source>Backup Successful</source> <translation>Sauvegarde réussie</translation> </message> <message> <source>The wallet data was successfully saved to %1.</source> <translation>Les données de portefeuille ont été enregistrées avec succès vers %1</translation> </message> </context> <context> <name>mtucicoin-core</name> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Se lier à l'adresse donnée et toujours l'écouter. Utilisez la notation [host]:port pour l'IPv6</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. Mtucicoin Core is probably already running.</source> <translation>Impossible d’obtenir un verrou sur le répertoire de données %s. Mtucicoin Core fonctionne probablement déjà.</translation> </message> <message> <source>Darksend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins.</source> <translation>Darksend utilise les montants dénominés exacts pour envoyer des fonds, vous pourriez simplement avoir besoin d'anonymiser plus de pièces.</translation> </message> <message> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation>Passer en mode de test de régression qui utilise une chaîne spéciale dans laquelle les blocs sont résolus instantanément.</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Erreur: L'écoute de connections entrantes a échouée (erreur retournée: %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>Exécuter une commande lorsqu'une alerte pertinente est reçue ou si nous voyons une bifurcation vraiment étendue (%s dans la commande est remplacé par le message)</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Exécuter la commande lorsqu'une transaction de portefeuille change (%s dans la commande est remplacée par TxID)</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Exécuter la commande lorsque le meilleur bloc change (%s dans cmd est remplacé par le hachage du bloc)</translation> </message> <message> <source>In this mode -genproclimit controls how many blocks are generated immediately.</source> <translation>Dans ce mode -genproclimit contrôle combien de blocs sont générés immédiatement.</translation> </message> <message> <source>InstantX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again.</source> <translation>InstantX nécessite des entrées avec au moins 6 confirmations, vous devriez attendre quelques minutes avant de réessayer.</translation> </message> <message> <source>Name to construct url for KeePass entry that stores the wallet passphrase</source> <translation>Nom pour construire l'URL pour l'entrée KeePass qui conserve la phrase de passe du portefeuille</translation> </message> <message> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation>Requête pour adresses de pairs via recherche DNS, si peu d'adresses (par défaut: 1 sauf si -connect)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Définir la taille maximale en octets des transactions prioritaires/à frais modiques (par défaut : %d)</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>Définir le nombre d'exétrons de vérification des scripts (%u à %d, 0 = auto, &lt; 0 = laisser ce nombre de cœurs inutilisés, par défaut : %d)</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>Ceci est une pré-version de test - l'utiliser à vos risques et périls - ne pas l'utiliser pour miner ou pour des applications marchandes</translation> </message> <message> <source>Unable to bind to %s on this computer. Mtucicoin Core is probably already running.</source> <translation>Impossible de se lier à %s sur cet ordinateur. Mtucicoin Core fonctionne probablement déjà.</translation> </message> <message> <source>Unable to locate enough Darksend denominated funds for this transaction.</source> <translation>Impossible de localiser suffisamment de fonds Darksend dénominés pour cette transaction.</translation> </message> <message> <source>Unable to locate enough Darksend non-denominated funds for this transaction that are not equal 1000 MTUCICOIN.</source> <translation>Impossible de localiser suffisamment de fonds non-dénominés Darksend pour cette transaction qui ne sont pas égaux à 1000 MTUCICOIN.</translation> </message> <message> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Attention : -paytxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous envoyez une transaction.</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Attention : Le réseau ne semble pas totalement d'accord ! Quelques mineurs semblent éprouver des difficultés.</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>Attention : Nous ne semblons pas être en accord complet avec nos pairs ! Vous pourriez avoir besoin d'effectuer une mise à niveau, ou d'autres nœuds du réseau pourraient avoir besoin d'effectuer une mise à niveau.</translation> </message> <message> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Avertissement : une erreur est survenue lors de la lecture de wallet.dat ! Toutes les clefs ont été lues correctement mais les données de transaction ou les entrées du carnet d'adresses sont peut-être incorrectes ou manquantes.</translation> </message> <message> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Avertissement : wallet.dat corrompu, données récupérées ! Le fichier wallet.dat original a été enregistré en tant que wallet.{timestamp}.bak dans %s ; si votre solde ou transactions sont incorrects vous devriez effectuer une restauration depuis une sauvegarde.</translation> </message> <message> <source>You must specify a masternodeprivkey in the configuration. Please see documentation for help.</source> <translation>Vous devez définir masternodeprivkey dans la configuration. Veuillez consulter la documentation pour plus d'aide.</translation> </message> <message> <source>(default: 1)</source> <translation>(par défaut : 1)</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Accepter les commandes de JSON-RPC et de la ligne de commande</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepter les connexions entrantes (par défaut : 1 si aucun -proxy ou -connect )</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation> </message> <message> <source>Already have that input.</source> <translation>Entrée déjà présente.</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenter de récupérer les clefs privées d'un wallet.dat corrompu</translation> </message> <message> <source>Block creation options:</source> <translation>Options de création de bloc :</translation> </message> <message> <source>Can't denominate: no compatible inputs left.</source> <translation>Ne peux pas dénommée: pas d'entrées compatibles restantes.</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Impossible de revenir à une version inférieure du portefeuille</translation> </message> <message> <source>Cannot resolve -bind address: '%s'</source> <translation>Impossible de résoudre l'adresse -bind : « %s »</translation> </message> <message> <source>Cannot resolve -externalip address: '%s'</source> <translation>Impossible de résoudre l'adresse -externalip : « %s »</translation> </message> <message> <source>Cannot write default address</source> <translation>Impossible d'écrire l'adresse par défaut</translation> </message> <message> <source>Collateral not valid.</source> <translation>Collatéral invalide.</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Ne se connecter qu'au(x) nœud(s) spécifié(s)</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation> </message> <message> <source>Connection options:</source> <translation>Options de connexion :</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Base corrompue de données des blocs détectée</translation> </message> <message> <source>Darksend options:</source> <translation>Options Darksend :</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Options de test/de débogage :</translation> </message> <message> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Découvrir sa propre adresse IP (par défaut : 1 lors de l'écoute et si aucun -externalip)</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Ne pas charger le portefeuille et désactiver les appels RPC</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Voulez-vous reconstruire la base de données des blocs maintenant ?</translation> </message> <message> <source>Done loading</source> <translation>Chargement terminé</translation> </message> <message> <source>Entries are full.</source> <translation>Les entrées sont pleines.</translation> </message> <message> <source>Error initializing block database</source> <translation>Erreur lors de l'initialisation de la base de données des blocs</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Erreur lors de l'initialisation de l'environnement de la base de données du portefeuille %s !</translation> </message> <message> <source>Error loading block database</source> <translation>Erreur du chargement de la base de données des blocs</translation> </message> <message> <source>Error loading wallet.dat</source> <translation>Erreur lors du chargement de wallet.dat</translation> </message> <message> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erreur lors du chargement de wallet.dat : portefeuille corrompu</translation> </message> <message> <source>Error opening block database</source> <translation>Erreur lors de l'ouverture de la base de données des blocs</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Erreur à la lecture de la base de données, arrêt en cours.</translation> </message> <message> <source>Error recovering public key.</source> <translation>Erreur à la récupération de la clé publique.</translation> </message> <message> <source>Error</source> <translation>Erreur</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Erreur : l'espace disque est faible !</translation> </message> <message> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Erreur : Portefeuille verrouillé, impossible de créer la transaction !</translation> </message> <message> <source>Error: You already have pending entries in the Darksend pool</source> <translation>Erreur : Vous avez déjà des entrées en attente dans la pool Darksend</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Échec de l'écoute sur un port quelconque. Utilisez -listen=0 si vous voulez ceci.</translation> </message> <message> <source>Failed to read block</source> <translation>La lecture du bloc a échoué</translation> </message> <message> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation>Si &lt;category&gt; n'est pas indiqué, extraire toutes les données de débogage.</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 = garder les méta-données de tx, par ex nom de compte et infos de paiements, 2 = supprimer méta-données)</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>Permettre connections JSON-RPC depuis la source spécifiée. Valide pour &lt;ip&gt; sont: une IP seule (ex. 1.2.3.4), un réseau/masque (ex. 1.2.3.4/255.255.255.0) ou un réseau/CIDR (ex. 1.2.3.4/24). Ce paramétre peut être utilisé plusieurs fois.</translation> </message> <message> <source>An error occurred while setting up the RPC address %s port %u for listening: %s</source> <translation>Une erreur est survenue lors du réglage RPC avec l'adresse %s port %u pour écouter: %s</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Se lier à l'adresse donnée et mettre les pairs qui se connectent en liste blanche. Utilisez la notation [hôte]:port pour l'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>Se lier à l'adresse indiquée pour écouter des connections JSON-RPC. Utilisez la notation [hôte]:port pour l'IPv6. Ce paramètre peut être utilisée à plusieurs reprises (par défaut: se lie a toutes les interfaces)</translation> </message> <message> <source>Change automatic finalized budget voting behavior. mode=auto: Vote for only exact finalized budget match to my generated budget. (string, default: auto)</source> <translation>Change le comportement d'un vote de budget finalisé automatique. mode=auto: Vote uniquement pour le budget finalisé qui correspond a mon budget généré. (string, par défaut : auto)</translation> </message> <message> <source>Continuously rate-limit free transactions to &lt;n&gt;*1000 bytes per minute (default:%u)</source> <translation>Limiter continuellement les transactions gratuites à &lt;n&gt;*1000 octets par minute (par défaut : %u)</translation> </message> <message> <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> <translation>Créer les nouveaux fichiers avec les permissions systèmes par défaut, au lieu du umask 077 (utile seulement si le wallet est désactivé)</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Effacer toutes les transactions du portefeuille et récupère celle qui font partie de la chaine de blocs via -rescan au démarrage</translation> </message> <message> <source>Disable all Mtucicoin specific functionality (Masternodes, Darksend, InstantX, Budgeting) (0-1, default: %u)</source> <translation>Désactivez toutes les fonctionnalités liées à Mtucicoin (Masternode, Darksend, InstantX, Budgetisation) (0-1, par défaut: %u)</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>Distribué sous la licence logicielle MIT, voir le fichier joint COPYING ou &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</translation> </message> <message> <source>Enable instantx, show confirmations for locked transactions (bool, default: %s)</source> <translation>Activer instantx, montrer les confirmations pour les transactions verrouillées (bool, par defaut: %s)</translation> </message> <message> <source>Enable use of automated darksend for funds stored in this wallet (0-1, default: %u)</source> <translation>Activer l'utilisation automatique de Darksend pour les fonds stockés dans ce portefeuille (0-1, défaut: %u)</translation> </message> <message> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation>Erreur: Paramètre obsolète -socks. Il n'est plus possible d'indiquer la version SOCKS, seul les proxy SOCKS5 sont supportés.</translation> </message> <message> <source>Fees (in MTUCICOIN/Kb) smaller than this are considered zero fee for relaying (default: %s)</source> <translation>Les frais (en MTUCICOIN/ko) inférieurs à ce seuil sont considérés comme nuls pour le relayage (par défaut : %s)</translation> </message> <message> <source>Fees (in MTUCICOIN/Kb) smaller than this are considered zero fee for transaction creation (default: %s)</source> <translation>Les frais (en MTUCICOIN/ko) inférieurs à ce seuil sont considérés comme nuls pour la création de transactions (par défaut : %s)</translation> </message> <message> <source>Flush database activity from memory pool to disk log every &lt;n&gt; megabytes (default: %u)</source> <translation>Purger l’activité de la base de données de la zone de mémoire vers le journal sur disque tous les &lt;n&gt; mégaoctets (par défaut : %u)</translation> </message> <message> <source>Found unconfirmed denominated outputs, will wait till they confirm to continue.</source> <translation>Détection de sorties dénominées non confirmées, attente de leur confirmation pour continuer.</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> <translation>Degré de profondeur de la vérification des blocs -checkblocks (0-4, par défaut : %u)</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>Si paytxfee n'est pas indiqué, inclure assez de frais pour que les transactions commencent leur confirmation en moyenne dans les n blocs (par défaut : %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>Montant invalide pour -maxtxfee=&lt;montant&gt; : « %s » (doit être au moins du montant de frais minrelay de %s pour éviter des transactions bloquées)</translation> </message> <message> <source>Log transaction priority and fee per kB when mining blocks (default: %u)</source> <translation>Lors du minage, journaliser la priorité des transactions et les frais par ko (par défaut : %u) </translation> </message> <message> <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> <translation>Maintenir un index complet des transactions, utilisé par l'appel rpc getrawtransaction (par défaut : %u)</translation> </message> <message> <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> <translation>Taille maximale des données dans les transactions support de données que l'on relaye et mine (par défaut : %u)</translation> </message> <message> <source>Maximum total fees to use in a single wallet transaction, setting too low may abort large transactions (default: %s)</source> <translation>Frais totaux maximum pour une transaction portefeuille unique, si trop bas, risque d'annulation pour transactions trop volumineuses (par défaut : %s)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> <translation>Délai en secondes de refus de reconnexion pour les pairs présentant un mauvais comportement (par défaut : %u)</translation> </message> <message> <source>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</source> <translation>Extraire les informations de débogage (par défaut : %u, fournir &lt;category&gt; est optionnel)</translation> </message> <message> <source>Provide liquidity to Darksend by infrequently mixing coins on a continual basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, low fees)</source> <translation>Fournir des liquidités à Darksend en mélangeant occasionnellement mais régulièrement des pièces (0-100, par défaut : %u, 1=très fréquent, frais élevés, 100=très rare, frais bas)</translation> </message> <message> <source>Require high priority for relaying free or low-fee transactions (default:%u)</source> <translation>Priorité haute requise pour relayer les transactions à frais modiques ou nuls (par défaut : %u)</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file (default: %u)</source> <translation>Envoyer les informations de débogage/trace vers la console au lieu du fichier debug.log (par défaut: %u)</translation> </message> <message> <source>Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)</source> <translation>Définir la limite processeur définissant quand la génération est en fonction (-1 = illimité, par défaut : %d)</translation> </message> <message> <source>Show N confirmations for a successfully locked transaction (0-9999, default: %u)</source> <translation>Afficher N confirmations for une transaction verrouillée réussie (0-9999, default : %u)</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>Ce produit comprend des logiciels développés par le projet OpenSSL afin d'être utilisés dans la boîte à outils OpenSSL &lt;https://www.openssl.org/&gt;, un logiciel de chiffrement écrit par Eric Young et un logiciel UPnP développé par Thomas Bernard.</translation> </message> <message> <source>To use mtucicoind, or the -server option to mtucicoin-qt, you must set an rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=mtucicoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s "Mtucicoin Alert" admin@foo.com </source> <translation>Pour utiliser mtucicoind, ou le paramètre -server de mtucicoin-qt, vous devez définir un rpc mot de passe dans le fichier de configuration: %s Il est recommandé que vous utilisiez ce mot de passe aléatoire: rpcuser=mtucicoinrpc rpcpassword=%s (Vous ne devez pas vous souvenir de ce mot de passe) Le nom d'utilisateur et le mot de passe NE DOIVENT PAS être équivalent. Si le fichier n'existe pas, créé le avec les permissions de lecture uniquement pour le propriétaire. Il est recommandé de régler alertnotify pour que vous soyez averti des problèmes; Pour exemple: alertnotify=echo %%s | mail -s "Alerte Mtucicoin" admin@foo.com </translation> </message> <message> <source>Unable to locate enough funds for this transaction that are not equal 1000 MTUCICOIN.</source> <translation>Impossible de localiser suffisamment de fonds pour cette transaction qui ne sont pas égaux à 1000 MTUCICOIN.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> <translation>Utiliser un serveur proxy SOCKS5 séparé pour atteindre les pairs par les services cachés de Tor (par défaut : %s)</translation> </message> <message> <source>Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>Attention : -maxtxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous envoyez une transaction.</translation> </message> <message> <source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Mtucicoin Core will not work properly.</source> <translation>Attention : Veuillez vérifier que la date et l'heure de votre ordinateur sont justes ! Si votre horloge n'est pas à l'heure, Mtucicoin Core ne fonctionnera pas correctement.</translation> </message> <message> <source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source> <translation>Pairs en liste blanche qui se connectent via le masque réseau ou adresse IP. Peut être spécifié de multiples fois.</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>Pairs en liste blanche ne peuvent être bannis pour DoS et leurs transactions sont toujours relayées, même si elles sont déjà en mémoire, utile par ex. pour une passerelle</translation> </message> <message> <source>(9999 could be used only on mainnet)</source> <translation>(9999 n'est utilisable que sur mainnet)</translation> </message> <message> <source>(default: %s)</source> <translation>(par défaut: %s)</translation> </message> <message> <source>&lt;category&gt; can be: </source> <translation>&lt;category&gt; peut être : </translation> </message> <message> <source>Accept public REST requests (default: %u)</source> <translation>Accepter les requetes REST publiques (par défaut: %u)</translation> </message> <message> <source>Acceptable ciphers (default: %s)</source> <translation>Chiffrements acceptables (par défaut: %s)</translation> </message> <message> <source>Always query for peer addresses via DNS lookup (default: %u)</source> <translation>Toujours requêter via recherche DNS pour des adresses de pairs (par défaut: %u)</translation> </message> <message> <source>Cannot resolve -whitebind address: '%s'</source> <translation>Impossible de résoudre l'adresse -whitebind : « %s »</translation> </message> <message> <source>Connect through SOCKS5 proxy</source> <translation>Connexion à travers un serveur mandataire SOCKS5</translation> </message> <message> <source>Connect to KeePassHttp on port &lt;port&gt; (default: %u)</source> <translation>Connecter à KeePassHttp sur le port &lt;port&gt; (par défaut: %u)</translation> </message> <message> <source>Copyright (C) 2009-%i The Bitcoin Core Developers</source> <translation>Copyright (C) 2009-%i The Bitcoin Core Developers</translation> </message> <message> <source>Copyright (C) 2014-%i The Mtucicoin Core Developers</source> <translation>Copyright (C) 2014-%i The Mtucicoin Core Developers</translation> </message> <message> <source>Could not parse -rpcbind value %s as network address</source> <translation>Impossible d'analyser la valeur -rpcbind %s en tant qu'adresse réseau</translation> </message> <message> <source>Darksend is idle.</source> <translation>Darksend est inactif.</translation> </message> <message> <source>Darksend request complete:</source> <translation>Requête Darksend complète :</translation> </message> <message> <source>Darksend request incomplete:</source> <translation>Requête Darksend incomplète.</translation> </message> <message> <source>Disable safemode, override a real safe mode event (default: %u)</source> <translation>Désactiver le mode sans échec, passer outre un événement sans échec réel (par défaut : %u)</translation> </message> <message> <source>Enable the client to act as a masternode (0-1, default: %u)</source> <translation>Autoriser le client à agir en tant que masternode (0-1, par défaut : %u)</translation> </message> <message> <source>Error connecting to Masternode.</source> <translation>Erreur de connexion au masternode.</translation> </message> <message> <source>Error loading wallet.dat: Wallet requires newer version of Mtucicoin Core</source> <translation>Erreur au chargement de wallet.dat : le Portefeuille nécessite une nouvelle version de Mtucicoin Core</translation> </message> <message> <source>Error: A fatal internal error occured, see debug.log for details</source> <translation>Erreur: Une erreur interne fatale est survenue, voir debug.log pour les détails</translation> </message> <message> <source>Error: Can't select current denominated inputs</source> <translation>Erreur: Impossible de selectionner les entrées denommées</translation> </message> <message> <source>Error: Unsupported argument -tor found, use -onion.</source> <translation>Erreur: Paramètre -tor non supporté, utilisez -onion.</translation> </message> <message> <source>Fee (in MTUCICOIN/kB) to add to transactions you send (default: %s)</source> <translation>Frais (en MTUCICOIN/ko) à ajouter aux transactions que vous envoyez (par défaut: %s)</translation> </message> <message> <source>Finalizing transaction.</source> <translation>Finalisation de la transaction.</translation> </message> <message> <source>Force safe mode (default: %u)</source> <translation>Forcer le mode sans échec (par défaut : %u)</translation> </message> <message> <source>Found enough users, signing ( waiting %s )</source> <translation>Nombre suffisant d'utilisateurs trouvé, signature ( attente %s )</translation> </message> <message> <source>Found enough users, signing ...</source> <translation>Nombre suffisant d'utilisateurs trouvé, signature ...</translation> </message> <message> <source>Generate coins (default: %u)</source> <translation>Générer des pièces (défaut : %u)</translation> </message> <message> <source>How many blocks to check at startup (default: %u, 0 = all)</source> <translation>Nombre de blocs à vérifier au démarrage (par défaut : %u, 0 = tous)</translation> </message> <message> <source>Importing...</source> <translation>Importation...</translation> </message> <message> <source>Imports blocks from external blk000??.dat file</source> <translation>Importe des blocs depuis un fichier blk000??.dat externe</translation> </message> <message> <source>Include IP addresses in debug output (default: %u)</source> <translation>Inclure les adresses IP dans la sortie debug (par défaut: %u)</translation> </message> <message> <source>Incompatible mode.</source> <translation>Mode incompatible.</translation> </message> <message> <source>Incompatible version.</source> <translation>Version incompatible.</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Bloc de genèse incorrect ou introuvable. Mauvais répertoire de données pour le réseau ?</translation> </message> <message> <source>Information</source> <translation>Informations</translation> </message> <message> <source>Initialization sanity check failed. Mtucicoin Core is shutting down.</source> <translation>Les tests de cohérences lors de l'initialisation ont échoués. Mtucicoin Core est en cours de fermeture.</translation> </message> <message> <source>Input is not valid.</source> <translation>L'entrée est invalide.</translation> </message> <message> <source>InstantX options:</source> <translation>Options InstantX :</translation> </message> <message> <source>Insufficient funds.</source> <translation>Fonds insuffisants</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Adresse -onion invalide : « %s »</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Adresse -proxy invalide : « %s »</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s'</source> <translation>Montant invalide pour -maxtxfee=&lt;montant&gt; : « %s »</translation> </message> <message> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: '%s'</source> <translation>Montant invalide pour -minrelayfee=&lt;montant&gt; : « %s »</translation> </message> <message> <source>Invalid amount for -mintxfee=&lt;amount&gt;: '%s'</source> <translation>Montant invalide pour -mintxfee=&lt;montant&gt; : « %s »</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Montant invalide pour -paytxfee=&lt;montant&gt; : « %s » (minimum possible: %s)</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s'</source> <translation>Montant invalide pour -paytxfee=&lt;montant&gt; : « %s »</translation> </message> <message> <source>Last successful Darksend action was too recent.</source> <translation>La dernière action Darksend réussie est trop récente.</translation> </message> <message> <source>Limit size of signature cache to &lt;n&gt; entries (default: %u)</source> <translation>Limiter la taille du cache des signatures à &lt;n&gt; entrées (par défaut : %u)</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Écouter les connexions JSON-RPC sur &lt;port&gt; (par défaut : %u ou tesnet : %u)</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Écouter les connexions sur &lt;port&gt; (par défaut: %u ou testnet: %u)</translation> </message> <message> <source>Loading budget cache...</source> <translation>Chargement du cache de budget...</translation> </message> <message> <source>Loading masternode cache...</source> <translation>Chargement du cache de masternode...</translation> </message> <message> <source>Loading masternode payment cache...</source> <translation>Chargement du cache de paiement masternode...</translation> </message> <message> <source>Lock is already in place.</source> <translation>Verrou déjà en place.</translation> </message> <message> <source>Lock masternodes from masternode configuration file (default: %u)</source> <translation>Vérouiller les masternodes depuis le fichier de configuration masternode (par défaut : %u)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: %u)</source> <translation>Garder au plus &lt;n&gt; connexions avec les pairs (par défaut : %u)</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Tampon maximal de réception par connexion, &lt;n&gt;*1000 octets (par défaut : %u)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Tampon maximal d'envoi par connexion », &lt;n&gt;*1000 octets (par défaut : %u)</translation> </message> <message> <source>Mixing in progress...</source> <translation>Mélange en cours...</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>Un port doit être spécifié avec -whitebind: '%s'</translation> </message> <message> <source>No Masternodes detected.</source> <translation>Aucun Masternode détecté.</translation> </message> <message> <source>No compatible Masternode found.</source> <translation>Aucun Masternode compatible trouvé.</translation> </message> <message> <source>Not in the Masternode list.</source> <translation>Absent de la liste des Masternodes.</translation> </message> <message> <source>Number of automatic wallet backups (default: 10)</source> <translation>Nombre de sauvegarde automatique de portefeuille (par défaut : 10)</translation> </message> <message> <source>Only accept block chain matching built-in checkpoints (default: %u)</source> <translation>N'accepter qu'une chaîne de blocs correspondant aux points de vérification intégrés (par défaut : %u)</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <translation>Se connecter uniquement aux nœuds du réseau &lt;net&gt; (IPv4, IPv6 ou onion)</translation> </message> <message> <source>Prepend debug output with timestamp (default: %u)</source> <translation>Ajouter l'horodatage au début de la sortie de débogage (par défaut : %u)</translation> </message> <message> <source>Run a thread to flush wallet periodically (default: %u)</source> <translation>Exécuter une tâche pour purger le portefeuille périodiquement (par défaut : %u) </translation> </message> <message> <source>Send trace/debug info to debug.log file (default: %u)</source> <translation>Envoyer les informations de débogage/trace au fichier debug.log (par défaut: %u)</translation> </message> <message> <source>Send transactions as zero-fee transactions if possible (default: %u)</source> <translation>N'envoyer que des transactions sans frais si possible (par défaut : %u)</translation> </message> <message> <source>Server certificate file (default: %s)</source> <translation>Fichier de certification du serveur (par défaut : %s)</translation> </message> <message> <source>Server private key (default: %s)</source> <translation>Clef privée du serveur (par défaut : %s)</translation> </message> <message> <source>Set external address:port to get to this masternode (example: %s)</source> <translation>Définir une adresse:port externe pour accéder à ce masternode (exemple : %s)</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: %u)</source> <translation>Définir la taille de la réserve de clefs à &lt;n&gt; (par défaut : %u)</translation> </message> <message> <source>Set minimum block size in bytes (default: %u)</source> <translation>Définir la taille de bloc minimale en octets (par défaut : %u)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: %d)</source> <translation>Définir le nombre de fils d’exécution pour desservir les appels RPC (par défaut : %d)</translation> </message> <message> <source>Sets the DB_PRIVATE flag in the wallet db environment (default: %u)</source> <translation>Définit le drapeau DB_PRIVATE dans l'environnement de la BD du portefeuille (par défaut : %u)</translation> </message> <message> <source>Signing timed out.</source> <translation>Signature expirée.</translation> </message> <message> <source>Specify configuration file (default: %s)</source> <translation>Définir le fichier de configuration (par défaut : %s)</translation> </message> <message> <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> <translation>Spécifier le délai d'expiration de la connexion en millisecondes (minimum : 1, par défaut : %d)</translation> </message> <message> <source>Specify masternode configuration file (default: %s)</source> <translation>Définir le fichier de configuration du masternode (par défaut : %s)</translation> </message> <message> <source>Specify pid file (default: %s)</source> <translation>Définir le fichier pid (défaut : %s)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: %u)</source> <translation>Dépenser la monnaie non confirmée lors de l'envoi de transactions (par défaut : %u)</translation> </message> <message> <source>Stop running after importing blocks from disk (default: %u)</source> <translation>Arrêter après l'importation des blocs du disque (par défaut : %u)</translation> </message> <message> <source>Submitted following entries to masternode: %u / %d</source> <translation>Les entrées suivantes ont été envoyées au masternode: %u / %d</translation> </message> <message> <source>Submitted to masternode, waiting for more entries ( %u / %d ) %s</source> <translation>Envoyé au masternode, en attente d'entrées supplémentaires ( %u / %d ) %s</translation> </message> <message> <source>Submitted to masternode, waiting in queue %s</source> <translation>Soumis au masternode, dans la file d'attente %s</translation> </message> <message> <source>Synchronization failed</source> <translation>La synchronisation a échouée</translation> </message> <message> <source>Synchronization finished</source> <translation>La synchronisation est terminée</translation> </message> <message> <source>Synchronizing budgets...</source> <translation>Synchronisation des budgets...</translation> </message> <message> <source>Synchronizing masternode winners...</source> <translation>Synchronisation des masternodes vainqueurs...</translation> </message> <message> <source>Synchronizing masternodes...</source> <translation>Synchronisation des masternodes...</translation> </message> <message> <source>Synchronizing sporks...</source> <translation>Synchronisation des sporks...</translation> </message> <message> <source>This is not a Masternode.</source> <translation>Ceci n'est pas un masternode.</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: %u)</source> <translation>Seuil de déconnexion des pairs présentant un mauvais comportement (par défaut : %u)</translation> </message> <message> <source>Use KeePass 2 integration using KeePassHttp plugin (default: %u)</source> <translation>Utiliser l'intégration KeePass 2 en utilisant le greffon KeePassHttp (par défaut : %u)</translation> </message> <message> <source>Use N separate masternodes to anonymize funds (2-8, default: %u)</source> <translation>Utiliser N masternodes différents pour anonymiser les fonds (2-8, par défaut : %u)</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Utiliser l'UPnP pour mapper le port d'écoute (par défaut : %u)</translation> </message> <message> <source>Wallet needed to be rewritten: restart Mtucicoin Core to complete</source> <translation>Le portefeuille devait être réécrit : redémarrer Mtucicoin Core pour terminer l'opération.</translation> </message> <message> <source>Warning: Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation>Attention : l'argument obsolète -benchmark a été ignoré, utiliser -debug=bench</translation> </message> <message> <source>Warning: Unsupported argument -debugnet ignored, use -debug=net.</source> <translation>Attention : l'argument obsolète -debugnet a été ignoré, utiliser -debug=net</translation> </message> <message> <source>Will retry...</source> <translation>Va réessayer ...</translation> </message> <message> <source>Invalid masternodeprivkey. Please see documenation.</source> <translation>masternodeprivkey invalide. Veuillez vous référer à la documentation.</translation> </message> <message> <source>(must be 9999 for mainnet)</source> <translation>(doit être 9999 pour mainnet)</translation> </message> <message> <source>Can't find random Masternode.</source> <translation>Masternode aléatoire introuvable.</translation> </message> <message> <source>Can't mix while sync in progress.</source> <translation>Ne peux pas mélanger pendant la synchronisation.</translation> </message> <message> <source>Could not parse masternode.conf</source> <translation>Impossible d'analyser masternode.conf</translation> </message> <message> <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Masque de réseau inconnu spécifié sur -whitelist : « %s »</translation> </message> <message> <source>Invalid port detected in masternode.conf</source> <translation>Port non valide détecté dans masternode.conf</translation> </message> <message> <source>Invalid private key.</source> <translation>Clé privée invalide.</translation> </message> <message> <source>Invalid script detected.</source> <translation>Script invalide détecté.</translation> </message> <message> <source>KeePassHttp id for the established association</source> <translation>Id KeePassHttp pour l'association établie</translation> </message> <message> <source>KeePassHttp key for AES encrypted communication with KeePass</source> <translation>Clé KeePassHttp pour la communication chiffrée AES avec KeePass</translation> </message> <message> <source>Keep N MTUCICOIN anonymized (default: %u)</source> <translation>Maintenir N mtucicoin anonymisé en permanence (défaut: %u)</translation> </message> <message> <source>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</source> <translation>Garder au plus &lt;n&gt; transactions sans connexion en mémoire (par défaut : %u)</translation> </message> <message> <source>Last Darksend was too recent.</source> <translation>Le dernier Darksend est trop récent.</translation> </message> <message> <source>Line: %d</source> <translation>Ligne: %d</translation> </message> <message> <source>Loading addresses...</source> <translation>Chargement des adresses...</translation> </message> <message> <source>Loading block index...</source> <translation>Chargement de l’index des blocs...</translation> </message> <message> <source>Loading wallet... (%3.2f %%)</source> <translation>Chargement du portefeuille... (%3.2f %%)</translation> </message> <message> <source>Loading wallet...</source> <translation>Chargement du portefeuille...</translation> </message> <message> <source>Masternode options:</source> <translation>Options Masternode :</translation> </message> <message> <source>Masternode queue is full.</source> <translation>La file d'attente du masternode est pleine.</translation> </message> <message> <source>Masternode:</source> <translation>Masternode :</translation> </message> <message> <source>Missing input transaction information.</source> <translation>Informations de transaction entrante manquantes.</translation> </message> <message> <source>No funds detected in need of denominating.</source> <translation>Aucuns fonds détectés nécessitant une dénomination.</translation> </message> <message> <source>No matching denominations found for mixing.</source> <translation>Pas de dénominations équivalentes trouvées pour le mélange.</translation> </message> <message> <source>Node relay options:</source> <translation>Options de noeud de relais:</translation> </message> <message> <source>Non-standard public key detected.</source> <translation>Clé publique non standard détectée.</translation> </message> <message> <source>Not compatible with existing transactions.</source> <translation>Non compatible avec les transactions existantes.</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Pas assez de descripteurs de fichiers de disponibles.</translation> </message> <message> <source>Options:</source> <translation>Options :</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Mot de passe pour les connexions JSON-RPC</translation> </message> <message> <source>RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Options RPC SSL : (voir le wiki Bitcoin pour les instructions de configuration de SSL)</translation> </message> <message> <source>RPC server options:</source> <translation>Options du serveur RPC :</translation> </message> <message> <source>RPC support for HTTP persistent connections (default: %d)</source> <translation>Support RPC pour connections HTTP persistantes (par défaut : %d)</translation> </message> <message> <source>Randomly drop 1 of every &lt;n&gt; network messages</source> <translation>Abandonner aléatoirement 1 message du réseau sur &lt;n&gt;</translation> </message> <message> <source>Randomly fuzz 1 of every &lt;n&gt; network messages</source> <translation>Tester aléatoirement 1 message du réseau sur &lt;n&gt;</translation> </message> <message> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruire l'index de la chaîne de blocs à partir des fichiers blk000??.dat courants</translation> </message> <message> <source>Receive and display P2P network alerts (default: %u)</source> <translation>Recevoir et afficher les alertes réseau P2P (par défaut : %u)</translation> </message> <message> <source>Relay and mine data carrier transactions (default: %u)</source> <translation>Relayer et miner les transactions de support de données (par défaut : %u)</translation> </message> <message> <source>Relay non-P2SH multisig (default: %u)</source> <translation>Relayer les multisig non-P2SH (par défaut : %u)</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions</source> <translation>Réanalyser la chaîne de blocs pour les transactions de portefeuille manquantes</translation> </message> <message> <source>Rescanning...</source> <translation>Nouvelle analyse...</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation> </message> <message> <source>Session not complete!</source> <translation>Session incomplète!</translation> </message> <message> <source>Session timed out.</source> <translation>Session expirée.</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Définir la taille du cache de la base de données en mégaoctets (%d to %d, default: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Définir la taille minimale de bloc en octets (par défaut : %d)</translation> </message> <message> <source>Set the masternode private key</source> <translation>Définir la clé privée du masternode</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Montrer toutes les options de débogage (utilisation : --help --help-debug)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 lorsque -debug n'est pas présent)</translation> </message> <message> <source>Signing failed.</source> <translation>La signature a échoué.</translation> </message> <message> <source>Signing transaction failed</source> <translation>La signature de la transaction a échoué</translation> </message> <message> <source>Specify data directory</source> <translation>Spécifier le répertoire de données</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Spécifiez le fichier de portefeuille (dans le répertoire de données)</translation> </message> <message> <source>Specify your own public address</source> <translation>Spécifier votre propre adresse publique</translation> </message> <message> <source>Synchronization pending...</source> <translation>Synchronisation en suspens...</translation> </message> <message> <source>This help message</source> <translation>Ce message d'aide</translation> </message> <message> <source>This is experimental software.</source> <translation>Ceci est un logiciel expérimental.</translation> </message> <message> <source>This is intended for regression testing tools and app development.</source> <translation>Ceci est à l'intention des outils de test de régression et du développement applicatif.</translation> </message> <message> <source>Transaction amount too small</source> <translation>Montant de la transaction trop bas</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Les montants de transaction doivent être positifs</translation> </message> <message> <source>Transaction created successfully.</source> <translation>Transaction créée avec succès.</translation> </message> <message> <source>Transaction fees are too high.</source> <translation>Les frais de transaction sont trop élevés.</translation> </message> <message> <source>Transaction not valid.</source> <translation>Transaction invalide.</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>La transaction est trop volumineuse pour les règles de frais en vigueur</translation> </message> <message> <source>Transaction too large</source> <translation>Transaction trop volumineuse</translation> </message> <message> <source>Transmitting final transaction.</source> <translation>Transmission de la transaction finale.</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>Impossible de se lier à %s sur cet ordinateur (erreur bind retournée %s)</translation> </message> <message> <source>Unable to sign spork message, wrong key?</source> <translation>Impossible de signer le message spork, mauvaise clé?</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Réseau inconnu spécifié sur -onlynet : « %s »</translation> </message> <message> <source>Unknown state: id = %u</source> <translation>État inconnu: id = %u</translation> </message> <message> <source>Upgrade wallet to latest format</source> <translation>Mettre à niveau le portefeuille vers le format le plus récent</translation> </message> <message> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utiliser OpenSSL (https) pour les connexions JSON-RPC</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Utiliser l'UPnP pour mapper le port d'écoute (par défaut : 1 lors de l'écoute)</translation> </message> <message> <source>Use the test network</source> <translation>Utiliser le réseau de test</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Nom d'utilisateur pour les connexions JSON-RPC</translation> </message> <message> <source>Value more than Darksend pool maximum allows.</source> <translation>Valeur supérieure au maximum autorisé par le pool.</translation> </message> <message> <source>Verifying blocks...</source> <translation>Vérification des blocs en cours...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Vérification du portefeuille en cours...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>Le portefeuille %s réside en dehors du répertoire de données %s</translation> </message> <message> <source>Wallet is locked.</source> <translation>Le Portefeuille est verrouillé.</translation> </message> <message> <source>Wallet options:</source> <translation>Options du portefeuille :</translation> </message> <message> <source>Wallet window title</source> <translation>Titre de la fenêtre du portefeuille</translation> </message> <message> <source>Warning</source> <translation>Avertissement</translation> </message> <message> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Avertissement : cette version est obsolète, une mise à niveau est nécessaire !</translation> </message> <message> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation>Vous devez reconstruire la base de données en utilisant -reindex afin de modifier -txindex</translation> </message> <message> <source>Your entries added successfully.</source> <translation>Vos entrées ajoutées avec succès.</translation> </message> <message> <source>Your transaction was accepted into the pool!</source> <translation>Votre transaction a été acceptée dans la pool!</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Supprimer toutes les transactions du portefeuille...</translation> </message> <message> <source>on startup</source> <translation>au démarrage</translation> </message> <message> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrompu, la récupération a échoué</translation> </message> </context> </TS>
freelion93/mtucicoin
src/qt/locale/mtucicoin_fr.ts
TypeScript
mit
197,952
'use strict'; angular.module('<%= name %>') .service('<%= serviceName %>', function ($q, $http) { // A private cache key. var cache = {}; // Update broadcast name. var broadcastUpdateEventName = '<%= serviceName %>Change'; /** * Return the promise with the collection, from cache or the server. * * @returns {*} */ this.get = function() { if (cache) { return $q.when(cache.data); } return getDataFromBackend(); }; /** * Return promise with the collection from the server. * * @returns {$q.promise} */ function getDataFromBackend() { var deferred = $q.defer(); var url = ''; $http({ method: 'GET', url: url, params: params, transformResponse: prepareDataForLeafletMarkers }).success(function(response) { setCache(response); deferred.resolve(response); }); return deferred.promise; } /** * Save cache, and broadcast an event, because data changed. * * @param data * Object with the data to cache. */ var setCache = function(data) { // Cache data by company ID. cache = { data: data, timestamp: new Date() }; // Clear cache in 60 seconds. $timeout(function() { if (cache.data && cache.data[cacheId]) { cache.data[cacheId] = null; } }, 60000); // Broadcast a change event. $rootScope.$broadcast(broadcastUpdateEventName); }; /** * Convert the response to a collection. * * @param response * The response from the $http. * * @returns {*} * The Collection requested. */ function prepareDataForLeafletMarkers(response) { var collection; // Convert response serialized to an object. collection = angular.fromJson(reponse).data; return collection; } });
ceoaliongroo/generator-angular-element
app/templates/app/basic/service.js
JavaScript
mit
1,961
'use strict'; angular.module('myApp.contact', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/contact', { templateUrl: 'app/view/contact.html', controller: 'contactCtrl' }); }]) .controller('contactCtrl',['$scope','$http', function($scope, $http) { $scope.result = 'hidden' $scope.resultMessage; $scope.formData; //formData is an object holding the name, email, subject, and message $scope.submitButtonDisabled = false; $scope.submitted = false; //used so that form errors are shown only after the form has been submitted $scope.submit = function(contactform) { $scope.submitted = true; $scope.submitButtonDisabled = true; if (contactform.$valid) { $http({ method : 'POST', url : 'http://localhost:8000/contact-form.php', data : $.param($scope.formData), //param method from jQuery headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload) }).success(function(data){ console.log(data); if (data) { //success comes from the return json object $scope.submitButtonDisabled = true; $scope.resultMessage = data; $scope.result='bg-success'; } else { $scope.submitButtonDisabled = false; $scope.resultMessage = data; $scope.result='bg-danger'; } }); } else { $scope.submitButtonDisabled = false; $scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.'; $scope.result='bg-danger'; } }; var myCenter=new google.maps.LatLng(42.656021, -71.330044); var mapProp = { center:myCenter, zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map=new google.maps.Map(document.getElementById("map"),mapProp); var marker=new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"203 University avenue Lowell, MA, 01854" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); google.maps.event.addDomListener(window, 'load'); }]);
ananddharne/ananddharne.github.io
app/assets/javascripts/crontollers/contact.js
JavaScript
mit
2,961
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using HPMSdk; using Hansoft.ObjectWrapper; using Hansoft.ObjectWrapper.CustomColumnValues; using Hansoft.Jean.Behavior; namespace Hansoft.Jean.Behavior.TrackLastStatusChangeBehavior { public class TrackLastStatusChangeBehavior : AbstractBehavior { string projectName; bool initializationOK = false; string trackingColumnName; string trackedColumnName; string viewName; EHPMReportViewType viewType; List<Project> projects; private List<ProjectView> projectViews; bool inverted = false; HPMProjectCustomColumnsColumn trackingColumn; HPMProjectCustomColumnsColumn trackedColumn; string title; public TrackLastStatusChangeBehavior(XmlElement configuration) : base(configuration) { projectName = GetParameter("HansoftProject"); string invert = GetParameter("InvertedMatch"); if (invert != null) inverted = invert.ToLower().Equals("yes"); trackingColumnName = GetParameter("TrackingColumn"); trackedColumnName = GetParameter("TrackedColumn"); viewName = GetParameter("View"); viewType = GetViewType(viewName); title = "TrackLastStatusChangeBehavior: " + configuration.InnerText; } public override void Initialize() { projects = new List<Project>(); projectViews = new List<ProjectView>(); initializationOK = false; projects = HPMUtilities.FindProjects(projectName, inverted); if (projects.Count == 0) throw new ArgumentException("Could not find any matching project:" + projectName); foreach (Project project in projects) { ProjectView projectView; if (viewType == EHPMReportViewType.AgileBacklog) projectView = project.ProductBacklog; else if (viewType == EHPMReportViewType.AllBugsInProject) projectView = project.BugTracker; else projectView = project.Schedule; projectViews.Add(projectView); } trackedColumn = projectViews[0].GetCustomColumn(trackedColumnName); if (trackedColumn == null) throw new ArgumentException("Could not find custom column in view " + viewName + " " + trackedColumnName); trackingColumn = projectViews[0].GetCustomColumn(trackingColumnName); if (trackingColumn == null) throw new ArgumentException("Could not find custom column in view " + viewName + " " + trackingColumnName); initializationOK = true; DoUpdateFromHistory(); } public override string Title { get { return title; } } // TODO: Subject to refactoting private EHPMReportViewType GetViewType(string viewType) { switch (viewType) { case ("Agile"): return EHPMReportViewType.AgileMainProject; case ("Scheduled"): return EHPMReportViewType.ScheduleMainProject; case ("Bugs"): return EHPMReportViewType.AllBugsInProject; case ("Backlog"): return EHPMReportViewType.AgileBacklog; default: throw new ArgumentException("Unsupported View Type: " + viewType); } } private void DoUpdateFromHistory() { foreach (ProjectView projectView in projectViews) { foreach (Task task in projectView.DeepLeaves) DoUpdateFromHistory(task); } } private void DoUpdateFromHistory(Task task) { HPMDataHistoryGetHistoryParameters pars = new HPMDataHistoryGetHistoryParameters(); pars.m_DataID = task.UniqueTaskID; pars.m_FieldID = EHPMStatisticsField.NoStatistics; pars.m_FieldData = 0; pars.m_DataIdent0 = EHPMStatisticsScope.NoStatisticsScope; pars.m_DataIdent1 = 0; HPMDataHistory history = SessionManager.Session.DataHistoryGetHistory(pars); if (history != null) DoUpdateFromHistory(task, history); } private void DoUpdateFromHistory(Task task, HPMDataHistory history) { // Ensure that we get the custom column of the right project HPMProjectCustomColumnsColumn actualCustomColumn = task.ProjectView.GetCustomColumn(trackingColumn.m_Name); DateTimeValue storedValue = (DateTimeValue)task.GetCustomColumnValue(actualCustomColumn); // ToInt64 will return the value as microseconds since 1970 Jan 1 ulong storedHpmTime = storedValue.ToHpmDateTime(); if (history.m_Latests.m_Time > storedHpmTime) { foreach (HPMDataHistoryEntry entry in history.m_HistoryEntries) { // Check if it is the status field if (entry.m_FieldID == 15) { if (entry.m_Time > storedHpmTime) { storedHpmTime = entry.m_Time; task.SetCustomColumnValue(trackingColumn, DateTimeValue.FromHpmDateTime(task, actualCustomColumn, storedHpmTime)); } } } } } public override void OnTaskChangeCustomColumnData(TaskChangeCustomColumnDataEventArgs e) { if (initializationOK) { if (e.Data.m_ColumnHash == trackedColumn.m_Hash) { Task task = Task.GetTask(e.Data.m_TaskID); if (projects.Contains(task.Project) && projectViews.Contains(task.ProjectView)) task.SetCustomColumnValue(trackingColumn, DateTimeValue.FromHpmDateTime(task, trackingColumn, HPMUtilities.HPMNow())); } } } public override void OnDataHistoryReceived(DataHistoryReceivedEventArgs e) { if (initializationOK) { if (SessionManager.Session.UtilIsIDTask(e.Data.m_UniqueIdentifier) || SessionManager.Session.UtilIsIDTaskRef(e.Data.m_UniqueIdentifier)) { Task task = Task.GetTask(e.Data.m_UniqueIdentifier); DoUpdateFromHistory(task); } } } } }
Hansoft/Hansoft-Jean-TrackLastStatusChangeBehavior
TrackLastStatusChangeBehavior.cs
C#
mit
6,789
long long MUL(long long a, long long b, long long MOD) { long long res = 1; while (b) { if (b & 1) { res = (res * a) % MOD; } a = (a * a) % MOD; b >>= 1; } return res; } long long MUL(long long a, long long b, long long MOD) { long long res = 0; while (b) { if (b & 1) { res = (res + a) % MOD; } a = (a + a) % MOD; b >>= 1; } return res; }
Hyyyyyyyyyy/acm
Ccccccccccc/快速幂快速乘.cpp
C++
mit
379
'use strict'; angular.module('f1feeder.version.version-directive', []) .directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
jkotrba/f1feeder
app/components/version/version-directive.js
JavaScript
mit
202
'use strict'; /** * Module Dependencies */ var gulp = require('gulp'); var sass = require('gulp-sass'); var app = require('./app.js'); /** * Config */ var PUBLIC = __dirname + '/public'; var ASSETS = PUBLIC + '/assets'; /** * Compiling */ gulp.task('sass', function(){ gulp.src(ASSETS + '/styles/sass/app.scss') .pipe(sass()) .pipe(gulp.dest(ASSETS + '/styles/css')); }); // lol gulp.task('piss', ['sass'], function() { app.init(); }); // Default gulp.task('default', ['piss']);
dictions/post
gulpfile.js
JavaScript
mit
505
#!usr/bin/python2.7 # coding: utf-8 # date: 16-wrzesień-2016 # autor: B.Kozak # Simple script giving length of sequences from fasta file import Bio from Bio import SeqIO import sys import os.path filename = sys.argv[-1] outname = filename.split('.') outname1 = '.'.join([outname[0], 'txt']) FastaFile = open(filename, 'rU') f = open(outname1, 'w') for rec in SeqIO.parse(FastaFile, 'fasta'): name = rec.id seq = rec.seq seqLen = len(rec) print name, seqLen f.write("%s\t" % name) f.write("%s\n" % seqLen) f.close() print 'Done'
bartosz-kozak/Sample-script
python/seq_len.py
Python
mit
544
class FeedsController < ApplicationController before_action :require_logged_in! LIMIT = 20 def show @feed_tweets = current_user.feed_tweets(LIMIT, params[:max_created_at]).includes(:user) respond_to do |format| format.html { render :show } format.json { render :show } end end end
akanshmurthy/codelearnings
appacademy/w6d5/app/controllers/feeds_controller.rb
Ruby
mit
321
import {waitFor} from './wait-for' const isRemoved = result => !result || (Array.isArray(result) && !result.length) // Check if the element is not present. // As the name implies, waitForElementToBeRemoved should check `present` --> `removed` function initialCheck(elements) { if (isRemoved(elements)) { throw new Error( 'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.', ) } } async function waitForElementToBeRemoved(callback, options) { // created here so we get a nice stacktrace const timeoutError = new Error('Timed out in waitForElementToBeRemoved.') if (typeof callback !== 'function') { initialCheck(callback) const elements = Array.isArray(callback) ? callback : [callback] const getRemainingElements = elements.map(element => { let parent = element.parentElement if (parent === null) return () => null while (parent.parentElement) parent = parent.parentElement return () => (parent.contains(element) ? element : null) }) callback = () => getRemainingElements.map(c => c()).filter(Boolean) } initialCheck(callback()) return waitFor(() => { let result try { result = callback() } catch (error) { if (error.name === 'TestingLibraryElementError') { return undefined } throw error } if (!isRemoved(result)) { throw timeoutError } return undefined }, options) } export {waitForElementToBeRemoved} /* eslint require-await: "off" */
testing-library/dom-testing-library
src/wait-for-element-to-be-removed.js
JavaScript
mit
1,602
""" [2015-12-28] Challenge #247 [Easy] Secret Santa https://www.reddit.com/r/dailyprogrammer/comments/3yiy2d/20151228_challenge_247_easy_secret_santa/ # Description Every December my friends do a "Secret Santa" - the traditional gift exchange where everybody is randomly assigned to give a gift to a friend. To make things exciting, the matching is all random (you cannot pick your gift recipient) and nobody knows who got assigned to who until the day when the gifts are exchanged - hence, the "secret" in the name. Since we're a big group with many couples and families, often a husband gets his wife as secret santa (or vice-versa), or a father is assigned to one of his children. This creates a series of issues: * If you have a younger kid and he/she is assigned to you, you might end up paying for your own gift and ruining the surprise. * When your significant other asks "who did you get for Secret Santa", you have to lie, hide gifts, etc. * The inevitable "this game is rigged!" commentary on the day of revelation. To fix this, you must design a program that randomly assigns the Secret Santa gift exchange, but *prevents people from the same family to be assigned to each other*. # Input A list of all Secret Santa participants. People who belong to the same family are listed in the same line separated by spaces. Thus, "Jeff Jerry" represents two people, Jeff and Jerry, who are family and should not be assigned to eachother. Joe Jeff Jerry Johnson # Output The list of Secret Santa assignments. As Secret Santa is a random assignment, output may vary. Joe -> Jeff Johnson -> Jerry Jerry -> Joe Jeff -> Johnson But **not** `Jeff -> Jerry` or `Jerry -> Jeff`! # Challenge Input Sean Winnie Brian Amy Samir Joe Bethany Bruno Anna Matthew Lucas Gabriel Martha Philip Andre Danielle Leo Cinthia Paula Mary Jane Anderson Priscilla Regis Julianna Arthur Mark Marina Alex Andrea # Bonus The assignment list must avoid "closed loops" where smaller subgroups get assigned to each other, breaking the overall loop. Joe -> Jeff Jeff -> Joe # Closed loop of 2 Jerry -> Johnson Johnson -> Jerry # Closed loop of 2 # Challenge Credit Thanks to /u/oprimo for his idea in /r/dailyprogrammer_ideas """ def main(): pass if __name__ == "__main__": main()
DayGitH/Python-Challenges
DailyProgrammer/DP20151228A.py
Python
mit
2,377
using System; using LuaInterface; using System.Collections.Generic; using System.Runtime.Serialization; using System.Collections; public class System_Collections_Generic_DictionaryWrap { public static void Register(LuaState L) { L.BeginClass(typeof(Dictionary<,>), typeof(System.Object), "Dictionary"); L.RegFunction("get_Item", get_Item); L.RegFunction("set_Item", set_Item); L.RegFunction(".geti", _geti); L.RegFunction(".seti", _seti); L.RegFunction("Add", Add); L.RegFunction("Clear", Clear); L.RegFunction("ContainsKey", ContainsKey); L.RegFunction("ContainsValue", ContainsValue); L.RegFunction("GetObjectData", GetObjectData); L.RegFunction("OnDeserialization", OnDeserialization); L.RegFunction("Remove", Remove); L.RegFunction("TryGetValue", TryGetValue); L.RegFunction("GetEnumerator", GetEnumerator); L.RegVar("this", _this, null); L.RegFunction("__tostring", ToLua.op_ToString); L.RegVar("Count", get_Count, null); L.RegVar("Comparer", get_Comparer, null); L.RegVar("Keys", get_Keys, null); L.RegVar("Values", get_Values, null); L.EndClass(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _get_this(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object o = LuaMethodCache.CallSingleMethod("get_Item", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _set_this(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type kt, vt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt, out vt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object arg1 = ToLua.CheckVarObject(L, 2, vt); LuaMethodCache.CallSingleMethod("set_Item", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _this(IntPtr L) { try { LuaDLL.lua_pushvalue(L, 1); LuaDLL.tolua_bindthis(L, _get_this, _set_this); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Item(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object o = LuaMethodCache.CallSingleMethod("get_Item", obj, arg0); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int set_Item(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type kt, vt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt, out vt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object arg1 = ToLua.CheckVarObject(L, 2, vt); LuaMethodCache.CallSingleMethod("set_Item", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _geti(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt = null; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); if (kt != typeof(int)) { LuaDLL.lua_pushnil(L); } else { object arg0 = ToLua.CheckVarObject(L, 2, kt); object o = LuaMethodCache.CallSingleMethod("get_Item", obj, arg0); ToLua.Push(L, o); } return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _seti(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type kt, vt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt, out vt); if (kt == typeof(int)) { object arg0 = ToLua.CheckVarObject(L, 2, kt); object arg1 = ToLua.CheckVarObject(L, 2, vt); LuaMethodCache.CallSingleMethod("set_Item", obj, arg0, arg1); } return 0; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Add(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type kt, vt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt, out vt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object arg1 = ToLua.CheckVarObject(L, 2, vt); LuaMethodCache.CallSingleMethod("Add", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Clear(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>)); LuaMethodCache.CallSingleMethod("Clear", obj); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ContainsKey(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); object arg0 = ToLua.CheckVarObject(L, 2, kt); bool o = (bool)LuaMethodCache.CallSingleMethod("ContainsKey", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int ContainsValue(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt, vt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt, out vt); object arg0 = ToLua.CheckVarObject(L, 2, vt); bool o = (bool)LuaMethodCache.CallSingleMethod("ContainsValue", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int GetObjectData(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>)); SerializationInfo arg0 = (SerializationInfo)ToLua.CheckObject(L, 2, typeof(SerializationInfo)); StreamingContext arg1 = (StreamingContext)ToLua.CheckObject(L, 3, typeof(StreamingContext)); LuaMethodCache.CallSingleMethod("GetObjectData", obj, arg0, arg1); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int OnDeserialization(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>)); object arg0 = ToLua.ToVarObject(L, 2); LuaMethodCache.CallSingleMethod("OnDeserialization", obj, arg0); return 0; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int Remove(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Type kt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); object arg0 = ToLua.CheckVarObject(L, 2, kt); bool o = (bool)LuaMethodCache.CallSingleMethod("Remove", obj, arg0); LuaDLL.lua_pushboolean(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int TryGetValue(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Type kt; object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>), out kt); object arg0 = ToLua.CheckVarObject(L, 2, kt); object arg1 = null; object[] args = new object[] { arg0, arg1 }; bool o = (bool)LuaMethodCache.CallSingleMethod("TryGetValue", obj, args); LuaDLL.lua_pushboolean(L, o); ToLua.Push(L, args[1]); return 2; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int GetEnumerator(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); object obj = ToLua.CheckGenericObject(L, 1, typeof(Dictionary<,>)); IEnumerator o = (IEnumerator)LuaMethodCache.CallSingleMethod("GetEnumerator", obj); ToLua.Push(L, o); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Count(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); int ret = (int)LuaMethodCache.CallSingleMethod("get_Count", o); LuaDLL.lua_pushinteger(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Count on a nil value" : e.Message); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Comparer(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); object ret = LuaMethodCache.CallSingleMethod("get_Comparer", o); ToLua.PushObject(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Comparer on a nil value" : e.Message); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Keys(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); object ret = LuaMethodCache.CallSingleMethod("get_Keys", o); ToLua.PushObject(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Keys on a nil value" : e.Message); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int get_Values(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); object ret = LuaMethodCache.CallSingleMethod("get_Values", o); ToLua.PushObject(L, ret); return 1; } catch(Exception e) { return LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Values on a nil value" : e.Message); } } }
joey1258/ToluaContainer
Assets/ToLua/BaseType/System_Collections_Generic_DictionaryWrap.cs
C#
mit
11,211
module Elastictastic module ParentChild extend ActiveSupport::Concern module ClassMethods attr_reader :parent_association def belongs_to(parent_name, options = {}) @parent_association = Association.new(parent_name, options) module_eval(<<-RUBY, __FILE__, __LINE__+1) def #{parent_name} _parent end RUBY end def has_many(children_name, options = {}) children_name = children_name.to_s child_associations[children_name] = Association.new(children_name, options) module_eval(<<-RUBY, __FILE__, __LINE__ + 1) def #{children_name} read_child(#{children_name.inspect}) end RUBY end def child_association(name) child_associations[name.to_s] end def child_associations @_child_associations ||= {} end def mapping super.tap do |mapping| mapping[type]['_parent'] = { 'type' => @parent_association.clazz.type } if @parent_association end end end def initialize(attributes = {}) super @_children = Hash.new do |hash, child_association_name| hash[child_association_name] = Elastictastic::ChildCollectionProxy.new( self.class.child_association(child_association_name.to_s), self ) end end def elasticsearch_doc=(doc) @_parent_id = doc.delete('_parent') super end def _parent #:nodoc: return @_parent if defined? @_parent @_parent = if @_parent_id self.class.parent_association.clazz.in_index(index).find(@_parent_id) end #TODO - here's a piece of debugging to fix a problem where we get weird parents. remove after fixing if @_parent && !@_parent.respond_to?(:id) raise ArgumentError.new("Bad parent loaded from id #{@_parent_id} is a #{@_parent.class.name}.") end @_parent end def _parent_id #:nodoc: if @_parent_id @_parent_id elsif @_parent unless @_parent.respond_to?(:id) raise ArgumentError, "@_parent is incorrectly set to #{Object.instance_method(:inspect).bind(@_parent).call}" end @_parent_id = @_parent.id end end def parent=(parent) if @_parent raise Elastictastic::IllegalModificationError, "Document is already a child of #{_parent}" end if persisted? raise Elastictastic::IllegalModificationError, "Can't change parent of persisted object" end #TODO - here's a piece of debugging to fix a problem where we get weird parents. remove after fixing if parent && !parent.respond_to?(:id) raise ArgumentError.new("Bad parent loaded from id #{parent_id} is a #{parent.class.name}.") end @_parent = parent end def save(options = {}) super self.class.child_associations.each_pair do |name, association| association.extract(self).transient_children.each do |child| child.save unless child.pending_save? end end end protected def read_child(field_name) @_children[field_name.to_s] end end end
brewster/elastictastic
lib/elastictastic/parent_child.rb
Ruby
mit
3,255
/* 1 Two Sum I * O(n^2) runtime, O(n) space - Brute force */ public class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { int ni = nums[i]; for (int j = i + 1; j < nums.length; j++) { int nj = nums[j]; if (ni + nj == target) { return new int[] {i, j}; } } } throw new IllegalArgumentException("No two sum solution"); } }
aenon/OnlineJudge
leetcode/1.Array_String/1.two-sum_brute_force.java
Java
mit
455
// @flow import React, { Component, PropTypes } from "react" import { connect } from "react-redux" import TextField from 'material-ui/TextField' import { CreateAuctionButton } from "../../molecules/" import * as AuctionActions from "../../../actions/auction" import { Button } from "../../atoms/" import styles from "./styles.css" export class CreateAuctionBox extends Component { constructor(props) { super(props) this.state = { name: "", minimum: "", message: "", image: "", auctionMsg: props.auctionMsg, } } change = (event) => { if ("id" in event.target && "value" in event.target) { console.log(event.target.id) console.log(event.target.value) this.setState({ [event.target.id]: event.target.value }) } } data = () => { const { name, minimum, message, image } = this.state const base = { name : name, minimum : minimum, message : message, image : image } if (firebase.auth().currentUser) { return Object.assign({}, base, { usrID : firebase.auth().currentUser.uid }) } return base } action = () => { const { name, minimum, message, image } = this.state if (name && minimum && message && image && minimum > 0) { const { dispatch } = this.props console.log(this.data()) dispatch(AuctionActions.queryCreateAuction(JSON.stringify(this.data()))) } } componentWillReceiveProps(nextProps) { if(JSON.stringify(this.state.auctionMsg) !== JSON.stringify(nextProps.auctionMsg)) { this.setState({ auctionMsg: nextProps.auctionMsg }) } } render() { const { auctionMsg } = this.state return ( <div className={ styles.root }> <h3>Create Bid</h3> <div>Status: <span style={{ color : (auctionMsg.status.toLowerCase() !== 'success' ? "red" : "green") }}>{ auctionMsg.status }</span></div> <TextField id="name" value={ this.state.name } floatingLabelText="Domain" onChange={this.change}/><br /> <TextField id="minimum" type="number" value={ this.state.minimum } floatingLabelText="Minimum" onChange={this.change}/><br /> <TextField id="message" value={ this.state.message } floatingLabelText="Message" onChange={this.change}/><br /> <TextField id="image" value={ this.state.image } floatingLabelText="Image" style={{ "marginBottom" : "1em"}} onChange={this.change}/><br /> <Button onClick={ this.action }> Create Auction </Button> </div> ) } } CreateAuctionBox.propTypes = { auctionMsg: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, } function mapStateToProps(state) { const { auctionMsg } = state.auction return { auctionMsg, } } export default connect(mapStateToProps)(CreateAuctionBox)
BradZzz/occasio
src/components/molecules/CreateAuctionBox/CreateAuctionBox.js
JavaScript
mit
2,780
"use strict"; var expect = require('chai').expect , protolib = require(__dirname + '/../') ; describe('protolib', function() { describe('clone', function() { it('should create a clone of the given object', function() { var object = { name: 'Philip' , hello: function() { return 'Hello, my name is ' + this.name; } , date: new Date() , arr: [1, {foo: 'bar'}] }; var clone_object = protolib.clone(object); expect(clone_object).to.have.property('name', 'Philip'); expect(clone_object.hello()).to.equal('Hello, my name is Philip'); expect(clone_object.date.getMonth()).to.equal(new Date().getMonth()); expect(clone_object).to.have.deep.property('arr[0]', 1); expect(clone_object).to.have.deep.property('arr[1].foo', 'bar'); }); it('should throw an error if input is not an object or array', function() { expect(protolib.clone).to.throw('Cannot clone!'); }); }); describe('inherit', function() { it('should set the prototype of an object to the given value', function() { var proto = {foo: 'bar'}; var object = protolib.inherit(proto); expect(object).to.have.property('foo', 'bar'); proto.foo = 'baz'; expect(object).to.have.property('foo', 'baz'); }); }); describe('mixin', function() { it('should add the prototype properties to the given object', function() { var proto = {type: 'list', values: [1, 2, 3]}; var object = {readonly: true}; protolib.mixin(object, proto); expect(object).to.have.property('readonly', true); expect(object).to.have.property('type', 'list'); expect(object).to.have.deep.property('values[0]', 1); expect(object).to.have.deep.property('values[1]', 2); expect(object).to.have.deep.property('values[2]', 3); }); it('should overwrite any existing properties with duplicate names', function() { var proto = {type: 'list', values: [1, 2, 3]}; var object = {type: 'none'}; protolib.mixin(object, proto); expect(object).to.have.property('type', 'list'); expect(object).to.have.deep.property('values[0]', 1); expect(object).to.have.deep.property('values[1]', 2); expect(object).to.have.deep.property('values[2]', 3); }); }); });
Elzair/protolib
test/test.js
JavaScript
mit
2,315
package recognizer; import lexical_analysis.Lexeme; import environment.Environment; public class Parser { Lexeme tree; Environment e; public Parser (Lexeme tree,Environment E){ this.tree = tree; e = E; getObjDecl(e,tree.getLeft().getLeft()); getMainDef(e,tree.getRight()); } public Environment getEnvironment(){ return e; } public void getObjDecl(Environment e,Lexeme l){ if (l != null){ objDecl(e,l.getLeft()); getObjDecl(e,l.getRight()); } } public void objDecl(Environment e, Lexeme l){ if (l == null){ return; } Lexeme id = l.getRight(); Lexeme arg = id.getRight().getRight().getLeft(); Lexeme objDecl = id.getRight().getRight().getRight().getLeft(); Lexeme val = expr(e,arg); // System.out.println("SETTING ENV FOR VAR " + id); id.setObjEnv(initObjEnv(e,objDecl)); e.insert(id, val); // System.out.println(e); } public void getMainDef(Environment e,Lexeme l){ //Skip main stuff l = l.getRight().getRight().getRight().getRight().getRight().getRight().getRight().getLeft(); // System.out.println(l); codeBlock(e,l); } public void statement(Environment e, Lexeme l){ if (l.type == Lexeme.Type.GLUE){ if (l.getLeft().type == Lexeme.Type.VAR || l.getLeft().type == Lexeme.Type.OS){ //CHANGE THIS LINE TO ACCEPT MORE TYPES objDecl(e, l.getLeft()); } else if (l.getLeft().type == Lexeme.Type.FUNC){ function(e,l); } else{expr(e,l.getLeft());} } else{ if (l.type == Lexeme.Type.WHILE){ whileLoop(e,l); } else{ conditional(e, l); } } } public Lexeme eval(Lexeme a, Lexeme operator, Lexeme b){ switch(operator.type){ case PLUS: //CONCAT for strings, ADDITION for ints if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.STRING){return new Lexeme(Lexeme.Type.STRING, a.sval + b.sval,operator.getLineNumber());} //STRING + STRING else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.STRING, a.sval + Integer.toString(b.ival),operator.getLineNumber());} //STRING + INT = STRING else if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival + b.ival,operator.getLineNumber());} else if (a.type == Lexeme.Type.OBRACKET){return append(a,operator,b);} else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.FALSE){return new Lexeme(Lexeme.Type.STRING, a.sval + "FALSE", operator.getLineNumber());} else if (a.type == Lexeme.Type.STRING && b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.STRING, a.sval + "TRUE", operator.getLineNumber());} else{ FatalError_Parser("Cannot apply + operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber()); } case MINUS: if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival - b.ival,operator.getLineNumber());} else{ FatalError_Parser("Cannot apply - operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber()); break; } case MULT: if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival * b.ival,operator.getLineNumber());} else{ FatalError_Parser("Cannot apply * operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber()); break; } case DIV: if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER,a.ival / b.ival,operator.getLineNumber());} else{ FatalError_Parser("Cannot apply / operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber()); break; } case EXP: if (a.type == Lexeme.Type.INTEGER && b.type == Lexeme.Type.INTEGER){return new Lexeme(Lexeme.Type.INTEGER, (int)Math.pow(a.ival, b.ival),operator.getLineNumber());} else{ FatalError_Parser("Cannot apply + operator to types " + Lexeme.typeToString(a.type) + " and " + Lexeme.typeToString(b.type), operator.getLineNumber()); break; } default: FatalError_Parser("Invalid Operator " +operator.sval, operator.getLineNumber()); break; } return null; } public Lexeme expr(Environment e, Lexeme l){ //Takes glue with expr at left if (l == null){ // System.out.println("expr retuns NULL"); return new Lexeme(Lexeme.Type.NULL); } Lexeme operand = l.getLeft(); Lexeme operator = l.getLeft().getRight(); Lexeme val; if (operand.type == Lexeme.Type.ID){ //If variable, get value; Environment objEnv = e.getKey(operand).getObjEnv(); // System.out.println(objEnv); //SET VAL BEGIN if (operand.getLeft() != null && operand.getLeft().type == Lexeme.Type.OPAREN){ //If Function call... // System.out.println(); Lexeme argList = argList(e, operand.getLeft()); val = functionCall(e,operand,argList); if (operator != null && operator.type == Lexeme.Type.EQUALS){ FatalError_Parser("Cannot use assignment on Function Call to " + operand.sval, operand.getLineNumber()); } } else if (operand.getLeft() != null && operand.getLeft().type == Lexeme.Type.OBRACKET){ // If array access..... Lexeme ndx = expr(e,operand.getLeft().getRight()); if (ndx.type != Lexeme.Type.INTEGER){ FatalError_Parser("Array must be integer, not "+ Lexeme.typeToString(ndx.type), operand.getLineNumber()); } Lexeme element = e.getNdx(operand,ndx.ival); element.setRight(ndx); val = applyOverride(objEnv,"GETNDX",element); if (operator != null && operator.type == Lexeme.Type.EQUALS){ Lexeme result = expr(e,l.getRight()); result.setRight(ndx);//Set right lexeme to ndx for dual argument calls to overrides return applyOverride(objEnv,"GETNDX",e.updateNdx(operand,applyOverride(objEnv,"SETNDX",result),ndx.ival)); } } else{ val = applyOverride(objEnv,"GET",e.get(operand)); } //SET VAL END if (operator == null){ return val; } else if (operator.type == Lexeme.Type.EQUALS){ //If assignment... Lexeme tempVal = applyOverride(objEnv,"SET",expr(e,l.getRight())); //Need to link new value to obj lexemes to keep obj stuff // Lexeme object = e.get(operand).getRight(); // tempVal.setRight(object); return applyOverride(objEnv,"GET",e.update(operand,tempVal)); //Will overwrite function calls... } else{ return eval(val,operator,expr(e,l.getRight())); } } else{ //Is a literal val = operand; if (operand.type == Lexeme.Type.OBRACKET){ Lexeme elementPlaceholder = operand.getLeft(); val = new Lexeme(Lexeme.Type.OBRACKET); val.setLeft(element(e,elementPlaceholder.getLeft())); } if (operator == null){ return val; } else{ return eval(val,operator,expr(e,l.getRight())); } } } public Lexeme element(Environment e, Lexeme l){ if (l == null){ return null; } l.setLeft(expr(e,l.getLeft())); //Eval this element l.setRight(element(e,l.getRight())); //eval next element return l;//return it } public Lexeme argList(Environment e, Lexeme l){//Take an arg list, including Parens, and evals each argument // System.out.println("argList: " + l);//Debug calls. Should be ( Lexeme placeholder = l.getRight(); //Glue node if (placeholder.type == Lexeme.Type.NULL){return null;} //No arguments to evaluate else{ Lexeme argGlue = placeholder.getLeft(); Lexeme result = new Lexeme(Lexeme.Type.GLUE); //Lexeme tree we will return; Lexeme rest = result; Lexeme arg; while (argGlue != null){ arg = argGlue.getLeft(); if (arg.getLeft().type == Lexeme.Type.FUNC){ //If its a func def, just pass, dont add to env rest.setLeft(arg.getLeft().getRight().getRight()); //Copied from val arg in function() } else{ rest.setLeft(expr(e,arg)); } argGlue = argGlue.getRight(); if (argGlue != null){ rest = rest.setAndAdvanceRight(new Lexeme(Lexeme.Type.GLUE)); } } return result; } } public Lexeme functionCall(Environment callEnv, Lexeme signature, Lexeme args){//Takes the def env and lexeme that hold args // System.out.println("Function Call: \n\tSignature: " + signature + "\n\tArgs: " + args); // args = args.cloneTree(); //unnecessary since everything in environment is a copy of the actual lexeme (clone) Lexeme definition = callEnv.get(signature); Environment defEnv = definition.getObjEnv(); if (definition.type != Lexeme.Type.OPAREN){ FatalError_Parser("Attempt to call " + signature.sval + ", a non-function type as a function", signature.getLineNumber()); } Environment local = new Environment(defEnv); Lexeme parms = definition.getRight().getLeft(); //Placeholder -> acutual parm list if (setParms(local, parms, args) == null){ FatalError_Parser("Incorrect number of arguments to function " + signature.sval, signature.getLineNumber()); } Lexeme codePlaceholder = definition.getRight().getRight().getRight().getRight();// ( -> parms -> ) -> { -> codePlaceholder Lexeme returnStatementPlaceholder = codePlaceholder.getRight(); // codePlaceholder -> returnStatementPlaceholder if (codePlaceholder.type != Lexeme.Type.NULL){ codeBlock(local,codePlaceholder.getLeft()); } if (returnStatementPlaceholder.type != Lexeme.Type.NULL){ return returnStatement(local,returnStatementPlaceholder.getLeft()); } return null; } public Lexeme returnStatement(Environment e, Lexeme l){ Lexeme value = l.getRight(); return expr(e,value); } public Environment setParms(Environment e, Lexeme parms, Lexeme args){//Sets each parm to the provided args in the env provided. Ordered. while (parms!= null && args != null){ if (parms.type == Lexeme.Type.COMMA){ parms = parms.getRight(); } else{ e.insert(parms, args.getLeft()); parms = parms.getRight(); args = args.getRight(); } } if (args != null || parms != null){ //Make sure args !> parms return null; } return e; } public Lexeme function(Environment e, Lexeme l){ //Takes glue that holds a function def Lexeme signature = l.getLeft().getRight(); Lexeme body = l.getLeft().getRight().getRight(); body.setObjEnv(e); //Save defining environment for use in calls return e.insert(signature,body); } public void conditional(Environment e, Lexeme l){ Environment local = new Environment(e); Lexeme predicateGlue = l.getRight().getRight(); //if -> ( -> predicate Glue Lexeme codePlaceholder = predicateGlue.getRight().getRight().getRight(); //predicateGlue -> ) -> { -> codePlaceholder if (predicate(local,predicateGlue.getLeft()).type == Lexeme.Type.TRUE){ codeBlock(local, codePlaceholder.getLeft()); } else{ Lexeme elseClause = codePlaceholder.getRight().getRight(); if (elseClause.type != Lexeme.Type.NULL){ codePlaceholder = elseClause.getLeft().getRight().getRight(); codeBlock(local,codePlaceholder.getLeft()); } } } public void whileLoop(Environment e, Lexeme l){ Environment local = new Environment(e); Lexeme predicateGlue = l.getRight().getRight(); //while -> ( -> predicate Glue Lexeme codePlaceholder = predicateGlue.getRight().getRight().getRight(); //predicateGlue -> ) -> { -> codePlaceholder while (predicate(local,predicateGlue.getLeft()).type == Lexeme.Type.TRUE){ codeBlock(local, codePlaceholder.getLeft()); } } public Lexeme predicate(Environment e, Lexeme l) { Lexeme op = l.getLeft(); if (op.type == Lexeme.Type.NOT){ Lexeme result = predicate(e,l.getRight()); if (result.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.FALSE);} else{return new Lexeme(Lexeme.Type.TRUE);} //NOT BOOLEAN TYPES TRANSLATE TO FALSE } Lexeme val = op; if (op.type == Lexeme.Type.ID){val = e.get(op);} if (op.getRight() != null){ Lexeme operator1 = op.getRight(); Lexeme operator2 = operator1.getRight(); return predicateEval(val,operator1,operator2,predicate(e,l.getRight())); } else{ return val; } } public Lexeme predicateEval(Lexeme a, Lexeme op1, Lexeme op2, Lexeme b){ switch(op1.type){ case AND: if (a.type == Lexeme.Type.TRUE && b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} case OR: if (a.type == Lexeme.Type.TRUE || b.type == Lexeme.Type.TRUE){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} case EQUALS: if (a.type != b.type){ return new Lexeme(Lexeme.Type.FALSE);} else{ if (a.type == Lexeme.Type.INTEGER){ if (a.ival == b.ival){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} } else if (a.type == Lexeme.Type.NULL){return new Lexeme(Lexeme.Type.TRUE);} else{ if (a.sval.equals(b.sval)){return new Lexeme(Lexeme.Type.TRUE);} else {return new Lexeme(Lexeme.Type.FALSE);} } } case GT: if (a.type != b.type || a.type != Lexeme.Type.INTEGER){ return new Lexeme(Lexeme.Type.FALSE);} else{ if (op2 != null){ if (a.ival >= b.ival){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} } else{ if (a.ival > b.ival){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} } } case LT: if (a.type != b.type || a.type != Lexeme.Type.INTEGER){ return new Lexeme(Lexeme.Type.FALSE);} else{ if (op2 != null){ if (a.ival <= b.ival){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} } else{ if (a.ival < b.ival){return new Lexeme(Lexeme.Type.TRUE);} else{return new Lexeme(Lexeme.Type.FALSE);} } } default: break; } return null; } public Environment initObjEnv(Environment e, Lexeme objDef){ Environment objLocal = new Environment(e); //Gonna return this once we set everything up if (objDef == null){ return objLocal; } Lexeme objDeclPlaceholder = objDef.getRight(); if (objDeclPlaceholder.type == Lexeme.Type.GLUE){ getObjDecl(objLocal,objDeclPlaceholder.getLeft()); } Lexeme overridesPlaceholder = objDeclPlaceholder.getRight(); if (overridesPlaceholder.type == Lexeme.Type.GLUE){ setOverrides(objLocal,overridesPlaceholder.getLeft()); } Lexeme helperPlaceholder = overridesPlaceholder.getRight(); if (helperPlaceholder.type == Lexeme.Type.GLUE){ setHelpers(objLocal,helperPlaceholder.getLeft()); } // System.out.println(objLocal); return objLocal; } public Lexeme applyOverride(Environment e, String overrideType, Lexeme arg){ Lexeme signature = new Lexeme(Lexeme.Type.ID, overrideType, arg.getLineNumber()); if (e == null || !e.exists(signature)){return arg;} Lexeme args = new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(arg); if (overrideType.equals("GETNDX") || overrideType.equals("SETNDX")){ //passing two arguments for GETNDX and SETNDX args.setRight(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(arg.getRight())); } return functionCall(e,signature,args); } public void setOverrides(Environment e, Lexeme overrideList){ if (overrideList == null){ return; } Lexeme override = overrideList.getLeft(); Lexeme sig = new Lexeme(Lexeme.Type.ID, Lexeme.typeToString(override.type), override.getLineNumber()); Lexeme function = override.getRight().getRight(); Lexeme funcBody = function.getLeft().getRight().getRight(); funcBody.setObjEnv(e); //Set def env for overrides e.insert(sig, funcBody); setOverrides(e,overrideList.getRight()); } public void setHelpers(Environment e, Lexeme helperList){ if (helperList == null){ return; } function(e,helperList.getLeft()); setHelpers(e, helperList.getRight()); } public void codeBlock(Environment e, Lexeme l){ if (l == null){ return; } statement(e,l.getLeft()); if (l.getRight() != null){codeBlock(e,l.getRight());} } private void FatalError_Parser(String msg, Integer line){ System.out.println("FATAL ERROR in PARSER on line: " + line +" - " + msg); System.exit(1); } public Lexeme append(Lexeme arr,Lexeme operator, Lexeme val){ //Takes operator for line number if (arr.type != Lexeme.Type.OBRACKET){ FatalError_Parser("Attempted to get index of type " + Lexeme.typeToString(arr.type) + ". Dont do that.", operator.getLineNumber()); } Lexeme element; if (arr.getLeft() == null){ arr.setLeft(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(val)); return arr; } else{ element = arr.getLeft(); while (element.getRight() != null){ element = element.getRight(); } element.setRight(new Lexeme(Lexeme.Type.GLUE).setLeftReturnSelf(val)); return arr; } } }
tmlewallen/Eevee
src/recognizer/Parser.java
Java
mit
16,717
package com.damienfremont.blog; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; @SpringBootApplication( // scanBasePackageClasses = { DataSourceConfig.class }) @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
DamienFremont/blog
20171119-springboot-datasource/springboot-datasource-2-semi_autoconfig/src/main/java/com/damienfremont/blog/Application.java
Java
mit
356
module Chemcaster class Image < Item attributes :width, :height, :data, :format resources :imageable end end
metamolecular/chemcaster-ruby
lib/chemcaster/image.rb
Ruby
mit
121
console.log('load version 2.0.0');
soulteary/xSwitch.js
demo/assets/test-2.0.0.js
JavaScript
mit
34
<?php /** * Zotero specific exception class with no added functionality * * @package libZotero */ class Zotero_Exception extends Exception { } /** * Explicit mappings for Zotero * * @package libZotero */ class Zotero_Mappings { public $itemTypes = array(); public $itemFields = array(); public $itemTypeCreatorTypes = array(); public $creatorFields = array(); } /** * Representation of a Zotero Feed (ATOM) * * @package libZotero */ class Zotero_Feed { /** * @var string */ public $lastModified; /** * @var string */ public $title; /** * @var string */ public $dateUpdated; /** * @var int */ public $totalResults; /** * @var int */ public $apiVersion; /** * @var string */ public $id; /** * @var array */ public $links = array(); /** * @var array */ public $entries = array(); public $entryNodes; public function __construct($doc) { if(!($doc instanceof DOMDocument)){ $domdoc = new DOMDocument(); $domdoc->loadXml($doc); $doc = $domdoc; } foreach($doc->getElementsByTagName("feed") as $feed){ $this->title = $feed->getElementsByTagName("title")->item(0)->nodeValue; $this->id = $feed->getElementsByTagName("id")->item(0)->nodeValue; $this->dateUpdated = $feed->getElementsByTagName("updated")->item(0)->nodeValue; //$this->apiVersion = $feed->getElementsByTagName("apiVersion")->item(0)->nodeValue;//apiVersion being removed from zotero responses $this->totalResults = $feed->getElementsByTagName("totalResults")->item(0)->nodeValue; // Get all of the link elements foreach($feed->childNodes as $childNode){ if($childNode->nodeName == "link"){ $linkNode = $childNode; $this->links[$linkNode->getAttribute('rel')] = array('type'=>$linkNode->getAttribute('type'), 'href'=>$linkNode->getAttribute('href')); } } $entryNodes = $doc->getElementsByTagName("entry"); $this->entryNodes = $entryNodes; /* //detect zotero entry type with sample entry node and parse entries appropriately $firstEntry = $entryNodes->item(0); $this->entryType = $this->detectZoteroEntryType($firstEntry); foreach($entryNodes as $entryNode){ switch($this->entryType) { case 'item': $entry = new Zotero_Item($entryNode); break; case 'collection': $entry = new Zotero_Collection($entryNode); break; case 'group': $entry = new Zotero_Group($entryNode); break; case 'user': $entry = new Zotero_User($entryNode); break; case 'tag': $entry = new Zotero_Tag($entryNode); break; default: throw new Zend_Exception("Unknown entry type"); } $this->entries[] = $entry; } */ } } public function detectZoteroEntryType($entryNode){ $itemTypeNodes = $entryNode->getElementsByTagName("itemType"); $numCollectionsNodes = $entryNode->getElementsByTagName("numCollections"); $numItemsNodes = $entryNode->getElementsByTagName("numItems"); /* $itemType = $xpath->evaluate("//zapi:itemType")->item(0)->nodeValue; $collectionKey = $xpath->evaluate("//zapi:collectionKey")->item(0)->nodeValue; $numItems = $xpath->evaluate("//zapi:numItems")->item(0)->nodeValue; */ if($itemTypeNodes->length) return 'item'; if($numCollectionsNodes->length) return 'collection'; if($numItemsNodes->length && !($collectionKeyNodes->length)) return 'tag'; //if($userID) return 'user'; //if($groupID) return 'group'; } public function nestEntries(){ // Look for item and collection entries with rel="up" links and move them under their parent entry if($nest && ($entryType == "collections" || $entryType == "items")){ foreach($this->feed->entries as $key => $entry){ if(isset($entry->links['up']['application/atom+xml'])){ // This flag will be set to true if a parent is found $this->foundParent = false; // Search for a parent $this->nestEntry($entry, $this->feed->entries); // If we found a parent to nest under, remove the entry from the top level if($this->foundParent == true){ unset($this->feed->entries[$key]); } } } } } public function dataObject() { $jsonItem = new stdClass; $jsonItem->lastModified = $this->lastModified; $jsonItem->title = $this->title; $jsonItem->dateUpdated = $this->dateUpdated; $jsonItem->totalResults = $this->totalResults; $jsonItem->id = $this->id; // foreach($this->links as $link){ // $jsonItem->links[] = $link; // } $jsonItem->links = $this->links; $jsonItem->entries = array(); foreach($this->entries as $entry){ $jsonItem->entries[] = $entry->dataObject(); } return $jsonItem; } } /** * Zotero API Feed entry (ATOM) * * @package libZotero */ class Zotero_Entry { /** * @var string */ public $title; /** * @var string */ public $dateAdded; /** * @var string */ public $dateUpdated; /** * @var string */ public $id; /** * @var array */ public $links = array(); /** * @var array */ public $author = array(); /** * @var int */ public $version = 0; public $contentArray = array(); /** * @var array */ public $entries = array(); public function __construct($entryNode) { if(!($entryNode instanceof DOMNode)){ if(is_string($entryNode)){ $doc = new DOMDocument(); $doc->loadXml($entryNode); $entryNodes = $doc->getElementsByTagName("entry"); if($entryNodes->length){ $entryNode = $entryNodes->item(0); } else { return null; } } } $parseFields = array('title', 'id', 'dateAdded', 'dateUpdated', 'author'); $this->title = $entryNode->getElementsByTagName("title")->item(0)->nodeValue; $this->id = $entryNode->getElementsByTagName("id")->item(0)->nodeValue; $this->dateAdded = $entryNode->getElementsByTagName("published")->item(0)->nodeValue; $this->dateUpdated = $entryNode->getElementsByTagName("updated")->item(0)->nodeValue; //try to parse author node if it's there try{ $author = array(); $authorNode = $entryNode->getElementsByTagName('author')->item(0); $author['name'] = $authorNode->getElementsByTagName('name')->item(0)->nodeValue; $author['uri'] = $authorNode->getElementsByTagName('uri')->item(0)->nodeValue; $this->author = $author; } catch(Exception $e){ } // Get all of the link elements foreach($entryNode->getElementsByTagName("link") as $linkNode){ if($linkNode->getAttribute('rel') == "enclosure"){ $this->links['enclosure'][$linkNode->getAttribute('type')] = array( 'href'=>$linkNode->getAttribute('href'), 'title'=>$linkNode->getAttribute('title'), 'length'=>$linkNode->getAttribute('length')); } else{ $this->links[$linkNode->getAttribute('rel')][$linkNode->getAttribute('type')] = array( 'href'=>$linkNode->getAttribute('href') ); } } } public function getContentType($entryNode){ $contentNode = $entryNode->getElementsByTagName('content')->item(0); if($contentNode) return $contentNode->getAttribute('type') || $contentNode->getAttributeNS('http://zotero.org/ns/api', 'type'); else return false; } public function associateWithLibrary($library){ $this->libraryType = $library->libraryType; $this->libraryID = $library->libraryID; $this->owningLibrary = $library; } } /** * Representation of a Zotero Collection * * @package libZotero * @see Zotero_Entry */ class Zotero_Collection extends Zotero_Entry { /** * @var int */ public $collectionVersion = 0; /** * @var int */ public $collectionKey = null; public $name = ''; /** * @var int */ public $numCollections = 0; /** * @var int */ public $numItems = 0; public $topLevel; /** * @var string */ public $parentCollectionKey = false; public $apiObject = array(); public $pristine = array(); public $childKeys = array(); public function __construct($entryNode, $library=null) { if(!$entryNode){ return; } parent::__construct($entryNode); $this->name = $this->title; //collection name is the Entry title //parse zapi tags $this->collectionKey = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'key')->item(0)->nodeValue; $this->collectionVersion = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'version')->item(0)->nodeValue; $this->numCollections = $entryNode->getElementsByTagName('numCollections')->item(0)->nodeValue; $this->numItems = $entryNode->getElementsByTagName('numItems')->item(0)->nodeValue; $contentNode = $entryNode->getElementsByTagName('content')->item(0); if($contentNode){ $contentType = $contentNode->getAttribute('type'); if($contentType == 'application/json'){ $this->pristine = json_decode($contentNode->nodeValue); $this->apiObject = json_decode($contentNode->nodeValue, true); $this->parentCollectionKey = $this->apiObject['parentCollection']; $this->name = $this->apiObject['name']; } elseif($contentType == 'xhtml'){ //$this->parseXhtmlContent($contentNode); } } if($library !== null){ $this->associateWithLibrary($library); } } public function get($key){ switch($key){ case 'title': case 'name': return $this->name; case 'collectionKey': case 'key': return $this->collectionKey; case 'parentCollection': case 'parentCollectionKey': return $this->parentCollectionKey; case 'collectionVersion': case 'version': return $this->collectionVersion; } if(array_key_exists($key, $this->apiObject)){ return $this->apiObject[$key]; } if(property_exists($this, $key)){ return $this->$key; } return null; } public function set($key, $val){ switch($key){ case 'title': case 'name': $this->name = $val; $this->apiObject['name'] = $val; break; case 'collectionKey': case 'key': $this->collectionKey = $val; $this->apiObject['collectionKey'] = $val; break; case 'parentCollection': case 'parentCollectionKey': $this->parentCollectionKey = $val; $this->apiObject['parentCollection'] = $val; break; case 'collectionVersion': case 'version': $this->collectionVersion = $val; $this->apiObject['collectionVersion'] = $val; break; } if(array_key_exists($key, $this->apiObject)){ $this->apiObject[$key] = $val; } if(property_exists($this, $key)){ $this->$key = $val; } } public function collectionJson(){ return json_encode($this->writeApiObject()); } public function writeApiObject() { $updateItem = array_merge($this->pristine, $this->apiObject); return $updateItem; } public function dataObject() { $jsonItem = new stdClass; //inherited from Entry $jsonItem->title = $this->title; $jsonItem->dateAdded = $this->dateAdded; $jsonItem->dateUpdated = $this->dateUpdated; $jsonItem->id = $this->id; $jsonItem->links = $this->links; $jsonItem->collectionKey = $this->collectionKey; $jsonItem->childKeys = $this->childKeys; $jsonItem->parentCollectionKey = $this->parentCollectionKey; return $jsonItem; } } /** * Representation of the set of collections belonging to a particular Zotero library * * @package libZotero */ class Zotero_Collections { public $orderedArray; public $collectionObjects; public $dirty; public $loaded; public function __construct(){ $this->orderedArray = array(); $this->collectionObjects = array(); } public static function sortByTitleCompare($a, $b){ if(strtolower($a->title) == strtolower($b->title)){ return 0; } if(strtolower($a->title) < strtolower($b->title)){ return -1; } return 1; } public function addCollection($collection) { $this->collectionObjects[$collection->collectionKey] = $collection; $this->orderedArray[] = $collection; } public function getCollection($collectionKey) { if(isset($this->collectionObjects[$collectionKey])){ return $this->collectionObjects[$collectionKey]; } return false; } public function addCollectionsFromFeed($feed) { $entries = $feed->entryNodes; if(empty($entries)){ var_dump($feed); die; return array(); } $addedCollections = array(); foreach($entries as $entry){ $collection = new Zotero_Collection($entry); $this->addCollection($collection); $addedCollections[] = $collection; } return $addedCollections; } //add keys of child collections to array public function nestCollections(){ foreach($this->collectionObjects as $key=>$collection){ if($collection->parentCollectionKey){ $parentCollection = $this->getCollection($collection->parentCollectionKey); $parentCollection->childKeys[] = $collection->collectionKey; } } } public function orderCollections(){ $orderedArray = array(); foreach($this->collectionObjects as $key=>$collection){ $orderedArray[] = $collection; } usort($orderedArray, array('Zotero_Collections', 'sortByTitleCompare')); $this->orderedArray = $orderedArray; return $this->orderedArray; } public function topCollectionKeys($collections){ $topCollections = array(); foreach($collections as $collection){ if($collection->parentCollectionKey == false){ $topCollections[] = $collection->collectionKey; } } return $topCollections; } public function collectionsJson(){ $collections = array(); foreach($this->collectionObjects as $collection){ $collections[] = $collection->dataObject(); } return json_encode($collections); } public function writeCollection($collection){ $cols = $this->writeCollections(array($collection)); if($cols === false){ return false; } return $cols[0]; } public function writeCollections($collections){ $writeCollections = array(); foreach($collections as $collection){ $collectionKey = $collection->get('collectionKey'); if($collectionKey == ""){ $newCollectionKey = Zotero_Lib_Utils::getKey(); $collection->set('collectionKey', $newCollectionKey); $collection->set('collectionVersion', 0); } $writeCollections[] = $collection; } $config = array('target'=>'collections', 'libraryType'=>$this->owningLibrary->libraryType, 'libraryID'=>$this->owningLibrary->libraryID, 'content'=>'json'); $requestUrl = $this->owningLibrary->apiRequestString($config); $chunks = array_chunk($writeCollections, 50); foreach($chunks as $chunk){ $writeArray = array(); foreach($chunk as $collection){ $writeArray[] = $collection->writeApiObject(); } $requestData = json_encode(array('collections'=>$writeArray)); $writeResponse = $this->owningLibrary->_request($requestUrl, 'POST', $requestData, array('Content-Type'=> 'application/json')); if($writeResponse->isError()){ foreach($chunk as $collection){ $collection->writeFailure = array('code'=>$writeResponse->getStatus(), 'message'=>$writeResponse->getBody()); } } else { Zotero_Lib_Utils::UpdateObjectsFromWriteResponse($chunk, $writeResponse); } } return $writeCollections; } public function writeUpdatedCollection($collection){ $this->writeCollections(array($collection)); return $collection; } /** * Load all collections in the library into the collections container * * @param array $params list of parameters limiting the request * @return null */ public function fetchAllCollections($params = array()){ $aparams = array_merge(array('target'=>'collections', 'content'=>'json', 'limit'=>100), $params); $reqUrl = $this->owningLibrary->apiRequestString($aparams); do{ $response = $this->owningLibrary->_request($reqUrl); if($response->isError()){ throw new Exception("Error fetching collections"); } $feed = new Zotero_Feed($response->getRawBody()); $this->addCollectionsFromFeed($feed); if(isset($feed->links['next'])){ $nextUrl = $feed->links['next']['href']; $parsedNextUrl = parse_url($nextUrl); $parsedNextUrl['query'] = $this->owningLibrary->apiQueryString($this->parseQueryString($parsedNextUrl['query']) ); $reqUrl = $parsedNextUrl['scheme'] . '://' . $parsedNextUrl['host'] . $parsedNextUrl['path'] . $parsedNextUrl['query']; } else{ $reqUrl = false; } } while($reqUrl); $this->loaded = true; return $this->orderedArray; } /** * Load 1 request worth of collections in the library into the collections container * * @param array $params list of parameters limiting the request * @return null */ public function fetchCollections($params = array()){ $aparams = array_merge(array('target'=>'collections', 'content'=>'json', 'limit'=>100), $params); $reqUrl = $this->owningLibrary->apiRequestString($aparams); $response = $this->owningLibrary->_request($reqUrl); if($response->isError()){ return false; throw new Exception("Error fetching collections"); } $feed = new Zotero_Feed($response->getRawBody()); $this->owningLibrary->_lastFeed = $feed; $addedCollections = $this->addCollectionsFromFeed($feed); if(isset($feed->links['next'])){ $nextUrl = $feed->links['next']['href']; $parsedNextUrl = parse_url($nextUrl); $parsedNextUrl['query'] = $this->apiQueryString($this->parseQueryString($parsedNextUrl['query']) ); $reqUrl = $parsedNextUrl['scheme'] . '://' . $parsedNextUrl['host'] . $parsedNextUrl['path'] . $parsedNextUrl['query']; } else{ $reqUrl = false; } return $addedCollections; } /** * Load a single collection by collectionKey * * @param string $collectionKey * @return Zotero_Collection */ public function fetchCollection($collectionKey){ $aparams = array('target'=>'collection', 'content'=>'json', 'collectionKey'=>$collectionKey); $reqUrl = $this->owningLibrary->apiRequestString($aparams); $response = $this->owningLibrary->_request($reqUrl, 'GET'); if($response->isError()){ return false; throw new Exception("Error fetching collection"); } $entry = Zotero_Lib_Utils::getFirstEntryNode($response->getRawBody()); if($entry == null){ return false; } $collection = new Zotero_Collection($entry, $this); $this->addCollection($collection); return $collection; } } /** * Representation of a set of items belonging to a particular Zotero library * * @package libZotero */ class Zotero_Items { public $itemObjects = array(); public $owningLibrary; public $itemsVersion = 0; //get an item from this container of items by itemKey public function getItem($itemKey) { if(isset($this->itemObjects[$itemKey])){ return $this->itemObjects[$itemKey]; } return false; } //add a Zotero_Item to this container of items public function addItem($item) { $itemKey = $item->itemKey; $this->itemObjects[$itemKey] = $item; if($this->owningLibrary){ $item->associateWithLibrary($this->owningLibrary); } } //add items to this container from a Zotero_Feed object public function addItemsFromFeed($feed) { $entries = $feed->entryNodes; $addedItems = array(); foreach($entries as $entry){ $item = new Zotero_Item($entry); $this->addItem($item); $addedItems[] = $item; } return $addedItems; } //replace an item in this container with a new Zotero_Item object with the same itemKey //useful for example after updating an item when the etag is out of date and to make sure //the current item we have reflects the best knowledge of the api public function replaceItem($item) { $this->addItem($item); } public function addChildKeys() { //empty existing childkeys first foreach($this->itemObjects as $key=>$item){ $item->childKeys = array(); } //run through and add item keys to their parent's item if we have the parent foreach($this->itemObjects as $key=>$item){ if($item->parentKey){ $pitem = $this->getItem($item->parentKey); if($pitem){ $pitem->childKeys[] = $item->itemKey; } } } } public function getPreloadedChildren($item){ $children = array(); foreach($item->childKeys as $childKey){ $childItem = $this->getItem($childKey); if($childItem){ $children[] = $childItem; } } return $children; } public function writeItem($item){ return $this->writeItems(array($item)); } //accept an array of `Zotero_Item`s public function writeItems($items){ $writeItems = array(); foreach($items as $item){ $itemKey = $item->get('itemKey'); if($itemKey == ""){ $newItemKey = Zotero_Lib_Utils::getKey(); $item->set('itemKey', $newItemKey); $item->set('itemVersion', 0); } $writeItems[] = $item; //add separate note items if this item has any $itemNotes = $item->get('notes'); if($itemNotes && (count($itemNotes) > 0) ){ foreach($itemNotes as $note){ $note->set('parentItem', $item->get('itemKey')); $note->set('itemKey', Zotero_Lib_Utils::getKey()); $note->set('itemVersion', 0); $writeItems[] = $note; } } } $config = array('target'=>'items', 'libraryType'=>$this->owningLibrary->libraryType, 'libraryID'=>$this->owningLibrary->libraryID, 'content'=>'json'); $requestUrl = $this->owningLibrary->apiRequestString($config); $chunks = array_chunk($writeItems, 50); foreach($chunks as $chunk){ $writeArray = array(); foreach($chunk as $item){ $writeArray[] = $item->writeApiObject(); } $requestData = json_encode(array('items'=>$writeArray)); $writeResponse = $this->owningLibrary->_request($requestUrl, 'POST', $requestData, array('Content-Type'=> 'application/json')); if($writeResponse->isError()){ foreach($chunk as $item){ $item->writeFailure = array('code'=>$writeResponse->getStatus(), 'message'=>$writeResponse->getBody()); } } else { Zotero_Lib_Utils::UpdateObjectsFromWriteResponse($chunk, $writeResponse); } } return $writeItems; } public function trashItem($item){ $item->trashItem(); return $item->save(); } public function trashItems($items){ foreach($items as $item){ $item->trashItem(); } return $this->writeItems($items); } public function deleteItem($item){ $aparams = array('target'=>'item', 'itemKey'=>$item->itemKey); $reqUrl = $this->owningLibrary->apiRequestString($aparams); $response = $this->owningLibrary->_request($reqUrl, 'DELETE', null, array('If-Unmodified-Since-Version'=>$item->itemVersion)); return $response; } //delete multiple items //modified version we submit to the api falls back from explicit argument, to $items->itemsVersion //if set and non-zero, to the max itemVersion of items passed for deletion public function deleteItems($items, $version=null){ if(count($items) > 50){ throw new Exception("Too many items to delete"); } $itemKeys = array(); $latestItemVersion = 0; foreach($items as $item){ array_push($itemKeys, $item->get('itemKey')); $v = $item->get('version'); if($v > $latestItemVersion){ $latestItemVersion = $v; } } if($version === null){ if($this->itemsVersion !== 0){ $version = $this->itemsVersion; } else { $version = $latestItemVersion; } } $aparams = array('target'=>'items', 'itemKey'=>$itemKeys); $reqUrl = $this->owningLibrary->apiRequestString($aparams); $response = $this->owningLibrary->_request($reqUrl, 'DELETE', null, array('If-Unmodified-Since-Version'=>$version)); return $response; } } /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage Response * @version $Id: Response.php 23484 2010-12-10 03:57:59Z mjh_ca $ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Http_Response represents an HTTP 1.0 / 1.1 response message. It * includes easy access to all the response's different elemts, as well as some * convenience methods for parsing and validating HTTP responses. * * @package Zend_Http * @subpackage Response * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ //class Zend_Http_Response class libZotero_Http_Response { /** * List of all known HTTP response codes - used by responseCodeAsText() to * translate numeric codes to messages. * * @var array */ protected static $messages = array( // Informational 1xx 100 => 'Continue', 101 => 'Switching Protocols', // Success 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', // Redirection 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', // 1.1 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', // 306 is deprecated but reserved 307 => 'Temporary Redirect', // Client Error 4xx 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', // Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' ); /** * The HTTP version (1.0, 1.1) * * @var string */ protected $version; /** * The HTTP response code * * @var int */ protected $code; /** * The HTTP response code as string * (e.g. 'Not Found' for 404 or 'Internal Server Error' for 500) * * @var string */ protected $message; /** * The HTTP response headers array * * @var array */ protected $headers = array(); /** * The HTTP response body * * @var string */ protected $body; /** * HTTP response constructor * * In most cases, you would use Zend_Http_Response::fromString to parse an HTTP * response string and create a new Zend_Http_Response object. * * NOTE: The constructor no longer accepts nulls or empty values for the code and * headers and will throw an exception if the passed values do not form a valid HTTP * responses. * * If no message is passed, the message will be guessed according to the response code. * * @param int $code Response code (200, 404, ...) * @param array $headers Headers array * @param string $body Response body * @param string $version HTTP version * @param string $message Response code as text * @throws Exception */ public function __construct($code, array $headers, $body = null, $version = '1.1', $message = null) { // Make sure the response code is valid and set it if (self::responseCodeAsText($code) === null) { throw new Exception("{$code} is not a valid HTTP response code"); } $this->code = $code; foreach ($headers as $name => $value) { if (is_int($name)) { $header = explode(":", $value, 2); if (count($header) != 2) { throw new Exception("'{$value}' is not a valid HTTP header"); } $name = trim($header[0]); $value = trim($header[1]); } $this->headers[ucwords(strtolower($name))] = $value; } // Set the body $this->body = $body; //var_dump($code); // Set the HTTP version if (! preg_match('|^\d\.\d$|', $version)) { throw new Exception("Invalid HTTP response version: $version"); } $this->version = $version; // If we got the response message, set it. Else, set it according to // the response code if (is_string($message)) { $this->message = $message; } else { $this->message = self::responseCodeAsText($code); } } /** * Check whether the response is an error * * @return boolean */ public function isError() { $restype = floor($this->code / 100); if ($restype == 4 || $restype == 5) { return true; } return false; } /** * Check whether the response in successful * * @return boolean */ public function isSuccessful() { $restype = floor($this->code / 100); if ($restype == 2 || $restype == 1) { // Shouldn't 3xx count as success as well ??? return true; } return false; } /** * Check whether the response is a redirection * * @return boolean */ public function isRedirect() { $restype = floor($this->code / 100); if ($restype == 3) { return true; } return false; } /** * Get the response body as string * * This method returns the body of the HTTP response (the content), as it * should be in it's readable version - that is, after decoding it (if it * was decoded), deflating it (if it was gzip compressed), etc. * * If you want to get the raw body (as transfered on wire) use * $this->getRawBody() instead. * * @return string */ public function getBody() { //added by fcheslack - curl adapter handles these things already so they are transparent to Zend_Response return $this->getRawBody(); $body = ''; // Decode the body if it was transfer-encoded switch (strtolower($this->getHeader('transfer-encoding'))) { // Handle chunked body case 'chunked': $body = self::decodeChunkedBody($this->body); break; // No transfer encoding, or unknown encoding extension: // return body as is default: $body = $this->body; break; } // Decode any content-encoding (gzip or deflate) if needed switch (strtolower($this->getHeader('content-encoding'))) { // Handle gzip encoding case 'gzip': $body = self::decodeGzip($body); break; // Handle deflate encoding case 'deflate': $body = self::decodeDeflate($body); break; default: break; } return $body; } /** * Get the raw response body (as transfered "on wire") as string * * If the body is encoded (with Transfer-Encoding, not content-encoding - * IE "chunked" body), gzip compressed, etc. it will not be decoded. * * @return string */ public function getRawBody() { return $this->body; } /** * Get the HTTP version of the response * * @return string */ public function getVersion() { return $this->version; } /** * Get the HTTP response status code * * @return int */ public function getStatus() { return $this->code; } /** * Return a message describing the HTTP response code * (Eg. "OK", "Not Found", "Moved Permanently") * * @return string */ public function getMessage() { return $this->message; } /** * Get the response headers * * @return array */ public function getHeaders() { return $this->headers; } /** * Get a specific header as string, or null if it is not set * * @param string$header * @return string|array|null */ public function getHeader($header) { $header = ucwords(strtolower($header)); if (! is_string($header) || ! isset($this->headers[$header])) return null; return $this->headers[$header]; } /** * Get all headers as string * * @param boolean $status_line Whether to return the first status line (IE "HTTP 200 OK") * @param string $br Line breaks (eg. "\n", "\r\n", "<br />") * @return string */ public function getHeadersAsString($status_line = true, $br = "\n") { $str = ''; if ($status_line) { $str = "HTTP/{$this->version} {$this->code} {$this->message}{$br}"; } // Iterate over the headers and stringify them foreach ($this->headers as $name => $value) { if (is_string($value)) $str .= "{$name}: {$value}{$br}"; elseif (is_array($value)) { foreach ($value as $subval) { $str .= "{$name}: {$subval}{$br}"; } } } return $str; } /** * Get the entire response as string * * @param string $br Line breaks (eg. "\n", "\r\n", "<br />") * @return string */ public function asString($br = "\n") { return $this->getHeadersAsString(true, $br) . $br . $this->getRawBody(); } /** * Implements magic __toString() * * @return string */ public function __toString() { return $this->asString(); } /** * A convenience function that returns a text representation of * HTTP response codes. Returns 'Unknown' for unknown codes. * Returns array of all codes, if $code is not specified. * * Conforms to HTTP/1.1 as defined in RFC 2616 (except for 'Unknown') * See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10 for reference * * @param int $code HTTP response code * @param boolean $http11 Use HTTP version 1.1 * @return string */ public static function responseCodeAsText($code = null, $http11 = true) { $messages = self::$messages; if (! $http11) $messages[302] = 'Moved Temporarily'; if ($code === null) { return $messages; } elseif (isset($messages[$code])) { return $messages[$code]; } else { return 'Unknown'; } } /** * Extract the response code from a response string * * @param string $response_str * @return int */ public static function extractCode($response_str) { preg_match("|^HTTP/[\d\.x]+ (\d+)|", $response_str, $m); if (isset($m[1])) { return (int) $m[1]; } else { return false; } } /** * Extract the HTTP message from a response * * @param string $response_str * @return string */ public static function extractMessage($response_str) { preg_match("|^HTTP/[\d\.x]+ \d+ ([^\r\n]+)|", $response_str, $m); if (isset($m[1])) { return $m[1]; } else { return false; } } /** * Extract the HTTP version from a response * * @param string $response_str * @return string */ public static function extractVersion($response_str) { preg_match("|^HTTP/([\d\.x]+) \d+|i", $response_str, $m); if (isset($m[1])) { return $m[1]; } else { return false; } } /** * Extract the headers from a response string * * @param string $response_str * @return array */ public static function extractHeaders($response_str) { $headers = array(); // First, split body and headers $parts = preg_split('|(?:\r?\n){2}|m', $response_str, 2); if (! $parts[0]) return $headers; // Split headers part to lines $lines = explode("\n", $parts[0]); unset($parts); $last_header = null; foreach($lines as $line) { $line = trim($line, "\r\n"); if ($line == "") break; // Locate headers like 'Location: ...' and 'Location:...' (note the missing space) if (preg_match("|^([\w-]+):\s*(.+)|", $line, $m)) { unset($last_header); $h_name = strtolower($m[1]); $h_value = $m[2]; if (isset($headers[$h_name])) { if (! is_array($headers[$h_name])) { $headers[$h_name] = array($headers[$h_name]); } $headers[$h_name][] = $h_value; } else { $headers[$h_name] = $h_value; } $last_header = $h_name; } elseif (preg_match("|^\s+(.+)$|", $line, $m) && $last_header !== null) { if (is_array($headers[$last_header])) { end($headers[$last_header]); $last_header_key = key($headers[$last_header]); $headers[$last_header][$last_header_key] .= $m[1]; } else { $headers[$last_header] .= $m[1]; } } } return $headers; } /** * Extract the body from a response string * * @param string $response_str * @return string */ public static function extractBody($response_str) { $parts = preg_split('|(?:\r?\n){2}|m', $response_str, 2); if (isset($parts[1])) { return $parts[1]; } return ''; } /** * Decode a "chunked" transfer-encoded body and return the decoded text * * @param string $body * @return string */ public static function decodeChunkedBody($body) { // Added by Dan S. -- don't fail on Transfer-encoding:chunked response //that isn't really chunked if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", trim($body), $m)) { return $body; } $decBody = ''; // If mbstring overloads substr and strlen functions, we have to // override it's internal encoding if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbIntEnc = mb_internal_encoding(); mb_internal_encoding('ASCII'); } while (trim($body)) { if (! preg_match("/^([\da-fA-F]+)[^\r\n]*\r\n/sm", $body, $m)) { throw new Exception("Error parsing body - doesn't seem to be a chunked message"); } $length = hexdec(trim($m[1])); $cut = strlen($m[0]); $decBody .= substr($body, $cut, $length); $body = substr($body, $cut + $length + 2); } if (isset($mbIntEnc)) { mb_internal_encoding($mbIntEnc); } return $decBody; } /** * Decode a gzip encoded message (when Content-encoding = gzip) * * Currently requires PHP with zlib support * * @param string $body * @return string */ public static function decodeGzip($body) { if (! function_exists('gzinflate')) { throw new Exception( 'zlib extension is required in order to decode "gzip" encoding' ); } return gzinflate(substr($body, 10)); } /** * Decode a zlib deflated message (when Content-encoding = deflate) * * Currently requires PHP with zlib support * * @param string $body * @return string */ public static function decodeDeflate($body) { if (! function_exists('gzuncompress')) { throw new Exception( 'zlib extension is required in order to decode "deflate" encoding' ); } /** * Some servers (IIS ?) send a broken deflate response, without the * RFC-required zlib header. * * We try to detect the zlib header, and if it does not exsit we * teat the body is plain DEFLATE content. * * This method was adapted from PEAR HTTP_Request2 by (c) Alexey Borzov * * @link http://framework.zend.com/issues/browse/ZF-6040 */ $zlibHeader = unpack('n', substr($body, 0, 2)); if ($zlibHeader[1] % 31 == 0) { return gzuncompress($body); } else { return gzinflate($body); } } /** * Create a new Zend_Http_Response object from a string * * @param string $response_str * @return Zend_Http_Response */ public static function fromString($response_str) { $code = self::extractCode($response_str); $headers = self::extractHeaders($response_str); $body = self::extractBody($response_str); $version = self::extractVersion($response_str); $message = self::extractMessage($response_str); return new libZotero_Http_Response($code, $headers, $body, $version, $message); } } class Zotero_Cite { private static $citePaperJournalArticleURL = false; // // Ported from cite.js in the Zotero client // /** * Mappings for names * Note that this is the reverse of the text variable map, since all mappings should be one to one * and it makes the code cleaner */ private static $zoteroNameMap = array( "author" => "author", "editor" => "editor", "bookAuthor" => "container-author", "composer" => "composer", "interviewer" => "interviewer", "recipient" => "recipient", "seriesEditor" => "collection-editor", "translator" => "translator" ); /** * Mappings for text variables */ private static $zoteroFieldMap = array( "title" => array("title"), "container-title" => array("publicationTitle", "reporter", "code"), /* reporter and code should move to SQL mapping tables */ "collection-title" => array("seriesTitle", "series"), "collection-number" => array("seriesNumber"), "publisher" => array("publisher", "distributor"), /* distributor should move to SQL mapping tables */ "publisher-place" => array("place"), "authority" => array("court"), "page" => array("pages"), "volume" => array("volume"), "issue" => array("issue"), "number-of-volumes" => array("numberOfVolumes"), "number-of-pages" => array("numPages"), "edition" => array("edition"), "version" => array("version"), "section" => array("section"), "genre" => array("type", "artworkSize"), /* artworkSize should move to SQL mapping tables, or added as a CSL variable */ "medium" => array("medium", "system"), "archive" => array("archive"), "archive_location" => array("archiveLocation"), "event" => array("meetingName", "conferenceName"), /* these should be mapped to the same base field in SQL mapping tables */ "event-place" => array("place"), "abstract" => array("abstractNote"), "URL" => array("url"), "DOI" => array("DOI"), "ISBN" => array("ISBN"), "call-number" => array("callNumber"), "note" => array("extra"), "number" => array("number"), "references" => array("history"), "shortTitle" => array("shortTitle"), "journalAbbreviation" => array("journalAbbreviation"), "language" => array("language") ); private static $zoteroDateMap = array( "issued" => "date", "accessed" => "accessDate" ); private static $zoteroTypeMap = array( 'book' => "book", 'bookSection' => "chapter", 'journalArticle' => "article-journal", 'magazineArticle' => "article-magazine", 'newspaperArticle' => "article-newspaper", 'thesis' => "thesis", 'encyclopediaArticle' => "entry-encyclopedia", 'dictionaryEntry' => "entry-dictionary", 'conferencePaper' => "paper-conference", 'letter' => "personal_communication", 'manuscript' => "manuscript", 'interview' => "interview", 'film' => "motion_picture", 'artwork' => "graphic", 'webpage' => "webpage", 'report' => "report", 'bill' => "bill", 'case' => "legal_case", 'hearing' => "bill", // ?? 'patent' => "patent", 'statute' => "bill", // ?? 'email' => "personal_communication", 'map' => "map", 'blogPost' => "webpage", 'instantMessage' => "personal_communication", 'forumPost' => "webpage", 'audioRecording' => "song", // ?? 'presentation' => "speech", 'videoRecording' => "motion_picture", 'tvBroadcast' => "broadcast", 'radioBroadcast' => "broadcast", 'podcast' => "song", // ?? 'computerProgram' => "book" // ?? ); private static $quotedRegexp = '/^".+"$/'; public static function convertItem($zoteroItem) { if (!$zoteroItem) { throw new Exception("Zotero item not provided"); } // don't return URL or accessed information for journal articles if a // pages field exists $itemType = $zoteroItem->get("itemType");//Zotero_ItemTypes::getName($zoteroItem->itemTypeID); $cslType = isset(self::$zoteroTypeMap[$itemType]) ? self::$zoteroTypeMap[$itemType] : false; if (!$cslType) $cslType = "article"; $ignoreURL = (($zoteroItem->get("accessDate") || $zoteroItem->get("url")) && in_array($itemType, array("journalArticle", "newspaperArticle", "magazineArticle")) && $zoteroItem->get("pages") && self::$citePaperJournalArticleURL); $cslItem = array( 'id' => $zoteroItem->owningLibrary->libraryID . "/" . $zoteroItem->get("key"), 'type' => $cslType ); // get all text variables (there must be a better way) // TODO: does citeproc-js permit short forms? foreach (self::$zoteroFieldMap as $variable=>$fields) { if ($variable == "URL" && $ignoreURL) continue; foreach($fields as $field) { $value = $zoteroItem->get($field); if ($value !== "" && $value !== null) { // Strip enclosing quotes if (preg_match(self::$quotedRegexp, $value)) { $value = substr($value, 1, strlen($value)-2); } $cslItem[$variable] = $value; break; } } } // separate name variables $creators = $zoteroItem->get('creators'); foreach ($creators as $creator) { $creatorType = $creator['creatorType'];// isset(self::$zoteroNameMap[$creatorType]) ? self::$zoteroNameMap[$creatorType] : false; if (!$creatorType) continue; if(isset($creator["name"])){ $nameObj = array('literal' => $creator['name']); } else { $nameObj = array('family' => $creator['lastName'], 'given' => $creator['firstName']); } if (isset($cslItem[$creatorType])) { $cslItem[$creatorType][] = $nameObj; } else { $cslItem[$creatorType] = array($nameObj); } } // get date variables foreach (self::$zoteroDateMap as $key=>$val) { $date = $zoteroItem->get($val); if ($date) { $cslItem[$key] = array("raw" => $date); } } return $cslItem; } } /** * Representation of a Zotero Item * * @package libZotero * @see Zotero_Entry */ class Zotero_Item extends Zotero_Entry { /** * @var int */ public $itemVersion = 0; /** * @var int */ public $itemKey = ''; /** * @var Zotero_Library */ public $owningLibrary = null; /** * @var string */ public $itemType = null; /** * @var string */ public $year = ''; /** * @var string */ public $creatorSummary = ''; /** * @var string */ public $numChildren = 0; /** * @var string */ public $numTags = 0; /** * @var array */ public $childKeys = array(); /** * @var string */ public $parentItemKey = ''; /** * @var array */ public $creators = array(); /** * @var string */ public $createdByUserID = null; /** * @var string */ public $lastModifiedByUserID = null; /** * @var string */ public $notes = array(); /** * @var int Represents the relationship of the child to the parent. 0:file, 1:file, 2:snapshot, 3:web-link */ public $linkMode = null; /** * @var string */ public $mimeType = null; public $parsedJson = null; public $etag = ''; public $writeFailure = null; /** * @var string content node of response useful if formatted bib request and we need to use the raw content */ public $content = null; public $bibContent = null; public $subContents = array(); public $apiObject = array('itemType'=>null, 'tags'=>array(), 'collections'=>array(), 'relations'=>array()); public $pristine = null; /** * @var array */ public static $fieldMap = array( "creator" => "Creator", "itemType" => "Type", "title" => "Title", "dateAdded" => "Date Added", "dateModified" => "Modified", "source" => "Source", "notes" => "Notes", "tags" => "Tags", "attachments" => "Attachments", "related" => "Related", "url" => "URL", "rights" => "Rights", "series" => "Series", "volume" => "Volume", "issue" => "Issue", "edition" => "Edition", "place" => "Place", "publisher" => "Publisher", "pages" => "Pages", "ISBN" => "ISBN", "publicationTitle" => "Publication", "ISSN" => "ISSN", "date" => "Date", "section" => "Section", "callNumber" => "Call Number", "archiveLocation" => "Loc. in Archive", "distributor" => "Distributor", "extra" => "Extra", "journalAbbreviation" => "Journal Abbr", "DOI" => "DOI", "accessDate" => "Accessed", "seriesTitle" => "Series Title", "seriesText" => "Series Text", "seriesNumber" => "Series Number", "institution" => "Institution", "reportType" => "Report Type", "code" => "Code", "session" => "Session", "legislativeBody" => "Legislative Body", "history" => "History", "reporter" => "Reporter", "court" => "Court", "numberOfVolumes" => "# of Volumes", "committee" => "Committee", "assignee" => "Assignee", "patentNumber" => "Patent Number", "priorityNumbers" => "Priority Numbers", "issueDate" => "Issue Date", "references" => "References", "legalStatus" => "Legal Status", "codeNumber" => "Code Number", "artworkMedium" => "Medium", "number" => "Number", "artworkSize" => "Artwork Size", "libraryCatalog" => "Library Catalog", "videoRecordingType" => "Recording Type", "interviewMedium" => "Medium", "letterType" => "Type", "manuscriptType" => "Type", "mapType" => "Type", "scale" => "Scale", "thesisType" => "Type", "websiteType" => "Website Type", "audioRecordingType" => "Recording Type", "label" => "Label", "presentationType" => "Type", "meetingName" => "Meeting Name", "studio" => "Studio", "runningTime" => "Running Time", "network" => "Network", "postType" => "Post Type", "audioFileType" => "File Type", "version" => "Version", "system" => "System", "company" => "Company", "conferenceName" => "Conference Name", "encyclopediaTitle" => "Encyclopedia Title", "dictionaryTitle" => "Dictionary Title", "language" => "Language", "programmingLanguage" => "Language", "university" => "University", "abstractNote" => "Abstract", "websiteTitle" => "Website Title", "reportNumber" => "Report Number", "billNumber" => "Bill Number", "codeVolume" => "Code Volume", "codePages" => "Code Pages", "dateDecided" => "Date Decided", "reporterVolume" => "Reporter Volume", "firstPage" => "First Page", "documentNumber" => "Document Number", "dateEnacted" => "Date Enacted", "publicLawNumber" => "Public Law Number", "country" => "Country", "applicationNumber" => "Application Number", "forumTitle" => "Forum/Listserv Title", "episodeNumber" => "Episode Number", "blogTitle" => "Blog Title", "caseName" => "Case Name", "nameOfAct" => "Name of Act", "subject" => "Subject", "proceedingsTitle" => "Proceedings Title", "bookTitle" => "Book Title", "shortTitle" => "Short Title", "docketNumber" => "Docket Number", "numPages" => "# of Pages" ); /** * @var array */ public static $typeMap = array( "note" => "Note", "attachment" => "Attachment", "book" => "Book", "bookSection" => "Book Section", "journalArticle" => "Journal Article", "magazineArticle" => "Magazine Article", "newspaperArticle" => "Newspaper Article", "thesis" => "Thesis", "letter" => "Letter", "manuscript" => "Manuscript", "interview" => "Interview", "film" => "Film", "artwork" => "Artwork", "webpage" => "Web Page", "report" => "Report", "bill" => "Bill", "case" => "Case", "hearing" => "Hearing", "patent" => "Patent", "statute" => "Statute", "email" => "E-mail", "map" => "Map", "blogPost" => "Blog Post", "instantMessage" => "Instant Message", "forumPost" => "Forum Post", "audioRecording" => "Audio Recording", "presentation" => "Presentation", "videoRecording" => "Video Recording", "tvBroadcast" => "TV Broadcast", "radioBroadcast" => "Radio Broadcast", "podcast" => "Podcast", "computerProgram" => "Computer Program", "conferencePaper" => "Conference Paper", "document" => "Document", "encyclopediaArticle" => "Encyclopedia Article", "dictionaryEntry" => "Dictionary Entry", ); /** * @var array */ public static $creatorMap = array( "author" => "Author", "contributor" => "Contributor", "editor" => "Editor", "translator" => "Translator", "seriesEditor" => "Series Editor", "interviewee" => "Interview With", "interviewer" => "Interviewer", "director" => "Director", "scriptwriter" => "Scriptwriter", "producer" => "Producer", "castMember" => "Cast Member", "sponsor" => "Sponsor", "counsel" => "Counsel", "inventor" => "Inventor", "attorneyAgent" => "Attorney/Agent", "recipient" => "Recipient", "performer" => "Performer", "composer" => "Composer", "wordsBy" => "Words By", "cartographer" => "Cartographer", "programmer" => "Programmer", "reviewedAuthor" => "Reviewed Author", "artist" => "Artist", "commenter" => "Commenter", "presenter" => "Presenter", "guest" => "Guest", "podcaster" => "Podcaster" ); public function __construct($entryNode=null, $library=null) { if(!$entryNode){ return; } elseif(is_string($entryNode)){ $xml = $entryNode; $doc = new DOMDocument(); $doc->loadXml($xml); $entryNode = $doc->getElementsByTagName('entry')->item(0); } parent::__construct($entryNode); //check if we have multiple subcontent nodes $subcontentNodes = $entryNode->getElementsByTagNameNS("http://zotero.org/ns/api", "subcontent"); // Extract the zapi elements: object key, version, itemType, year, numChildren, numTags $this->itemKey = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'key')->item(0)->nodeValue; $this->itemVersion = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'version')->item(0)->nodeValue; $this->itemType = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'itemType')->item(0)->nodeValue; // Look for numTags node // this may be always present in v2 api $numTagsNode = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', "numTags")->item(0); if($numTagsNode){ $this->numTags = $numTagsNode->nodeValue; } // Look for year node $yearNode = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', "year")->item(0); if($yearNode){ $this->year = $yearNode->nodeValue; } // Look for numChildren node $numChildrenNode = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', "numChildren")->item(0); if($numChildrenNode){ $this->numChildren = $numChildrenNode->nodeValue; } // Look for creatorSummary node - only present if there are non-empty creators $creatorSummaryNode = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', "creatorSummary")->item(0); if($creatorSummaryNode){ $this->creatorSummary = $creatorSummaryNode->nodeValue; } // pull out and parse various subcontent nodes, or parse the single content node if($subcontentNodes->length > 0){ for($i = 0; $i < $subcontentNodes->length; $i++){ $scnode = $subcontentNodes->item($i); $this->parseContentNode($scnode); } } else{ $contentNode = $entryNode->getElementsByTagName('content')->item(0); $this->parseContentNode($contentNode); } if($library !== null){ $this->associateWithLibrary($library); } } public function parseContentNode($node){ $type = $node->getAttributeNS('http://zotero.org/ns/api', 'type'); if($type == 'application/json' || $type == 'json'){ $this->pristine = json_decode($node->nodeValue, true); $this->apiObject = json_decode($node->nodeValue, true); $this->apiObj = &$this->apiObject; if(isset($this->apiObject['creators'])){ $this->creators = $this->apiObject['creators']; } else{ $this->creators = array(); } $this->itemVersion = isset($this->apiObject['itemVersion']) ? $this->apiObject['itemVersion'] : 0; $this->parentItemKey = isset($this->apiObject['parentItem']) ? $this->apiObject['parentItem'] : false; if($this->itemType == 'attachment'){ $this->mimeType = $this->apiObject['contentType']; $this->translatedMimeType = Zotero_Lib_Utils::translateMimeType($this->mimeType); } if(array_key_exists('linkMode', $this->apiObject)){ $this->linkMode = $this->apiObject['linkMode']; } $this->synced = true; } elseif($type == 'bib'){ $bibNode = $node->getElementsByTagName('div')->item(0); $this->bibContent = $bibNode->ownerDocument->saveXML($bibNode); } $contentString = ''; $childNodes = $node->childNodes; foreach($childNodes as $childNode){ $contentString .= $childNode->ownerDocument->saveXML($childNode); } $this->subContents[$type] = $contentString; } public function initItemFromTemplate($template){ $this->itemVersion = 0; $this->itemType = $template['itemType']; $this->itemKey = ''; $this->pristine = $template; $this->apiObject = $template; } public function get($key){ switch($key){ case 'key': case 'itemKey': return $this->itemKey; case 'itemVersion': case 'version': return $this->itemVersion; case 'title': return $this->title; case 'creatorSummary': return $this->creatorSummary; case 'year': return $this->year; case 'parentItem': case 'parentItemKey': return $this->parentItemKey; } if(array_key_exists($key, $this->apiObject)){ return $this->apiObject[$key]; } if(property_exists($this, $key)){ return $this->$key; } return null; } public function set($key, $val){ if(array_key_exists($key, $this->apiObject)){ $this->apiObject[$key] = $val; } switch($key){ case "itemKey": case "key": $this->itemKey = $val; $this->apiObject['itemKey'] = $val; break; case "itemVersion": case "version": $this->itemVersion = $val; $this->apiObject["itemVersion"] = $val; break; case "title": $this->title = $val; break; case "itemType": $this->itemType = $val; //TODO: translate api object to new item type break; case "linkMode": //TODO: something here? break; case "deleted": $this->apiObject["deleted"] = $val; break; case "parentItem": case "parentKey": case "parentItemKey": if( $val === '' ){ $val = false; } $this->parentItemKey = $val; $this->apiObject["parentItem"] = $val; break; } } public function addCreator($creatorArray){ $this->creators[] = $creatorArray; $this->apiObject['creators'][] = $creatorArray; } public function updateItemObject(){ return $this->writeApiObject(); } public function newItemObject(){ $newItem = $this->apiObject; $newCreatorsArray = array(); if(isset($newItem['creators'])) { foreach($newItem['creators'] as $creator){ if($creator['creatorType']){ if(empty($creator['name']) && empty($creator['firstName']) && empty($creator['lastName'])){ continue; } else{ $newCreatorsArray[] = $creator; } } } $newItem['creators'] = $newCreatorsArray; } return $newItem; } public function isAttachment(){ if($this->itemType == 'attachment'){ return true; } } public function hasFile(){ if(!$this->isAttachment()){ return false; } $hasEnclosure = isset($this->links['enclosure']); $linkMode = $this->apiObject['linkMode']; if($hasEnclosure && ($linkMode == 0 || $linkMode == 1)){ return true; } } public function attachmentIsSnapshot(){ if(!isset($this->links['enclosure'])) return false; if(!isset($this->links['enclosure']['text/html'])) return false; $tail = substr($this->links['enclosure']['text/html']['href'], -4); if($tail == "view") return true; return false; } public function json(){ return json_encode($this->apiObject()); } public function formatItemField($field){ switch($field){ case "title": return htmlspecialchars($this->title); break; case "creator": if(isset($this->creatorSummary)){ return htmlspecialchars($this->creatorSummary); } else{ return ''; } break; case "dateModified": case "dateUpdated": return htmlspecialchars($this->dateUpdated); break; case "dateAdded": return htmlspecialchars($this->dateAdded); break; default: if(isset($this->apiObject[$field])){ return htmlspecialchars($this->apiObject[$field]); } else{ return ''; } } } public function compareItem($otherItem){ $diff = array_diff_assoc($this->apiObject, $otherItem->apiObject); return $diff; } public function addToCollection($collection){ if(is_string($collection)){ $collectionKey = $collection; } else { $collectionKey = $collection->get('collectionKey'); } $memberCollectionKeys = $this->get('collections'); if(!is_array($memberCollectionKeys)){ $memberCollectionKeys = array($collectionKey); $this->set('collections', $memberCollectionKeys); } else { if(!in_array($collectionKey, $memberCollectionKeys)) { $memberCollectionKeys[] = $collectionKey; $this->set('collections', $memberCollectionKeys); } } } public function removeFromCollection($collection){ if(is_string($collection)){ $collectionKey = $collection; } else { $collectionKey = $collection->get('collectionKey'); } $memberCollectionKeys = $this->get('collections'); if(!is_array($memberCollectionKeys)){ $memberCollectionKeys = array($collectionKey); $this->set('collections', $memberCollectionKeys); } else { $ind = array_search($collectionKey, $memberCollectionKeys); if($ind !== false){ array_splice($memberCollectionKeys, $ind, 1); $this->set('collections', $memberCollectionKeys); } } } public function addTag($newtagname, $type=null){ $itemTags = $this->get('tags'); //assumes we'll get an array foreach($itemTags as $tag){ if(is_string($tag) && $tag == $newtagname){ return; } elseif(is_array($tag) && isset($tag['tag']) && $tag['tag'] == $newtagname) { return; } } if($type !== null){ $itemTags[] = array('tag'=>$newtagname, 'type'=>$type); } else { $itemTags[] = array('tag'=>$newtagname); } $this->set('tags', $itemTags); } public function removeTag($rmtagname){ $itemTags = $this->get('tags'); //assumes we'll get an array foreach($itemTags as $ind=>$tag){ if( (is_string($tag) && $tag == $rmtagname) || (is_array($tag) && isset($tag['tag']) && $tag['tag'] == $rmtagname) ){ array_splice($itemTags, $ind, 1); $this->set('tags', $itemTags); return; } } } public function addNote($noteItem){ $this->notes[] = $noteItem; } public function uploadFile(){ } public function uploadChildAttachment(){ } public function writeApiObject(){ $updateItem = array_merge($this->pristine, $this->apiObject); if(empty($updateItem['creators'])){ return $updateItem; } $newCreators = array(); foreach($updateItem['creators'] as $creator){ if(empty($creator['name']) && empty($creator['firstName']) && empty($creator['lastName'])){ continue; } else { $newCreators[] = $creator; } } $updateItem['creators'] = $newCreators; return $updateItem; } public function writePatch(){ } public function trashItem(){ $this->set('deleted', 1); } public function untrashItem(){ $this->set('deleted', 0); } public function save() { return $this->owningLibrary->items->writeItems(array($this)); } public function getChildren(){ //short circuit if has item has no children if(!($this->numChildren)){//} || (this.parentItemKey !== false)){ return array(); } $config = array('target'=>'children', 'libraryType'=>$this->owningLibrary->libraryType, 'libraryID'=>$this->owningLibrary->libraryID, 'itemKey'=>$this->itemKey, 'content'=>'json'); $requestUrl = $this->owningLibrary->apiRequestString($config); $response = $this->owningLibrary->_request($requestUrl, 'GET'); //load response into item objects $fetchedItems = array(); if($response->isError()){ return false; throw new Exception("Error fetching items"); } $feed = new Zotero_Feed($response->getRawBody()); $fetchedItems = $this->owningLibrary->items->addItemsFromFeed($feed); return $fetchedItems; } public function getCSLItem(){ return Zotero_Cite::convertItem($this); } } /** * Representation of a Zotero Group * * @package libZotero * @see Zotero_Entry */ class Zotero_Group extends Zotero_Entry { /** * @var array */ public $properties; /** * @var int */ public $id; /** * @var int */ public $groupID; /** * @var int */ public $owner; public $ownerID; /** * @var string */ public $type; /** * @var string */ public $name; /** * @var string */ public $libraryEditing; /** * @var string */ public $libraryReading; /** * @var string */ public $fileEditing; /** * @var bool */ public $hasImage; /** * @var string */ public $description; /** * @var array */ public $disciplines; /** * @var bool */ public $enableComments; /** * @var string */ public $url = ''; /** * @var array */ public $adminIDs; /** * @var array */ public $memberIDs; public function __construct($entryNode = null) { if(!$entryNode){ return; } elseif(is_string($entryNode)){ $xml = $entryNode; $doc = new DOMDocument(); $doc->loadXml($xml); $entryNode = $doc->getElementsByTagName('entry')->item(0); } parent::__construct($entryNode); if(!$entryNode){ return; } $contentNode = $entryNode->getElementsByTagName('content')->item(0); $contentType = parent::getContentType($entryNode); if($contentType == 'application/json'){ $this->apiObject = json_decode($contentNode->nodeValue, true); //$this->etag = $contentNode->getAttribute('etag'); $this->name = $this->apiObject['name']; $this->ownerID = $this->apiObject['owner']; $this->owner = $this->ownerID; $this->groupType = $this->apiObject['type']; $this->description = $this->apiObject['description']; $this->url = $this->apiObject['url']; $this->libraryEditing = $this->apiObject['libraryEditing']; $this->libraryReading = $this->apiObject['libraryReading']; $this->fileEditing = $this->apiObject['fileEditing']; } if(!empty($this->apiObject['admins'])){ $this->adminIDs = $this->apiObject['admins']; } else { $this->adminIDs = array(); } if($this->ownerID){ $this->adminIDs[] = $this->ownerID; } if(!empty($this->apiObject['members'])){ $this->memberIDs = $this->apiObject['members']; } else{ $this->memberIDs = array(); } $this->numItems = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'numItems')->item(0)->nodeValue; $contentNodes = $entryNode->getElementsByTagName("content"); if($contentNodes->length > 0){ $cNode = $contentNodes->item(0); if($cNode->getAttribute('type') == 'application/json'){ $jsonObject = json_decode($cNode->nodeValue, true); //parse out relevant values from the json and put them on our object $this->name = $jsonObject['name']; $this->ownerID = $jsonObject['owner']; $this->owner = $this->ownerID; $this->type = $jsonObject['type']; $this->groupType = $this->type; $this->description = $jsonObject['description']; $this->url = $jsonObject['url']; $this->hasImage = isset($jsonObject['hasImage']) ? $jsonObject['hasImage'] : 0; $this->libraryEditing = $jsonObject['libraryEditing']; $this->memberIDs = isset($jsonObject['members']) ? $jsonObject['members'] : array(); $this->members = $this->memberIDs; $this->adminIDs = isset($jsonObject['admins']) ? $jsonObject['admins'] : array(); $this->adminIDs[] = $jsonObject['owner']; $this->admins = $this->adminIDs; } elseif($cNode->getAttribute('type') == 'application/xml'){ $groupElements = $entryNode->getElementsByTagName("group"); $groupElement = $groupElements->item(0); if(!$groupElement) return; $groupAttributes = $groupElement->attributes; $this->properties = array(); foreach($groupAttributes as $attrName => $attrNode){ $this->properties[$attrName] = urldecode($attrNode->value); if($attrName == 'name'){ $this->$attrName = $attrNode->value; } else{ $this->$attrName = urldecode($attrNode->value); } } $this->groupID = $this->properties['id']; $description = $entryNode->getElementsByTagName("description")->item(0); if($description) { $this->properties['description'] = $description->nodeValue; $this->description = $description->nodeValue; } $url = $entryNode->getElementsByTagName("url")->item(0); if($url) { $this->properties['url'] = $url->nodeValue; $this->url = $url->nodeValue; } $this->adminIDs = array(); $admins = $entryNode->getElementsByTagName("admins")->item(0); if($admins){ $this->adminIDs = $admins === null ? array() : explode(" ", $admins->nodeValue); } $this->adminIDs[] = $this->owner; $this->memberIDs = array(); $members = $entryNode->getElementsByTagName("members")->item(0); if($members){ $this->memberIDs = ($members === null ? array() : explode(" ", $members->nodeValue)); } //initially disallow library access $this->userReadable = false; $this->userEditable = false; } } //get groupID from zapi:groupID if available if($entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'groupID')->length > 0){ $this->groupID = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', 'groupID')->item(0)->nodeValue; $this->id = $this->groupID; } else{ //get link nodes and extract groupID $linkNodes = $entryNode->getElementsByTagName("link"); if($linkNodes->length > 0){ for($i = 0; $i < $linkNodes->length; $i++){ $linkNode = $linkNodes->item($i); if($linkNode->getAttribute('rel') == 'self'){ $selfHref = $linkNode->getAttribute('href'); $matches = array(); preg_match('/^https:\/\/.{3,6}\.zotero\.org\/groups\/([0-9]+)$/', $selfHref, $matches); if(isset($matches[1])){ $this->groupID = intval($matches[1]); $this->id = $this->groupID; } } } } } //initially disallow library access $this->userReadable = false; $this->userEditable = false; } public function setProperty($key, $val) { $this->properties[$key] = $val; return $this; } public function updateString() { $doc = new DOMDocument(); $el = $doc->appendChild(new DOMElement('group')); $descriptionString = htmlspecialchars($this->description, ENT_COMPAT | ENT_HTML401, 'UTF-8', false); $el->appendChild(new DOMElement('description', $descriptionString)); $el->appendChild(new DOMElement('url', $this->url)); if($this->groupID){ $el->setAttribute('id', $this->groupID); } $el->setAttribute('owner', $this->ownerID); $el->setAttribute('type', $this->type); $el->setAttribute('name', $this->name); $el->setAttribute('libraryEditing', $this->libraryEditing); $el->setAttribute('libraryReading', $this->libraryReading); $el->setAttribute('fileEditing', $this->fileEditing); $el->setAttribute('hasImage', $this->hasImage); return $doc->saveXML($el); } public function propertiesArray() { $properties = array(); $properties['owner'] = $this->owner; $properties['type'] = $this->type; $properties['name'] = $this->name; $properties['libraryEditing'] = $this->libraryEditing; $properties['libraryReading'] = $this->libraryReading; $properties['fileEditing'] = $this->fileEditing; $properties['hasImage'] = $this->hasImage; $properties['disciplines'] = $this->disciplines; $properties['enableComments'] = $this->enableComments; $properties['description'] = $this->description; return $properties; } public function dataObject() { $jsonItem = new stdClass; //inherited from Entry $jsonItem->title = $this->title; $jsonItem->dateAdded = $this->dateAdded; $jsonItem->dateUpdated = $this->dateUpdated; $jsonItem->id = $this->id; //Group vars $jsonItem->groupID = $this->groupID; $jsonItem->owner = $this->owner; $jsonItem->memberIDs = $this->memberIDs; $jsonItem->adminIDs = $this->adminIDs; $jsonItem->type = $this->type; $jsonItem->name = $this->name; $jsonItem->libraryEditing = $this->libraryEditing; $jsonItem->libraryReading = $this->libraryReading; $jsonItem->hasImage = $this->hadImage; $jsonItem->description = $this->description; $jsonItem->url = $this->url; return $jsonItem; } } /** * Representation of a Zotero Tag * * @package libZotero */ class Zotero_Tag extends Zotero_Entry { /** * @var int */ /* public $tagID; public $libraryID; public $key; public $name; public $dateAdded; public $dateModified; public $type; */ public $numItems = 0; public function __construct($entryNode) { if(!$entryNode){ libZoteroDebug( "no entryNode in tag constructor\n" ); return; } elseif(is_string($entryNode)){ libZoteroDebug( "entryNode is string in tag constructor\n" ); $xml = $entryNode; $doc = new DOMDocument(); libZoteroDebug( $xml ); $doc->loadXml($xml); $entryNode = $doc->getElementsByTagName('entry')->item(0); } parent::__construct($entryNode); $this->name = $this->title; if(!$entryNode){ libZoteroDebug( "second no entryNode in tag constructor\n" ); return; } $numItems = $entryNode->getElementsByTagNameNS('http://zotero.org/ns/api', "numItems")->item(0); if($numItems) { $this->numItems = (int)$numItems->nodeValue; } $tagElements = $entryNode->getElementsByTagName("tag"); $tagElement = $tagElements->item(0); $contentNode = $entryNode->getElementsByTagName('content')->item(0); if($contentNode){ $contentType = $contentNode->getAttribute('type'); if($contentType == 'application/json'){ $this->pristine = json_decode($contentNode->nodeValue, true); $this->apiObject = json_decode($contentNode->nodeValue, true); } elseif($contentType == 'xhtml'){ //$this->parseXhtmlContent($contentNode); } } } public function get($key) { switch($key){ case "tag": case "name": case "title": return $this->name; } if(array_key_exists($key, $this->apiObject)){ return $this->apiObject[$key]; } if(property_exists($this, $key)){ return $this->$key; } return null; } public function dataObject() { $jsonItem = new stdClass; //inherited from Entry $jsonItem->title = $this->title; $jsonItem->dateAdded = $this->dateAdded; $jsonItem->dateUpdated = $this->dateUpdated; $jsonItem->id = $this->id; $jsonItem->properties = $this->properties; return $jsonItem; } } /** * Representation of a Zotero Item Creator * * @package libZotero */ class Zotero_Creator { public $creatorType = null; public $localized = null; public $firstName = null; public $lastName = null; public $name = null; public function getWriteObject(){ if(empty($this->creatorType) || (empty($this->name) && empty($this->firstName) && empty($this->lastName) ) ){ return false; } $a = array('creatorType'=>$this->creatorType); if(!empty($this->name)){ $a['name'] = $this->name; } else{ $a['firstName'] = $this->firstName; $a['lastName'] = $this->lastName; } return $a; } } define('LIBZOTERO_DEBUG', 0); define('ZOTERO_API_VERSION', 2); function libZoteroDebug($m){ if(LIBZOTERO_DEBUG){ echo $m; } return; } /** * Interface to API and storage of a Zotero user or group library * * @package libZotero */ class Zotero_Library { const ZOTERO_URI = 'https://api.zotero.org'; const ZOTERO_WWW_URI = 'http://www.zotero.org'; const ZOTERO_WWW_API_URI = 'http://www.zotero.org/api'; public $_apiKey = ''; protected $_ch = null; protected $_followRedirects = true; public $libraryType = null; public $libraryID = null; public $libraryString = null; public $libraryUrlIdentifier = null; public $libraryBaseWebsiteUrl = null; public $items = null; public $collections = null; public $dirty = null; public $useLibraryAsContainer = true; public $libraryVersion = 0; protected $_lastResponse = null; protected $_lastFeed = null; protected $_cacheResponses = false; protected $_cachettl = 0; protected $_cachePrefix = 'libZotero'; /** * Constructor for Zotero_Library * * @param string $libraryType user|group * @param string $libraryID id for zotero library, unique when combined with libraryType * @param string $libraryUrlIdentifier library identifier used in urls, either ID or slug * @param string $apiKey zotero api key * @param string $baseWebsiteUrl base url to use when generating links to the website version of items * @param string $cachettl cache time to live in seconds, cache disabled if 0 * @return Zotero_Library */ public function __construct($libraryType = null, $libraryID = null, $libraryUrlIdentifier = null, $apiKey = null, $baseWebsiteUrl="http://www.zotero.org", $cachettl=0) { $this->_apiKey = $apiKey; if (!extension_loaded('curl')) { throw new Exception("You need cURL"); } $this->libraryType = $libraryType; $this->libraryID = $libraryID; $this->libraryString = $this->libraryString($this->libraryType, $this->libraryID); $this->libraryUrlIdentifier = $libraryUrlIdentifier; $this->libraryBaseWebsiteUrl = $baseWebsiteUrl . '/'; if($this->libraryType == 'group'){ $this->libraryBaseWebsiteUrl .= 'groups/'; } $this->libraryBaseWebsiteUrl .= $this->libraryUrlIdentifier . '/items'; $this->items = new Zotero_Items(); $this->items->owningLibrary = $this; $this->collections = new Zotero_Collections(); $this->collections->owningLibrary = $this; $this->collections->libraryUrlIdentifier = $this->libraryUrlIdentifier; $this->dirty = false; if($cachettl > 0){ $this->_cachettl = $cachettl; $this->_cacheResponses = true; } } /** * Destructor, closes cURL. */ public function __destruct() { //curl_close($this->_ch); } /** * Set _followRedirect, controlling whether curl automatically follows location header redirects * @param bool $follow automatically follow location header redirect */ public function setFollow($follow){ $this->_followRedirects = $follow; } /** * set the cache time to live after initialization * * @param int $cachettl cache time to live in seconds, 0 disables * @return null */ public function setCacheTtl($cachettl){ if($cachettl == 0){ $this->_cacheResponses = false; $this->_cachettl = 0; } else{ $this->_cacheResponses = true; $this->_cachettl = $cachettl; } } /** * Make http request to zotero api * * @param string $url target api url * @param string $method http method GET|POST|PUT|DELETE * @param string $body request body if write * @param array $headers headers to set on request * @return HTTP_Response */ public function _request($url, $method="GET", $body=NULL, $headers=array(), $basicauth=array()) { libZoteroDebug( "url being requested: " . $url . "\n\n"); $ch = curl_init(); $httpHeaders = array(); //set api version - allowed to be overridden by passed in value if(!isset($headers['Zotero-API-Version'])){ $headers['Zotero-API-Version'] = ZOTERO_API_VERSION; } foreach($headers as $key=>$val){ $httpHeaders[] = "$key: $val"; } //disable Expect header $httpHeaders[] = 'Expect:'; if(!empty($basicauth)){ $passString = $basicauth['username'] . ':' . $basicauth['password']; curl_setopt($ch, CURLOPT_USERPWD, $passString); curl_setopt($ch, CURLOPT_FORBID_REUSE, true); } else{ curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); if($this->_followRedirects){ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); } else{ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); } $umethod = strtoupper($method); switch($umethod){ case "GET": curl_setopt($ch, CURLOPT_HTTPGET, true); break; case "POST": curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "PUT": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "DELETE": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } $gotCached = false; if($this->_cacheResponses && $umethod == 'GET'){ $cachedResponse = apc_fetch($url, $success); if($success){ $responseBody = $cachedResponse['responseBody']; $responseInfo = $cachedResponse['responseInfo']; $zresponse = libZotero_Http_Response::fromString($responseBody); $gotCached = true; } } if(!$gotCached){ $responseBody = curl_exec($ch); $responseInfo = curl_getinfo($ch); //var_dump($responseInfo); $zresponse = libZotero_Http_Response::fromString($responseBody); //Zend Response does not parse out the multiple sets of headers returned when curl automatically follows //a redirect and the new headers are left in the body. Zend_Http_Client gets around this by manually //handling redirects. That may end up being a better solution, but for now we'll just re-read responses //until a non-redirect is read if($this->_followRedirects){ while($zresponse->isRedirect()){ $redirectedBody = $zresponse->getBody(); $zresponse = libZotero_Http_Response::fromString($redirectedBody); } } $saveCached = array( 'responseBody'=>$responseBody, 'responseInfo'=>$responseInfo, ); if($this->_cacheResponses && !($zresponse->isError()) ){ apc_store($url, $saveCached, $this->_cachettl); } } $this->_lastResponse = $zresponse; return $zresponse; } public function proxyHttpRequest($url, $method='GET', $body=null, $headers=array()) { $endPoint = $url; try{ $response = $this->_request($url, $method, $body, $headers); if($response->getStatus() == 303){ //this might not account for GET parameters in the first url depending on the server $newLocation = $response->getHeader("Location"); $reresponse = $this->_request($newLocation, $method, $body, $headers); return $reresponse; } } catch(Exception $e){ $r = new libZotero_Http_Response(500, array(), $e->getMessage()); return $r; } return $response; } public function _cacheSave(){ } public function _cacheLoad(){ } /** * get the last HTTP_Response returned * * @return HTTP_Response */ public function getLastResponse(){ return $this->_lastResponse; } /** * get the last status code from last HTTP_Response returned * * @return HTTP_Response */ public function getLastStatus(){ return $this->_lastResponse->getStatus(); } /** * Get the last Zotero_Feed parsed * * @return Zotero_Feed */ public function getLastFeed(){ return $this->_lastFeed; } /** * Construct a string that uniquely identifies a library * This is not related to the server GUIDs * * @return string */ public static function libraryString($type, $libraryID){ $lstring = ''; if($type == 'user') $lstring = 'u'; elseif($type == 'group') $lstring = 'g'; $lstring .= $libraryID; return $lstring; } /** * generate an api url for a request based on array of parameters * * @param array $params list of parameters that define the request * @param string $base the base api url * @return string */ public function apiRequestUrl($params = array(), $base = Zotero_Library::ZOTERO_URI) { if(!isset($params['target'])){ throw new Exception("No target defined for api request"); } //special case for www based api requests until those methods are mapped for api.zotero if($params['target'] == 'user' || $params['target'] == 'cv'){ $base = Zotero_Library::ZOTERO_WWW_API_URI; } //allow overriding of libraryType and ID in params if they are passed //otherwise use the settings for this instance of library if(!empty($params['libraryType']) && !empty($params['libraryID'])){ $url = $base . '/' . $params['libraryType'] . 's/' . $params['libraryID']; } else{ $url = $base . '/' . $this->libraryType . 's/' . $this->libraryID; } if(!empty($params['collectionKey'])){ if($params['collectionKey'] == 'trash'){ $url .= '/items/trash'; return $url; } else{ $url .= '/collections/' . $params['collectionKey']; } } switch($params['target']){ case 'items': $url .= '/items'; break; case 'item': if(!empty($params['itemKey'])){ $url .= '/items/' . $params['itemKey']; } else{ $url .= '/items'; } break; case 'collections': $url .= '/collections'; break; case 'collection': break; case 'tags': $url .= '/tags'; break; case 'children': $url .= '/items/' . $params['itemKey'] . '/children'; break; case 'itemTemplate': $url = $base . '/items/new'; break; case 'key': $url = $base . '/users/' . $params['userID'] . '/keys/' . $params['apiKey']; break; case 'userGroups': $url = $base . '/users/' . $params['userID'] . '/groups'; break; case 'groups': $url = $base . '/groups'; break; case 'cv': $url .= '/cv'; break; case 'deleted': $url .= '/deleted'; break; default: return false; } if(isset($params['targetModifier'])){ switch($params['targetModifier']){ case 'top': $url .= '/top'; break; case 'children': $url .= '/children'; break; case 'file': if($params['target'] != 'item'){ throw new Exception('Trying to get file on non-item target'); } $url .= '/file'; break; case 'fileview': if($params['target'] != 'item'){ throw new Exception('Trying to get file on non-item target'); } $url .= '/file/view'; break; } } return $url; } /** * generate an api query string for a request based on array of parameters * * @param array $passedParams list of parameters that define the request * @return string */ public function apiQueryString($passedParams=array()){ // Tags query formats // // ?tag=foo // ?tag=foo bar // phrase // ?tag=-foo // negation // ?tag=\-foo // literal hyphen (only for first character) // ?tag=foo&tag=bar // AND // ?tag=foo&tagType=0 // ?tag=foo bar || bar&tagType=0 $queryParamOptions = array('start', 'limit', 'order', 'sort', 'content', 'q', 'itemType', 'locale', 'key', 'itemKey', 'tag', 'tagType', 'style', 'format', 'linkMode', 'linkwrap' ); //build simple api query parameters object if((!isset($passedParams['key'])) && $this->_apiKey){ $passedParams['key'] = $this->_apiKey; } $queryParams = array(); foreach($queryParamOptions as $i=>$val){ if(isset($passedParams[$val]) && ($passedParams[$val] != '')) { //check if itemKey belongs in the url or the querystring if($val == 'itemKey' && isset($passedParams['target']) && ($passedParams['target'] != 'items') ) continue; $queryParams[$val] = $passedParams[$val]; } } $queryString = '?'; ksort($queryParams); $queryParamsArray = array(); foreach($queryParams as $index=>$value){ if(is_array($value)){ foreach($value as $key=>$val){ if(is_string($val) || is_int($val)){ $queryParamsArray[] = urlEncode($index) . '=' . urlencode($val); } } } elseif(is_string($value) || is_int($value)){ $queryParamsArray[] = urlencode($index) . '=' . urlencode($value); } } $queryString .= implode('&', $queryParamsArray); return $queryString; } public function apiRequestString($params = array(), $base = Zotero_Library::ZOTERO_URI) { return $this->apiRequestUrl($params) . $this->apiQueryString($params); } /** * parse a query string and separate into parameters * without using the php way of representing query strings * * @param string $query * @return array */ public function parseQueryString($query){ $params = explode('&', $query); $aparams = array(); foreach($params as $val){ $t = explode('=', $val); $aparams[urldecode($t[0])] = urldecode($t[1]); } return $aparams; } /** * Load all collections in the library into the collections container * * @param array $params list of parameters limiting the request * @return null */ public function fetchAllCollections($params = array()){ return $this->collections->fetchAllCollections($params); } /** * Load 1 request worth of collections in the library into the collections container * * @param array $params list of parameters limiting the request * @return null */ public function fetchCollections($params = array()){ return $this->collections->fetchCollections($params); } /** * Load a single collection by collectionKey * * @param string $collectionKey * @return Zotero_Collection */ public function fetchCollection($collectionKey){ return $this->collections->fetchCollection($collectionKey); } /** * Make a single request loading top level items * * @param array $params list of parameters that define the request * @return array of fetched items */ public function fetchItemsTop($params=array()){ $params['targetModifier'] = 'top'; return $this->fetchItems($params); } /** * Make a single request loading item keys * * @param array $params list of parameters that define the request * @return array of fetched items */ public function fetchItemKeys($params=array()){ $fetchedKeys = array(); $aparams = array_merge(array('target'=>'items', 'format'=>'keys'), array('key'=>$this->_apiKey), $params); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl); if($response->isError()){ throw new Exception("Error fetching item keys"); } $body = $response->getRawBody(); $fetchedKeys = explode("\n", trim($body) ); return $fetchedKeys; } /** * Make a single request loading items in the trash * * @param array $params list of parameters additionally filtering the request * @return array of fetched items */ public function fetchTrashedItems($params=array()){ $fetchedItems = array(); $aparams = array_merge(array('content'=>'json'), array('key'=>$this->_apiKey), $params, array('collectionKey'=>'trash')); $reqUrl = $this->apiRequestString($aparams); libZoteroDebug( "\n"); libZoteroDebug( $reqUrl . "\n" ); //die; $response = $this->_request($reqUrl); if($response->isError()){ throw new Exception("Error fetching items"); } $feed = new Zotero_Feed($response->getRawBody()); $this->_lastFeed = $feed; $fetchedItems = $this->items->addItemsFromFeed($feed); return $fetchedItems; } /** * Make a single request loading a list of items * * @param array $params list of parameters that define the request * @return array of fetched items */ public function fetchItems($params = array()){ $fetchedItems = array(); $aparams = array_merge(array('target'=>'items', 'content'=>'json'), array('key'=>$this->_apiKey), $params); $reqUrl = $this->apiRequestString($aparams); libZoteroDebug( $reqUrl . "\n" ); $response = $this->_request($reqUrl); if($response->isError()){ throw new Exception("Error fetching items"); } $feed = new Zotero_Feed($response->getRawBody()); $this->_lastFeed = $feed; $fetchedItems = $this->items->addItemsFromFeed($feed); return $fetchedItems; } /** * Make a single request loading a list of items * * @param string $itemKey key of item to stop retrieval at * @param array $params list of parameters that define the request * @return array of fetched items */ public function fetchItemsAfter($itemKey, $params = array()){ $fetchedItems = array(); $itemKeys = $this->fetchItemKeys($params); if($itemKey != ''){ $index = array_search($itemKey, $itemKeys); if($index == false){ return array(); } } $offset = 0; while($offset < $index){ if($index - $offset > 50){ $uindex = $offset + 50; } else{ $uindex = $index; } $itemKeysToFetch = array_slice($itemKeys, 0, $uindex); $offset == $uindex; $params['itemKey'] = implode(',', $itemKeysToFetch); $fetchedSet = $this->fetchItems($params); $fetchedItems = array_merge($fetchedItems, $fetchedSet); } return $fetchedItems; } /** * Load a single item by itemKey * * @param string $itemKey * @return Zotero_Item */ public function fetchItem($itemKey, $params=array()){ $aparams = array_merge(array('target'=>'item', 'content'=>'json', 'itemKey'=>$itemKey), $params); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; throw new Exception("Error fetching items"); } $entry = Zotero_Lib_Utils::getFirstEntryNode($response->getRawBody()); if($entry == null) return false; $item = new Zotero_Item($entry, $this); $this->items->addItem($item); return $item; } /** * Load a single item bib by itemKey * * @param string $itemKey * @return Zotero_Item */ public function fetchItemBib($itemKey, $style){ //TODO:parse correctly and return just bib $aparams = array('target'=>'item', 'content'=>'bib', 'itemKey'=>$itemKey); if($style){ $aparams['style'] = $style; } $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; throw new Exception("Error fetching items"); } $entry = Zotero_Lib_Utils::getFirstEntryNode($response->getRawBody()); if($entry == null) return false; $item = new Zotero_Item($entry, $this); $this->items->addItem($item); return $item; } /** * construct the url for file download of the item if it exists * * @param string $itemKey * @return string */ public function itemDownloadLink($itemKey){ $aparams = array('target'=>'item', 'itemKey'=>$itemKey, 'targetModifier'=>'file'); return $this->apiRequestString($aparams); } /** * Write a modified item back to the api * * @param Zotero_Item $item the modified item to be written back * @return Zotero_Response */ public function writeUpdatedItem($item){ if($item->owningLibrary == null) { $item->associateWithLibrary($this); } return $this->items->writeItem($item); } public function uploadNewAttachedFile($item, $fileContents, $fileinfo=array()){ //get upload authorization $aparams = array('target'=>'item', 'targetModifier'=>'file', 'itemKey'=>$item->itemKey); $reqUrl = $this->apiRequestString($aparams); $postData = "md5={$fileinfo['md5']}&filename={$fileinfo['filename']}&filesize={$fileinfo['filesize']}&mtime={$fileinfo['mtime']}"; //$postData = $fileinfo; libZoteroDebug("uploadNewAttachedFile postData: $postData"); $headers = array('If-None-Match'=>'*'); $response = $this->_request($reqUrl, 'POST', $postData, $headers); if($response->getStatus() == 200){ libZoteroDebug("200 response from upload authorization "); $body = $response->getRawBody(); $resObject = json_decode($body, true); if(!empty($resObject['exists'])){ libZoteroDebug("File already exists "); return true;//api already has a copy, short-circuit with positive result } else{ libZoteroDebug("uploading filecontents padded as specified "); //upload file padded with information we just got $uploadPostData = $resObject['prefix'] . $fileContents . $resObject['suffix']; libZoteroDebug($uploadPostData); $uploadHeaders = array('Content-Type'=>$resObject['contentType']); $uploadResponse = $this->_request($resObject['url'], 'POST', $uploadPostData, $uploadHeaders); if($uploadResponse->getStatus() == 201){ libZoteroDebug("got upload response 201 "); //register upload $ruparams = array('target'=>'item', 'targetModifier'=>'file', 'itemKey'=>$item->itemKey); $registerReqUrl = $this->apiRequestUrl($ruparams) . $this->apiQueryString($ruparams); //$registerUploadData = array('upload'=>$resObject['uploadKey']); $registerUploadData = "upload=" . $resObject['uploadKey']; libZoteroDebug("<br />Register Upload Data <br /><br />"); $regUpResponse = $this->_request($registerReqUrl, 'POST', $registerUploadData, array('If-None-Match'=>'*')); if($regUpResponse->getStatus() == 204){ libZoteroDebug("successfully registered upload "); return true; } else{ return false; } } else{ return false; } } } else{ libZoteroDebug("non-200 response from upload authorization "); return false; } } public function createAttachmentItem($parentItem, $attachmentInfo){ //get attachment template $templateItem = $this->getTemplateItem('attachment', 'imported_file'); $templateItem->parentKey = $parentItem->itemKey; //create child item return $this->createItem($templateItem); } /** * Make API request to create a new item * * @param Zotero_Item $item the newly created Zotero_Item to be added to the server * @return Zotero_Response */ public function createItem($item){ $this->items->writeItems(array($item)); } /** * Get a template for a new item of a certain type * * @param string $itemType type of item the template is for * @return Zotero_Item */ public function getTemplateItem($itemType, $linkMode=null){ $newItem = new Zotero_Item(null, $this); $aparams = array('target'=>'itemTemplate', 'itemType'=>$itemType); if($linkMode){ $aparams['linkMode'] = $linkMode; } $reqUrl = $this->apiRequestString($aparams); libZoteroDebug($reqUrl); $response = $this->_request($reqUrl); if($response->isError()){ throw new Exception("API error retrieving item template - {$response->getStatus()} : {$response->getRawBody()}"); } libZoteroDebug($response->getRawBody()); $itemTemplate = json_decode($response->getRawBody(), true); $newItem->initItemFromTemplate($itemTemplate); return $newItem; } /** * Add child notes to a parent item * * @param Zotero_Item $parentItem the item the notes are to be children of * @param Zotero_Item|array $noteItem the note item or items * @return array of Zotero_Item */ public function addNotes($parentItem, $noteItem){ $aparams = array('target'=>'items'); $reqUrl = $this->apiRequestString($aparams); $noteWriteItems = array(); if(!is_array($noteItem)){ if(get_class($noteItem) == "Zotero_Item"){ $noteWriteItems[] = $noteItem; } else { throw new Exception("Unexpected note item type"); } } else{ foreach($noteItem as $nitem){ $noteWriteItems[] = $nitem; } } //set parentItem for all notes $parentItemKey = $parentItem->get("itemKey"); foreach($noteWriteItems as $nitem){ $nitem->set("parentItem", $parentItemKey); } return $this->items->writeItems($noteWriteItems); } /** * Create a new collection in this library * * @param string $name the name of the new item * @param Zotero_Item $parent the optional parent collection for the new collection * @return Zotero_Response */ public function createCollection($name, $parent = false){ $collection = new Zotero_Collection(null, $this); $collection->set('name', $name); $collection->set('parentCollectionKey', $parent); return $this->collections->writeCollection($collection); } /** * Delete a collection from the library * * @param Zotero_Collection $collection collection object to be deleted * @return Zotero_Response */ public function removeCollection($collection){ $aparams = array('target'=>'collection', 'collectionKey'=>$collection->collectionKey); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'DELETE', null, array('If-Unmodified-Since-Version'=>$collection->get('collectionVersion'))); return $response; } /** * Add Items to a collection * * @param Zotero_Collection $collection to add items to * @param array $items * @return Zotero_Response */ public function addItemsToCollection($collection, $items){ foreach($items as $item){ $item->addToCollection($collection); } $updatedItems = $this->items->writeItems($items); return $updatedItems; } /** * Remove items from a collection * * @param Zotero_Collection $collection to add items to * @param array $items * @return array $removedItemKeys list of itemKeys successfully removed */ public function removeItemsFromCollection($collection, $items){ foreach($items as $item){ $item->removeFromCollection($collection); } $updatedItems = $this->items->writeItems($items); return $updatedItems; } /** * Remove a single item from a collection * * @param Zotero_Collection $collection to add items to * @param Zotero_Item $item * @return Zotero_Response */ public function removeItemFromCollection($collection, $item){ $item->removeFromCollection($collection); return $this->items->writeItems(array($item)); } /** * Write a modified collection object back to the api * * @param Zotero_Collection $collection to modify * @return Zotero_Response */ public function writeUpdatedCollection($collection){ return $this->collections->writeUpdatedCollection($collection); } /** * Permanently delete an item from the API * * @param Zotero_Item $item * @return Zotero_Response */ public function deleteItem($item){ $this->items->deleteItem($item); } public function deleteItems($items, $version=null){ $this->items->deleteItems($items, $version); } /** * Put an item in the trash * * @param Zotero_Item $item * @return Zotero_Response */ public function trashItem($item){ return $item->trashItem(); } /** * Fetch any child items of a particular item * * @param Zotero_Item $item * @return array $fetchedItems */ public function fetchItemChildren($item){ if(is_string($item)){ $itemKey = $item; } else { $itemKey = $item->itemKey; } $aparams = array('target'=>'children', 'itemKey'=>$itemKey, 'content'=>'json'); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); //load response into item objects $fetchedItems = array(); if($response->isError()){ return false; throw new Exception("Error fetching items"); } $feed = new Zotero_Feed($response->getRawBody()); $this->_lastFeed = $feed; $fetchedItems = $this->items->addItemsFromFeed($feed); return $fetchedItems; } /** * Get the list of itemTypes the API knows about * * @return array $itemTypes */ public function getItemTypes(){ $reqUrl = Zotero_Library::ZOTERO_URI . 'itemTypes'; $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ throw new Zotero_Exception("failed to fetch itemTypes"); } $itemTypes = json_decode($response->getBody(), true); return $itemTypes; } /** * Get the list of item Fields the API knows about * * @return array $itemFields */ public function getItemFields(){ $reqUrl = Zotero_Library::ZOTERO_URI . 'itemFields'; $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ throw new Zotero_Exception("failed to fetch itemFields"); } $itemFields = json_decode($response->getBody(), true); return $itemFields; } /** * Get the creatorTypes associated with an itemType * * @param string $itemType * @return array $creatorTypes */ public function getCreatorTypes($itemType){ $reqUrl = Zotero_Library::ZOTERO_URI . 'itemTypeCreatorTypes?itemType=' . $itemType; $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ throw new Zotero_Exception("failed to fetch creatorTypes"); } $creatorTypes = json_decode($response->getBody(), true); return $creatorTypes; } /** * Get the creator Fields the API knows about * * @return array $creatorFields */ public function getCreatorFields(){ $reqUrl = Zotero_Library::ZOTERO_URI . 'creatorFields'; $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ throw new Zotero_Exception("failed to fetch creatorFields"); } $creatorFields = json_decode($response->getBody(), true); return $creatorFields; } /** * Fetch all the tags defined by the passed parameters * * @param array $params list of parameters defining the request * @return array $tags */ public function fetchAllTags($params){ $aparams = array_merge(array('target'=>'tags', 'content'=>'json', 'limit'=>50), $params); $reqUrl = $this->apiRequestString($aparams); do{ $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; } $doc = new DOMDocument(); $doc->loadXml($response->getBody()); $feed = new Zotero_Feed($doc); $entries = $doc->getElementsByTagName('entry'); $tags = array(); foreach($entries as $entry){ $tag = new Zotero_Tag($entry); $tags[] = $tag; } if(isset($feed->links['next'])){ $nextUrl = $feed->links['next']['href']; $parsedNextUrl = parse_url($nextUrl); $parsedNextUrl['query'] = $this->apiQueryString(array_merge(array('key'=>$this->_apiKey), $this->parseQueryString($parsedNextUrl['query']) ) ); $reqUrl = $parsedNextUrl['scheme'] . '://' . $parsedNextUrl['host'] . $parsedNextUrl['path'] . $parsedNextUrl['query']; } else{ $reqUrl = false; } } while($reqUrl); return $tags; } /** * Make a single request for Zotero tags in this library defined by the passed parameters * * @param array $params list of parameters defining the request * @return array $tags */ public function fetchTags($params = array()){ $aparams = array_merge(array('target'=>'tags', 'content'=>'json', 'limit'=>50), $params); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ libZoteroDebug( $response->getMessage() . "\n" ); libZoteroDebug( $response->getBody() ); return false; } $entries = Zotero_Lib_Utils::getEntryNodes($response->getRawBody()); $tags = array(); foreach($entries as $entry){ $tag = new Zotero_Tag($entry); $tags[] = $tag; } return $tags; } /** * Get the permissions a key has for a library * if no key is passed use the currently set key for the library * * @param int|string $userID * @param string $key * @return array $keyPermissions */ public function getKeyPermissions($userID=null, $key=false) { if($userID === null){ $userID = $this->libraryID; } if($key == false){ if($this->_apiKey == '') { false; } $key = $this->_apiKey; } $reqUrl = $this->apiRequestUrl(array('target'=>'key', 'apiKey'=>$key, 'userID'=>$userID)); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; } $body = $response->getBody(); $doc = new DOMDocument(); $doc->loadXml($body); $keyNode = $doc->getElementsByTagName('key')->item(0); $keyPerms = $this->parseKey($keyNode); return $keyPerms; } /** * Parse a key response into an array * * @param $keyNode DOMNode from key response * @return array $keyPermissions */ public function parseKey($keyNode){ return Zotero_Lib_Utils::parseKey($keyNode); } /** * Get groups a user belongs to * * @param string $userID * @return array $groups */ public function fetchGroups($userID=''){ if($userID == ''){ $userID = $this->libraryID; } $aparams = array('target'=>'userGroups', 'userID'=>$userID, 'content'=>'json', 'order'=>'title'); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ libZoteroDebug( $response->getStatus() ); libZoteroDebug( $response->getBody() ); return false; } $entries = Zotero_Lib_Utils::getEntryNodes($response->getRawBody()); $groups = array(); foreach($entries as $entry){ $group = new Zotero_Group($entry); $groups[] = $group; } return $groups; } /** * Get recently created public groups * * @return array $groups */ public function fetchRecentGroups(){ return array(); $aparams = array('target'=>'groups', 'limit'=>'10', 'content'=>'json', 'order'=>'dateAdded', 'sort'=>'desc', 'fq'=>'-GroupType:Private'); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; } $entries = Zotero_Lib_Utils::getEntryNodes($response->getRawBody()); $groups = array(); foreach($entries as $entry){ $group = new Zotero_Group($entry); $groups[] = $group; } return $groups; } /** * Get CV for a user * * @param string $userID * @return array $groups */ public function getCV($userID=''){ if($userID == '' && $this->libraryType == 'user'){ $userID = $this->libraryID; } $aparams = array('target'=>'cv', 'libraryType'=>'user', 'libraryID'=>$userID, 'linkwrap'=>'1'); $reqUrl = $this->apiRequestString($aparams); $response = $this->_request($reqUrl, 'GET'); if($response->isError()){ return false; } $doc = new DOMDocument(); $doc->loadXml($response->getBody()); $sectionNodes = $doc->getElementsByTagNameNS('*', 'cvsection'); $sections = array(); foreach($sectionNodes as $sectionNode){ $sectionTitle = $sectionNode->getAttribute('title'); $c = $doc->saveHTML($sectionNode);// $sectionNode->nodeValue; $sections[] = array('title'=> $sectionTitle, 'content'=>$c); } return $sections; } //these functions aren't really necessary for php since serializing //or apc caching works fine, with only the possible loss of a curl //handle that will be re-initialized public function saveLibrary(){ $serialized = serialize($this); return $serialized; } public static function loadLibrary($dump){ return unserialize($dump); } } /** * Utility functions for libZotero * * @package libZotero */ class Zotero_Lib_Utils { const ZOTERO_URI = 'https://api.zotero.org'; const ZOTERO_WWW_URI = 'http://www.zotero.org'; const ZOTERO_WWW_API_URI = 'http://www.zotero.org/api'; public static function randomString($len=0, $chars=null) { if ($chars === null) { $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; } if ($len==0) { $len = 8; } $randomstring = ''; for ($i = 0; $i < $len; $i++) { $rnum = rand(0, strlen($chars) - 1); $randomstring .= $chars[$rnum]; } return $randomstring; } public static function getKey() { $baseString = "23456789ABCDEFGHIJKMNPQRSTUVWXZ"; return Zotero_Lib_Utils::randomString(8, $baseString); } //update items appropriately based on response to multi-write request //for success: // update objectKey if item doesn't have one yet (newly created item) // update itemVersion to response's Last-Modified-Version header // mark as synced //for unchanged: // don't need to do anything? itemVersion should remain the same? // mark as synced if not already? //for failed: // do something. flag as error? display some message to user? public static function updateObjectsFromWriteResponse($objectsArray, $response){ $data = json_decode($response->getRawBody(), true); if($response->getStatus() == 200){ $newLastModifiedVersion = $response->getHeader("Last-Modified-Version"); if(isset($data['success'])){ foreach($data['success'] as $ind=>$key){ $i = intval($ind); $object = $objectsArray[$i]; $objectKey = $object->get('key'); if($objectKey != '' && $objectKey != $key){ throw new Exception("Item key mismatch in multi-write request"); } if($objectKey == ''){ $object->set('key', $key); } $object->set('version', $newLastModifiedVersion); $object->synced = true; $object->writeFailure = false; } } if(isset($data['failed'])){ foreach($data['failed'] as $ind=>$val){ $i = intval($ind); $object = $objectsArray[$i]; $object->writeFailure = $val; } } } elseif($response->getStatus() == 204){ $objectsArray[0]->synced = true; } } public static function parseKey($keynode){ $key = array(); $keyPerms = array("library"=>"0", "notes"=>"0", "write"=>"0", 'groups'=>array()); $accessEls = $keyNode->getElementsByTagName('access'); foreach($accessEls as $access){ if($libraryAccess = $access->getAttribute("library")){ $keyPerms['library'] = $libraryAccess; } if($notesAccess = $access->getAttribute("notes")){ $keyPerms['notes'] = $notesAccess; } if($groupAccess = $access->getAttribute("group")){ $groupPermission = $access->getAttribute("write") == '1' ? 'write' : 'read'; $keyPerms['groups'][$groupAccess] = $groupPermission; } elseif($writeAccess = $access->getAttribute("write")) { $keyPerms['write'] = $writeAccess; } } return $keyPerms; } public static function libraryString($type, $libraryID){ $lstring = ''; if($type == 'user') $lstring = 'u'; elseif($type == 'group') $lstring = 'g'; $lstring += $libraryID; return $lstring; } public static function wrapLinks($txt, $nofollow=false){ //extremely ugly wrapping of urls in html if($nofollow){ $repstring = " <a rel='nofollow' href='$1'>$1</a>"; } else{ $repstring = " <a href='$1'>$1</a>"; } //will break completely on CDATA with unescaped brackets, and probably on alot of malformed html return preg_replace('/(http:\/\/[-a-zA-Z0-9._~:\/?#\[\]@!$&\'\(\)*+,;=]+)(?=\.|,|;|\s)(?![^<]*>)/i', $repstring, $txt); //alternative regexes /* return preg_replace('/(?<!<[^>]*)(http:\/\/[\S]+)(?=\.|,|;)/i', " <a href='$1'>$1</a>", $txt); return preg_replace('/<(?[^>]+>)(http:\/\/[\S]+)(?=\.|,|;)/i', " <a href='$1'>$1</a>", $txt); return preg_replace('/\s(http:\/\/[\S]+)(?=\.|,|;)/i', " <a href='$1'>$1</a>", $txt); */ } public static function wrapDOIs($txt){ $matches = array(); $doi = preg_match("(10\.[^\s\/]+\/[^\s]+)", $txt, $matches); $m1 = htmlspecialchars($matches[0]); $safetxt = htmlspecialchars($txt); return "<a href=\"http://dx.doi.org/{$matches[0]}\" rel=\"nofollow\">{$safetxt}</a>"; } public static function getFirstEntryNode($body){ $doc = new DOMDocument(); $doc->loadXml($body); $entryNodes = $doc->getElementsByTagName("entry"); if($entryNodes->length){ return $entryNodes->item(0); } else { return null; } } public static function getEntryNodes($body){ $doc = new DOMDocument(); $doc->loadXml($body); $entryNodes = $doc->getElementsByTagName("entry"); return $entryNodes; } public static function utilRequest($url, $method="GET", $body=NULL, $headers=array(), $basicauth=array() ) { libZoteroDebug( "url being requested: " . $url . "\n\n"); $ch = curl_init(); $httpHeaders = array(); //set api version - allowed to be overridden by passed in value if(!isset($headers['Zotero-API-Version'])){ $headers['Zotero-API-Version'] = ZOTERO_API_VERSION; } foreach($headers as $key=>$val){ $httpHeaders[] = "$key: $val"; } //disable Expect header $httpHeaders[] = 'Expect:'; if(!empty($basicauth)){ $passString = $basicauth['username'] . ':' . $basicauth['password']; /* echo $passString; curl_setopt($ch, CURLOPT_USERPWD, $passString); curl_setopt($ch, CURLOPT_FORBID_REUSE, true); */ $authHeader = 'Basic ' . base64_encode($passString); $httpHeaders[] = "Authorization: {$authHeader}"; } else{ $passString = ''; curl_setopt($ch, CURLOPT_USERPWD, $passString); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); //FOLLOW LOCATION HEADERS curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $umethod = strtoupper($method); switch($umethod){ case "GET": curl_setopt($ch, CURLOPT_HTTPGET, true); break; case "POST": curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "PUT": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); break; case "DELETE": curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } $responseBody = curl_exec($ch); $responseInfo = curl_getinfo($ch); $zresponse = libZotero_Http_Response::fromString($responseBody); //Zend Response does not parse out the multiple sets of headers returned when curl automatically follows //a redirect and the new headers are left in the body. Zend_Http_Client gets around this by manually //handling redirects. That may end up being a better solution, but for now we'll just re-read responses //until a non-redirect is read while($zresponse->isRedirect()){ $redirectedBody = $zresponse->getBody(); $zresponse = libZotero_Http_Response::fromString($redirectedBody); } curl_close($ch); return $zresponse; } public static function apiQueryString($passedParams=array()){ $queryParamOptions = array('start', 'limit', 'order', 'sort', 'content', 'q', 'fq', 'itemType', 'locale', 'key', 'itemKey', 'tag', 'tagType', 'style', 'format', 'linkMode', 'linkwrap' ); //build simple api query parameters object $queryParams = array(); foreach($queryParamOptions as $i=>$val){ if(isset($passedParams[$val]) && ($passedParams[$val] != '')) { //check if itemKey belongs in the url or the querystring if($val == 'itemKey' && isset($passedParams['target']) && ($passedParams['target'] != 'items') ) continue; $queryParams[$val] = $passedParams[$val]; } } $queryString = '?'; $queryParamsArray = array(); foreach($queryParams as $index=>$value){ if(is_array($value)){ foreach($value as $key=>$val){ if(is_string($val) || is_int($val)){ $queryParamsArray[] = urlEncode($index) . '=' . urlencode($val); } } } elseif(is_string($value) || is_int($value)){ $queryParamsArray[] = urlencode($index) . '=' . urlencode($value); } } $queryString .= implode('&', $queryParamsArray); //print "apiQueryString: " . $queryString . "\n"; return $queryString; } public static function translateMimeType($mimeType) { switch ($mimeType) { case 'text/html': return 'html'; case 'application/pdf': case 'application/x-pdf': case 'application/acrobat': case 'applications/vnd.pdf': case 'text/pdf': case 'text/x-pdf': return 'pdf'; case 'image/jpg': case 'image/jpeg': return 'jpg'; case 'image/gif': return 'gif'; case 'application/msword': case 'application/doc': case 'application/vnd.msword': case 'application/vnd.ms-word': case 'application/winword': case 'application/word': case 'application/x-msw6': case 'application/x-msword': return 'doc'; case 'application/vnd.oasis.opendocument.text': case 'application/x-vnd.oasis.opendocument.text': return 'odt'; case 'video/flv': case 'video/x-flv': return 'flv'; case 'image/tif': case 'image/tiff': case 'image/tif': case 'image/x-tif': case 'image/tiff': case 'image/x-tiff': case 'application/tif': case 'application/x-tif': case 'application/tiff': case 'application/x-tiff': return 'tiff'; case 'application/zip': case 'application/x-zip': case 'application/x-zip-compressed': case 'application/x-compress': case 'application/x-compressed': case 'multipart/x-zip': return 'zip'; case 'video/quicktime': case 'video/x-quicktime': return 'mov'; case 'video/avi': case 'video/msvideo': case 'video/x-msvideo': return 'avi'; case 'audio/wav': case 'audio/x-wav': case 'audio/wave': return 'wav'; case 'audio/aiff': case 'audio/x-aiff': case 'sound/aiff': return 'aiff'; case 'text/plain': return 'plain text'; case 'application/rtf': return 'rtf'; default: return $mimeType; } } }
vanch3d/nvl-slim
sources/Zotero/libZoteroSingle.php
PHP
mit
148,252
/*! * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! * @module bigquery/dataset */ 'use strict'; var common = require('@google-cloud/common'); var extend = require('extend'); var is = require('is'); var util = require('util'); /** * @type {module:bigquery/table} * @private */ var Table = require('./table.js'); /*! Developer Documentation * * @param {module:bigquery} bigQuery - BigQuery instance. * @param {string} id - The ID of the Dataset. */ /** * Interact with your BigQuery dataset. Create a Dataset instance with * {module:bigquery#createDataset} or {module:bigquery#dataset}. * * @alias module:bigquery/dataset * @constructor * * @example * var dataset = bigquery.dataset('institutions'); */ function Dataset(bigQuery, id) { var methods = { /** * Create a dataset. * * @example * dataset.create(function(err, dataset, apiResponse) { * if (!err) { * // The dataset was created successfully. * } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.create().then(function(data) { * var dataset = data[0]; * var apiResponse = data[1]; * }); */ create: true, /** * Check if the dataset exists. * * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {boolean} callback.exists - Whether the dataset exists or not. * * @example * dataset.exists(function(err, exists) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.exists().then(function(data) { * var exists = data[0]; * }); */ exists: true, /** * Get a dataset if it exists. * * You may optionally use this to "get or create" an object by providing an * object with `autoCreate` set to `true`. Any extra configuration that is * normally required for the `create` method must be contained within this * object as well. * * @param {options=} options - Configuration object. * @param {boolean} options.autoCreate - Automatically create the object if * it does not exist. Default: `false` * * @example * dataset.get(function(err, dataset, apiResponse) { * if (!err) { * // `dataset.metadata` has been populated. * } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.get().then(function(data) { * var dataset = data[0]; * var apiResponse = data[1]; * }); */ get: true, /** * Get the metadata for the Dataset. * * @resource [Datasets: get API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/get} * * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {object} callback.metadata - The dataset's metadata. * @param {object} callback.apiResponse - The full API response. * * @example * dataset.getMetadata(function(err, metadata, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.getMetadata().then(function(data) { * var metadata = data[0]; * var apiResponse = data[1]; * }); */ getMetadata: true, /** * Sets the metadata of the Dataset object. * * @resource [Datasets: patch API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch} * * @param {object} metadata - Metadata to save on the Dataset. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this * request. * @param {object} callback.apiResponse - The full API response. * * @example * var metadata = { * description: 'Info for every institution in the 2013 IPEDS universe' * }; * * dataset.setMetadata(metadata, function(err, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.setMetadata(metadata).then(function(data) { * var apiResponse = data[0]; * }); */ setMetadata: true }; common.ServiceObject.call(this, { parent: bigQuery, baseUrl: '/datasets', id: id, createMethod: bigQuery.createDataset.bind(bigQuery), methods: methods }); this.bigQuery = bigQuery; } util.inherits(Dataset, common.ServiceObject); /** * Run a query scoped to your dataset as a readable object stream. * * See {module:bigquery#createQueryStream} for full documentation of this * method. */ Dataset.prototype.createQueryStream = function(options) { if (is.string(options)) { options = { query: options }; } options = extend(true, {}, options, { defaultDataset: { datasetId: this.id } }); return this.bigQuery.createQueryStream(options); }; /** * Create a table given a tableId or configuration object. * * @resource [Tables: insert API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/insert} * * @param {string} id - Table id. * @param {object=} options - See a * [Table resource](https://cloud.google.com/bigquery/docs/reference/v2/tables#resource). * @param {string|object} options.schema - A comma-separated list of name:type * pairs. Valid types are "string", "integer", "float", "boolean", and * "timestamp". If the type is omitted, it is assumed to be "string". * Example: "name:string, age:integer". Schemas can also be specified as a * JSON array of fields, which allows for nested and repeated fields. See * a [Table resource](http://goo.gl/sl8Dmg) for more detailed information. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {module:bigquery/table} callback.table - The newly created table. * @param {object} callback.apiResponse - The full API response. * * @example * var tableId = 'institution_data'; * * var options = { * // From the data.gov CSV dataset (http://goo.gl/kSE7z6): * schema: 'UNITID,INSTNM,ADDR,CITY,STABBR,ZIP,FIPS,OBEREG,CHFNM,...' * }; * * dataset.createTable(tableId, options, function(err, table, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.createTable(tableId, options).then(function(data) { * var table = data[0]; * var apiResponse = data[1]; * }); */ Dataset.prototype.createTable = function(id, options, callback) { var self = this; if (is.fn(options)) { callback = options; options = {}; } var body = extend(true, {}, options, { tableReference: { datasetId: this.id, projectId: this.bigQuery.projectId, tableId: id } }); if (is.string(options.schema)) { body.schema = Table.createSchemaFromString_(options.schema); } if (is.array(options.schema)) { body.schema = { fields: options.schema }; } if (body.schema && body.schema.fields) { body.schema.fields = body.schema.fields.map(function(field) { if (field.fields) { field.type = 'RECORD'; } return field; }); } this.request({ method: 'POST', uri: '/tables', json: body }, function(err, resp) { if (err) { callback(err, null, resp); return; } var table = self.table(resp.tableReference.tableId); table.metadata = resp; callback(null, table, resp); }); }; /** * Delete the dataset. * * @resource [Datasets: delete API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/datasets/delete} * * @param {object=} options - The configuration object. * @param {boolean} options.force - Force delete dataset and all tables. * Default: false. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {object} callback.apiResponse - The full API response. * * @example * //- * // Delete the dataset, only if it does not have any tables. * //- * dataset.delete(function(err, apiResponse) {}); * * //- * // Delete the dataset and any tables it contains. * //- * dataset.delete({ force: true }, function(err, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.delete().then(function(data) { * var apiResponse = data[0]; * }); */ Dataset.prototype.delete = function(options, callback) { if (!callback) { callback = options; options = {}; } var query = { deleteContents: !!options.force }; this.request({ method: 'DELETE', uri: '', qs: query }, callback); }; /** * Get a list of tables. * * @resource [Tables: list API Documentation]{@link https://cloud.google.com/bigquery/docs/reference/v2/tables/list} * * @param {object=} query - Configuration object. * @param {boolean} query.autoPaginate - Have pagination handled automatically. * Default: true. * @param {number} query.maxApiCalls - Maximum number of API calls to make. * @param {number} query.maxResults - Maximum number of results to return. * @param {string} query.pageToken - Token returned from a previous call, to * request the next page of results. * @param {function} callback - The callback function. * @param {?error} callback.err - An error returned while making this request * @param {module:bigquery/table[]} callback.tables - The list of tables from * your Dataset. * @param {object} callback.apiResponse - The full API response. * * @example * dataset.getTables(function(err, tables, nextQuery, apiResponse) { * // If `nextQuery` is non-null, there are more results to fetch. * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * dataset.getTables().then(function(data) { * var tables = data[0]; * }); */ Dataset.prototype.getTables = function(query, callback) { var that = this; if (is.fn(query)) { callback = query; query = {}; } query = query || {}; this.request({ uri: '/tables', qs: query }, function(err, resp) { if (err) { callback(err, null, null, resp); return; } var nextQuery = null; if (resp.nextPageToken) { nextQuery = extend({}, query, { pageToken: resp.nextPageToken }); } var tables = (resp.tables || []).map(function(tableObject) { var table = that.table(tableObject.tableReference.tableId); table.metadata = tableObject; return table; }); callback(null, tables, nextQuery, resp); }); }; /** * List all or some of the {module:bigquery/table} objects in your project as a * readable object stream. * * @param {object=} query - Configuration object. See * {module:bigquery/dataset#getTables} for a complete list of options. * @return {stream} * * @example * dataset.getTablesStream() * .on('error', console.error) * .on('data', function(table) {}) * .on('end', function() { * // All tables have been retrieved * }); * * //- * // If you anticipate many results, you can end a stream early to prevent * // unnecessary processing and API requests. * //- * dataset.getTablesStream() * .on('data', function(table) { * this.end(); * }); */ Dataset.prototype.getTablesStream = common.paginator.streamify('getTables'); /** * Run a query scoped to your dataset. * * See {module:bigquery#query} for full documentation of this method. */ Dataset.prototype.query = function(options, callback) { if (is.string(options)) { options = { query: options }; } options = extend(true, {}, options, { defaultDataset: { datasetId: this.id } }); return this.bigQuery.query(options, callback); }; /** * Create a Table object. * * @param {string} id - The ID of the table. * @return {module:bigquery/table} * * @example * var institutions = dataset.table('institution_data'); */ Dataset.prototype.table = function(id) { return new Table(this, id); }; /*! Developer Documentation * * These methods can be auto-paginated. */ common.paginator.extend(Dataset, ['getTables']); /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ common.util.promisifyAll(Dataset, { exclude: ['table'] }); module.exports = Dataset;
DayanaHudson/GMUExchange
node_modules/google-cloud/node_modules/@google-cloud/bigquery/src/dataset.js
JavaScript
mit
13,273
(function(Button, set) { set += ": "; test(set + "Test btn class added", function() { var $elements; $elements = new Button($("<a>").add("<button>").add("<input>")); ok($elements.hasClass("btn"), "Buttons should be of the btn class"); }); test(set + "Test button creation, no arguments", function() { var button = new Button(); ok(button.hasClass("btn"), "Button should be of the btn class"); ok(button.is("button"), "Button should be a <button> element"); equal(button.attr("type"), "button", "Type attribute should be 'button'"); }); test(set + "Test default buttons", function() { var button = new Button(); button.primary(); equal(button.attr("class"), "btn " + button.options.PRIMARY, "Primary style button should be of the btn and '" + button.options.PRIMARY + "' classes only"); button.info(); equal(button.attr("class"), "btn " + button.options.INFO, "Info style button should be of the btn and '" + button.options.INFO + "' classes only"); button.success(); equal(button.attr("class"), "btn " + button.options.SUCCESS, "Success style button should be of the btn and '" + button.options.SUCCESS + "' classes only"); button.warning(); equal(button.attr("class"), "btn " + button.options.WARNING, "Warning style button should be of the btn and '" + button.options.WARNING + "' classes only"); button.danger(); equal(button.attr("class"), "btn " + button.options.DANGER, "Danger style button should be of the btn and '" + button.options.DANGER + "' classes only"); button.link(); equal(button.attr("class"), "btn " + button.options.LINK, "Link style button should be of the btn and '" + button.options.LINK + "' classes only"); button.defaultStyle(); equal(button.attr("class"), "btn", "Default button should be of the btn class only"); }); test(set+ "Test button sizes", function() { var button = new Button(); button.large(); equal(button.attr("class"), "btn " + button.sizes.LARGE, "Large button should be of the btn and '" + button.sizes.LARGE + "' classes only"); button.defaultSize(); equal(button.attr("class"), "btn", "Default button should be of the btn class only"); button.small(); equal(button.attr("class"), "btn " + button.sizes.SMALL, "Small button should be of the btn and '" + button.sizes.SMALL + "' classes only"); button.extraSmall(); equal(button.attr("class"), "btn " + button.sizes.EXTRASMALL, "Extra small button should be of the btn and '" + button.sizes.EXTRASMALL + "' classes only"); }); test(set + "Test block-level button", function () { var button = new Button(); button.block(); equal(button.attr("class"), "btn " + button.BLOCK, "Block level button should be of the btn and '" + button.BLOCK + "' classes only"); }); test(set + "Test disable <button> and <input> elements", function() { var buttons, hasClass; buttons = new Button($("<button>").add("<input>")); hasClass = false; buttons.disable(); equal(buttons.attr("disabled"), "disabled", "Disabled elements should have the disabled attribute value of 'disabled'"); buttons.map(function() { hasClass = hasClass || $(this).hasClass(Button.prototype.DISABLED); }); equal(hasClass, false, "Elements should not be of the '" + Button.prototype.DISABLED + "' class"); }); test(set + "Test disable <a> element", function() { var button = new Button("<a>"); button.disable(); ok(button.attr("disabled") === undefined, "Disabled anchor elements should not have the disabled attribute"); ok(button.hasClass(button.DISABLED), "Disabled anchor elements should be of the '" + button.DISABLED + "' class"); }); test(set + "Test set text", function() { var anotherButton, buttons, functionExpectedValue, oldText, text; oldText = "Hello, tester!"; text = "Hello, world!"; buttons = new Button( $("<button>") .add("<input type='button'>") .add("<input type='submit'>") .add("<input type='reset'>") .add("<input type='text'>")); //not a real button anotherButton = new Button("<button>" + oldText + "</button>"); buttons.text(text); //.eq() returns a jQuery object, so no worries about the Button.prototype.text() calls, here! equal(buttons.eq(0).text(), text, "<button> element should have text() set to " + text); equal(buttons.eq(0).attr("value"), undefined, "<button> element should not have the value attribute set"); equal(buttons.eq(1).text(), "", "<input> button element should have text() set to an empty string"); equal(buttons.eq(1).attr("value"), text, "<input> button element should have the value attribute set to " + text); equal(buttons.eq(2).text(), "", "<input> submit element should have text() set to an empty string"); equal(buttons.eq(2).attr("value"), text, "<input> submit element should have the value attribute set to " + text); equal(buttons.eq(3).text(), "", "<input> reset element should have text() set to an empty string"); equal(buttons.eq(3).attr("value"), text, "<input> reset element should have the value attribute set to " + text); equal(buttons.eq(4).text(), text, "<input> text (not a button) element should have text() set to " + text); equal(buttons.eq(4).attr("value"), undefined, "<input> text (not a button) element should not have the value attribute set"); anotherButton.text(function(index, old) { return "" + text + "-" + index + "-" + old; }); functionExpectedValue = "" + text + "-0-" + oldText; equal($.fn.text.apply(anotherButton, []), functionExpectedValue, "Setting text with this function should return '" + functionExpectedValue + "' for text()"); }); test(set + "Test get text", function() { var buttons, text; text = "Hello, world, again!"; buttons = { button: new Button("<button>" + text + "</button>"), input: { button: new Button("<input type='button' value='" + text + "'>"), submit: new Button("<input type='submit' value='" + text + "'>"), reset: new Button("<input type='reset' value='" + text + "'>"), notAButton: new Button("<input type='text' value='" + text + "'>") }, anchor: new Button("<a>" + text + "</a>") }; equal(buttons.button.text(), text, "<button> element should have text() return '" + text + "'"); equal(buttons.input.button.text(), text, "<input> button element should have text() return '" + text + "'"); equal(buttons.input.submit.text(), text, "<input> submit element should have text() return '" + text + "'"); equal(buttons.input.reset.text(), text, "<input> reset element should have text() return '" + text + "'"); equal(buttons.input.notAButton.text(), "", "<input> text (not a button) element should have text() return an empty string"); equal(buttons.anchor.text(), text, "<a> element should have text() return '" + text + "'"); }); })(uk.co.stevenmeyer.bootstrap.css.Button, "css.Button");
StevenMeyer/BootstrapLib
test/tests/2.0/css/button.js
JavaScript
mit
7,695
package org.hive2hive.core.events.framework; public interface IEventGenerator { // so far, just a marker interface }
albu89/Hive2Hive-dev
org.hive2hive.core/src/main/java/org/hive2hive/core/events/framework/IEventGenerator.java
Java
mit
124
require_relative '../../../../../environments/rspec_env' shared_examples_for 'a model, integration' do # clazz must be defined by the calling file let(:model) { clazz.new } describe 'unique behavior' do it 'inherits from the common model class' do expect(model).to be_a(CukeModeler::Model) end end end
enkessler/cuke_modeler
testing/rspec/spec/integration/shared/models_integration_specs.rb
Ruby
mit
332
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import os, os.path from matplotlib import pyplot as plt from pylab import get_cmap import SimpleCV as cv from glob import glob # <codecell> def show_img(img, ax = None): if ax is not None: plt.sca(ax) nimg = img.getNumpy() return plt.imshow(nimg, aspect='equal') # <codecell> path = '/home/will/Dropbox/burnimages/*.jpg' norm_files = sorted(f for f in glob(path) if '-e' not in f) masked_files = sorted(f for f in glob(path) if '-e' in f) fig, axs = plt.subplots(6,6, figsize = (10,10)) for f, ax in zip(norm_files, axs.flatten()): img = cv.Image(f) show_img(img, ax = ax) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() # <codecell> from itertools import islice, izip_longest from dateutil.parser import parse def make_wound_mask(norm_img, green_img, color, minsize = None, maxsize = None): wmask = green_img.hueDistance(color).invert().threshold(200) blobs = norm_img.findBlobsFromMask(wmask, minsize = minsize, maxsize = maxsize) return wmask, blobs fig, axs = plt.subplots(6,6, figsize = (10,10)) results = [] for fname, mf, of, ax in izip_longest(norm_files, masked_files, norm_files, axs.flatten()): mask_img = cv.Image(mf) norm_img = cv.Image(of) dt = parse(fname.rsplit(os.sep,1)[1].replace('.jpg', '').replace('.',':')) wound_mask, wound_blobs = make_wound_mask(norm_img, mask_img, cv.Color.GREEN, minsize = 1000) dime_mask, dime_blobs = make_wound_mask(norm_img, mask_img, cv.Color.BLUE, minsize = 500) layer = cv.DrawingLayer((norm_img.width, norm_img.height)) wound_blobs[-1].drawHull(color=cv.Color.BLUE, width = 100, layer = layer) dime_blobs[-1].drawHull(color=cv.Color.RED, width = 100, layer = layer) norm_img.addDrawingLayer(layer) fnorm = norm_img.applyLayers() ratio = wound_blobs[-1].area()/dime_blobs[-1].area() results.append((dt, ratio)) if ax is not None: show_img(fnorm, ax = ax) ax.set_xticks([]) ax.set_yticks([]) ax.set_title(ratio) fig.tight_layout() # <codecell> import pandas as pd res_df = pd.DataFrame(sorted(results), columns = ['SampleTime', 'Ratio']) dime_diameter = 18 #mm dime_area = 3.141*(dime_diameter/2)**2 res_df['Area-mm2'] = dime_area*res_df['Ratio'] res_df.set_index('SampleTime', inplace=True) res_df # <codecell> res_df['Area-mm2'].plot() out = pd.ewma(res_df['Area-mm2'], freq='d', span = 1) out.plot(lw = 10, alpha = 0.7) plt.ylabel('Wound-Area-mm^2') # <codecell>
JudoWill/ResearchNotebooks
Woundy.py
Python
mit
2,781
package org.simpleflatmapper.converter.joda.impl; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormatter; import org.simpleflatmapper.converter.Context; import org.simpleflatmapper.converter.ContextualConverter; public class CharSequenceToJodaLocalDateTimeConverter implements ContextualConverter<CharSequence, LocalDateTime> { private final DateTimeFormatter dateTimeFormatter; public CharSequenceToJodaLocalDateTimeConverter(DateTimeFormatter dateTimeFormatter) { this.dateTimeFormatter = dateTimeFormatter; } @Override public LocalDateTime convert(CharSequence in, Context context) throws Exception { if (in == null || in.length() == 0) return null; return dateTimeFormatter.parseLocalDateTime(String.valueOf(in)); } }
arnaudroger/SimpleFlatMapper
sfm-converter-joda-time/src/main/java/org/simpleflatmapper/converter/joda/impl/CharSequenceToJodaLocalDateTimeConverter.java
Java
mit
802
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> pii; string sub() { string s; int k; cin >> s >> k; int cnt = 0; for (int i = 0; i < (int)s.size(); i++) { if (s[i] == '+') continue; else { if (i + k - 1 >= (int)s.size()) return "IMPOSSIBLE"; cnt++; for (int z = i; z < i + k; z++) if (s[z] == '+') s[z] = '-'; else s[z] = '+'; } } stringstream ss; ss << cnt; string res; ss >> res; return res; } int main() { int t; cin >> t; for (int i = 0; i < t; i++) cout << "Case #" << i + 1 << ": " << sub() << endl; }
Izaron/Competitive
Google Code Jam/2017/Qualification Round/oversized_pancake_flipper.cpp
C++
mit
787
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using BusinessForms; using BusinessForms.FSControllers; using PalvelutoriModel.Translation; using PalvelutoriModel.Caching; using PS = PalvelutoriModel.PassthroughControllers; using PalvelutoriModel.Vetuma; namespace Microsoft.AspNetCore.Builder { public static class PalvelutoriExtensions { public static void AddPalvelutori(this IServiceCollection services, string dataPath, string djangoApi) { services.AddTransient<PS.KohdeController>(); services.AddTransient<PS.KohteetController>(); services.AddTransient<PS.KayttajaController>(); services.AddTransient<PS.KayttajatController>(); services.AddTransient<PS.LoginController>(); services.AddTransient<PS.PalveluPaketitController>(); services.AddTransient<PS.AdminResourceCalenderController>(); services.AddTransient<PS.YritysSearchController>(); services.AddTransient<BFContext>(sp => new BFContext(sp, djangoApi)); services.AddSingleton<IFSProvider>(sp => new FSProvider(dataPath) ); services.AddSingleton<DjangoCache, DjangoCache>(); } public static void UsePalvelutoriTranslation(this IApplicationBuilder app) { app.Use(TranslationMiddleware.ExtractLanguage); } public static void AddVetuma<TVetumaController>(this IServiceCollection services, VetumaEnvironment environment) where TVetumaController : Controller { services.AddSingleton<VetumaEnvironment>(en => environment); services.AddTransient<IVetumaFactory, VetumaFactory>(); // TODO: Tämä ehkä vähän huono tässä -> Voisi olla fiksummassakin paikassa. services.AddTransient<TVetumaController>(); } } } namespace PalvelutoriModel { internal static class LocalExtensions { internal static string GetUserID(this Controller controller) { return "416757105098753"; } } }
DigiTurku/munpalvelut_frontend
App/Palvelutori/src/PalvelutoriModel/PalvelutoriExtensions.cs
C#
mit
2,179
//--------------------------------------------------------------------- // <copyright file="MediaDisk.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Microsoft.Deployment.WindowsInstaller.MediaDisk struct. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents a media disk source of a product or a patch. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] public struct MediaDisk { private int diskId; private string volumeLabel; private string diskPrompt; /// <summary> /// Creates a new media disk. /// </summary> /// <param name="diskId"></param> /// <param name="volumeLabel"></param> /// <param name="diskPrompt"></param> public MediaDisk(int diskId, string volumeLabel, string diskPrompt) { this.diskId = diskId; this.volumeLabel = volumeLabel; this.diskPrompt = diskPrompt; } /// <summary> /// Gets or sets the disk id of the media disk. /// </summary> public int DiskId { get { return this.diskId; } set { this.diskId = value; } } /// <summary> /// Gets or sets the volume label of the media disk. /// </summary> public string VolumeLabel { get { return this.volumeLabel; } set { this.volumeLabel = value; } } /// <summary> /// Gets or sets the disk prompt of the media disk. /// </summary> public string DiskPrompt { get { return this.diskPrompt; } set { this.diskPrompt = value; } } } }
OneGet/oneget
src/Microsoft.PackageManagement.MsiProvider/Deployment/WindowsInstaller/MediaDisk.cs
C#
mit
2,080
package com.cal.angelgame; public class Decoration extends GameObject { /** * Anything drawn to the screen that is not interactable * wrapper for game object * * will have animation function: maybe * * @param x * @param y * @param width * @param height */ public Decoration(float x, float y, float width, float height) { super(x, y, width, height); // TODO Auto-generated constructor stub } }
phorust/BitSlayer
angelgame/src/com/cal/angelgame/Decoration.java
Java
mit
425
/* * Copyright (c) 2019 Handywedge Co.,Ltd. * * This software is released under the MIT License. * * http://opensource.org/licenses/mit-license.php */ package com.handywedge.interceptor; import jakarta.enterprise.context.RequestScoped; @RequestScoped public class FWTransactionManager { private int layer = 0; boolean isTopLayer() { return layer == 0; } void incrementLayer() { layer++; } void decrementLayer() { layer--; } }
cstudioteam/handywedge
handywedge-master/handywedge-core/src/main/java/com/handywedge/interceptor/FWTransactionManager.java
Java
mit
468
/// <reference path="Xrm.js" /> var EntityLogicalName = "uomschedule"; var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Properties = { description: "description", name: "name" }; var Form_a793fa7c_8b63_43f0_b4bc_73f75a68935a_Controls = { description: "description", name: "name" }; var pageData = { "Event": "none", "SaveMode": 1, "EventSource": null, "AuthenticationHeader": "", "CurrentTheme": "Default", "OrgLcid": 1033, "OrgUniqueName": "", "QueryStringParameters": { "_gridType": "1056", "etc": "1056", "id": "", "pagemode": "iframe", "preloadcache": "1344548892170", "rskey": "141637534" }, "ServerUrl": "", "UserId": "", "UserLcid": 1033, "UserRoles": [""], "isOutlookClient": false, "isOutlookOnline": true, "DataXml": "", "EntityName": "uomschedule", "Id": "", "IsDirty": false, "CurrentControl": "", "CurrentForm": null, "Forms": [], "FormType": 2, "ViewPortHeight": 558, "ViewPortWidth": 1231, "Attributes": [{ "Name": "description", "Value": "", "Type": "memo", "Format": "text", "IsDirty": false, "RequiredLevel": "none", "SubmitMode": "dirty", "UserPrivilege": { "canRead": true, "canUpdate": true, "canCreate": true }, "MaxLength": 2000, "Controls": [{ "Name": "description" }] }, { "Name": "name", "Value": "", "Type": "string", "Format": "text", "IsDirty": false, "RequiredLevel": "none", "SubmitMode": "dirty", "UserPrivilege": { "canRead": true, "canUpdate": true, "canCreate": true }, "MaxLength": 200, "Controls": [{ "Name": "name" }] }], "AttributesLength": 2, "Controls": [{ "Name": "description", "Type": "standard", "Disabled": false, "Visible": true, "Label": "Description", "Attribute": "description" }, { "Name": "name", "Type": "standard", "Disabled": false, "Visible": true, "Label": "Name", "Attribute": "name" }], "ControlsLength": 2, "Navigation": [], "Tabs": [{ "Label": "General", "Name": "general", "DisplayState": "expanded", "Visible": true, "Sections": [{ "Label": "UOM Schedule Information", "Name": "uom schedule information", "Visible": true, "Controls": [{ "Name": "name" }, { "Name": "description" }] }] }] }; var Xrm = new _xrm(pageData);
Nazi-Nigger/Ms-CRM-2016-Controls
Ms-CRM-2016-Controls/Ms-CRM-2016-Controls Resources/Javascript/Intellisense Files/Unit Group Form - Information.js
JavaScript
mit
2,848
require "test_helper" class WorkerTest < ActiveSupport::TestCase class Receiver attr_accessor :last_action def run @last_action = :run end def process(message) @last_action = [ :process, message ] end def connection self end def logger # Impersonating a connection requires a TaggedLoggerProxy'ied logger. inner_logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN } ActionCable::Connection::TaggedLoggerProxy.new(inner_logger, tags: []) end end setup do @worker = ActionCable::Server::Worker.new @receiver = Receiver.new end teardown do @receiver.last_action = nil end test "invoke" do @worker.invoke @receiver, :run, connection: @receiver.connection assert_equal :run, @receiver.last_action end test "invoke with arguments" do @worker.invoke @receiver, :process, "Hello", connection: @receiver.connection assert_equal [ :process, "Hello" ], @receiver.last_action end end
sergey-alekseev/rails
actioncable/test/worker_test.rb
Ruby
mit
1,020
require 'spec_helper' describe "/api/v1/tickets", :type => :api do include Rack::Test::Methods let!(:project) { FactoryGirl.create(:project, :name => "Ticketee") } let!(:user) { FactoryGirl.create(:user) } before do user.permissions.create!(:action => "view",:thing => project) end let(:token) { user.authentication_token } context "index" do before do 5.times do FactoryGirl.create(:ticket, :project => project, :user => user) end end let(:url) { "/api/v1/projects/#{project.id}/tickets" } it "XML" do get "#{url}.xml", :token => token last_response.body.should eql(project.tickets.to_xml) end it "JSON" do get "#{url}.json", :token => token last_response.body.should eql(project.tickets.to_json) end end end
kosh88/ticketeefinal
spec/api/v1/tickets_spec.rb
Ruby
mit
713
// To set up environmental variables, see http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const Twilio = require('twilio').Twilio; const client = new Twilio(accountSid, authToken); const service = client.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); service .syncLists('MyFirstList') .syncListItems(0) .update({ data: { number: '001', attack: '49', name: 'Bulbasaur', }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
TwilioDevEd/api-snippets
sync/rest/lists/update-list-item/update-list-item.3.x.js
JavaScript
mit
595
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'newpage', 'af', { toolbar: 'Nuwe bladsy' } );
otto-torino/gino
ckeditor/plugins/newpage/lang/af.js
JavaScript
mit
247
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2016_12_01 module Models # # Network interface and its custom security rules. # class NetworkInterfaceAssociation include MsRestAzure # @return [String] Network interface ID. attr_accessor :id # @return [Array<SecurityRule>] Collection of custom security rules. attr_accessor :security_rules # # Mapper for NetworkInterfaceAssociation class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'NetworkInterfaceAssociation', type: { name: 'Composite', class_name: 'NetworkInterfaceAssociation', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, security_rules: { client_side_validation: true, required: false, serialized_name: 'securityRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SecurityRuleElementType', type: { name: 'Composite', class_name: 'SecurityRule' } } } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2016-12-01/generated/azure_mgmt_network/models/network_interface_association.rb
Ruby
mit
1,914
class ChangeColumnScreenshotTimestampInSpacesToSnapshotTimestamp < ActiveRecord::Migration[4.2] def change rename_column :spaces, :screenshot_timestamp, :snapshot_timestamp end end
getguesstimate/guesstimate-server
db/migrate/20160522003439_change_column_screenshot_timestamp_in_spaces_to_snapshot_timestamp.rb
Ruby
mit
189
/* * 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 com.ccc.smartfloorplan.action; import com.ccc.smartfloorplan.entity.Floor; import com.ccc.smartfloorplan.entity.JdbcConn; import com.ccc.util.XmlMapping; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author davidchang */ @WebServlet(name = "GetAllFloorAction", urlPatterns = "{/GetAllFloorAction}") public class GetAllFloorAction extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs; try { XmlMapping configXml = new XmlMapping(new File(getServletConfig().getServletContext().getRealPath("/WEB-INF/config.xml"))); Class.forName(configXml.LookupKey("DRIVER_MANAGER")); conn = DriverManager.getConnection(configXml.LookupKey("DB_URL"), configXml.LookupKey("USER"), configXml.LookupKey("PASS")); pstmt = conn.prepareStatement("SELECT `id`, `sort`, `disabled`, `name`, `adminId`, `imageUri` FROM `floors` WHERE `disabled` = 0 ORDER BY `id` ASC"); rs = pstmt.executeQuery(); List<Floor> floors = new ArrayList<>(); while (rs.next()) { Floor floor = new Floor(); floor.setId(rs.getInt("id")); floor.setSort(rs.getInt("sort")); floor.setDisabled(rs.getInt("disabled")); floor.setName(rs.getString("name")); floor.setAdminId(rs.getInt("adminId")); floor.setImageUri(rs.getString("imageUri")); floors.add(floor); } HttpSession session = request.getSession(); session.setAttribute("floors", floors); session.setMaxInactiveInterval(5 * 60); } catch (ClassNotFoundException ex) { Logger.getLogger(GetAllFloorAction.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(GetAllFloorAction.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
chechiachang/booking-manager-maven
src/main/java/com/ccc/smartfloorplan/action/GetAllFloorAction.java
Java
mit
5,322
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Agent * * @ORM\Table(name="agent", indexes={@ORM\Index(name="fk_agent_user_fk_idx", columns={"usr_id"})}) * @ORM\Entity */ class Agent { /** * @var integer * * @ORM\Column(name="agt_id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $agtId; /** * @var string * * @ORM\Column(name="agt_email", type="string", length=150, nullable=false) */ private $agtEmail; /** * @var boolean * * @ORM\Column(name="agt_state", type="boolean", nullable=true) */ private $agtState; /** * Get agtId * * @return integer */ public function getAgtId() { return $this->agtId; } /** * Set agtEmail * * @param string $agtEmail * * @return Agent */ public function setAgtEmail($agtEmail) { $this->agtEmail = $agtEmail; return $this; } /** * Get agtEmail * * @return string */ public function getAgtEmail() { return $this->agtEmail; } /** * Set agtState * * @param boolean $agtState * * @return Agent */ public function setAgtState($agtState) { $this->agtState = $agtState; return $this; } /** * Get agtState * * @return boolean */ public function getAgtState() { return $this->agtState; } }
fabiancnieto/job_a-p-p_c-l-i-c-kd-eliv
src/AppBundle/Entity/Agent.php
PHP
mit
1,541
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PokerTell.Plugins.PlayerPeeker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PokerTell.Plugins.PlayerPeeker")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9b46abfd-fa34-4167-bf32-70384f94f8c4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
thlorenz/pokertell
Src/Plugins/PokerTell.Plugins.PlayerPeeker/Properties/AssemblyInfo.cs
C#
mit
1,472
require 'active_support/inflector' module Brightcontent class RoutesParser def initialize(routes_hash = nil, engine_resources = Brightcontent.engine_resources) @routes_hash = routes_hash @engine_resources = engine_resources end def resources Resources.new(resources_array) end private attr_reader :engine_resources def resources_array (resource_names - engine_resources).map do |name| Resource.new(name) end end def resource_names routes_hash.map do |route| next unless route && route[:controller] && route[:path_spec] name = route[:controller].match(/brightcontent\/(.+)/)[1] if route[:action] == "index" && route[:path_spec].start_with?('/' + name) name end end.compact.uniq end def routes_hash @routes_hash ||= Engine.routes.routes.map do |r| { controller: r.defaults[:controller], action: r.defaults[:action], path_spec: r.path.spec.to_s } end end end end
brightin/brightcontent
core/lib/brightcontent/routes_parser.rb
Ruby
mit
1,069
using System; using System.IO; using System.Text; using System.Globalization; namespace UniHttp { internal sealed class ResponseHandler { const char COLON = ':'; const char SPACE = ' '; const char CR = '\r'; const char LF = '\n'; readonly HttpSettings settings; readonly CookieJar cookieJar; readonly CacheHandler cacheHandler; internal ResponseHandler(HttpSettings settings, CookieJar cookieJar, CacheHandler cacheHandler) { this.settings = settings; this.cookieJar = cookieJar; this.cacheHandler = cacheHandler; } internal HttpResponse Process(HttpRequest request, HttpStream source, Progress progress, CancellationToken cancellationToken) { HttpResponse response = new HttpResponse(request); response.HttpVersion = source.ReadTo(SPACE).TrimEnd(SPACE); response.StatusCode = int.Parse(source.ReadTo(SPACE).TrimEnd(SPACE)); response.StatusPhrase = source.ReadTo(LF).TrimEnd(); string name = source.ReadTo(COLON, LF).TrimEnd(COLON, CR, LF); while(name != String.Empty) { string valuesStr = source.ReadTo(LF).TrimStart(SPACE).TrimEnd(CR, LF); response.Headers.Append(name, valuesStr); name = source.ReadTo(COLON, LF).TrimEnd(COLON, CR, LF); } response.MessageBody = BuildMessageBody(response, source, progress, cancellationToken); ProcessCookie(response); ProcessCache(response); return response; } internal HttpResponse Process(HttpRequest request, CacheMetadata cache, Progress progress, CancellationToken cancellationToken) { HttpResponse response = new HttpResponse(request); response.HttpVersion = "HTTP/1.1"; response.StatusCode = 200; response.StatusPhrase = "OK (cache)"; response.Headers.Append(HeaderField.ContentType, cache.contentType); response.MessageBody = BuildMessageBodyFromCache(response, progress, cancellationToken); return response; } internal HttpResponse Process(HttpRequest request, Exception exception) { HttpResponse response = new HttpResponse(request); response.HttpVersion = "HTTP/1.1"; response.StatusCode = 0; response.StatusPhrase = exception.Message.Trim(); response.Headers.Append(HeaderField.ContentType, "text/plain"); response.MessageBody = Encoding.UTF8.GetBytes(string.Concat(exception.GetType(), CR, LF, exception.StackTrace)); return response; } byte[] BuildMessageBody(HttpResponse response, HttpStream source, Progress progress, CancellationToken cancellationToken) { if(response.StatusCode == StatusCode.NotModified) { return BuildMessageBodyFromCache(response, progress, cancellationToken); } if(response.Headers.Contains(HeaderField.TransferEncoding, "chunked")) { return BuildMessageBodyFromChunked(response, source, progress, cancellationToken); } if(response.Headers.Contains(HeaderField.ContentLength)) { return BuildMessageBodyFromContentLength(response, source, progress, cancellationToken); } throw new Exception("Could not determine how to read message body!"); } byte[] BuildMessageBodyFromCache(HttpResponse response, Progress progress, CancellationToken cancellationToken) { using(CacheStream source = cacheHandler.GetMessageBodyStream(response.Request)) { MemoryStream destination = new MemoryStream(); if(source.CanSeek) { progress.Start(source.BytesRemaining); source.CopyTo(destination, source.BytesRemaining, cancellationToken, progress); } else { progress.Start(); source.CopyTo(destination, cancellationToken); } progress.Finialize(); return destination.ToArray(); } } byte[] BuildMessageBodyFromChunked(HttpResponse response, HttpStream source, Progress progress, CancellationToken cancellationToken) { MemoryStream destination = new MemoryStream(); progress.Start(); long chunkSize = ReadChunkSize(source); while(chunkSize > 0) { source.CopyTo(destination, chunkSize, cancellationToken, progress); source.SkipTo(LF); chunkSize = ReadChunkSize(source); } source.SkipTo(LF); progress.Finialize(); return DecodeMessageBody(response, destination, cancellationToken); } byte[] BuildMessageBodyFromContentLength(HttpResponse response, HttpStream source, Progress progress, CancellationToken cancellationToken) { long contentLength = long.Parse(response.Headers[HeaderField.ContentLength][0]); MemoryStream destination = new MemoryStream(); progress.Start(contentLength); source.CopyTo(destination, contentLength, cancellationToken, progress); progress.Finialize(); return DecodeMessageBody(response, destination, cancellationToken); } byte[] DecodeMessageBody(HttpResponse response, MemoryStream messageStream, CancellationToken cancellationToken) { if(response.Headers.Contains(HeaderField.ContentEncoding, "gzip")) { messageStream.Seek(0, SeekOrigin.Begin); return DecodeMessageBodyAsGzip(messageStream, cancellationToken); } return messageStream.ToArray(); } byte[] DecodeMessageBodyAsGzip(MemoryStream compressedStream, CancellationToken cancellationToken) { using(GzipDecompressStream gzipStream = new GzipDecompressStream(compressedStream)) { MemoryStream destination = new MemoryStream(); gzipStream.CopyTo(destination, cancellationToken); return destination.ToArray(); } } long ReadChunkSize(HttpStream source) { MemoryStream destination = new MemoryStream(); source.ReadTo(destination, LF); string hexStr = Encoding.ASCII.GetString(destination.ToArray()).TrimEnd(CR, LF); return long.Parse(hexStr, NumberStyles.HexNumber); } void ProcessCookie(HttpResponse response) { if(settings.useCookies) { cookieJar.Update(response); } } void ProcessCache(HttpResponse response) { if(settings.useCache) { if(response.StatusCode == StatusCode.NotModified) { response.Headers.Append(HeaderField.ContentType, response.Request.cache.contentType); } if(cacheHandler.IsCachable(response)) { cacheHandler.CacheResponse(response); } } } } }
taka-oyama/UniHttp
Assets/UniHttp/Support/Response/ResponseHandler.cs
C#
mit
6,030
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Zend_Pdf_Element_String */ // require_once 'Zend/Pdf/Element/String.php'; /** * PDF file 'binary string' element implementation * * @category Zend * @package Zend_Pdf * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Element_String_Binary extends Zend_Pdf_Element_String { /** * Object value * * @var string */ public $value; /** * Escape string according to the PDF rules * * @param string $inStr * @return string */ public static function escape($inStr) { return strtoupper(bin2hex($inStr)); } /** * Unescape string according to the PDF rules * * @param string $inStr * @return string */ public static function unescape($inStr) { $chunks = array(); $offset = 0; $length = 0; while ($offset < strlen($inStr)) { // Collect hexadecimal characters $start = $offset; $offset += strspn($inStr, "0123456789abcdefABCDEF", $offset); $chunks[] = substr($inStr, $start, $offset - $start); $length += strlen(end($chunks)); // Skip non-hexadecimal characters $offset += strcspn($inStr, "0123456789abcdefABCDEF", $offset); } if ($length % 2 != 0) { // We have odd number of digits. // Final digit is assumed to be '0' $chunks[] = '0'; } return pack('H*' , implode($chunks)); } /** * Return object as string * * @param Zend_Pdf_Factory $factory * @return string */ public function toString($factory = null) { return '<' . self::escape((string)$this->value) . '>'; } }
ProfilerTeam/Profiler
protected/vendors/Zend/Pdf/Element/String/Binary.php
PHP
mit
2,543
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.uff.ic.oceano.ostra.service.behaviortable; import br.uff.ic.oceano.util.NumberUtil; import br.uff.ic.oceano.ostra.model.DataMiningPattern; import br.uff.ic.oceano.ostra.model.DataMiningResult; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * * @author DanCastellani */ public class Behavior { private DataMiningResult dataMiningResult; private List<DataMiningPattern> rules = new ArrayList<DataMiningPattern>(); private String value = ""; private Double highestConfidence = 0D; //prefix private static final String PROPORTIONAL = "proportional_"; private static final String INVERSE = "inverse_"; private static final String NEUTRAL = "neutral"; //proportional private static final String PROPORTIONAL_MINUS = PROPORTIONAL + "minus"; private static final String PROPORTIONAL_PLUS = PROPORTIONAL + "plus"; private static final String PROPORTIONAL_BOTH = PROPORTIONAL + "both"; //inverse private static final String INVERSE_MINUS_PLUS = INVERSE + "minus_plus"; private static final String INVERSE_PLUS_MINUS = INVERSE + "plus_minus"; private static final String INVERSE_BOTH = INVERSE + "both"; private static final String INVERSE_NEUTRAL_MINUS = INVERSE + "neutral_minus"; private static final String INVERSE_NEUTRAL_PLUS = INVERSE + "neutral_plus"; //undefined private static final String UNDEFINED = "undefined"; private static final String NO_BEHAVIOR = "no_behavior"; public String getFormatedRules() { String s = ""; for (DataMiningPattern rule : rules) { s += rule.toString() + "<br/>"; } return s; } public String getBehaviorName() { return getBehaviorName_Real(); } public String getBehaviorName_Real() { List<String> behaviors = new LinkedList<String>(); for (DataMiningPattern dataMiningPattern : rules) { behaviors.add(getSimpleBehaviorName(dataMiningPattern)); } final boolean hasNeutralBehavior = existsBehavior(behaviors, NEUTRAL); final boolean hasProportionalBehavior = existsBehavior(behaviors, PROPORTIONAL); final boolean hasInverseBehavior = existsBehavior(behaviors, INVERSE); if (hasInverseBehavior && hasProportionalBehavior) { return UNDEFINED; } if (hasInverseBehavior) { if (hasNeutralBehavior) { //because neutral is proportional (0 -> 0) return UNDEFINED; } else { final boolean hasInverseMinusPlus = existsBehavior(behaviors, INVERSE_MINUS_PLUS); final boolean hasInversePlusMinus = existsBehavior(behaviors, INVERSE_PLUS_MINUS); final boolean hasInverseNeutralMinus = existsBehavior(behaviors, INVERSE_NEUTRAL_MINUS); final boolean hasInverseNeutralPlus = existsBehavior(behaviors, INVERSE_NEUTRAL_PLUS); // if (hasInverseMinusPlus && hasInversePlusMinus) { // return INVERSE_BOTH; // } if (hasInverseMinusPlus) { return INVERSE_MINUS_PLUS; } if (hasInversePlusMinus) { return INVERSE_PLUS_MINUS; } if (hasInverseNeutralMinus && hasInverseNeutralPlus) { DataMiningPattern betterPattern = null; final String dataMiningMetricName = dataMiningResult.getRuleMetricName(); for (DataMiningPattern currentDataMiningPattern : rules) { if (betterPattern == null) { betterPattern = currentDataMiningPattern; } if (betterPattern.getMetricValue(dataMiningMetricName) < currentDataMiningPattern.getMetricValue(dataMiningMetricName)) { betterPattern = currentDataMiningPattern; } else if (betterPattern.getMetricValue(dataMiningMetricName) == currentDataMiningPattern.getMetricValue(dataMiningMetricName)) { if (betterPattern.getSupport() < currentDataMiningPattern.getSupport()) { betterPattern = currentDataMiningPattern; } } } return getSimpleBehaviorName(betterPattern); // return INVERSE_BOTH; } if (hasInverseNeutralMinus) { return INVERSE_NEUTRAL_MINUS; } if (hasInverseNeutralPlus) { return INVERSE_NEUTRAL_PLUS; } } } else if (hasProportionalBehavior) { final boolean hasProportionalMinus = existsBehavior(behaviors, PROPORTIONAL_MINUS); final boolean hasProportionalPlus = existsBehavior(behaviors, PROPORTIONAL_PLUS); //as for proportional behavior, the neutral doesnt influence, we will ignore it. if (hasProportionalMinus && hasProportionalPlus) { DataMiningPattern betterPattern = null; final String dataMiningMetricName = dataMiningResult.getRuleMetricName(); for (DataMiningPattern currentDataMiningPattern : rules) { if (betterPattern == null) { betterPattern = currentDataMiningPattern; } if (betterPattern.getMetricValue(dataMiningMetricName) < currentDataMiningPattern.getMetricValue(dataMiningMetricName)) { betterPattern = currentDataMiningPattern; } else if (betterPattern.getMetricValue(dataMiningMetricName) == currentDataMiningPattern.getMetricValue(dataMiningMetricName)) { if (betterPattern.getSupport() < currentDataMiningPattern.getSupport()) { betterPattern = currentDataMiningPattern; } } } return getSimpleBehaviorName(betterPattern); // return PROPORTIONAL_BOTH; } if (hasProportionalMinus) { return PROPORTIONAL_MINUS; } if (hasProportionalPlus) { return PROPORTIONAL_PLUS; } } else if (hasNeutralBehavior) { return NEUTRAL; } return NO_BEHAVIOR; } private String getSimpleBehaviorName(DataMiningPattern rule) { final String behavior = getRuleBehavior(rule); if (behavior.equals("--")) { return PROPORTIONAL_MINUS; } else if (behavior.equals("++")) { return PROPORTIONAL_PLUS; } else if (behavior.equals("00")) { return NEUTRAL; } else if (behavior.equals("-+")) { return INVERSE_MINUS_PLUS; } else if (behavior.equals("-0")) { return INVERSE_NEUTRAL_MINUS; } else if (behavior.equals("+-")) { return INVERSE_PLUS_MINUS; } else if (behavior.equals("+0")) { return INVERSE_NEUTRAL_PLUS; } else if (behavior.equals("0+")) { return INVERSE_NEUTRAL_PLUS; } else if (behavior.equals("0-")) { return INVERSE_NEUTRAL_MINUS; } else { return NO_BEHAVIOR; } } public Behavior(DataMiningResult dataMiningResult) { this.dataMiningResult = dataMiningResult; } public Behavior(String value, DataMiningResult dataMiningResult) { this.value = value; this.dataMiningResult = dataMiningResult; } /** * @return the rules */ public List<DataMiningPattern> getRules() { return rules; } /** * @param rules the rules to set */ public void setRules(List<DataMiningPattern> rules) { this.rules = rules; } /** * @return the value */ public String getValue() { return value; } /** * @return the value */ public String getShortValue() { if (value.length() >= 3) { return value.substring(0, 3); } else { return value; } } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } @Override public String toString() { return value; } /** * @return the highestConfidence */ public Double getHighestConfidence() { return highestConfidence; } /** * @return the highestConfidence */ public String getFormatedHighestConfidence() { return NumberUtil.format(highestConfidence); } /** * @param highestConfidence the highestConfidence to set */ public void setHighestConfidence(Double highestConfidence) { this.highestConfidence = highestConfidence; } private static String getRuleBehavior(DataMiningPattern rule) { return DataMiningPattern.getValue(rule.getPrecedent()) + DataMiningPattern.getValue(rule.getConsequent()); } private boolean existsBehavior(List<String> behaviors, String prefix) { for (String behavior : behaviors) { if (behavior.startsWith(prefix)) { return true; } } return false; } public String getAverageSuport() { double sum = 0; for (DataMiningPattern rule : rules) { sum += rule.getSupport()!=null?rule.getSupport():0.0; } return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum); } public String getAverageConfidence() { double sum = 0; for (DataMiningPattern rule : rules) { sum += rule.getConfidence()!=null?rule.getConfidence():0.0; } return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum); } public String getAverageLift() { double sum = 0; for (DataMiningPattern rule : rules) { sum += rule.getLift()!=null?rule.getLift():0.0; } return NumberUtil.format((rules != null && !rules.isEmpty()) ? sum / rules.size() : sum); } /** * @return the dataMiningResult */ public DataMiningResult getDataMiningResult() { return dataMiningResult; } /** * @param dataMiningResult the dataMiningResult to set */ public void setDataMiningResult(DataMiningResult dataMiningResult) { this.dataMiningResult = dataMiningResult; } }
gems-uff/oceano
web/src/main/java/br/uff/ic/oceano/ostra/service/behaviortable/Behavior.java
Java
mit
10,770
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using MathNet.Spatial.Euclidean; using MathNet.Spatial.Units; namespace Large_File_Transformations { public class AppViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; #region Properties private string _transformationString; private string _outputFileName; private string _inputFileName; private bool _isNotBusy; private string _displayText; public string DisplayText { get { return _displayText; } set { if (value == _displayText) return; _displayText = value; RaisePropertyChanged(); } } public string InputFileName { get { return _inputFileName; } set { if (value == _inputFileName) return; _inputFileName = value; this.SetOutputFileName(); RaisePropertyChanged(); } } public string OutputFileName { get { return _outputFileName; } set { if (value == _outputFileName) return; _outputFileName = value; RaisePropertyChanged(); } } public string TransformationString { get { return _transformationString; } set { if (value == _transformationString) return; _transformationString = value; RaisePropertyChanged(); } } public bool IsNotBusy { get { return _isNotBusy; } set { if (value == _isNotBusy) return; _isNotBusy = value; RaisePropertyChanged(); } } #endregion public AppViewModel() { this.IsNotBusy = true; this.TransformationString = "0, 0, 0, 0"; } /// <summary> /// Called when the input filename has been changed in the property setter, this method automatically /// creates a new output file name in the same directory with a suffix before the file extension /// </summary> private void SetOutputFileName() { string extension = Path.GetExtension(this.InputFileName); string filename = Path.GetFileNameWithoutExtension(this.InputFileName); string directory = Path.GetDirectoryName(this.InputFileName); string newName = filename + "_transformed" + extension; this.OutputFileName = Path.Combine(directory, newName); } public void ExecuteTransformation() { if (!TransformationStringParser.Parse(this.TransformationString).IsValid) return; this.IsNotBusy = false; BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.ProgressChanged += WorkerOnProgressChanged; worker.RunWorkerCompleted += WorkerOnRunWorkerCompleted; worker.DoWork += WorkerOnDoWork; worker.RunWorkerAsync(); } private void WorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { int lineCount = 0; long fileSize = new FileInfo(this.InputFileName).Length; long readSize = 0; List<string> buffer = new List<string>(); // Load the transforms var transform = TransformationStringParser.Parse(this.TransformationString); Angle angle = new Angle(transform.Rz, new Degrees()); Vector3D rotationAxis = new Vector3D(0, 0, 1); Vector3D shift = new Vector3D(transform.Tx, transform.Ty, transform.Tz); Regex extractor = new Regex(@"-{0,1}\d*\.\d+"); using (StreamReader reader = new StreamReader(this.InputFileName)) { string line; while ((line = reader.ReadLine()) != null) { readSize += ASCIIEncoding.ASCII.GetByteCount(line); // Do the work here and add it to buffer var matches = extractor.Matches(line); if (matches.Count != 3) { throw new ArgumentException("Error, wrong number of matches in line: " + line); } var p = new Point3D(double.Parse(matches[0].ToString()), double.Parse(matches[1].ToString()), double.Parse(matches[2].ToString())); // Point3D t = (p.Rotate(rotationAxis, angle)) + shift; Point3D t = (p + shift).Rotate(rotationAxis, angle); buffer.Add(t.X + " " + t.Y + " " + t.Z); if (buffer.Count >= 500) { File.AppendAllLines(this.OutputFileName, buffer); buffer.Clear(); this.WorkerOnProgressChanged(sender, new ProgressChangedEventArgs(1, (double)(readSize) / fileSize)); } } File.AppendAllLines(this.OutputFileName, buffer); } } private void WorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { this.IsNotBusy = true; this.DisplayText = "Done"; } private void WorkerOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs) { this.DisplayText = string.Format("{0:0.00}%", (double)progressChangedEventArgs.UserState * 100); } protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
mattj23/tree_point_tools
Large File Transformations/Large File Transformations/AppViewModel.cs
C#
mit
6,219
<div class="hide"> <div class="white-popup mfp-with-anim mfp-hide" id="thanks"> <h4 class="popup-title">Сообщение отправлено!</h4> <p class="sub-title-text">Спасибо, мы свяжемся с вами в ближайшее время.</p> </div> </div>
InterProFront/InterProShop
resources/views/front/popups/thank.blade.php
PHP
mit
301
import { remote } from '../../../src' describe('parent element test', () => { it('should return parent element of an element', async () => { const browser = await remote({ capabilities: { browserName: 'foobar' } }) const elem = await browser.$('#foo') const subElem = await elem.$('#bar') const parentEl = await subElem.parentElement() expect(parentEl.elementId).toBe('some-parent-elem') }) it('should throw error if parent element does not exist', async () => { const browser = await remote({ waitforInterval: 1, waitforTimeout: 1, capabilities: { browserName: 'foobar' } }) const elem = await browser.$('#foo') const parentElem = await elem.parentElement() const err = await parentElem.click().catch((err) => err) expect(err.message) .toContain('parent element of element with selector "#foo"') }) })
webdriverio/webdriverio
packages/webdriverio/tests/commands/element/parentElement.test.ts
TypeScript
mit
1,035
'use strict' const Twitter = require('twitter') const twitterOpts = require('./auth.json') const client = new Twitter(twitterOpts) const twttr = require('./twttr/') twttr.getTrendingTopics(client).then((tt) => { tt.forEach((topic, idx) => { twttr.searchTopic(client, topic).then((tweets) => { let statuses = twttr.transformTweets(tweets) console.log(statuses) // insights: word count, graphos etc. }) }) })
edravis/pulse
index.js
JavaScript
mit
437
import game import pygame from pygame.locals import * class Resources: <<<<<<< HEAD def cambiar(self,imagen): sheet = game.load_image(imagen) rects = [pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(4,4,30,38), pygame.Rect(4,4,30,38), pygame.Rect(4,4,30,38)] caminando_der = game.load_sprites(sheet, rects, (0,0,0)) caminando_izq = game.flip_sprites(caminando_der) rects = [pygame.Rect(76,2,26,40), pygame.Rect(112,2,24,40)] quieto_der = game.load_sprites(sheet, rects, (0,0,0)) quieto_izq = game.flip_sprites(quieto_der) rects = [pygame.Rect(4,4,30,38), pygame.Rect(38,4,30,36)] saltando_der = game.load_sprites(sheet, rects, (0,0,0)) saltando_izq = game.flip_sprites(saltando_der) player = [ [quieto_der, quieto_izq], [caminando_der,caminando_izq], [saltando_der, saltando_izq]] return player def __init__(self,imagen): # Carga de imagenes self.imagen=imagen sheet = game.load_image(self.imagen) ======= def __init__(self): # Carga de imagenes sheet = game.load_image('graphics/arc22.png') >>>>>>> origin/master #rects = [#pygame.Rect(514,8,24,34), # pygame.Rect(550,8,30,34), # pygame.Rect(582,8,28,34), # pygame.Rect(550,8,30,34)] rects = [pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(112,2,26,40), pygame.Rect(4,4,30,38), pygame.Rect(4,4,30,38), pygame.Rect(4,4,30,38)] caminando_der = game.load_sprites(sheet, rects, (0,0,0)) caminando_izq = game.flip_sprites(caminando_der) rects = [pygame.Rect(76,2,26,40), pygame.Rect(112,2,24,40)] quieto_der = game.load_sprites(sheet, rects, (0,0,0)) quieto_izq = game.flip_sprites(quieto_der) <<<<<<< HEAD ======= >>>>>>> origin/master rects = [pygame.Rect(4,4,30,38), pygame.Rect(38,4,30,36)] saltando_der = game.load_sprites(sheet, rects, (0,0,0)) saltando_izq = game.flip_sprites(saltando_der) self.player = [ [quieto_der, quieto_izq], [caminando_der,caminando_izq], [saltando_der, saltando_izq]] <<<<<<< HEAD ======= >>>>>>> origin/master sheet = game.load_image('graphics/blocks11.png') suelo = game.load_sprite(sheet, pygame.Rect(444,104,32,32)) subsuelo = game.load_sprite(sheet, pygame.Rect(172,138,32,32)) self.tiles = [suelo, subsuelo]
cangothic/2D-Platformer
resources.py
Python
mit
2,891
module Mutations class CreateProject < BaseMutation argument :brand_id, ID, required: true argument :project_attributes, Types::ProjectAttributes, required: true field :project, Types::ProjectType, null: false def authorized?(brand_id:, project_attributes:) @brand = Brand.find(brand_id) @project = @brand.projects.new(project_attributes.to_h) context[:current_ability].authorize! :create, @project true end def resolve(**_args) @project.save! { project: @project } end end end
neinteractiveliterature/larp_library
app/graphql/mutations/create_project.rb
Ruby
mit
549
package commandParsing.exceptions; import gui.factories.ErrorFactory; import java.util.HashMap; import java.util.Map; import drawableobject.DrawableObject; public class RunTimeDivideByZeroException extends SLOGOException { private static final long serialVersionUID = 1L; public RunTimeDivideByZeroException () { super(); } public RunTimeDivideByZeroException (String stringOfInterest) { super(stringOfInterest); } public RunTimeDivideByZeroException (Throwable exception) { super(exception); } public RunTimeDivideByZeroException (String stringOfInterest, Throwable cause) { super(stringOfInterest, cause); } @Override public DrawableObject generateErrorMessage () { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ErrorFactory.ERROR_MESSAGE, "Error: divided by zero."); return new DrawableObject(ErrorFactory.PARENT, ErrorFactory.TYPE, parameters); } }
akyker20/Slogo_IDE
src/commandParsing/exceptions/RunTimeDivideByZeroException.java
Java
mit
1,002
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; namespace Unicorn { /// <summary> /// /// </summary> /// <see cref="http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266932.aspx"/> public class AsyncBarrier { private readonly int participantCount; private int remainingParticipants; private ConcurrentStack<TaskCompletionSource<bool>> waiters; public AsyncBarrier(int participantCount) { if (participantCount <= 0) { throw new ArgumentOutOfRangeException("participantCount"); } remainingParticipants = this.participantCount = participantCount; waiters = new ConcurrentStack<TaskCompletionSource<bool>>(); } public Task SignalAndWait() { var tcs = new TaskCompletionSource<bool>(); waiters.Push(tcs); if (Interlocked.Decrement(ref remainingParticipants) == 0) { remainingParticipants = participantCount; var waiters = this.waiters; this.waiters = new ConcurrentStack<TaskCompletionSource<bool>>(); Parallel.ForEach(waiters, w => w.SetResult(true)); } return tcs.Task; } } }
FatJohn/UnicornToolkit
Library/Unicorn.Shared/Threading.Tasks.Synchronize/AsyncBarrier.cs
C#
mit
1,353
<?php /** * Spiral Framework. Scaffolder * * @license MIT * @author Anton Titov (Wolfy-J) * @author Valentin V (vvval) */ declare(strict_types=1); namespace Spiral\Scaffolder\Declaration; use Spiral\Console\Command; use Spiral\Reactor\ClassDeclaration; use Spiral\Reactor\DependedInterface; class CommandDeclaration extends ClassDeclaration implements DependedInterface { public function __construct(string $name, string $comment = '') { parent::__construct($name, 'Command', [], $comment); $this->declareStructure(); } /** * {@inheritdoc} */ public function getDependencies(): array { return [Command::class => null]; } /** * Set command alias. */ public function setAlias(string $name): void { $this->constant('NAME')->setValue($name); } public function setDescription(string $description): void { $this->constant('DESCRIPTION')->setValue($description); } /** * Declare default command body. */ private function declareStructure(): void { $perform = $this->method('perform')->setProtected(); $perform->setReturn('void'); $perform->setComment('Perform command'); $this->constant('NAME')->setProtected()->setValue(''); $this->constant('DESCRIPTION')->setProtected()->setValue(''); $this->constant('ARGUMENTS')->setProtected()->setValue([]); $this->constant('OPTIONS')->setProtected()->setValue([]); } }
spiral-modules/scaffolder
src/Declaration/CommandDeclaration.php
PHP
mit
1,520
import Aquaman from './components/Aquaman.jsx'; // eslint-disable-line no-unused-vars import '../styles/appStyles.scss';
mvezer/aquaman
src/client/js/app.js
JavaScript
mit
121
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Animal")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Animal")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1083093f-2582-458d-9e54-063f81044017")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
owolp/Telerik-Academy
Module-1/OOP/Homework/04-OOP-Principles-Part-1/Animal/Properties/AssemblyInfo.cs
C#
mit
1,343
// File: corpus_test.cpp #include "crn_core.h" #include "corpus_test.h" #include "crn_find_files.h" #include "crn_console.h" #include "crn_image_utils.h" #include "crn_hash.h" #include "crn_hash_map.h" #include "crn_radix_sort.h" #include "crn_mipmapped_texture.h" namespace crnlib { corpus_tester::corpus_tester() { m_bad_block_img.resize(256, 256); m_next_bad_block_index = 0; m_total_bad_block_files = 0; } void corpus_tester::print_comparative_metric_stats(const command_line_params& cmd_line_params, const crnlib::vector<image_utils::error_metrics>& stats1, const crnlib::vector<image_utils::error_metrics>& stats2, uint num_blocks_x, uint num_blocks_y) { num_blocks_y; crnlib::vector<uint> better_blocks; crnlib::vector<uint> equal_blocks; crnlib::vector<uint> worse_blocks; crnlib::vector<float> delta_psnr; for (uint i = 0; i < stats1.size(); i++) { //uint bx = i % num_blocks_x; //uint by = i / num_blocks_x; const image_utils::error_metrics& em1 = stats1[i]; const image_utils::error_metrics& em2 = stats2[i]; if (em1.mPeakSNR < em2.mPeakSNR) { worse_blocks.push_back(i); delta_psnr.push_back((float)(em2.mPeakSNR - em1.mPeakSNR)); } else if (fabs(em1.mPeakSNR - em2.mPeakSNR) < .001f) equal_blocks.push_back(i); else better_blocks.push_back(i); } console::printf("Num worse blocks: %u, %3.3f%%", worse_blocks.size(), worse_blocks.size() * 100.0f / stats1.size()); console::printf("Num equal blocks: %u, %3.3f%%", equal_blocks.size(), equal_blocks.size() * 100.0f / stats1.size()); console::printf("Num better blocks: %u, %3.3f%%", better_blocks.size(), better_blocks.size() * 100.0f / stats1.size()); console::printf("Num equal+better blocks: %u, %3.3f%%", equal_blocks.size() + better_blocks.size(), (equal_blocks.size() + better_blocks.size()) * 100.0f / stats1.size()); if (!cmd_line_params.has_key("nobadblocks")) { crnlib::vector<uint> indices[2]; indices[0].resize(worse_blocks.size()); indices[1].resize(worse_blocks.size()); uint* pSorted_indices = NULL; if (worse_blocks.size()) { pSorted_indices = indirect_radix_sort(worse_blocks.size(), &indices[0][0], &indices[1][0], &delta_psnr[0], 0, sizeof(float), true); console::printf("List of worse blocks sorted by delta PSNR:"); for (uint i = 0; i < worse_blocks.size(); i++) { uint block_index = worse_blocks[pSorted_indices[i]]; uint bx = block_index % num_blocks_x; uint by = block_index / num_blocks_x; console::printf("%u. [%u,%u] %3.3f %3.3f %3.3f", i, bx, by, stats1[block_index].mPeakSNR, stats2[block_index].mPeakSNR, stats2[block_index].mPeakSNR - stats1[block_index].mPeakSNR); } } } } void corpus_tester::print_metric_stats(const crnlib::vector<image_utils::error_metrics>& stats, uint num_blocks_x, uint num_blocks_y) { num_blocks_y; image_utils::error_metrics best_metrics; image_utils::error_metrics worst_metrics; worst_metrics.mPeakSNR = 1e+6f; vec2I best_loc; vec2I worst_loc; utils::zero_object(best_loc); utils::zero_object(worst_loc); double psnr_total = 0.0f; double psnr2_total = 0.0f; uint num_non_inf = 0; uint num_inf = 0; for (uint i = 0; i < stats.size(); i++) { uint bx = i % num_blocks_x; uint by = i / num_blocks_x; const image_utils::error_metrics& em = stats[i]; if ((em.mPeakSNR < 200.0f) && (em > best_metrics)) { best_metrics = em; best_loc.set(bx, by); } if (em < worst_metrics) { worst_metrics = em; worst_loc.set(bx, by); } if (em.mPeakSNR < 200.0f) { psnr_total += em.mPeakSNR; psnr2_total += em.mPeakSNR * em.mPeakSNR; num_non_inf++; } else { num_inf++; } } console::printf("Number of infinite PSNR blocks: %u", num_inf); console::printf("Number of non-infinite PSNR blocks: %u", num_non_inf); if (num_non_inf) { psnr_total /= num_non_inf; psnr2_total /= num_non_inf; double psnr_std_dev = sqrt(psnr2_total - psnr_total * psnr_total); console::printf("Average Non-Inf PSNR: %3.3f, Std dev: %3.3f", psnr_total, psnr_std_dev); console::printf("Worst PSNR: %3.3f, Block Location: %i,%i", worst_metrics.mPeakSNR, worst_loc[0], worst_loc[1]); console::printf("Best Non-Inf PSNR: %3.3f, Block Location: %i,%i", best_metrics.mPeakSNR, best_loc[0], best_loc[1]); } } void corpus_tester::flush_bad_blocks() { if (!m_next_bad_block_index) return; dynamic_string filename(cVarArg, "badblocks_%u.tga", m_total_bad_block_files); console::printf("Writing bad block image: %s", filename.get_ptr()); image_utils::write_to_file(filename.get_ptr(), m_bad_block_img, image_utils::cWriteFlagIgnoreAlpha); m_bad_block_img.set_all(color_quad_u8::make_black()); m_total_bad_block_files++; m_next_bad_block_index = 0; } void corpus_tester::add_bad_block(image_u8& block) { uint num_blocks_x = m_bad_block_img.get_block_width(4); uint num_blocks_y = m_bad_block_img.get_block_height(4); uint total_blocks = num_blocks_x * num_blocks_y; m_bad_block_img.blit((m_next_bad_block_index % num_blocks_x) * 4, (m_next_bad_block_index / num_blocks_x) * 4, block); m_next_bad_block_index++; if (m_next_bad_block_index == total_blocks) flush_bad_blocks(); } static bool progress_callback(uint percentage_complete, void* pUser_data_ptr) { static int s_prev_percentage_complete = -1; pUser_data_ptr; if (s_prev_percentage_complete != static_cast<int>(percentage_complete)) { console::progress("%u%%", percentage_complete); s_prev_percentage_complete = percentage_complete; } return true; } bool corpus_tester::test(const char* pCmd_line) { console::printf("Command line:\n\"%s\"", pCmd_line); static const command_line_params::param_desc param_desc_array[] = { {"corpus_test", 0, false}, {"in", 1, true}, {"deep", 0, false}, {"alpha", 0, false}, {"nomips", 0, false}, {"perceptual", 0, false}, {"endpointcaching", 0, false}, {"multithreaded", 0, false}, {"writehybrid", 0, false}, {"nobadblocks", 0, false}, }; command_line_params cmd_line_params; if (!cmd_line_params.parse(pCmd_line, CRNLIB_ARRAY_SIZE(param_desc_array), param_desc_array, true)) return false; double total_time1 = 0, total_time2 = 0; command_line_params::param_map_const_iterator it = cmd_line_params.begin(); for (; it != cmd_line_params.end(); ++it) { if (it->first != "in") continue; if (it->second.m_values.empty()) { console::error("Must follow /in parameter with a filename!\n"); return false; } for (uint in_value_index = 0; in_value_index < it->second.m_values.size(); in_value_index++) { const dynamic_string& filespec = it->second.m_values[in_value_index]; find_files file_finder; if (!file_finder.find(filespec.get_ptr(), find_files::cFlagAllowFiles | (cmd_line_params.has_key("deep") ? find_files::cFlagRecursive : 0))) { console::warning("Failed finding files: %s", filespec.get_ptr()); continue; } if (file_finder.get_files().empty()) { console::warning("No files found: %s", filespec.get_ptr()); return false; } const find_files::file_desc_vec& files = file_finder.get_files(); image_u8 o(4, 4), a(4, 4), b(4, 4); uint first_channel = 0; uint num_channels = 3; bool perceptual = cmd_line_params.get_value_as_bool("perceptual", false); if (perceptual) { first_channel = 0; num_channels = 0; } console::printf("Perceptual mode: %u", perceptual); for (uint file_index = 0; file_index < files.size(); file_index++) { const find_files::file_desc& file_desc = files[file_index]; console::printf("-------- Loading image: %s", file_desc.m_fullname.get_ptr()); image_u8 img; if (!image_utils::read_from_file(img, file_desc.m_fullname.get_ptr(), 0)) { console::warning("Failed loading image file: %s", file_desc.m_fullname.get_ptr()); continue; } if ((!cmd_line_params.has_key("alpha")) && img.is_component_valid(3)) { for (uint y = 0; y < img.get_height(); y++) for (uint x = 0; x < img.get_width(); x++) img(x, y).a = 255; img.set_component_valid(3, false); } mipmapped_texture orig_tex; orig_tex.assign(crnlib_new<image_u8>(img)); if (!cmd_line_params.has_key("nomips")) { mipmapped_texture::generate_mipmap_params genmip_params; genmip_params.m_srgb = true; console::printf("Generating mipmaps"); if (!orig_tex.generate_mipmaps(genmip_params, false)) { console::error("Mipmap generation failed!"); return false; } } console::printf("Compress 1"); mipmapped_texture tex1(orig_tex); dxt_image::pack_params convert_params; convert_params.m_endpoint_caching = cmd_line_params.get_value_as_bool("endpointcaching", 0, false); convert_params.m_compressor = cCRNDXTCompressorCRN; convert_params.m_quality = cCRNDXTQualityNormal; convert_params.m_perceptual = perceptual; convert_params.m_num_helper_threads = cmd_line_params.get_value_as_bool("multithreaded", 0, true) ? (g_number_of_processors - 1) : 0; convert_params.m_pProgress_callback = progress_callback; timer t; t.start(); if (!tex1.convert(PIXEL_FMT_ETC1, false, convert_params)) { console::error("Texture conversion failed!"); return false; } double time1 = t.get_elapsed_secs(); total_time1 += time1; console::printf("Elapsed time: %3.3f", time1); console::printf("Compress 2"); mipmapped_texture tex2(orig_tex); convert_params.m_endpoint_caching = false; convert_params.m_compressor = cCRNDXTCompressorCRN; convert_params.m_quality = cCRNDXTQualitySuperFast; t.start(); if (!tex2.convert(PIXEL_FMT_ETC1, false, convert_params)) { console::error("Texture conversion failed!"); return false; } double time2 = t.get_elapsed_secs(); total_time2 += time2; console::printf("Elapsed time: %3.3f", time2); image_u8 hybrid_img(img.get_width(), img.get_height()); for (uint l = 0; l < orig_tex.get_num_levels(); l++) { image_u8 orig_img, img1, img2; image_u8* pOrig = orig_tex.get_level(0, l)->get_unpacked_image(orig_img, cUnpackFlagUncook | cUnpackFlagUnflip); image_u8* pImg1 = tex1.get_level(0, l)->get_unpacked_image(img1, cUnpackFlagUncook | cUnpackFlagUnflip); image_u8* pImg2 = tex2.get_level(0, l)->get_unpacked_image(img2, cUnpackFlagUncook | cUnpackFlagUnflip); const uint num_blocks_x = pOrig->get_block_width(4); const uint num_blocks_y = pOrig->get_block_height(4); crnlib::vector<image_utils::error_metrics> metrics[2]; for (uint by = 0; by < num_blocks_y; by++) { for (uint bx = 0; bx < num_blocks_x; bx++) { pOrig->extract_block(o.get_ptr(), bx * 4, by * 4, 4, 4); pImg1->extract_block(a.get_ptr(), bx * 4, by * 4, 4, 4); pImg2->extract_block(b.get_ptr(), bx * 4, by * 4, 4, 4); image_utils::error_metrics em1; em1.compute(o, a, first_channel, num_channels); image_utils::error_metrics em2; em2.compute(o, b, first_channel, num_channels); metrics[0].push_back(em1); metrics[1].push_back(em2); if (em1.mPeakSNR < em2.mPeakSNR) { add_bad_block(o); hybrid_img.blit(bx * 4, by * 4, b); } else { hybrid_img.blit(bx * 4, by * 4, a); } } } if (cmd_line_params.has_key("writehybrid")) image_utils::write_to_file("hybrid.tga", hybrid_img, image_utils::cWriteFlagIgnoreAlpha); console::printf("---- Mip level: %u, Total blocks: %ux%u, %u", l, num_blocks_x, num_blocks_y, num_blocks_x * num_blocks_y); console::printf("Compressor 1:"); print_metric_stats(metrics[0], num_blocks_x, num_blocks_y); console::printf("Compressor 2:"); print_metric_stats(metrics[1], num_blocks_x, num_blocks_y); console::printf("Compressor 1 vs. 2:"); print_comparative_metric_stats(cmd_line_params, metrics[0], metrics[1], num_blocks_x, num_blocks_y); image_utils::error_metrics em; em.compute(*pOrig, *pImg1, 0, perceptual ? 0 : 3); em.print("Compressor 1: "); em.compute(*pOrig, *pImg2, 0, perceptual ? 0 : 3); em.print("Compressor 2: "); em.compute(*pOrig, hybrid_img, 0, perceptual ? 0 : 3); em.print("Best of Both: "); } } } // file_index } flush_bad_blocks(); console::printf("Total times: %4.3f vs. %4.3f", total_time1, total_time2); return true; } } // namespace crnlib
rokups/Urho3D
Source/ThirdParty/crunch/crunch/corpus_test.cpp
C++
mit
13,342
#!/usr/bin/env ruby dir = File.expand_path(File.dirname(__FILE__)) $: << dir unless $:.include?(dir) require 'switchy' class Sparky attr_accessor :passed, :failed, :pending @@run_pins = [[Switchy::PINS::C4, Switchy::PINS::C2], [Switchy::PINS::C5, Switchy::PINS::D0 ]] @@fail_pins = [[Switchy::PINS::C6, Switchy::PINS::D1], [Switchy::PINS::C7, Switchy::PINS::D2]] @@pending_pins = [[Switchy::PINS::B7, Switchy::PINS::D3], [Switchy::PINS::B6, Switchy::PINS::D4]] @@pass_pins = [[Switchy::PINS::B3, Switchy::PINS::D7, Switchy::PINS::B5, Switchy::PINS::D5], [Switchy::PINS::B2, Switchy::PINS::B0, Switchy::PINS::B4, Switchy::PINS::D6]] @@reset_pins = [[Switchy::PINS::C4, Switchy::PINS::C2, Switchy::PINS::C6, Switchy::PINS::D1, Switchy::PINS::B7, Switchy::PINS::D3, Switchy::PINS::B5, Switchy::PINS::B3, Switchy::PINS::D7, Switchy::PINS::D5]] def initialize @passed, @failed, @pending = -1, -1, -1 @switchy = Switchy.new end def set_pins(pins) pins.first.each do |pin| @switchy.set_pin pin, 1 end pins.last.each do |pin| @switchy.set_pin pin, 0 end end def set_pin(pin) @switchy.set_pin pin.first, 1 @switchy.set_pin pin.last, 0 end def clear_pin(pin) @switchy.set_pin pin.first, 0 end def clear_pins(pins) pins.first.each do |pin| @switchy.set_pin pin, 0 end end def pass set_pins @@pass_pins end alias :passed :pass def clear_pass clear_pins @@pass_pins end def fail set_pins @@fail_pins end alias :failed :fail def clear_failed clear_pins @@fail_pins end def pending set_pins @@pending_pins end def clear_pending clear_pins @@pending_pins end def run set_pins @@run_pins end def clear_run clear_pins @@run_pins end def reset clear_pins @@reset_pins end def start_run reset run end def finish_run reset if @failed > -1 failed elsif @pending > -1 pending else pass end end def example_passed clear_pin pin(:passed, @passed % 4) if @passed >= 0 @passed += 1 set_pin pin(:passed, @passed % 4) end def example_failed clear_pin pin(:failed, @failed % 2) if @failed >= 0 @failed += 1 set_pin pin(:failed, @failed % 2) end def example_pending clear_pin pin(:pending, @pending % 2) if @pending >= 0 @pending += 1 set_pin pin(:pending, @pending % 2) end def pin(set, idx) pins = case set when :passed then @@pass_pins when :failed then @@fail_pins when :pending then @@pending_pins end [ pins.first[idx], pins.last[idx] ] end end
dbrady/switchy
lib/sparky.rb
Ruby
mit
2,796
#include "masternodemanager.h" #include "ui_masternodemanager.h" #include "addeditadrenalinenode.h" #include "adrenalinenodeconfigdialog.h" #include "sync.h" #include "clientmodel.h" #include "walletmodel.h" #include "activemasternode.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "masternode.h" #include "walletdb.h" #include "wallet.h" #include "init.h" #include "rpcserver.h" #include <boost/lexical_cast.hpp> #include <fstream> using namespace json_spirit; using namespace std; #include <QAbstractItemDelegate> #include <QPainter> #include <QTimer> #include <QDebug> #include <QScrollArea> #include <QScroller> #include <QDateTime> #include <QApplication> #include <QClipboard> #include <QMessageBox> #include <QThread> #include <QtConcurrent/QtConcurrent> #include <QScrollBar> MasternodeManager::MasternodeManager(QWidget *parent) : QWidget(parent), ui(new Ui::MasternodeManager), clientModel(0), walletModel(0) { ui->setupUi(this); ui->editButton->setEnabled(false); ui->startButton->setEnabled(false); ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableWidget_2->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableWidget_3->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateNodeList())); if(!GetBoolArg("-reindexaddr", false)) timer->start(1000); fFilterUpdated = true; nTimeFilterUpdated = GetTime(); updateNodeList(); } MasternodeManager::~MasternodeManager() { delete ui; } void MasternodeManager::on_tableWidget_2_itemSelectionChanged() { if(ui->tableWidget_2->selectedItems().count() > 0) { ui->editButton->setEnabled(true); ui->startButton->setEnabled(true); } } void MasternodeManager::updateAdrenalineNode(QString alias, QString addr, QString privkey, QString txHash, QString txIndex, QString donationAddress, QString donationPercentage, QString status) { LOCK(cs_adrenaline); bool bFound = false; int nodeRow = 0; for(int i=0; i < ui->tableWidget_2->rowCount(); i++) { if(ui->tableWidget_2->item(i, 0)->text() == alias) { bFound = true; nodeRow = i; break; } } if(nodeRow == 0 && !bFound) ui->tableWidget_2->insertRow(0); QTableWidgetItem *aliasItem = new QTableWidgetItem(alias); QTableWidgetItem *addrItem = new QTableWidgetItem(addr); QTableWidgetItem *donationAddressItem = new QTableWidgetItem(donationAddress); QTableWidgetItem *donationPercentageItem = new QTableWidgetItem(donationPercentage); QTableWidgetItem *statusItem = new QTableWidgetItem(status); ui->tableWidget_2->setItem(nodeRow, 0, aliasItem); ui->tableWidget_2->setItem(nodeRow, 1, addrItem); ui->tableWidget_2->setItem(nodeRow, 2, donationPercentageItem); ui->tableWidget_2->setItem(nodeRow, 3, donationAddressItem); ui->tableWidget_2->setItem(nodeRow, 4, statusItem); } static QString seconds_to_DHMS(quint32 duration) { QString res; int seconds = (int) (duration % 60); duration /= 60; int minutes = (int) (duration % 60); duration /= 60; int hours = (int) (duration % 24); int days = (int) (duration / 24); if((hours == 0)&&(days == 0)) return res.sprintf("%02dm:%02ds", minutes, seconds); if (days == 0) return res.sprintf("%02dh:%02dm:%02ds", hours, minutes, seconds); return res.sprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds); } void MasternodeManager::updateListConc() { if (ui->tableWidget->isVisible()) { ui->tableWidget_3->clearContents(); ui->tableWidget_3->setRowCount(0); std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector(); ui->tableWidget_3->horizontalHeader()->setSortIndicator(ui->tableWidget->horizontalHeader()->sortIndicatorSection() ,ui->tableWidget->horizontalHeader()->sortIndicatorOrder()); BOOST_FOREACH(CMasternode& mn, vMasternodes) { int mnRow = 0; ui->tableWidget_3->insertRow(0); // populate list // Address, Rank, Active, Active Seconds, Last Seen, Pub Key QTableWidgetItem *activeItem = new QTableWidgetItem(QString::number(mn.IsEnabled())); QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString())); QString Rank = QString::number(mnodeman.GetMasternodeRank(mn.vin, pindexBest->nHeight)); QTableWidgetItem *rankItem = new QTableWidgetItem(Rank.rightJustified(2, '0', false)); QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(mn.lastTimeSeen - mn.sigTime))); QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat(mn.lastTimeSeen))); CScript pubkey; pubkey =GetScriptForDestination(mn.pubkey.GetID()); CTxDestination address1; ExtractDestination(pubkey, address1); CTransfercoinAddress address2(address1); QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(address2.ToString())); ui->tableWidget_3->setItem(mnRow, 0, addressItem); ui->tableWidget_3->setItem(mnRow, 1, rankItem); ui->tableWidget_3->setItem(mnRow, 2, activeItem); ui->tableWidget_3->setItem(mnRow, 3, activeSecondsItem); ui->tableWidget_3->setItem(mnRow, 4, lastSeenItem); ui->tableWidget_3->setItem(mnRow, 5, pubkeyItem); } ui->countLabel->setText(QString::number(ui->tableWidget_3->rowCount())); on_UpdateButton_clicked(); ui->tableWidget->setVisible(0); ui->tableWidget_3->setVisible(1); ui->tableWidget_3->verticalScrollBar()->setSliderPosition(ui->tableWidget->verticalScrollBar()->sliderPosition()); } else { ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector(); ui->tableWidget->horizontalHeader()->setSortIndicator(ui->tableWidget_3->horizontalHeader()->sortIndicatorSection() ,ui->tableWidget_3->horizontalHeader()->sortIndicatorOrder()); BOOST_FOREACH(CMasternode& mn, vMasternodes) { int mnRow = 0; ui->tableWidget->insertRow(0); // populate list // Address, Rank, Active, Active Seconds, Last Seen, Pub Key QTableWidgetItem *activeItem = new QTableWidgetItem(QString::number(mn.IsEnabled())); QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString())); QString Rank = QString::number(mnodeman.GetMasternodeRank(mn.vin, pindexBest->nHeight)); QTableWidgetItem *rankItem = new QTableWidgetItem(Rank.rightJustified(2, '0', false)); QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(mn.lastTimeSeen - mn.sigTime))); QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat(mn.lastTimeSeen))); CScript pubkey; pubkey =GetScriptForDestination(mn.pubkey.GetID()); CTxDestination address1; ExtractDestination(pubkey, address1); CTransfercoinAddress address2(address1); QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(address2.ToString())); ui->tableWidget->setItem(mnRow, 0, addressItem); ui->tableWidget->setItem(mnRow, 1, rankItem); ui->tableWidget->setItem(mnRow, 2, activeItem); ui->tableWidget->setItem(mnRow, 3, activeSecondsItem); ui->tableWidget->setItem(mnRow, 4, lastSeenItem); ui->tableWidget->setItem(mnRow, 5, pubkeyItem); } ui->countLabel->setText(QString::number(ui->tableWidget->rowCount())); on_UpdateButton_clicked(); ui->tableWidget_3->setVisible(0); ui->tableWidget->setVisible(1); ui->tableWidget->verticalScrollBar()->setSliderPosition(ui->tableWidget_3->verticalScrollBar()->sliderPosition()); } } void MasternodeManager::updateNodeList() { TRY_LOCK(cs_masternodes, lockMasternodes); if(!lockMasternodes) return; static int64_t nTimeListUpdated = GetTime(); // to prevent high cpu usage update only once in MASTERNODELIST_UPDATE_SECONDS seconds // or MASTERNODELIST_FILTER_COOLDOWN_SECONDS seconds after filter was last changed int64_t nSecondsToWait = fFilterUpdated ? nTimeFilterUpdated - GetTime() + MASTERNODELIST_FILTER_COOLDOWN_SECONDS : nTimeListUpdated - GetTime() + MASTERNODELIST_UPDATE_SECONDS; if (fFilterUpdated) ui->countLabel->setText(QString::fromStdString(strprintf("Please wait... %d", nSecondsToWait))); if (nSecondsToWait > 0) return; nTimeListUpdated = GetTime(); nTimeListUpdated = GetTime(); fFilterUpdated = false; if (f1.isFinished()) f1 = QtConcurrent::run(this,&MasternodeManager::updateListConc); } void MasternodeManager::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { } } void MasternodeManager::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { } } void MasternodeManager::on_createButton_clicked() { AddEditAdrenalineNode* aenode = new AddEditAdrenalineNode(); aenode->exec(); } void MasternodeManager::on_startButton_clicked() { // start the node QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); QModelIndexList selected = selectionModel->selectedRows(); if(selected.count() == 0) return; QModelIndex index = selected.at(0); int r = index.row(); std::string sAlias = ui->tableWidget_2->item(r, 0)->text().toStdString(); if(pwalletMain->IsLocked()) { } std::string statusObj; statusObj += "<center>Alias: " + sAlias; BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { if(mne.getAlias() == sAlias) { std::string errorMessage; std::string strDonateAddress = mne.getDonationAddress(); std::string strDonationPercentage = mne.getDonationPercentage(); bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strDonateAddress, strDonationPercentage, errorMessage); if(result) { statusObj += "<br>Successfully started masternode." ; } else { statusObj += "<br>Failed to start masternode.<br>Error: " + errorMessage; } break; } } statusObj += "</center>"; pwalletMain->Lock(); QMessageBox msg; msg.setText(QString::fromStdString(statusObj)); msg.exec(); } void MasternodeManager::on_startAllButton_clicked() { if(pwalletMain->IsLocked()) { } std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; int total = 0; int successful = 0; int fail = 0; std::string statusObj; BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { total++; std::string errorMessage; std::string strDonateAddress = mne.getDonationAddress(); std::string strDonationPercentage = mne.getDonationPercentage(); bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strDonateAddress, strDonationPercentage, errorMessage); if(result) { successful++; } else { fail++; statusObj += "\nFailed to start " + mne.getAlias() + ". Error: " + errorMessage; } } pwalletMain->Lock(); std::string returnObj; returnObj = "Successfully started " + boost::lexical_cast<std::string>(successful) + " masternodes, failed to start " + boost::lexical_cast<std::string>(fail) + ", total " + boost::lexical_cast<std::string>(total); if (fail > 0) returnObj += statusObj; QMessageBox msg; msg.setText(QString::fromStdString(returnObj)); msg.exec(); } void MasternodeManager::on_UpdateButton_clicked() { BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::string strDonateAddress = mne.getDonationAddress(); std::string strDonationPercentage = mne.getDonationPercentage(); std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector(); if (errorMessage == ""){ updateAdrenalineNode(QString::fromStdString(mne.getAlias()), QString::fromStdString(mne.getIp()), QString::fromStdString(mne.getPrivKey()), QString::fromStdString(mne.getTxHash()), QString::fromStdString(mne.getOutputIndex()), QString::fromStdString(strDonateAddress), QString::fromStdString(strDonationPercentage), QString::fromStdString("Not in the masternode list.")); } else { updateAdrenalineNode(QString::fromStdString(mne.getAlias()), QString::fromStdString(mne.getIp()), QString::fromStdString(mne.getPrivKey()), QString::fromStdString(mne.getTxHash()), QString::fromStdString(mne.getOutputIndex()), QString::fromStdString(strDonateAddress), QString::fromStdString(strDonationPercentage), QString::fromStdString(errorMessage)); } BOOST_FOREACH(CMasternode& mn, vMasternodes) { if (mn.addr.ToString().c_str() == mne.getIp()){ updateAdrenalineNode(QString::fromStdString(mne.getAlias()), QString::fromStdString(mne.getIp()), QString::fromStdString(mne.getPrivKey()), QString::fromStdString(mne.getTxHash()), QString::fromStdString(mne.getOutputIndex()), QString::fromStdString(strDonateAddress), QString::fromStdString(strDonationPercentage), QString::fromStdString("Masternode is Running.")); } } } }
transferdev/Transfercoin
src/qt/masternodemanager.cpp
C++
mit
13,652
# frozen_string_literal: true module Platform module Unions class Account < Platform::Unions::Base description "Users and organizations." visibility :internal possible_types( Objects::User, Objects::Organization, Objects::Bot, ) def self.resolve_type(obj, ctx) :stand_in end end end end
xuorig/graphql-ruby
spec/fixtures/upgrader/account.transformed.rb
Ruby
mit
370
module ConsoleTweet VERSION = '0.1.6' end
seejohnrun/console_tweet
lib/console_tweet/version.rb
Ruby
mit
46
#include "PMDGWrapper.h" static enum DATA_REQUEST_ID { DATA_REQUEST, CONTROL_REQUEST, AIR_PATH_REQUEST }; static enum EVENT_ID { EVENT_SIM_START, // used to track the loaded aircraft }; HANDLE hSimConnect = NULL; byte bQuit=false; PMDG_NGX_Data sPmdgData; int iPmdgUpdated=0; PMDG_NGX_Control sControl; void(__stdcall * airCraftLoadedCallback)(char *airPath); HANDLE PollForDataThread; bool InitSimConnect(bool restart) { int hr=SimConnect_Open(&hSimConnect, "PMDGWrapper", NULL, 0, 0, 0); if (!SUCCEEDED(hr)) { hSimConnect=NULL; return false; } // 1) Set up data connection SetupDataConnection(); // 2) Set up control connection SetupControlConnection(); // 3) Request current aircraft .air file path //hr = SimConnect_RequestSystemState(hSimConnect, AIR_PATH_REQUEST, "AircraftLoaded"); // also request notifications on sim start and aircraft change if (!restart) hr = SimConnect_SubscribeToSystemEvent(hSimConnect, EVENT_SIM_START, "SimStart"); // process messages if (PollForDataThread==NULL) PollForDataThread = CreateThread(NULL, 0, PollForData, 0, 0, NULL); // get the first data Sleep(50); return true; } void SetupDataConnection() { // Associate an ID with the PMDG data area name int hr = SimConnect_MapClientDataNameToID (hSimConnect, PMDG_NGX_DATA_NAME, PMDG_NGX_DATA_ID); // Define the data area structure - this is a required step int size=sizeof(PMDG_NGX_Data); hr = SimConnect_AddToClientDataDefinition (hSimConnect, PMDG_NGX_DATA_DEFINITION, 0, sizeof(PMDG_NGX_Data), 0, 0); // Sign up for notification of data change. // SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_CHANGED flag asks for the data to be sent only when some of the data is changed. hr = SimConnect_RequestClientData(hSimConnect, PMDG_NGX_DATA_ID, DATA_REQUEST, PMDG_NGX_DATA_DEFINITION, SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_CHANGED, 0, 0, 0); } void SetupControlConnection() { // First method: control data area sControl.Event = 0; sControl.Parameter = 0; // Associate an ID with the PMDG control area name int hr = SimConnect_MapClientDataNameToID (hSimConnect, PMDG_NGX_CONTROL_NAME, PMDG_NGX_CONTROL_ID); // Define the control area structure - this is a required step hr = SimConnect_AddToClientDataDefinition (hSimConnect, PMDG_NGX_CONTROL_DEFINITION, 0, sizeof(PMDG_NGX_Control), 0, 0); // Sign up for notification of control change. hr = SimConnect_RequestClientData(hSimConnect, PMDG_NGX_CONTROL_ID, CONTROL_REQUEST, PMDG_NGX_CONTROL_DEFINITION, SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_CHANGED, 0, 0, 0); } void CloseSimConnect() { SimConnect_Close(hSimConnect); hSimConnect=NULL; } DWORD WINAPI PollForData(LPVOID lpParam) { while( bQuit == 0 ) { // receive and process the NGX data SimConnect_CallDispatch(hSimConnect, MyDispatchProc, NULL); if (false) { CloseSimConnect(); InitSimConnect(true); } Sleep(100); } return 0; } void CALLBACK MyDispatchProc(SIMCONNECT_RECV* pData, DWORD cbData, void *pContext) { switch(pData->dwID) { case SIMCONNECT_RECV_ID_EXCEPTION: break; case SIMCONNECT_RECV_ID_OPEN: break; case SIMCONNECT_RECV_ID_CLIENT_DATA: // Receive and process the NGX data block { SIMCONNECT_RECV_CLIENT_DATA *pObjData = (SIMCONNECT_RECV_CLIENT_DATA*)pData; switch(pObjData->dwRequestID) { case DATA_REQUEST: { if (iPmdgUpdated%100 == 0) printf("Receive and process the NGX data block count=%d\n", iPmdgUpdated); PMDG_NGX_Data *pS = (PMDG_NGX_Data*)&pObjData->dwData; sPmdgData = *pS; iPmdgUpdated++; break; } case CONTROL_REQUEST: { printf("Receive and process the NGX control block event=%d\n", ((PMDG_NGX_Control*)&pObjData->dwData)->Event); // keep the present state of Control area to know if the server had received and reset the command PMDG_NGX_Control *pS = (PMDG_NGX_Control*)&pObjData->dwData; //printf("Received control: %d %d\n", pS->Event, pS->Parameter); sControl = *pS; break; } } break; } case SIMCONNECT_RECV_ID_EVENT: { SIMCONNECT_RECV_EVENT *evt = (SIMCONNECT_RECV_EVENT*)pData; switch (evt->uEventID) { case EVENT_SIM_START: // Track aircraft changes { HRESULT hr = SimConnect_RequestSystemState(hSimConnect, AIR_PATH_REQUEST, "AircraftLoaded"); break; } } break; } case SIMCONNECT_RECV_ID_SYSTEM_STATE: // Track aircraft changes { SIMCONNECT_RECV_SYSTEM_STATE *evt = (SIMCONNECT_RECV_SYSTEM_STATE*)pData; if (evt->dwRequestID == AIR_PATH_REQUEST) { if (airCraftLoadedCallback!=NULL) airCraftLoadedCallback(evt->szString); if (strstr(evt->szString, "PMDG 737") != NULL) { //SetupDataConnection(); //SetupControlConnection(); } } break; } case SIMCONNECT_RECV_ID_QUIT: { break; } default: printf("Received:%d\n",pData->dwID); break; } fflush(stdout); } __declspec(dllexport) void SetACLoadedCallback(void(__stdcall * callback)(char *airPath)) { airCraftLoadedCallback=callback; HRESULT hr = SimConnect_RequestSystemState(hSimConnect, AIR_PATH_REQUEST, "AircraftLoaded"); } __declspec(dllexport) int GetPMDGDataStructureLength() { int size=sizeof(PMDG_NGX_Data); return size; } __declspec(dllexport) void* GetPMDGData() { return &sPmdgData; } void RaiseMPDGEvent(char *eventName, int parameter) { int eventID = offsetof(PMDG_NGX_Data, COMM_ServiceInterphoneSw); } __declspec(dllexport) int RaisePMDGEvent(int pmdgEvent, int parameter) { if (hSimConnect==NULL) return -1; // wait for the previous command to finish while (sControl.Event != 0) Sleep(2); sControl.Event = pmdgEvent; sControl.Parameter = parameter; int hr=SimConnect_SetClientData (hSimConnect, PMDG_NGX_CONTROL_ID, PMDG_NGX_CONTROL_DEFINITION, 0, 0, sizeof(PMDG_NGX_Control), &sControl); return hr>0 ? 1 : 0; }
maciekish/SimInterface
Windows/PMDGWrapper/PMDGWrapper.cpp
C++
mit
5,917
package openssl import ( "fmt" "io/ioutil" "os/exec" "regexp" log "github.com/cihub/seelog" ) type CSR struct { //path string //key string content []byte contentKey []byte } func (o *Openssl) LoadCSR(filename, keyfile string) (*CSR, error) { var err error o.Init() filename = o.Path + "/" + filename keyfile = o.Path + "/" + keyfile c := &CSR{} c.content, err = ioutil.ReadFile(filename) if err != nil { return nil, err } c.contentKey, err = ioutil.ReadFile(keyfile) if err != nil { return nil, err } return c, nil } func (o *Openssl) CreateCSR(cn string, server bool) (*CSR, error) { var err error o.Init() log.Info("Create CSR") c := &CSR{} args := []string{ "req", "-days", "3650", "-nodes", "-new", "-keyout", "/dev/stdout", "-out", "/dev/stdout", "-config", o.GetConfigFile(), "-batch", "-utf8", "-subj", "/C=" + o.Country + "/ST=" + o.Province + "/L=" + o.City + "/O=" + o.Organization + "/CN=" + cn + "/emailAddress=" + o.Email, } if server { args = append(args, "-extensions", "server") } content, err := exec.Command("openssl", args...).CombinedOutput() if err != nil { return nil, fmt.Errorf("openssl req: " + err.Error() + " (" + string(content) + ")") } reCert := regexp.MustCompile("(?ms)-----BEGIN CERTIFICATE REQUEST-----(.+)-----END CERTIFICATE REQUEST-----") reKey := regexp.MustCompile("(?ms)-----BEGIN PRIVATE KEY-----(.+)-----END PRIVATE KEY-----") c.content = reCert.Find(content) c.contentKey = reKey.Find(content) if len(c.content) == 0 { err = fmt.Errorf("Generated csr is 0 long") return nil, err } if len(c.contentKey) == 0 { err = fmt.Errorf("Generated csr key is 0 long") return nil, err } //if err = ioutil.WriteFile(c.key, c.contentKey, 0600); err != nil { //return nil, err //} return c, nil } func (csr *CSR) Save(filename string) error { if err := ioutil.WriteFile(filename, csr.content, 0600); err != nil { return err } return nil } func (csr *CSR) SaveKey(filename string) error { if err := ioutil.WriteFile(filename, csr.contentKey, 0600); err != nil { return err } return nil } func (csr *CSR) String() string { if csr != nil { return string(csr.content) } return "" } func (csr *CSR) KeyString() string { if csr != nil { return string(csr.contentKey) } return "" }
stamp/go-openssl
csr.go
GO
mit
2,332
const Hapi = require('hapi'); const Request = require('request'); const port = process.env.PORT || 8080; const server = new Hapi.Server(); const cephalopods = 'http://api.gbif.org/v1/species/136'; server.connection({ port: port, host: '0.0.0.0' }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { Request(cephalopods, function (err, response, body) { return reply(body); }); } }); server.start(function () { console.log('Server started on ' + port); });
nvcexploder/fishy-nodevember
index.js
JavaScript
mit
545
namespace $ { /** @deprecated Use `$mol_wire_probe` */ export let $mol_atom2_value = $mol_wire_probe /** @deprecated Use `$mol_wire_field` */ export let $mol_atom2_field = $mol_wire_field /** @deprecated Doesn't reqired anymore */ export function $mol_atom2_autorun( calculate : ()=> any ) { return new $mol_after_frame( calculate ) } }
eigenmethod/mol
atom2/atom2.ts
TypeScript
mit
354
const {env, browsers} = require('config'); const isProd = env === 'production'; module.exports = { // parser: 'sugarss', plugins: { 'postcss-preset-env': browsers, 'cssnano': isProd ? {} : false, } };
TongChia/frontend-boilerplate
postcss.config.js
JavaScript
mit
216
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; namespace osu.Desktop.Tests.Beatmaps { public class TestWorkingBeatmap : WorkingBeatmap { public TestWorkingBeatmap(Beatmap beatmap) : base(beatmap.BeatmapInfo) { this.beatmap = beatmap; } private readonly Beatmap beatmap; protected override Beatmap GetBeatmap() => beatmap; protected override Texture GetBackground() => null; protected override Track GetTrack() => null; } }
Damnae/osu
osu.Desktop.Tests/Beatmaps/TestWorkingBeatmap.cs
C#
mit
746
#include "pipeline_builder.hpp" #include "pipeline_state.hpp" #include "shader.hpp" #include "shader_signature.hpp" #include "constants.hpp" #include "../Common/texture_formats_common.hpp" #include <set> #include <algorithm> namespace AgpuGL { void processTextureWithSamplerCombinations(const std::set<TextureWithSamplerCombination> &rawTextureSamplerCombinations, const agpu::shader_signature_ref &shaderSignature, TextureWithSamplerCombinationMap &map, std::vector<MappedTextureWithSamplerCombination> &usedCombinations) { // Split between natural pairs, and non-natural pairs. std::vector<MappedTextureWithSamplerCombination> naturalTextureWithSamplerCombinations; std::vector<MappedTextureWithSamplerCombination> nonNaturalTextureWithSamplerCombinations; auto glShaderSignature = shaderSignature.as<GLShaderSignature> (); for (auto & combination : rawTextureSamplerCombinations) { int textureUnit = glShaderSignature->mapDescriptorSetAndBinding(AGPU_SHADER_BINDING_TYPE_SAMPLED_IMAGE, combination.textureDescriptorSet, combination.textureDescriptorBinding); if (textureUnit < 0) return; int sampler = glShaderSignature->mapDescriptorSetAndBinding(AGPU_SHADER_BINDING_TYPE_SAMPLER, combination.samplerDescriptorSet, combination.samplerDescriptorBinding); if (sampler < 0) return; MappedTextureWithSamplerCombination mappedCombination; mappedCombination.combination = combination; mappedCombination.name = combination.createName(); mappedCombination.sourceTextureUnit = textureUnit; mappedCombination.sourceSamplerUnit = sampler; if (textureUnit == sampler) naturalTextureWithSamplerCombinations.push_back(mappedCombination); else nonNaturalTextureWithSamplerCombinations.push_back(mappedCombination); } auto naturalTextureUnitCount = glShaderSignature->bindingPointsUsed[(int)OpenGLResourceBindingType::Sampler]; // Assign the natural pairs usedCombinations.reserve(naturalTextureWithSamplerCombinations.size() + nonNaturalTextureWithSamplerCombinations.size()); for (auto &combination : naturalTextureWithSamplerCombinations) { combination.mappedTextureUnit = combination.mappedSamplerUnit = combination.sourceSamplerUnit; usedCombinations.push_back(combination); } // Assign the non-natural pairs auto nextTextureUnit = naturalTextureUnitCount; for (auto &combination : nonNaturalTextureWithSamplerCombinations) { combination.mappedTextureUnit = nextTextureUnit++; combination.mappedSamplerUnit = combination.sourceSamplerUnit; usedCombinations.push_back(combination); } for (auto &combination : usedCombinations) { map.insert(std::make_pair(combination.combination, combination)); } } GLGraphicsPipelineBuilder::GLGraphicsPipelineBuilder() { // Depth buffer depthEnabled = false; depthWriteMask = true; depthFunction = AGPU_LESS; // Depth biasing depthBiasEnabled = false; depthBiasConstantFactor = 0; depthBiasClamp = 0; depthBiasSlopeFactor = 0; // Face culling frontFaceWinding = AGPU_COUNTER_CLOCKWISE; cullingMode = AGPU_CULL_MODE_NONE; // Polgons polygonMode = AGPU_POLYGON_MODE_FILL; // Color buffer blendingEnabled = false; redMask = true; greenMask = true; blueMask = true; alphaMask = true; sourceBlendFactor = AGPU_BLENDING_ONE; destBlendFactor = AGPU_BLENDING_ZERO; blendOperation = AGPU_BLENDING_OPERATION_ADD; sourceBlendFactorAlpha = AGPU_BLENDING_ONE; destBlendFactorAlpha = AGPU_BLENDING_ZERO; blendOperationAlpha = AGPU_BLENDING_OPERATION_ADD; // Stencil buffer stencilEnabled = false; stencilWriteMask = ~0; stencilReadMask = ~0; stencilFrontFailOp = AGPU_KEEP; stencilFrontDepthFailOp = AGPU_KEEP; stencilFrontDepthPassOp = AGPU_KEEP; stencilFrontFunc = AGPU_ALWAYS; stencilBackFailOp = AGPU_KEEP; stencilBackDepthFailOp = AGPU_KEEP; stencilBackDepthPassOp = AGPU_KEEP; stencilBackFunc = AGPU_ALWAYS; // Render targets renderTargetFormats.resize(1, AGPU_TEXTURE_FORMAT_B8G8R8A8_UNORM); depthStencilFormat = AGPU_TEXTURE_FORMAT_D24_UNORM_S8_UINT; primitiveType = AGPU_POINTS; } GLGraphicsPipelineBuilder::~GLGraphicsPipelineBuilder() { } agpu::pipeline_builder_ref GLGraphicsPipelineBuilder::createBuilder(const agpu::device_ref &device) { auto result = agpu::makeObject<GLGraphicsPipelineBuilder> (); auto builder = result.as<GLGraphicsPipelineBuilder> (); builder->device = device; builder->reset(); return result; } agpu_error GLGraphicsPipelineBuilder::reset() { shaders.clear(); errorMessages.clear(); return AGPU_OK; } void GLGraphicsPipelineBuilder::buildTextureWithSampleCombinationMapInto(TextureWithSamplerCombinationMap &map, std::vector<MappedTextureWithSamplerCombination> &usedCombinations) { std::set<TextureWithSamplerCombination> rawTextureSamplerCombinations; // Get all of the combinations. for(auto &shaderWithEntryPoint : shaders) { auto shader = shaderWithEntryPoint.first; if(!shader) continue; for (auto combination : shader.as<GLShader>()->getTextureWithSamplerCombination(shaderWithEntryPoint.second)) rawTextureSamplerCombinations.insert(combination); } processTextureWithSamplerCombinations(rawTextureSamplerCombinations, shaderSignature, map, usedCombinations); } agpu::pipeline_state_ptr GLGraphicsPipelineBuilder::build () { GLuint program = 0; GLint baseInstanceUniformIndex = -1; bool succeded = true; std::vector<GLShaderForSignatureRef> shaderInstances; std::vector<MappedTextureWithSamplerCombination> mappedTextureWithSamplerCombinations; TextureWithSamplerCombinationMap textureWithSamplerCombinationMap; if(!shaders.empty()) { buildTextureWithSampleCombinationMapInto(textureWithSamplerCombinationMap, mappedTextureWithSamplerCombinations); // Instantiate the shaders for(auto &shaderWithEntryPoint : shaders) { const auto &shader = shaderWithEntryPoint.first; if(!shaderSignature) { errorMessages += "Missing shader signature."; succeded = false; break; } GLShaderForSignatureRef shaderForSignature; std::string errorMessage; // Create the shader instance. auto error = shader.as<GLShader> ()->instanceForSignature(shaderSignature, textureWithSamplerCombinationMap, shaderWithEntryPoint.second, &shaderForSignature, &errorMessage); errorMessages += errorMessage; if(error != AGPU_OK) { printError("Instance error: %d:%s\n", error, errorMessage.c_str()); succeded = false; break; } shaderInstances.push_back(shaderForSignature); } if(!succeded) return nullptr; succeded = false; deviceForGL->onMainContextBlocking([&]{ // Create the progrma program = deviceForGL->glCreateProgram(); // Attach the shaders. for(auto shaderInstance : shaderInstances) { // Attach the shader instance to the program. std::string errorMessage; auto error = shaderInstance->attachToProgram(program, &errorMessage); errorMessages += errorMessage; if(error != AGPU_OK) return; } // Link the program. deviceForGL->glLinkProgram(program); // Check the link status GLint status; deviceForGL->glGetProgramiv(program, GL_LINK_STATUS, &status); if(status != GL_TRUE) { // TODO: Get the info log return; } // Get some special uniforms baseInstanceUniformIndex = deviceForGL->glGetUniformLocation(program, "SPIRV_Cross_BaseInstance"); succeded = true; }); } if(!succeded) return nullptr; // Create the pipeline state object auto result = agpu::makeObject<GLPipelineState> (); auto pipeline = result.as<GLPipelineState> (); pipeline->device = device; pipeline->programHandle = program; pipeline->type = AgpuPipelineStateType::Graphics; pipeline->shaderSignature = shaderSignature; pipeline->shaderInstances = shaderInstances; pipeline->mappedTextureWithSamplerCombinations = mappedTextureWithSamplerCombinations; auto graphicsState = new AgpuGraphicsPipelineStateData(); graphicsState->device = device; pipeline->extraStateData = graphicsState; // Base instance graphicsState->baseInstanceUniformIndex = baseInstanceUniformIndex; // Depth state graphicsState->depthEnabled = depthEnabled; graphicsState->depthWriteMask = depthWriteMask; graphicsState->depthFunction = mapCompareFunction(depthFunction); // Face culling graphicsState->frontFaceWinding = mapFaceWinding(frontFaceWinding); graphicsState->cullingMode = mapCullingMode(cullingMode); // Color buffer graphicsState->blendingEnabled = blendingEnabled; graphicsState->redMask = redMask; graphicsState->greenMask = greenMask; graphicsState->blueMask = blueMask; graphicsState->alphaMask = alphaMask; graphicsState->sourceBlendFactor = mapBlendFactor(sourceBlendFactor, false); graphicsState->destBlendFactor = mapBlendFactor(destBlendFactor, false); graphicsState->blendOperation = mapBlendOperation(blendOperation); graphicsState->sourceBlendFactorAlpha = mapBlendFactor(sourceBlendFactorAlpha, true); graphicsState->destBlendFactorAlpha = mapBlendFactor(destBlendFactorAlpha, true); graphicsState->blendOperationAlpha = mapBlendOperation(blendOperationAlpha); // Stencil testing graphicsState->stencilEnabled = stencilEnabled; graphicsState->stencilWriteMask = stencilWriteMask; graphicsState->stencilReadMask = stencilReadMask; graphicsState->stencilFrontFailOp = mapStencilOperation(stencilFrontFailOp); graphicsState->stencilFrontDepthFailOp = mapStencilOperation(stencilFrontDepthFailOp); graphicsState->stencilFrontDepthPassOp = mapStencilOperation(stencilFrontDepthPassOp); graphicsState->stencilFrontFunc = mapCompareFunction(stencilFrontFunc); graphicsState->stencilBackFailOp = mapStencilOperation(stencilBackFailOp); graphicsState->stencilBackDepthFailOp = mapStencilOperation(stencilBackDepthFailOp); graphicsState->stencilBackDepthPassOp = mapStencilOperation(stencilBackDepthPassOp); graphicsState->stencilBackFunc = mapCompareFunction(stencilBackFunc); // Multisampling graphicsState->sampleCount = sampleCount; graphicsState->sampleQuality = sampleQuality; // Miscellaneous graphicsState->primitiveTopology = primitiveType; graphicsState->renderTargetCount = (int)renderTargetFormats.size(); graphicsState->hasSRGBTarget = false; for (auto format : renderTargetFormats) { if(isSRGBTextureFormat(format)) { graphicsState->hasSRGBTarget = true; break; } } return result.disown(); } agpu_error GLGraphicsPipelineBuilder::attachShader(const agpu::shader_ref &shader ) { CHECK_POINTER(shader); return attachShaderWithEntryPoint(shader, shader.as<GLShader> ()->type, "main"); } agpu_error GLGraphicsPipelineBuilder::attachShaderWithEntryPoint(const agpu::shader_ref &shader, agpu_shader_type type, agpu_cstring entry_point ) { CHECK_POINTER(shader); shaders.push_back(std::make_pair(shader, entry_point)); return AGPU_OK; } agpu_size GLGraphicsPipelineBuilder::getBuildingLogLength ( ) { return (agpu_size)errorMessages.size(); } agpu_error GLGraphicsPipelineBuilder::getBuildingLog ( agpu_size buffer_size, agpu_string_buffer buffer ) { if(buffer_size == 0) return AGPU_OK; size_t toCopy = std::min(size_t(buffer_size - 1), errorMessages.size()); if(toCopy > 0) memcpy(buffer, errorMessages.data(), toCopy); buffer[buffer_size-1] = 0; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setShaderSignature(const agpu::shader_signature_ref &signature) { CHECK_POINTER(signature); shaderSignature = signature; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setBlendState(agpu_int renderTargetMask, agpu_bool enabled) { this->blendingEnabled = enabled; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setBlendFunction(agpu_int renderTargetMask, agpu_blending_factor sourceFactor, agpu_blending_factor destFactor, agpu_blending_operation colorOperation, agpu_blending_factor sourceAlphaFactor, agpu_blending_factor destAlphaFactor, agpu_blending_operation alphaOperation) { this->sourceBlendFactor = sourceFactor; this->destBlendFactor = destFactor; this->blendOperation = colorOperation; this->sourceBlendFactorAlpha = sourceAlphaFactor; this->destBlendFactorAlpha = destAlphaFactor; this->blendOperationAlpha = alphaOperation; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setColorMask(agpu_int renderTargetMask, agpu_bool redEnabled, agpu_bool greenEnabled, agpu_bool blueEnabled, agpu_bool alphaEnabled) { this->redMask = redEnabled; this->greenMask = greenEnabled; this->blueMask = blueEnabled; this->alphaMask = alphaEnabled; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setFrontFace ( agpu_face_winding winding ) { this->frontFaceWinding = winding; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setCullMode ( agpu_cull_mode mode ) { this->cullingMode = mode; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setDepthBias ( agpu_float constant_factor, agpu_float clamp, agpu_float slope_factor ) { this->depthBiasEnabled = true; this->depthBiasConstantFactor = constant_factor; this->depthBiasClamp = clamp; this->depthBiasSlopeFactor = slope_factor; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setDepthState ( agpu_bool enabled, agpu_bool writeMask, agpu_compare_function function ) { this->depthEnabled = enabled; this->depthWriteMask = writeMask; this->depthFunction = function; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setStencilState ( agpu_bool enabled, agpu_int writeMask, agpu_int readMask ) { this->stencilEnabled = enabled; this->stencilWriteMask = writeMask; this->stencilReadMask = readMask; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setStencilFrontFace(agpu_stencil_operation stencilFailOperation, agpu_stencil_operation depthFailOperation, agpu_stencil_operation stencilDepthPassOperation, agpu_compare_function stencilFunction) { this->stencilFrontFailOp = stencilFailOperation; this->stencilFrontDepthFailOp = depthFailOperation; this->stencilFrontDepthPassOp = stencilDepthPassOperation; this->stencilFrontFunc = stencilFunction; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setStencilBackFace(agpu_stencil_operation stencilFailOperation, agpu_stencil_operation depthFailOperation, agpu_stencil_operation stencilDepthPassOperation, agpu_compare_function stencilFunction) { this->stencilBackFailOp = stencilFailOperation; this->stencilBackDepthFailOp = depthFailOperation; this->stencilBackDepthPassOp = stencilDepthPassOperation; this->stencilBackFunc = stencilFunction; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setRenderTargetCount(agpu_int count) { renderTargetFormats.resize(count, AGPU_TEXTURE_FORMAT_B8G8R8A8_UNORM); return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setRenderTargetFormat(agpu_uint index, agpu_texture_format format) { if (index >= renderTargetFormats.size()) return AGPU_INVALID_PARAMETER; renderTargetFormats[index] = format; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setDepthStencilFormat(agpu_texture_format format) { return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setPolygonMode(agpu_polygon_mode mode) { this->polygonMode = mode; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setPrimitiveType(agpu_primitive_topology type) { this->primitiveType = type; return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setVertexLayout(const agpu::vertex_layout_ref &layout) { return AGPU_OK; } agpu_error GLGraphicsPipelineBuilder::setSampleDescription(agpu_uint sample_count, agpu_uint sample_quality) { this->sampleCount = sample_count; this->sampleQuality = sample_quality; return AGPU_OK; } } // End of namespace AgpuGL
ronsaldo/abstract-gpu
implementations/OpenGL/pipeline_builder.cpp
C++
mit
16,588
$(document).ready(function() { SVGUpInstance.init('inforamaui', {"icons": { "logo":{"url":"images/inforama-icon.svg"}, "downarrow":{"url":"images/down-arrow.svg"}, "usericon":{"url":"images/user-icon.svg"} }, "classes":{ "mainstyle":{ "svgdefault":{"fillcolor":"#AA8833"}, "svghover":{"fillcolor":"#8CC63E"}, "cssdefault":{"opacity":"0.3", "width":"40px", "height":"40px", "transition":"all 0.5s"}, "csshover":{"opacity":"1", "width":"50px", "height":"50px"} } }} ); });
Inforama-dev/svgup
demos/bundles.js
JavaScript
mit
519
/* Copyright (c) 2009-2010 Satoshi Nakamoto Copyright (c) 2009-2012 The Bitcoin developers Copyright (c) 2013-2014 The StealthCoin/StealthSend Developers */ /* Copyright (c) 2014-2015, Triangles Developers */ /* See LICENSE for licensing information */ #include "anonymize.h" #include "util.h" #include <boost/filesystem.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <string> #include <cstring> char const* anonymize_tor_data_directory( ) { static std::string const retrieved = ( GetDataDir( ) / "tor" ).string( ); return retrieved.c_str( ); } char const* anonymize_service_directory( ) { static std::string const retrieved = ( GetDataDir( ) / "onion" ).string( ); return retrieved.c_str( ); } int check_interrupted( ) { return boost::this_thread::interruption_requested( ) ? 1 : 0; } static boost::mutex initializing; static std::auto_ptr<boost::unique_lock<boost::mutex> > uninitialized( new boost::unique_lock<boost::mutex>( initializing ) ); void set_initialized( ) { uninitialized.reset(); } void wait_initialized( ) { boost::unique_lock<boost::mutex> checking(initializing); }
wurstgelee/triangles
src/tor/anonymize.cpp
C++
mit
1,239
#include "input/inputmanager.h" namespace donut { TInputManager::TInputManager() { } TInputManager::~TInputManager() { } }
AnisB/Donut
engine/src/input/InputManager.cpp
C++
mit
135
/** * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.v8; import com.github.anba.es6draft.Script; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.internal.Properties.Function; import com.github.anba.es6draft.runtime.internal.Source; import com.github.anba.es6draft.runtime.objects.intl.IntlAbstractOperations; import com.github.anba.es6draft.runtime.objects.reflect.RealmObject; /** * Stub functions for tests. */ public final class TestingFunctions { /** shell-function: {@code gc()} */ @Function(name = "gc", arity = 0) public void gc() { // empty } /** * shell-function: {@code getDefaultLocale()} * * @param cx * the execution context * @return the default locale */ @Function(name = "getDefaultLocale", arity = 0) public String getDefaultLocale(ExecutionContext cx) { return IntlAbstractOperations.DefaultLocale(cx.getRealm()); } /** * shell-function: {@code getDefaultTimeZone()} * * @param cx * the execution context * @return the default timezone */ @Function(name = "getDefaultTimeZone", arity = 0) public String getDefaultTimeZone(ExecutionContext cx) { return IntlAbstractOperations.DefaultTimeZone(cx.getRealm()); } /** * shell-function: {@code getCurrentRealm()} * * @param cx * the execution context * @param caller * the caller execution context * @return the current realm object */ @Function(name = "getCurrentRealm", arity = 0) public RealmObject getCurrentRealm(ExecutionContext cx, ExecutionContext caller) { return caller.getRealm().getRealmObject(); } /** * shell-function: {@code evalInRealm(realm, sourceString)} * * @param cx * the execution context * @param caller * the caller execution context * @param realmObject * the target realm * @param sourceString * the source string * @return the evaluation result */ @Function(name = "evalInRealm", arity = 2) public Object evalInRealm(ExecutionContext cx, ExecutionContext caller, RealmObject realmObject, String sourceString) { Source source = new Source(caller.sourceInfo(), "<evalInRealm>", 1); Script script = realmObject.getRealm().getScriptLoader().script(source, sourceString); return script.evaluate(realmObject.getRealm()); } }
anba/es6draft
src/test/java/com/github/anba/es6draft/v8/TestingFunctions.java
Java
mit
2,712
package com.example.stream.eb.database; import android.content.Context; import org.greenrobot.greendao.database.Database; /** * Created by StReaM on 8/20/2017. */ public class DatabaseManager { private DaoSession mDaoSession = null; private UserProfileDao mDao = null; private DatabaseManager() { } public DatabaseManager init(Context context) { initDao(context); return this; } private static final class Holder { private static final DatabaseManager INSTANCE = new DatabaseManager(); } public static DatabaseManager getInstance (){ return Holder.INSTANCE; } private void initDao(Context context) { final ReleaseOpenHelper helper = new ReleaseOpenHelper(context, "stream_eb.db"); final Database db = helper.getWritableDb(); mDaoSession = new DaoMaster(db).newSession(); mDao = mDaoSession.getUserProfileDao(); } public final UserProfileDao getDao() { return mDao; } }
streamj/JX
stream-eb/src/main/java/com/example/stream/eb/database/DatabaseManager.java
Java
mit
1,027
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 clevelandcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock("0x620995fa30c65100adb47dc3cb4a0badb1c522a9d8e62bbb630e8c3e6b9c1717"); static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // clevelandcoin: starting difficulty is 1 / 2^12 CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "clevelandcoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; int64 nMinimumInputValue = CENT / 100; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { if (nVersion > CTransaction::CURRENT_VERSION) return false; BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY); if (nFees < txMinFee) return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d, hash.ToString().c_str(), nFees, txMinFee); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n", hash.ToString().c_str(), mapTx.size()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = 50 * COIN; // Subsidy is cut in half every 840000 blocks, which will occur approximately every 4 years nSubsidy >>= (nHeight / 840000); // clevelandcoin: 840k blocks in ~4 years return nSubsidy + nFees; } static const int64 nTargetTimespan = 3.5 * 24 * 60 * 60; // clevelandcoin: 3.5 days static const int64 nTargetSpacing = 2.5 * 60; // clevelandcoin: 2.5 minutes static const int64 nInterval = nTargetTimespan / nTargetSpacing; // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special difficulty rule for testnet: if (fTestNet) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // clevelandcoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal clevelandcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC. int64 nBIP30SwitchTime = 1349049600; bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime); // BIP16 didn't become active until October 1 2012 int64 nBIP16SwitchTime = 1349049600; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); if (fEnforceBIP30) { CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); // if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: // strMiscWarning = _("Warning: this version is obsolete, upgrade required"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Special short-term limits to avoid 10,000 BDB lock limit: if (GetBlockTime() < 1376568000) // stop enforcing 15 August 2013 noon GMT { // Rule is: #unique txids referenced <= 4,500 // ... to prevent 10,000 BDB lock exhaustion on old clients set<uint256> setTxIn; for (size_t i = 0; i < vtx.size(); i++) { setTxIn.insert(vtx[i].GetHash()); if (i == 0) continue; // skip coinbase txin BOOST_FOREACH(const CTxIn& txin, vtx[i].vin) setTxIn.insert(txin.prevout.hash); } size_t nTxids = setTxIn.size(); if (nTxids > 4500) return error("CheckBlock() : 15 Aug maxlocks violation"); } // Check proof of work matches claimed amount if (!CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "clevelandcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; hashGenesisBlock = uint256("0xf5ae71e26c74beacc88382716aced69cddf3dffff24f384e1808905e0188f68f"); } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis Block: // CBlock(hash=12a765e31ffd4059bada, PoW=0000050c34a64b415b6b, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=97ddfbbae6, nTime=1317972665, nBits=1e0ffff0, nNonce=2084524493, vtx=1) // CTransaction(hash=97ddfbbae6, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536) // CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4) // vMerkleTree: 97ddfbbae6 // Genesis block const char* pszTimestamp = "Cleveland coin birth"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG; CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1389575440; block.nBits = 0x1e0ffff0; block.nNonce = 387689626; if (fTestNet) { block.nTime = 1317798646; block.nNonce = 385270584; } //// debug print printf("%s\n", block.GetHash().ToString().c_str()); printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0xa02bf4cab7b33fc23a2d4cf4dada496887bf903b3f65a9bc67f346bb5204d67f")); // If genesis block hash does not match, then generate new genesis hash. if (true && block.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) break; if ((block.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); printf("block.GetHash = %s\n", block.GetHash().ToString().c_str()); } block.print(); assert(block.GetHash() == hashGenesisBlock); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file\n", nLoaded); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI if it applies to me if(AppliesToMe()) uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xfb, 0xc0, 0xb6, 0xdb }; // clevelandcoin: increase each by adding 2 to bitcoin's value. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%d invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); // Truncate messages to the size of the tx in them unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); unsigned int oldSize = vMsg.size(); if (nSize < oldSize) { vMsg.resize(nSize); printf("truncating oversized TX %s (%u -> %u)\n", tx.GetHash().ToString().c_str(), oldSize, nSize); } bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Don't bother if send buffer is too full to respond anyway if (pfrom->vSend.size() >= SendBufferSize()) break; // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size // clevelandcoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes) bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetPoWHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); loop { unsigned int nHashesDone = 0; //unsigned int nNonceFound; uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (pblock->nNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
paul44011/ccoin
src/src/main.cpp
C++
mit
129,462
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Windows.Forms; using CM3D2.MaidFiddler.Hook; using CM3D2.MaidFiddler.Plugin.Gui; using CM3D2.MaidFiddler.Plugin.Utils; using ExIni; using UnityEngine; using UnityInjector; using UnityInjector.Attributes; using Application = System.Windows.Forms.Application; namespace CM3D2.MaidFiddler.Plugin { [PluginName("Maid Fiddler"), PluginVersion(VERSION)] public class MaidFiddler : PluginBase { public const string CONTRIBUTORS = "denikson"; public const string VERSION = "BETA 0.11.3"; public const string VERSION_TAG = "Beta-0.11.3"; public const string PROJECT_PAGE = "https://github.com/denikson/CM3D2.MaidFiddler"; public const string RESOURCE_URL = "https://raw.githubusercontent.com/denikson/CM3D2.MaidFiddler/master"; public const string RELEASES_LATEST_REQUEST_URL = "https://api.github.com/repos/denikson/CM3D2.MaidFiddler/releases/latest"; public const string RELEASES_URL = "https://www.github.com/denikson/CM3D2.MaidFiddler/releases"; public const int SUPPORTED_MIN_CM3D2_VERSION = 109; public const uint SUPPORTED_PATCH_MAX = 1310; public const uint SUPPORTED_PATCH_MIN = 1310; private const bool DEFAULT_USE_JAPANESE_NAME_STYLE = false; private const bool DEFAULT_OPEN_ON_STARTUP = false; private const bool DEFAULT_CHECK_FOR_UPDATES = true; private const MaidOrderDirection DEFAULT_ORDER_DIRECTION = Plugin.MaidOrderDirection.Ascending; private const string DEFAULT_LANGUAGE_FILE = "ENG"; private static readonly KeyCode[] DEFAULT_KEY_CODE = {KeyCode.A}; private readonly List<MaidOrderStyle> DEFAULT_ORDER_STYLES = new List<MaidOrderStyle> {MaidOrderStyle.GUID}; public MaidFiddlerGUI.MaidCompareMethod[] COMPARE_METHODS; private bool isUpdatePromptShowed; private KeyHelper keyCreateGUI; public bool CFGCheckForUpdates { get { IniKey value = Preferences["GUI"]["CheckForUpdates"]; bool checkForUpdates = DEFAULT_CHECK_FOR_UPDATES; if (!string.IsNullOrEmpty(value.Value) && bool.TryParse(value.Value, out checkForUpdates)) return checkForUpdates; Debugger.WriteLine(LogLevel.Warning, "Failed to get CheckForUpdates value. Setting to default..."); value.Value = DEFAULT_CHECK_FOR_UPDATES.ToString(); SaveConfig(); return checkForUpdates; } set { Preferences["GUI"]["CheckForUpdates"].Value = value.ToString(); SaveConfig(); } } public bool CFGOpenOnStartup { get { IniKey value = Preferences["GUI"]["OpenOnStartup"]; bool openOnStartup = DEFAULT_OPEN_ON_STARTUP; if (!string.IsNullOrEmpty(value.Value) && bool.TryParse(value.Value, out openOnStartup)) return openOnStartup; Debugger.WriteLine(LogLevel.Warning, "Failed to get OpenOnStartup value. Setting to default..."); value.Value = DEFAULT_OPEN_ON_STARTUP.ToString(); SaveConfig(); return openOnStartup; } set { Preferences["GUI"]["OpenOnStartup"].Value = value.ToString(); SaveConfig(); } } public MaidOrderDirection CFGOrderDirection { get { IniKey value = Preferences["GUI"]["OrderDirection"]; MaidOrderDirection orderDirection = DEFAULT_ORDER_DIRECTION; if (!string.IsNullOrEmpty(value.Value) && EnumHelper.TryParse(value.Value, out orderDirection, true)) return orderDirection; Debugger.WriteLine(LogLevel.Warning, "Failed to get order direction. Setting do default..."); value.Value = EnumHelper.GetName(DEFAULT_ORDER_DIRECTION); SaveConfig(); return orderDirection; } set { Preferences["GUI"]["OrderDirection"].Value = value.ToString(); SaveConfig(); MaidOrderDirection = (int) value; } } public List<MaidOrderStyle> CFGOrderStyle { get { IniKey value = Preferences["GUI"]["OrderStyle"]; List<MaidOrderStyle> orderStyles; if (string.IsNullOrEmpty(value.Value)) { Debugger.WriteLine(LogLevel.Warning, "Failed to get order style. Setting do default..."); value.Value = EnumHelper.EnumsToString(DEFAULT_ORDER_STYLES, '|'); orderStyles = DEFAULT_ORDER_STYLES; SaveConfig(); } else { orderStyles = EnumHelper.ParseEnums<MaidOrderStyle>(value.Value, '|'); if (orderStyles.Count != 0) return orderStyles; Debugger.WriteLine(LogLevel.Warning, "Failed to get order style. Setting do default..."); value.Value = EnumHelper.EnumsToString(DEFAULT_ORDER_STYLES, '|'); orderStyles = DEFAULT_ORDER_STYLES; SaveConfig(); } return orderStyles; } set { MaidCompareMethods = value.Select(o => COMPARE_METHODS[(int) o]).ToArray(); Preferences["GUI"]["OrderStyle"].Value = EnumHelper.EnumsToString(value, '|'); SaveConfig(); } } public string CFGSelectedDefaultLanguage { get { string result = Preferences["GUI"]["DefaultTranslation"].Value; if (!string.IsNullOrEmpty(result) && Translation.Exists(result)) return result; Preferences["GUI"]["DefaultTranslation"].Value = result = DEFAULT_LANGUAGE_FILE; SaveConfig(); return result; } set { if (value != null && (value = value.Trim()) != string.Empty && Translation.Exists(value)) Preferences["GUI"]["DefaultTranslation"].Value = value; else Preferences["GUI"]["DefaultTranslation"].Value = DEFAULT_LANGUAGE_FILE; SaveConfig(); } } public List<KeyCode> CFGStartGUIKey { get { List<KeyCode> keys = new List<KeyCode>(); IniKey value = Preferences["Keys"]["StartGUIKey"]; if (string.IsNullOrEmpty(value.Value)) { value.Value = EnumHelper.EnumsToString(DEFAULT_KEY_CODE, '+'); keys.AddRange(DEFAULT_KEY_CODE); SaveConfig(); } else { keys = EnumHelper.ParseEnums<KeyCode>(value.Value, '+'); if (keys.Count != 0) return keys; Debugger.WriteLine(LogLevel.Warning, "Failed to parse given key combo. Using default combination"); keys = DEFAULT_KEY_CODE.ToList(); value.Value = EnumHelper.EnumsToString(keys, '+'); SaveConfig(); } return keys; } set { Preferences["Keys"]["StartGUIKey"].Value = EnumHelper.EnumsToString(value, '+'); keyCreateGUI.Keys = value.ToArray(); SaveConfig(); } } public bool CFGUseJapaneseNameStyle { get { IniKey value = Preferences["GUI"]["UseJapaneseNameStyle"]; bool useJapNameStyle = DEFAULT_USE_JAPANESE_NAME_STYLE; if (!string.IsNullOrEmpty(value.Value) && bool.TryParse(value.Value, out useJapNameStyle)) return useJapNameStyle; Debugger.WriteLine(LogLevel.Warning, "Failed to get UseJapaneseNameStyle value. Setting to default..."); value.Value = DEFAULT_USE_JAPANESE_NAME_STYLE.ToString(); SaveConfig(); return useJapNameStyle; } set { UseJapaneseNameStyle = value; Preferences["GUI"]["UseJapaneseNameStyle"].Value = value.ToString(); SaveConfig(); } } public static string DATA_PATH { get; private set; } public MaidFiddlerGUI Gui { get; set; } public Thread GuiThread { get; set; } public MaidFiddlerGUI.MaidCompareMethod[] MaidCompareMethods { get; private set; } public int MaidOrderDirection { get; private set; } public static bool RunningOnSybaris { get { object[] attributes = typeof (Maid).GetCustomAttributes(typeof (MaidFiddlerPatcherAttribute), false); return attributes.Length == 1 && (PatcherType) ((MaidFiddlerPatcherAttribute) attributes[0]).PatcherType == PatcherType.Sybaris; } } public bool UseJapaneseNameStyle { get; private set; } public void Dispose() { Gui?.Dispose(); } public void Awake() { DontDestroyOnLoad(this); ServicePointManager.ServerCertificateValidationCallback += FiddlerUtils.RemoteCertificateValidationCallback; Debugger.ErrorOccured += (exception, message) => FiddlerUtils.ThrowErrorMessage(exception, message, this); COMPARE_METHODS = new MaidFiddlerGUI.MaidCompareMethod[] { MaidCompareID, MaidCompareCreateTime, MaidCompareFirstName, MaidCompareLastName, MaidCompareEmployedDay }; DATA_PATH = RunningOnSybaris ? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config") : DataPath; Debugger.WriteLine(LogLevel.Info, $"Data path: {DATA_PATH}"); LoadConfig(); if (!FiddlerUtils.CheckPatcherVersion()) { Destroy(this); return; } FiddlerHooks.SaveLoadedEvent += OnSaveLoaded; Debugger.WriteLine(LogLevel.Info, "Creating the GUI thread"); GuiThread = new Thread(LoadGUI); GuiThread.Start(); Debugger.WriteLine($"MaidFiddler {VERSION} loaded!"); if (CFGCheckForUpdates) { Thread updateCheckThread = new Thread(FiddlerUtils.RunUpdateChecker); updateCheckThread.Start(); } else { Debugger.WriteLine(LogLevel.Info, "Skipping update checking!"); } } public void LateUpdate() { Gui?.DoIfVisible(Gui.UpdateSelectedMaidValues); Gui?.DoIfVisible(Gui.UpdatePlayerValues); } private void LoadConfig() { Debugger.WriteLine(LogLevel.Info, "Loading launching key combination..."); keyCreateGUI = new KeyHelper(CFGStartGUIKey.ToArray()); Debugger.WriteLine( LogLevel.Info, $"Loaded {keyCreateGUI.Keys.Length} long key combo: {EnumHelper.EnumsToString(keyCreateGUI.Keys, '+')}"); Debugger.WriteLine(LogLevel.Info, "Loading name style info..."); UseJapaneseNameStyle = CFGUseJapaneseNameStyle; Debugger.WriteLine(LogLevel.Info, $"Using Japanese name style: {UseJapaneseNameStyle}"); Debugger.WriteLine(LogLevel.Info, "Loading order style info..."); List<MaidOrderStyle> orderStyles = CFGOrderStyle; MaidCompareMethods = orderStyles.Select(o => COMPARE_METHODS[(int) o]).ToArray(); Debugger.WriteLine( LogLevel.Info, $"Sorting maids by method order {EnumHelper.EnumsToString(orderStyles, '>')}"); Debugger.WriteLine(LogLevel.Info, "Loading order direction info..."); MaidOrderDirection = (int) CFGOrderDirection; Debugger.WriteLine( LogLevel.Info, $"Sorting maids in {EnumHelper.GetName((MaidOrderDirection) MaidOrderDirection)} direction"); Translation.LoadTranslation(CFGSelectedDefaultLanguage); } public void LoadGUI() { try { Application.SetCompatibleTextRenderingDefault(false); if (Gui == null) Gui = new MaidFiddlerGUI(this); Application.Run(Gui); } catch (Exception e) { FiddlerUtils.ThrowErrorMessage(e, "Generic error", this); } } public void OnDestroy() { if (Gui == null) return; Debugger.WriteLine("Closing GUI..."); Gui.Close(true); Gui = null; Debugger.WriteLine("GUI closed. Suspending the thread..."); GuiThread.Abort(); Debugger.WriteLine("Thread suspended"); } public void OnSaveLoaded(int saveNo) { Debugger.WriteLine(LogLevel.Info, $"Level loading! Save no. {saveNo}"); if (!(Gui?.Visible).GetValueOrDefault(true)) Gui?.UnloadMaids(); Gui?.DoIfVisible(Gui.ReloadMaids); Gui?.DoIfVisible(Gui.ReloadPlayer); } public void OpenGUI() { Gui?.Show(); } public void Update() { if (!isUpdatePromptShowed && FiddlerUtils.UpdatesChecked) { isUpdatePromptShowed = true; if (FiddlerUtils.UpdateInfo.IsAvailable) ShowUpdatePrompt(); } keyCreateGUI.Update(); if (keyCreateGUI.HasBeenPressed()) OpenGUI(); Gui?.DoIfVisible(Gui.UpdateMaids); } private void ShowUpdatePrompt() { Debugger.WriteLine(LogLevel.Info, "Latest version is newer than the current one! Showing update prompt!"); ManualResetEvent mre = new ManualResetEvent(false); // ReSharper disable once UseObjectOrCollectionInitializer NotifyIcon notification = new NotifyIcon { Icon = SystemIcons.Application, BalloonTipIcon = ToolTipIcon.Info, BalloonTipTitle = Translation.IsTranslated("INFO_UPDATE_AVAILABLE_BUBBLE_TITLE") ? string.Format( Translation.GetTranslation("INFO_UPDATE_AVAILABLE_BUBBLE_TITLE"), FiddlerUtils.UpdateInfo.Version) : $"Maid Fiddler version {FiddlerUtils.UpdateInfo.Version} is available!", BalloonTipText = Translation.IsTranslated("INFO_UPDATE_AVAILABLE_BUBBLE") ? Translation.GetTranslation("INFO_UPDATE_AVAILABLE_BUBBLE") : "Download the new version from Maid Fiddler GitHub page!" }; notification.BalloonTipClosed += (sender, args) => { Debugger.WriteLine(LogLevel.Info, "Closing the notification!"); mre.Set(); }; notification.BalloonTipClicked += (sender, args) => { Debugger.WriteLine(LogLevel.Info, "Showing update information!"); mre.Set(); string title = Translation.IsTranslated("INFO_UPDATE_AVAILABLE_TITLE") ? string.Format( Translation.GetTranslation("INFO_UPDATE_AVAILABLE_TITLE"), FiddlerUtils.UpdateInfo.Version) : $"Version {FiddlerUtils.UpdateInfo.Version} is available!"; string text = Translation.IsTranslated("INFO_UPDATE_AVAILABLE") ? string.Format( Translation.GetTranslation("INFO_UPDATE_AVAILABLE"), FiddlerUtils.UpdateInfo.Version, FiddlerUtils.UpdateInfo.Changelog, RELEASES_URL) : $"Maid Fiddler version {FiddlerUtils.UpdateInfo.Version} is available to download!\nUpdate log:\n{FiddlerUtils.UpdateInfo.Changelog}\n\nHead to {RELEASES_URL} to download the latest version."; MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Information); }; notification.Visible = true; notification.ShowBalloonTip(5000); Thread showThread = new Thread( () => { mre.WaitOne(6000); Debugger.WriteLine(LogLevel.Info, "Closing notification icon..."); notification.Visible = false; notification.Dispose(); }); showThread.Start(); } public int MaidCompareEmployedDay(Maid x, Maid y) { return ComputeOrder(x.Param.status.employment_day, y.Param.status.employment_day); } public int MaidCompareCreateTime(Maid x, Maid y) { return ComputeOrder(x.Param.status.create_time_num, y.Param.status.create_time_num); } private int ComputeOrder<T>(T x, T y) where T : IComparable<T> { return MaidOrderDirection * x.CompareTo(y); } public int MaidCompareFirstName(Maid x, Maid y) { return MaidOrderDirection * string.CompareOrdinal( x.Param.status.first_name.ToUpperInvariant(), y.Param.status.first_name.ToUpperInvariant()); } public int MaidCompareID(Maid x, Maid y) { return MaidOrderDirection * string.CompareOrdinal(x.Param.status.guid, y.Param.status.guid); } public int MaidCompareLastName(Maid x, Maid y) { return MaidOrderDirection * string.CompareOrdinal( x.Param.status.last_name.ToUpperInvariant(), y.Param.status.last_name.ToUpperInvariant()); } } public enum MaidOrderStyle { GUID = 0, CreationTime = 1, FirstName = 2, LastName = 3, EmployedDay = 4 } public enum MaidOrderDirection { Descending = -1, Ascending = 1 } }
denikson/CM3D2.MaidFiddler
CM3D2.MaidFiddler.Plugin/MaidFiddler.cs
C#
mit
19,159
import _ from 'lodash' // eslint-disable-line export default function loadInitialState(req) { const user = req.user const state = { auth: {}, } if (user) { state.auth = { user: {id: user.id}, } if (req.session.accessToken) { state.auth.accessToken = req.session.accessToken.token } } if (req.csrfToken) { state.auth.csrf = req.csrfToken() } // Immutable.fromJS has a bug with objects flagged as anonymous in node 6 // https://github.com/facebook/immutable-js/issues/1001 return JSON.parse(JSON.stringify(state)) // callback(null, state) }
founderlab/fl-base-webapp
server/clientApps/loadInitialState.js
JavaScript
mit
602
import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import pluralize from 'common/utils/pluralize'; import search from './actions'; import { selectSearchResultIds, selectIsSearching, selectIsSearchComplete } from './selectors'; import Element from 'common/components/Element'; import H3 from 'common/components/H3'; import Button from 'common/components/Button'; import VocabList from 'common/components/VocabList'; import { blue, orange } from 'common/styles/colors'; SearchResults.propTypes = { ids: PropTypes.arrayOf(PropTypes.number), isSearching: PropTypes.bool, isSearchComplete: PropTypes.bool, onReset: PropTypes.func.isRequired, }; SearchResults.defaultProps = { ids: [], isSearching: false, isSearchComplete: false, }; export function SearchResults({ ids, isSearching, isSearchComplete, onReset }) { const tooBroad = ids.length >= 50; const amount = `${ids.length}${tooBroad ? '+' : ''}`; const wordsFoundText = `${amount} ${pluralize('word', ids.length)} found${ tooBroad ? '. Try refining your search keywords.' : '' }`; return ( (isSearching || isSearchComplete) && ( <Fragment> <Element flexRow flexCenter> <H3>{(isSearching && 'Searching...') || wordsFoundText}</H3> {isSearchComplete && ( <Button bgColor={orange[5]} colorHover={orange[5]} onClick={onReset}> Clear Results </Button> )} </Element> <VocabList ids={ids} bgColor={blue[5]} showSecondary showFuri /> </Fragment> ) ); } const mapStateToProps = (state, props) => ({ ids: selectSearchResultIds(state, props), isSearching: selectIsSearching(state, props), isSearchComplete: selectIsSearchComplete(state, props), }); const mapDispatchToProps = { onReset: search.clear, }; export default connect(mapStateToProps, mapDispatchToProps)(SearchResults);
Kaniwani/KW-Frontend
app/features/search/SearchResults.js
JavaScript
mit
1,946
import { toTitleCase } from 'utils'; export default values => { let newValues = { ...values }; // Add a sourceType if no source (i.e. not scraped) and no sourceType if (!newValues['source'] && !newValues['sourceType']) { newValues['sourceType'] = 'user'; } switch (newValues['sourceType']) { case 'user': newValues = { ...newValues, url: undefined, page: undefined, book: undefined, }; break; case 'website': newValues = { ...newValues, page: undefined, book: undefined }; break; case 'book': newValues = { ...newValues, url: undefined }; break; default: break; } if (Array.isArray(values['ingredients'])) { newValues = { ...newValues, ingredients: values['ingredients'].map(ingredient => ({ ...ingredient, text: ingredient.text.trim(), })), }; } return { public: true, ...newValues, title: toTitleCase(values['title']), }; };
jf248/scrape-the-plate
frontend/src/components/recipes/edit/components/Step2/normalize.js
JavaScript
mit
1,006