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
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v20.2.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var logger_1 = require("../logger"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnApi_1 = require("../columnController/columnApi"); var gridApi_1 = require("../gridApi"); var utils_1 = require("../utils"); /** Adds drag listening onto an element. In ag-Grid this is used twice, first is resizing columns, * second is moving the columns and column groups around (ie the 'drag' part of Drag and Drop. */ var DragService = /** @class */ (function () { function DragService() { this.onMouseUpListener = this.onMouseUp.bind(this); this.onMouseMoveListener = this.onMouseMove.bind(this); this.onTouchEndListener = this.onTouchUp.bind(this); this.onTouchMoveListener = this.onTouchMove.bind(this); this.dragEndFunctions = []; this.dragSources = []; } DragService.prototype.init = function () { this.logger = this.loggerFactory.create('DragService'); }; DragService.prototype.destroy = function () { this.dragSources.forEach(this.removeListener.bind(this)); this.dragSources.length = 0; }; DragService.prototype.removeListener = function (dragSourceAndListener) { var element = dragSourceAndListener.dragSource.eElement; var mouseDownListener = dragSourceAndListener.mouseDownListener; element.removeEventListener('mousedown', mouseDownListener); // remove touch listener only if it exists if (dragSourceAndListener.touchEnabled) { var touchStartListener = dragSourceAndListener.touchStartListener; element.removeEventListener('touchstart', touchStartListener, { passive: true }); } }; DragService.prototype.removeDragSource = function (params) { var dragSourceAndListener = utils_1._.find(this.dragSources, function (item) { return item.dragSource === params; }); if (!dragSourceAndListener) { return; } this.removeListener(dragSourceAndListener); utils_1._.removeFromArray(this.dragSources, dragSourceAndListener); }; DragService.prototype.setNoSelectToBody = function (noSelect) { var eDocument = this.gridOptionsWrapper.getDocument(); var eBody = eDocument.querySelector('body'); if (utils_1._.exists(eBody)) { // when we drag the mouse in ag-Grid, this class gets added / removed from the body, so that // the mouse isn't selecting text when dragging. utils_1._.addOrRemoveCssClass(eBody, 'ag-unselectable', noSelect); } }; DragService.prototype.addDragSource = function (params, includeTouch) { if (includeTouch === void 0) { includeTouch = false; } var mouseListener = this.onMouseDown.bind(this, params); params.eElement.addEventListener('mousedown', mouseListener); var touchListener = null; var suppressTouch = this.gridOptionsWrapper.isSuppressTouch(); if (includeTouch && !suppressTouch) { touchListener = this.onTouchStart.bind(this, params); params.eElement.addEventListener('touchstart', touchListener, { passive: false }); } this.dragSources.push({ dragSource: params, mouseDownListener: mouseListener, touchStartListener: touchListener, touchEnabled: includeTouch }); }; // gets called whenever mouse down on any drag source DragService.prototype.onTouchStart = function (params, touchEvent) { var _this = this; this.currentDragParams = params; this.dragging = false; var touch = touchEvent.touches[0]; this.touchLastTime = touch; this.touchStart = touch; touchEvent.preventDefault(); // we temporally add these listeners, for the duration of the drag, they // are removed in touch end handling. params.eElement.addEventListener('touchmove', this.onTouchMoveListener, { passive: true }); params.eElement.addEventListener('touchend', this.onTouchEndListener, { passive: true }); params.eElement.addEventListener('touchcancel', this.onTouchEndListener, { passive: true }); this.dragEndFunctions.push(function () { params.eElement.removeEventListener('touchmove', _this.onTouchMoveListener, { passive: true }); params.eElement.removeEventListener('touchend', _this.onTouchEndListener, { passive: true }); params.eElement.removeEventListener('touchcancel', _this.onTouchEndListener, { passive: true }); }); // see if we want to start dragging straight away if (params.dragStartPixels === 0) { this.onCommonMove(touch, this.touchStart); } }; // gets called whenever mouse down on any drag source DragService.prototype.onMouseDown = function (params, mouseEvent) { var _this = this; // we ignore when shift key is pressed. this is for the range selection, as when // user shift-clicks a cell, this should not be interpreted as the start of a drag. // if (mouseEvent.shiftKey) { return; } if (params.skipMouseEvent) { if (params.skipMouseEvent(mouseEvent)) { return; } } // if there are two elements with parent / child relationship, and both are draggable, // when we drag the child, we should NOT drag the parent. an example of this is row moving // and range selection - row moving should get preference when use drags the rowDrag component. if (mouseEvent._alreadyProcessedByDragService) { return; } mouseEvent._alreadyProcessedByDragService = true; // only interested in left button clicks if (mouseEvent.button !== 0) { return; } this.currentDragParams = params; this.dragging = false; this.mouseEventLastTime = mouseEvent; this.mouseStartEvent = mouseEvent; var eDocument = this.gridOptionsWrapper.getDocument(); // we temporally add these listeners, for the duration of the drag, they // are removed in mouseup handling. eDocument.addEventListener('mousemove', this.onMouseMoveListener); eDocument.addEventListener('mouseup', this.onMouseUpListener); this.dragEndFunctions.push(function () { eDocument.removeEventListener('mousemove', _this.onMouseMoveListener); eDocument.removeEventListener('mouseup', _this.onMouseUpListener); }); //see if we want to start dragging straight away if (params.dragStartPixels === 0) { this.onMouseMove(mouseEvent); } }; // returns true if the event is close to the original event by X pixels either vertically or horizontally. // we only start dragging after X pixels so this allows us to know if we should start dragging yet. DragService.prototype.isEventNearStartEvent = function (currentEvent, startEvent) { // by default, we wait 4 pixels before starting the drag var dragStartPixels = this.currentDragParams.dragStartPixels; var requiredPixelDiff = utils_1._.exists(dragStartPixels) ? dragStartPixels : 4; return utils_1._.areEventsNear(currentEvent, startEvent, requiredPixelDiff); }; DragService.prototype.getFirstActiveTouch = function (touchList) { for (var i = 0; i < touchList.length; i++) { if (touchList[i].identifier === this.touchStart.identifier) { return touchList[i]; } } return null; }; DragService.prototype.onCommonMove = function (currentEvent, startEvent) { if (!this.dragging) { // if mouse hasn't travelled from the start position enough, do nothing if (!this.dragging && this.isEventNearStartEvent(currentEvent, startEvent)) { return; } this.dragging = true; var event_1 = { type: events_1.Events.EVENT_DRAG_STARTED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_1); this.currentDragParams.onDragStart(startEvent); this.setNoSelectToBody(true); } this.currentDragParams.onDragging(currentEvent); }; DragService.prototype.onTouchMove = function (touchEvent) { var touch = this.getFirstActiveTouch(touchEvent.touches); if (!touch) { return; } // this.___statusPanel.setInfoText(Math.random() + ' onTouchMove preventDefault stopPropagation'); // if we don't preview default, then the browser will try and do it's own touch stuff, // like do 'back button' (chrome does this) or scroll the page (eg drag column could be confused // with scroll page in the app) // touchEvent.preventDefault(); this.onCommonMove(touch, this.touchStart); }; // only gets called after a mouse down - as this is only added after mouseDown // and is removed when mouseUp happens DragService.prototype.onMouseMove = function (mouseEvent) { this.onCommonMove(mouseEvent, this.mouseStartEvent); }; DragService.prototype.onTouchUp = function (touchEvent) { var touch = this.getFirstActiveTouch(touchEvent.changedTouches); // i haven't worked this out yet, but there is no matching touch // when we get the touch up event. to get around this, we swap in // the last touch. this is a hack to 'get it working' while we // figure out what's going on, why we are not getting a touch in // current event. if (!touch) { touch = this.touchLastTime; } // if mouse was left up before we started to move, then this is a tap. // we check this before onUpCommon as onUpCommon resets the dragging // let tap = !this.dragging; // let tapTarget = this.currentDragParams.eElement; this.onUpCommon(touch); // if tap, tell user // console.log(`${Math.random()} tap = ${tap}`); // if (tap) { // tapTarget.click(); // } }; DragService.prototype.onMouseUp = function (mouseEvent) { this.onUpCommon(mouseEvent); }; DragService.prototype.onUpCommon = function (eventOrTouch) { if (this.dragging) { this.dragging = false; this.currentDragParams.onDragStop(eventOrTouch); var event_2 = { type: events_1.Events.EVENT_DRAG_STOPPED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_2); } this.setNoSelectToBody(false); this.mouseStartEvent = null; this.mouseEventLastTime = null; this.touchStart = null; this.touchLastTime = null; this.currentDragParams = null; this.dragEndFunctions.forEach(function (func) { return func(); }); this.dragEndFunctions.length = 0; }; __decorate([ context_1.Autowired('loggerFactory'), __metadata("design:type", logger_1.LoggerFactory) ], DragService.prototype, "loggerFactory", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], DragService.prototype, "eventService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], DragService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnApi'), __metadata("design:type", columnApi_1.ColumnApi) ], DragService.prototype, "columnApi", void 0); __decorate([ context_1.Autowired('gridApi'), __metadata("design:type", gridApi_1.GridApi) ], DragService.prototype, "gridApi", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], DragService.prototype, "init", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], DragService.prototype, "destroy", null); DragService = __decorate([ context_1.Bean('dragService') ], DragService); return DragService; }()); exports.DragService = DragService;
sufuf3/cdnjs
ajax/libs/ag-grid/21.0.0/lib/dragAndDrop/dragService.js
JavaScript
mit
13,765
<?php namespace Kunstmaan\AdminBundle\Helper\Menu; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; /** * SettingsMenuAdaptor to add the Settings MenuItem to the top menu and build the Settings tree */ class SettingsMenuAdaptor implements MenuAdaptorInterface { /** @var AuthorizationCheckerInterface */ private $authorizationChecker; /** @var bool */ private $isEnabledVersionChecker; /** @var bool */ private $exceptionLoggingEnabled; /** * @param bool $isEnabledVersionChecker */ public function __construct(AuthorizationCheckerInterface $authorizationChecker, $isEnabledVersionChecker, bool $exceptionLoggingEnabled = true) { $this->authorizationChecker = $authorizationChecker; $this->isEnabledVersionChecker = (bool) $isEnabledVersionChecker; $this->exceptionLoggingEnabled = $exceptionLoggingEnabled; } public function adaptChildren(MenuBuilder $menu, array &$children, MenuItem $parent = null, Request $request = null) { if (\is_null($parent)) { $menuItem = new TopMenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings') ->setLabel('settings.title') ->setUniqueId('settings') ->setParent($parent) ->setRole('settings'); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if (!\is_null($parent) && 'KunstmaanAdminBundle_settings' == $parent->getRoute()) { if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN') && $this->isEnabledVersionChecker) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings_bundle_version') ->setLabel('settings.version.bundle') ->setUniqueId('bundle_versions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if ($this->exceptionLoggingEnabled) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('kunstmaanadminbundle_admin_exception') ->setLabel('settings.exceptions.title') ->setUniqueId('exceptions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); $parent->setActive(true); } $children[] = $menuItem; } } } }
Kunstmaan/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Helper/Menu/SettingsMenuAdaptor.php
PHP
mit
2,981
/* http://keith-wood.name/calculator.html Catalan initialisation for the jQuery calculator extension Written by Esteve Camps (ecamps at google dot com) June 2010. */ (function($) { // hide the namespace $.calculator.regionalOptions['ca'] = { decimalChar: ',', buttonText: '...', buttonStatus: 'Obrir la calculadora', closeText: 'Tancar', closeStatus: 'Tancar la calculadora', useText: 'Usar', useStatus: 'Usar el valor actual', eraseText: 'Esborrar', eraseStatus: 'Esborrar el valor actual', backspaceText: 'BS', backspaceStatus: 'Esborrar el darrer dígit', clearErrorText: 'CE', clearErrorStatus: 'Esborrar el darrer número', clearText: 'CA', clearStatus: 'Reiniciar el càlcul', memClearText: 'MC', memClearStatus: 'Esborrar la memòria', memRecallText: 'MR', memRecallStatus: 'Recuperar el valor de la memòria', memStoreText: 'MS', memStoreStatus: 'Guardar el valor a la memòria', memAddText: 'M+', memAddStatus: 'Afegir a la memòria', memSubtractText: 'M-', memSubtractStatus: 'Treure de la memòria', base2Text: 'Bin', base2Status: 'Canviar al mode Binari', base8Text: 'Oct', base8Status: 'Canviar al mode Octal', base10Text: 'Dec', base10Status: 'Canviar al mode Decimal', base16Text: 'Hex', base16Status: 'Canviar al mode Hexadecimal', degreesText: 'Deg', degreesStatus: 'Canviar al mode Graus', radiansText: 'Rad', radiansStatus: 'Canviar al mode Radians', isRTL: false}; $.calculator.setDefaults($.calculator.regionalOptions['ca']); })(jQuery);
rsantellan/ventanas-html-proyecto
ventanas/src/AppBundle/Resources/public/admin/vendor/calculator/jquery.calculator-ca.js
JavaScript
mit
1,535
/** * EditorCommands.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class enables you to add custom editor commands and it contains * overrides for native browser commands to address various bugs and issues. * * @class tinymce.EditorCommands */ define("tinymce/EditorCommands", [ "tinymce/html/Serializer", "tinymce/Env", "tinymce/util/Tools", "tinymce/dom/ElementUtils", "tinymce/dom/RangeUtils", "tinymce/dom/TreeWalker" ], function(Serializer, Env, Tools, ElementUtils, RangeUtils, TreeWalker) { // Added for compression purposes var each = Tools.each, extend = Tools.extend; var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; var isIE = Env.ie, isOldIE = Env.ie && Env.ie < 11; var TRUE = true, FALSE = false; return function(editor) { var dom, selection, formatter, commands = {state: {}, exec: {}, value: {}}, settings = editor.settings, bookmark; editor.on('PreInit', function() { dom = editor.dom; selection = editor.selection; settings = editor.settings; formatter = editor.formatter; }); /** * Executes the specified command. * * @method execCommand * @param {String} command Command to execute. * @param {Boolean} ui Optional user interface state. * @param {Object} value Optional value for command. * @param {Object} args Optional extra arguments to the execCommand. * @return {Boolean} true/false if the command was found or not. */ function execCommand(command, ui, value, args) { var func, customCommand, state = 0; if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) { editor.focus(); } args = editor.fire('BeforeExecCommand', {command: command, ui: ui, value: value}); if (args.isDefaultPrevented()) { return false; } customCommand = command.toLowerCase(); if ((func = commands.exec[customCommand])) { func(customCommand, ui, value); editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } // Plugin commands each(editor.plugins, function(p) { if (p.execCommand && p.execCommand(command, ui, value)) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); state = true; return false; } }); if (state) { return state; } // Theme commands if (editor.theme && editor.theme.execCommand && editor.theme.execCommand(command, ui, value)) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } // Browser commands try { state = editor.getDoc().execCommand(command, ui, value); } catch (ex) { // Ignore old IE errors } if (state) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } return false; } /** * Queries the current state for a command for example if the current selection is "bold". * * @method queryCommandState * @param {String} command Command to check the state of. * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. */ function queryCommandState(command) { var func; // Is hidden then return undefined if (editor._isHidden()) { return; } command = command.toLowerCase(); if ((func = commands.state[command])) { return func(command); } // Browser commands try { return editor.getDoc().queryCommandState(command); } catch (ex) { // Fails sometimes see bug: 1896577 } return false; } /** * Queries the command value for example the current fontsize. * * @method queryCommandValue * @param {String} command Command to check the value of. * @return {Object} Command value of false if it's not found. */ function queryCommandValue(command) { var func; // Is hidden then return undefined if (editor._isHidden()) { return; } command = command.toLowerCase(); if ((func = commands.value[command])) { return func(command); } // Browser commands try { return editor.getDoc().queryCommandValue(command); } catch (ex) { // Fails sometimes see bug: 1896577 } } /** * Adds commands to the command collection. * * @method addCommands * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. */ function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); } function addCommand(command, callback, scope) { command = command.toLowerCase(); commands.exec[command] = function(command, ui, value, args) { return callback.call(scope || editor, ui, value, args); }; } /** * Returns true/false if the command is supported or not. * * @method queryCommandSupported * @param {String} command Command that we check support for. * @return {Boolean} true/false if the command is supported or not. */ function queryCommandSupported(command) { command = command.toLowerCase(); if (commands.exec[command]) { return true; } // Browser commands try { return editor.getDoc().queryCommandSupported(command); } catch (ex) { // Fails sometimes see bug: 1896577 } return false; } function addQueryStateHandler(command, callback, scope) { command = command.toLowerCase(); commands.state[command] = function() { return callback.call(scope || editor); }; } function addQueryValueHandler(command, callback, scope) { command = command.toLowerCase(); commands.value[command] = function() { return callback.call(scope || editor); }; } function hasCustomCommand(command) { command = command.toLowerCase(); return !!commands.exec[command]; } // Expose public methods extend(this, { execCommand: execCommand, queryCommandState: queryCommandState, queryCommandValue: queryCommandValue, queryCommandSupported: queryCommandSupported, addCommands: addCommands, addCommand: addCommand, addQueryStateHandler: addQueryStateHandler, addQueryValueHandler: addQueryValueHandler, hasCustomCommand: hasCustomCommand }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undefined) { ui = FALSE; } if (value === undefined) { value = null; } return editor.getDoc().execCommand(command, ui, value); } function isFormatMatch(name) { return formatter.match(name); } function toggleFormat(name, value) { formatter.toggle(name, value ? {value: value} : undefined); editor.nodeChanged(); } function storeSelection(type) { bookmark = selection.getBookmark(type); } function restoreSelection() { selection.moveToBookmark(bookmark); } // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel': function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel': function() { editor.undoManager.add(); }, 'Cut,Copy,Paste': function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { var msg = editor.translate( "Your browser doesn't support direct access to the clipboard. " + "Please use the Ctrl+X/C/V keyboard shortcuts instead." ); if (Env.mac) { msg = msg.replace(/Ctrl\+/g, '\u2318+'); } editor.notificationManager.open({text: msg, type: 'error'}); } }, // Override unlink command unlink: function() { if (selection.isCollapsed()) { var elm = selection.getNode(); if (elm.tagName == 'A') { editor.dom.remove(elm, true); } return; } formatter.remove("link"); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function(command) { var align = command.substring(7); if (align == 'full') { align = 'justify'; } // Remove all other alignments first each('left,center,right,justify'.split(','), function(name) { if (align != name) { formatter.remove('align' + name); } }); if (align != 'none') { toggleFormat('align' + align); } }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList': function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName': function(command, ui, value) { toggleFormat(command, value); }, FontSize: function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = explode(settings.font_size_style_values); fontClasses = explode(settings.font_size_classes); if (fontClasses) { value = fontClasses[value - 1] || value; } else { value = fontSizes[value - 1] || value; } } toggleFormat(command, value); }, RemoveFormat: function(command) { formatter.remove(command); }, mceBlockQuote: function() { toggleFormat('blockquote'); }, FormatBlock: function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup: function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode: function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth: function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode: function(command, ui, value) { selection.select(value); }, mceInsertContent: function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args; var marker, rng, node, node2, bookmarkHtml, merge, data; var textInlineElements = editor.schema.getTextInlineElements(); function trimOrPaddLeftRight(html) { var rng, container, offset; rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; function hasSiblingText(siblingName) { return container[siblingName] && container[siblingName].nodeType == 3; } if (container.nodeType == 3) { if (offset > 0) { html = html.replace(/^&nbsp;/, ' '); } else if (!hasSiblingText('previousSibling')) { html = html.replace(/^ /, '&nbsp;'); } if (offset < container.length) { html = html.replace(/&nbsp;(<br>|)$/, ' '); } else if (!hasSiblingText('nextSibling')) { html = html.replace(/(&nbsp;| )(<br>|)$/, '&nbsp;'); } } return html; } // Removes &nbsp; from a [b] c -> a &nbsp;c -> a c function trimNbspAfterDeleteAndPaddValue() { var rng, container, offset; rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; if (container.nodeType == 3 && rng.collapsed) { if (container.data[offset] === '\u00a0') { container.deleteData(offset, 1); if (!/[\u00a0| ]$/.test(value)) { value += ' '; } } else if (container.data[offset - 1] === '\u00a0') { container.deleteData(offset - 1, 1); if (!/[\u00a0| ]$/.test(value)) { value = ' ' + value; } } } } function markInlineFormatElements(fragment) { if (merge) { for (node = fragment.firstChild; node; node = node.walk(true)) { if (textInlineElements[node.name]) { node.attr('data-mce-new', "true"); } } } } function reduceInlineTextElements() { if (merge) { var root = editor.getBody(), elementUtils = new ElementUtils(dom); each(dom.select('*[data-mce-new]'), function(node) { node.removeAttribute('data-mce-new'); for (var testNode = node.parentNode; testNode && testNode != root; testNode = testNode.parentNode) { if (elementUtils.compare(testNode, node)) { dom.remove(node, true); } } }); } } function moveSelectionToMarker(marker) { var parentEditableFalseElm; function getContentEditableFalseParent(node) { var root = editor.getBody(); for (; node && node !== root; node = node.parentNode) { if (editor.dom.getContentEditable(node) === 'false') { return node; } } return null; } if (!marker) { return; } selection.scrollIntoView(marker); // If marker is in cE=false then move selection to that element instead parentEditableFalseElm = getContentEditableFalseParent(marker); if (parentEditableFalseElm) { dom.remove(marker); selection.select(parentEditableFalseElm); return; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); // TODO: Why can't we normalize on IE if (!isIE) { node2 = marker.nextSibling; if (node2 && node2.nodeType == 3) { node.appendData(node2.data); node2.parentNode.removeChild(node2); } } } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); } if (typeof value != 'string') { merge = value.merge; data = value.data; value = value.content; } // Check for whitespace before/after value if (/^ | $/.test(value)) { value = trimOrPaddLeftRight(value); } // Setup parser and serializer parser = editor.parser; serializer = new Serializer({ validate: settings.validate }, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;&#x200B;</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html', selection: true}; editor.fire('BeforeSetContent', args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) { value += '{$caret}'; } // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // If selection is at <body>|<p></p> then move it into <body><p>|</p> rng = selection.getRng(); var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); var body = editor.getBody(); if (caretElement === body && selection.isCollapsed()) { if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { rng = dom.createRng(); rng.setStart(body.firstChild, 0); rng.setEnd(body.firstChild, 0); selection.setRng(rng); } } // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) { editor.getDoc().execCommand('Delete', false, null); trimNbspAfterDeleteAndPaddValue(); } parentNode = selection.getNode(); // Parse the fragment within the context of the parent node var parserArgs = {context: parentNode.nodeName.toLowerCase(), data: data}; fragment = parser.parse(value, parserArgs); markInlineFormatElements(fragment); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { if (editor.schema.isValidChild(node.parent.name, 'span')) { node.parent.insert(marker, node, node.name === 'br'); } break; } } } editor._selectionOverrides.showBlockCaretContainer(parentNode); // If parser says valid we can insert the contents into that parent if (!parserArgs.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) { dom.setHTML(parentNode, value); } else { selection.setContent(value); } } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) { parentNode = node = rootNode; } else { node = parentNode; } // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) { dom.setHTML(rootNode, value); } else { dom.setOuterHTML(parentNode, value); } } reduceInlineTextElements(); moveSelectionToMarker(dom.get('mce_marker')); editor.fire('SetContent', args); editor.addVisual(); }, mceInsertRawHTML: function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent( editor.getContent().replace(/tiny_mce_marker/g, function() { return value; }) ); }, mceToggleFormat: function(command, ui, value) { toggleFormat(value); }, mceSetContent: function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent': function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue, 10); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { if (dom.getContentEditable(element) === "false") { return; } if (element.nodeName != "LI") { var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; if (command == 'outdent') { value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); } else { value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; dom.setStyle(element, indentStyleName, value); } } }); } else { execNativeCommand(command); } }, mceRepaint: function() { }, InsertHorizontalRule: function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid: function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent: function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'}))); }, mceInsertLink: function(command, ui, value) { var anchor; if (typeof value == 'string') { value = {href: value}; } anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll: function() { var root = dom.getRoot(), rng; if (selection.getRng().setStart) { rng = dom.createRng(); rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); selection.setRng(rng); } else { // IE will render it's own root level block elements and sometimes // even put font elements in them when the user starts typing. So we need to // move the selection to a more suitable element from this: // <body>|<p></p></body> to this: <body><p>|</p></body> rng = selection.getRng(); if (!rng.item) { rng.moveToElementText(root); rng.select(); } } }, "delete": function() { execNativeCommand("Delete"); // Check if body is empty after the delete call if so then set the contents // to an empty string and move the caret to any block produced by that operation // this fixes the issue with root blocks not being properly produced after a delete call on IE var body = editor.getBody(); if (dom.isEmpty(body)) { editor.setContent(''); if (body.firstChild && dom.isBlock(body.firstChild)) { editor.selection.setCursorLocation(body.firstChild, 0); } else { editor.selection.setCursorLocation(body, 0); } } }, mceNewDocument: function() { editor.setContent(''); }, InsertLineBreak: function(command, ui, value) { // We load the current event in from EnterKey.js when appropriate to heed // certain event-specific variations such as ctrl-enter in a list var evt = value; var brElm, extraBr, marker; var rng = selection.getRng(true); new RangeUtils(dom).normalize(rng); var offset = rng.startOffset; var container = rng.startContainer; // Resolve node index if (container.nodeType == 1 && container.hasChildNodes()) { var isAfterLastNodeInContainer = offset > container.childNodes.length - 1; container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; if (isAfterLastNodeInContainer && container.nodeType == 3) { offset = container.nodeValue.length; } else { offset = 0; } } var parentBlock = dom.getParent(container, dom.isBlock); var parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null; var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 // Enter inside block contained within a LI then split or insert before/after LI var isControlKey = evt && evt.ctrlKey; if (containerBlockName == 'LI' && !isControlKey) { parentBlock = containerBlock; parentBlockName = containerBlockName; } // Walks the parent block to the right and look for BR elements function hasRightSideContent() { var walker = new TreeWalker(container, parentBlock), node; var nonEmptyElementsMap = editor.schema.getNonEmptyElements(); while ((node = walker.next())) { if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) { return true; } } } if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { // Insert extra BR element at the end block elements if (!isOldIE && !hasRightSideContent()) { brElm = dom.create('br'); rng.insertNode(brElm); rng.setStartAfter(brElm); rng.setEndAfter(brElm); extraBr = true; } } brElm = dom.create('br'); rng.insertNode(brElm); // Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it var documentMode = dom.doc.documentMode; if (isOldIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); } // Insert temp marker and scroll to that marker = dom.create('span', {}, '&nbsp;'); brElm.parentNode.insertBefore(marker, brElm); selection.scrollIntoView(marker); dom.remove(marker); if (!extraBr) { rng.setStartAfter(brElm); rng.setEndAfter(brElm); } else { rng.setStartBefore(brElm); rng.setEndBefore(brElm); } selection.setRng(rng); editor.undoManager.add(); return TRUE; } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { var name = 'align' + command.substring(7); var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); var matches = map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { return isFormatMatch(command); }, mceBlockQuote: function() { return isFormatMatch('blockquote'); }, Outdent: function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } } return ( queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) ); }, 'InsertUnorderedList,InsertOrderedList': function(command) { var list = dom.getParent(selection.getNode(), 'ul,ol'); return list && ( command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL' ); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName': function(command) { var value = 0, parent; if ((parent = dom.getParent(selection.getNode(), 'span'))) { if (command == 'fontsize') { value = parent.style.fontSize; } else { value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo: function() { editor.undoManager.undo(); }, Redo: function() { editor.undoManager.redo(); } }); }; });
michalgraczyk/calculus
web/js/tiny_mce/js/tinymce/classes/EditorCommands.js
JavaScript
mit
29,362
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using Perspex.Media; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; namespace TheArtOfDev.HtmlRenderer.Perspex.Adapters { /// <summary> /// Adapter for Perspex Font. /// </summary> internal sealed class FontAdapter : RFont { public RFontStyle Style { get; } #region Fields and Consts /// <summary> /// the size of the font /// </summary> private readonly double _size; /// <summary> /// the vertical offset of the font underline location from the top of the font. /// </summary> private readonly double _underlineOffset = -1; /// <summary> /// Cached font height. /// </summary> private readonly double _height = -1; /// <summary> /// Cached font whitespace width. /// </summary> private double _whitespaceWidth = -1; #endregion /// <summary> /// Init. /// </summary> public FontAdapter(string fontFamily, double size, RFontStyle style) { Style = style; Name = fontFamily; _size = size; //TODO: Somehow get proper line spacing and underlinePosition var lineSpacing = 1; var underlinePosition = 0; _height = 96d / 72d * _size * lineSpacing; _underlineOffset = 96d / 72d * _size * (lineSpacing + underlinePosition); } public string Name { get; set; } public override double Size { get { return _size; } } public override double UnderlineOffset { get { return _underlineOffset; } } public override double Height { get { return _height; } } public override double LeftPadding { get { return _height / 6f; } } public override double GetWhitespaceWidth(RGraphics graphics) { if (_whitespaceWidth < 0) { _whitespaceWidth = graphics.MeasureString(" ", this).Width; } return _whitespaceWidth; } public FontStyle FontStyle => Style.HasFlag(RFontStyle.Italic) ? FontStyle.Italic : FontStyle.Normal; public FontWeight Weight => Style.HasFlag(RFontStyle.Bold) ? FontWeight.Bold : FontWeight.Normal; } }
danwalmsley/Perspex
src/Perspex.HtmlRenderer/Adapters/FontAdapter.cs
C#
mit
2,736
require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../test_helper' describe "<%= class_name %>", ActiveSupport::TestCase do # Replace this with your real tests. it "should be true" do assert true end end
claudiobm/ClockingIT-In-CapellaDesign
vendor/plugins/test_spec_on_rails/lib/generators/model/templates/unit_test.rb
Ruby
mit
233
<?php /** * WPSEO plugin file. * * @package WPSEO\Internals\Options */ /** * Option: wpseo. */ class WPSEO_Option_Wpseo extends WPSEO_Option { /** * @var string Option name. */ public $option_name = 'wpseo'; /** * @var array Array of defaults for the option. * Shouldn't be requested directly, use $this->get_defaults(); */ protected $defaults = array( // Non-form fields, set via (ajax) function. 'ms_defaults_set' => false, // Non-form field, should only be set via validation routine. 'version' => '', // Leave default as empty to ensure activation/upgrade works. // Form fields. 'disableadvanced_meta' => true, 'onpage_indexability' => true, 'baiduverify' => '', // Text field. 'googleverify' => '', // Text field. 'msverify' => '', // Text field. 'yandexverify' => '', 'site_type' => '', // List of options. 'has_multiple_authors' => '', 'environment_type' => '', 'content_analysis_active' => true, 'keyword_analysis_active' => true, 'enable_admin_bar_menu' => true, 'enable_cornerstone_content' => true, 'enable_xml_sitemap' => true, 'enable_text_link_counter' => true, 'show_onboarding_notice' => false, 'first_activated_on' => false, 'recalibration_beta' => false, ); /** * @var array Sub-options which should not be overloaded with multi-site defaults. */ public $ms_exclude = array( /* Privacy. */ 'baiduverify', 'googleverify', 'msverify', 'yandexverify', ); /** @var array Possible values for the site_type option. */ protected $site_types = array( '', 'blog', 'shop', 'news', 'smallBusiness', 'corporateOther', 'personalOther', ); /** @var array Possible environment types. */ protected $environment_types = array( '', 'production', 'staging', 'development', ); /** @var array Possible has_multiple_authors options. */ protected $has_multiple_authors_options = array( '', true, false, ); /** * @var string Name for an option higher in the hierarchy to override setting access. */ protected $override_option_name = 'wpseo_ms'; /** * Add the actions and filters for the option. * * @todo [JRF => testers] Check if the extra actions below would run into problems if an option * is updated early on and if so, change the call to schedule these for a later action on add/update * instead of running them straight away. * * @return \WPSEO_Option_Wpseo */ protected function __construct() { parent::__construct(); /* Clear the cache on update/add. */ add_action( 'add_option_' . $this->option_name, array( 'WPSEO_Utils', 'clear_cache' ) ); add_action( 'update_option_' . $this->option_name, array( 'WPSEO_Utils', 'clear_cache' ) ); /** * Filter the `wpseo` option defaults. * * @param array $defaults Array the defaults for the `wpseo` option attributes. */ $this->defaults = apply_filters( 'wpseo_option_wpseo_defaults', $this->defaults ); } /** * Get the singleton instance of this class. * * @return object */ public static function get_instance() { if ( ! ( self::$instance instanceof self ) ) { self::$instance = new self(); } return self::$instance; } /** * Add filters to make sure that the option is merged with its defaults before being returned. * * @return void */ public function add_option_filters() { parent::add_option_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_option_filter_hook(); if ( has_filter( $hookname, $callback ) === false ) { add_filter( $hookname, $callback, $priority ); } } /** * Remove the option filters. * Called from the clean_up methods to make sure we retrieve the original old option. * * @return void */ public function remove_option_filters() { parent::remove_option_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_option_filter_hook(); remove_filter( $hookname, $callback, $priority ); } /** * Add filters to make sure that the option default is returned if the option is not set. * * @return void */ public function add_default_filters() { parent::add_default_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_default_option_filter_hook(); if ( has_filter( $hookname, $callback ) === false ) { add_filter( $hookname, $callback, $priority ); } } /** * Remove the default filters. * Called from the validate() method to prevent failure to add new options. * * @return void */ public function remove_default_filters() { parent::remove_default_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_default_option_filter_hook(); remove_filter( $hookname, $callback, $priority ); } /** * Validate the option. * * @param array $dirty New value for the option. * @param array $clean Clean value for the option, normally the defaults. * @param array $old Old value of the option. * * @return array Validated clean value for the option to be saved to the database. */ protected function validate_option( $dirty, $clean, $old ) { foreach ( $clean as $key => $value ) { switch ( $key ) { case 'version': $clean[ $key ] = WPSEO_VERSION; break; /* Verification strings. */ case 'baiduverify': case 'googleverify': case 'msverify': case 'yandexverify': $this->validate_verification_string( $key, $dirty, $old, $clean ); break; /* * Boolean dismiss warnings - not fields - may not be in form * (and don't need to be either as long as the default is false). */ case 'ms_defaults_set': if ( isset( $dirty[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::validate_bool( $dirty[ $key ] ); } elseif ( isset( $old[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::validate_bool( $old[ $key ] ); } break; case 'site_type': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->site_types, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'environment_type': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->environment_types, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'has_multiple_authors': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->has_multiple_authors_options, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'first_activated_on': $clean[ $key ] = false; if ( isset( $dirty[ $key ] ) ) { if ( $dirty[ $key ] === false || WPSEO_Utils::validate_int( $dirty[ $key ] ) ) { $clean[ $key ] = $dirty[ $key ]; } } break; /* * Boolean (checkbox) fields. */ /* * Covers: * 'disableadvanced_meta' * 'yoast_tracking' */ default: $clean[ $key ] = ( isset( $dirty[ $key ] ) ? WPSEO_Utils::validate_bool( $dirty[ $key ] ) : false ); break; } } return $clean; } /** * Verifies that the feature variables are turned off if the network is configured so. * * @param mixed $options Value of the option to be returned. Typically an array. * * @return mixed Filtered $options value. */ public function verify_features_against_network( $options = array() ) { if ( ! is_array( $options ) || empty( $options ) ) { return $options; } // For the feature variables, set their values to off in case they are disabled. $feature_vars = array( 'disableadvanced_meta' => false, 'onpage_indexability' => false, 'content_analysis_active' => false, 'keyword_analysis_active' => false, 'enable_admin_bar_menu' => false, 'enable_cornerstone_content' => false, 'enable_xml_sitemap' => false, 'enable_text_link_counter' => false, ); // We can reuse this logic from the base class with the above defaults to parse with the correct feature values. $options = $this->prevent_disabled_options_update( $options, $feature_vars ); return $options; } /** * Gets the filter hook name and callback for adjusting the retrieved option value against the network-allowed features. * * @return array Array where the first item is the hook name, the second is the hook callback, * and the third is the hook priority. */ protected function get_verify_features_option_filter_hook() { return array( "option_{$this->option_name}", array( $this, 'verify_features_against_network' ), 11, ); } /** * Gets the filter hook name and callback for adjusting the default option value against the network-allowed features. * * @return array Array where the first item is the hook name, the second is the hook callback, * and the third is the hook priority. */ protected function get_verify_features_default_option_filter_hook() { return array( "default_option_{$this->option_name}", array( $this, 'verify_features_against_network' ), 11, ); } /** * Clean a given option value. * * @param array $option_value Old (not merged with defaults or filtered) option value to * clean according to the rules for this option. * @param string $current_version Optional. Version from which to upgrade, if not set, * version specific upgrades will be disregarded. * @param array $all_old_option_values Optional. Only used when importing old options to have * access to the real old values, in contrast to the saved ones. * * @return array Cleaned option. */ protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) { return $option_value; } }
mandino/hotelmilosantabarbara.com
wp-content/plugins/wordpress-seo/inc/options/class-wpseo-option-wpseo.php
PHP
mit
10,210
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.test.utility.events; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.persistence.tools.workbench.utility.AbstractModel; import org.eclipse.persistence.tools.workbench.utility.ClassTools; import org.eclipse.persistence.tools.workbench.utility.CollectionTools; import org.eclipse.persistence.tools.workbench.utility.events.CollectionChangeListener; import org.eclipse.persistence.tools.workbench.utility.events.ListChangeEvent; import org.eclipse.persistence.tools.workbench.utility.events.ListChangeListener; import org.eclipse.persistence.tools.workbench.utility.events.ReflectiveChangeListener; import org.eclipse.persistence.tools.workbench.utility.iterators.CloneListIterator; public class ReflectiveListChangeListenerTests extends TestCase { public static Test suite() { return new TestSuite(ReflectiveListChangeListenerTests.class); } public ReflectiveListChangeListenerTests(String name) { super(name); } private ListChangeListener buildZeroArgumentListener(Object target) { return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedZeroArgument", "itemRemovedZeroArgument", "itemReplacedZeroArgument", "listChangedZeroArgument"); } private ListChangeListener buildSingleArgumentListener(Object target) { return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedSingleArgument", "itemRemovedSingleArgument", "itemReplacedSingleArgument", "listChangedSingleArgument"); } public void testItemAddedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.addString(string); assertTrue(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.addString(string); assertTrue(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.addString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertTrue(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.addString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertTrue(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertTrue(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertTrue(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertTrue(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertTrue(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedZeroArgument() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertTrue(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertTrue(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedSingleArgument() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertTrue(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertTrue(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertTrue(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertTrue(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertTrue(target.listChangedSingleArgumentFlag); } public void testListChangedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertTrue(target.listChangedSingleArgumentFlag); } public void testBogusDoubleArgument1() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); boolean exCaught = false; try { ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, "listChangedDoubleArgument"); fail("bogus listener: " + listener); } catch (RuntimeException ex) { if (ex.getCause().getClass() == NoSuchMethodException.class) { exCaught = true; } } assertTrue(exCaught); } public void testBogusDoubleArgument2() throws Exception { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); Method method = ClassTools.method(target, "listChangedDoubleArgument", new Class[] {ListChangeEvent.class, Object.class}); boolean exCaught = false; try { ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, method); fail("bogus listener: " + listener); } catch (RuntimeException ex) { if (ex.getMessage().equals(method.toString())) { exCaught = true; } } assertTrue(exCaught); } public void testListenerMismatch() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); // build a LIST change listener and hack it so we // can add it as a COLLECTION change listener Object listener = ReflectiveChangeListener.buildListChangeListener(target, "itemAddedSingleArgument"); testModel.addCollectionChangeListener((CollectionChangeListener) listener); boolean exCaught = false; try { testModel.changeCollection(); fail("listener mismatch: " + listener); } catch (IllegalArgumentException ex) { exCaught = true; } assertTrue(exCaught); } private class TestModel extends AbstractModel { private List strings = new ArrayList(); public static final String STRINGS_LIST = "strings"; TestModel() { super(); } ListIterator strings() { return new CloneListIterator(this.strings); } void addString(String string) { this.addItemToList(string, this.strings, STRINGS_LIST); } void removeString(String string) { this.removeItemFromList(this.strings.indexOf(string), this.strings, STRINGS_LIST); } void replaceString(String oldString, String newString) { this.setItemInList(this.strings.indexOf(oldString), newString, this.strings, STRINGS_LIST); } void replaceAllStrings(String[] newStrings) { this.strings.clear(); CollectionTools.addAll(this.strings, newStrings); this.fireListChanged(STRINGS_LIST); } void changeCollection() { this.fireCollectionChanged("bogus collection"); } } private class Target { TestModel testModel; String listName; String string; int index; String replacedString; boolean itemAddedZeroArgumentFlag = false; boolean itemAddedSingleArgumentFlag = false; boolean itemRemovedZeroArgumentFlag = false; boolean itemRemovedSingleArgumentFlag = false; boolean itemReplacedZeroArgumentFlag = false; boolean itemReplacedSingleArgumentFlag = false; boolean listChangedZeroArgumentFlag = false; boolean listChangedSingleArgumentFlag = false; Target(TestModel testModel, String listName, String string, int index) { super(); this.testModel = testModel; this.listName = listName; this.string = string; this.index = index; } Target(TestModel testModel, String listName, String string, int index, String replacedString) { this(testModel, listName, string, index); this.replacedString = replacedString; } void itemAddedZeroArgument() { this.itemAddedZeroArgumentFlag = true; } void itemAddedSingleArgument(ListChangeEvent e) { this.itemAddedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.index, e.getIndex()); } void itemRemovedZeroArgument() { this.itemRemovedZeroArgumentFlag = true; } void itemRemovedSingleArgument(ListChangeEvent e) { this.itemRemovedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.index, e.getIndex()); } void itemReplacedZeroArgument() { this.itemReplacedZeroArgumentFlag = true; } void itemReplacedSingleArgument(ListChangeEvent e) { this.itemReplacedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.replacedString, e.replacedItems().next()); assertEquals(this.index, e.getIndex()); } void listChangedZeroArgument() { this.listChangedZeroArgumentFlag = true; } void listChangedSingleArgument(ListChangeEvent e) { this.listChangedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertFalse(e.items().hasNext()); assertEquals(this.index, e.getIndex()); } void listChangedDoubleArgument(ListChangeEvent e, Object o) { fail("bogus event: " + e); } } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench.test/utility/source/org/eclipse/persistence/tools/workbench/test/utility/events/ReflectiveListChangeListenerTests.java
Java
epl-1.0
22,586
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.machine.shared.dto; import org.eclipse.che.api.core.factory.FactoryParameter; import org.eclipse.che.api.core.model.machine.MachineConfig; import org.eclipse.che.api.core.rest.shared.dto.Hyperlinks; import org.eclipse.che.api.core.rest.shared.dto.Link; import org.eclipse.che.dto.shared.DTO; import java.util.List; import java.util.Map; import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation.MANDATORY; import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation.OPTIONAL; /** * @author Alexander Garagatyi */ @DTO public interface MachineConfigDto extends MachineConfig, Hyperlinks { @Override @FactoryParameter(obligation = OPTIONAL) String getName(); void setName(String name); MachineConfigDto withName(String name); @Override @FactoryParameter(obligation = MANDATORY) MachineSourceDto getSource(); void setSource(MachineSourceDto source); MachineConfigDto withSource(MachineSourceDto source); @Override @FactoryParameter(obligation = MANDATORY) boolean isDev(); void setDev(boolean dev); MachineConfigDto withDev(boolean dev); @Override @FactoryParameter(obligation = MANDATORY) String getType(); void setType(String type); MachineConfigDto withType(String type); @Override @FactoryParameter(obligation = OPTIONAL) MachineLimitsDto getLimits(); void setLimits(MachineLimitsDto limits); MachineConfigDto withLimits(MachineLimitsDto limits); @Override List<ServerConfDto> getServers(); void setServers(List<ServerConfDto> servers); MachineConfigDto withServers(List<ServerConfDto> servers); @Override Map<String, String> getEnvVariables(); void setEnvVariables(Map<String, String> envVariables); MachineConfigDto withEnvVariables(Map<String, String> envVariables); @Override MachineConfigDto withLinks(List<Link> links); }
bartlomiej-laczkowski/che
wsmaster/che-core-api-machine-shared/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineConfigDto.java
Java
epl-1.0
2,478
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.test.mappingsmodel.query; import org.eclipse.persistence.tools.workbench.test.mappingsmodel.ModelProblemsTestCase; import org.eclipse.persistence.tools.workbench.mappingsmodel.ProblemConstants; import org.eclipse.persistence.tools.workbench.mappingsmodel.db.MWColumn; import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.relational.MWUserDefinedQueryKey; import junit.framework.Test; import junit.framework.TestSuite; public class MWUserDefinedQueryKeyTests extends ModelProblemsTestCase { public static Test suite() { return new TestSuite(MWUserDefinedQueryKeyTests.class); } /** * Constructor for MWQueryableTests. * @param name */ public MWUserDefinedQueryKeyTests(String name){ super(name); } public void testFieldExistsProblem() { String problem = ProblemConstants.DESCRIPTOR_QUERY_KEY_NO_COLUMN_SPECIFIED; MWUserDefinedQueryKey qKey = getPersonDescriptor().addQueryKey("qKey", (MWColumn)getPersonDescriptor().getPrimaryTable().columns().next()); assertTrue("The query key should not have the problem: " + problem, !hasProblem(problem, getPersonDescriptor())); qKey.setColumn(null); assertTrue("The query key should have the problem: " + problem, hasProblem(problem, getPersonDescriptor())); } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench.test/mappingsplugin/source/org/eclipse/persistence/tools/workbench/test/mappingsmodel/query/MWUserDefinedQueryKeyTests.java
Java
epl-1.0
2,104
/******************************************************************************* * Copyright (c) 2006, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.parser; /** * The query BNF for a function expression returning a numeric value. * <p> * JPA 1.0: * <div><b>BNF:</b> <code>functions_returning_numerics::= LENGTH(string_primary) | * LOCATE(string_primary, string_primary[, simple_arithmetic_expression]) | * ABS(simple_arithmetic_expression) | SQRT(simple_arithmetic_expression) | * MOD(simple_arithmetic_expression, simple_arithmetic_expression) | * SIZE(collection_valued_path_expression)</code><p></div> * * JPA 2.0: * <div><b>BNF:</b> <code>functions_returning_numerics::= LENGTH(string_primary) | * LOCATE(string_primary, string_primary[, simple_arithmetic_expression]) | * ABS(simple_arithmetic_expression) | SQRT(simple_arithmetic_expression) | * MOD(simple_arithmetic_expression, simple_arithmetic_expression) | * SIZE(collection_valued_path_expression) | * INDEX(identification_variable)</code><p></div> * * @version 2.4 * @since 2.3 * @author Pascal Filion */ @SuppressWarnings("nls") public final class FunctionsReturningNumericsBNF extends JPQLQueryBNF { /** * The unique identifier of this BNF rule. */ public static final String ID = "functions_returning_numerics"; /** * Creates a new <code>FunctionsReturningNumericsBNF</code>. */ public FunctionsReturningNumericsBNF() { super(ID); } /** * {@inheritDoc} */ @Override protected void initialize() { super.initialize(); registerExpressionFactory(LengthExpressionFactory.ID); registerExpressionFactory(LocateExpressionFactory.ID); registerExpressionFactory(AbsExpressionFactory.ID); registerExpressionFactory(SqrtExpressionFactory.ID); registerExpressionFactory(ModExpressionFactory.ID); registerExpressionFactory(SizeExpressionFactory.ID); } }
RallySoftware/eclipselink.runtime
jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/FunctionsReturningNumericsBNF.java
Java
epl-1.0
3,120
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dmccann - August 6/2009 - 2.0 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.oxm.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.eclipse.persistence.config.DescriptorCustomizer; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The XmlCustomizer annotation is used to specify a class that implements the * org.eclipse.persistence.config.DescriptorCustomizer * interface and is to run against a class descriptor after all metadata * processing has been completed. */ @Target({TYPE}) @Retention(RUNTIME) public @interface XmlCustomizer { /** * (Required) Defines the name of the descriptor customizer that should be * applied to this classes descriptor. */ Class<? extends DescriptorCustomizer> value(); }
gameduell/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/annotations/XmlCustomizer.java
Java
epl-1.0
1,534
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package kernel */ $tpl = eZTemplate::factory(); $Module = $Params['Module']; $roleID = $Params['RoleID']; $ini = eZINI::instance( 'module.ini' ); $modules = $ini->variable( 'ModuleSettings', 'ModuleList' ); sort( $modules ); $role = eZRole::fetch( 0, $roleID ); if ( $role === null ) { $role = eZRole::fetch( $roleID ); if ( $role ) { if ( $role->attribute( 'version' ) == '0' ) { $temporaryRole = $role->createTemporaryVersion(); unset( $role ); $role = $temporaryRole; } } else { return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); } } $http = eZHTTPTool::instance(); $tpl->setVariable( 'module', $Module ); $role->turnOffCaching(); $tpl->setVariable( 'role', $role ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); if ( $http->hasPostVariable( 'NewName' ) && $role->attribute( 'name' ) != $http->postVariable( 'NewName' ) ) { $role->setAttribute( 'name' , $http->postVariable( 'NewName' ) ); $role->store(); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } $showModules = true; $showFunctions = false; $showLimitations = false; $noFunctions = false; $noLimitations = false; if ( $http->hasPostVariable( 'Apply' ) ) { $originalRole = eZRole::fetch( $role->attribute( 'version' ) ); $originalRoleName = $originalRole->attribute( 'name' ); $originalRoleID = $originalRole->attribute( 'id' ); // Who changes which role(s) should be logged. if ( $http->hasSessionVariable( 'RoleWasChanged' ) and $http->sessionVariable( 'RoleWasChanged' ) === true ) { eZAudit::writeAudit( 'role-change', array( 'Role ID' => $originalRoleID, 'Role name' => $originalRoleName, 'Comment' => 'Changed the current role: kernel/role/edit.php' ) ); $http->removeSessionVariable( 'RoleWasChanged' ); } $originalRole->revertFromTemporaryVersion(); eZContentCacheManager::clearAllContentCache(); $Module->redirectTo( $Module->functionURI( 'view' ) . '/' . $originalRoleID . '/'); /* Clean up policy cache */ eZUser::cleanupCache(); } if ( $http->hasPostVariable( 'Discard' ) ) { $http->removeSessionVariable( 'RoleWasChanged' ); $role = eZRole::fetch( $roleID ) ; $originalRole = eZRole::fetch( $role->attribute( 'version') ); $role->removeThis(); if ( $originalRole != null && $originalRole->attribute( 'is_new' ) == 1 ) { $originalRole->remove(); } $Module->redirectTo( $Module->functionURI( 'list' ) . '/' ); } if ( $http->hasPostVariable( 'ChangeRoleName' ) ) { $role->setAttribute( 'name', $http->postVariable( 'NewName' ) ); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'AddModule' ) ) { if ( $http->hasPostVariable( 'Modules' ) ) $currentModule = $http->postVariable( 'Modules' ); else if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => '*' ) ); } if ( $http->hasPostVariable( 'AddFunction' ) ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'ModuleFunction' ); eZDebugSetting::writeDebug( 'kernel-role-edit', $currentModule, 'currentModule'); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction ) ); } if ( $http->hasPostVariable( 'AddLimitation' ) ) { $policy = false; if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $hasNodeLimitation = false; $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); if ( $policy ) { $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); if ( $limitationIdentifier == 'Node' ) { $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); if ( $nodeLimitationValues != null ) $hasNodeLimitation = true; else eZPolicyLimitation::removeByID( $limitationID ); } if ( $limitationIdentifier == 'Subtree' ) { $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); if ( $nodeLimitationValues == null ) eZPolicyLimitation::removeByID( $limitationID ); } } // if ( !$hasNodeLimitation ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'CurrentFunction' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $currentFunctionLimitations = $functions[ $currentFunction ]; foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) and $functionLimitation['name'] != 'Node' and $functionLimitation['name'] != 'Subtree' ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); if ( !in_array( '-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } } } if ( !$policy ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'CurrentFunction' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '' ) ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $currentFunctionLimitations = $functions[ $currentFunction ]; eZDebugSetting::writeDebug( 'kernel-role-edit', $currentFunctionLimitations, 'currentFunctionLimitations' ); $db = eZDB::instance(); $db->begin(); foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues' ); if ( !in_array('-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } $db->commit(); } } if ( $http->hasPostVariable( 'RemovePolicy' ) ) { $policyID = $http->postVariable( 'RolePolicy' ) ; eZDebugSetting::writeDebug( 'kernel-role-edit', $policyID, 'trying to remove policy' ); eZPolicy::removeByID( $policyID ); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'RemovePolicies' ) and $http->hasPostVariable( 'DeleteIDArray' ) ) { $db = eZDB::instance(); $db->begin(); foreach( $http->postVariable( 'DeleteIDArray' ) as $deleteID) { eZDebugSetting::writeDebug( 'kernel-role-edit', $deleteID, 'trying to remove policy' ); eZPolicy::removeByID( $deleteID ); } $db->commit(); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'CustomFunction' ) ) { if ( $http->hasPostVariable( 'Modules' ) ) $currentModule = $http->postVariable( 'Modules' ); else if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); if ( $currentModule != '*' ) { $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); } else { $functionNames = array(); } $showModules = false; $showFunctions = true; if ( count( $functionNames ) < 1 ) { $showModules = true; $showFunctions = false; $showLimitations = false; $noFunctions = true; } $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'no_functions', $noFunctions ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step 2: select function' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep2.tpl' ); return; } if ( $http->hasPostVariable( 'DiscardFunction' ) ) { $showModules = true; $showFunctions = false; } if ( $http->hasPostVariable( 'SelectButton' ) or $http->hasPostVariable( 'BrowseCancelButton' ) or $http->hasPostVariable( 'Limitation' ) or $http->hasPostVariable( 'SelectedNodeIDArray' ) or $http->hasPostVariable( 'BrowseLimitationNodeButton' ) or $http->hasPostVariable( 'DeleteNodeButton' ) or $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) or $http->hasPostVariable( 'DeleteSubtreeButton' ) ) { $db = eZDB::instance(); $db->begin(); if ( $http->hasPostVariable( 'DeleteNodeButton' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) { if ( $http->hasPostVariable( 'DeleteNodeIDArray' ) ) { $deletedIDList = $http->postVariable( 'DeleteNodeIDArray' ); foreach ( $deletedIDList as $deletedID ) { eZPolicyLimitationValue::removeByValue( $deletedID, $http->sessionVariable( 'BrowsePolicyID' ) ); } } } if ( $http->hasPostVariable( 'DeleteSubtreeButton' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) { if ( $http->hasPostVariable( 'DeleteSubtreeIDArray' ) ) { $deletedIDList = $http->postVariable( 'DeleteSubtreeIDArray' ); foreach ( $deletedIDList as $deletedID ) { $subtree = eZContentObjectTreeNode::fetch( $deletedID , false, false); $path = $subtree['path_string']; eZPolicyLimitationValue::removeByValue( $path, $http->sessionVariable( 'BrowsePolicyID' ) ); } } } if ( $http->hasPostVariable( 'Limitation' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) $http->removeSessionVariable( 'BrowsePolicyID' ); if ( $http->hasSessionVariable( 'BrowseCurrentModule' ) ) $currentModule = $http->sessionVariable( 'BrowseCurrentModule' ); if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); $showModules = false; $showFunctions = false; $showLimitations = true; $nodeList = array(); $nodeIDList = array(); $subtreeList = array(); $subtreeIDList = array(); // Check for temporary node and subtree policy limitation if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policyID = $http->sessionVariable( 'BrowsePolicyID' ); // Fetch node limitations $nodeLimitation = eZPolicyLimitation::fetchByIdentifier( $policyID, 'Node' ); if ( $nodeLimitation != null ) { $nodeLimitationID = $nodeLimitation->attribute('id'); $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $nodeLimitationID ); foreach ( $nodeLimitationValues as $nodeLimitationValue ) { $nodeID = $nodeLimitationValue->attribute( 'value' ); $nodeIDList[] = $nodeID; $node = eZContentObjectTreeNode::fetch( $nodeID ); $nodeList[] = $node; } } // Fetch subtree limitations $subtreeLimitation = eZPolicyLimitation::fetchByIdentifier( $policyID, 'Subtree' ); if ( $subtreeLimitation != null ) { $subtreeLimitationID = $subtreeLimitation->attribute('id'); $subtreeLimitationValues = eZPolicyLimitationValue::fetchList( $subtreeLimitationID ); foreach ( $subtreeLimitationValues as $subtreeLimitationValue ) { $subtreePath = $subtreeLimitationValue->attribute( 'value' ); $subtreeObject = eZContentObjectTreeNode::fetchByPath( $subtreePath ); if ( $subtreeObject ) { $subtreeID = $subtreeObject->attribute( 'node_id' ); $subtreeIDList[] = $subtreeID; $subtree = eZContentObjectTreeNode::fetch( $subtreeID ); $subtreeList[] = $subtree; } } } } if ( $http->hasSessionVariable( 'BrowseCurrentFunction' ) ) $currentFunction = $http->sessionVariable( 'BrowseCurrentFunction' ); if ( $http->hasPostVariable( 'CurrentFunction' ) ) $currentFunction = $http->postVariable( 'CurrentFunction' ); if ( $http->hasPostVariable( 'ModuleFunction' ) ) $currentFunction = $http->postVariable( 'ModuleFunction' ); $currentFunctionLimitations = array(); foreach( $functions[ $currentFunction ] as $key => $limitation ) { if( count( $limitation[ 'values' ] == 0 ) && array_key_exists( 'class', $limitation ) ) { $obj = new $limitation['class']( array() ); $limitationValueList = call_user_func_array ( array( $obj , $limitation['function']) , $limitation['parameter'] ); $limitationValueArray = array(); foreach( $limitationValueList as $limitationValue ) { $limitationValuePair = array(); $limitationValuePair['Name'] = $limitationValue[ 'name' ]; $limitationValuePair['value'] = $limitationValue[ 'id' ]; $limitationValueArray[] = $limitationValuePair; } $limitation[ 'values' ] = $limitationValueArray; } $currentFunctionLimitations[ $key ] = $limitation; } if ( count( $currentFunctionLimitations ) < 1 ) { $showModules = false; $showFunctions = true; $showLimitations = false; $noLimitations = true; } if ( $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) || $http->hasPostVariable( 'BrowseLimitationNodeButton' ) ) { // Store other limitations if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); } foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) and $functionLimitation['name'] != 'Node' and $functionLimitation['name'] != 'Subtree' ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues'); if ( !in_array('-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] )) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues'); if ( !in_array( '-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $policyLimitation, 'policyLimitationCreated' ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } $db->commit(); $http->setSessionVariable( 'BrowseCurrentModule', $currentModule ); $http->setSessionVariable( 'BrowseCurrentFunction', $currentFunction ); if ( $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) ) { eZContentBrowse::browse( array( 'action_name' => 'FindLimitationSubtree', 'from_page' => '/role/edit/' . $roleID . '/' ), $Module ); } elseif ( $http->hasPostVariable( 'BrowseLimitationNodeButton' ) ) { eZContentBrowse::browse( array( 'action_name' => 'FindLimitationNode', 'from_page' => '/role/edit/' . $roleID . '/' ), $Module ); } return; } if ( $http->hasPostVariable( 'SelectedNodeIDArray' ) and $http->postVariable( 'BrowseActionName' ) == 'FindLimitationNode' and !$http->hasPostVariable( 'BrowseCancelButton' ) ) { $selectedNodeIDList = $http->postVariable( 'SelectedNodeIDArray' ); if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); // Remove other limitations. When the policy is applied to node, no other constraints needed. // Removes limitations only from a DropList if it is specified in the module. if ( isset( $currentFunctionLimitations['Node']['DropList'] ) ) { $dropList = $currentFunctionLimitations['Node']['DropList']; foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( in_array( $limitationIdentifier, $dropList ) ) { eZPolicyLimitation::removeByID( $limitationID ); } } } else { foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); } } } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); } $nodeLimitation = eZPolicyLimitation::fetchByIdentifier( $policy->attribute('id'), 'Node' ); if ( $nodeLimitation == null ) $nodeLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), 'Node' ); foreach ( $selectedNodeIDList as $nodeID ) { if ( !in_array( $nodeID, $nodeIDList ) ) { $nodeLimitationValue = eZPolicyLimitationValue::createNew( $nodeLimitation->attribute( 'id' ), $nodeID ); $node = eZContentObjectTreeNode::fetch( $nodeID ); $nodeList[] = $node; } } } if ( $http->hasPostVariable( 'SelectedNodeIDArray' ) and $http->postVariable( 'BrowseActionName' ) == 'FindLimitationSubtree' and !$http->hasPostVariable( 'BrowseCancelButton' ) ) { $selectedSubtreeIDList = $http->postVariable( 'SelectedNodeIDArray' ); if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); } $subtreeLimitation = eZPolicyLimitation::fetchByIdentifier( $policy->attribute('id'), 'Subtree' ); if ( $subtreeLimitation == null ) $subtreeLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), 'Subtree' ); foreach ( $selectedSubtreeIDList as $nodeID ) { if ( !in_array( $nodeID, $subtreeIDList ) ) { $subtree = eZContentObjectTreeNode::fetch( $nodeID ); $pathString = $subtree->attribute( 'path_string' ); $policyLimitationValue = eZPolicyLimitationValue::createNew( $subtreeLimitation->attribute( 'id' ), $pathString ); $subtreeList[] = $subtree; } } } if ( $http->hasPostVariable( 'Limitation' ) && count( $currentFunctionLimitations ) == 0 ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'ModuleFunction' ); eZDebugSetting::writeDebug( 'kernel-role-edit', $currentModule, 'currentModule' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction ) ); } else { $db->commit(); $currentLimitationList = array(); foreach ( $currentFunctionLimitations as $currentFunctionLimitation ) { $limitationName = $currentFunctionLimitation['name']; $currentLimitationList[$limitationName] = '-1'; } if ( isset( $policyID ) ) { $limitationList = eZPolicyLimitation::fetchByPolicyID( $policyID ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); $limitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); $valueList = array(); foreach ( $limitationValues as $limitationValue ) { $value = $limitationValue->attribute( 'value' ); $valueList[] = $value; } $currentLimitationList[$limitationIdentifier] = $valueList; } } $tpl->setVariable( 'current_function', $currentFunction ); $tpl->setVariable( 'function_limitations', $currentFunctionLimitations ); $tpl->setVariable( 'no_limitations', $noLimitations ); $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'node_list', $nodeList ); $tpl->setVariable( 'subtree_list', $subtreeList ); $tpl->setVariable( 'current_limitation_list', $currentLimitationList ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step three: set function limitations' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep3.tpl' ); return; } $db->commit(); } if ( $http->hasPostVariable( 'DiscardLimitation' ) || $http->hasPostVariable( 'Step2') ) { $currentModule = $http->postVariable( 'CurrentModule' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); $showModules = false; $showFunctions = true; $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'no_functions', false ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step two: select function' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep2.tpl' ); return; } if ( $http->hasPostVariable( 'CreatePolicy' ) || $http->hasPostVariable( 'Step1' ) ) { // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $tpl->setVariable( 'modules', $modules ); $moduleList = array(); foreach( $modules as $module ) { $moduleList[] = eZModule::exists( $module ); } $tpl->setVariable( 'module_list', $moduleList ); $tpl->setVariable( 'role', $role ); $tpl->setVariable( 'module', $Module ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step one: select module' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep1.tpl' ); return; } // Set flag for audit. If true audit will be processed // Cancel button was pressed if ( $http->hasPostVariable( 'CancelPolicyButton' ) ) $http->setSessionVariable( 'RoleWasChanged', false ); $policies = $role->attribute( 'policies' ); $tpl->setVariable( 'no_functions', $noFunctions ); $tpl->setVariable( 'no_limitations', $noLimitations ); $tpl->setVariable( 'show_modules', $showModules ); $tpl->setVariable( 'show_limitations', $showLimitations ); $tpl->setVariable( 'show_functions', $showFunctions ); $tpl->setVariable( 'policies', $policies ); $tpl->setVariable( 'modules', $modules ); $tpl->setVariable( 'module', $Module ); $tpl->setVariable( 'role', $role ); $tpl->setVariable( 'step', 0 ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $Result = array(); $Result['path'] = array( array( 'text' => 'Role', 'url' => 'role/list' ), array( 'text' => $role->attribute( 'name' ), 'url' => false ) ); $Result['content'] = $tpl->fetch( 'design:role/edit.tpl' ); ?>
CG77/ezpublish-legacy
kernel/role/edit.php
PHP
gpl-2.0
30,498
<?php /** * @file * Contains \Drupal\user\Form\UserPasswordForm. */ namespace Drupal\user\Form; use Drupal\Core\Field\Plugin\Field\FieldType\EmailItem; use Drupal\Core\Form\FormBase; use Drupal\Core\Language\Language; use Drupal\Core\Language\LanguageManager; use Drupal\user\UserStorageControllerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a user password reset form. */ class UserPasswordForm extends FormBase { /** * The user storage controller. * * @var \Drupal\user\UserStorageControllerInterface */ protected $userStorageController; /** * The language manager. * * @var \Drupal\Core\Language\LanguageManager */ protected $languageManager; /** * Constructs a UserPasswordForm object. * * @param \Drupal\user\UserStorageControllerInterface $user_storage_controller * The user storage controller. * @param \Drupal\Core\Language\LanguageManager $language_manager * The language manager. */ public function __construct(UserStorageControllerInterface $user_storage_controller, LanguageManager $language_manager) { $this->userStorageController = $user_storage_controller; $this->languageManager = $language_manager; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('entity.manager')->getStorageController('user'), $container->get('language_manager') ); } /** * {@inheritdoc} */ public function getFormId() { return 'user_pass'; } /** * {@inheritdoc} * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. */ public function buildForm(array $form, array &$form_state) { $form['name'] = array( '#type' => 'textfield', '#title' => $this->t('Username or e-mail address'), '#size' => 60, '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH), '#required' => TRUE, '#attributes' => array( 'autocorrect' => 'off', 'autocapitalize' => 'off', 'spellcheck' => 'false', 'autofocus' => 'autofocus', ), ); // Allow logged in users to request this also. $user = $this->currentUser(); if ($user->isAuthenticated()) { $form['name']['#type'] = 'value'; $form['name']['#value'] = $user->getEmail(); $form['mail'] = array( '#prefix' => '<p>', '#markup' => $this->t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->getEmail())), '#suffix' => '</p>', ); } else { $form['name']['#default_value'] = $this->getRequest()->query->get('name'); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('E-mail new password')); return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { $name = trim($form_state['values']['name']); // Try to load by email. $users = $this->userStorageController->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorageController->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { form_set_value(array('#parents' => array('account')), $account, $form_state); } else { $this->setFormError('name', $form_state, $this->t('Sorry, %name is not recognized as a username or an e-mail address.', array('%name' => $name))); } } /** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $langcode = $this->languageManager->getCurrentLanguage()->id; $account = $form_state['values']['account']; // Mail one time login URL and instructions using current language. $mail = _user_mail_notify('password_reset', $account, $langcode); if (!empty($mail)) { watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->getUsername(), '%email' => $account->getEmail())); drupal_set_message($this->t('Further instructions have been sent to your e-mail address.')); } $form_state['redirect_route']['route_name'] = 'user.page'; } }
allgood2386/lexrants-me
core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php
PHP
gpl-2.0
4,512
<?php /** * This is a helper class for WordPress that allows format HTML tags, including inputs, textareas, etc * * @author Rinat Khaziev * @version 0.1 */ class Html_Helper { function __construct() { } /** * Render multiple choice checkboxes * * @param string $name * @param string $description * @param array $data */ function checkboxes( $name = '', $description = '', $data = array(), $checked = array() ) { if ( $name != '' ) { $name = filter_var( $name, FILTER_SANITIZE_STRING ); if ( $description ); echo $this->element( 'p', __( $description ) ); echo '<input type="hidden" name="' . esc_attr( $name ) .'" value="" />'; foreach ( (array) $data as $item ) { $is_checked_attr = in_array( $item, (array) $checked ) ? ' checked="true" ' : ''; $item = filter_var( $item, FILTER_SANITIZE_STRING ); echo '<div class="sm-input-wrapper">'; echo '<input type="checkbox" name="' . esc_attr( $name ) . '[]" value="' . esc_attr( $item ) . '" id="' .esc_attr( $name ) . esc_attr( $item ) . '" ' . $is_checked_attr . ' />'; echo '<label for="' .esc_attr( $name ) . esc_attr( $item ) . '">' . esc_attr ( $item ) . '</label>'; echo '</div>'; } } } function _checkbox( $name = '', $description = '', $value = '', $atts, $checked = array() ) { // Generate unique id to make label clickable $rnd_id = uniqid( 'uniq-label-id-' ); return '<div class="checkbox-option-wrapper"><input type="checkbox" id="' . esc_attr( $rnd_id ) . '" value="'. esc_attr( $value ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $atts ) . ' /><label for="' . esc_attr( $rnd_id ) . '">' . esc_html ($description ) . '</label></div>'; } function _radio( $name = '', $description = '', $value = '', $atts, $checked = array() ) { // Generate unique id to make label clickable $rnd_id = uniqid( 'uniq-label-id-' ); return '<div class="checkbox-option-wrapper"><input type="radio" id="' . esc_attr( $rnd_id ) . '" value="'. esc_attr( $value ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $atts ) . ' /><label for="' . esc_attr( $rnd_id ) . '">' . esc_html ($description ) . '</label></div>'; } /** * This method supports unlimited arguments, * each argument represents html value */ function table_row() { $data = func_get_args(); $ret = ''; foreach ( $data as $cell ) $ret .= $this->element( 'td', $cell, null, false ); return "<tr>" . $ret . "</tr>\n"; } /** * easy wrapper method * * @param unknown $type (select|input) * @param string $name * @param mixed $data */ function input( $type, $name, $data = null, $attrs = array() ) { switch ( $type ) { case 'select': return $this->_select( $name, $data, $attrs ); break; case 'text': case 'hidden': case 'submit': case 'file': case 'checkbox': return $this->_text( $name, $type, $data, $attrs ) ; break; case 'radio': return $this->_radio( $name, $data, $attrs ) ; default: return; } } /** * This is a private method to render inputs * * @access private */ function _text( $name = '', $type='text', $data = '', $attrs = array() ) { return '<input type="' . esc_attr( $type ) . '" value="'. esc_attr( $data ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $attrs ) . ' />'; } /** * * * @access private */ function _select( $name, $data = array(), $attrs ) { $ret = ''; foreach ( (array) $data as $key => $value ) { $attrs_to_pass = array( 'value' => $key ); if ( isset( $attrs[ 'default' ] ) && $key == $attrs[ 'default' ] ) $attrs_to_pass[ 'selected' ] = 'selected'; $ret .= $this->element( 'option', $value, $attrs_to_pass, false ); } return '<select name="' . esc_attr( $name ) . '">' . $ret . '</select>'; } function table_head( $data = array(), $params = null ) { echo '<table><thead>'; foreach ( $data as $th ) { echo '<th>' . esc_html( $th ) . '</th>'; } echo '</thead><tbody>'; } function table_foot() { echo '</tbody></table>'; } function form_start( $attrs = array() ) { echo '<form' . $this->_format_attributes( $attrs ) .'>'; } function form_end() { echo '</form>'; } /** * Renders html element * * @param string $tag one of allowed tags * @param string content innerHTML content of tag * @param array $params additional attributes * @param bool $escape escape innerHTML or not, defaults to true * @return string rendered html tag */ function element( $tag, $content, $params = array(), $escape = true ) { $allowed = apply_filters( 'hh_allowed_html_elements' , array( 'div', 'p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'option', 'label', 'textarea', 'select', 'option' ) ); $attr_string = $this->_format_attributes( $params ); if ( in_array( $tag, $allowed ) ) return "<{$tag} {$attr_string}>" . ( $escape ? esc_html ( $content ) : $content ) . "</{$tag}>"; } /** * Formats and returns string of allowed html attrs * * @param array $attrs * @return string attributes */ function _format_attributes( $attrs = array() ) { $attr_string = ''; foreach ( (array) $attrs as $attr => $value ) { if ( in_array( $attr, $this->_allowed_html_attrs() ) ) $attr_string .= " {$attr}='" . esc_attr ( $value ) . "'"; } return $attr_string; } /** * Validates and returns url as A HTML element * * @param string $url any valid url * @param string $title * @param unknown $params array of html attributes * @return string html link */ function a( $url, $title = '', $params = array() ) { $attr_string = $this->_format_attributes( $params ); if ( filter_var( trim( $url ), FILTER_VALIDATE_URL ) ) return '<a href="' . esc_url( trim( $url ) ) . '" ' . $attr_string . '>' . ( $title != '' ? esc_html ( $title ) : esc_url( trim( $url ) ) ) . '</a>'; } /** * Returns allowed HTML attributes */ function _allowed_html_attrs() { return apply_filters( 'hh_allowed_html_attributes', array( 'href', 'class', 'id', 'value', 'action', 'name', 'method', 'selected', 'checked', 'for', 'multiple' ) ); } }
Luckynumberseven/project2
wp-content/plugins/frontend-uploader/lib/php/class-html-helper.php
PHP
gpl-2.0
6,132
<?php /** * @package EasyBlog * @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved. * @license GNU/GPL, see LICENSE.php * * EasyBlog is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Restricted access'); ?> <!-- Post item wrapper --> <div id="entry-<?php echo $row->id; ?>" class="blog-post micro-photo clearfix prel<?php echo (!empty($row->team)) ? ' teamblog-post' : '' ;?>" itemscope itemtype="http://schema.org/Blog"> <div class="blog-post-in"> <div class="blog-head"> <!-- @template: Admin tools --> <?php echo $this->fetch( 'blog.admin.tool.php' , array( 'row' => $row ) ); ?> <?php if( $system->config->get( 'layout_avatar' ) && $this->getParam( 'show_avatar_frontpage' ) ){ ?> <!-- @template: Avatar --> <?php echo $this->fetch( 'blog.avatar.php' , array( 'row' => $row ) ); ?> <?php } ?> <div class="blog-head-in"> <!-- Post title --> <div class="blog-photo"> <h2 id="title-<?php echo $row->id; ?>" class="blog-title<?php echo ($row->isFeatured) ? ' featured' : '';?> rip mbs" itemprop="name"> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id='.$row->id); ?>" title="<?php echo $this->escape( $row->title );?>" itemprop="url"><?php echo $row->title; ?></a> <?php if( $row->isFeatured ) { ?> <!-- Show a featured tag if the entry is featured --> <sup class="tag-featured"><?php echo Jtext::_('COM_EASYBLOG_FEATURED_FEATURED'); ?></sup> <?php } ?> </h2> </div> <!-- Post metadata --> <?php echo $this->fetch( 'blog.meta.php' , array( 'row' => $row, 'postedText' => JText::_( 'COM_EASYBLOG_PHOTO_UPLOADED' ) ) ); ?> </div> <div class="clear"></div> </div> <!-- Content wrappings --> <div class="blog-content clearfix"> <!-- @Trigger onAfterDisplayTitle --> <?php echo $row->event->afterDisplayTitle; ?> <!-- Post content --> <div class="blog-text clearfix prel"> <!-- @Trigger: onBeforeDisplayContent --> <?php echo $row->event->beforeDisplayContent; ?> <!-- Load social buttons --> <?php if( in_array( $system->config->get( 'main_socialbutton_position' ) , array( 'top' , 'left' , 'right' ) ) ){ ?> <?php echo EasyBlogHelper::showSocialButton( $row , true ); ?> <?php } ?> <!-- Photo items --> <?php if( $row->images ){ ?> <?php foreach( $row->images as $image ){ ?> <p class="photo-source"> <span> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id='.$row->id); ?>"><img src="<?php echo $image;?>" /></a> </span> </p> <?php } ?> <?php } ?> <!-- Post content --> <?php echo $row->text; ?> <!-- @Trigger: onAfterDisplayContent --> <?php echo $row->event->afterDisplayContent; ?> <!-- Copyright text --> <?php if( $system->config->get( 'layout_copyrights' ) && !empty($row->copyrights) ) { ?> <?php echo $this->fetch( 'blog.copyright.php' , array( 'row' => $row ) ); ?> <?php } ?> <!-- Maps --> <?php if( $system->config->get( 'main_locations_blog_frontpage' ) ){ ?> <?php echo EasyBlogHelper::getHelper( 'Maps' )->getHTML( true , $row->address, $row->latitude , $row->longitude , $system->config->get( 'main_locations_blog_map_width') , $system->config->get( 'main_locations_blog_map_height' ), JText::sprintf( 'COM_EASYBLOG_LOCATIONS_BLOG_POSTED_FROM' , $row->address ), 'post_map_canvas_' . $row->id );?> <?php } ?> </div> <?php if( $this->getParam( 'show_last_modified' ) ){ ?> <!-- Modified date --> <span class="blog-modified-date"> <?php echo JText::_( 'COM_EASYBLOG_LAST_MODIFIED' ); ?> <?php echo JText::_( 'COM_EASYBLOG_ON' ); ?> <time datetime="<?php echo $this->formatDate( '%Y-%m-%d' , $row->modified ); ?>"> <span><?php echo $this->formatDate( $system->config->get('layout_dateformat') , $row->modified ); ?></span> </time> </span> <?php } ?> <?php if( $this->getparam( 'show_tags' , true ) && $this->getParam( 'show_tags_frontpage' , true ) ){ ?> <?php echo $this->fetch( 'tags.item.php' , array( 'tags' => $row->tags ) ); ?> <?php } ?> <!-- Load bottom social buttons --> <?php if( $system->config->get( 'main_socialbutton_position' ) == 'bottom' ){ ?> <?php echo EasyBlogHelper::showSocialButton( $row , true ); ?> <?php } ?> <!-- Standard facebook like button needs to be at the bottom --> <?php if( $system->config->get('main_facebook_like') && $system->config->get('main_facebook_like_layout') == 'standard' && $system->config->get( 'integrations_facebook_show_in_listing') ) : ?> <?php echo $this->fetch( 'facebook.standard.php' , array( 'facebook' => $row->facebookLike ) ); ?> <?php endif; ?> <?php if( $system->config->get( 'layout_showcomment' ) && EasyBlogHelper::getHelper( 'Comment')->isBuiltin() ){ ?> <!-- Recent comment listings on the frontpage --> <?php echo $this->fetch( 'blog.item.comment.list.php' , array( 'row' => $row ) ); ?> <?php } ?> </div> <!-- Bottom metadata --> <?php echo $this->fetch( 'blog.meta.bottom.php' , array( 'row' => $row ) ); ?> </div> </div>
david-strejc/octopus
components/com_easyblog/themes/nomad/blog.item.photo.php
PHP
gpl-2.0
5,596
#include "gtest/gtest.h" #include "llt_mockcpp.h" #include <stdio.h> #include <stdlib.h> //½¨ÒéÕâÑùÒýÓ㬱ÜÃâÏÂÃæÓùؼü×ÖʱÐèÒª¼Óǰ׺ testing:: using namespace testing; #ifdef __cplusplus extern "C" { #endif extern unsigned int uttest_OM_AcpuCallBackMsgProc_case1(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case2(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case3(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case4(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case1(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case2(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case3(void); extern void OM_Log1(char *cFileName, unsigned int ulLineNum, unsigned int enModuleId, unsigned int enSubModId, unsigned int enLevel, char *pcString, int lPara1); extern unsigned int VOS_RegisterPIDInfo(unsigned int ulPID, void* pfnInitFun, void* pfnMsgFun); extern unsigned int VOS_RegisterMsgTaskPrio(unsigned int ulFID, unsigned int TaskPrio); #ifdef __cplusplus } #endif #ifndef VOS_OK #define VOS_OK 0 #endif #ifndef VOS_ERR #define VOS_ERR 1 #endif TEST(OM_AcpuCallBackMsgProc1, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case1(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc2, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case2(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc3, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case3(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc4, UT) { uttest_OM_AcpuCallBackMsgProc_case4(); } TEST(OM_AcpuCallBackFidInit1, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue(VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case1()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit2, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case2()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit3, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_OK)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case3()); GlobalMockObject::reset(); }
slade87/ALE21-Kernel
drivers/hisi/modem_hi6xxx/oam/comm/acore/om/uttest_omappoutside.cpp
C++
gpl-2.0
2,725
/* SESC: Super ESCalar simulator Copyright (C) 2005 University of California, Santa Cruz Contributed by Jose Renau This file is part of SESC. SESC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. SESC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SESC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <ctype.h> #include <math.h> //#include "nanassert.h" //#include "Snippets.h" //#include "SescConf.h" #include "nanassert.h" #include "SescConf.h" #include "Snippets.h" extern "C" { #include "cacti42_areadef.h" #include "cacti_interface.h" #include "cacti42_def.h" #include "cacti42_io.h" } #ifdef SESC_SESCTHERM #include "ThermTrace.h" ThermTrace *sescTherm=0; #endif /*------------------------------------------------------------------------------*/ #include <vector> static double tech; static int res_memport; static double wattch2cactiFactor = 1; double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ); double getEnergy(const char *,xcacti_flp *); //extern "C" void output_data(result_type *result, arearesult_type *arearesult, // area_type *arearesult_subbanked, // parameter_type *parameters, double *NSubbanks); /* extern "C" void output_data(result_type *result, arearesult_type *arearesult, parameter_type *parameters); extern "C" total_result_type cacti_interface( int cache_size, int line_size, int associativity, int rw_ports, int excl_read_ports, int excl_write_ports, int single_ended_read_ports, int banks, double tech_node, int output_width, int specific_tag, int tag_width, int access_mode, int pure_sram); extern "C" void xcacti_power_flp(const result_type *result, const arearesult_type *arearesult, const area_type *arearesult_subbanked, const parameter_type *parameters, xcacti_flp *xflp); */ void iterate(); int getInstQueueSize(const char* proc) { // get the clusters int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; int total = 0; int num = 0; for(int i = min ; i <= max ; i++){ const char* cc = SescConf->getCharPtr(proc,"cluster",i) ; if(SescConf->checkInt(cc,"winSize")){ int sz = SescConf->getInt(cc,"winSize") ; total += sz; num++; } } // check if(!num){ fprintf(stderr,"no clusters\n"); exit(-1); } return total/num; } #ifdef SESC_SESCTHERM static void update_layout_bank(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp) { double dx; double dy; double a; // +------------------------------+ // | bank ctrl | // +------------------------------+ // | tag | de | data | // | array | co | array | // | | de | | // +------------------------------+ // | tag_ctrl | data_ctrl | // +------------------------------+ const char *flpSec = SescConf->getCharPtr("","floorplan"); size_t max = SescConf->getRecordMax(flpSec,"blockDescr"); max++; char cadena[1024]; //-------------------------------- // Find top block bank_ctrl dy = flp->delta_y*(xflp->bank_ctrl_a/xflp->total_a); if (xflp->bank_ctrl_e) { // Only if bankCtrl consumes energy sprintf(cadena, "%sBankCtrl %g %g %g %g", blockName, flp->delta_x, dy, flp->x, flp->y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sBankCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double tag_start_y = dy + flp->y; //-------------------------------- // Find lower blocks tag_ctrl and data_ctrl dy = flp->delta_y*((3*xflp->tag_ctrl_a+3*xflp->data_ctrl_a)/xflp->total_a); a = xflp->tag_ctrl_a+xflp->data_ctrl_a; dx = flp->delta_x*(xflp->tag_ctrl_a/a); double tag_end_y = flp->y+flp->delta_y-dy; if (xflp->tag_array_e) { // Only if tag consumes energy sprintf(cadena,"%sTagCtrl %g %g %g %g", blockName, dx/3, dy, flp->x+dx/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } sprintf(cadena,"%sDataCtrl %g %g %g %g", blockName, (flp->delta_x-dx)/3, dy, flp->x+dx+(flp->delta_x-dx)/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; //-------------------------------- // Find middle blocks tag array, decode, and data array a = xflp->tag_array_a+xflp->data_array_a+xflp->decode_a; dy = tag_end_y - tag_start_y; if (xflp->tag_array_e) { dx = flp->delta_x*(xflp->tag_array_a/a); sprintf(cadena, "%sTagArray %g %g %g %g", blockName, dx, dy, flp->x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double x = flp->x + dx; dx = flp->delta_x*((xflp->decode_a)/a); sprintf(cadena, "%sDecode %g %g %g %g", blockName, dx, dy, x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDecodeEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; dx = flp->delta_x*((xflp->data_array_a)/a); sprintf(cadena, "%sDataArray %g %g %g %g", blockName, dx, dy, flp->x+flp->delta_x-dx, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } static void update_sublayout(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp, int id) { if(id==1) { update_layout_bank(blockName,xflp,flp); }else if ((id % 2) == 0) { // even number ThermTrace::FLPUnit flp1 = *flp; ThermTrace::FLPUnit flp2 = *flp; if (flp->delta_x > flp->delta_y) { // x-axe is bigger flp1.delta_x = flp->delta_x/2; flp2.delta_x = flp->delta_x/2; flp2.x = flp->x+flp->delta_x/2; }else{ // y-axe is bigger flp1.delta_y = flp->delta_x/2; flp2.delta_y = flp->delta_y/2; flp2.y = flp->y + flp->delta_y/2; } update_sublayout(blockName, xflp, &flp1, id/2); update_sublayout(blockName, xflp, &flp2, id/2); }else{ MSG("Invalid number of banks to partition. Please use power of two"); exit(-1); I(0); // In } } void update_layout(const char *blockName, xcacti_flp *xflp) { const ThermTrace::FLPUnit *flp = sescTherm->findBlock(blockName); I(flp); if (flp == 0) { MSG("Error: blockName[%s] not found in blockDescr",blockName); exit(-1); return; // no match found } update_sublayout(blockName, xflp, flp, xflp->NSubbanks*xflp->assoc); } #endif void iterate() { std::vector<char *> sections; std::vector<char *>::iterator it; SescConf->getAllSections(sections) ; char line[100] ; for(it = sections.begin();it != sections.end(); it++) { const char *block = *it; if (!SescConf->checkCharPtr(block,"deviceType")) continue; const char *name = SescConf->getCharPtr(block,"deviceType") ; if(strcasecmp(name,"vbus")==0){ SescConf->updateRecord(block,"busEnergy",0.0) ; // FIXME: compute BUS energy }else if (strcasecmp(name,"niceCache") == 0) { // No energy for ideal caches (DRAM bank) SescConf->updateRecord(block, "RdHitEnergy" ,0.0); SescConf->updateRecord(block, "RdMissEnergy" ,0.0); SescConf->updateRecord(block, "WrHitEnergy" ,0.0); SescConf->updateRecord(block, "WrMissEnergy" ,0.0); }else if(strstr(name,"cache") || strstr(name,"tlb") || strstr(name,"mem") || strstr(name,"dir") || !strcmp(name,"revLVIDTable") ) { xcacti_flp xflp; double eng = getEnergy(block, &xflp); #ifdef SESC_SESCTHERM2 if (SescConf->checkCharPtr(block,"blockName")) { const char *blockName = SescConf->getCharPtr(block,"blockName"); MSG("%s (block=%s) has blockName %s",name, block, blockName); update_layout(blockName, &xflp); } #else // write it SescConf->updateRecord(block, "RdHitEnergy" ,eng); SescConf->updateRecord(block, "RdMissEnergy" ,eng * 2); // Rd miss + lineFill SescConf->updateRecord(block, "WrHitEnergy" ,eng); SescConf->updateRecord(block, "WrMissEnergy" ,eng * 2); // Wr miss + lineFill #endif } } } char * strfy(int v){ char *t = new char[10] ; sprintf(t,"%d",v); return t ; } char *strfy(double v){ char *t = new char[10] ; sprintf(t,"%lf",v); return t ; } double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ) { int nsets = size/(bsize*assoc); int fully_assoc, associativity; int rwPorts = 0; double ret; if (nsets == 0) { printf("Invalid cache parameters size[%d], bsize[%d], assoc[%d]\n", size, bsize, assoc); exit(0); } if (subBanks == 0) { printf("Invalid cache subbanks parameters\n"); exit(0); } if ((size/subBanks)<64) { printf("size %d: subBanks %d: assoc %d : nset %d\n",size,subBanks,assoc,nsets); size =64*subBanks; } if (rdPorts>1) { wrPorts = rdPorts-2; rdPorts = 2; } if ((rdPorts+wrPorts+rwPorts) < 1) { rdPorts = 0; wrPorts = 0; rwPorts = 1; } if (bsize*8 < bits) bsize = bits/8; BITOUT = bits; if (size == bsize * assoc) { fully_assoc = 1; }else{ fully_assoc = 0; } size = roundUpPower2(size); if (fully_assoc) { associativity = size/bsize; }else{ associativity = assoc; } if (associativity >= 32) associativity = size/bsize; nsets = size/(bsize*associativity); total_result_type result2; printf("\n\n\n########################################################"); printf("\nInput to Cacti_Interface..."); printf("\n size = %d, bsize = %d, assoc = %d, rports = %d, wports = %d", size, bsize, associativity, rdPorts, wrPorts); printf("\n subBanks = %d, tech = %f, bits = %d", subBanks, tech, bits); result2 = cacti_interface(size, bsize, associativity, rwPorts, rdPorts, wrPorts, 0, subBanks, tech, bits, 0, 0, // custom tag 0, useTag); #ifdef DEBUG //output_data(&result,&arearesult,&arearesult_subbanked,&parameters); output_data(&result2.result,&result2.area,&result2.params); #endif //xcacti_power_flp(&result,&arearesult,&arearesult_subbanked,&parameters, xflp); xcacti_power_flp(&result2.result, &result2.area, &result2.arearesult_subbanked, &result2.params, xflp); //return wattch2cactiFactor * 1e9*(result.total_power_without_routing/subBanks + result.total_routing_power); return wattch2cactiFactor * 1e9*(result2.result.total_power_without_routing.readOp.dynamic / subBanks + result2.result.total_routing_power.readOp.dynamic); } double getEnergy(const char *section, xcacti_flp *xflp) { // set the input int cache_size = SescConf->getInt(section,"size") ; int block_size = SescConf->getInt(section,"bsize") ; int assoc = SescConf->getInt(section,"assoc") ; int write_ports = 0 ; int read_ports = SescConf->getInt(section,"numPorts"); int readwrite_ports = 1; int subbanks = 1; int bits = 32; if(SescConf->checkInt(section,"subBanks")) subbanks = SescConf->getInt(section,"subBanks"); if(SescConf->checkInt(section,"bits")) bits = SescConf->getInt(section,"bits"); printf("Module [%s]...\n", section); return getEnergy(cache_size ,block_size ,assoc ,read_ports ,readwrite_ports ,subbanks ,1 ,bits ,xflp); } void processBranch(const char *proc) { // FIXME: add thermal block to branch predictor // get the branch const char* bpred = SescConf->getCharPtr(proc,"bpred") ; // get the type const char* type = SescConf->getCharPtr(bpred,"type") ; xcacti_flp xflp; double bpred_power=0; // switch based on the type if(!strcmp(type,"Taken") || !strcmp(type,"Oracle") || !strcmp(type,"NotTaken") || !strcmp(type,"Static")) { // No tables bpred_power= 0; }else if(!strcmp(type,"2bit")) { int size = SescConf->getInt(bpred,"size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); bpred_power= 0; }else if(!strcmp(type,"2level")) { int size = SescConf->getInt(bpred,"l2size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else if(!strcmp(type,"ogehl")) { int mTables = SescConf->getInt(bpred,"mtables") ; int size = SescConf->getInt(bpred,"tsize") ; I(0); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp) * mTables; }else if(!strcmp(type,"hybrid")) { int size = SescConf->getInt(bpred,"localSize") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: update layout #endif size = SescConf->getInt(bpred,"metaSize"); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power += getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else{ MSG("Unknown energy for branch predictor type [%s]", type); exit(-1); } #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure const char *bpredBlockName = SescConf->getCharPtr(bpred, "blockName"); update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"bpredEnergy",bpred_power) ; #endif int btbSize = SescConf->getInt(bpred,"btbSize"); int btbAssoc = SescConf->getInt(bpred,"btbAssoc"); double btb_power = 0; if (btbSize) { btb_power = getEnergy(btbSize*8, 8, btbAssoc, 1, 0, 1, 1, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"btbEnergy",btb_power) ; #endif }else{ SescConf->updateRecord(proc,"btbEnergy",0.0) ; } double ras_power =0; int ras_size = SescConf->getInt(bpred,"rasSize"); if (ras_size) { ras_power = getEnergy(ras_size*8, 8, 1, 1, 0, 1, 0, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure (all bpred may share a block) update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"rasEnergy",ras_power) ; #endif }else{ SescConf->updateRecord(proc,"rasEnergy",0.0) ; } } void processorCore() { const char *proc = SescConf->getCharPtr("","cpucore",0) ; fprintf(stderr,"proc = [%s]\n",proc); xcacti_flp xflp; //---------------------------------------------- // Branch Predictor processBranch(proc); //---------------------------------------------- // Register File int issueWidth= SescConf->getInt(proc,"issueWidth"); int size = SescConf->getInt(proc,"intRegs"); int banks = 1; int rdPorts = 2*issueWidth; int wrPorts = issueWidth; int bits = 32; int bytes = 8; if(SescConf->checkInt(proc,"bits")) { bits = SescConf->getInt(proc,"bits"); bytes = bits/8; if (bits*8 != bytes) { fprintf(stderr,"Not valid number of bits for the processor core [%d]\n",bits); exit(-2); } } if(SescConf->checkInt(proc,"intRegBanks")) banks = SescConf->getInt(proc,"intRegBanks"); if(SescConf->checkInt(proc,"intRegRdPorts")) rdPorts = SescConf->getInt(proc,"intRegRdPorts"); if(SescConf->checkInt(proc,"intRegWrPorts")) wrPorts = SescConf->getInt(proc,"intRegWrPorts"); double regEnergy = getEnergy(size*bytes, bytes, 1, rdPorts, wrPorts, banks, 0, bits, &xflp); printf("\nRegister [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*bytes, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"IntRegBlockName"); I(blockName); update_layout(blockName, &xflp); blockName = SescConf->getCharPtr(proc,"fpRegBlockName"); I(blockName); update_layout(blockName , &xflp); // FIXME: different energy for FP register #else SescConf->updateRecord(proc,"wrRegEnergy",regEnergy); SescConf->updateRecord(proc,"rdRegEnergy",regEnergy); #endif //---------------------------------------------- // Load/Store Queue size = SescConf->getInt(proc,"maxLoads"); banks = 1; rdPorts = res_memport; wrPorts = res_memport; if(SescConf->checkInt(proc,"lsqBanks")) banks = SescConf->getInt(proc,"lsqBanks"); regEnergy = getEnergy(size*2*bytes,2*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"ldqRdWrEnergy",regEnergy); #endif printf("\nLoad Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*2*bytes, banks, 2*res_memport, regEnergy); size = SescConf->getInt(proc,"maxStores"); regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"stqRdWrEnergy",regEnergy); #endif printf("\nStore Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); #ifdef SESC_INORDER size = size/4; regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); printf("\nStore Inorder Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); SescConf->updateRecord(proc,"stqRdWrEnergyInOrder",regEnergy); #ifdef SESC_SESCTHERM I(0); exit(-1); // Not supported #endif #endif //---------------------------------------------- // Reorder Buffer size = SescConf->getInt(proc,"robSize"); banks = size/64; if (banks == 0) { banks = 1; }else{ banks = roundUpPower2(banks); } // Retirement should hit another bank rdPorts = 1; // continuous possitions wrPorts = 1; regEnergy = getEnergy(size*2,2*issueWidth,1,rdPorts,wrPorts,banks,0,16*issueWidth, &xflp); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"robBlockName"); I(blockName); update_layout(blockName, &xflp); // FIXME: partition energies per structure #else SescConf->updateRecord(proc,"robEnergy",regEnergy); #endif printf("\nROB [%d bytes] banks[%d] ports[%d] Energy[%g]\n",size*2, banks, 2*rdPorts, regEnergy); //---------------------------------------------- // Rename Table { double bitsPerEntry = log(SescConf->getInt(proc,"intRegs"))/log(2); size = roundUpPower2(static_cast<unsigned int>(32*bitsPerEntry/8)); banks = 1; rdPorts = 2*issueWidth; wrPorts = issueWidth; regEnergy = getEnergy(size,1,1,rdPorts,wrPorts,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); //FIXME: create a IntRATblockName // FIXME: partition energies per structure #endif printf("\nrename [%d bytes] banks[%d] Energy[%g]\n",size, banks, regEnergy); regEnergy += getEnergy(size,1,1,rdPorts/2+1,wrPorts/2+1,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); // FIXME: partition energies per structure #else // unified FP+Int RAT energy counter SescConf->updateRecord(proc,"renameEnergy",regEnergy); #endif } //---------------------------------------------- // Window Energy & Window + DDIS { int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; I(min==0); for(int i = min ; i <= max ; i++) { const char *cluster = SescConf->getCharPtr(proc,"cluster",i) ; // TRADITIONAL COLLAPSING ISSUE LOGIC // Recalculate windowRdWrEnergy using CACTI (keep select and wake) size = SescConf->getInt(cluster,"winSize"); banks = 1; rdPorts = SescConf->getInt(cluster,"wakeUpNumPorts"); wrPorts = issueWidth; int robSize = SescConf->getInt(proc,"robSize"); float entryBits = 4*(log(robSize)/log(2)); // src1, src2, dest, instID entryBits += 7; // opcode entryBits += 1; // ready bit int tableBits = static_cast<int>(entryBits * size); int tableBytes; if (tableBits < 8) { tableBits = 8; tableBytes = 1; }else{ tableBytes = tableBits/8; } int assoc= roundUpPower2(static_cast<unsigned int>(entryBits/8)); tableBytes = roundUpPower2(tableBytes); regEnergy = getEnergy(tableBytes,tableBytes/assoc,assoc,rdPorts,wrPorts,banks,1,static_cast<int>(entryBits), &xflp); printf("\nWindow [%d bytes] assoc[%d] banks[%d] ports[%d] Energy[%g]\n" ,tableBytes, assoc, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(cluster,"blockName"); I(blockName); update_layout(blockName, &xflp); #else // unified FP+Int RAT energy counter SescConf->updateRecord(cluster,"windowRdWrEnergy" ,regEnergy,0); #endif } } } void cacti_setup() { const char *technology = SescConf->getCharPtr("","technology"); fprintf(stderr,"technology = [%s]\n",technology); tech = SescConf->getInt(technology,"tech"); fprintf(stderr, "tech : %9.0fnm\n" , tech); tech /= 1000; #ifdef SESC_SESCTHERM sescTherm = new ThermTrace(0); // No input trace, just read conf #endif const char *proc = SescConf->getCharPtr("","cpucore",0); const char *l1Cache = SescConf->getCharPtr(proc,"dataSource"); const char *l1CacheSpace = strstr(l1Cache," "); char *l1Section = strdup(l1Cache); if (l1CacheSpace) l1Section[l1CacheSpace - l1Cache] = 0; res_memport = SescConf->getInt(l1Section,"numPorts"); xcacti_flp xflp; double l1Energy = getEnergy(l1Section, &xflp); double WattchL1Energy = SescConf->getDouble("","wattchDataCacheEnergy"); if (WattchL1Energy) { wattch2cactiFactor = WattchL1Energy/l1Energy; fprintf(stderr,"wattch2cacti Factor %g\n", wattch2cactiFactor); }else{ fprintf(stderr,"-----WARNING: No wattch correction factor\n"); } processorCore(); iterate(); }
dilawar/sesc
src_without_LF/libpower/cacti/cacti_setup.cpp
C++
gpl-2.0
23,999
/* * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /* * @test * @summary It tests (almost) all keytool behaviors with NSS. * @library /test/lib /test/jdk/sun/security/pkcs11 * @modules java.base/sun.security.tools.keytool * java.base/sun.security.util * java.base/sun.security.x509 * @run main/othervm/timeout=600 NssTest */ public class NssTest { public static void main(String[] args) throws Exception { Path libPath = PKCS11Test.getNSSLibPath("softokn3"); if (libPath == null) { return; } System.out.println("Using NSS lib at " + libPath); copyFiles(); System.setProperty("nss", ""); System.setProperty("nss.lib", String.valueOf(libPath)); PKCS11Test.loadNSPR(libPath.getParent().toString()); KeyToolTest.main(args); } private static void copyFiles() throws IOException { Path srcPath = Paths.get(System.getProperty("test.src")); Files.copy(srcPath.resolve("p11-nss.txt"), Paths.get("p11-nss.txt")); Path dbPath = srcPath.getParent().getParent() .resolve("pkcs11").resolve("nss").resolve("db"); Files.copy(dbPath.resolve("cert8.db"), Paths.get("cert8.db")); Files.copy(dbPath.resolve("key3.db"), Paths.get("key3.db")); Files.copy(dbPath.resolve("secmod.db"), Paths.get("secmod.db")); } }
md-5/jdk10
test/jdk/sun/security/tools/keytool/NssTest.java
Java
gpl-2.0
2,505
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ChapterMarker.cs" company="HandBrake Project (http://handbrake.fr)"> // This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License. // </copyright> // <summary> // A Movie Chapter // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace HandBrake.ApplicationServices.Services.Encode.Model.Models { using System; using HandBrake.ApplicationServices.Utilities; /// <summary> /// A Movie Chapter /// </summary> public class ChapterMarker : PropertyChangedBase { /// <summary> /// Backing field for chapter name /// </summary> private string chapterName; /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// </summary> public ChapterMarker() { } /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// </summary> /// <param name="number"> /// The number. /// </param> /// <param name="name"> /// The name. /// </param> /// <param name="duration"> /// The duration. /// </param> public ChapterMarker(int number, string name, TimeSpan duration) { this.ChapterName = name; this.ChapterNumber = number; this.Duration = duration; } /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// Copy Constructor /// </summary> /// <param name="chapter"> /// The chapter. /// </param> public ChapterMarker(ChapterMarker chapter) { this.ChapterName = chapter.ChapterName; this.ChapterNumber = chapter.ChapterNumber; this.Duration = chapter.Duration; } /// <summary> /// Gets or sets The number of this Chapter, in regards to it's parent Title /// </summary> public int ChapterNumber { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> public TimeSpan Duration { get; set; } /// <summary> /// Gets or sets ChapterName. /// </summary> public string ChapterName { get { return this.chapterName; } set { this.chapterName = value; this.NotifyOfPropertyChange(() => this.ChapterName); } } } }
Rodeo314/hb-saintdev
win/CS/HandBrake.ApplicationServices/Services/Encode/Model/Models/ChapterMarker.cs
C#
gpl-2.0
2,905
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "nstencil_half_multi_3d_tri.h" #include "neigh_list.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ NStencilHalfMulti3dTri::NStencilHalfMulti3dTri(LAMMPS *lmp) : NStencil(lmp) {} /* ---------------------------------------------------------------------- */ void NStencilHalfMulti3dTri::set_stencil_properties() { int n = ncollections; int i, j; // Cross collections: use full stencil, looking one way through hierarchy // smaller -> larger => use full stencil in larger bin // larger -> smaller => no nstencil required // If cut offs are same, use half stencil for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if(cutcollectionsq[i][i] > cutcollectionsq[j][j]) continue; flag_skip_multi[i][j] = false; if(cutcollectionsq[i][i] == cutcollectionsq[j][j]){ flag_half_multi[i][j] = true; bin_collection_multi[i][j] = i; } else { flag_half_multi[i][j] = false; bin_collection_multi[i][j] = j; } } } } /* ---------------------------------------------------------------------- create stencils based on bin geometry and cutoff ------------------------------------------------------------------------- */ void NStencilHalfMulti3dTri::create() { int icollection, jcollection, bin_collection, i, j, k, ns; int n = ncollections; double cutsq; for (icollection = 0; icollection < n; icollection++) { for (jcollection = 0; jcollection < n; jcollection++) { if (flag_skip_multi[icollection][jcollection]) { nstencil_multi[icollection][jcollection] = 0; continue; } ns = 0; sx = stencil_sx_multi[icollection][jcollection]; sy = stencil_sy_multi[icollection][jcollection]; sz = stencil_sz_multi[icollection][jcollection]; mbinx = stencil_mbinx_multi[icollection][jcollection]; mbiny = stencil_mbiny_multi[icollection][jcollection]; mbinz = stencil_mbinz_multi[icollection][jcollection]; bin_collection = bin_collection_multi[icollection][jcollection]; cutsq = cutcollectionsq[icollection][jcollection]; if (flag_half_multi[icollection][jcollection]) { for (k = 0; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance_multi(i,j,k,bin_collection) < cutsq) stencil_multi[icollection][jcollection][ns++] = k*mbiny*mbinx + j*mbinx + i; } else { for (k = -sz; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance_multi(i,j,k,bin_collection) < cutsq) stencil_multi[icollection][jcollection][ns++] = k*mbiny*mbinx + j*mbinx + i; } nstencil_multi[icollection][jcollection] = ns; } } }
akohlmey/lammps
src/nstencil_half_multi_3d_tri.cpp
C++
gpl-2.0
3,559
<?php /** * File containing the eZXHTMLXMLOutput class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package kernel */ class eZXHTMLXMLOutput extends eZXMLOutputHandler { public $OutputTags = array( 'section' => array( 'quickRender' => true, 'initHandler' => 'initHandlerSection', 'renderHandler' => 'renderChildrenOnly' ), 'embed' => array( 'initHandler' => 'initHandlerEmbed', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification', 'xhtml:id' => 'id', 'object_id' => false, 'node_id' => false, 'show_path' => false ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'embed-inline' => array( 'initHandler' => 'initHandlerEmbed', 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification', 'xhtml:id' => 'id', 'object_id' => false, 'node_id' => false, 'show_path' => false ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'table' => array( 'initHandler' => 'initHandlerTable', 'leavingHandler' => 'leavingHandlerTable', 'renderHandler' => 'renderAll', 'contentVarName' => 'rows', 'attrNamesTemplate' => array( 'class' => 'classification', 'width' => 'width' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'tr' => array( //'quickRender' => array( 'tr', "\n" ), 'initHandler' => 'initHandlerTr', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'td' => array( 'initHandler' => 'initHandlerTd', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'xhtml:width' => 'width', 'xhtml:colspan' => 'colspan', 'xhtml:rowspan' => 'rowspan', 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'th' => array( 'initHandler' => 'initHandlerTd', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'xhtml:width' => 'width', 'xhtml:colspan' => 'colspan', 'xhtml:rowspan' => 'rowspan', 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'ol' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'ul' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'li' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'header' => array( 'initHandler' => 'initHandlerHeader', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'paragraph' => array( //'quickRender' => array( 'p', "\n" ), 'renderHandler' => 'renderParagraph', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'line' => array( //'quickRender' => array( '', "<br/>" ), 'renderHandler' => 'renderLine' ), 'literal' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'strong' => array( 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'emphasize' => array( 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'link' => array( 'initHandler' => 'initHandlerLink', 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'xhtml:id' => 'id', 'xhtml:title' => 'title', 'url_id' => false, 'object_id' => false, 'node_id' => false, 'show_path' => false, 'ezurl_id' => false, 'anchor_name' => false, 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'anchor' => array( 'renderHandler' => 'renderInline' ), 'custom' => array( 'initHandler' => 'initHandlerCustom', 'renderHandler' => 'renderCustom', 'attrNamesTemplate' => array( 'name' => false ) ), '#text' => array( 'quickRender' => true, 'renderHandler' => 'renderText' ) ); function eZXHTMLXMLOutput( &$xmlData, $aliasedType, $contentObjectAttribute = null ) { $this->eZXMLOutputHandler( $xmlData, $aliasedType, $contentObjectAttribute ); $ini = eZINI::instance('ezxml.ini'); if ( $ini->variable( 'ezxhtml', 'RenderParagraphInTableCells' ) == 'disabled' ) $this->RenderParagraphInTableCells = false; } function initHandlerSection( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); if( !isset( $parentParams['section_level'] ) ) $parentParams['section_level'] = 0; else $parentParams['section_level']++; // init header counter for current level and for the next level if needed $level = $parentParams['section_level']; if ( $level != 0 ) { if ( !isset( $this->HeaderCount[$level] ) ) $this->HeaderCount[$level] = 0; if ( !isset( $this->HeaderCount[$level + 1] ) ) $this->HeaderCount[$level + 1] = 0; } return $ret; } function initHandlerHeader( $element, &$attributes, &$siblingParams, &$parentParams ) { $level = $parentParams['section_level']; $this->HeaderCount[$level]++; // headers auto-numbering $i = 1; $headerAutoName = ''; while ( $i <= $level ) { if ( $i > 1 ) $headerAutoName .= "_"; $headerAutoName .= $this->HeaderCount[$i]; $i++; } $levelNumber = str_replace( "_", ".", $headerAutoName ); if ( $this->ObjectAttributeID ) $headerAutoName = $this->ObjectAttributeID . '_' . $headerAutoName; $ret = array( 'tpl_vars' => array( 'level' => $level, 'header_number' => $levelNumber, 'toc_anchor_name' => $headerAutoName ) ); return $ret; } function initHandlerLink( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); // Set link parameters for rendering children of link tag $href=''; if ( $element->getAttribute( 'url_id' ) != null ) { $linkID = $element->getAttribute( 'url_id' ); if ( isset( $this->LinkArray[$linkID] ) ) $href = $this->LinkArray[$linkID]; } elseif ( $element->getAttribute( 'node_id' ) != null ) { $nodeID = $element->getAttribute( 'node_id' ); $node = isset( $this->NodeArray[$nodeID] ) ? $this->NodeArray[$nodeID] : null; if ( $node != null ) { $view = $element->getAttribute( 'view' ); if ( $view ) $href = 'content/view/' . $view . '/' . $nodeID; else $href = $node->attribute( 'url_alias' ); } else { eZDebug::writeWarning( "Node #$nodeID doesn't exist", "XML output handler: link" ); } } elseif ( $element->getAttribute( 'object_id' ) != null ) { $objectID = $element->getAttribute( 'object_id' ); if ( isset( $this->ObjectArray["$objectID"] ) ) { $object = $this->ObjectArray["$objectID"]; $node = $object->attribute( 'main_node' ); if ( $node ) { $nodeID = $node->attribute( 'node_id' ); $view = $element->getAttribute( 'view' ); if ( $view ) $href = 'content/view/' . $view . '/' . $nodeID; else $href = $node->attribute( 'url_alias' ); } else { eZDebug::writeWarning( "Object #$objectID doesn't have assigned nodes", "XML output handler: link" ); } } else { eZDebug::writeWarning( "Object #$objectID doesn't exist", "XML output handler: link" ); } } elseif ( $element->getAttribute( 'href' ) != null ) { $href = $element->getAttribute( 'href' ); } if ( $element->getAttribute( 'anchor_name' ) != null ) { $href .= '#' . $element->getAttribute( 'anchor_name' ); } if ( $href !== false ) { $attributes['href'] = $href; $parentParams['link_parameters'] = $attributes; } return $ret; } function initHandlerEmbed( $element, &$attributes, &$siblingParams, &$parentParams ) { // default return value in case of errors $ret = array( 'no_render' => true ); $tplSuffix = ''; $objectID = $element->getAttribute( 'object_id' ); if ( $objectID && !empty( $this->ObjectArray["$objectID"] ) ) { $object = $this->ObjectArray["$objectID"]; } else { $nodeID = $element->getAttribute( 'node_id' ); if ( $nodeID ) { if ( isset( $this->NodeArray[$nodeID] ) ) { $node = $this->NodeArray[$nodeID]; $objectID = $node->attribute( 'contentobject_id' ); $object = $node->object(); $tplSuffix = '_node'; } else { eZDebug::writeWarning( "Node #$nodeID doesn't exist", "XML output handler: embed" ); return $ret; } } } if ( !isset( $object ) || !$object || !( $object instanceof eZContentObject ) ) { eZDebug::writeWarning( "Can't fetch object #$objectID", "XML output handler: embed" ); return $ret; } if ( $object->attribute( 'status' ) != eZContentObject::STATUS_PUBLISHED ) { eZDebug::writeWarning( "Object #$objectID is not published", "XML output handler: embed" ); return $ret; } if ( eZINI::instance()->variable( 'SiteAccessSettings', 'ShowHiddenNodes' ) !== 'true' ) { if ( isset( $node ) ) { // embed with a node ID if ( $node->attribute( 'is_invisible' ) ) { eZDebug::writeNotice( "Node #{$nodeID} is invisible", "XML output handler: embed" ); return $ret; } } else { // embed with an object id // checking if at least a location is visible $oneVisible = false; foreach( $object->attribute( 'assigned_nodes' ) as $assignedNode ) { if ( !$assignedNode->attribute( 'is_invisible' ) ) { $oneVisible = true; break; } } if ( !$oneVisible ) { eZDebug::writeNotice( "None of the object #{$objectID}'s location(s) is visible", "XML output handler: embed" ); return $ret; } } } if ( $object->attribute( 'can_read' ) || $object->attribute( 'can_view_embed' ) ) { $templateName = $element->nodeName . $tplSuffix; } else { $templateName = $element->nodeName . '_denied'; } $objectParameters = array(); $excludeAttrs = array( 'view', 'class', 'node_id', 'object_id' ); foreach ( $attributes as $attrName => $value ) { if ( !in_array( $attrName, $excludeAttrs ) ) { if ( strpos( $attrName, ':' ) !== false ) $attrName = substr( $attrName, strpos( $attrName, ':' ) + 1 ); $objectParameters[$attrName] = $value; unset( $attributes[$attrName] ); } } if ( isset( $parentParams['link_parameters'] ) ) $linkParameters = $parentParams['link_parameters']; else $linkParameters = array(); $ret = array( 'template_name' => $templateName, 'tpl_vars' => array( 'object' => $object, 'link_parameters' => $linkParameters, 'object_parameters' => $objectParameters ), 'design_keys' => array( 'class_identifier' => $object->attribute( 'class_identifier' ) ) ); if ( $tplSuffix == '_node') $ret['tpl_vars']['node'] = $node; return $ret; } function initHandlerTable( $element, &$attributes, &$siblingParams, &$parentParams ) { // Backing up the section_level, headings' level should be restarted inside tables. // @see http://issues.ez.no/11536 $this->SectionLevelStack[] = $parentParams['section_level']; $parentParams['section_level'] = 0; // Numbers of rows and cols are lower by 1 for back-compatibility. $rowCount = self::childTagCount( $element ) -1; $lastRow = $element->lastChild; while ( $lastRow && !( $lastRow instanceof DOMElement && $lastRow->nodeName == 'tr' ) ) { $lastRow = $lastRow->previousSibling; } $colCount = self::childTagCount( $lastRow ); if ( $colCount ) $colCount--; $ret = array( 'tpl_vars' => array( 'col_count' => $colCount, 'row_count' => $rowCount ) ); return $ret; } function leavingHandlerTable( $element, &$attributes, &$siblingParams, &$parentParams ) { // Restoring the section_level as it was before entering the table. // @see http://issues.ez.no/11536 $parentParams['section_level'] = array_pop($this->SectionLevelStack); } function initHandlerTr( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); if( !isset( $siblingParams['table_row_count'] ) ) $siblingParams['table_row_count'] = 0; else $siblingParams['table_row_count']++; $parentParams['table_row_count'] = $siblingParams['table_row_count']; // Number of cols is lower by 1 for back-compatibility. $colCount = self::childTagCount( $element ); if ( $colCount ) $colCount--; $ret = array( 'tpl_vars' => array( 'row_count' => $parentParams['table_row_count'], 'col_count' => $colCount ) ); // Allow overrides based on table class $parent = $element->parentNode; if ( $parent instanceof DOMElement && $parent->hasAttribute('class') ) $ret['design_keys'] = array( 'table_classification' => $parent->getAttribute('class') ); return $ret; } function initHandlerTd( $element, &$attributes, &$siblingParams, &$parentParams ) { if( !isset( $siblingParams['table_col_count'] ) ) $siblingParams['table_col_count'] = 0; else $siblingParams['table_col_count']++; $ret = array( 'tpl_vars' => array( 'col_count' => &$siblingParams['table_col_count'], 'row_count' => &$parentParams['table_row_count'] ) ); // Allow overrides based on table class $parent = $element->parentNode->parentNode; if ( $parent instanceof DOMElement && $parent->hasAttribute('class') ) $ret['design_keys'] = array( 'table_classification' => $parent->getAttribute('class') ); if ( !$this->RenderParagraphInTableCells && self::childTagCount( $element ) == 1 ) { // paragraph will not be rendered so its align attribute needs to // be taken into account at the td/th level // Looking for the paragraph with align attribute foreach( $element->childNodes as $c ) { if ( $c instanceof DOMElement ) { if ( $c->hasAttribute( 'align' ) ) { $attributes['align'] = $c->getAttribute( 'align' ); } break ; } } } return $ret; } function initHandlerCustom( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array( 'template_name' => $attributes['name'] ); return $ret; } // Render handlers function renderParagraph( $element, $childrenOutput, $vars ) { // don't render if inside 'li' or inside 'td'/'th' (by option) $parent = $element->parentNode; if ( ( $parent->nodeName == 'li' && self::childTagCount( $parent ) == 1 ) || ( in_array( $parent->nodeName, array( 'td', 'th' ) ) && !$this->RenderParagraphInTableCells && self::childTagCount( $parent ) == 1 ) ) { return $childrenOutput; } // Break paragraph by block tags (like table, ol, ul, header and paragraphs) $tagText = ''; $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key => $childOutput ) { if ( $childOutput[0] === true )// is inline { if( $childOutput[1] === ' ' ) { if ( isset( $childrenOutput[$key+1] ) && $childrenOutput[$key+1][0] === false ) continue; else if ( isset( $childrenOutput[ $key - 1 ] ) && $childrenOutput[ $key - 1 ][0] === false ) continue; } $inlineContent .= $childOutput[1]; } // Only render paragraph if current tag is block and previous was an inline tag // OR if current one is inline and it's the last item in the child list if ( ( $childOutput[0] === false && $lastTagInline === true ) || ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) ) { $tagText .= $this->renderTag( $element, $inlineContent, $vars ); $inlineContent = ''; } if ( $childOutput[0] === false )// is block $tagText .= $childOutput[1]; $lastTagInline = $childOutput[0]; } return array( false, $tagText ); } /* Count child elemnts, ignoring whitespace and text * * @param DOMElement $parent * @return int */ protected static function childTagCount( DOMElement $parent ) { $count = 0; foreach( $parent->childNodes as $child ) { if ( $child instanceof DOMElement ) $count++; } return $count; } function renderInline( $element, $childrenOutput, $vars ) { $renderedArray = array(); $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key=>$childOutput ) { if ( $childOutput[0] === true )// is inline $inlineContent .= $childOutput[1]; // Only render tag if current tag is block and previous was an inline tag // OR if current one is inline and it's the last item in the child list if ( ( $childOutput[0] === false && $lastTagInline === true ) || ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) ) { $tagText = $this->renderTag( $element, $inlineContent, $vars ); $renderedArray[] = array( true, $tagText ); $inlineContent = ''; } if ( $childOutput[0] === false )// is block $renderedArray[] = array( false, $childOutput[1] ); $lastTagInline = $childOutput[0]; } return $renderedArray; } function renderLine( $element, $childrenOutput, $vars ) { $renderedArray = array(); $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key=>$childOutput ) { if ( $childOutput[0] === true )// is inline $inlineContent .= $childOutput[1]; // Render line tag only if the last part of childrenOutput is inline and the next tag // within the same paragraph is 'line' too. if ( $childOutput[0] === false && $lastTagInline === true ) { $renderedArray[] = array( true, $inlineContent ); $inlineContent = ''; } elseif ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) { $next = $element->nextSibling; // Make sure we get next element that is an element (ignoring whitespace) while ( $next && !$next instanceof DOMElement ) { $next = $next->nextSibling; } if ( $next && $next->nodeName == 'line' ) { $tagText = $this->renderTag( $element, $inlineContent, $vars ); $renderedArray[] = array( true, $tagText ); } else $renderedArray[] = array( true, $inlineContent ); } if ( $childOutput[0] === false )// is block $renderedArray[] = array( false, $childOutput[1] ); $lastTagInline = $childOutput[0]; } return $renderedArray; } function renderCustom( $element, $childrenOutput, $vars ) { if ( $this->XMLSchema->isInline( $element ) ) { $ret = $this->renderInline( $element, $childrenOutput, $vars ); } else { $ret = $this->renderAll( $element, $childrenOutput, $vars ); } return $ret; } function renderChildrenOnly( $element, $childrenOutput, $vars ) { $tagText = ''; foreach( $childrenOutput as $childOutput ) { $tagText .= $childOutput[1]; } return array( false, $tagText ); } function renderText( $element, $childrenOutput, $vars ) { if ( $element->parentNode->nodeName != 'literal' ) { if ( trim( $element->textContent ) === '' && ( ( $element->previousSibling && $element->previousSibling->nodeName === 'line' ) || ( $element->nextSibling && $element->nextSibling->nodeName === 'line' ) ) ) { // spaces before or after a line element are irrelevant return array( true, '' ); } $text = htmlspecialchars( $element->textContent ); $text = str_replace( array( '&amp;nbsp;', "\xC2\xA0" ), '&nbsp;', $text); // Get rid of linebreak and spaces stored in xml file $text = str_replace( "\n", '', $text ); if ( $this->AllowMultipleSpaces ) $text = str_replace( ' ', ' &nbsp;', $text ); else $text = preg_replace( "# +#", " ", $text ); if ( $this->AllowNumericEntities ) $text = preg_replace( '/&amp;#([0-9]+);/', '&#\1;', $text ); } else { $text = $element->textContent; } return array( true, $text ); } /// Array of parameters for rendering tags that are children of 'link' tag public $LinkParameters = array(); public $HeaderCount = array(); /** * Stack of section levels saved when entering tables. * @var array */ protected $SectionLevelStack = array(); public $RenderParagraphInTableCells = true; } ?>
guillaumelecerf/ezpublish-legacy
kernel/classes/datatypes/ezxmltext/handlers/output/ezxhtmlxmloutput.php
PHP
gpl-2.0
27,406
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8231598 * @requires os.family == "windows" * @library /test/lib * @summary keytool does not export sun.security.mscapi */ import jdk.test.lib.SecurityTools; public class ProviderClassOption { public static void main(String[] args) throws Throwable { SecurityTools.keytool("-v -storetype Windows-ROOT -list" + " -providerClass sun.security.mscapi.SunMSCAPI") .shouldHaveExitValue(0); } }
md-5/jdk10
test/jdk/sun/security/mscapi/ProviderClassOption.java
Java
gpl-2.0
1,509
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.alarm.filter; import org.opennms.web.filter.NoSubstringFilter; public class NegativeEventParmLikeFilter extends NoSubstringFilter { public static final String TYPE = "noparmmatchany"; public NegativeEventParmLikeFilter(String value) { super(TYPE, "eventParms", "eventParms", value + "(string,text)"); } @Override public String getTextDescription() { String strippedType = getValue().replace("(string,text)", ""); String[] parms = strippedType.split("="); StringBuffer buffer = new StringBuffer(parms[0] + " is not \""); buffer.append(parms[parms.length - 1]); buffer.append("\""); return buffer.toString(); } @Override public String getDescription() { return TYPE + "=" + getValueString().replace("(string,text)", ""); } }
vishwaAbhinav/OpenNMS
opennms-webapp/src/main/java/org/opennms/web/alarm/filter/NegativeEventParmLikeFilter.java
Java
gpl-2.0
2,058
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.3 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2013 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2013 * $Id$ * */ class CRM_Core_I18n_SchemaStructure_3_4_0 { static function &columns() { static $result = NULL; if (!$result) { $result = array( 'civicrm_option_group' => array( 'label' => "varchar(255)", 'description' => "varchar(255)", ), 'civicrm_contact_type' => array( 'label' => "varchar(64)", 'description' => "text", ), 'civicrm_premiums' => array( 'premiums_intro_title' => "varchar(255)", 'premiums_intro_text' => "text", ), 'civicrm_product' => array( 'name' => "varchar(255)", 'description' => "text", 'options' => "text", ), 'civicrm_membership_type' => array( 'name' => "varchar(128)", 'description' => "varchar(255)", ), 'civicrm_membership_status' => array( 'label' => "varchar(128)", ), 'civicrm_participant_status_type' => array( 'label' => "varchar(255)", ), 'civicrm_tell_friend' => array( 'title' => "varchar(255)", 'intro' => "text", 'suggested_message' => "text", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", ), 'civicrm_price_set' => array( 'title' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_batch' => array( 'label' => "varchar(64)", 'description' => "text", ), 'civicrm_custom_group' => array( 'title' => "varchar(64)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_custom_field' => array( 'label' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_dashboard' => array( 'label' => "varchar(255)", ), 'civicrm_option_value' => array( 'label' => "varchar(255)", 'description' => "text", ), 'civicrm_contribution_page' => array( 'title' => "varchar(255)", 'intro_text' => "text", 'pay_later_text' => "text", 'pay_later_receipt' => "text", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", 'thankyou_footer' => "text", 'for_organization' => "text", 'receipt_from_name' => "varchar(255)", 'receipt_text' => "text", 'footer_text' => "text", 'honor_block_title' => "varchar(255)", 'honor_block_text' => "text", ), 'civicrm_membership_block' => array( 'new_title' => "varchar(255)", 'new_text' => "text", 'renewal_title' => "varchar(255)", 'renewal_text' => "text", ), 'civicrm_price_field' => array( 'label' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_price_field_value' => array( 'label' => "varchar(255)", 'description' => "text", ), 'civicrm_uf_group' => array( 'title' => "varchar(64)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_uf_field' => array( 'help_post' => "text", 'help_pre' => "text", 'label' => "varchar(255)", ), 'civicrm_event' => array( 'title' => "varchar(255)", 'summary' => "text", 'description' => "text", 'registration_link_text' => "varchar(255)", 'event_full_text' => "text", 'fee_label' => "varchar(255)", 'intro_text' => "text", 'footer_text' => "text", 'confirm_title' => "varchar(255)", 'confirm_text' => "text", 'confirm_footer_text' => "text", 'confirm_email_text' => "text", 'confirm_from_name' => "varchar(255)", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", 'thankyou_footer_text' => "text", 'pay_later_text' => "text", 'pay_later_receipt' => "text", 'waitlist_text' => "text", 'approval_req_text' => "text", 'template_title' => "varchar(255)", ), ); } return $result; } static function &indices() { static $result = NULL; if (!$result) { $result = array( 'civicrm_price_set' => array( 'UI_title' => array( 'name' => 'UI_title', 'field' => array( 'title', ), 'unique' => 1, ), ), 'civicrm_custom_group' => array( 'UI_title_extends' => array( 'name' => 'UI_title_extends', 'field' => array( 'title', 'extends', ), 'unique' => 1, ), ), 'civicrm_custom_field' => array( 'UI_label_custom_group_id' => array( 'name' => 'UI_label_custom_group_id', 'field' => array( 'label', 'custom_group_id', ), 'unique' => 1, ), ), ); } return $result; } static function &tables() { static $result = NULL; if (!$result) { $result = array_keys(self::columns()); } return $result; } }
tomlagier/NoblePower
wp-content/plugins/civicrm/civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php
PHP
gpl-2.0
7,148
<?php // phpcs:ignoreFile -- compatibility library for PHP 5-7.1 if (class_exists('ParagonIE_Sodium_Core_ChaCha20_IetfCtx', false)) { return; } /** * Class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx */ class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx extends ParagonIE_Sodium_Core32_ChaCha20_Ctx { /** * ParagonIE_Sodium_Core_ChaCha20_IetfCtx constructor. * * @internal You should not use this directly from another application * * @param string $key ChaCha20 key. * @param string $iv Initialization Vector (a.k.a. nonce). * @param string $counter The initial counter value. * Defaults to 4 0x00 bytes. * @throws InvalidArgumentException * @throws SodiumException * @throws TypeError */ public function __construct($key = '', $iv = '', $counter = '') { if (self::strlen($iv) !== 12) { throw new InvalidArgumentException('ChaCha20 expects a 96-bit nonce in IETF mode.'); } parent::__construct($key, self::substr($iv, 0, 8), $counter); if (!empty($counter)) { $this->container[12] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 0, 4)); } $this->container[13] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 0, 4)); $this->container[14] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 4, 4)); $this->container[15] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 8, 4)); } }
tstephen/srp-digital
wp-content/plugins/wordfence/crypto/vendor/paragonie/sodium_compat/src/Core32/ChaCha20/IetfCtx.php
PHP
gpl-2.0
1,562
#ifndef NETWORK_RULES_HPP #define NETWORK_RULES_HPP #include <map> #include "ReactionRule.hpp" #include "generator.hpp" class NetworkRules { public: typedef ReactionRule reaction_rule_type; typedef SpeciesTypeID species_id_type; typedef abstract_limited_generator<reaction_rule_type> reaction_rule_generator; typedef reaction_rule_type::identifier_type identifier_type; public: virtual identifier_type add_reaction_rule(ReactionRule const&) = 0; virtual void remove_reaction_rule(ReactionRule const&) = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1) const = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1, species_id_type const& r2) const = 0; virtual ~NetworkRules() = 0; }; #endif /* NETWORK_RULES_HPP */
navoj/ecell4
ecell4/egfrd/legacy/NetworkRules.hpp
C++
gpl-2.0
821
""" color scheme source data """ schemes = {'classic': [(255, 237, 237), (255, 224, 224), (255, 209, 209), (255, 193, 193), (255, 176, 176), (255, 159, 159), (255, 142, 142), (255, 126, 126), (255, 110, 110), (255, 94, 94), (255, 81, 81), (255, 67, 67), (255, 56, 56), (255, 46, 46), (255, 37, 37), (255, 29, 29), (255, 23, 23), (255, 18, 18), (255, 14, 14), (255, 11, 11), (255, 8, 8), (255, 6, 6), (255, 5, 5), (255, 3, 3), (255, 2, 2), (255, 2, 2), (255, 1, 1), (255, 1, 1), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 1, 0), (255, 4, 0), (255, 6, 0), (255, 10, 0), (255, 14, 0), (255, 18, 0), (255, 22, 0), (255, 26, 0), (255, 31, 0), (255, 36, 0), (255, 41, 0), (255, 45, 0), (255, 51, 0), (255, 57, 0), (255, 62, 0), (255, 68, 0), (255, 74, 0), (255, 81, 0), (255, 86, 0), (255, 93, 0), (255, 99, 0), (255, 105, 0), (255, 111, 0), (255, 118, 0), (255, 124, 0), (255, 131, 0), (255, 137, 0), (255, 144, 0), (255, 150, 0), (255, 156, 0), (255, 163, 0), (255, 169, 0), (255, 175, 0), (255, 181, 0), (255, 187, 0), (255, 192, 0), (255, 198, 0), (255, 203, 0), (255, 208, 0), (255, 213, 0), (255, 218, 0), (255, 222, 0), (255, 227, 0), (255, 232, 0), (255, 235, 0), (255, 238, 0), (255, 242, 0), (255, 245, 0), (255, 247, 0), (255, 250, 0), (255, 251, 0), (253, 252, 0), (250, 252, 1), (248, 252, 2), (244, 252, 2), (241, 252, 3), (237, 252, 3), (233, 252, 3), (229, 252, 4), (225, 252, 4), (220, 252, 5), (216, 252, 5), (211, 252, 6), (206, 252, 7), (201, 252, 7), (197, 252, 8), (191, 251, 8), (185, 249, 9), (180, 247, 9), (174, 246, 10), (169, 244, 11), (164, 242, 11), (158, 240, 12), (151, 238, 13), (146, 236, 14), (140, 233, 14), (134, 231, 15), (128, 228, 16), (122, 226, 17), (116, 223, 18), (110, 221, 19), (105, 218, 20), (99, 216, 21), (93, 214, 22), (88, 211, 23), (82, 209, 24), (76, 207, 25), (71, 204, 26), (66, 202, 28), (60, 200, 30), (55, 198, 31), (50, 196, 33), (45, 194, 34), (40, 191, 35), (36, 190, 37), (31, 188, 39), (27, 187, 40), (23, 185, 43), (19, 184, 44), (15, 183, 46), (12, 182, 48), (9, 181, 51), (6, 181, 53), (3, 180, 55), (1, 180, 57), (0, 180, 60), (0, 180, 62), (0, 180, 65), (0, 181, 68), (0, 182, 70), (0, 182, 74), (0, 183, 77), (0, 184, 80), (0, 184, 84), (0, 186, 88), (0, 187, 92), (0, 188, 95), (0, 190, 99), (0, 191, 104), (0, 193, 108), (0, 194, 112), (0, 196, 116), (0, 198, 120), (0, 200, 125), (0, 201, 129), (0, 203, 134), (0, 205, 138), (0, 207, 143), (0, 209, 147), (0, 211, 151), (0, 213, 156), (0, 215, 160), (0, 216, 165), (0, 219, 171), (0, 222, 178), (0, 224, 184), (0, 227, 190), (0, 229, 197), (0, 231, 203), (0, 233, 209), (0, 234, 214), (0, 234, 220), (0, 234, 225), (0, 234, 230), (0, 234, 234), (0, 234, 238), (0, 234, 242), (0, 234, 246), (0, 234, 248), (0, 234, 251), (0, 234, 254), (0, 234, 255), (0, 232, 255), (0, 228, 255), (0, 224, 255), (0, 219, 255), (0, 214, 254), (0, 208, 252), (0, 202, 250), (0, 195, 247), (0, 188, 244), (0, 180, 240), (0, 173, 236), (0, 164, 232), (0, 156, 228), (0, 147, 222), (0, 139, 218), (0, 130, 213), (0, 122, 208), (0, 117, 205), (0, 112, 203), (0, 107, 199), (0, 99, 196), (0, 93, 193), (0, 86, 189), (0, 78, 184), (0, 71, 180), (0, 65, 175), (0, 58, 171), (0, 52, 167), (0, 46, 162), (0, 40, 157), (0, 35, 152), (0, 30, 147), (0, 26, 142), (0, 22, 136), (0, 18, 131), (0, 15, 126), (0, 12, 120), (0, 9, 115), (1, 8, 110), (1, 6, 106), (1, 5, 101), (2, 4, 97), (3, 4, 92), (4, 5, 89), (5, 5, 85), (6, 6, 82), (7, 7, 79), (8, 8, 77), (10, 10, 77), (12, 12, 77), (14, 14, 76), (16, 16, 74), (19, 19, 73), (21, 21, 72), (24, 24, 71), (26, 26, 69), (29, 29, 70), (32, 32, 69), (35, 35, 68), (37, 37, 67), (40, 40, 67), (42, 42, 65), (44, 44, 65), (46, 46, 64), (48, 48, 63), (49, 50, 62), (51, 51, 61), (53, 52, 61)], 'fire': [(255, 255, 255), (255, 255, 253), (255, 255, 250), (255, 255, 247), (255, 255, 244), (255, 255, 241), (255, 255, 238), (255, 255, 234), (255, 255, 231), (255, 255, 227), (255, 255, 223), (255, 255, 219), (255, 255, 214), (255, 255, 211), (255, 255, 206), (255, 255, 202), (255, 255, 197), (255, 255, 192), (255, 255, 187), (255, 255, 183), (255, 255, 178), (255, 255, 172), (255, 255, 167), (255, 255, 163), (255, 255, 157), (255, 255, 152), (255, 255, 147), (255, 255, 142), (255, 255, 136), (255, 255, 132), (255, 255, 126), (255, 255, 121), (255, 255, 116), (255, 255, 111), (255, 255, 106), (255, 255, 102), (255, 255, 97), (255, 255, 91), (255, 255, 87), (255, 255, 82), (255, 255, 78), (255, 255, 74), (255, 255, 70), (255, 255, 65), (255, 255, 61), (255, 255, 57), (255, 255, 53), (255, 255, 50), (255, 255, 46), (255, 255, 43), (255, 255, 39), (255, 255, 38), (255, 255, 34), (255, 255, 31), (255, 255, 29), (255, 255, 26), (255, 255, 25), (255, 254, 23), (255, 251, 22), (255, 250, 22), (255, 247, 23), (255, 245, 23), (255, 242, 24), (255, 239, 24), (255, 236, 25), (255, 232, 25), (255, 229, 26), (255, 226, 26), (255, 222, 27), (255, 218, 27), (255, 215, 28), (255, 210, 28), (255, 207, 29), (255, 203, 29), (255, 199, 30), (255, 194, 30), (255, 190, 31), (255, 186, 31), (255, 182, 32), (255, 176, 32), (255, 172, 33), (255, 168, 34), (255, 163, 34), (255, 159, 35), (255, 154, 35), (255, 150, 36), (255, 145, 36), (255, 141, 37), (255, 136, 37), (255, 132, 38), (255, 128, 39), (255, 124, 39), (255, 119, 40), (255, 115, 40), (255, 111, 41), (255, 107, 41), (255, 103, 42), (255, 99, 42), (255, 95, 43), (255, 92, 44), (255, 89, 44), (255, 85, 45), (255, 81, 45), (255, 79, 46), (255, 76, 47), (255, 72, 47), (255, 70, 48), (255, 67, 48), (255, 65, 49), (255, 63, 50), (255, 60, 50), (255, 59, 51), (255, 57, 51), (255, 55, 52), (255, 55, 53), (255, 53, 53), (253, 54, 54), (253, 54, 54), (251, 55, 55), (250, 56, 56), (248, 56, 56), (247, 57, 57), (246, 57, 57), (244, 58, 58), (242, 59, 59), (240, 59, 59), (239, 60, 60), (238, 61, 61), (235, 61, 61), (234, 62, 62), (232, 62, 62), (229, 63, 63), (228, 64, 64), (226, 64, 64), (224, 65, 65), (222, 66, 66), (219, 66, 66), (218, 67, 67), (216, 67, 67), (213, 68, 68), (211, 69, 69), (209, 69, 69), (207, 70, 70), (205, 71, 71), (203, 71, 71), (200, 72, 72), (199, 73, 73), (196, 73, 73), (194, 74, 74), (192, 74, 74), (190, 75, 75), (188, 76, 76), (186, 76, 76), (183, 77, 77), (181, 78, 78), (179, 78, 78), (177, 79, 79), (175, 80, 80), (173, 80, 80), (170, 81, 81), (169, 82, 82), (166, 82, 82), (165, 83, 83), (162, 83, 83), (160, 84, 84), (158, 85, 85), (156, 85, 85), (154, 86, 86), (153, 87, 87), (150, 87, 87), (149, 88, 88), (147, 89, 89), (146, 90, 90), (144, 91, 91), (142, 92, 92), (142, 94, 94), (141, 95, 95), (140, 96, 96), (139, 98, 98), (138, 99, 99), (136, 100, 100), (135, 101, 101), (135, 103, 103), (134, 104, 104), (133, 105, 105), (133, 107, 107), (132, 108, 108), (131, 109, 109), (132, 111, 111), (131, 112, 112), (130, 113, 113), (130, 114, 114), (130, 116, 116), (130, 117, 117), (130, 118, 118), (129, 119, 119), (130, 121, 121), (130, 122, 122), (130, 123, 123), (130, 124, 124), (131, 126, 126), (131, 127, 127), (130, 128, 128), (131, 129, 129), (132, 131, 131), (132, 132, 132), (133, 133, 133), (134, 134, 134), (135, 135, 135), (136, 136, 136), (138, 138, 138), (139, 139, 139), (140, 140, 140), (141, 141, 141), (142, 142, 142), (143, 143, 143), (144, 144, 144), (145, 145, 145), (147, 147, 147), (148, 148, 148), (149, 149, 149), (150, 150, 150), (151, 151, 151), (152, 152, 152), (153, 153, 153), (154, 154, 154), (155, 155, 155), (156, 156, 156), (157, 157, 157), (158, 158, 158), (159, 159, 159), (160, 160, 160), (160, 160, 160), (161, 161, 161), (162, 162, 162), (163, 163, 163), (164, 164, 164), (165, 165, 165), (166, 166, 166), (167, 167, 167), (167, 167, 167), (168, 168, 168), (169, 169, 169), (170, 170, 170), (170, 170, 170), (171, 171, 171), (172, 172, 172), (173, 173, 173), (173, 173, 173), (174, 174, 174), (175, 175, 175), (175, 175, 175), (176, 176, 176), (176, 176, 176), (177, 177, 177), (177, 177, 177)], 'omg': [(255, 255, 255), (255, 254, 254), (255, 253, 253), (255, 251, 251), (255, 250, 250), (255, 249, 249), (255, 247, 247), (255, 246, 246), (255, 244, 244), (255, 242, 242), (255, 241, 241), (255, 239, 239), (255, 237, 237), (255, 235, 235), (255, 233, 233), (255, 231, 231), (255, 229, 229), (255, 227, 227), (255, 226, 226), (255, 224, 224), (255, 222, 222), (255, 220, 220), (255, 217, 217), (255, 215, 215), (255, 213, 213), (255, 210, 210), (255, 208, 208), (255, 206, 206), (255, 204, 204), (255, 202, 202), (255, 199, 199), (255, 197, 197), (255, 194, 194), (255, 192, 192), (255, 189, 189), (255, 188, 188), (255, 185, 185), (255, 183, 183), (255, 180, 180), (255, 178, 178), (255, 176, 176), (255, 173, 173), (255, 171, 171), (255, 169, 169), (255, 167, 167), (255, 164, 164), (255, 162, 162), (255, 160, 160), (255, 158, 158), (255, 155, 155), (255, 153, 153), (255, 151, 151), (255, 149, 149), (255, 147, 147), (255, 145, 145), (255, 143, 143), (255, 141, 141), (255, 139, 139), (255, 137, 137), (255, 136, 136), (255, 134, 134), (255, 132, 132), (255, 131, 131), (255, 129, 129), (255, 128, 128), (255, 127, 127), (255, 127, 127), (255, 126, 126), (255, 125, 125), (255, 125, 125), (255, 124, 124), (255, 123, 122), (255, 123, 122), (255, 122, 121), (255, 122, 121), (255, 121, 120), (255, 120, 119), (255, 119, 118), (255, 119, 118), (255, 118, 116), (255, 117, 116), (255, 117, 115), (255, 115, 114), (255, 115, 114), (255, 114, 113), (255, 114, 112), (255, 113, 111), (255, 113, 111), (255, 112, 110), (255, 111, 108), (255, 111, 108), (255, 110, 107), (255, 110, 107), (255, 109, 105), (255, 109, 105), (255, 108, 104), (255, 107, 104), (255, 107, 102), (255, 106, 102), (255, 106, 101), (255, 105, 101), (255, 104, 99), (255, 104, 99), (255, 103, 98), (255, 103, 98), (255, 102, 97), (255, 102, 96), (255, 101, 96), (255, 101, 96), (255, 100, 94), (255, 100, 94), (255, 99, 93), (255, 99, 92), (255, 98, 91), (255, 98, 91), (255, 97, 90), (255, 97, 89), (255, 96, 89), (255, 96, 89), (255, 95, 88), (255, 95, 88), (255, 94, 86), (255, 93, 86), (255, 93, 85), (255, 93, 85), (255, 92, 85), (255, 92, 84), (255, 91, 83), (255, 91, 83), (255, 90, 82), (255, 90, 82), (255, 89, 81), (255, 89, 82), (255, 89, 80), (255, 89, 80), (255, 89, 79), (255, 89, 79), (255, 88, 79), (255, 88, 79), (255, 87, 78), (255, 87, 78), (255, 87, 78), (255, 87, 77), (255, 87, 77), (255, 86, 77), (255, 86, 77), (255, 85, 76), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 85, 75), (255, 84, 75), (255, 84, 75), (255, 83, 74), (255, 83, 75), (255, 83, 75), (255, 84, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 77), (255, 84, 78), (255, 83, 78), (255, 84, 79), (255, 84, 78), (255, 84, 79), (255, 83, 79), (255, 84, 80), (255, 83, 80), (255, 84, 81), (255, 85, 82), (255, 85, 82), (255, 85, 83), (255, 85, 83), (255, 85, 84), (255, 85, 84), (255, 86, 85), (255, 86, 85), (255, 87, 87), (254, 89, 89), (254, 91, 92), (253, 92, 93), (252, 94, 96), (251, 96, 98), (251, 97, 100), (249, 99, 103), (249, 100, 105), (248, 102, 108), (247, 104, 111), (246, 105, 113), (245, 107, 116), (244, 109, 119), (243, 110, 122), (242, 112, 125), (241, 113, 127), (240, 115, 130), (239, 117, 134), (238, 118, 136), (237, 120, 140), (236, 121, 142), (235, 123, 145), (234, 124, 148), (233, 126, 151), (232, 127, 154), (232, 129, 157), (230, 130, 159), (230, 132, 162), (229, 133, 165), (228, 135, 168), (227, 136, 170), (227, 138, 173), (226, 139, 176), (225, 140, 178), (224, 142, 181), (223, 143, 183), (223, 144, 185), (223, 146, 188), (222, 147, 190), (221, 148, 192), (221, 150, 195), (220, 151, 197), (219, 152, 199), (219, 153, 201), (219, 154, 202), (219, 156, 205), (218, 157, 207), (217, 158, 208), (217, 159, 210), (217, 160, 211), (217, 161, 213), (216, 162, 214), (216, 163, 216), (216, 164, 217), (215, 165, 218), (216, 166, 219), (215, 166, 220), (215, 167, 222), (215, 168, 223), (215, 169, 223), (215, 170, 224), (215, 170, 225)], 'pbj': [(41, 10, 89), (41, 10, 89), (42, 10, 89), (42, 10, 89), (42, 10, 88), (43, 10, 88), (43, 9, 88), (43, 9, 88), (44, 9, 88), (44, 9, 88), (45, 10, 89), (46, 10, 88), (46, 9, 88), (47, 9, 88), (47, 9, 88), (47, 9, 88), (48, 8, 88), (48, 8, 87), (49, 8, 87), (49, 8, 87), (49, 7, 87), (50, 7, 87), (50, 7, 87), (51, 7, 86), (51, 6, 86), (53, 7, 86), (53, 7, 86), (54, 7, 86), (54, 6, 85), (55, 6, 85), (55, 6, 85), (56, 5, 85), (56, 5, 85), (57, 5, 84), (57, 5, 84), (58, 4, 84), (59, 4, 84), (59, 5, 84), (60, 4, 84), (60, 4, 84), (61, 4, 84), (61, 4, 83), (62, 3, 83), (63, 3, 83), (63, 3, 83), (64, 3, 82), (64, 3, 82), (65, 3, 82), (66, 3, 82), (67, 4, 82), (68, 4, 82), (69, 4, 82), (69, 4, 81), (70, 4, 81), (71, 4, 81), (71, 4, 80), (72, 4, 80), (73, 4, 80), (73, 4, 79), (75, 5, 80), (76, 5, 80), (77, 5, 79), (77, 5, 79), (78, 5, 79), (79, 5, 78), (80, 5, 78), (80, 5, 78), (80, 5, 77), (81, 5, 77), (83, 6, 76), (83, 6, 76), (84, 6, 76), (85, 6, 75), (86, 6, 75), (87, 6, 74), (88, 6, 74), (88, 6, 73), (89, 6, 73), (91, 7, 73), (92, 7, 73), (93, 7, 72), (94, 7, 72), (94, 7, 71), (95, 7, 71), (96, 7, 70), (96, 7, 70), (97, 7, 69), (99, 9, 70), (100, 9, 69), (101, 10, 69), (102, 10, 68), (103, 11, 67), (104, 11, 67), (105, 12, 66), (106, 13, 66), (107, 14, 66), (108, 15, 65), (109, 16, 64), (110, 16, 64), (111, 17, 63), (112, 18, 62), (113, 18, 61), (114, 19, 61), (115, 20, 60), (118, 22, 60), (119, 22, 59), (120, 22, 58), (120, 23, 58), (121, 24, 57), (122, 25, 56), (124, 26, 55), (125, 27, 54), (127, 29, 54), (128, 30, 54), (130, 31, 53), (131, 32, 52), (132, 33, 51), (133, 34, 50), (134, 35, 49), (135, 36, 48), (137, 38, 48), (138, 39, 47), (140, 40, 46), (141, 41, 46), (142, 42, 45), (143, 42, 44), (144, 43, 43), (145, 44, 42), (146, 45, 42), (149, 47, 41), (150, 48, 41), (151, 49, 40), (152, 50, 39), (153, 51, 38), (154, 52, 38), (155, 53, 37), (157, 55, 36), (159, 57, 36), (160, 57, 35), (160, 58, 34), (162, 59, 33), (163, 60, 33), (164, 61, 32), (165, 62, 31), (167, 63, 30), (168, 65, 30), (169, 66, 29), (170, 67, 29), (172, 68, 28), (173, 69, 27), (174, 70, 26), (175, 71, 26), (176, 71, 25), (178, 73, 25), (179, 74, 24), (180, 75, 24), (181, 76, 23), (182, 77, 23), (183, 78, 23), (184, 79, 22), (186, 80, 22), (187, 81, 21), (188, 82, 21), (189, 83, 21), (190, 83, 20), (191, 84, 20), (192, 85, 19), (192, 86, 19), (193, 87, 18), (194, 87, 18), (196, 89, 18), (196, 90, 18), (197, 90, 18), (198, 90, 18), (199, 91, 18), (200, 92, 18), (201, 93, 18), (202, 93, 18), (203, 94, 18), (204, 96, 19), (204, 96, 19), (205, 97, 19), (206, 98, 19), (207, 99, 19), (208, 99, 19), (209, 100, 19), (210, 100, 19), (211, 100, 19), (212, 102, 20), (213, 103, 20), (214, 103, 20), (214, 104, 20), (215, 105, 20), (215, 105, 20), (216, 106, 20), (217, 107, 20), (218, 107, 20), (219, 108, 20), (220, 109, 21), (221, 109, 21), (222, 110, 21), (222, 111, 21), (223, 111, 21), (224, 112, 21), (225, 113, 21), (226, 113, 21), (227, 114, 21), (227, 114, 21), (228, 115, 22), (229, 116, 22), (229, 116, 22), (230, 117, 22), (231, 117, 22), (231, 118, 22), (232, 119, 22), (233, 119, 22), (234, 120, 22), (234, 120, 22), (235, 121, 22), (236, 121, 22), (237, 122, 23), (237, 122, 23), (238, 123, 23), (239, 124, 23), (239, 124, 23), (240, 125, 23), (240, 125, 23), (241, 126, 23), (241, 126, 23), (242, 127, 23), (243, 127, 23), (243, 128, 23), (244, 128, 24), (244, 128, 24), (245, 129, 24), (246, 129, 24), (246, 130, 24), (247, 130, 24), (247, 131, 24), (248, 131, 24), (249, 131, 24), (249, 132, 24), (250, 132, 24), (250, 133, 24), (250, 133, 24), (250, 133, 24), (251, 134, 24), (251, 134, 25), (252, 135, 25), (252, 135, 25), (253, 135, 25), (253, 136, 25), (253, 136, 25), (254, 136, 25), (254, 136, 25), (255, 137, 25)], 'pgaitch': [(255, 254, 165), (255, 254, 164), (255, 253, 163), (255, 253, 162), (255, 253, 161), (255, 252, 160), (255, 252, 159), (255, 252, 157), (255, 251, 156), (255, 251, 155), (255, 251, 153), (255, 250, 152), (255, 250, 150), (255, 250, 149), (255, 249, 148), (255, 249, 146), (255, 249, 145), (255, 248, 143), (255, 248, 141), (255, 248, 139), (255, 247, 138), (255, 247, 136), (255, 246, 134), (255, 246, 132), (255, 246, 130), (255, 245, 129), (255, 245, 127), (255, 245, 125), (255, 244, 123), (255, 244, 121), (255, 243, 119), (255, 243, 117), (255, 242, 114), (255, 242, 112), (255, 241, 111), (255, 241, 109), (255, 240, 107), (255, 240, 105), (255, 239, 102), (255, 239, 100), (255, 238, 99), (255, 238, 97), (255, 237, 95), (255, 237, 92), (255, 236, 90), (255, 237, 89), (255, 236, 87), (255, 235, 84), (255, 235, 82), (255, 234, 80), (255, 233, 79), (255, 233, 77), (255, 232, 74), (255, 231, 72), (255, 230, 70), (255, 230, 69), (255, 229, 67), (255, 228, 65), (255, 227, 63), (255, 226, 61), (255, 225, 60), (255, 225, 58), (255, 224, 56), (255, 223, 54), (255, 222, 52), (255, 222, 51), (255, 221, 49), (255, 220, 47), (255, 219, 46), (255, 218, 44), (255, 216, 43), (255, 215, 42), (255, 214, 41), (255, 213, 39), (255, 212, 39), (255, 211, 37), (255, 209, 36), (255, 208, 34), (255, 208, 33), (255, 206, 33), (255, 205, 32), (255, 204, 30), (255, 202, 29), (255, 201, 29), (255, 199, 28), (254, 199, 28), (254, 199, 27), (253, 198, 27), (252, 197, 27), (251, 196, 27), (250, 195, 26), (249, 195, 26), (248, 194, 26), (248, 193, 26), (247, 192, 26), (246, 192, 25), (245, 191, 26), (244, 190, 26), (243, 189, 25), (241, 188, 25), (240, 187, 25), (239, 187, 25), (238, 186, 25), (236, 185, 25), (236, 184, 26), (235, 183, 26), (233, 182, 25), (232, 181, 25), (230, 181, 26), (229, 180, 26), (228, 179, 25), (227, 178, 25), (226, 177, 26), (224, 176, 26), (222, 176, 25), (221, 175, 25), (220, 173, 26), (219, 172, 26), (217, 171, 25), (215, 170, 25), (214, 170, 26), (212, 169, 26), (211, 167, 25), (209, 166, 25), (208, 166, 26), (206, 165, 26), (204, 163, 26), (203, 162, 26), (202, 161, 25), (200, 161, 26), (198, 159, 26), (197, 158, 26), (195, 157, 26), (193, 157, 27), (192, 155, 27), (190, 154, 27), (189, 153, 27), (187, 152, 28), (186, 151, 28), (184, 150, 28), (182, 149, 28), (181, 148, 29), (179, 147, 29), (177, 146, 29), (175, 144, 29), (174, 144, 30), (172, 142, 30), (170, 141, 30), (169, 140, 30), (167, 139, 31), (165, 138, 31), (164, 137, 31), (162, 136, 31), (161, 135, 32), (159, 134, 32), (157, 133, 32), (154, 132, 32), (153, 131, 33), (151, 130, 33), (150, 129, 33), (148, 127, 33), (147, 127, 34), (145, 126, 34), (143, 124, 34), (141, 123, 34), (140, 122, 35), (139, 121, 35), (137, 120, 35), (135, 119, 35), (134, 118, 36), (132, 117, 36), (130, 116, 36), (129, 115, 36), (127, 113, 36), (126, 113, 37), (124, 112, 37), (122, 111, 37), (121, 110, 37), (120, 109, 38), (118, 108, 38), (116, 107, 38), (115, 105, 38), (113, 104, 38), (112, 104, 39), (110, 103, 39), (108, 102, 39), (107, 101, 39), (106, 100, 40), (104, 99, 40), (102, 98, 40), (101, 96, 40), (99, 96, 40), (99, 96, 41), (97, 94, 41), (96, 93, 41), (94, 92, 41), (92, 91, 41), (92, 90, 42), (90, 90, 42), (89, 89, 42), (87, 87, 42), (86, 86, 42), (85, 86, 43), (84, 85, 43), (83, 84, 43), (81, 83, 43), (80, 82, 43), (80, 82, 44), (78, 80, 44), (77, 80, 44), (75, 79, 44), (75, 78, 44), (74, 78, 45), (73, 76, 45), (71, 75, 45), (71, 75, 45), (70, 74, 45), (69, 74, 46), (68, 73, 46), (67, 72, 46), (66, 71, 46), (65, 71, 46), (64, 69, 46), (64, 69, 47), (63, 68, 47), (62, 67, 47), (61, 67, 47), (60, 66, 47), (59, 65, 47), (59, 65, 48), (59, 64, 48), (58, 63, 48), (57, 63, 48), (56, 62, 48), (56, 62, 48), (55, 61, 48), (55, 61, 49), (55, 60, 49), (55, 60, 49), (54, 59, 49), (53, 58, 49), (53, 57, 49), (52, 57, 49), (52, 57, 50), (52, 56, 50), (52, 56, 50), (52, 56, 50), (52, 55, 50), (51, 54, 50), (51, 53, 50), (51, 53, 50), (51, 52, 50), (51, 53, 51), (51, 53, 51), (51, 52, 51), (51, 52, 51)]} def valid_schemes(): return schemes.keys()
ashmastaflash/IDCOAS
integration/heatmaps/heatmap/colorschemes.py
Python
gpl-2.0
33,688
<?php /** * File containing the ezpOauthBadRequestException class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package kernel */ /** * This is the base exception for triggering BAD REQUEST response. * * @package oauth */ abstract class ezpOauthBadRequestException extends ezpOauthException { public function __construct( $message ) { parent::__construct( $message ); } } ?>
CG77/ezpublish-legacy
kernel/private/rest/classes/exceptions/bad_request.php
PHP
gpl-2.0
558
class Organization::Public::Piece::AllGroupsController < Sys::Controller::Public::Base def pre_dispatch @piece = Organization::Piece::AllGroup.where(id: Page.current_piece.id).first render :text => '' unless @piece @item = Page.current_item end def index sys_group_codes = @piece.content.root_sys_group.children.pluck(:code) @groups = @piece.content.groups.public.where(sys_group_code: sys_group_codes) end end
tao-k/zomeki
app/controllers/organization/public/piece/all_groups_controller.rb
Ruby
gpl-3.0
441
package org.ovirt.engine.ui.uicommonweb.models.templates; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.uicommonweb.builders.BuilderExecutor; import org.ovirt.engine.ui.uicommonweb.builders.vm.CommentVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.CommonVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.CoreVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.HwOnlyVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.KernelParamsVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.NameAndDescriptionVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.SerialNumberPolicyVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.ExistingNonClusterModelBehavior; public class ExistingBlankTemplateModelBehavior extends ExistingNonClusterModelBehavior { private VmTemplate template; public ExistingBlankTemplateModelBehavior(VmTemplate template) { super(template); this.template = template; } @Override protected void postBuild() { getModel().getBaseTemplate().setIsAvailable(false); getModel().getTemplateVersionName().setIsAvailable(false); getModel().getVmType().setIsChangeable(true); getModel().getEmulatedMachine().setIsAvailable(false); getModel().getCustomCpu().setIsAvailable(false); getModel().getOSType().setIsAvailable(false); updateCustomPropertySheet(latestCluster()); getModel().getCustomPropertySheet().deserialize(template.getCustomProperties()); updateTimeZone(template.getTimeZone()); getModel().getVmInitEnabled().setEntity(template.getVmInit() != null); getModel().getVmInitModel().init(template); } @Override protected Version getClusterCompatibilityVersion() { return latestCluster(); } @Override protected void buildModel(VmBase vmBase, BuilderExecutor.BuilderExecutionFinished<VmBase, UnitVmModel> callback) { new BuilderExecutor<>(callback, new NameAndDescriptionVmBaseToUnitBuilder(), new CommentVmBaseToUnitBuilder(), new CommonVmBaseToUnitBuilder( new HwOnlyVmBaseToUnitBuilder().withEveryFeatureSupported(), new CoreVmBaseToUnitBuilder( new KernelParamsVmBaseToUnitBuilder(), new SerialNumberPolicyVmBaseToUnitBuilder().withEveryFeatureSupported() ).withEveryFeatureSupported())) .build(vmBase, getModel()); } public VmTemplate getVmTemplate() { return template; } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/templates/ExistingBlankTemplateModelBehavior.java
Java
gpl-3.0
2,954
using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design; using Microsoft.Win32; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Reflection; using System.IO; using dnlib.DotNet; namespace ICSharpCode.ILSpy.AddIn { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] // This attribute is used to register the information needed to show this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(GuidList.guidILSpyAddInPkgString)] [ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_string)] public sealed class ILSpyAddInPackage : Package { /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public ILSpyAddInPackage() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); } ///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenReferenceInILSpy); MenuCommand menuItem = new MenuCommand(OpenReferenceInILSpyCallback, menuCommandID); mcs.AddCommand(menuItem); // Create the command for the menu item. CommandID menuCommandID2 = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenProjectOutputInILSpy); MenuCommand menuItem2 = new MenuCommand(OpenProjectOutputInILSpyCallback, menuCommandID2); mcs.AddCommand(menuItem2); // Create the command for the menu item. CommandID menuCommandID3 = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenILSpy); MenuCommand menuItem3 = new MenuCommand(OpenILSpyCallback, menuCommandID3); mcs.AddCommand(menuItem3); } } #endregion /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void OpenReferenceInILSpyCallback(object sender, EventArgs e) { var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer; var items =(object[]) explorer.SelectedItems; foreach (EnvDTE.UIHierarchyItem item in items) { dynamic reference = item.Object; string path = null; if (reference.PublicKeyToken != "") { var token = Utils.HexStringToBytes(reference.PublicKeyToken); path = GacInterop.FindAssemblyInNetGac(new AssemblyNameInfo() { Name = reference.Identity, Version = new Version(reference.Version), PublicKeyOrToken = new PublicKeyToken(token), Culture = string.Empty }); } if (path == null) path = reference.Path; OpenAssemblyInILSpy(path); } } private void OpenProjectOutputInILSpyCallback(object sender, EventArgs e) { var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer; var items = (object[])explorer.SelectedItems; foreach (EnvDTE.UIHierarchyItem item in items) { EnvDTE.Project project = (EnvDTE.Project)item.Object; EnvDTE.Configuration config = project.ConfigurationManager.ActiveConfiguration; string projectPath = Path.GetDirectoryName(project.FileName); string outputPath = config.Properties.Item("OutputPath").Value.ToString(); string assemblyFileName = project.Properties.Item("OutputFileName").Value.ToString(); OpenAssemblyInILSpy(Path.Combine(projectPath, outputPath, assemblyFileName)); } } private void OpenILSpyCallback(object sender, EventArgs e) { Process.Start(GetILSpyPath()); } private string GetILSpyPath() { var basePath = Path.GetDirectoryName(typeof(ILSpyAddInPackage).Assembly.Location); return Path.Combine(basePath, "dnSpy.exe"); } private void OpenAssemblyInILSpy(string assemblyFileName) { if (!File.Exists(assemblyFileName)) { ShowMessage("Could not find assembly '{0}', please ensure the project and all references were built correctly!", assemblyFileName); return; } Process.Start(GetILSpyPath(), Utils.ArgumentArrayToCommandLine(assemblyFileName)); } private void ShowMessage(string format, params object[] items) { IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); Guid clsid = Guid.Empty; int result; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( uiShell.ShowMessageBox( 0, ref clsid, "ILSpy.AddIn", string.Format(CultureInfo.CurrentCulture, format, items), string.Empty, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, 0, // false out result ) ); } } }
UlyssesWu/dnSpy
ILSpy.AddIn/ILSpyAddInPackage.cs
C#
gpl-3.0
6,884
package fr.xephi.authme.data.limbo.persistence; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.EIGHT; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.FOUR; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.ONE; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.SIXTEEN; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.SIXTY_FOUR; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.THIRTY_TWO; import static fr.xephi.authme.data.limbo.persistence.SegmentSize.TWO_FIFTY; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; /** * Test for {@link SegmentNameBuilder}. */ public class SegmentNameBuilderTest { /** * Checks that using a given segment size really produces as many segments as defined. * E.g. if we partition with {@link SegmentSize#EIGHT} we expect eight different buckets. */ @Test public void shouldCreatePromisedSizeOfSegments() { for (SegmentSize part : SegmentSize.values()) { // Perform this check only for `length` <= 5 because the test creates all hex numbers with `length` digits. if (part.getLength() <= 5) { checkTotalSegmentsProduced(part); } } } private void checkTotalSegmentsProduced(SegmentSize part) { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(part); Set<String> encounteredSegments = new HashSet<>(); int shift = part.getLength() * 4; // e.g. (1 << 16) - 1 = 0xFFFF. (Number of digits = shift/4, since 16 = 2^4) int max = (1 << shift) - 1; // when for (int i = 0; i <= max; ++i) { String uuid = toPaddedHex(i, part.getLength()); encounteredSegments.add(nameBuilder.createSegmentName(uuid)); } // then assertThat(encounteredSegments, hasSize(part.getTotalSegments())); } private static String toPaddedHex(int dec, int padLength) { String hexResult = Integer.toString(dec, 16); while (hexResult.length() < padLength) { hexResult = "0" + hexResult; } return hexResult; } @Test public void shouldCreateOneSegment() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(ONE); // when / then assertThat(nameBuilder.createSegmentName("abc"), equalTo("seg1-0")); assertThat(nameBuilder.createSegmentName("f0e"), equalTo("seg1-0")); assertThat(nameBuilder.createSegmentName("329"), equalTo("seg1-0")); } @Test public void shouldCreateFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(FOUR); // when / then assertThat(nameBuilder.createSegmentName("f9cc"), equalTo("seg4-3")); assertThat(nameBuilder.createSegmentName("84c9"), equalTo("seg4-2")); assertThat(nameBuilder.createSegmentName("3799"), equalTo("seg4-0")); } @Test public void shouldCreateEightSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(EIGHT); // when / then assertThat(nameBuilder.createSegmentName("fc9c"), equalTo("seg8-7")); assertThat(nameBuilder.createSegmentName("90ad"), equalTo("seg8-4")); assertThat(nameBuilder.createSegmentName("35e4"), equalTo("seg8-1")); assertThat(nameBuilder.createSegmentName("a39f"), equalTo("seg8-5")); } @Test public void shouldCreateSixteenSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTEEN); // when / then assertThat(nameBuilder.createSegmentName("fc9a054"), equalTo("seg16-f")); assertThat(nameBuilder.createSegmentName("b0a945e"), equalTo("seg16-b")); assertThat(nameBuilder.createSegmentName("7afebab"), equalTo("seg16-7")); } @Test public void shouldCreateThirtyTwoSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(THIRTY_TWO); // when / then assertThat(nameBuilder.createSegmentName("f890c9"), equalTo("seg32-11101")); assertThat(nameBuilder.createSegmentName("49c39a"), equalTo("seg32-01101")); assertThat(nameBuilder.createSegmentName("b75d09"), equalTo("seg32-10010")); } @Test public void shouldCreateSixtyFourSegments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(SIXTY_FOUR); // when / then assertThat(nameBuilder.createSegmentName("82f"), equalTo("seg64-203")); assertThat(nameBuilder.createSegmentName("9b4"), equalTo("seg64-221")); assertThat(nameBuilder.createSegmentName("068"), equalTo("seg64-012")); } @Test public void shouldCreate256Segments() { // given SegmentNameBuilder nameBuilder = new SegmentNameBuilder(TWO_FIFTY); // when / then assertThat(nameBuilder.createSegmentName("a813c"), equalTo("seg256-a8")); assertThat(nameBuilder.createSegmentName("b4d01"), equalTo("seg256-b4")); assertThat(nameBuilder.createSegmentName("7122f"), equalTo("seg256-71")); } }
Xephi/AuthMeReloaded
src/test/java/fr/xephi/authme/data/limbo/persistence/SegmentNameBuilderTest.java
Java
gpl-3.0
5,364
/* * Copyright (C) 2015 The Android Open Source Project * * 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. */ package android.os.storage; import android.os.Parcel; import android.os.Parcelable; import android.util.DebugUtils; import android.util.TimeUtils; import com.android.internal.util.IndentingPrintWriter; import com.android.internal.util.Preconditions; import java.util.Objects; /** * Metadata for a storage volume which may not be currently present. * * @hide */ public class VolumeRecord implements Parcelable { public static final String EXTRA_FS_UUID = "android.os.storage.extra.FS_UUID"; public static final int USER_FLAG_INITED = 1 << 0; public static final int USER_FLAG_SNOOZED = 1 << 1; public final int type; public final String fsUuid; public String partGuid; public String nickname; public int userFlags; public long createdMillis; public long lastTrimMillis; public long lastBenchMillis; public VolumeRecord(int type, String fsUuid) { this.type = type; this.fsUuid = Preconditions.checkNotNull(fsUuid); } public VolumeRecord(Parcel parcel) { type = parcel.readInt(); fsUuid = parcel.readString(); partGuid = parcel.readString(); nickname = parcel.readString(); userFlags = parcel.readInt(); createdMillis = parcel.readLong(); lastTrimMillis = parcel.readLong(); lastBenchMillis = parcel.readLong(); } public int getType() { return type; } public String getFsUuid() { return fsUuid; } public String getNickname() { return nickname; } public boolean isInited() { return (userFlags & USER_FLAG_INITED) != 0; } public boolean isSnoozed() { return (userFlags & USER_FLAG_SNOOZED) != 0; } public void dump(IndentingPrintWriter pw) { pw.println("VolumeRecord:"); pw.increaseIndent(); pw.printPair("type", DebugUtils.valueToString(VolumeInfo.class, "TYPE_", type)); pw.printPair("fsUuid", fsUuid); pw.printPair("partGuid", partGuid); pw.println(); pw.printPair("nickname", nickname); pw.printPair("userFlags", DebugUtils.flagsToString(VolumeRecord.class, "USER_FLAG_", userFlags)); pw.println(); pw.printPair("createdMillis", TimeUtils.formatForLogging(createdMillis)); pw.printPair("lastTrimMillis", TimeUtils.formatForLogging(lastTrimMillis)); pw.printPair("lastBenchMillis", TimeUtils.formatForLogging(lastBenchMillis)); pw.decreaseIndent(); pw.println(); } @Override public VolumeRecord clone() { final Parcel temp = Parcel.obtain(); try { writeToParcel(temp, 0); temp.setDataPosition(0); return CREATOR.createFromParcel(temp); } finally { temp.recycle(); } } @Override public boolean equals(Object o) { if (o instanceof VolumeRecord) { return Objects.equals(fsUuid, ((VolumeRecord) o).fsUuid); } else { return false; } } @Override public int hashCode() { return fsUuid.hashCode(); } public static final Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() { @Override public VolumeRecord createFromParcel(Parcel in) { return new VolumeRecord(in); } @Override public VolumeRecord[] newArray(int size) { return new VolumeRecord[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(type); parcel.writeString(fsUuid); parcel.writeString(partGuid); parcel.writeString(nickname); parcel.writeInt(userFlags); parcel.writeLong(createdMillis); parcel.writeLong(lastTrimMillis); parcel.writeLong(lastBenchMillis); } }
syslover33/ctank
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/os/storage/VolumeRecord.java
Java
gpl-3.0
4,577
#include "AtomicMaker.h" #include <string> void AtomicMaker::readParam(std::istream& in) { read<Boundary>(in, "boundary", boundary_); readParamComposite(in, random_); read<int>(in, "nMolecule", nMolecule_); } void AtomicMaker::writeConfig(std::ostream& out) { Vector r; Vector v; int iMol; out << "BOUNDARY" << std::endl; out << std::endl; out << boundary_ << std::endl; out << std::endl; out << "MOLECULES" << std::endl; out << std::endl; out << "species " << 0 << std::endl; out << "nMolecule " << nMolecule_ << std::endl; out << std::endl; for (iMol = 0; iMol < nMolecule_; ++iMol) { out << "molecule " << iMol << std::endl; boundary_.randomPosition(random_, r); out << r << std::endl; out << std::endl; } } int main() { AtomicMaker obj; obj.readParam(std::cin); obj.writeConfig(std::cout); }
jmysona/testing2
src/draft/tools/atomicMaker/AtomicMaker.cpp
C++
gpl-3.0
898
/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ /* @file * Simple object for creating a simple pcap style packet trace */ #include "dev/net/etherdump.hh" #include <sys/time.h> #include <algorithm> #include <string> #include "base/logging.hh" #include "base/output.hh" #include "sim/core.hh" using std::string; EtherDump::EtherDump(const Params *p) : SimObject(p), stream(simout.create(p->file, true)->stream()), maxlen(p->maxlen) { } #define DLT_EN10MB 1 // Ethernet (10Mb) #define TCPDUMP_MAGIC 0xa1b2c3d4 #define PCAP_VERSION_MAJOR 2 #define PCAP_VERSION_MINOR 4 struct pcap_file_header { uint32_t magic; uint16_t version_major; uint16_t version_minor; int32_t thiszone; // gmt to local correction uint32_t sigfigs; // accuracy of timestamps uint32_t snaplen; // max length saved portion of each pkt uint32_t linktype; // data link type (DLT_*) }; struct pcap_pkthdr { uint32_t seconds; uint32_t microseconds; uint32_t caplen; // length of portion present uint32_t len; // length this packet (off wire) }; void EtherDump::init() { struct pcap_file_header hdr; hdr.magic = TCPDUMP_MAGIC; hdr.version_major = PCAP_VERSION_MAJOR; hdr.version_minor = PCAP_VERSION_MINOR; hdr.thiszone = 0; hdr.snaplen = 1500; hdr.sigfigs = 0; hdr.linktype = DLT_EN10MB; stream->write(reinterpret_cast<char *>(&hdr), sizeof(hdr)); stream->flush(); } void EtherDump::dumpPacket(EthPacketPtr &packet) { pcap_pkthdr pkthdr; pkthdr.seconds = curTick() / SimClock::Int::s; pkthdr.microseconds = (curTick() / SimClock::Int::us) % ULL(1000000); pkthdr.caplen = std::min(packet->length, maxlen); pkthdr.len = packet->length; stream->write(reinterpret_cast<char *>(&pkthdr), sizeof(pkthdr)); stream->write(reinterpret_cast<char *>(packet->data), pkthdr.caplen); stream->flush(); } EtherDump * EtherDumpParams::create() { return new EtherDump(this); }
vineodd/PIMSim
GEM5Simulation/gem5/src/dev/net/etherdump.cc
C++
gpl-3.0
3,646
namespace ArdupilotMega.Antenna { partial class Tracker { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Tracker)); this.CMB_interface = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.CMB_baudrate = new System.Windows.Forms.ComboBox(); this.CMB_serialport = new System.Windows.Forms.ComboBox(); this.TRK_pantrim = new System.Windows.Forms.TrackBar(); this.TXT_panrange = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.TXT_tiltrange = new System.Windows.Forms.TextBox(); this.TRK_tilttrim = new System.Windows.Forms.TrackBar(); this.label2 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.CHK_revpan = new System.Windows.Forms.CheckBox(); this.CHK_revtilt = new System.Windows.Forms.CheckBox(); this.TXT_pwmrangepan = new System.Windows.Forms.TextBox(); this.TXT_pwmrangetilt = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.BUT_connect = new ArdupilotMega.Controls.MyButton(); this.LBL_pantrim = new System.Windows.Forms.Label(); this.LBL_tilttrim = new System.Windows.Forms.Label(); this.BUT_find = new ArdupilotMega.Controls.MyButton(); this.TXT_centerpan = new System.Windows.Forms.TextBox(); this.TXT_centertilt = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.TRK_pantrim)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TRK_tilttrim)).BeginInit(); this.SuspendLayout(); // // CMB_interface // this.CMB_interface.FormattingEnabled = true; this.CMB_interface.Items.AddRange(new object[] { resources.GetString("CMB_interface.Items"), resources.GetString("CMB_interface.Items1")}); resources.ApplyResources(this.CMB_interface, "CMB_interface"); this.CMB_interface.Name = "CMB_interface"; this.CMB_interface.SelectedIndexChanged += new System.EventHandler(this.CMB_interface_SelectedIndexChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // CMB_baudrate // this.CMB_baudrate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CMB_baudrate.FormattingEnabled = true; this.CMB_baudrate.Items.AddRange(new object[] { resources.GetString("CMB_baudrate.Items"), resources.GetString("CMB_baudrate.Items1"), resources.GetString("CMB_baudrate.Items2"), resources.GetString("CMB_baudrate.Items3"), resources.GetString("CMB_baudrate.Items4"), resources.GetString("CMB_baudrate.Items5"), resources.GetString("CMB_baudrate.Items6"), resources.GetString("CMB_baudrate.Items7")}); resources.ApplyResources(this.CMB_baudrate, "CMB_baudrate"); this.CMB_baudrate.Name = "CMB_baudrate"; // // CMB_serialport // this.CMB_serialport.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CMB_serialport.FormattingEnabled = true; resources.ApplyResources(this.CMB_serialport, "CMB_serialport"); this.CMB_serialport.Name = "CMB_serialport"; // // TRK_pantrim // resources.ApplyResources(this.TRK_pantrim, "TRK_pantrim"); this.TRK_pantrim.Maximum = 360; this.TRK_pantrim.Minimum = -360; this.TRK_pantrim.Name = "TRK_pantrim"; this.TRK_pantrim.TickFrequency = 5; this.TRK_pantrim.Scroll += new System.EventHandler(this.TRK_pantrim_Scroll); // // TXT_panrange // resources.ApplyResources(this.TXT_panrange, "TXT_panrange"); this.TXT_panrange.Name = "TXT_panrange"; this.TXT_panrange.TextChanged += new System.EventHandler(this.TXT_panrange_TextChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // TXT_tiltrange // resources.ApplyResources(this.TXT_tiltrange, "TXT_tiltrange"); this.TXT_tiltrange.Name = "TXT_tiltrange"; this.TXT_tiltrange.TextChanged += new System.EventHandler(this.TXT_tiltrange_TextChanged); // // TRK_tilttrim // resources.ApplyResources(this.TRK_tilttrim, "TRK_tilttrim"); this.TRK_tilttrim.Maximum = 180; this.TRK_tilttrim.Minimum = -180; this.TRK_tilttrim.Name = "TRK_tilttrim"; this.TRK_tilttrim.TickFrequency = 5; this.TRK_tilttrim.Scroll += new System.EventHandler(this.TRK_tilttrim_Scroll); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // CHK_revpan // resources.ApplyResources(this.CHK_revpan, "CHK_revpan"); this.CHK_revpan.Name = "CHK_revpan"; this.CHK_revpan.UseVisualStyleBackColor = true; this.CHK_revpan.CheckedChanged += new System.EventHandler(this.CHK_revpan_CheckedChanged); // // CHK_revtilt // resources.ApplyResources(this.CHK_revtilt, "CHK_revtilt"); this.CHK_revtilt.Name = "CHK_revtilt"; this.CHK_revtilt.UseVisualStyleBackColor = true; this.CHK_revtilt.CheckedChanged += new System.EventHandler(this.CHK_revtilt_CheckedChanged); // // TXT_pwmrangepan // resources.ApplyResources(this.TXT_pwmrangepan, "TXT_pwmrangepan"); this.TXT_pwmrangepan.Name = "TXT_pwmrangepan"; // // TXT_pwmrangetilt // resources.ApplyResources(this.TXT_pwmrangetilt, "TXT_pwmrangetilt"); this.TXT_pwmrangetilt.Name = "TXT_pwmrangetilt"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // label12 // resources.ApplyResources(this.label12, "label12"); this.label12.Name = "label12"; // // BUT_connect // resources.ApplyResources(this.BUT_connect, "BUT_connect"); this.BUT_connect.Name = "BUT_connect"; this.BUT_connect.UseVisualStyleBackColor = true; this.BUT_connect.Click += new System.EventHandler(this.BUT_connect_Click); // // LBL_pantrim // resources.ApplyResources(this.LBL_pantrim, "LBL_pantrim"); this.LBL_pantrim.Name = "LBL_pantrim"; // // LBL_tilttrim // resources.ApplyResources(this.LBL_tilttrim, "LBL_tilttrim"); this.LBL_tilttrim.Name = "LBL_tilttrim"; // // BUT_find // resources.ApplyResources(this.BUT_find, "BUT_find"); this.BUT_find.Name = "BUT_find"; this.BUT_find.UseVisualStyleBackColor = true; this.BUT_find.Click += new System.EventHandler(this.BUT_find_Click); // // TXT_centerpan // resources.ApplyResources(this.TXT_centerpan, "TXT_centerpan"); this.TXT_centerpan.Name = "TXT_centerpan"; this.TXT_centerpan.TextChanged += new System.EventHandler(this.TXT_centerpan_TextChanged); // // TXT_centertilt // resources.ApplyResources(this.TXT_centertilt, "TXT_centertilt"); this.TXT_centertilt.Name = "TXT_centertilt"; this.TXT_centertilt.TextChanged += new System.EventHandler(this.TXT_centertilt_TextChanged); // // label13 // resources.ApplyResources(this.label13, "label13"); this.label13.Name = "label13"; // // label14 // resources.ApplyResources(this.label14, "label14"); this.label14.Name = "label14"; // // Tracker // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.TXT_centertilt); this.Controls.Add(this.TXT_centerpan); this.Controls.Add(this.BUT_find); this.Controls.Add(this.LBL_tilttrim); this.Controls.Add(this.LBL_pantrim); this.Controls.Add(this.label12); this.Controls.Add(this.label10); this.Controls.Add(this.label11); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.TXT_pwmrangetilt); this.Controls.Add(this.TXT_pwmrangepan); this.Controls.Add(this.CHK_revtilt); this.Controls.Add(this.CHK_revpan); this.Controls.Add(this.label7); this.Controls.Add(this.label2); this.Controls.Add(this.label5); this.Controls.Add(this.label6); this.Controls.Add(this.TXT_tiltrange); this.Controls.Add(this.TRK_tilttrim); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.TXT_panrange); this.Controls.Add(this.TRK_pantrim); this.Controls.Add(this.CMB_baudrate); this.Controls.Add(this.BUT_connect); this.Controls.Add(this.CMB_serialport); this.Controls.Add(this.label1); this.Controls.Add(this.CMB_interface); this.Name = "Tracker"; ((System.ComponentModel.ISupportInitialize)(this.TRK_pantrim)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TRK_tilttrim)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox CMB_interface; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox CMB_baudrate; private ArdupilotMega.Controls.MyButton BUT_connect; private System.Windows.Forms.ComboBox CMB_serialport; private System.Windows.Forms.TrackBar TRK_pantrim; private System.Windows.Forms.TextBox TXT_panrange; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox TXT_tiltrange; private System.Windows.Forms.TrackBar TRK_tilttrim; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label7; private System.Windows.Forms.CheckBox CHK_revpan; private System.Windows.Forms.CheckBox CHK_revtilt; private System.Windows.Forms.TextBox TXT_pwmrangepan; private System.Windows.Forms.TextBox TXT_pwmrangetilt; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label LBL_pantrim; private System.Windows.Forms.Label LBL_tilttrim; private Controls.MyButton BUT_find; private System.Windows.Forms.TextBox TXT_centerpan; private System.Windows.Forms.TextBox TXT_centertilt; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; } }
trunet/ardupilot
Tools/ArdupilotMegaPlanner/Antenna/Tracker.Designer.cs
C#
gpl-3.0
15,376
#!/usr/bin/python # # GEOMTERY.OUT to OpenDX # # Created: April 2009 (AVK) # Modified: February 2012 (AVK) # import math import sys def r3minv(a, b): t1 = a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) + \ a[0][1] * (a[1][2] * a[2][0] - a[1][0] * a[2][2]) + \ a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) if math.fabs(t1) < 1e-40: print "r3mv: singular matrix" sys.exit(0) t1 = 1.0/t1 b[0][0] = t1 * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) b[0][1] = t1 * (a[0][2] * a[2][1] - a[0][1] * a[2][2]) b[0][2] = t1 * (a[0][1] * a[1][2] - a[0][2] * a[1][1]) b[1][0] = t1 * (a[1][2] * a[2][0] - a[1][0] * a[2][2]) b[1][1] = t1 * (a[0][0] * a[2][2] - a[0][2] * a[2][0]) b[1][2] = t1 * (a[0][2] * a[1][0] - a[0][0] * a[1][2]) b[2][0] = t1 * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) b[2][1] = t1 * (a[0][1] * a[2][0] - a[0][0] * a[2][1]) b[2][2] = t1 * (a[0][0] * a[1][1] - a[0][1] * a[1][0]) return # # angular part of site-centered orbital # current implementation is for d-orbitals only # class Orbital: def __init__(self,coefs): self.pos=[] self.tri=[] self.coefs=coefs self.make() # real spherical harmonics def Rlm(self,l,m,theta,phi): if l==2 and m==-2: return -math.sqrt(15.0/(16*math.pi))*math.sin(2*phi)*math.sin(theta)**2 if l==2 and m==-1: return -math.sqrt(15.0/(16*math.pi))*math.sin(phi)*math.sin(2*theta) if l==2 and m==0: return math.sqrt(5/(64*math.pi))*(1+3*math.cos(2*theta)) if l==2 and m==1: return -math.sqrt(15.0/(16*math.pi))*math.cos(phi)*math.sin(2*theta) if l==2 and m==2: return math.sqrt(15.0/(16*math.pi))*math.cos(2*phi)*math.sin(theta)**2 def val(self,theta,phi): v=0 for m in range(5): v+=self.coefs[m]*self.Rlm(2,m-2,theta,phi) return v def make(self): raw_pos=[] raw_con=[] n=30 for t in range(n): theta=math.pi*t/(n-1) for p in range(n): phi=2*math.pi*p/(n-1) v=5.5*self.val(theta,phi) x=v*math.sin(theta)*math.cos(phi) y=v*math.sin(theta)*math.sin(phi) z=v*math.cos(theta) raw_pos.append([x,y,z]) for t in range(n): for p in range(n): i1=t i2=(t+1)%n j1=p j2=(p+1)%n n1=i1*n+j1 n2=i1*n+j2 n3=i2*n+j2 n4=i2*n+j1 raw_con.append([n1,n2,n3]) raw_con.append([n1,n3,n4]) # find equal positions eq_pos=[-1 for i in range(n*n)] l=0 for i in range(n*n): if eq_pos[i]==-1: eq_pos[i]=l self.pos.append(raw_pos[i]) for j in range(i+1,n*n): if abs(raw_pos[i][0]-raw_pos[j][0])<1e-10 and \ abs(raw_pos[i][1]-raw_pos[j][1])<1e-10 and \ abs(raw_pos[i][2]-raw_pos[j][2])<1e-10: eq_pos[j]=l l+=1 npos=l # substitute positions in triangles by non-equal positions for i in range(2*n*n): raw_con[i][0]=eq_pos[raw_con[i][0]] raw_con[i][1]=eq_pos[raw_con[i][1]] raw_con[i][2]=eq_pos[raw_con[i][2]] eq_con=[-1 for i in range(2*n*n)] # mark degenerate triangles for i in range(2*n*n): if raw_con[i][0]==raw_con[i][1] or raw_con[i][0]==raw_con[i][2] or \ raw_con[i][1]==raw_con[i][2]: eq_con[i]=-2 # find equal triangles l=0 for i in range(2*n*n): if eq_con[i]==-1: eq_con[i]=l self.tri.append(raw_con[i]) for j in range(i+1,2*n*n): if raw_con[i][0]==raw_con[j][0] and raw_con[i][1]==raw_con[j][1] and \ raw_con[i][2]==raw_con[j][2]: eq_con[j]=l l+=1 # # species-specific variables # class Species: def __init__(self, label): self.label = label self.R = 1.0 self.color = [0.5, 0.5, 0.5] self.visible = True # # atom-specific variables # class Atom: def __init__(self, species, posc, posl): self.species = species self.posc = posc self.posl = posl self.nghbr = [] self.orbital = 0 # # geometry-specific variables # class Geometry: def __init__(self): self.avec = [] self.speciesList = {} self.atomList = [] # read 'GEOMETRY.OUT' self.readGeometry() # make a list of nearest neighbours for each atom self.findNeighbours() # print basic info self.printGeometry() def readGeometry(self): fin = open("GEOMETRY.OUT","r") while True : line = fin.readline() if not line: break line = line.strip(" \n") if line == "avec": for i in range(3): s1 = fin.readline().strip(" \n").split() self.avec.append([float(s1[0]), float(s1[1]), float(s1[2])]) if line == "atoms": # get number of species s1 = fin.readline().strip(" \n").split() nspecies = int(s1[0]) # go over species for i in range(nspecies): # construct label from species file name s1 = fin.readline().strip(" \n").split() label = s1[0][1:s1[0].find(".in")] # crate new species sp = Species(label) # put species to the list self.speciesList[label] = sp # get number of atoms for current species s1 = fin.readline().strip(" \n").split() natoms = int(s1[0]) # go over atoms for j in range(natoms): s1 = fin.readline().strip(" \n").split() posl = [float(s1[0]), float(s1[1]), float(s1[2])] posc = [0, 0, 0] for l in range(3): for x in range(3): posc[x] += posl[l] * self.avec[l][x] # create new atom self.atomList.append(Atom(sp, posc, posl)) fin.close() def printGeometry(self): print "lattice vectors" print " a1 : %12.6f %12.6f %12.6f"%(self.avec[0][0], self.avec[0][1], self.avec[0][2]) print " a2 : %12.6f %12.6f %12.6f"%(self.avec[1][0], self.avec[1][1], self.avec[1][2]) print " a3 : %12.6f %12.6f %12.6f"%(self.avec[2][0], self.avec[2][1], self.avec[2][2]) print "atoms" for i in range(len(self.atomList)): print "%4i (%2s) at position %12.6f %12.6f %12.6f"%\ (i, self.atomList[i].species.label, self.atomList[i].posc[0],\ self.atomList[i].posc[1], self.atomList[i].posc[2]) def findNeighbours(self): for iat in range(len(self.atomList)): xi = self.atomList[iat].posc nn = [] # add nearest neigbours for jat in range(len(self.atomList)): xj = self.atomList[jat].posc for i1 in range(-4,5): for i2 in range(-4,5): for i3 in range(-4,5): t = [0, 0, 0] for x in range(3): t[x] = i1 * self.avec[0][x] + i2 * self.avec[1][x] + i3 * self.avec[2][x] r = [0, 0, 0] for x in range(3): r[x] = xj[x] + t[x] - xi[x] d = math.sqrt(r[0]**2 + r[1]**2 + r[2]**2) if (d <= 10.0): nn.append([jat, r, d]) # sort by distance for i in range(len(nn) - 1): for j in range(i+1, len(nn)): if nn[j][2] < nn[i][2]: nn[i], nn[j] = nn[j], nn[i] self.atomList[iat].nghbr = nn[:] # # cell (not necessarily primitive) with atoms and bonds # class Cell: def __init__(self, geometry, box): self.geometry = geometry self.box = box self.bonds = [] self.atoms = [] self.bondList = [] return def hide(self, label): print " " print "hiding", label self.geometry.speciesList[label].visible = False return def atomSphere(self, label, color, R): self.geometry.speciesList[label].color = color self.geometry.speciesList[label].R = R return def bond(self, label1, label2, length, extend): self.bondList.append([label1, label2, length, extend]) return def atomOrbital(self, ias, fname, iorb): fin = open(fname, "r") f1 = [] for i in range(5): s1 = fin.readline().strip(" \n").split() if i == (iorb - 1): for j in range(5): f1.append(float(s1[j])) self.geometry.atomList[ias].orbital = Orbital(f1) return def write(self): self.fillBox() self.makeBonds() self.writeAtoms() self.writeBonds() #self.writeOrbitals() # def inBox(self, p, box): # n=[0,0,0] # a=box[0] # b=box[1] # c=box[2] # i=0 # # n[0]=a[1]*b[2]-a[2]*b[1] # n[1]=a[2]*b[0]-a[0]*b[2] # n[2]=a[0]*b[1]-a[1]*b[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-c[0])+n[1]*(p[1]-c[1])+n[2]*(p[2]-c[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # n[0]=a[1]*c[2]-a[2]*c[1] # n[1]=a[2]*c[0]-a[0]*c[2] # n[2]=a[0]*c[1]-a[1]*c[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-b[0])+n[1]*(p[1]-b[1])+n[2]*(p[2]-b[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # n[0]=b[1]*c[2]-b[2]*c[1] # n[1]=b[2]*c[0]-b[0]*c[2] # n[2]=b[0]*c[1]-b[1]*c[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-a[0])+n[1]*(p[1]-a[1])+n[2]*(p[2]-a[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # if i==3: return True # else: return False def inBox(self, r, imv): # coorinates in the inits of box vectors rb = [0, 0, 0] for i in range(3): for j in range(3): rb[i] += imv[i][j] * r[j] if (rb[0] >= -0.5 and rb[0] <= 0.5) and \ (rb[1] >= -0.5 and rb[1] <= 0.5) and \ (rb[2] >= -0.5 and rb[2] <= 0.5): return True else: return False def fillBox(self): print " " print "populating the box" print " box parameters" print " center : %12.6f %12.6f %12.6f"%(self.box[0][0], self.box[0][1], self.box[0][2]) print " v1 : %12.6f %12.6f %12.6f"%(self.box[1][0], self.box[1][1], self.box[1][2]) print " v2 : %12.6f %12.6f %12.6f"%(self.box[2][0], self.box[2][1], self.box[2][2]) print " v3 : %12.6f %12.6f %12.6f"%(self.box[3][0], self.box[3][1], self.box[3][2]) mv = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range(3): for x in range(3): mv[x][i] = self.box[1+i][x] imv = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] r3minv(mv, imv) for ias in range(len(self.geometry.atomList)): if self.geometry.atomList[ias].species.visible: for i1 in range(-4, 5): for i2 in range(-4, 5): for i3 in range(-4, 5): # absolute position (position in the unit cell + translation) r = [0, 0, 0] for x in range(3): r[x] = self.geometry.atomList[ias].posc[x] + \ i1 * self.geometry.avec[0][x] + \ i2 * self.geometry.avec[1][x] + \ i3 * self.geometry.avec[2][x] # position with respect to the center of the box r0 = [0, 0, 0] for x in range(3): r0[x] = r[x] - self.box[0][x] if self.inBox(r0, imv): self.atoms.append([ias, r]) return def writeAtoms(self): print " " print "writing ATOMS.dx" fout = open("ATOMS.dx", "w+") fout.write("object 1 class array type float rank 0 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] fout.write("%f\n"%self.geometry.atomList[ias].species.R) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object 2 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] color = self.geometry.atomList[ias].species.color fout.write("%f %f %f\n"%(color[0], color[1], color[2])) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object 3 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] pos = self.atoms[i][1] fout.write("%f %f %f # %s\n"%(pos[0], pos[1], pos[2], self.geometry.atomList[ias].species.label)) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object \"atoms\" class field\n") fout.write("component \"data\" value 1\n") fout.write("component \"colors\" value 2\n") fout.write("component \"positions\" value 3\n") fout.write("attribute \"name\" string \"cell\"") fout.close() return def index_in_atoms(self, r): for i in range(len(self.atoms)): if math.fabs(r[0] - self.atoms[i][1][0]) < 1e-10 and \ math.fabs(r[1] - self.atoms[i][1][1]) < 1e-10 and \ math.fabs(r[2] - self.atoms[i][1][2]) < 1e-10: return i return -1 def makeBonds(self): for ibond in range(len(self.bondList)): lbl1 = self.bondList[ibond][0] lbl2 = self.bondList[ibond][1] length = self.bondList[ibond][2] extend = self.bondList[ibond][3] # go over all atoms in the box for i in range(len(self.atoms)): ias = self.atoms[i][0] if self.geometry.atomList[ias].species.label == lbl1: # go over nearest neigbours of atom ias for j in range(len(self.geometry.atomList[ias].nghbr)): jas = self.geometry.atomList[ias].nghbr[j][0] if (self.geometry.atomList[jas].species.label == lbl2) and \ (self.geometry.atomList[ias].nghbr[j][2] <= length): # absolute position of neigbour: position of central atom + connecting vector rj = [0, 0, 0] for x in range(3): rj[x] = self.atoms[i][1][x] + self.geometry.atomList[ias].nghbr[j][1][x] # index of this neigbour in the list of atoms in the box idx = self.index_in_atoms(rj) if idx!=-1: self.bonds.append([i, idx]) elif extend: self.atoms.append([jas, rj]) self.bonds.append([i, len(self.atoms)-1]) return def writeBonds(self): print " " print "writing BONDS.dx" fout = open("BONDS.dx","w+") fout.write("object 1 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): pos = self.atoms[i][1] fout.write("%f %f %f\n"%(pos[0], pos[1], pos[2])) fout.write("#\n") fout.write("object 2 class array type int rank 1 shape 2 items %i data follows\n"%len(self.bonds)) for i in range(len(self.bonds)): fout.write("%i %i\n"%(self.bonds[i][0], self.bonds[i][1])) fout.write("attribute \"element type\" string \"lines\"\n") fout.write("attribute \"ref\" string \"positions\"\n") fout.write("#\n") fout.write("object \"atom_connect\" class field\n") fout.write("component \"positions\" value 1\n") fout.write("component \"connections\" value 2\n") fout.write("end\n") fout.close() return def writeOrbitals(self): print " " print "writing ORBITALS.dx" fout=open("ORBITALS.dx","w+") iorb=0 for iat in range(len(self.atomList)): print self.atomList[iat].orbital if self.atomList[iat].orbital != 0: iorb+=1 r0=self.atomList[iat].posc fout.write("object %i class array type float rank 1 shape 3 items %i data follows\n"%\ ((iorb-1)*2+1,len(self.atomList[iat].orbital.pos))) for i in range(len(self.atomList[iat].orbital.pos)): r=[0,0,0] for x in range(3): r[x]=r0[x]+self.atomList[iat].orbital.pos[i][x] fout.write("%f %f %f\n"%(r[0],r[1],r[2])) fout.write("#\n") fout.write("object %i class array type int rank 1 shape 3 items %i data follows\n"%\ ((iorb-1)*2+2,len(self.atomList[iat].orbital.tri))) for i in range(len(self.atomList[iat].orbital.tri)): fout.write("%i %i %i\n"%(self.atomList[iat].orbital.tri[i][0],\ self.atomList[iat].orbital.tri[i][1],\ self.atomList[iat].orbital.tri[i][2])) fout.write("attribute \"ref\" string \"positions\"\n") fout.write("attribute \"element type\" string \"triangles\"\n") fout.write("attribute \"dep\" string \"connections\"\n") fout.write("#\n") fout.write("object \"orbital%i\" class field\n"%iorb) fout.write("component \"positions\" value %i\n"%((iorb-1)*2+1)) fout.write("component \"connections\" value %i\n"%((iorb-1)*2+2)) fout.write("#\n") norb=iorb fout.write("object \"orbital\" class group\n") for iorb in range(norb): fout.write(" member %i value \"orbital%i\"\n"%(iorb,iorb+1)) fout.write("end\n") fout.close() # # # print " " print "GEOMTERY.OUT to OpenDX" print " " # # get the geometry # geometry = Geometry() # # 3D box (center point + 3 non-collinear vectors) # example: # box=[[0,0,0],[10,0,0],[0,10,0],[0,0,10]] box = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] #geometry.avec[0],geometry.avec[1],geometry.avec[2]] # # cell with user-defined shape # cell = Cell(geometry, box) # # cell.hide(label) # hides species with a given label # example: # cell.hide("Ca") #cell.hide("Y") # # cell.atomSphere(label,color,radius) # sets [r,g,b] color and radius of species with a given label # example: red Mn sphere with radius 1.0 # cell.atomSphere("Mn",[1.0,0.0,0.0],1.0) cell.atomSphere("La", [0.0, 1.0, 0.0], 1.0) cell.atomSphere("Cu", [1.0, 0.0, 0.0], 1.0) cell.atomSphere("O", [0.0, 0.0, 1.0], 1.0) # # cell.bond(label1,label2,d,extend) # defines a bond with a maximum length 'd' from species 'label1' to species 'label2' # if extend is True, the bond can go outside the box # example: Mn-O bond # cell.bond("Mn","O",5,True) cell.bond("Cu", "O", 5, True) # # cell.atomOrbital(j, file_name, i) # defines angular part of the site-centered orbital i for atom j; # the orbital coefficients are taken from file file_name # example: #cell.atomOrbital(4, "Cu1_mtrx.txt", 1) # # write to .dx files # cell.write()
rgvanwesep/exciting-plus-rgvw-mod
utilities/geometry2dx__mtrx.py
Python
gpl-3.0
20,319
#Copyright (C) 2014 Marc Herndon # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License, #version 2, as published by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ This module contains the definition of the `Attribute` class, used to represent individual SMART attributes associated with a `Device`. """ class Attribute(object): """ Contains all of the information associated with a single SMART attribute in a `Device`'s SMART table. This data is intended to exactly mirror that obtained through smartctl. """ def __init__(self, num, name, flags, value, worst, thresh, attr_type, updated, when_failed, raw): self.num = num """**(str):** Attribute's ID as a decimal value (1-255).""" self.name = name """ **(str):** Attribute's name, as reported by smartmontools' drive.db. """ self.flags = flags """**(str):** Attribute flags as a hexadecimal value (ie: 0x0032).""" self.value = value """**(str):** Attribute's current normalized value.""" self.worst = worst """**(str):** Worst recorded normalized value for this attribute.""" self.thresh = thresh """**(str):** Attribute's failure threshold.""" self.type = attr_type """**(str):** Attribute's type, generally 'pre-fail' or 'old-age'.""" self.updated = updated """ **(str):** When is this attribute updated? Generally 'Always' or 'Offline' """ self.when_failed = when_failed """ **(str):** When did this attribute cross below `pySMART.attribute.Attribute.thresh`? Reads '-' when not failed. Generally either 'FAILING_NOW' or 'In_the_Past' otherwise. """ self.raw = raw """**(str):** Attribute's current raw (non-normalized) value.""" def __repr__(self): """Define a basic representation of the class object.""" return "<SMART Attribute %r %s/%s raw:%s>" % ( self.name, self.value, self.thresh, self.raw) def __str__(self): """ Define a formatted string representation of the object's content. In the interest of not overflowing 80-character lines this does not print the value of `pySMART.attribute.Attribute.flags_hex`. """ return "{0:>3} {1:24}{2:4}{3:4}{4:4}{5:9}{6:8}{7:12}{8}".format( self.num, self.name, self.value, self.worst, self.thresh, self.type, self.updated, self.when_failed, self.raw) __all__ = ['Attribute']
scith/htpc-manager_ynh
sources/libs/pySMART/attribute.py
Python
gpl-3.0
3,070
define([ 'angular' , './view-rubberband-controller' , './view-rubberband-directive' ], function( angular , Controller , directive ) { "use strict"; return angular.module('mtk.viewRubberband', []) .controller('ViewRubberbandController', Controller) .directive('mtkViewRubberband', directive) ; });
jeroenbreen/metapolator
app/lib/ui/metapolator/view-rubberband/view-rubberband.js
JavaScript
gpl-3.0
354
from .main import Sabnzbd def start(): return Sabnzbd() config = [{ 'name': 'sabnzbd', 'groups': [ { 'tab': 'downloaders', 'list': 'download_providers', 'name': 'sabnzbd', 'label': 'Sabnzbd', 'description': 'Use <a href="http://sabnzbd.org/" target="_blank">SABnzbd</a> (0.7+) to download NZBs.', 'wizard': True, 'options': [ { 'name': 'enabled', 'default': 0, 'type': 'enabler', 'radio_group': 'nzb', }, { 'name': 'host', 'default': 'localhost:8080', }, { 'name': 'api_key', 'label': 'Api Key', 'description': 'Used for all calls to Sabnzbd.', }, { 'name': 'category', 'label': 'Category', 'description': 'The category CP places the nzb in. Like <strong>movies</strong> or <strong>couchpotato</strong>', }, { 'name': 'priority', 'label': 'Priority', 'type': 'dropdown', 'default': '0', 'advanced': True, 'values': [('Paused', -2), ('Low', -1), ('Normal', 0), ('High', 1), ('Forced', 2)], 'description': 'Add to the queue with this priority.', }, { 'name': 'manual', 'default': False, 'type': 'bool', 'advanced': True, 'description': 'Disable this downloader for automated searches, but use it when I manually send a release.', }, { 'name': 'remove_complete', 'advanced': True, 'label': 'Remove NZB', 'default': False, 'type': 'bool', 'description': 'Remove the NZB from history after it completed.', }, { 'name': 'delete_failed', 'default': True, 'advanced': True, 'type': 'bool', 'description': 'Delete a release after the download has failed.', }, ], } ], }]
jerbob92/CouchPotatoServer
couchpotato/core/downloaders/sabnzbd/__init__.py
Python
gpl-3.0
2,548
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ // sync_reset.cpp -- test for // // Original Author: John Aynsley, Doulos, Inc. // // MODIFICATION LOG - modifiers, enter your name, affiliation, date and // // $Log: sync_reset.cpp,v $ // Revision 1.2 2011/05/08 19:18:46 acg // Andy Goodrich: remove extraneous + prefixes from git diff. // // sync_reset_on/off #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc> using namespace sc_core; using std::cout; using std::endl; struct M2: sc_module { M2(sc_module_name _name) { SC_THREAD(ticker); SC_THREAD(calling); SC_THREAD(target1); t1 = sc_get_current_process_handle(); sc_spawn_options opt; opt.spawn_method(); opt.dont_initialize(); opt.set_sensitivity( &t1.reset_event() ); sc_spawn(sc_bind( &M2::reset_handler, this ), "reset_handler", &opt); SC_THREAD(target2); t2 = sc_get_current_process_handle(); SC_METHOD(target3); sensitive << ev; t3 = sc_get_current_process_handle(); count = 1; f0 = f1 = f2 = f3 = f4 = f5 = f6 = f7 = f8 = f9 = 0; f10 = f11 = f12 = f13 = f14 = f15 = f16 = f17 = f18 = f19 = 0; f20 = f21 = f22 = f23 = f24 = f25 = f26 = f27 = f28 = f29 = 0; f30 = f31 = f32 = f33 = f34 = f35 = f36 = f37 = f38 = f39 = 0; f40 = f41 = f42 = f43 = f44 = f45 = f46 = f47 = f48 = f49 = 0; } sc_process_handle t1, t2, t3; sc_event ev; int count; int f0, f1, f2, f3, f4, f5, f6, f7, f8, f9; int f10, f11, f12, f13, f14, f15, f16, f17, f18, f19; int f20, f21, f22, f23, f24, f25, f26, f27, f28, f29; int f30, f31, f32, f33, f34, f35, f36, f37, f38, f39; int f40, f41, f42, f43, f44, f45, f46, f47, f48, f49; void ticker() { for (;;) { wait(10, SC_NS); sc_assert( !sc_is_unwinding() ); ev.notify(); } } void calling() { count = 1; wait(15, SC_NS); // Target runs at 10 NS count = 2; t1.sync_reset_on(); // Target does not run at 15 NS wait(10, SC_NS); // Target is reset at 20 NS count = 3; wait(10, SC_NS); // Target is reset again at 30 NS count = 4; t1.sync_reset_off(); // Target does not run at 35 NS wait(10, SC_NS); // Target runs at 40 NS count = 5; t1.sync_reset_off(); // Double sync_reset_off wait(10, SC_NS); // Target runs at 50 NS count = 6; t1.sync_reset_on(); t1.disable(); wait(10, SC_NS); // Target does not run at 60 NS count = 7; t1.enable(); // Target does not run at 65 NS wait(10, SC_NS); // Target reset at 70 NS count = 8; t1.disable(); wait(10, SC_NS); // Target does not run at 80 NS count = 9; t1.sync_reset_off(); wait(10, SC_NS); // Target still disabled at 90 NS count = 10; t1.enable(); wait(10, SC_NS); // Target runs at 100 NS count = 11; t1.suspend(); wait(10, SC_NS); // Target does not run at 110 NS count = 12; wait(10, SC_NS); // Target still suspended at 120 NS count = 13; t1.resume(); // Target runs at 125 NS wait(1, SC_NS); count = 14; wait(9, SC_NS); // Target runs again at 130 NS count = 15; t1.sync_reset_on(); // Double sync_reset_on wait(10, SC_NS); // Target reset at 140 NS count = 16; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 150 NS count = 17; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 160 NS count = 18; t1.sync_reset_on(); wait(10, SC_NS); // Target reset at 170 NS count = 19; t1.reset(); // Target reset at 175 NS wait(SC_ZERO_TIME); count = 20; wait(1, SC_NS); t1.reset(); // Target reset at 176 NS count = 21; t1.reset(); // Target reset at 176 NS wait(1, SC_NS); count = 22; wait(8, SC_NS); // Target reset at 180 NS count = 23; wait(10, SC_NS); // Target reset at 190 NS count = 24; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 200 NS count = 25; wait(10, SC_NS); // Target runs at 210 NS count = 26; t1.reset(); wait(SC_ZERO_TIME); // Target reset at 215 t1.disable(); // Close it down wait(sc_time(300, SC_NS) - sc_time_stamp()); count = 27; t2.resume(); wait(SC_ZERO_TIME); count = 28; wait(15, SC_NS); count = 29; t2.sync_reset_on(); wait(10, SC_NS); t2.sync_reset_off(); t2.suspend(); wait(sc_time(405, SC_NS) - sc_time_stamp()); count = 30; t3.resume(); wait(SC_ZERO_TIME); count = 31; wait(10, SC_NS); count = 32; t3.sync_reset_on(); wait(10, SC_NS); sc_stop(); } void target1() { //cout << "Target1 called/reset at " << sc_time_stamp() << " count = " << count << endl; switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); f0=1; break; case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f1=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f2=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f3=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f4=1; break; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f5=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f6=1; break; case 20: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f7=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f8=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f9=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f10=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f11=1; break; default: sc_assert( false ); break; } for (;;) { try { wait(ev); //cout << "Target1 awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(10, SC_NS) ); f12=1; break; case 4: sc_assert( sc_time_stamp() == sc_time(40, SC_NS) ); f13=1; break; case 5: sc_assert( sc_time_stamp() == sc_time(50, SC_NS) ); f14=1; break; case 10: sc_assert( sc_time_stamp() == sc_time(100, SC_NS) ); f15=1; break; case 13: sc_assert( sc_time_stamp() == sc_time(125, SC_NS) ); f16=1; break; case 14: sc_assert( sc_time_stamp() == sc_time(130, SC_NS) ); f17=1; break; case 16: sc_assert( sc_time_stamp() == sc_time(150, SC_NS) ); f18=1; break; case 17: sc_assert( sc_time_stamp() == sc_time(160, SC_NS) ); f19=1; break; case 24: sc_assert( sc_time_stamp() == sc_time(200, SC_NS) ); f20=1; break; case 25: sc_assert( sc_time_stamp() == sc_time(210, SC_NS) ); f21=1; break; default: sc_assert( false ); break; } } catch (const sc_unwind_exception& ex) { sc_assert( sc_is_unwinding() ); sc_assert( ex.is_reset() ); throw ex; } } } void reset_handler() { //cout << "reset_handler awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f22=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f23=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f24=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f27=1; break;; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f28=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f29=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f31=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f32=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f33=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f34=1; break; default: sc_assert( false ); break; } } void target2() { if (sc_delta_count() == 0) t2.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 27: sc_assert( sc_time_stamp() == sc_time(300, SC_NS) ); f35=1; break; case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f37=1; break; default: sc_assert( false ); break; } while(1) { try { wait(10, SC_NS); } catch (const sc_unwind_exception& e) { switch (count) { case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f38=1; break; default: sc_assert( false ); break; } throw e; } switch (count) { case 28: sc_assert( sc_time_stamp() == sc_time(310, SC_NS) ); f36=1; break; default: sc_assert( false ); break; } } } void target3() { if (sc_delta_count() == 0) t3.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); break; case 30: sc_assert( sc_time_stamp() == sc_time(405, SC_NS) ); f39=1; break; case 31: sc_assert( sc_time_stamp() == sc_time(410, SC_NS) ); f40=1; break; case 32: sc_assert( sc_time_stamp() == sc_time(420, SC_NS) ); f41=1; break; default: sc_assert( false ); break; } } SC_HAS_PROCESS(M2); }; int sc_main(int argc, char* argv[]) { M2 m("m"); sc_start(); sc_assert(m.f0); sc_assert(m.f1); sc_assert(m.f2); sc_assert(m.f3); sc_assert(m.f4); sc_assert(m.f5); sc_assert(m.f6); sc_assert(m.f7); sc_assert(m.f8); sc_assert(m.f9); sc_assert(m.f10); sc_assert(m.f11); sc_assert(m.f12); sc_assert(m.f13); sc_assert(m.f14); sc_assert(m.f15); sc_assert(m.f16); sc_assert(m.f17); sc_assert(m.f18); sc_assert(m.f19); sc_assert(m.f20); sc_assert(m.f21); sc_assert(m.f22); sc_assert(m.f23); sc_assert(m.f24); sc_assert(m.f27); sc_assert(m.f28); sc_assert(m.f29); sc_assert(m.f31); sc_assert(m.f32); sc_assert(m.f33); sc_assert(m.f34); sc_assert(m.f35); sc_assert(m.f36); sc_assert(m.f37); sc_assert(m.f38); sc_assert(m.f39); sc_assert(m.f40); sc_assert(m.f41); cout << endl << "Success" << endl; return 0; }
vineodd/PIMSim
GEM5Simulation/gem5/src/systemc/tests/systemc/1666-2011-compliance/sync_reset/sync_reset.cpp
C++
gpl-3.0
11,660
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blimp/common/compositor/reference_tracker.h" #include <stdint.h> #include <algorithm> #include <unordered_set> #include <vector> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace blimp { namespace { class ReferenceTrackerTest : public testing::Test { public: ReferenceTrackerTest() = default; ~ReferenceTrackerTest() override = default; protected: ReferenceTracker tracker_; std::vector<uint32_t> added_; std::vector<uint32_t> removed_; private: DISALLOW_COPY_AND_ASSIGN(ReferenceTrackerTest); }; TEST_F(ReferenceTrackerTest, SingleItemCommitFlow) { tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemMultipleTimesInSingleCommit) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemMultipleTimesAcrossCommits) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, SingleItemComplexInteractions) { uint32_t item = 1; tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item); tracker_.IncrementRefCount(item); tracker_.DecrementRefCount(item); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item)); } TEST_F(ReferenceTrackerTest, MultipleItems) { uint32_t item1 = 1; uint32_t item2 = 2; uint32_t item3 = 3; tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.IncrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1, item2, item3)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item3)); removed_.clear(); tracker_.DecrementRefCount(item2); tracker_.IncrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item3)); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item2)); added_.clear(); removed_.clear(); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item2)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.DecrementRefCount(item1); tracker_.DecrementRefCount(item2); tracker_.DecrementRefCount(item3); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item1, item2, item3)); } TEST_F(ReferenceTrackerTest, MultipleItemsWithClear) { uint32_t item1 = 1; uint32_t item2 = 2; tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.ClearRefCounts(); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_TRUE(added_.empty()); EXPECT_TRUE(removed_.empty()); tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item1); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1)); EXPECT_TRUE(removed_.empty()); added_.clear(); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item2)); EXPECT_THAT(removed_, testing::UnorderedElementsAre(item1)); added_.clear(); removed_.clear(); tracker_.ClearRefCounts(); tracker_.IncrementRefCount(item1); tracker_.IncrementRefCount(item2); tracker_.CommitRefCounts(&added_, &removed_); EXPECT_THAT(added_, testing::UnorderedElementsAre(item1)); EXPECT_TRUE(removed_.empty()); added_.clear(); } } // namespace } // namespace blimp
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/blimp/common/compositor/reference_tracker_unittest.cc
C++
gpl-3.0
6,177
// UK lang variables tinyMCE.addI18n('pt.codehighlighting',{ codehighlighting_desc : "Code Highlighting", codehighlighting_title : "Code Highlighting", codehighlighting_langaugepicker : "Choose the language", codehighlighting_pagecode : "Paste your code here", codehighlighting_button_desc: "Insert code", codehighlighting_nogutter : "No Gutter", codehighlighting_collapse : "Collapse", codehighlighting_nocontrols : "No Controls", codehighlighting_showcolumns : "Show Columns" });
ahilles107/Newscoop
newscoop/js/tinymce/plugins/codehighlighting/langs/pt.js
JavaScript
gpl-3.0
494
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. var a = [0,1,2,3]; assertEquals(0, a.length = 0); assertEquals('undefined', typeof a[0]); assertEquals('undefined', typeof a[1]); assertEquals('undefined', typeof a[2]); assertEquals('undefined', typeof a[3]); var a = [0,1,2,3]; assertEquals(2, a.length = 2); assertEquals(0, a[0]); assertEquals(1, a[1]); assertEquals('undefined', typeof a[2]); assertEquals('undefined', typeof a[3]); var a = new Array(); a[0] = 0; a[1000] = 1000; a[1000000] = 1000000; a[2000000] = 2000000; assertEquals(2000001, a.length); assertEquals(0, a.length = 0); assertEquals(0, a.length); assertEquals('undefined', typeof a[0]); assertEquals('undefined', typeof a[1000]); assertEquals('undefined', typeof a[1000000]); assertEquals('undefined', typeof a[2000000]); var a = new Array(); a[0] = 0; a[1000] = 1000; a[1000000] = 1000000; a[2000000] = 2000000; assertEquals(2000001, a.length); assertEquals(2000, a.length = 2000); assertEquals(2000, a.length); assertEquals(0, a[0]); assertEquals(1000, a[1000]); assertEquals('undefined', typeof a[1000000]); assertEquals('undefined', typeof a[2000000]); var a = new Array(); a[Math.pow(2,31)-1] = 0; a[Math.pow(2,30)-1] = 0; assertEquals(Math.pow(2,31), a.length); var a = new Array(); a[0] = 0; a[1000] = 1000; a[Math.pow(2,30)-1] = Math.pow(2,30)-1; a[Math.pow(2,31)-1] = Math.pow(2,31)-1; a[Math.pow(2,32)-2] = Math.pow(2,32)-2; assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]); assertEquals(Math.pow(2,31)-1, a[Math.pow(2,31)-1]); assertEquals(Math.pow(2,32)-2, a[Math.pow(2,32)-2]); assertEquals(Math.pow(2,32)-1, a.length); assertEquals(Math.pow(2,30) + 1, a.length = Math.pow(2,30)+1); // not a smi! assertEquals(Math.pow(2,30)+1, a.length); assertEquals(0, a[0]); assertEquals(1000, a[1000]); assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]); assertEquals('undefined', typeof a[Math.pow(2,31)-1]); assertEquals('undefined', typeof a[Math.pow(2,32)-2], "top"); var a = new Array(); assertEquals(Object(12), a.length = new Number(12)); assertEquals(12, a.length); Number.prototype.valueOf = function() { return 10; } var n = new Number(100); assertEquals(n, a.length = n); assertEquals(10, a.length); n.valueOf = function() { return 20; } assertEquals(n, a.length = n); assertEquals(20, a.length); var o = { length: -23 }; Array.prototype.pop.apply(o); assertEquals(4294967272, o.length); // Check case of compiled stubs. var a = []; for (var i = 0; i < 7; i++) { assertEquals(3, a.length = 3); var t = 239; t = a.length = 7; assertEquals(7, t); } (function () { "use strict"; var frozen_object = Object.freeze({__proto__:[]}); assertThrows(function () { frozen_object.length = 10 }); })();
victorzhao/miniblink49
v8_4_5/test/mjsunit/array-length.js
JavaScript
gpl-3.0
4,264
// // DO NOT REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // // @Authors: // christiank // dinwiggy // // Copyright 2004-2010 by OM International // // This file is part of OpenPetra.org. // // OpenPetra.org is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // OpenPetra.org is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OpenPetra.org. If not, see <http://www.gnu.org/licenses/>. // using System; using System.Data; using System.Windows.Forms; using Ict.Common; using Ict.Common.Controls; using Ict.Common.Remoting.Client; using Ict.Common.Verification; using Ict.Petra.Client.App.Core; using Ict.Petra.Client.App.Core.RemoteObjects; using Ict.Petra.Client.MPartner; using Ict.Petra.Shared; using Ict.Petra.Shared.Interfaces.MPartner; using Ict.Petra.Shared.MCommon; using Ict.Petra.Shared.MCommon.Data; using Ict.Petra.Shared.MPartner.Partner.Data; using Ict.Petra.Shared.MPersonnel; using Ict.Petra.Shared.MPersonnel.Personnel.Data; using Ict.Petra.Shared.MPersonnel.Person; using Ict.Petra.Shared.MPersonnel.Validation; namespace Ict.Petra.Client.MPartner.Gui { public partial class TUC_IndividualData_PreviousExperience { /// <summary>holds a reference to the Proxy System.Object of the Serverside UIConnector</summary> private IPartnerUIConnectorsPartnerEdit FPartnerEditUIConnector; #region Properties /// <summary>used for passing through the Clientside Proxy for the UIConnector</summary> public IPartnerUIConnectorsPartnerEdit PartnerEditUIConnector { get { return FPartnerEditUIConnector; } set { FPartnerEditUIConnector = value; } } #endregion #region Events /// <summary>todoComment</summary> public event TRecalculateScreenPartsEventHandler RecalculateScreenParts; #endregion /// <summary> /// todoComment /// </summary> public void SpecialInitUserControl(IndividualDataTDS AMainDS) { FMainDS = AMainDS; LoadDataOnDemand(); } /// <summary> /// add a new batch /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewRecord(System.Object sender, EventArgs e) { this.CreateNewPmPastExperience(); } // Sets the key for a new row private void NewRowManual(ref PmPastExperienceRow ARow) { ARow.PartnerKey = FMainDS.PPerson[0].PartnerKey; ARow.Key = Convert.ToInt32(TRemote.MCommon.WebConnectors.GetNextSequence(TSequenceNames.seq_past_experience)); } /// <summary> /// Performs checks to determine whether a deletion of the current /// row is permissable /// </summary> /// <param name="ARowToDelete">the currently selected row to be deleted</param> /// <param name="ADeletionQuestion">can be changed to a context-sensitive deletion confirmation question</param> /// <returns>true if user is permitted and able to delete the current row</returns> private bool PreDeleteManual(PmPastExperienceRow ARowToDelete, ref string ADeletionQuestion) { /*Code to execute before the delete can take place*/ ADeletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?"); ADeletionQuestion += String.Format("{0}{0}({1} {2}, {3} {4})", Environment.NewLine, lblLocation.Text, txtLocation.Text, lblRole.Text, txtRole.Text); return true; } /// <summary> /// Code to be run after the deletion process /// </summary> /// <param name="ARowToDelete">the row that was/was to be deleted</param> /// <param name="AAllowDeletion">whether or not the user was permitted to delete</param> /// <param name="ADeletionPerformed">whether or not the deletion was performed successfully</param> /// <param name="ACompletionMessage">if specified, is the deletion completion message</param> private void PostDeleteManual(PmPastExperienceRow ARowToDelete, bool AAllowDeletion, bool ADeletionPerformed, string ACompletionMessage) { if (ADeletionPerformed) { DoRecalculateScreenParts(); } } private void DoRecalculateScreenParts() { OnRecalculateScreenParts(new TRecalculateScreenPartsEventArgs() { ScreenPart = TScreenPartEnum.spCounters }); } private void ShowDetailsManual(PmPastExperienceRow ARow) { // In theory, the next Method call could be done in Methods NewRowManual; however, NewRowManual runs before // the Row is actually added and this would result in the Count to be one too less, so we do the Method call here, short // of a non-existing 'AfterNewRowManual' Method.... DoRecalculateScreenParts(); } /// <summary> /// Gets the data from all controls on this UserControl. /// The data is stored in the DataTables/DataColumns to which the Controls /// are mapped. /// </summary> public void GetDataFromControls2() { // Get data out of the Controls only if there is at least one row of data (Note: Column Headers count as one row) if (grdDetails.Rows.Count > 1) { GetDataFromControls(); } } /// <summary> /// This Method is needed for UserControls who get dynamicly loaded on TabPages. /// Since we don't have controls on this UserControl that need adjusting after resizing /// on 'Large Fonts (120 DPI)', we don't need to do anything here. /// </summary> public void AdjustAfterResizing() { } /// <summary> /// called for HereFlag event for work location check box /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HereFlagChanged(object sender, EventArgs e) { if (this.chkHereFlag.Checked) { chkSimilarOrgFlag.Enabled = false; chkSimilarOrgFlag.Checked = true; } else { chkSimilarOrgFlag.Enabled = true; chkSimilarOrgFlag.Checked = false; } } /// <summary> /// Loads Previous Experience Data from Petra Server into FMainDS, if not already loaded. /// </summary> /// <returns>true if successful, otherwise false.</returns> private Boolean LoadDataOnDemand() { Boolean ReturnValue; try { // Make sure that Typed DataTables are already there at Client side if (FMainDS.PmPastExperience == null) { FMainDS.Tables.Add(new PmPastExperienceTable()); FMainDS.InitVars(); } if (TClientSettings.DelayedDataLoading && (FMainDS.PmPastExperience.Rows.Count == 0)) { FMainDS.Merge(FPartnerEditUIConnector.GetDataPersonnelIndividualData(TIndividualDataItemEnum.idiPreviousExperiences)); // Make DataRows unchanged if (FMainDS.PmPastExperience.Rows.Count > 0) { if (FMainDS.PmPastExperience.Rows[0].RowState != DataRowState.Added) { FMainDS.PmPastExperience.AcceptChanges(); } } } if (FMainDS.PmPastExperience.Rows.Count != 0) { ReturnValue = true; } else { ReturnValue = false; } } catch (System.NullReferenceException) { return false; } catch (Exception) { throw; } return ReturnValue; } private void OnRecalculateScreenParts(TRecalculateScreenPartsEventArgs e) { if (RecalculateScreenParts != null) { RecalculateScreenParts(this, e); } } private void ValidateDataDetailsManual(PmPastExperienceRow ARow) { TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection; TSharedPersonnelValidation_Personnel.ValidatePreviousExperienceManual(this, ARow, ref VerificationResultCollection, FValidationControlsDict); } } }
tpokorra/openpetra.js
csharp/ICT/Petra/Client/MPartner/Gui/UC_IndividualData_PreviousExperience.ManualCode.cs
C#
gpl-3.0
9,535
/* * This file is part of the PulseView project. * * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP #define PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP #include "segment.hpp" #include <utility> #include <vector> #include <QObject> using std::enable_shared_from_this; using std::pair; namespace AnalogSegmentTest { struct Basic; } namespace pv { namespace data { class Analog; class AnalogSegment : public Segment, public enable_shared_from_this<Segment> { Q_OBJECT public: struct EnvelopeSample { float min; float max; }; struct EnvelopeSection { uint64_t start; unsigned int scale; uint64_t length; EnvelopeSample *samples; }; private: struct Envelope { uint64_t length; uint64_t data_length; EnvelopeSample *samples; }; private: static const unsigned int ScaleStepCount = 10; static const int EnvelopeScalePower; static const int EnvelopeScaleFactor; static const float LogEnvelopeScaleFactor; static const uint64_t EnvelopeDataUnit; public: AnalogSegment(Analog& owner, uint32_t segment_id, uint64_t samplerate); virtual ~AnalogSegment(); void append_interleaved_samples(const float *data, size_t sample_count, size_t stride); float get_sample(int64_t sample_num) const; void get_samples(int64_t start_sample, int64_t end_sample, float* dest) const; const pair<float, float> get_min_max() const; float* get_iterator_value_ptr(SegmentDataIterator* it); void get_envelope_section(EnvelopeSection &s, uint64_t start, uint64_t end, float min_length) const; private: void reallocate_envelope(Envelope &e); void append_payload_to_envelope_levels(); private: Analog& owner_; struct Envelope envelope_levels_[ScaleStepCount]; float min_value_, max_value_; friend struct AnalogSegmentTest::Basic; }; } // namespace data } // namespace pv #endif // PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP
uwehermann/pulseview
pv/data/analogsegment.hpp
C++
gpl-3.0
2,563
/************************************************************************* * Copyright 2009-2014 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE * THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL, * COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE, * AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, * SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, * WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, * REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO * IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT * NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS. ************************************************************************/ package com.eucalyptus.ws; import javax.annotation.Nullable; import org.jboss.netty.handler.codec.http.HttpResponseStatus; public class EucalyptusRemoteFault extends Exception { String relatesTo; String action; String faultDetail; String faultCode; String faultString; HttpResponseStatus status; public EucalyptusRemoteFault( final String action, final String relatesTo, final String faultCode, final String faultString ) { super( String.format( "Action:%s Code:%s Id:%s Error: %s", action, faultCode, relatesTo, faultString ) ); this.relatesTo = relatesTo; this.action = action; this.faultCode = faultCode; this.faultString = faultString; } public EucalyptusRemoteFault( final String action, final String relatesTo, final String faultCode, final String faultString, final String faultDetail, final HttpResponseStatus status ) { this( action, relatesTo, faultCode, faultString ); this.faultDetail = faultDetail; this.status = status; } public String getRelatesTo( ) { return this.relatesTo; } public String getAction( ) { return this.action; } public String getFaultDetail( ) { return this.faultDetail; } public String getFaultCode( ) { return this.faultCode; } public String getFaultString( ) { return this.faultString; } @Nullable public HttpResponseStatus getStatus( ) { return status; } }
eethomas/eucalyptus
clc/modules/msgs/src/main/java/com/eucalyptus/ws/EucalyptusRemoteFault.java
Java
gpl-3.0
4,910
package org.ovirt.engine.ui.uicommonweb.models.providers; import org.ovirt.engine.core.common.action.AddExternalSubnetParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.network.NetworkView; import org.ovirt.engine.core.common.businessentities.network.ProviderNetwork; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.help.HelpTag; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; public class NewExternalSubnetModel extends Model { private EntityModel<NetworkView> network; private ExternalSubnetModel subnetModel; private final SearchableListModel sourceModel; public NewExternalSubnetModel(NetworkView network, SearchableListModel sourceModel) { this.sourceModel = sourceModel; setNetwork(new EntityModel<NetworkView>()); getNetwork().setEntity(network); setSubnetModel(new ExternalSubnetModel()); getSubnetModel().setExternalNetwork(network.getProvidedBy()); setTitle(ConstantsManager.getInstance().getConstants().newExternalSubnetTitle()); setHelpTag(HelpTag.new_external_subnet); setHashName("new_external_subnet"); //$NON-NLS-1$ initCommands(); } protected void initCommands() { UICommand okCommand = UICommand.createDefaultOkUiCommand("OnSave", this); //$NON-NLS-1$ getCommands().add(okCommand); UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$ getCommands().add(cancelCommand); } public EntityModel<NetworkView> getNetwork() { return network; } private void setNetwork(EntityModel<NetworkView> network) { this.network = network; } public ExternalSubnetModel getSubnetModel() { return subnetModel; } private void setSubnetModel(ExternalSubnetModel subnetModel) { this.subnetModel = subnetModel; } private void onSave() { if (!validate()) { return; } // Save changes. flush(); startProgress(null); ProviderNetwork providedBy = getNetwork().getEntity().getProvidedBy(); Frontend.getInstance().runAction(VdcActionType.AddSubnetToProvider, new AddExternalSubnetParameters(getSubnetModel().getSubnet(), providedBy.getProviderId(), providedBy.getExternalId()), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); stopProgress(); if (returnValue != null && returnValue.getSucceeded()) { cancel(); } } }, this, true); } public void flush() { getSubnetModel().flush(); } private void cancel() { sourceModel.setWindow(null); } @Override public void executeCommand(UICommand command) { super.executeCommand(command); if ("OnSave".equals(command.getName())) { //$NON-NLS-1$ onSave(); } else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$ cancel(); } } public boolean validate() { return getSubnetModel().validate(); } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/providers/NewExternalSubnetModel.java
Java
gpl-3.0
3,910
<?php /* * This file is part of Phraseanet * * (c) 2005-2016 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Guzzle\Http\Url; class media_adapter extends media_abstract { /** * Constructor * * Enforces Url to de defined * * @param int $width * @param int $height * @param Url $url */ public function __construct($width, $height, Url $url) { parent::__construct($width, $height, $url); } }
nmaillat/Phraseanet
lib/classes/media/adapter.php
PHP
gpl-3.0
556
<?php /** * File: table_easywi_statistics.php. * Author: Ulrich Block * Date: 17.10.15 * Contact: <ulrich.block@easy-wi.com> * * This file is part of Easy-WI. * * Easy-WI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Easy-WI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Easy-WI. If not, see <http://www.gnu.org/licenses/>. * * Diese Datei ist Teil von Easy-WI. * * Easy-WI ist Freie Software: Sie koennen es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder spaeteren * veroeffentlichten Version, weiterverbreiten und/oder modifizieren. * * Easy-WI wird in der Hoffnung, dass es nuetzlich sein wird, aber * OHNE JEDE GEWAEHELEISTUNG, bereitgestellt; sogar ohne die implizite * Gewaehrleistung der MARKTFAEHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License fuer weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. */ $defined['easywi_statistics'] = array( 'gameMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterServerAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterSlotsAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNoPassword' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNoTag' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNotRunning' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterDBAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBSpaceUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsCompleted' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsInProcess' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsNew' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userAmount' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userAmountActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterVserverAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterServerAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterSlotsAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverTrafficAllowed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverTrafficUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterSpaceAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterVhostAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceGiven' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceGivenActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userID' => array("Type"=>"int(10) unsigned","Null"=>"NO","Key"=>"PRI","Default"=>"0","Extra"=>""), 'statDate' => array("Type"=>"date","Null"=>"NO","Key"=>"PRI","Default"=>"2015-01-01","Extra"=>""), 'countUpdates' => array("Type"=>"int(10) unsigned","Null"=>"NO","Key"=>"","Default"=>"0","Extra"=>"") );
TR-Host/easy-wi-mirror
web/stuff/data/table_easywi_statistics.php
PHP
gpl-3.0
8,010
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "calendar.h" #include "ptreferential/ptreferential.h" #include "type/data.h" namespace navitia { namespace calendar { type::Indexes Calendar::get_calendars(const std::string& filter, const std::vector<std::string>& forbidden_uris, const type::Data &d, const boost::gregorian::date_period filter_period, const boost::posix_time::ptime){ type::Indexes to_return; to_return = ptref::make_query(type::Type_e::Calendar, filter, forbidden_uris, d); if (to_return.empty() || (filter_period.begin().is_not_a_date())) { return to_return; } type::Indexes indexes; for (type::idx_t idx : to_return) { navitia::type::Calendar* cal = d.pt_data->calendars[idx]; for (const boost::gregorian::date_period per : cal->active_periods) { if (filter_period.begin() == filter_period.end()) { if (per.contains(filter_period.begin())) { indexes.insert(cal->idx); break; } } else { if (filter_period.intersects(per)) { indexes.insert(cal->idx); break; } } } } return indexes; } } }
TeXitoi/navitia
source/calendar/calendar.cpp
C++
agpl-3.0
2,441
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 OpenERP S.A (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name' : 'Portal', 'version': '1.0', 'depends': [ 'base', 'share', 'auth_signup', ], 'author': 'OpenERP SA', 'category': 'Portal', 'description': """ Customize access to your OpenERP database to external users by creating portals. ================================================================================ A portal defines a specific user menu and access rights for its members. This menu can ben seen by portal members, public users and any other user that have the access to technical features (e.g. the administrator). Also, each portal member is linked to a specific partner. The module also associates user groups to the portal users (adding a group in the portal automatically adds it to the portal users, etc). That feature is very handy when used in combination with the module 'share'. """, 'website': 'http://www.openerp.com', 'data': [ 'portal_data.xml', 'portal_view.xml', 'wizard/portal_wizard_view.xml', 'wizard/share_wizard_view.xml', 'security/ir.model.access.csv', ], 'demo': ['portal_demo.xml'], 'css': ['static/src/css/portal.css'], 'auto_install': True, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
poiesisconsulting/openerp-restaurant
portal/__openerp__.py
Python
agpl-3.0
2,288
""" Unit tests for the asset upload endpoint. """ from datetime import datetime from io import BytesIO from pytz import UTC import json from django.conf import settings from contentstore.tests.utils import CourseTestCase from contentstore.views import assets from contentstore.utils import reverse_course_url from xmodule.assetstore.assetmgr import AssetMetadataFoundTemporary from xmodule.assetstore import AssetMetadata from xmodule.contentstore.content import StaticContent from xmodule.contentstore.django import contentstore from xmodule.modulestore.django import modulestore from xmodule.modulestore.xml_importer import import_course_from_xml from django.test.utils import override_settings from opaque_keys.edx.locations import SlashSeparatedCourseKey, AssetLocation import mock from ddt import ddt from ddt import data TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT MAX_FILE_SIZE = settings.MAX_ASSET_UPLOAD_FILE_SIZE_IN_MB * 1000 ** 2 class AssetsTestCase(CourseTestCase): """ Parent class for all asset tests. """ def setUp(self): super(AssetsTestCase, self).setUp() self.url = reverse_course_url('assets_handler', self.course.id) def upload_asset(self, name="asset-1", extension=".txt"): """ Post to the asset upload url """ f = self.get_sample_asset(name, extension) return self.client.post(self.url, {"name": name, "file": f}) def get_sample_asset(self, name, extension=".txt"): """Returns an in-memory file with the given name for testing""" f = BytesIO(name) f.name = name + extension return f class BasicAssetsTestCase(AssetsTestCase): """ Test getting assets via html w/o additional args """ def test_basic(self): resp = self.client.get(self.url, HTTP_ACCEPT='text/html') self.assertEquals(resp.status_code, 200) def test_static_url_generation(self): course_key = SlashSeparatedCourseKey('org', 'class', 'run') location = course_key.make_asset_key('asset', 'my_file_name.jpg') path = StaticContent.get_static_path_from_location(location) self.assertEquals(path, '/static/my_file_name.jpg') def test_pdf_asset(self): module_store = modulestore() course_items = import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=contentstore(), verbose=True ) course = course_items[0] url = reverse_course_url('assets_handler', course.id) # Test valid contentType for pdf asset (textbook.pdf) resp = self.client.get(url, HTTP_ACCEPT='application/json') self.assertContains(resp, "/c4x/edX/toy/asset/textbook.pdf") asset_location = AssetLocation.from_deprecated_string('/c4x/edX/toy/asset/textbook.pdf') content = contentstore().find(asset_location) # Check after import textbook.pdf has valid contentType ('application/pdf') # Note: Actual contentType for textbook.pdf in asset.json is 'text/pdf' self.assertEqual(content.content_type, 'application/pdf') class PaginationTestCase(AssetsTestCase): """ Tests the pagination of assets returned from the REST API. """ def test_json_responses(self): """ Test the ajax asset interfaces """ self.upload_asset("asset-1") self.upload_asset("asset-2") self.upload_asset("asset-3") self.upload_asset("asset-4", ".odt") # Verify valid page requests self.assert_correct_asset_response(self.url, 0, 4, 4) self.assert_correct_asset_response(self.url + "?page_size=2", 0, 2, 4) self.assert_correct_asset_response( self.url + "?page_size=2&page=1", 2, 2, 4) self.assert_correct_sort_response(self.url, 'date_added', 'asc') self.assert_correct_sort_response(self.url, 'date_added', 'desc') self.assert_correct_sort_response(self.url, 'display_name', 'asc') self.assert_correct_sort_response(self.url, 'display_name', 'desc') self.assert_correct_filter_response(self.url, 'asset_type', '') self.assert_correct_filter_response(self.url, 'asset_type', 'OTHER') self.assert_correct_filter_response( self.url, 'asset_type', 'Documents') # Verify querying outside the range of valid pages self.assert_correct_asset_response( self.url + "?page_size=2&page=-1", 0, 2, 4) self.assert_correct_asset_response( self.url + "?page_size=2&page=2", 2, 2, 4) self.assert_correct_asset_response( self.url + "?page_size=3&page=1", 3, 1, 4) @mock.patch('xmodule.contentstore.mongo.MongoContentStore.get_all_content_for_course') def test_mocked_filtered_response(self, mock_get_all_content_for_course): """ Test the ajax asset interfaces """ asset_key = self.course.id.make_asset_key( AssetMetadata.GENERAL_ASSET_TYPE, 'test.jpg') upload_date = datetime(2015, 1, 12, 10, 30, tzinfo=UTC) thumbnail_location = [ 'c4x', 'edX', 'toy', 'thumbnail', 'test_thumb.jpg', None] mock_get_all_content_for_course.return_value = [ [ { "asset_key": asset_key, "displayname": "test.jpg", "contentType": "image/jpg", "url": "/c4x/A/CS102/asset/test.jpg", "uploadDate": upload_date, "id": "/c4x/A/CS102/asset/test.jpg", "portable_url": "/static/test.jpg", "thumbnail": None, "thumbnail_location": thumbnail_location, "locked": None } ], 1 ] # Verify valid page requests self.assert_correct_filter_response(self.url, 'asset_type', 'OTHER') def assert_correct_asset_response(self, url, expected_start, expected_length, expected_total): """ Get from the url and ensure it contains the expected number of responses """ resp = self.client.get(url, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) assets_response = json_response['assets'] self.assertEquals(json_response['start'], expected_start) self.assertEquals(len(assets_response), expected_length) self.assertEquals(json_response['totalCount'], expected_total) def assert_correct_sort_response(self, url, sort, direction): """ Get from the url w/ a sort option and ensure items honor that sort """ resp = self.client.get( url + '?sort=' + sort + '&direction=' + direction, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) assets_response = json_response['assets'] name1 = assets_response[0][sort] name2 = assets_response[1][sort] name3 = assets_response[2][sort] if direction == 'asc': self.assertLessEqual(name1, name2) self.assertLessEqual(name2, name3) else: self.assertGreaterEqual(name1, name2) self.assertGreaterEqual(name2, name3) def assert_correct_filter_response(self, url, filter_type, filter_value): """ Get from the url w/ a filter option and ensure items honor that filter """ requested_file_types = settings.FILES_AND_UPLOAD_TYPE_FILTERS.get( filter_value, None) resp = self.client.get( url + '?' + filter_type + '=' + filter_value, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) assets_response = json_response['assets'] if filter_value is not '': content_types = [asset['content_type'].lower() for asset in assets_response] if filter_value is 'OTHER': all_file_type_extensions = [] for file_type in settings.FILES_AND_UPLOAD_TYPE_FILTERS: all_file_type_extensions.extend(file_type) for content_type in content_types: self.assertNotIn(content_type, all_file_type_extensions) else: for content_type in content_types: self.assertIn(content_type, requested_file_types) @ddt class UploadTestCase(AssetsTestCase): """ Unit tests for uploading a file """ def setUp(self): super(UploadTestCase, self).setUp() self.url = reverse_course_url('assets_handler', self.course.id) def test_happy_path(self): resp = self.upload_asset() self.assertEquals(resp.status_code, 200) def test_no_file(self): resp = self.client.post(self.url, {"name": "file.txt"}, "application/json") self.assertEquals(resp.status_code, 400) @data( (int(MAX_FILE_SIZE / 2.0), "small.file.test", 200), (MAX_FILE_SIZE, "justequals.file.test", 200), (MAX_FILE_SIZE + 90, "large.file.test", 413), ) @mock.patch('contentstore.views.assets.get_file_size') def test_file_size(self, case, get_file_size): max_file_size, name, status_code = case get_file_size.return_value = max_file_size f = self.get_sample_asset(name=name) resp = self.client.post(self.url, { "name": name, "file": f }) self.assertEquals(resp.status_code, status_code) class DownloadTestCase(AssetsTestCase): """ Unit tests for downloading a file. """ def setUp(self): super(DownloadTestCase, self).setUp() self.url = reverse_course_url('assets_handler', self.course.id) # First, upload something. self.asset_name = 'download_test' resp = self.upload_asset(self.asset_name) self.assertEquals(resp.status_code, 200) self.uploaded_url = json.loads(resp.content)['asset']['url'] def test_download(self): # Now, download it. resp = self.client.get(self.uploaded_url, HTTP_ACCEPT='text/html') self.assertEquals(resp.status_code, 200) self.assertEquals(resp.content, self.asset_name) def test_download_not_found_throw(self): url = self.uploaded_url.replace(self.asset_name, 'not_the_asset_name') resp = self.client.get(url, HTTP_ACCEPT='text/html') self.assertEquals(resp.status_code, 404) def test_metadata_found_in_modulestore(self): # Insert asset metadata into the modulestore (with no accompanying asset). asset_key = self.course.id.make_asset_key(AssetMetadata.GENERAL_ASSET_TYPE, 'pic1.jpg') asset_md = AssetMetadata(asset_key, { 'internal_name': 'EKMND332DDBK', 'basename': 'pix/archive', 'locked': False, 'curr_version': '14', 'prev_version': '13' }) modulestore().save_asset_metadata(asset_md, 15) # Get the asset metadata and have it be found in the modulestore. # Currently, no asset metadata should be found in the modulestore. The code is not yet storing it there. # If asset metadata *is* found there, an exception is raised. This test ensures the exception is indeed raised. # THIS IS TEMPORARY. Soon, asset metadata *will* be stored in the modulestore. with self.assertRaises((AssetMetadataFoundTemporary, NameError)): self.client.get(unicode(asset_key), HTTP_ACCEPT='text/html') class AssetToJsonTestCase(AssetsTestCase): """ Unit test for transforming asset information into something we can send out to the client via JSON. """ @override_settings(LMS_BASE="lms_base_url") def test_basic(self): upload_date = datetime(2013, 6, 1, 10, 30, tzinfo=UTC) content_type = 'image/jpg' course_key = SlashSeparatedCourseKey('org', 'class', 'run') location = course_key.make_asset_key('asset', 'my_file_name.jpg') thumbnail_location = course_key.make_asset_key('thumbnail', 'my_file_name_thumb.jpg') # pylint: disable=protected-access output = assets._get_asset_json("my_file", content_type, upload_date, location, thumbnail_location, True) self.assertEquals(output["display_name"], "my_file") self.assertEquals(output["date_added"], "Jun 01, 2013 at 10:30 UTC") self.assertEquals(output["url"], "/c4x/org/class/asset/my_file_name.jpg") self.assertEquals(output["external_url"], "lms_base_url/c4x/org/class/asset/my_file_name.jpg") self.assertEquals(output["portable_url"], "/static/my_file_name.jpg") self.assertEquals(output["thumbnail"], "/c4x/org/class/thumbnail/my_file_name_thumb.jpg") self.assertEquals(output["id"], unicode(location)) self.assertEquals(output['locked'], True) output = assets._get_asset_json("name", content_type, upload_date, location, None, False) self.assertIsNone(output["thumbnail"]) class LockAssetTestCase(AssetsTestCase): """ Unit test for locking and unlocking an asset. """ def test_locking(self): """ Tests a simple locking and unlocking of an asset in the toy course. """ def verify_asset_locked_state(locked): """ Helper method to verify lock state in the contentstore """ asset_location = StaticContent.get_location_from_path('/c4x/edX/toy/asset/sample_static.txt') content = contentstore().find(asset_location) self.assertEqual(content.locked, locked) def post_asset_update(lock, course): """ Helper method for posting asset update. """ content_type = 'application/txt' upload_date = datetime(2013, 6, 1, 10, 30, tzinfo=UTC) asset_location = course.id.make_asset_key('asset', 'sample_static.txt') url = reverse_course_url('assets_handler', course.id, kwargs={'asset_key_string': unicode(asset_location)}) resp = self.client.post( url, # pylint: disable=protected-access json.dumps(assets._get_asset_json( "sample_static.txt", content_type, upload_date, asset_location, None, lock)), "application/json" ) self.assertEqual(resp.status_code, 201) return json.loads(resp.content) # Load the toy course. module_store = modulestore() course_items = import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=contentstore(), verbose=True ) course = course_items[0] verify_asset_locked_state(False) # Lock the asset resp_asset = post_asset_update(True, course) self.assertTrue(resp_asset['locked']) verify_asset_locked_state(True) # Unlock the asset resp_asset = post_asset_update(False, course) self.assertFalse(resp_asset['locked']) verify_asset_locked_state(False)
beni55/edx-platform
cms/djangoapps/contentstore/views/tests/test_assets.py
Python
agpl-3.0
15,204
define(['angular'], function(angular) { 'use strict'; return angular.module('superdesk.services.storage', []) /** * LocalStorage wrapper * * it stores data as json to keep its type */ .service('storage', function() { /** * Get item from storage * * @param {string} key * @returns {mixed} */ this.getItem = function(key) { return angular.fromJson(localStorage.getItem(key)); }; /** * Set storage item * * @param {string} key * @param {mixed} data */ this.setItem = function(key, data) { localStorage.setItem(key, angular.toJson(data)); }; /** * Remove item from storage * * @param {string} key */ this.removeItem = function(key) { localStorage.removeItem(key); }; /** * Remove all items from storage */ this.clear = function() { localStorage.clear(); }; }); });
plamut/superdesk
client/app/scripts/superdesk/services/storage.js
JavaScript
agpl-3.0
1,250
<?php /* * StatusNet - the distributed open-source microblogging tool * Copyright (C) 2008-2010, StatusNet, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('STATUSNET')) { exit(1); } /** * Utility class to wrap basic oEmbed lookups. * * Blacklisted hosts will use an alternate lookup method: * - Twitpic * * Whitelisted hosts will use known oEmbed API endpoints: * - Flickr, YFrog * * Sites that provide discovery links will use them directly; a bug * in use of discovery links with query strings is worked around. * * Others will fall back to oohembed (unless disabled). * The API endpoint can be configured or disabled through config * as 'oohembed'/'endpoint'. */ class oEmbedHelper { protected static $apiMap = array( 'flickr.com' => 'http://www.flickr.com/services/oembed/', 'yfrog.com' => 'http://www.yfrog.com/api/oembed', 'youtube.com' => 'http://www.youtube.com/oembed', 'viddler.com' => 'http://lab.viddler.com/services/oembed/', 'qik.com' => 'http://qik.com/api/oembed.json', 'revision3.com' => 'http://revision3.com/api/oembed/', 'hulu.com' => 'http://www.hulu.com/api/oembed.json', 'vimeo.com' => 'http://www.vimeo.com/api/oembed.json', 'my.opera.com' => 'http://my.opera.com/service/oembed', ); protected static $functionMap = array( 'twitpic.com' => 'oEmbedHelper::twitPic', ); /** * Perform or fake an oEmbed lookup for the given resource. * * Some known hosts are whitelisted with API endpoints where we * know they exist but autodiscovery data isn't available. * If autodiscovery links are missing and we don't recognize the * host, we'll pass it to noembed.com's public service which * will either proxy or fake info on a lot of sites. * * A few hosts are blacklisted due to known problems with oohembed, * in which case we'll look up the info another way and return * equivalent data. * * Throws exceptions on failure. * * @param string $url * @param array $params * @return object */ public static function getObject($url, $params=array()) { $host = parse_url($url, PHP_URL_HOST); if (substr($host, 0, 4) == 'www.') { $host = substr($host, 4); } common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url); // You can fiddle with the order of discovery -- either skipping // some types or re-ordering them. $order = common_config('oembed', 'order'); foreach ($order as $method) { switch ($method) { case 'built-in': common_log(LOG_INFO, 'Considering built-in oEmbed methods...'); // Blacklist: systems with no oEmbed API of their own, which are // either missing from or broken on noembed.com's proxy. // we know how to look data up in another way... if (array_key_exists($host, self::$functionMap)) { common_log(LOG_INFO, 'We have a built-in method for ' . $host); $func = self::$functionMap[$host]; return call_user_func($func, $url, $params); } break; case 'well-known': common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...'); // Whitelist: known API endpoints for sites that don't provide discovery... if (array_key_exists($host, self::$apiMap)) { $api = self::$apiMap[$host]; common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"'); break 2; } break; case 'discovery': try { common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.'); $api = self::discover($url); common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url); break 2; } catch (Exception $e) { common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.'); // Just ignore it! } break; case 'service': $api = common_config('oembed', 'endpoint'); common_log(LOG_INFO, 'Using service API endpoint ' . $api); break 2; break; } } if (empty($api)) { // TRANS: Server exception thrown in oEmbed action if no API endpoint is available. throw new ServerException(_('No oEmbed API endpoint available.')); } return self::getObjectFrom($api, $url, $params); } /** * Perform basic discovery. * @return string */ static function discover($url) { // @fixme ideally skip this for non-HTML stuff! $body = self::http($url); return self::discoverFromHTML($url, $body); } /** * Partially ripped from OStatus' FeedDiscovery class. * * @param string $url source URL, used to resolve relative links * @param string $body HTML body text * @return mixed string with URL or false if no target found */ static function discoverFromHTML($url, $body) { // DOMDocument::loadHTML may throw warnings on unrecognized elements, // and notices on unrecognized namespaces. $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE)); $dom = new DOMDocument(); $ok = $dom->loadHTML($body); error_reporting($old); if (!$ok) { throw new oEmbedHelper_BadHtmlException(); } // Ok... now on to the links! $feeds = array( 'application/json+oembed' => false, ); $nodes = $dom->getElementsByTagName('link'); for ($i = 0; $i < $nodes->length; $i++) { $node = $nodes->item($i); if ($node->hasAttributes()) { $rel = $node->attributes->getNamedItem('rel'); $type = $node->attributes->getNamedItem('type'); $href = $node->attributes->getNamedItem('href'); if ($rel && $type && $href) { $rel = array_filter(explode(" ", $rel->value)); $type = trim($type->value); $href = trim($href->value); if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) { // Save the first feed found of each type... $feeds[$type] = $href; } } } } // Return the highest-priority feed found foreach ($feeds as $type => $url) { if ($url) { return $url; } } throw new oEmbedHelper_DiscoveryException(); } /** * Actually do an oEmbed lookup to a particular API endpoint. * * @param string $api oEmbed API endpoint URL * @param string $url target URL to look up info about * @param array $params * @return object */ static function getObjectFrom($api, $url, $params=array()) { $params['url'] = $url; $params['format'] = 'json'; $data = self::json($api, $params); return self::normalize($data); } /** * Normalize oEmbed format. * * @param object $orig * @return object */ static function normalize($orig) { $data = clone($orig); if (empty($data->type)) { throw new Exception('Invalid oEmbed data: no type field.'); } if ($data->type == 'image') { // YFrog does this. $data->type = 'photo'; } if (isset($data->thumbnail_url)) { if (!isset($data->thumbnail_width)) { // !?!?! $data->thumbnail_width = common_config('attachments', 'thumb_width'); $data->thumbnail_height = common_config('attachments', 'thumb_height'); } } return $data; } /** * Using a local function for twitpic lookups, as oohembed's adapter * doesn't return a valid result: * http://code.google.com/p/oohembed/issues/detail?id=19 * * This code fetches metadata from Twitpic's own API, and attempts * to guess proper thumbnail size from the original's size. * * @todo respect maxwidth and maxheight params * * @param string $url * @param array $params * @return object */ static function twitPic($url, $params=array()) { $matches = array(); if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) { $id = $matches[1]; } else { throw new Exception("Invalid twitpic URL"); } // Grab metadata from twitpic's API... // http://dev.twitpic.com/docs/2/media_show $data = self::json('http://api.twitpic.com/2/media/show.json', array('id' => $id)); $oembed = (object)array('type' => 'photo', 'url' => 'http://twitpic.com/show/full/' . $data->short_id, 'width' => $data->width, 'height' => $data->height); if (!empty($data->message)) { $oembed->title = $data->message; } // Thumbnail is cropped and scaled to 150x150 box: // http://dev.twitpic.com/docs/thumbnails/ $thumbSize = 150; $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id; $oembed->thumbnail_width = $thumbSize; $oembed->thumbnail_height = $thumbSize; return $oembed; } /** * Fetch some URL and return JSON data. * * @param string $url * @param array $params query-string params * @return object */ static protected function json($url, $params=array()) { $data = self::http($url, $params); return json_decode($data); } /** * Hit some web API and return data on success. * @param string $url * @param array $params * @return string */ static protected function http($url, $params=array()) { $client = HTTPClient::start(); if ($params) { $query = http_build_query($params, null, '&'); if (strpos($url, '?') === false) { $url .= '?' . $query; } else { $url .= '&' . $query; } } $response = $client->get($url); if ($response->isOk()) { return $response->getBody(); } else { throw new Exception('Bad HTTP response code: ' . $response->getStatus()); } } } class oEmbedHelper_Exception extends Exception { public function __construct($message = "", $code = 0, $previous = null) { parent::__construct($message, $code); } } class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception { function __construct($previous=null) { return parent::__construct('Bad HTML in discovery data.', 0, $previous); } } class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception { function __construct($previous=null) { return parent::__construct('No oEmbed discovery data.', 0, $previous); } }
gayathri6/stepstream_salute
lib_old/oembedhelper.php
PHP
agpl-3.0
12,206
// Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package netsync import ( "container/list" "net" "sync" "sync/atomic" "time" "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/mempool" peerpkg "github.com/btcsuite/btcd/peer" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" ) const ( // minInFlightBlocks is the minimum number of blocks that should be // in the request queue for headers-first mode before requesting // more. minInFlightBlocks = 10 // maxRejectedTxns is the maximum number of rejected transactions // hashes to store in memory. maxRejectedTxns = 1000 // maxRequestedBlocks is the maximum number of requested block // hashes to store in memory. maxRequestedBlocks = wire.MaxInvPerMsg // maxRequestedTxns is the maximum number of requested transactions // hashes to store in memory. maxRequestedTxns = wire.MaxInvPerMsg ) // zeroHash is the zero value hash (all zeros). It is defined as a convenience. var zeroHash chainhash.Hash // newPeerMsg signifies a newly connected peer to the block handler. type newPeerMsg struct { peer *peerpkg.Peer } // blockMsg packages a bitcoin block message and the peer it came from together // so the block handler has access to that information. type blockMsg struct { block *btcutil.Block peer *peerpkg.Peer reply chan struct{} } // invMsg packages a bitcoin inv message and the peer it came from together // so the block handler has access to that information. type invMsg struct { inv *wire.MsgInv peer *peerpkg.Peer } // headersMsg packages a bitcoin headers message and the peer it came from // together so the block handler has access to that information. type headersMsg struct { headers *wire.MsgHeaders peer *peerpkg.Peer } // donePeerMsg signifies a newly disconnected peer to the block handler. type donePeerMsg struct { peer *peerpkg.Peer } // txMsg packages a bitcoin tx message and the peer it came from together // so the block handler has access to that information. type txMsg struct { tx *btcutil.Tx peer *peerpkg.Peer reply chan struct{} } // getSyncPeerMsg is a message type to be sent across the message channel for // retrieving the current sync peer. type getSyncPeerMsg struct { reply chan int32 } // processBlockResponse is a response sent to the reply channel of a // processBlockMsg. type processBlockResponse struct { isOrphan bool err error } // processBlockMsg is a message type to be sent across the message channel // for requested a block is processed. Note this call differs from blockMsg // above in that blockMsg is intended for blocks that came from peers and have // extra handling whereas this message essentially is just a concurrent safe // way to call ProcessBlock on the internal block chain instance. type processBlockMsg struct { block *btcutil.Block flags blockchain.BehaviorFlags reply chan processBlockResponse } // isCurrentMsg is a message type to be sent across the message channel for // requesting whether or not the sync manager believes it is synced with the // currently connected peers. type isCurrentMsg struct { reply chan bool } // pauseMsg is a message type to be sent across the message channel for // pausing the sync manager. This effectively provides the caller with // exclusive access over the manager until a receive is performed on the // unpause channel. type pauseMsg struct { unpause <-chan struct{} } // headerNode is used as a node in a list of headers that are linked together // between checkpoints. type headerNode struct { height int32 hash *chainhash.Hash } // peerSyncState stores additional information that the SyncManager tracks // about a peer. type peerSyncState struct { syncCandidate bool requestQueue []*wire.InvVect requestedTxns map[chainhash.Hash]struct{} requestedBlocks map[chainhash.Hash]struct{} } // SyncManager is used to communicate block related messages with peers. The // SyncManager is started as by executing Start() in a goroutine. Once started, // it selects peers to sync from and starts the initial block download. Once the // chain is in sync, the SyncManager handles incoming block and header // notifications and relays announcements of new blocks to peers. type SyncManager struct { peerNotifier PeerNotifier started int32 shutdown int32 chain *blockchain.BlockChain txMemPool *mempool.TxPool chainParams *chaincfg.Params progressLogger *blockProgressLogger msgChan chan interface{} wg sync.WaitGroup quit chan struct{} // These fields should only be accessed from the blockHandler thread rejectedTxns map[chainhash.Hash]struct{} requestedTxns map[chainhash.Hash]struct{} requestedBlocks map[chainhash.Hash]struct{} syncPeer *peerpkg.Peer peerStates map[*peerpkg.Peer]*peerSyncState // The following fields are used for headers-first mode. headersFirstMode bool headerList *list.List startHeader *list.Element nextCheckpoint *chaincfg.Checkpoint } // resetHeaderState sets the headers-first mode state to values appropriate for // syncing from a new peer. func (sm *SyncManager) resetHeaderState(newestHash *chainhash.Hash, newestHeight int32) { sm.headersFirstMode = false sm.headerList.Init() sm.startHeader = nil // When there is a next checkpoint, add an entry for the latest known // block into the header pool. This allows the next downloaded header // to prove it links to the chain properly. if sm.nextCheckpoint != nil { node := headerNode{height: newestHeight, hash: newestHash} sm.headerList.PushBack(&node) } } // findNextHeaderCheckpoint returns the next checkpoint after the passed height. // It returns nil when there is not one either because the height is already // later than the final checkpoint or some other reason such as disabled // checkpoints. func (sm *SyncManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint { checkpoints := sm.chain.Checkpoints() if len(checkpoints) == 0 { return nil } // There is no next checkpoint if the height is already after the final // checkpoint. finalCheckpoint := &checkpoints[len(checkpoints)-1] if height >= finalCheckpoint.Height { return nil } // Find the next checkpoint. nextCheckpoint := finalCheckpoint for i := len(checkpoints) - 2; i >= 0; i-- { if height >= checkpoints[i].Height { break } nextCheckpoint = &checkpoints[i] } return nextCheckpoint } // startSync will choose the best peer among the available candidate peers to // download/sync the blockchain from. When syncing is already running, it // simply returns. It also examines the candidates for any which are no longer // candidates and removes them as needed. func (sm *SyncManager) startSync() { // Return now if we're already syncing. if sm.syncPeer != nil { return } // Once the segwit soft-fork package has activated, we only // want to sync from peers which are witness enabled to ensure // that we fully validate all blockchain data. segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit) if err != nil { log.Errorf("Unable to query for segwit soft-fork state: %v", err) return } best := sm.chain.BestSnapshot() var bestPeer *peerpkg.Peer for peer, state := range sm.peerStates { if !state.syncCandidate { continue } if segwitActive && !peer.IsWitnessEnabled() { log.Debugf("peer %v not witness enabled, skipping", peer) continue } // Remove sync candidate peers that are no longer candidates due // to passing their latest known block. NOTE: The < is // intentional as opposed to <=. While technically the peer // doesn't have a later block when it's equal, it will likely // have one soon so it is a reasonable choice. It also allows // the case where both are at 0 such as during regression test. if peer.LastBlock() < best.Height { state.syncCandidate = false continue } // TODO(davec): Use a better algorithm to choose the best peer. // For now, just pick the first available candidate. bestPeer = peer } // Start syncing from the best peer if one was selected. if bestPeer != nil { // Clear the requestedBlocks if the sync peer changes, otherwise // we may ignore blocks we need that the last sync peer failed // to send. sm.requestedBlocks = make(map[chainhash.Hash]struct{}) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Errorf("Failed to get block locator for the "+ "latest block: %v", err) return } log.Infof("Syncing to block height %d from peer %v", bestPeer.LastBlock(), bestPeer.Addr()) // When the current height is less than a known checkpoint we // can use block headers to learn about which blocks comprise // the chain up to the checkpoint and perform less validation // for them. This is possible since each header contains the // hash of the previous header and a merkle root. Therefore if // we validate all of the received headers link together // properly and the checkpoint hashes match, we can be sure the // hashes for the blocks in between are accurate. Further, once // the full blocks are downloaded, the merkle root is computed // and compared against the value in the header which proves the // full block hasn't been tampered with. // // Once we have passed the final checkpoint, or checkpoints are // disabled, use standard inv messages learn about the blocks // and fully validate them. Finally, regression test mode does // not support the headers-first approach so do normal block // downloads when in regression test mode. if sm.nextCheckpoint != nil && best.Height < sm.nextCheckpoint.Height && sm.chainParams != &chaincfg.RegressionNetParams { bestPeer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) sm.headersFirstMode = true log.Infof("Downloading headers for blocks %d to "+ "%d from peer %s", best.Height+1, sm.nextCheckpoint.Height, bestPeer.Addr()) } else { bestPeer.PushGetBlocksMsg(locator, &zeroHash) } sm.syncPeer = bestPeer } else { log.Warnf("No sync peer candidates available") } } // isSyncCandidate returns whether or not the peer is a candidate to consider // syncing from. func (sm *SyncManager) isSyncCandidate(peer *peerpkg.Peer) bool { // Typically a peer is not a candidate for sync if it's not a full node, // however regression test is special in that the regression tool is // not a full node and still needs to be considered a sync candidate. if sm.chainParams == &chaincfg.RegressionNetParams { // The peer is not a candidate if it's not coming from localhost // or the hostname can't be determined for some reason. host, _, err := net.SplitHostPort(peer.Addr()) if err != nil { return false } if host != "127.0.0.1" && host != "localhost" { return false } } else { // The peer is not a candidate for sync if it's not a full // node. Additionally, if the segwit soft-fork package has // activated, then the peer must also be upgraded. segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit) if err != nil { log.Errorf("Unable to query for segwit "+ "soft-fork state: %v", err) } nodeServices := peer.Services() if nodeServices&wire.SFNodeNetwork != wire.SFNodeNetwork || (segwitActive && !peer.IsWitnessEnabled()) { return false } } // Candidate if all checks passed. return true } // handleNewPeerMsg deals with new peers that have signalled they may // be considered as a sync peer (they have already successfully negotiated). It // also starts syncing if needed. It is invoked from the syncHandler goroutine. func (sm *SyncManager) handleNewPeerMsg(peer *peerpkg.Peer) { // Ignore if in the process of shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } log.Infof("New valid peer %s (%s)", peer, peer.UserAgent()) // Initialize the peer state isSyncCandidate := sm.isSyncCandidate(peer) sm.peerStates[peer] = &peerSyncState{ syncCandidate: isSyncCandidate, requestedTxns: make(map[chainhash.Hash]struct{}), requestedBlocks: make(map[chainhash.Hash]struct{}), } // Start syncing by choosing the best candidate if needed. if isSyncCandidate && sm.syncPeer == nil { sm.startSync() } } // handleDonePeerMsg deals with peers that have signalled they are done. It // removes the peer as a candidate for syncing and in the case where it was // the current sync peer, attempts to select a new best peer to sync from. It // is invoked from the syncHandler goroutine. func (sm *SyncManager) handleDonePeerMsg(peer *peerpkg.Peer) { state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received done peer message for unknown peer %s", peer) return } // Remove the peer from the list of candidate peers. delete(sm.peerStates, peer) log.Infof("Lost peer %s", peer) // Remove requested transactions from the global map so that they will // be fetched from elsewhere next time we get an inv. for txHash := range state.requestedTxns { delete(sm.requestedTxns, txHash) } // Remove requested blocks from the global map so that they will be // fetched from elsewhere next time we get an inv. // TODO: we could possibly here check which peers have these blocks // and request them now to speed things up a little. for blockHash := range state.requestedBlocks { delete(sm.requestedBlocks, blockHash) } // Attempt to find a new peer to sync from if the quitting peer is the // sync peer. Also, reset the headers-first state if in headers-first // mode so if sm.syncPeer == peer { sm.syncPeer = nil if sm.headersFirstMode { best := sm.chain.BestSnapshot() sm.resetHeaderState(&best.Hash, best.Height) } sm.startSync() } } // handleTxMsg handles transaction messages from all peers. func (sm *SyncManager) handleTxMsg(tmsg *txMsg) { peer := tmsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received tx message from unknown peer %s", peer) return } // NOTE: BitcoinJ, and possibly other wallets, don't follow the spec of // sending an inventory message and allowing the remote peer to decide // whether or not they want to request the transaction via a getdata // message. Unfortunately, the reference implementation permits // unrequested data, so it has allowed wallets that don't follow the // spec to proliferate. While this is not ideal, there is no check here // to disconnect peers for sending unsolicited transactions to provide // interoperability. txHash := tmsg.tx.Hash() // Ignore transactions that we have already rejected. Do not // send a reject message here because if the transaction was already // rejected, the transaction was unsolicited. if _, exists = sm.rejectedTxns[*txHash]; exists { log.Debugf("Ignoring unsolicited previously rejected "+ "transaction %v from %s", txHash, peer) return } // Process the transaction to include validation, insertion in the // memory pool, orphan handling, etc. acceptedTxs, err := sm.txMemPool.ProcessTransaction(tmsg.tx, true, true, mempool.Tag(peer.ID())) // Remove transaction from request maps. Either the mempool/chain // already knows about it and as such we shouldn't have any more // instances of trying to fetch it, or we failed to insert and thus // we'll retry next time we get an inv. delete(state.requestedTxns, *txHash) delete(sm.requestedTxns, *txHash) if err != nil { // Do not request this transaction again until a new block // has been processed. sm.rejectedTxns[*txHash] = struct{}{} sm.limitMap(sm.rejectedTxns, maxRejectedTxns) // When the error is a rule error, it means the transaction was // simply rejected as opposed to something actually going wrong, // so log it as such. Otherwise, something really did go wrong, // so log it as an actual error. if _, ok := err.(mempool.RuleError); ok { log.Debugf("Rejected transaction %v from %s: %v", txHash, peer, err) } else { log.Errorf("Failed to process transaction %v: %v", txHash, err) } // Convert the error into an appropriate reject message and // send it. code, reason := mempool.ErrToRejectErr(err) peer.PushRejectMsg(wire.CmdTx, code, reason, txHash, false) return } sm.peerNotifier.AnnounceNewTransactions(acceptedTxs) } // current returns true if we believe we are synced with our peers, false if we // still have blocks to check func (sm *SyncManager) current() bool { if !sm.chain.IsCurrent() { return false } // if blockChain thinks we are current and we have no syncPeer it // is probably right. if sm.syncPeer == nil { return true } // No matter what chain thinks, if we are below the block we are syncing // to we are not current. if sm.chain.BestSnapshot().Height < sm.syncPeer.LastBlock() { return false } return true } // handleBlockMsg handles block messages from all peers. func (sm *SyncManager) handleBlockMsg(bmsg *blockMsg) { peer := bmsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received block message from unknown peer %s", peer) return } // If we didn't ask for this block then the peer is misbehaving. blockHash := bmsg.block.Hash() if _, exists = state.requestedBlocks[*blockHash]; !exists { // The regression test intentionally sends some blocks twice // to test duplicate block insertion fails. Don't disconnect // the peer or ignore the block when we're in regression test // mode in this case so the chain code is actually fed the // duplicate blocks. if sm.chainParams != &chaincfg.RegressionNetParams { log.Warnf("Got unrequested block %v from %s -- "+ "disconnecting", blockHash, peer.Addr()) peer.Disconnect() return } } // When in headers-first mode, if the block matches the hash of the // first header in the list of headers that are being fetched, it's // eligible for less validation since the headers have already been // verified to link together and are valid up to the next checkpoint. // Also, remove the list entry for all blocks except the checkpoint // since it is needed to verify the next round of headers links // properly. isCheckpointBlock := false behaviorFlags := blockchain.BFNone if sm.headersFirstMode { firstNodeEl := sm.headerList.Front() if firstNodeEl != nil { firstNode := firstNodeEl.Value.(*headerNode) if blockHash.IsEqual(firstNode.hash) { behaviorFlags |= blockchain.BFFastAdd if firstNode.hash.IsEqual(sm.nextCheckpoint.Hash) { isCheckpointBlock = true } else { sm.headerList.Remove(firstNodeEl) } } } } // Remove block from request maps. Either chain will know about it and // so we shouldn't have any more instances of trying to fetch it, or we // will fail the insert and thus we'll retry next time we get an inv. delete(state.requestedBlocks, *blockHash) delete(sm.requestedBlocks, *blockHash) // Process the block to include validation, best chain selection, orphan // handling, etc. _, isOrphan, err := sm.chain.ProcessBlock(bmsg.block, behaviorFlags) if err != nil { // When the error is a rule error, it means the block was simply // rejected as opposed to something actually going wrong, so log // it as such. Otherwise, something really did go wrong, so log // it as an actual error. if _, ok := err.(blockchain.RuleError); ok { log.Infof("Rejected block %v from %s: %v", blockHash, peer, err) } else { log.Errorf("Failed to process block %v: %v", blockHash, err) } if dbErr, ok := err.(database.Error); ok && dbErr.ErrorCode == database.ErrCorruption { panic(dbErr) } // Convert the error into an appropriate reject message and // send it. code, reason := mempool.ErrToRejectErr(err) peer.PushRejectMsg(wire.CmdBlock, code, reason, blockHash, false) return } // Meta-data about the new block this peer is reporting. We use this // below to update this peer's lastest block height and the heights of // other peers based on their last announced block hash. This allows us // to dynamically update the block heights of peers, avoiding stale // heights when looking for a new sync peer. Upon acceptance of a block // or recognition of an orphan, we also use this information to update // the block heights over other peers who's invs may have been ignored // if we are actively syncing while the chain is not yet current or // who may have lost the lock announcment race. var heightUpdate int32 var blkHashUpdate *chainhash.Hash // Request the parents for the orphan block from the peer that sent it. if isOrphan { // We've just received an orphan block from a peer. In order // to update the height of the peer, we try to extract the // block height from the scriptSig of the coinbase transaction. // Extraction is only attempted if the block's version is // high enough (ver 2+). header := &bmsg.block.MsgBlock().Header if blockchain.ShouldHaveSerializedBlockHeight(header) { coinbaseTx := bmsg.block.Transactions()[0] cbHeight, err := blockchain.ExtractCoinbaseHeight(coinbaseTx) if err != nil { log.Warnf("Unable to extract height from "+ "coinbase tx: %v", err) } else { log.Debugf("Extracted height of %v from "+ "orphan block", cbHeight) heightUpdate = cbHeight blkHashUpdate = blockHash } } orphanRoot := sm.chain.GetOrphanRoot(blockHash) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Warnf("Failed to get block locator for the "+ "latest block: %v", err) } else { peer.PushGetBlocksMsg(locator, orphanRoot) } } else { // When the block is not an orphan, log information about it and // update the chain state. sm.progressLogger.LogBlockHeight(bmsg.block) // Update this peer's latest block height, for future // potential sync node candidacy. best := sm.chain.BestSnapshot() heightUpdate = best.Height blkHashUpdate = &best.Hash // Clear the rejected transactions. sm.rejectedTxns = make(map[chainhash.Hash]struct{}) } // Update the block height for this peer. But only send a message to // the server for updating peer heights if this is an orphan or our // chain is "current". This avoids sending a spammy amount of messages // if we're syncing the chain from scratch. if blkHashUpdate != nil && heightUpdate != 0 { peer.UpdateLastBlockHeight(heightUpdate) if isOrphan || sm.current() { go sm.peerNotifier.UpdatePeerHeights(blkHashUpdate, heightUpdate, peer) } } // Nothing more to do if we aren't in headers-first mode. if !sm.headersFirstMode { return } // This is headers-first mode, so if the block is not a checkpoint // request more blocks using the header list when the request queue is // getting short. if !isCheckpointBlock { if sm.startHeader != nil && len(state.requestedBlocks) < minInFlightBlocks { sm.fetchHeaderBlocks() } return } // This is headers-first mode and the block is a checkpoint. When // there is a next checkpoint, get the next round of headers by asking // for headers starting from the block after this one up to the next // checkpoint. prevHeight := sm.nextCheckpoint.Height prevHash := sm.nextCheckpoint.Hash sm.nextCheckpoint = sm.findNextHeaderCheckpoint(prevHeight) if sm.nextCheckpoint != nil { locator := blockchain.BlockLocator([]*chainhash.Hash{prevHash}) err := peer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) if err != nil { log.Warnf("Failed to send getheaders message to "+ "peer %s: %v", peer.Addr(), err) return } log.Infof("Downloading headers for blocks %d to %d from "+ "peer %s", prevHeight+1, sm.nextCheckpoint.Height, sm.syncPeer.Addr()) return } // This is headers-first mode, the block is a checkpoint, and there are // no more checkpoints, so switch to normal mode by requesting blocks // from the block after this one up to the end of the chain (zero hash). sm.headersFirstMode = false sm.headerList.Init() log.Infof("Reached the final checkpoint -- switching to normal mode") locator := blockchain.BlockLocator([]*chainhash.Hash{blockHash}) err = peer.PushGetBlocksMsg(locator, &zeroHash) if err != nil { log.Warnf("Failed to send getblocks message to peer %s: %v", peer.Addr(), err) return } } // fetchHeaderBlocks creates and sends a request to the syncPeer for the next // list of blocks to be downloaded based on the current list of headers. func (sm *SyncManager) fetchHeaderBlocks() { // Nothing to do if there is no start header. if sm.startHeader == nil { log.Warnf("fetchHeaderBlocks called with no start header") return } // Build up a getdata request for the list of blocks the headers // describe. The size hint will be limited to wire.MaxInvPerMsg by // the function, so no need to double check it here. gdmsg := wire.NewMsgGetDataSizeHint(uint(sm.headerList.Len())) numRequested := 0 for e := sm.startHeader; e != nil; e = e.Next() { node, ok := e.Value.(*headerNode) if !ok { log.Warn("Header list node type is not a headerNode") continue } iv := wire.NewInvVect(wire.InvTypeBlock, node.hash) haveInv, err := sm.haveInventory(iv) if err != nil { log.Warnf("Unexpected failure when checking for "+ "existing inventory during header block "+ "fetch: %v", err) } if !haveInv { syncPeerState := sm.peerStates[sm.syncPeer] sm.requestedBlocks[*node.hash] = struct{}{} syncPeerState.requestedBlocks[*node.hash] = struct{}{} // If we're fetching from a witness enabled peer // post-fork, then ensure that we receive all the // witness data in the blocks. if sm.syncPeer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessBlock } gdmsg.AddInvVect(iv) numRequested++ } sm.startHeader = e.Next() if numRequested >= wire.MaxInvPerMsg { break } } if len(gdmsg.InvList) > 0 { sm.syncPeer.QueueMessage(gdmsg, nil) } } // handleHeadersMsg handles block header messages from all peers. Headers are // requested when performing a headers-first sync. func (sm *SyncManager) handleHeadersMsg(hmsg *headersMsg) { peer := hmsg.peer _, exists := sm.peerStates[peer] if !exists { log.Warnf("Received headers message from unknown peer %s", peer) return } // The remote peer is misbehaving if we didn't request headers. msg := hmsg.headers numHeaders := len(msg.Headers) if !sm.headersFirstMode { log.Warnf("Got %d unrequested headers from %s -- "+ "disconnecting", numHeaders, peer.Addr()) peer.Disconnect() return } // Nothing to do for an empty headers message. if numHeaders == 0 { return } // Process all of the received headers ensuring each one connects to the // previous and that checkpoints match. receivedCheckpoint := false var finalHash *chainhash.Hash for _, blockHeader := range msg.Headers { blockHash := blockHeader.BlockHash() finalHash = &blockHash // Ensure there is a previous header to compare against. prevNodeEl := sm.headerList.Back() if prevNodeEl == nil { log.Warnf("Header list does not contain a previous" + "element as expected -- disconnecting peer") peer.Disconnect() return } // Ensure the header properly connects to the previous one and // add it to the list of headers. node := headerNode{hash: &blockHash} prevNode := prevNodeEl.Value.(*headerNode) if prevNode.hash.IsEqual(&blockHeader.PrevBlock) { node.height = prevNode.height + 1 e := sm.headerList.PushBack(&node) if sm.startHeader == nil { sm.startHeader = e } } else { log.Warnf("Received block header that does not "+ "properly connect to the chain from peer %s "+ "-- disconnecting", peer.Addr()) peer.Disconnect() return } // Verify the header at the next checkpoint height matches. if node.height == sm.nextCheckpoint.Height { if node.hash.IsEqual(sm.nextCheckpoint.Hash) { receivedCheckpoint = true log.Infof("Verified downloaded block "+ "header against checkpoint at height "+ "%d/hash %s", node.height, node.hash) } else { log.Warnf("Block header at height %d/hash "+ "%s from peer %s does NOT match "+ "expected checkpoint hash of %s -- "+ "disconnecting", node.height, node.hash, peer.Addr(), sm.nextCheckpoint.Hash) peer.Disconnect() return } break } } // When this header is a checkpoint, switch to fetching the blocks for // all of the headers since the last checkpoint. if receivedCheckpoint { // Since the first entry of the list is always the final block // that is already in the database and is only used to ensure // the next header links properly, it must be removed before // fetching the blocks. sm.headerList.Remove(sm.headerList.Front()) log.Infof("Received %v block headers: Fetching blocks", sm.headerList.Len()) sm.progressLogger.SetLastLogTime(time.Now()) sm.fetchHeaderBlocks() return } // This header is not a checkpoint, so request the next batch of // headers starting from the latest known header and ending with the // next checkpoint. locator := blockchain.BlockLocator([]*chainhash.Hash{finalHash}) err := peer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) if err != nil { log.Warnf("Failed to send getheaders message to "+ "peer %s: %v", peer.Addr(), err) return } } // haveInventory returns whether or not the inventory represented by the passed // inventory vector is known. This includes checking all of the various places // inventory can be when it is in different states such as blocks that are part // of the main chain, on a side chain, in the orphan pool, and transactions that // are in the memory pool (either the main pool or orphan pool). func (sm *SyncManager) haveInventory(invVect *wire.InvVect) (bool, error) { switch invVect.Type { case wire.InvTypeWitnessBlock: fallthrough case wire.InvTypeBlock: // Ask chain if the block is known to it in any form (main // chain, side chain, or orphan). return sm.chain.HaveBlock(&invVect.Hash) case wire.InvTypeWitnessTx: fallthrough case wire.InvTypeTx: // Ask the transaction memory pool if the transaction is known // to it in any form (main pool or orphan). if sm.txMemPool.HaveTransaction(&invVect.Hash) { return true, nil } // Check if the transaction exists from the point of view of the // end of the main chain. entry, err := sm.chain.FetchUtxoEntry(&invVect.Hash) if err != nil { return false, err } return entry != nil && !entry.IsFullySpent(), nil } // The requested inventory is is an unsupported type, so just claim // it is known to avoid requesting it. return true, nil } // handleInvMsg handles inv messages from all peers. // We examine the inventory advertised by the remote peer and act accordingly. func (sm *SyncManager) handleInvMsg(imsg *invMsg) { peer := imsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received inv message from unknown peer %s", peer) return } // Attempt to find the final block in the inventory list. There may // not be one. lastBlock := -1 invVects := imsg.inv.InvList for i := len(invVects) - 1; i >= 0; i-- { if invVects[i].Type == wire.InvTypeBlock { lastBlock = i break } } // If this inv contains a block announcement, and this isn't coming from // our current sync peer or we're current, then update the last // announced block for this peer. We'll use this information later to // update the heights of peers based on blocks we've accepted that they // previously announced. if lastBlock != -1 && (peer != sm.syncPeer || sm.current()) { peer.UpdateLastAnnouncedBlock(&invVects[lastBlock].Hash) } // Ignore invs from peers that aren't the sync if we are not current. // Helps prevent fetching a mass of orphans. if peer != sm.syncPeer && !sm.current() { return } // If our chain is current and a peer announces a block we already // know of, then update their current block height. if lastBlock != -1 && sm.current() { blkHeight, err := sm.chain.BlockHeightByHash(&invVects[lastBlock].Hash) if err == nil { peer.UpdateLastBlockHeight(blkHeight) } } // Request the advertised inventory if we don't already have it. Also, // request parent blocks of orphans if we receive one we already have. // Finally, attempt to detect potential stalls due to long side chains // we already have and request more blocks to prevent them. for i, iv := range invVects { // Ignore unsupported inventory types. switch iv.Type { case wire.InvTypeBlock: case wire.InvTypeTx: case wire.InvTypeWitnessBlock: case wire.InvTypeWitnessTx: default: continue } // Add the inventory to the cache of known inventory // for the peer. peer.AddKnownInventory(iv) // Ignore inventory when we're in headers-first mode. if sm.headersFirstMode { continue } // Request the inventory if we don't already have it. haveInv, err := sm.haveInventory(iv) if err != nil { log.Warnf("Unexpected failure when checking for "+ "existing inventory during inv message "+ "processing: %v", err) continue } if !haveInv { if iv.Type == wire.InvTypeTx { // Skip the transaction if it has already been // rejected. if _, exists := sm.rejectedTxns[iv.Hash]; exists { continue } } // Ignore invs block invs from non-witness enabled // peers, as after segwit activation we only want to // download from peers that can provide us full witness // data for blocks. if !peer.IsWitnessEnabled() && iv.Type == wire.InvTypeBlock { continue } // Add it to the request queue. state.requestQueue = append(state.requestQueue, iv) continue } if iv.Type == wire.InvTypeBlock { // The block is an orphan block that we already have. // When the existing orphan was processed, it requested // the missing parent blocks. When this scenario // happens, it means there were more blocks missing // than are allowed into a single inventory message. As // a result, once this peer requested the final // advertised block, the remote peer noticed and is now // resending the orphan block as an available block // to signal there are more missing blocks that need to // be requested. if sm.chain.IsKnownOrphan(&iv.Hash) { // Request blocks starting at the latest known // up to the root of the orphan that just came // in. orphanRoot := sm.chain.GetOrphanRoot(&iv.Hash) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Errorf("PEER: Failed to get block "+ "locator for the latest block: "+ "%v", err) continue } peer.PushGetBlocksMsg(locator, orphanRoot) continue } // We already have the final block advertised by this // inventory message, so force a request for more. This // should only happen if we're on a really long side // chain. if i == lastBlock { // Request blocks after this one up to the // final one the remote peer knows about (zero // stop hash). locator := sm.chain.BlockLocatorFromHash(&iv.Hash) peer.PushGetBlocksMsg(locator, &zeroHash) } } } // Request as much as possible at once. Anything that won't fit into // the request will be requested on the next inv message. numRequested := 0 gdmsg := wire.NewMsgGetData() requestQueue := state.requestQueue for len(requestQueue) != 0 { iv := requestQueue[0] requestQueue[0] = nil requestQueue = requestQueue[1:] switch iv.Type { case wire.InvTypeWitnessBlock: fallthrough case wire.InvTypeBlock: // Request the block if there is not already a pending // request. if _, exists := sm.requestedBlocks[iv.Hash]; !exists { sm.requestedBlocks[iv.Hash] = struct{}{} sm.limitMap(sm.requestedBlocks, maxRequestedBlocks) state.requestedBlocks[iv.Hash] = struct{}{} if peer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessBlock } gdmsg.AddInvVect(iv) numRequested++ } case wire.InvTypeWitnessTx: fallthrough case wire.InvTypeTx: // Request the transaction if there is not already a // pending request. if _, exists := sm.requestedTxns[iv.Hash]; !exists { sm.requestedTxns[iv.Hash] = struct{}{} sm.limitMap(sm.requestedTxns, maxRequestedTxns) state.requestedTxns[iv.Hash] = struct{}{} // If the peer is capable, request the txn // including all witness data. if peer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessTx } gdmsg.AddInvVect(iv) numRequested++ } } if numRequested >= wire.MaxInvPerMsg { break } } state.requestQueue = requestQueue if len(gdmsg.InvList) > 0 { peer.QueueMessage(gdmsg, nil) } } // limitMap is a helper function for maps that require a maximum limit by // evicting a random transaction if adding a new value would cause it to // overflow the maximum allowed. func (sm *SyncManager) limitMap(m map[chainhash.Hash]struct{}, limit int) { if len(m)+1 > limit { // Remove a random entry from the map. For most compilers, Go's // range statement iterates starting at a random item although // that is not 100% guaranteed by the spec. The iteration order // is not important here because an adversary would have to be // able to pull off preimage attacks on the hashing function in // order to target eviction of specific entries anyways. for txHash := range m { delete(m, txHash) return } } } // blockHandler is the main handler for the sync manager. It must be run as a // goroutine. It processes block and inv messages in a separate goroutine // from the peer handlers so the block (MsgBlock) messages are handled by a // single thread without needing to lock memory data structures. This is // important because the sync manager controls which blocks are needed and how // the fetching should proceed. func (sm *SyncManager) blockHandler() { out: for { select { case m := <-sm.msgChan: switch msg := m.(type) { case *newPeerMsg: sm.handleNewPeerMsg(msg.peer) case *txMsg: sm.handleTxMsg(msg) msg.reply <- struct{}{} case *blockMsg: sm.handleBlockMsg(msg) msg.reply <- struct{}{} case *invMsg: sm.handleInvMsg(msg) case *headersMsg: sm.handleHeadersMsg(msg) case *donePeerMsg: sm.handleDonePeerMsg(msg.peer) case getSyncPeerMsg: var peerID int32 if sm.syncPeer != nil { peerID = sm.syncPeer.ID() } msg.reply <- peerID case processBlockMsg: _, isOrphan, err := sm.chain.ProcessBlock( msg.block, msg.flags) if err != nil { msg.reply <- processBlockResponse{ isOrphan: false, err: err, } } msg.reply <- processBlockResponse{ isOrphan: isOrphan, err: nil, } case isCurrentMsg: msg.reply <- sm.current() case pauseMsg: // Wait until the sender unpauses the manager. <-msg.unpause default: log.Warnf("Invalid message type in block "+ "handler: %T", msg) } case <-sm.quit: break out } } sm.wg.Done() log.Trace("Block handler done") } // handleBlockchainNotification handles notifications from blockchain. It does // things such as request orphan block parents and relay accepted blocks to // connected peers. func (sm *SyncManager) handleBlockchainNotification(notification *blockchain.Notification) { switch notification.Type { // A block has been accepted into the block chain. Relay it to other // peers. case blockchain.NTBlockAccepted: // Don't relay if we are not current. Other peers that are // current should already know about it. if !sm.current() { return } block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain accepted notification is not a block.") break } // Generate the inventory vector and relay it. iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash()) sm.peerNotifier.RelayInventory(iv, block.MsgBlock().Header) // A block has been connected to the main block chain. case blockchain.NTBlockConnected: block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain connected notification is not a block.") break } // Remove all of the transactions (except the coinbase) in the // connected block from the transaction pool. Secondly, remove any // transactions which are now double spends as a result of these // new transactions. Finally, remove any transaction that is // no longer an orphan. Transactions which depend on a confirmed // transaction are NOT removed recursively because they are still // valid. for _, tx := range block.Transactions()[1:] { sm.txMemPool.RemoveTransaction(tx, false) sm.txMemPool.RemoveDoubleSpends(tx) sm.txMemPool.RemoveOrphan(tx) sm.peerNotifier.TransactionConfirmed(tx) acceptedTxs := sm.txMemPool.ProcessOrphans(tx) sm.peerNotifier.AnnounceNewTransactions(acceptedTxs) } // A block has been disconnected from the main block chain. case blockchain.NTBlockDisconnected: block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain disconnected notification is not a block.") break } // Reinsert all of the transactions (except the coinbase) into // the transaction pool. for _, tx := range block.Transactions()[1:] { _, _, err := sm.txMemPool.MaybeAcceptTransaction(tx, false, false) if err != nil { // Remove the transaction and all transactions // that depend on it if it wasn't accepted into // the transaction pool. sm.txMemPool.RemoveTransaction(tx, true) } } } } // NewPeer informs the sync manager of a newly active peer. func (sm *SyncManager) NewPeer(peer *peerpkg.Peer) { // Ignore if we are shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &newPeerMsg{peer: peer} } // QueueTx adds the passed transaction message and peer to the block handling // queue. Responds to the done channel argument after the tx message is // processed. func (sm *SyncManager) QueueTx(tx *btcutil.Tx, peer *peerpkg.Peer, done chan struct{}) { // Don't accept more transactions if we're shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { done <- struct{}{} return } sm.msgChan <- &txMsg{tx: tx, peer: peer, reply: done} } // QueueBlock adds the passed block message and peer to the block handling // queue. Responds to the done channel argument after the block message is // processed. func (sm *SyncManager) QueueBlock(block *btcutil.Block, peer *peerpkg.Peer, done chan struct{}) { // Don't accept more blocks if we're shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { done <- struct{}{} return } sm.msgChan <- &blockMsg{block: block, peer: peer, reply: done} } // QueueInv adds the passed inv message and peer to the block handling queue. func (sm *SyncManager) QueueInv(inv *wire.MsgInv, peer *peerpkg.Peer) { // No channel handling here because peers do not need to block on inv // messages. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &invMsg{inv: inv, peer: peer} } // QueueHeaders adds the passed headers message and peer to the block handling // queue. func (sm *SyncManager) QueueHeaders(headers *wire.MsgHeaders, peer *peerpkg.Peer) { // No channel handling here because peers do not need to block on // headers messages. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &headersMsg{headers: headers, peer: peer} } // DonePeer informs the blockmanager that a peer has disconnected. func (sm *SyncManager) DonePeer(peer *peerpkg.Peer) { // Ignore if we are shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &donePeerMsg{peer: peer} } // Start begins the core block handler which processes block and inv messages. func (sm *SyncManager) Start() { // Already started? if atomic.AddInt32(&sm.started, 1) != 1 { return } log.Trace("Starting sync manager") sm.wg.Add(1) go sm.blockHandler() } // Stop gracefully shuts down the sync manager by stopping all asynchronous // handlers and waiting for them to finish. func (sm *SyncManager) Stop() error { if atomic.AddInt32(&sm.shutdown, 1) != 1 { log.Warnf("Sync manager is already in the process of " + "shutting down") return nil } log.Infof("Sync manager shutting down") close(sm.quit) sm.wg.Wait() return nil } // SyncPeerID returns the ID of the current sync peer, or 0 if there is none. func (sm *SyncManager) SyncPeerID() int32 { reply := make(chan int32) sm.msgChan <- getSyncPeerMsg{reply: reply} return <-reply } // ProcessBlock makes use of ProcessBlock on an internal instance of a block // chain. func (sm *SyncManager) ProcessBlock(block *btcutil.Block, flags blockchain.BehaviorFlags) (bool, error) { reply := make(chan processBlockResponse, 1) sm.msgChan <- processBlockMsg{block: block, flags: flags, reply: reply} response := <-reply return response.isOrphan, response.err } // IsCurrent returns whether or not the sync manager believes it is synced with // the connected peers. func (sm *SyncManager) IsCurrent() bool { reply := make(chan bool) sm.msgChan <- isCurrentMsg{reply: reply} return <-reply } // Pause pauses the sync manager until the returned channel is closed. // // Note that while paused, all peer and block processing is halted. The // message sender should avoid pausing the sync manager for long durations. func (sm *SyncManager) Pause() chan<- struct{} { c := make(chan struct{}) sm.msgChan <- pauseMsg{c} return c } // New constructs a new SyncManager. Use Start to begin processing asynchronous // block, tx, and inv updates. func New(config *Config) (*SyncManager, error) { sm := SyncManager{ peerNotifier: config.PeerNotifier, chain: config.Chain, txMemPool: config.TxMemPool, chainParams: config.ChainParams, rejectedTxns: make(map[chainhash.Hash]struct{}), requestedTxns: make(map[chainhash.Hash]struct{}), requestedBlocks: make(map[chainhash.Hash]struct{}), peerStates: make(map[*peerpkg.Peer]*peerSyncState), progressLogger: newBlockProgressLogger("Processed", log), msgChan: make(chan interface{}, config.MaxPeers*3), headerList: list.New(), quit: make(chan struct{}), } best := sm.chain.BestSnapshot() if !config.DisableCheckpoints { // Initialize the next checkpoint based on the current height. sm.nextCheckpoint = sm.findNextHeaderCheckpoint(best.Height) if sm.nextCheckpoint != nil { sm.resetHeaderState(&best.Hash, best.Height) } } else { log.Info("Checkpoints are disabled") } sm.chain.Subscribe(sm.handleBlockchainNotification) return &sm, nil }
adrianbrink/tendereum
vendor/github.com/cosmos/tendereum/vendor/github.com/btcsuite/btcd/netsync/manager.go
GO
agpl-3.0
46,884
<?php /** This file is part of KCFinder project * * @desc Autoload classes magic function * @package KCFinder * @version 2.21 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */ require_once(dirname(__FILE__).'/../../../../config-defaults.php'); require_once(dirname(__FILE__).'/../../../../common.php'); require_once(dirname(__FILE__).'/../../../admin_functions.php'); $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='SessionName'"; $usresult = db_execute_assoc($usquery,'',true); if ($usresult) { $usrow = $usresult->FetchRow(); @session_name($usrow['stg_value']); } else { session_name("LimeSurveyAdmin"); } session_set_cookie_params(0,$relativeurl.'/'); if (session_id() == "") @session_start(); $_SESSION['KCFINDER'] = array(); $sAllowedExtensions = implode(' ',array_map('trim',explode(',',$allowedresourcesuploads))); $_SESSION['KCFINDER']['types']=array('files'=>$sAllowedExtensions, 'flash'=>$sAllowedExtensions, 'images'=>$sAllowedExtensions); if ($demoModeOnly === false && isset($_SESSION['loginID']) && isset($_SESSION['FileManagerContext'])) { // disable upload at survey creation time // because we don't know the sid yet if (preg_match('/^(create|edit):(question|group|answer)/',$_SESSION['FileManagerContext']) != 0 || preg_match('/^edit:survey/',$_SESSION['FileManagerContext']) !=0 || preg_match('/^edit:assessments/',$_SESSION['FileManagerContext']) !=0 || preg_match('/^edit:emailsettings/',$_SESSION['FileManagerContext']) != 0) { $contextarray=explode(':',$_SESSION['FileManagerContext'],3); $surveyid=$contextarray[2]; if(bHasSurveyPermission($surveyid,'surveycontent','update')) { $_SESSION['KCFINDER']['disabled'] = false ; $_SESSION['KCFINDER']['uploadURL'] = "{$relativeurl}/upload/surveys/{$surveyid}/" ; $_SESSION['KCFINDER']['uploadDir'] = $uploaddir.'/surveys/'.$surveyid; } } elseif (preg_match('/^edit:label/',$_SESSION['FileManagerContext']) != 0) { $contextarray=explode(':',$_SESSION['FileManagerContext'],3); $labelid=$contextarray[2]; // check if the user has label management right and labelid defined if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1 && isset($labelid) && $labelid != '') { $_SESSION['KCFINDER']['disabled'] = false ; $_SESSION['KCFINDER']['uploadURL'] = "{$relativeurl}/upload/labels/{$labelid}/" ; $_SESSION['KCFINDER']['uploadDir'] = "{$uploaddir}/labels/{$labelid}" ; } } } function __autoload($class) { if ($class == "uploader") require "core/uploader.php"; elseif ($class == "browser") require "core/browser.php"; elseif (file_exists("core/types/$class.php")) require "core/types/$class.php"; elseif (file_exists("lib/class_$class.php")) require "lib/class_$class.php"; elseif (file_exists("lib/helper_$class.php")) require "lib/helper_$class.php"; } ?>
yscdaxian/goweb
limesurvey/admin/scripts/kcfinder/core/autoload.php
PHP
agpl-3.0
3,384
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt erpnext.POS = Class.extend({ init: function(wrapper, frm) { this.wrapper = wrapper; this.frm = frm; this.wrapper.html('<div class="container">\ <div class="row" style="margin: -9px 0px 10px -30px; border-bottom: 1px solid #c7c7c7;">\ <div class="party-area col-sm-3 col-xs-6"></div>\ <div class="barcode-area col-sm-3 col-xs-6"></div>\ <div class="search-area col-sm-3 col-xs-6"></div>\ <div class="item-group-area col-sm-3 col-xs-6"></div>\ </div>\ <div class="row">\ <div class="col-sm-6">\ <div class="pos-bill">\ <div class="item-cart">\ <table class="table table-condensed table-hover" id="cart" style="table-layout: fixed;">\ <thead>\ <tr>\ <th style="width: 40%">Item</th>\ <th style="width: 9%"></th>\ <th style="width: 17%; text-align: right;">Qty</th>\ <th style="width: 9%"></th>\ <th style="width: 25%; text-align: right;">Rate</th>\ </tr>\ </thead>\ <tbody>\ </tbody>\ </table>\ </div>\ <br>\ <div class="totals-area" style="margin-left: 40%;">\ <table class="table table-condensed">\ <tr>\ <td><b>Net Total</b></td>\ <td style="text-align: right;" class="net-total"></td>\ </tr>\ </table>\ <div class="tax-table" style="display: none;">\ <table class="table table-condensed">\ <thead>\ <tr>\ <th style="width: 60%">Taxes</th>\ <th style="width: 40%; text-align: right;"></th>\ </tr>\ </thead>\ <tbody>\ </tbody>\ </table>\ </div>\ <div class="grand-total-area">\ <table class="table table-condensed">\ <tr>\ <td style="vertical-align: middle;"><b>Grand Total</b></td>\ <td style="text-align: right; font-size: 200%; \ font-size: bold;" class="grand-total"></td>\ </tr>\ </table>\ </div>\ </div>\ </div>\ <br><br>\ <div class="row">\ <div class="col-sm-9">\ <button class="btn btn-success btn-lg make-payment">\ <i class="icon-money"></i> Make Payment</button>\ </div>\ <div class="col-sm-3">\ <button class="btn btn-default btn-lg remove-items" style="display: none;">\ <i class="icon-trash"></i> Del</button>\ </div>\ </div>\ <br><br>\ </div>\ <div class="col-sm-6">\ <div class="item-list-area">\ <div class="col-sm-12">\ <div class="row item-list"></div></div>\ </div>\ </div>\ </div></div>'); this.check_transaction_type(); this.make(); var me = this; $(this.frm.wrapper).on("refresh-fields", function() { me.refresh(); }); this.call_function("remove-items", function() {me.remove_selected_items();}); this.call_function("make-payment", function() {me.make_payment();}); }, check_transaction_type: function() { var me = this; // Check whether the transaction is "Sales" or "Purchase" if (wn.meta.has_field(cur_frm.doc.doctype, "customer")) { this.set_transaction_defaults("Customer", "export"); } else if (wn.meta.has_field(cur_frm.doc.doctype, "supplier")) { this.set_transaction_defaults("Supplier", "import"); } }, set_transaction_defaults: function(party, export_or_import) { var me = this; this.party = party; this.price_list = (party == "Customer" ? this.frm.doc.selling_price_list : this.frm.doc.buying_price_list); this.sales_or_purchase = (party == "Customer" ? "Sales" : "Purchase"); this.net_total = "net_total_" + export_or_import; this.grand_total = "grand_total_" + export_or_import; this.amount = export_or_import + "_amount"; this.rate = export_or_import + "_rate"; }, call_function: function(class_name, fn, event_name) { this.wrapper.find("." + class_name).on(event_name || "click", fn); }, make: function() { this.make_party(); this.make_item_group(); this.make_search(); this.make_barcode(); this.make_item_list(); }, make_party: function() { var me = this; this.party_field = wn.ui.form.make_control({ df: { "fieldtype": "Link", "options": this.party, "label": this.party, "fieldname": "pos_party", "placeholder": this.party }, parent: this.wrapper.find(".party-area"), only_input: true, }); this.party_field.make_input(); this.party_field.$input.on("change", function() { if(!me.party_field.autocomplete_open) wn.model.set_value(me.frm.doctype, me.frm.docname, me.party.toLowerCase(), this.value); }); }, make_item_group: function() { var me = this; this.item_group = wn.ui.form.make_control({ df: { "fieldtype": "Link", "options": "Item Group", "label": "Item Group", "fieldname": "pos_item_group", "placeholder": "Item Group" }, parent: this.wrapper.find(".item-group-area"), only_input: true, }); this.item_group.make_input(); this.item_group.$input.on("change", function() { if(!me.item_group.autocomplete_open) me.make_item_list(); }); }, make_search: function() { var me = this; this.search = wn.ui.form.make_control({ df: { "fieldtype": "Data", "label": "Item", "fieldname": "pos_item", "placeholder": "Search Item" }, parent: this.wrapper.find(".search-area"), only_input: true, }); this.search.make_input(); this.search.$input.on("keypress", function() { if(!me.search.autocomplete_open) if(me.item_timeout) clearTimeout(me.item_timeout); me.item_timeout = setTimeout(function() { me.make_item_list(); }, 1000); }); }, make_barcode: function() { var me = this; this.barcode = wn.ui.form.make_control({ df: { "fieldtype": "Data", "label": "Barcode", "fieldname": "pos_barcode", "placeholder": "Barcode / Serial No" }, parent: this.wrapper.find(".barcode-area"), only_input: true, }); this.barcode.make_input(); this.barcode.$input.on("keypress", function() { if(me.barcode_timeout) clearTimeout(me.barcode_timeout); me.barcode_timeout = setTimeout(function() { me.add_item_thru_barcode(); }, 1000); }); }, make_item_list: function() { var me = this; me.item_timeout = null; wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_items', args: { sales_or_purchase: this.sales_or_purchase, price_list: this.price_list, item_group: this.item_group.$input.val(), item: this.search.$input.val() }, callback: function(r) { var $wrap = me.wrapper.find(".item-list"); me.wrapper.find(".item-list").empty(); if (r.message) { $.each(r.message, function(index, obj) { if (obj.image) image = '<img src="' + obj.image + '" class="img-responsive" \ style="border:1px solid #eee; max-height: 140px;">'; else image = '<div class="missing-image"><i class="icon-camera"></i></div>'; $(repl('<div class="col-xs-3 pos-item" data-item_code="%(item_code)s">\ <div style="height: 140px; overflow: hidden;">%(item_image)s</div>\ <div class="small">%(item_code)s</div>\ <div class="small">%(item_name)s</div>\ <div class="small">%(item_price)s</div>\ </div>', { item_code: obj.name, item_price: format_currency(obj.ref_rate, obj.currency), item_name: obj.name===obj.item_name ? "" : obj.item_name, item_image: image })).appendTo($wrap); }); } // if form is local then allow this function $(me.wrapper).find("div.pos-item").on("click", function() { if(me.frm.doc.docstatus==0) { if(!me.frm.doc[me.party.toLowerCase()] && ((me.frm.doctype == "Quotation" && me.frm.doc.quotation_to == "Customer") || me.frm.doctype != "Quotation")) { msgprint("Please select " + me.party + " first."); return; } else me.add_to_cart($(this).attr("data-item_code")); } }); } }); }, add_to_cart: function(item_code, serial_no) { var me = this; var caught = false; // get no_of_items var no_of_items = me.wrapper.find("#cart tbody tr").length; // check whether the item is already added if (no_of_items != 0) { $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { if (d.item_code == item_code) { caught = true; if (serial_no) { d.serial_no += '\n' + serial_no; me.frm.script_manager.trigger("serial_no", d.doctype, d.name); } else { d.qty += 1; me.frm.script_manager.trigger("qty", d.doctype, d.name); } } }); } // if item not found then add new item if (!caught) { this.add_new_item_to_grid(item_code, serial_no); } this.refresh(); this.refresh_search_box(); }, add_new_item_to_grid: function(item_code, serial_no) { var me = this; var child = wn.model.add_child(me.frm.doc, this.frm.doctype + " Item", this.frm.cscript.fname); child.item_code = item_code; if (serial_no) child.serial_no = serial_no; this.frm.script_manager.trigger("item_code", child.doctype, child.name); }, refresh_search_box: function() { var me = this; // Clear Item Box and remake item list if (this.search.$input.val()) { this.search.set_input(""); this.make_item_list(); } }, update_qty: function(item_code, qty) { var me = this; $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { if (d.item_code == item_code) { if (qty == 0) { wn.model.clear_doc(d.doctype, d.name); me.refresh_grid(); } else { d.qty = qty; me.frm.script_manager.trigger("qty", d.doctype, d.name); } } }); me.refresh(); }, refresh: function() { var me = this; this.party_field.set_input(this.frm.doc[this.party.toLowerCase()]); this.barcode.set_input(""); this.show_items_in_item_cart(); this.show_taxes(); this.set_totals(); // if form is local then only run all these functions if (this.frm.doc.docstatus===0) { this.call_when_local(); } this.disable_text_box_and_button(); this.hide_payment_button(); // If quotation to is not Customer then remove party if (this.frm.doctype == "Quotation") { this.party_field.$wrapper.remove(); if (this.frm.doc.quotation_to == "Customer") this.make_party(); } }, show_items_in_item_cart: function() { var me = this; var $items = this.wrapper.find("#cart tbody").empty(); $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { $(repl('<tr id="%(item_code)s" data-selected="false">\ <td>%(item_code)s%(item_name)s</td>\ <td style="vertical-align:middle;" align="right">\ <div class="decrease-qty" style="cursor:pointer;">\ <i class="icon-minus-sign icon-large text-danger"></i>\ </div>\ </td>\ <td style="vertical-align:middle;"><input type="text" value="%(qty)s" \ class="form-control qty" style="text-align: right;"></td>\ <td style="vertical-align:middle;cursor:pointer;">\ <div class="increase-qty" style="cursor:pointer;">\ <i class="icon-plus-sign icon-large text-success"></i>\ </div>\ </td>\ <td style="text-align: right;"><b>%(amount)s</b><br>%(rate)s</td>\ </tr>', { item_code: d.item_code, item_name: d.item_name===d.item_code ? "" : ("<br>" + d.item_name), qty: d.qty, rate: format_currency(d[me.rate], me.frm.doc.currency), amount: format_currency(d[me.amount], me.frm.doc.currency) } )).appendTo($items); }); this.wrapper.find(".increase-qty, .decrease-qty").on("click", function() { var item_code = $(this).closest("tr").attr("id"); me.selected_item_qty_operation(item_code, $(this).attr("class")); }); }, show_taxes: function() { var me = this; var taxes = wn.model.get_children(this.sales_or_purchase + " Taxes and Charges", this.frm.doc.name, this.frm.cscript.other_fname, this.frm.doctype); $(this.wrapper).find(".tax-table") .toggle((taxes && taxes.length) ? true : false) .find("tbody").empty(); $.each(taxes, function(i, d) { if (d.tax_amount) { $(repl('<tr>\ <td>%(description)s %(rate)s</td>\ <td style="text-align: right;">%(tax_amount)s</td>\ <tr>', { description: d.description, rate: ((d.charge_type == "Actual") ? '' : ("(" + d.rate + "%)")), tax_amount: format_currency(flt(d.tax_amount)/flt(me.frm.doc.conversion_rate), me.frm.doc.currency) })).appendTo(".tax-table tbody"); } }); }, set_totals: function() { var me = this; this.wrapper.find(".net-total").text(format_currency(this.frm.doc[this.net_total], me.frm.doc.currency)); this.wrapper.find(".grand-total").text(format_currency(this.frm.doc[this.grand_total], me.frm.doc.currency)); }, call_when_local: function() { var me = this; // append quantity to the respective item after change from input box $(this.wrapper).find("input.qty").on("change", function() { var item_code = $(this).closest("tr")[0].id; me.update_qty(item_code, $(this).val()); }); // on td click toggle the highlighting of row $(this.wrapper).find("#cart tbody tr td").on("click", function() { var row = $(this).closest("tr"); if (row.attr("data-selected") == "false") { row.attr("class", "warning"); row.attr("data-selected", "true"); } else { row.prop("class", null); row.attr("data-selected", "false"); } me.refresh_delete_btn(); }); me.refresh_delete_btn(); this.barcode.$input.focus(); }, disable_text_box_and_button: function() { var me = this; // if form is submitted & cancelled then disable all input box & buttons if (this.frm.doc.docstatus>=1) { $(this.wrapper).find('input, button').each(function () { $(this).prop('disabled', true); }); $(this.wrapper).find(".remove-items").hide(); $(this.wrapper).find(".make-payment").hide(); } else { $(this.wrapper).find('input, button').each(function () { $(this).prop('disabled', false); }); $(this.wrapper).find(".make-payment").show(); } }, hide_payment_button: function() { var me = this; // Show Make Payment button only in Sales Invoice if (this.frm.doctype != "Sales Invoice") $(this.wrapper).find(".make-payment").hide(); }, refresh_delete_btn: function() { $(this.wrapper).find(".remove-items").toggle($(".item-cart .warning").length ? true : false); }, add_item_thru_barcode: function() { var me = this; me.barcode_timeout = null; wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_item_code', args: {barcode_serial_no: this.barcode.$input.val()}, callback: function(r) { if (r.message) { if (r.message[1] == "serial_no") me.add_to_cart(r.message[0][0].item_code, r.message[0][0].name); else me.add_to_cart(r.message[0][0].name); } else msgprint(wn._("Invalid Barcode")); me.refresh(); } }); }, remove_selected_items: function() { var me = this; var selected_items = []; var no_of_items = $(this.wrapper).find("#cart tbody tr").length; for(var x=0; x<=no_of_items - 1; x++) { var row = $(this.wrapper).find("#cart tbody tr:eq(" + x + ")"); if(row.attr("data-selected") == "true") { selected_items.push(row.attr("id")); } } var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype); $.each(child, function(i, d) { for (var i in selected_items) { if (d.item_code == selected_items[i]) { wn.model.clear_doc(d.doctype, d.name); } } }); this.refresh_grid(); }, refresh_grid: function() { this.frm.fields_dict[this.frm.cscript.fname].grid.refresh(); this.frm.script_manager.trigger("calculate_taxes_and_totals"); this.refresh(); }, selected_item_qty_operation: function(item_code, operation) { var me = this; var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype); $.each(child, function(i, d) { if (d.item_code == item_code) { if (operation == "increase-qty") d.qty += 1; else if (operation == "decrease-qty") d.qty != 1 ? d.qty -= 1 : d.qty = 1; me.refresh(); } }); }, make_payment: function() { var me = this; var no_of_items = $(this.wrapper).find("#cart tbody tr").length; var mode_of_payment = []; if (no_of_items == 0) msgprint(wn._("Payment cannot be made for empty cart")); else { wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_mode_of_payment', callback: function(r) { for (x=0; x<=r.message.length - 1; x++) { mode_of_payment.push(r.message[x].name); } // show payment wizard var dialog = new wn.ui.Dialog({ width: 400, title: 'Payment', fields: [ {fieldtype:'Data', fieldname:'total_amount', label:'Total Amount', read_only:1}, {fieldtype:'Select', fieldname:'mode_of_payment', label:'Mode of Payment', options:mode_of_payment.join('\n'), reqd: 1}, {fieldtype:'Button', fieldname:'pay', label:'Pay'} ] }); dialog.set_values({ "total_amount": $(".grand-total").text() }); dialog.show(); dialog.get_input("total_amount").prop("disabled", true); dialog.fields_dict.pay.input.onclick = function() { me.frm.set_value("mode_of_payment", dialog.get_values().mode_of_payment); me.frm.set_value("paid_amount", dialog.get_values().total_amount); me.frm.cscript.mode_of_payment(me.frm.doc); me.frm.save(); dialog.hide(); me.refresh(); }; } }); } }, });
Tejal011089/Medsyn2_app
accounts/doctype/sales_invoice/pos.js
JavaScript
agpl-3.0
17,987
/* * eXist Open Source Native XML Database * Copyright (C) 2010 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.versioning.svn.xquery; import org.exist.dom.QName; import org.exist.util.io.Resource; import org.exist.versioning.svn.internal.wc.DefaultSVNOptions; import org.exist.versioning.svn.wc.SVNClientManager; import org.exist.versioning.svn.wc.SVNWCUtil; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.tmatesoft.svn.core.SVNException; /** * Recursively cleans up the working copy, removing locks and resuming unfinished operations. * * @author <a href="mailto:amir.akhmedov@gmail.com">Amir Akhmedov</a> * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> */ public class SVNCleanup extends AbstractSVNFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("clean-up", SVNModule.NAMESPACE_URI, SVNModule.PREFIX), "Recursively cleans up the working copy, removing locks and resuming unfinished operations.", new SequenceType[] { DB_PATH }, new FunctionReturnSequenceType(Type.EMPTY, Cardinality.ZERO, "")); /** * * @param context */ public SVNCleanup(XQueryContext context) { super(context, signature); } /** * Process the function. All arguments are passed in the array args. The number of * arguments, their type and cardinality have already been checked to match * the function signature. * * @param args * @param contextSequence */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { String uri = args[0].getStringValue(); DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(true); SVNClientManager manager = SVNClientManager.newInstance(options, "", ""); try { manager.getWCClient().doCleanup(new Resource(uri)); } catch (SVNException e) { throw new XPathException(this, e.getMessage(), e); } return Sequence.EMPTY_SEQUENCE; } }
shabanovd/exist
extensions/svn/src/org/exist/versioning/svn/xquery/SVNCleanup.java
Java
lgpl-2.1
3,112
// --------------------------------------------------------------------- // // Copyright (C) 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test Volume of a Ball #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_tools.h> #include <deal.II/fe/mapping_q.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/numerics/data_out.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/grid_in.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/manifold_lib.h> #include <deal.II/matrix_free/matrix_free.h> #include <deal.II/matrix_free/fe_evaluation.h> #include <iostream> #include <fstream> #include <sstream> using namespace dealii; void test (const double R) { const unsigned int dim = 3; const unsigned int global_mesh_refinement_steps = 4; const unsigned int fe_degree = 2; const unsigned int n_q_points_1d = 3; // derived Point<dim> center; for (unsigned int d=0; d < dim; d++) center[d] = d; Triangulation<dim> triangulation; DoFHandler<dim> dof_handler(triangulation); FE_Q<dim> fe(fe_degree); QGauss<dim> quadrature_formula(n_q_points_1d); GridGenerator::hyper_ball (triangulation, center, R); triangulation.set_all_manifold_ids_on_boundary(0); static SphericalManifold<dim> surface_description(center); triangulation.set_manifold (0, surface_description); triangulation.refine_global(global_mesh_refinement_steps); dof_handler.distribute_dofs (fe); MappingQ<dim> mapping(fe_degree); FEValues<dim> fe_values (mapping, fe, quadrature_formula, update_JxW_values); DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active (), endc = dof_handler.end (); const unsigned int n_q_points = quadrature_formula.size(); double volume = 0.; for (; cell!=endc; ++cell) { fe_values.reinit (cell); for (unsigned int q=0; q<n_q_points; ++q) volume += fe_values.JxW (q); } deallog << "Volume: " << volume << std::endl << "Exact volume: " << 4.0*numbers::PI *std::pow(R,3.0)/3. << std::endl; dof_handler.clear (); } using namespace dealii; int main (int argc, char *argv[]) { initlog(); test(15); return 0; }
shakirbsm/dealii
tests/manifold/spherical_manifold_04.cc
C++
lgpl-2.1
2,888
package org.jaudiotagger.issues; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.FieldKey; import java.io.File; /** * Test deletions of ID3v1 tag */ public class Issue383Test extends AbstractTestCase { /** * This song is incorrectly shown as 6:08 when should be 3:34 but all apps (Media Monkey, iTunes) * also report incorrect length, however think problem is audio does continue until 6:08 but is just quiet sound * * @throws Exception */ public void testIssueIncorrectTrackLength() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test106.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test106.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getAudioHeader().getTrackLength(),368); } catch(Exception e) { caught=e; } assertNull(caught); } /** * This song is incorrectly shown as 01:12:52, but correct length was 2:24. Other applications * such as Media Monkey show correct value. * * @throws Exception */ public void testIssue() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test107.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test107.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getTag().getFirst(FieldKey.TRACK),"01"); assertEquals(af.getAudioHeader().getTrackLength(),4372); } catch(Exception e) { caught=e; } assertNull(caught); } }
nhminus/jaudiotagger-androidpatch
srctest/org/jaudiotagger/issues/Issue383Test.java
Java
lgpl-2.1
2,217
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.functions.query; import lucee.runtime.PageContext; import lucee.runtime.exp.PageException; import lucee.runtime.functions.BIF; import lucee.runtime.op.Caster; import lucee.runtime.type.Query; public final class QueryDeleteRow extends BIF { private static final long serialVersionUID = 7610413135885802876L; public static boolean call(PageContext pc, Query query) throws PageException { return call(pc,query,query.getRowCount()); } public static boolean call(PageContext pc, Query query, double row) throws PageException { if(row==-9999) row=query.getRowCount();// used for named arguments query.removeRow((int)row); return true; } @Override public Object invoke(PageContext pc, Object[] args) throws PageException { if(args.length==1)return call(pc,Caster.toQuery(args[0])); return call(pc,Caster.toQuery(args[0]),Caster.toDoubleValue(args[1])); } }
paulklinkenberg/Lucee4
lucee-java/lucee-core/src/lucee/runtime/functions/query/QueryDeleteRow.java
Java
lgpl-2.1
1,691
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.server.deployment; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FULL_REPLACE_DEPLOYMENT; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_ARCHIVE; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_HASH; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_PATH; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_RELATIVE_TO; import static org.jboss.as.server.controller.resources.DeploymentAttributes.ENABLED; import static org.jboss.as.server.controller.resources.DeploymentAttributes.OWNER; import static org.jboss.as.server.controller.resources.DeploymentAttributes.PERSISTENT; import static org.jboss.as.server.controller.resources.DeploymentAttributes.RUNTIME_NAME; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.addFlushHandler; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.asString; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.createFailureException; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.getInputStream; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.hasValidContentAdditionParameterDefined; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationContext.ResultAction; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.protocol.StreamUtils; import org.jboss.as.repository.ContentReference; import org.jboss.as.repository.ContentRepository; import org.jboss.as.server.controller.resources.DeploymentAttributes; import org.jboss.as.server.logging.ServerLogger; import org.jboss.dmr.ModelNode; /** * Handles replacement in the runtime of one deployment by another. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ public class DeploymentFullReplaceHandler implements OperationStepHandler { public static final String OPERATION_NAME = FULL_REPLACE_DEPLOYMENT; protected final ContentRepository contentRepository; private final DeploymentTransformation deploymentTransformation; protected DeploymentFullReplaceHandler(final ContentRepository contentRepository) { assert contentRepository != null : "Null contentRepository"; this.contentRepository = contentRepository; this.deploymentTransformation = new DeploymentTransformation(); } public static DeploymentFullReplaceHandler create(final ContentRepository contentRepository) { return new DeploymentFullReplaceHandler(contentRepository); } public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { // Validate op. Store any corrected values back to the op before manipulating further ModelNode correctedOperation = operation.clone(); for (AttributeDefinition def : DeploymentAttributes.FULL_REPLACE_DEPLOYMENT_ATTRIBUTES.values()) { def.validateAndSet(operation, correctedOperation); } // Pull data from the op final String name = DeploymentAttributes.NAME.resolveModelAttribute(context, correctedOperation).asString(); final PathElement deploymentPath = PathElement.pathElement(DEPLOYMENT, name); final String runtimeName = correctedOperation.hasDefined(RUNTIME_NAME.getName()) ? correctedOperation.get(RUNTIME_NAME.getName()).asString() : name; // clone the content param, so we can modify it to our own content ModelNode content = correctedOperation.require(CONTENT).clone(); // Throw a specific exception if the replaced deployment doesn't already exist // BES 2013/10/30 -- this is pointless; the readResourceForUpdate call will throw // an exception with an equally informative message if the deployment doesn't exist // final Resource root = context.readResource(PathAddress.EMPTY_ADDRESS); // boolean exists = root.hasChild(deploymentPath); // if (!exists) { // throw ServerLogger.ROOT_LOGGER.noSuchDeployment(name); // } // verify that the resource existance before removing it context.readResourceForUpdate(PathAddress.pathAddress(deploymentPath)); // WFCORE-495 remove and call context.addResource() as below to add new resource with updated PERSISTENT value final ModelNode deploymentModel = context.removeResource(PathAddress.pathAddress(deploymentPath)).getModel(); final ModelNode originalDeployment = deploymentModel.clone(); // Keep track of runtime name of deployment we are replacing for use in Stage.RUNTIME final String replacedRuntimeName = RUNTIME_NAME.resolveModelAttribute(context, deploymentModel).asString(); final PathAddress address = PathAddress.pathAddress(deploymentPath); // Keep track of hash we are replacing so we can drop it from the content repo if all is well ModelNode replacedContent = deploymentModel.get(CONTENT).get(0); final byte[] replacedHash = replacedContent.hasDefined(CONTENT_HASH.getName()) ? CONTENT_HASH.resolveModelAttribute(context, replacedContent).asBytes() : null; // Set up the new content attribute final byte[] newHash; // TODO: JBAS-9020: for the moment overlays are not supported, so there is a single content item final DeploymentHandlerUtil.ContentItem contentItem; ModelNode contentItemNode = content.require(0); if (contentItemNode.hasDefined(CONTENT_HASH.getName())) { newHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes(); ContentReference reference = ModelContentReference.fromModelAddress(address, newHash); contentItem = addFromHash(reference); } else if (hasValidContentAdditionParameterDefined(contentItemNode)) { contentItem = addFromContentAdditionParameter(context, contentItemNode, name); newHash = contentItem.getHash(); // Replace the content data contentItemNode = new ModelNode(); contentItemNode.get(CONTENT_HASH.getName()).set(newHash); content.clear(); content.add(contentItemNode); } else { contentItem = addUnmanaged(context, contentItemNode); newHash = null; } // deploymentModel.get(NAME).set(name); // already there deploymentModel.get(RUNTIME_NAME.getName()).set(runtimeName); deploymentModel.get(CONTENT).set(content); // The 'persistent' and 'owner' parameters are hidden internal API, so handle them specifically // Persistent is hidden from CLI users so let's set this to true here if it is not defined if (!operation.hasDefined(PERSISTENT.getName())) { operation.get(PERSISTENT.getName()).set(true); } PERSISTENT.validateAndSet(operation, deploymentModel); OWNER.validateAndSet(operation, deploymentModel); // ENABLED stays as is if not present in operation boolean wasDeployed = ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean(); if (operation.hasDefined(ENABLED.getName())) { ENABLED.validateAndSet(operation, deploymentModel); } // Do the runtime part if the deployment is enabled if (ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean()) { DeploymentUtils.enableAttribute(deploymentModel); } else if (wasDeployed) { DeploymentUtils.disableAttribute(deploymentModel); } boolean persistent = PERSISTENT.resolveModelAttribute(context, operation).asBoolean(); final Resource resource = Resource.Factory.create(!persistent); resource.writeModel(deploymentModel); context.addResource(PathAddress.pathAddress(deploymentPath), resource); if (ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean()) { DeploymentHandlerUtil.replace(context, originalDeployment, runtimeName, name, replacedRuntimeName, contentItem); } else if (wasDeployed) { DeploymentHandlerUtil.undeploy(context, operation, name, runtimeName); } addFlushHandler(context, contentRepository, new OperationContext.ResultHandler() { @Override public void handleResult(ResultAction resultAction, OperationContext context, ModelNode operation) { if (resultAction == ResultAction.KEEP) { if (replacedHash != null && (newHash == null || !Arrays.equals(replacedHash, newHash))) { // The old content is no longer used; clean from repos contentRepository.removeContent(ModelContentReference.fromModelAddress(address, replacedHash)); } if (newHash != null) { contentRepository.addContentReference(ModelContentReference.fromModelAddress(address, newHash)); } } else if (newHash != null && (replacedHash == null || !Arrays.equals(replacedHash, newHash))) { // Due to rollback, the new content isn't used; clean from repos contentRepository.removeContent(ModelContentReference.fromModelAddress(address, newHash)); } } }); } DeploymentHandlerUtil.ContentItem addFromHash(ContentReference reference) throws OperationFailedException { if (!contentRepository.syncContent(reference)) { throw ServerLogger.ROOT_LOGGER.noSuchDeploymentContent(reference.getHexHash()); } return new DeploymentHandlerUtil.ContentItem(reference.getHash()); } DeploymentHandlerUtil.ContentItem addFromContentAdditionParameter(OperationContext context, ModelNode contentItemNode, String name) throws OperationFailedException { byte[] hash; InputStream in = getInputStream(context, contentItemNode); InputStream transformed = null; try { try { transformed = deploymentTransformation.doTransformation(context, contentItemNode, name, in); hash = contentRepository.addContent(transformed); } catch (IOException e) { throw createFailureException(e.toString()); } } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(transformed); } contentItemNode.clear(); // AS7-1029 contentItemNode.get(CONTENT_HASH.getName()).set(hash); // TODO: remove the content addition stuff? return new DeploymentHandlerUtil.ContentItem(hash); } DeploymentHandlerUtil.ContentItem addUnmanaged(OperationContext context, ModelNode contentItemNode) throws OperationFailedException { final String path = CONTENT_PATH.resolveModelAttribute(context, contentItemNode).asString(); final String relativeTo = asString(contentItemNode, CONTENT_RELATIVE_TO.getName()); final boolean archive = CONTENT_ARCHIVE.resolveModelAttribute(context, contentItemNode).asBoolean(); return new DeploymentHandlerUtil.ContentItem(path, relativeTo, archive); } }
ivassile/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentFullReplaceHandler.java
Java
lgpl-2.1
12,747
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "currentprojectfind.h" #include "projectexplorer.h" #include "project.h" #include "session.h" #include <coreplugin/idocument.h> #include <utils/qtcassert.h> #include <QDebug> #include <QSettings> #include <QLabel> #include <QHBoxLayout> using namespace Find; using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; using namespace TextEditor; CurrentProjectFind::CurrentProjectFind(ProjectExplorerPlugin *plugin) : AllProjectsFind(plugin), m_plugin(plugin) { connect(m_plugin, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), this, SLOT(handleProjectChanged())); } QString CurrentProjectFind::id() const { return QLatin1String("Current Project"); } QString CurrentProjectFind::displayName() const { return tr("Current Project"); } bool CurrentProjectFind::isEnabled() const { return ProjectExplorerPlugin::currentProject() != 0 && BaseFileFind::isEnabled(); } QVariant CurrentProjectFind::additionalParameters() const { Project *project = ProjectExplorerPlugin::currentProject(); if (project && project->document()) return qVariantFromValue(project->document()->fileName()); return QVariant(); } Utils::FileIterator *CurrentProjectFind::files(const QStringList &nameFilters, const QVariant &additionalParameters) const { QTC_ASSERT(additionalParameters.isValid(), return new Utils::FileIterator()); QList<Project *> allProjects = m_plugin->session()->projects(); QString projectFile = additionalParameters.toString(); foreach (Project *project, allProjects) { if (project->document() && projectFile == project->document()->fileName()) return filesForProjects(nameFilters, QList<Project *>() << project); } return new Utils::FileIterator(); } QString CurrentProjectFind::label() const { QTC_ASSERT(ProjectExplorerPlugin::currentProject(), return QString()); return tr("Project '%1':").arg(ProjectExplorerPlugin::currentProject()->displayName()); } void CurrentProjectFind::handleProjectChanged() { emit enabledChanged(isEnabled()); } void CurrentProjectFind::writeSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); writeCommonSettings(settings); settings->endGroup(); } void CurrentProjectFind::readSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); readCommonSettings(settings, QString(QLatin1Char('*'))); settings->endGroup(); }
ostash/qt-creator-i18n-uk
src/plugins/projectexplorer/currentprojectfind.cpp
C++
lgpl-2.1
3,806
package org.intermine.sql.writebatch; /* * Copyright (C) 2002-2015 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.DataOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.intermine.model.StringConstructor; import org.postgresql.PGConnection; import org.postgresql.copy.CopyManager; /** * An implementation of the BatchWriter interface that uses PostgreSQL-specific COPY commands. * * @author Matthew Wakeling */ public class BatchWriterPostgresCopyImpl extends BatchWriterPreparedStatementImpl { private static final Logger LOG = Logger.getLogger(BatchWriterPostgresCopyImpl.class); protected static final BigInteger TEN = new BigInteger("10"); protected static final BigInteger HUNDRED = new BigInteger("100"); protected static final BigInteger THOUSAND = new BigInteger("1000"); protected static final BigInteger TEN_THOUSAND = new BigInteger("10000"); /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected int doInserts(String name, TableBatch table, List<FlushJob> batches) throws SQLException { String[] colNames = table.getColNames(); if ((colNames != null) && (!table.getIdsToInsert().isEmpty())) { try { CopyManager copyManager = null; if (con.isWrapperFor(PGConnection.class)) { copyManager = con.unwrap(PGConnection.class).getCopyAPI(); } if (copyManager == null) { LOG.warn("Database with Connection " + con.getClass().getName() + " is incompatible with the PostgreSQL COPY command - falling" + " back to prepared statements"); super.doInserts(name, table, batches); } else { PostgresByteArrayOutputStream baos = new PostgresByteArrayOutputStream(); PostgresDataOutputStream dos = new PostgresDataOutputStream(baos); dos.writeBytes("PGCOPY\n"); dos.writeByte(255); dos.writeBytes("\r\n"); dos.writeByte(0); // Signature done dos.writeInt(0); // Flags - we aren't supplying OIDS dos.writeInt(0); // Length of header extension for (Map.Entry<Object, Object> insertEntry : table.getIdsToInsert() .entrySet()) { Object inserts = insertEntry.getValue(); if (inserts instanceof Object[]) { Object[] values = (Object[]) inserts; dos.writeShort(colNames.length); for (int i = 0; i < colNames.length; i++) { writeObject(dos, values[i]); } } else { for (Object[] values : ((List<Object[]>) inserts)) { dos.writeShort(colNames.length); for (int i = 0; i < colNames.length; i++) { writeObject(dos, values[i]); } } } } StringBuffer sqlBuffer = new StringBuffer("COPY ").append(name).append(" ("); for (int i = 0; i < colNames.length; i++) { if (i > 0) { sqlBuffer.append(", "); } sqlBuffer.append(colNames[i]); } sqlBuffer.append(") FROM STDIN BINARY"); String sql = sqlBuffer.toString(); dos.writeShort(-1); dos.flush(); batches.add(new FlushJobPostgresCopyImpl(copyManager, sql, baos.getBuffer(), baos.size())); } } catch (IOException e) { throw new SQLException(e.toString()); } return table.getIdsToInsert().size(); } return 0; } // TODO: Add support for UUID. private static void writeObject(PostgresDataOutputStream dos, Object o) throws IOException { if (o == null) { dos.writeInt(-1); } else if (o instanceof Integer) { dos.writeInt(4); dos.writeInt(((Integer) o).intValue()); } else if (o instanceof Short) { dos.writeInt(2); dos.writeShort(((Short) o).intValue()); } else if (o instanceof Boolean) { dos.writeInt(1); dos.writeByte(((Boolean) o).booleanValue() ? 1 : 0); } else if (o instanceof Float) { dos.writeInt(4); dos.writeFloat(((Float) o).floatValue()); } else if (o instanceof Double) { dos.writeInt(8); dos.writeDouble(((Double) o).doubleValue()); } else if (o instanceof Long) { dos.writeInt(8); dos.writeLong(((Long) o).longValue()); } else if (o instanceof String) { dos.writeLargeUTF((String) o); } else if (o instanceof StringConstructor) { dos.writeLargeUTF((StringConstructor) o); } else if (o instanceof BigDecimal) { BigInteger unscaledValue = ((BigDecimal) o).unscaledValue(); int signum = ((BigDecimal) o).signum(); if (signum == -1) { unscaledValue = unscaledValue.negate(); } int scale = ((BigDecimal) o).scale(); int nBaseScale = (scale + 3) / 4; int nBaseScaleRemainder = scale % 4; List<Integer> digits = new ArrayList<Integer>(); if (nBaseScaleRemainder == 1) { BigInteger[] res = unscaledValue.divideAndRemainder(TEN); int digit = res[1].intValue() * 1000; digits.add(new Integer(digit)); unscaledValue = res[0]; } else if (nBaseScaleRemainder == 2) { BigInteger[] res = unscaledValue.divideAndRemainder(HUNDRED); int digit = res[1].intValue() * 100; digits.add(new Integer(digit)); unscaledValue = res[0]; } else if (nBaseScaleRemainder == 3) { BigInteger[] res = unscaledValue.divideAndRemainder(THOUSAND); int digit = res[1].intValue() * 10; digits.add(new Integer(digit)); unscaledValue = res[0]; } while (!unscaledValue.equals(BigInteger.ZERO)) { BigInteger[] res = unscaledValue.divideAndRemainder(TEN_THOUSAND); digits.add(new Integer(res[1].intValue())); unscaledValue = res[0]; } dos.writeInt(8 + (2 * digits.size())); dos.writeShort(digits.size()); dos.writeShort(digits.size() - nBaseScale - 1); dos.writeShort(signum == 1 ? 0x0000 : 0x4000); dos.writeShort(scale); //StringBuffer log = new StringBuffer("Writing BigDecimal ") // .append(o.toString()) // .append(" as (digitCount = ") // .append(Integer.toString(digits.size())) // .append(", weight = ") // .append(Integer.toString(digits.size() - nBaseScale - 1)) // .append(", sign = ") // .append(Integer.toString(signum == 1 ? 0x0000 : 0x4000)) // .append(", dscale = ") // .append(Integer.toString(scale)) // .append(")"); for (int i = digits.size() - 1; i >= 0; i--) { int digit = digits.get(i).intValue(); dos.writeShort(digit); // log.append(" " + digit); } //LOG.error(log.toString()); } else { throw new IllegalArgumentException("Cannot store values of type " + o.getClass()); } } /** * {@inheritDoc} */ @Override protected int doIndirectionInserts(String name, IndirectionTableBatch table, List<FlushJob> batches) throws SQLException { if (!table.getRowsToInsert().isEmpty()) { try { CopyManager copyManager = null; if (con.isWrapperFor(PGConnection.class)) { copyManager = con.unwrap(PGConnection.class).getCopyAPI(); } if (copyManager == null) { LOG.warn("Database is incompatible with the PostgreSQL COPY command - falling" + " back to prepared statements"); super.doIndirectionInserts(name, table, batches); } else { PostgresByteArrayOutputStream baos = new PostgresByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeBytes("PGCOPY\n"); dos.writeByte(255); dos.writeBytes("\r\n"); dos.writeByte(0); // Signature done dos.writeInt(0); // Flags - we aren't supplying OIDS dos.writeInt(0); // Length of header extension for (Row row : table.getRowsToInsert()) { dos.writeShort(2); dos.writeInt(4); dos.writeInt(row.getLeft()); dos.writeInt(4); dos.writeInt(row.getRight()); } String sql = "COPY " + name + " (" + table.getLeftColName() + ", " + table.getRightColName() + ") FROM STDIN BINARY"; dos.writeShort(-1); dos.flush(); batches.add(new FlushJobPostgresCopyImpl(copyManager, sql, baos.getBuffer(), baos.size())); } } catch (IOException e) { throw new SQLException(e.toString()); } } return table.getRowsToInsert().size(); } /** * {@inheritDoc} */ @Override protected int getTableSize(String name, Connection conn) throws SQLException { Statement s = conn.createStatement(); ResultSet r = s.executeQuery("SELECT reltuples FROM pg_class WHERE relname = '" + name.toLowerCase() + "'"); if (r.next()) { int returnValue = (int) r.getFloat(1); if (r.next()) { throw new SQLException("Too many results for table " + name.toLowerCase()); } return returnValue; } else { throw new SQLException("No results"); } } }
tomck/intermine
intermine/objectstore/main/src/org/intermine/sql/writebatch/BatchWriterPostgresCopyImpl.java
Java
lgpl-2.1
11,352
<?php /*************************************************************************************/ /* */ /* Thelia */ /* */ /* Copyright (c) OpenStudio */ /* email : info@thelia.net */ /* web : http://www.thelia.net */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 3 of the License */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /*************************************************************************************/ $bootstrapToggle = false; $bootstraped = false; // Autoload bootstrap foreach ($argv as $arg) { if ($arg === '-b') { $bootstrapToggle = true; continue; } if ($bootstrapToggle) { require __DIR__ . DIRECTORY_SEPARATOR . $arg; $bootstraped = true; } } if (!$bootstraped) { if (isset($bootstrapFile)) { require $bootstrapFile; } elseif (is_file($file = __DIR__ . '/../core/vendor/autoload.php')) { require $file; } elseif (is_file($file = __DIR__ . '/../../bootstrap.php')) { // Here we are on a thelia/thelia-project require $file; } else { cliOutput('No autoload file found. Please use the -b argument to include yours', 'error'); exit(1); } } if (php_sapi_name() != 'cli') { cliOutput('this script can only be launched with cli sapi', 'error'); exit(1); } use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Thelia\Install\Exception\UpdateException; /*************************************************** * Load Update class ***************************************************/ try { $update = new \Thelia\Install\Update(false); } catch (UpdateException $ex) { cliOutput($ex->getMessage(), 'error'); exit(2); } /*************************************************** * Check if update is needed ***************************************************/ if ($update->isLatestVersion()) { cliOutput("You already have the latest version of Thelia : " . $update->getCurrentVersion(), 'success'); exit(3); } $current = $update->getCurrentVersion(); $files = $update->getLatestVersion(); $web = $update->getWebVersion(); while (1) { if ($web !== null && $files != $web) { cliOutput(sprintf( "Thelia server is reporting the current stable release version is %s ", $web ), 'warning'); } cliOutput(sprintf( "You are going to update Thelia from version %s to version %s.", $current, $files ), 'info'); if ($web !== null && $files < $web) { cliOutput(sprintf( "Your files belongs to version %s, which is not the latest stable release.", $web ), 'warning'); cliOutput(sprintf( "It is recommended to upgrade your files first then run this script again." . PHP_EOL . "The latest version is available at http://thelia.net/#download ." ), 'warning'); cliOutput("Continue update process anyway ? (Y/n)"); } else { cliOutput("Continue update process ? (Y/n)"); } $rep = readStdin(true); if ($rep == 'y') { break; } elseif ($rep == 'n') { cliOutput("Update aborted", 'warning'); exit(0); } } $backup = false; while (1) { cliOutput(sprintf("Would you like to backup the current database before proceeding ? (Y/n)")); $rep = readStdin(true); if ($rep == 'y') { $backup = true; break; } elseif ($rep == 'n') { $backup = false; break; } } /*************************************************** * Update ***************************************************/ $updateError = null; try { // backup db if (true === $backup) { try { $update->backupDb(); cliOutput(sprintf('Your database has been backed up. The sql file : %s', $update->getBackupFile()), 'info'); } catch (\Exception $e) { cliOutput('Sorry, your database can\'t be backed up. Reason : ' . $e->getMessage(), 'error'); exit(4); } } // update $update->process($backup); } catch (UpdateException $ex) { $updateError = $ex; } foreach ($update->getMessages() as $message) { cliOutput($message[0], $message[1]); } if (null === $updateError) { cliOutput(sprintf('Thelia as been successfully updated to version %s', $update->getCurrentVersion()), 'success'); if ($update->hasPostInstructions()) { cliOutput('==================================='); cliOutput($update->getPostInstructions()); cliOutput('==================================='); } } else { cliOutput(sprintf('Sorry, an unexpected error has occured : %s', $updateError->getMessage()), 'error'); print $updateError->getTraceAsString() . PHP_EOL; print "Trace: " . PHP_EOL; foreach ($update->getLogs() as $log) { cliOutput(sprintf('[%s] %s' . PHP_EOL, $log[0], $log[1]), 'error'); } if (true === $backup) { while (1) { cliOutput("Would you like to restore the backup database ? (Y/n)"); $rep = readStdin(true); if ($rep == 'y') { cliOutput("Database restore started. Wait, it could take a while..."); if (false === $update->restoreDb()) { cliOutput(sprintf( 'Sorry, your database can\'t be restore. Try to do it manually : %s', $update->getBackupFile() ), 'error'); exit(5); } else { cliOutput("Database successfully restore."); exit(5); } break; } elseif ($rep == 'n') { exit(0); } } } } /*************************************************** * Try to delete cache ***************************************************/ $finder = new Finder(); $fs = new Filesystem(); $hasDeleteError = false; $finder->files()->in(THELIA_CACHE_DIR); cliOutput(sprintf("Try to delete cache in : %s", THELIA_CACHE_DIR), 'info'); foreach ($finder as $file) { try { $fs->remove($file); } catch (\Symfony\Component\Filesystem\Exception\IOException $ex) { $hasDeleteError = true; } } if (true === $hasDeleteError) { cliOutput("The cache has not been cleared properly. Try to run the command manually : " . "(sudo) php Thelia cache:clear (--env=prod)."); } cliOutput("Update process finished.", 'info'); exit(0); /*************************************************** * Utils ***************************************************/ function readStdin($normalize = false) { $fr = fopen("php://stdin", "r"); $input = fgets($fr, 128); $input = rtrim($input); fclose($fr); if ($normalize) { $input = strtolower(trim($input)); } return $input; } function joinPaths() { $args = func_get_args(); $paths = []; foreach ($args as $arg) { $paths[] = trim($arg, '/\\'); } $path = join(DIRECTORY_SEPARATOR, $paths); if (substr($args[0], 0, 1) === '/') { $path = DIRECTORY_SEPARATOR . $path; } return $path; } function cliOutput($message, $type = null) { switch ($type) { case 'success': $color = "\033[0;32m"; break; case 'info': $color = "\033[0;34m"; break; case 'error': $color = "\033[0;31m"; break; case 'warning': $color = "\033[1;33m"; break; default: $color = "\033[0m"; } echo PHP_EOL . $color . $message . "\033[0m" . PHP_EOL; }
vigourouxjulien/thelia
setup/update.php
PHP
lgpl-3.0
9,119
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.filesys.repo.rules.operations; import org.alfresco.filesys.repo.OpenFileMode; import org.alfresco.filesys.repo.rules.Operation; import org.alfresco.service.cmr.repository.NodeRef; /** * Open File Operation. * <p> * Open a file with the given name. */ public class OpenFileOperation implements Operation { private String name; private OpenFileMode mode; private boolean truncate = false; private String path; private NodeRef rootNode; /** * * @param name the name of the file to open * @param mode if true open the file in read/write * @param truncate boolean * @param rootNode root node * @param path the full path/name to open */ public OpenFileOperation(String name, OpenFileMode mode, boolean truncate, NodeRef rootNode, String path) { this.name = name; this.rootNode = rootNode; this.truncate = truncate; this.path = path; this.mode = mode; } public String getName() { return name; } public String getPath() { return path; } public NodeRef getRootNodeRef() { return rootNode; } public OpenFileMode getMode() { return mode; } public boolean isTruncate() { return truncate; } public String toString() { return "OpenFileOperation: " + name; } public int hashCode() { return name.hashCode(); } public boolean equals(Object o) { if(o instanceof OpenFileOperation) { OpenFileOperation c = (OpenFileOperation)o; if(name.equals(c.getName())) { return true; } } return false; } }
Tybion/community-edition
projects/repository/source/java/org/alfresco/filesys/repo/rules/operations/OpenFileOperation.java
Java
lgpl-3.0
2,566
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetVMGetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetVMGetMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); string instanceId = (string)ParseParameter(invokeMethodInputParameters[2]); if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId)) { var result = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId); WriteObject(result); } else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName)) { var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName); WriteObject(result); } } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetVMGetParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; string instanceId = string.Empty; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceId" }, new object[] { resourceGroupName, vmScaleSetName, instanceId }); } } [Cmdlet("Get", "AzureRmVmssVM", DefaultParameterSetName = "InvokeByDynamicParameters")] public partial class GetAzureRmVmssVM : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { if (this.ParameterSetName == "InvokeByDynamicParameters") { this.MethodName = "VirtualMachineScaleSetVMGet"; } else { this.MethodName = "VirtualMachineScaleSetVMGetInstanceView"; } base.ProcessRecord(); } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = false, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 1, Mandatory = false, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = false, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 2, Mandatory = false, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pInstanceView = new RuntimeDefinedParameter(); pInstanceView.Name = "InstanceView"; pInstanceView.ParameterType = typeof(SwitchParameter); pInstanceView.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 4, Mandatory = true }); pInstanceView.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParametersForFriendMethod", Position = 5, Mandatory = true }); pInstanceView.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceView", pInstanceView); return dynamicParameters; } } }
nemanja88/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Generated/VirtualMachineScaleSetVM/VirtualMachineScaleSetVMGetMethod.cs
C#
apache-2.0
9,368
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.utilities.status; public class ServerState { public static final ServerState NEW_SERVER = new ServerState("New Server"); public static final ServerState NOT_STARTING = new ServerState("Not Starting"); public static final ServerState STARTING = new ServerState("Starting"); public static final ServerState STARTED = new ServerState("Started"); public static final ServerState STARTUP_FAILED = new ServerState("Startup Failed"); public static final ServerState STOPPING = new ServerState("Stopping"); public static final ServerState STOPPED = new ServerState("Stopped"); public static final ServerState STOPPED_WITH_ERR = new ServerState("Stopped with error"); public static final ServerState[] STATES = new ServerState[] {NEW_SERVER, NOT_STARTING, STARTING, STARTED, STARTUP_FAILED, STOPPING, STOPPED, STOPPED_WITH_ERR}; private final String _name; private ServerState(String name) { _name = name; } public String getName() { return _name; } @Override public String toString() { return _name; } public static ServerState fromString(String name) throws Exception { for (ServerState element : STATES) { if (element.getName().equals(name)) { return element; } } throw new Exception("Unrecognized Server State: " + name); } }
andreasnef/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/utilities/status/ServerState.java
Java
apache-2.0
1,711
#region License // // Copyright (c) 2018, Fluent Migrator Project // // 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. // #endregion using FluentMigrator.Runner; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; namespace FluentMigrator.Tests.Integration.Processors.Oracle.OracleNative { [TestFixture] [Category("Oracle")] public class OracleColumnTests : OracleColumnTestsBase { /// <inheritdoc /> protected override IServiceCollection AddOracleServices(IServiceCollection services) { return services.ConfigureRunner(r => r.AddOracle()); } } }
eloekset/fluentmigrator
test/FluentMigrator.Tests/Integration/Processors/Oracle/OracleNative/OracleColumnTests.cs
C#
apache-2.0
1,137
#include "cbase.h" #include "asw_weapon_hornet_barrage.h" #ifdef CLIENT_DLL #include "c_asw_player.h" #include "c_asw_marine.h" #include "c_asw_alien.h" #include "asw_input.h" #include "prediction.h" #else #include "asw_marine.h" #include "asw_player.h" #include "asw_alien.h" #include "particle_parse.h" #include "te_effect_dispatch.h" #include "asw_rocket.h" #include "asw_gamerules.h" #endif #include "asw_marine_skills.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Weapon_Hornet_Barrage, DT_ASW_Weapon_Hornet_Barrage ) BEGIN_NETWORK_TABLE( CASW_Weapon_Hornet_Barrage, DT_ASW_Weapon_Hornet_Barrage ) #ifdef CLIENT_DLL RecvPropFloat( RECVINFO( m_flNextLaunchTime ) ), RecvPropFloat( RECVINFO( m_flFireInterval ) ), RecvPropInt( RECVINFO( m_iRocketsToFire ) ), #else SendPropFloat( SENDINFO( m_flNextLaunchTime ) ), SendPropFloat( SENDINFO( m_flFireInterval ) ), SendPropInt( SENDINFO( m_iRocketsToFire ), 8 ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CASW_Weapon_Hornet_Barrage ) DEFINE_PRED_FIELD_TOL( m_flNextLaunchTime, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), DEFINE_PRED_FIELD( m_iRocketsToFire, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), END_PREDICTION_DATA() #endif LINK_ENTITY_TO_CLASS( asw_weapon_hornet_barrage, CASW_Weapon_Hornet_Barrage ); PRECACHE_WEAPON_REGISTER( asw_weapon_hornet_barrage ); #ifndef CLIENT_DLL //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CASW_Weapon_Hornet_Barrage ) END_DATADESC() #endif /* not client */ CASW_Weapon_Hornet_Barrage::CASW_Weapon_Hornet_Barrage() { } void CASW_Weapon_Hornet_Barrage::Precache() { BaseClass::Precache(); PrecacheScriptSound( "ASW_Hornet_Barrage.Fire" ); } bool CASW_Weapon_Hornet_Barrage::OffhandActivate() { if (!GetMarine() || GetMarine()->GetFlags() & FL_FROZEN) // don't allow this if the marine is frozen return false; PrimaryAttack(); return true; } void CASW_Weapon_Hornet_Barrage::PrimaryAttack() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return; CASW_Player *pPlayer = GetCommander(); if ( !pPlayer ) return; if ( m_iRocketsToFire.Get() > 0 ) return; #ifndef CLIENT_DLL bool bThisActive = (pMarine && pMarine->GetActiveWeapon() == this); #endif // mine weapon is lost when all mines are gone if ( UsesClipsForAmmo1() && !m_iClip1 ) { //Reload(); #ifndef CLIENT_DLL if (pMarine) { pMarine->Weapon_Detach(this); if (bThisActive) pMarine->SwitchToNextBestWeapon(NULL); } Kill(); #endif return; } SetRocketsToFire(); m_flFireInterval = GetRocketFireInterval(); m_flNextLaunchTime = gpGlobals->curtime; const char *pszSound = "ASW_Hornet_Barrage.Fire"; CPASAttenuationFilter filter( this, pszSound ); if ( IsPredicted() && CBaseEntity::GetPredictionPlayer() ) { filter.UsePredictionRules(); } EmitSound( filter, entindex(), pszSound ); // decrement ammo m_iClip1 -= 1; m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate(); } void CASW_Weapon_Hornet_Barrage::ItemPostFrame( void ) { BaseClass::ItemPostFrame(); if ( GetRocketsToFire() > 0 && GetNextLaunchTime() <= gpGlobals->curtime ) { FireRocket(); #ifndef CLIENT_DLL if ( GetRocketsToFire() <= 0 ) { DestroyIfEmpty( true ); } #endif } } void CASW_Weapon_Hornet_Barrage::SetRocketsToFire() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return; m_iRocketsToFire = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_COUNT ); } float CASW_Weapon_Hornet_Barrage::GetRocketFireInterval() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return 0.5f; return MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_INTERVAL ); } void CASW_Weapon_Hornet_Barrage::FireRocket() { CASW_Player *pPlayer = GetCommander(); CASW_Marine *pMarine = GetMarine(); if ( !pPlayer || !pMarine || pMarine->GetHealth() <= 0 ) { m_iRocketsToFire = 0; return; } WeaponSound(SINGLE); // tell the marine to tell its weapon to draw the muzzle flash pMarine->DoMuzzleFlash(); pMarine->DoAnimationEvent( PLAYERANIMEVENT_FIRE_GUN_PRIMARY ); Vector vecSrc = GetRocketFiringPosition(); m_iRocketsToFire = m_iRocketsToFire.Get() - 1; m_flNextLaunchTime = gpGlobals->curtime + m_flFireInterval.Get(); #ifndef CLIENT_DLL float fGrenadeDamage = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_DMG ); CASW_Rocket::Create( fGrenadeDamage, vecSrc, GetRocketAngle(), pMarine, this ); if ( ASWGameRules() ) { ASWGameRules()->m_fLastFireTime = gpGlobals->curtime; } pMarine->OnWeaponFired( this, 1 ); #endif } const QAngle& CASW_Weapon_Hornet_Barrage::GetRocketAngle() { static QAngle angRocket = vec3_angle; CASW_Player *pPlayer = GetCommander(); CASW_Marine *pMarine = GetMarine(); if ( !pPlayer || !pMarine || pMarine->GetHealth() <= 0 ) { return angRocket; } Vector vecDir = pPlayer->GetAutoaimVectorForMarine(pMarine, GetAutoAimAmount(), GetVerticalAdjustOnlyAutoAimAmount()); // 45 degrees = 0.707106781187 VectorAngles( vecDir, angRocket ); angRocket[ YAW ] += random->RandomFloat( -35, 35 ); return angRocket; } const Vector& CASW_Weapon_Hornet_Barrage::GetRocketFiringPosition() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return vec3_origin; static Vector vecSrc; vecSrc = pMarine->Weapon_ShootPosition(); return vecSrc; }
ppittle/AlienSwarmDirectorMod
trunk/src/game/shared/swarm/asw_weapon_hornet_barrage.cpp
C++
apache-2.0
5,658
# Copyright 2013 OpenStack Foundation. # 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. import os import socket import ssl import urllib2 import mock from oslo_config import cfg import testtools import webob import webob.exc from neutron.common import exceptions as exception from neutron.tests import base from neutron import wsgi CONF = cfg.CONF TEST_VAR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'var')) def open_no_proxy(*args, **kwargs): # NOTE(jamespage): # Deal with more secure certification chain verficiation # introduced in python 2.7.9 under PEP-0476 # https://github.com/python/peps/blob/master/pep-0476.txt if hasattr(ssl, "_create_unverified_context"): opener = urllib2.build_opener( urllib2.ProxyHandler({}), urllib2.HTTPSHandler(context=ssl._create_unverified_context()) ) else: opener = urllib2.build_opener(urllib2.ProxyHandler({})) return opener.open(*args, **kwargs) class TestWorkerService(base.BaseTestCase): """WorkerService tests.""" @mock.patch('neutron.db.api') def test_start_withoutdb_call(self, apimock): _service = mock.Mock() _service.pool = mock.Mock() _service.pool.spawn = mock.Mock() _service.pool.spawn.return_value = None _app = mock.Mock() cfg.CONF.set_override("connection", "", "database") workerservice = wsgi.WorkerService(_service, _app) workerservice.start() self.assertFalse(apimock.get_engine.called) class TestWSGIServer(base.BaseTestCase): """WSGI server tests.""" def test_start_random_port(self): server = wsgi.Server("test_random_port") server.start(None, 0, host="127.0.0.1") self.assertNotEqual(0, server.port) server.stop() server.wait() @mock.patch('neutron.openstack.common.service.ProcessLauncher') def test_start_multiple_workers(self, ProcessLauncher): launcher = ProcessLauncher.return_value server = wsgi.Server("test_multiple_processes") server.start(None, 0, host="127.0.0.1", workers=2) launcher.launch_service.assert_called_once_with(mock.ANY, workers=2) server.stop() launcher.stop.assert_called_once_with() server.wait() launcher.wait.assert_called_once_with() def test_start_random_port_with_ipv6(self): server = wsgi.Server("test_random_port") server.start(None, 0, host="::1") self.assertEqual("::1", server.host) self.assertNotEqual(0, server.port) server.stop() server.wait() def test_ipv6_listen_called_with_scope(self): server = wsgi.Server("test_app") with mock.patch.object(wsgi.eventlet, 'listen') as mock_listen: with mock.patch.object(socket, 'getaddrinfo') as mock_get_addr: mock_get_addr.return_value = [ (socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', ('fe80::204:acff:fe96:da87%eth0', 1234, 0, 2)) ] with mock.patch.object(server, 'pool') as mock_pool: server.start(None, 1234, host="fe80::204:acff:fe96:da87%eth0") mock_get_addr.assert_called_once_with( "fe80::204:acff:fe96:da87%eth0", 1234, socket.AF_UNSPEC, socket.SOCK_STREAM ) mock_listen.assert_called_once_with( ('fe80::204:acff:fe96:da87%eth0', 1234, 0, 2), family=socket.AF_INET6, backlog=cfg.CONF.backlog ) mock_pool.spawn.assert_has_calls([ mock.call( server._run, None, mock_listen.return_value) ]) def test_app(self): greetings = 'Hello, World!!!' def hello_world(env, start_response): if env['PATH_INFO'] != '/': start_response('404 Not Found', [('Content-Type', 'text/plain')]) return ['Not Found\r\n'] start_response('200 OK', [('Content-Type', 'text/plain')]) return [greetings] server = wsgi.Server("test_app") server.start(hello_world, 0, host="127.0.0.1") response = open_no_proxy('http://127.0.0.1:%d/' % server.port) self.assertEqual(greetings, response.read()) server.stop() @mock.patch.object(wsgi, 'eventlet') @mock.patch.object(wsgi, 'loggers') def test__run(self, logging_mock, eventlet_mock): server = wsgi.Server('test') server._run("app", "socket") eventlet_mock.wsgi.server.assert_called_once_with( 'socket', 'app', max_size=server.num_threads, log=mock.ANY, keepalive=CONF.wsgi_keep_alive, socket_timeout=server.client_socket_timeout ) self.assertTrue(len(logging_mock.mock_calls)) class SerializerTest(base.BaseTestCase): def test_serialize_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" input_dict = {'servers': {'test': 'pass'}} content_type = 'application/unknown' serializer = wsgi.Serializer() self.assertRaises( exception.InvalidContentType, serializer.serialize, input_dict, content_type) def test_get_deserialize_handler_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" content_type = 'application/unknown' serializer = wsgi.Serializer() self.assertRaises( exception.InvalidContentType, serializer.get_deserialize_handler, content_type) def test_serialize_content_type_json(self): """Test serialize with content type json.""" input_data = {'servers': ['test=pass']} content_type = 'application/json' serializer = wsgi.Serializer() result = serializer.serialize(input_data, content_type) self.assertEqual('{"servers": ["test=pass"]}', result) def test_deserialize_raise_bad_request(self): """Test serialize verifies that exception is raises.""" content_type = 'application/unknown' data_string = 'test' serializer = wsgi.Serializer() self.assertRaises( webob.exc.HTTPBadRequest, serializer.deserialize, data_string, content_type) def test_deserialize_json_content_type(self): """Test Serializer.deserialize with content type json.""" content_type = 'application/json' data_string = '{"servers": ["test=pass"]}' serializer = wsgi.Serializer() result = serializer.deserialize(data_string, content_type) self.assertEqual({'body': {u'servers': [u'test=pass']}}, result) class RequestDeserializerTest(testtools.TestCase): def setUp(self): super(RequestDeserializerTest, self).setUp() class JSONDeserializer(object): def deserialize(self, data, action='default'): return 'pew_json' self.body_deserializers = {'application/json': JSONDeserializer()} self.deserializer = wsgi.RequestDeserializer(self.body_deserializers) def test_get_deserializer(self): """Test RequestDeserializer.get_body_deserializer.""" expected_json_serializer = self.deserializer.get_body_deserializer( 'application/json') self.assertEqual( expected_json_serializer, self.body_deserializers['application/json']) def test_get_expected_content_type(self): """Test RequestDeserializer.get_expected_content_type.""" request = wsgi.Request.blank('/') request.headers['Accept'] = 'application/json' self.assertEqual('application/json', self.deserializer.get_expected_content_type(request)) def test_get_action_args(self): """Test RequestDeserializer.get_action_args.""" env = { 'wsgiorg.routing_args': [None, { 'controller': None, 'format': None, 'action': 'update', 'id': 12}]} expected = {'action': 'update', 'id': 12} self.assertEqual(expected, self.deserializer.get_action_args(env)) def test_deserialize(self): """Test RequestDeserializer.deserialize.""" with mock.patch.object( self.deserializer, 'get_action_args') as mock_method: mock_method.return_value = {'action': 'create'} request = wsgi.Request.blank('/') request.headers['Accept'] = 'application/json' deserialized = self.deserializer.deserialize(request) expected = ('create', {}, 'application/json') self.assertEqual(expected, deserialized) def test_get_body_deserializer_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" content_type = 'application/unknown' deserializer = wsgi.RequestDeserializer() self.assertRaises( exception.InvalidContentType, deserializer.get_body_deserializer, content_type) class ResponseSerializerTest(testtools.TestCase): def setUp(self): super(ResponseSerializerTest, self).setUp() class JSONSerializer(object): def serialize(self, data, action='default'): return 'pew_json' class HeadersSerializer(object): def serialize(self, response, data, action): response.status_int = 404 self.body_serializers = {'application/json': JSONSerializer()} self.serializer = wsgi.ResponseSerializer( self.body_serializers, HeadersSerializer()) def test_serialize_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" self.assertRaises( exception.InvalidContentType, self.serializer.serialize, {}, 'application/unknown') def test_get_body_serializer(self): """Verify that exception InvalidContentType is raised.""" self.assertRaises( exception.InvalidContentType, self.serializer.get_body_serializer, 'application/unknown') def test_get_serializer(self): """Test ResponseSerializer.get_body_serializer.""" content_type = 'application/json' self.assertEqual(self.body_serializers[content_type], self.serializer.get_body_serializer(content_type)) def test_serialize_json_response(self): response = self.serializer.serialize({}, 'application/json') self.assertEqual('application/json', response.headers['Content-Type']) self.assertEqual('pew_json', response.body) self.assertEqual(404, response.status_int) def test_serialize_response_None(self): response = self.serializer.serialize( None, 'application/json') self.assertEqual('application/json', response.headers['Content-Type']) self.assertEqual('', response.body) self.assertEqual(404, response.status_int) class RequestTest(base.BaseTestCase): def test_content_type_missing(self): request = wsgi.Request.blank('/tests/123', method='POST') request.body = "<body />" self.assertIsNone(request.get_content_type()) def test_content_type_unsupported(self): request = wsgi.Request.blank('/tests/123', method='POST') request.headers["Content-Type"] = "text/html" request.body = "fake<br />" self.assertIsNone(request.get_content_type()) def test_content_type_with_charset(self): request = wsgi.Request.blank('/tests/123') request.headers["Content-Type"] = "application/json; charset=UTF-8" result = request.get_content_type() self.assertEqual("application/json", result) def test_content_type_with_given_content_types(self): request = wsgi.Request.blank('/tests/123') request.headers["Content-Type"] = "application/new-type;" self.assertIsNone(request.get_content_type()) def test_content_type_from_accept(self): request = wsgi.Request.blank('/tests/123') request.headers["Accept"] = "application/json" result = request.best_match_content_type() self.assertEqual("application/json", result) request = wsgi.Request.blank('/tests/123') request.headers["Accept"] = ("application/json; q=0.3") result = request.best_match_content_type() self.assertEqual("application/json", result) def test_content_type_from_query_extension(self): request = wsgi.Request.blank('/tests/123.json') result = request.best_match_content_type() self.assertEqual("application/json", result) request = wsgi.Request.blank('/tests/123.invalid') result = request.best_match_content_type() self.assertEqual("application/json", result) def test_content_type_accept_and_query_extension(self): request = wsgi.Request.blank('/tests/123.json') request.headers["Accept"] = "application/json" result = request.best_match_content_type() self.assertEqual("application/json", result) def test_content_type_accept_default(self): request = wsgi.Request.blank('/tests/123.unsupported') request.headers["Accept"] = "application/unsupported1" result = request.best_match_content_type() self.assertEqual("application/json", result) def test_content_type_accept_with_given_content_types(self): request = wsgi.Request.blank('/tests/123') request.headers["Accept"] = "application/new_type" result = request.best_match_content_type() self.assertEqual("application/json", result) class ActionDispatcherTest(base.BaseTestCase): def test_dispatch(self): """Test ActionDispatcher.dispatch.""" serializer = wsgi.ActionDispatcher() serializer.create = lambda x: x self.assertEqual('pants', serializer.dispatch('pants', action='create')) def test_dispatch_action_None(self): """Test ActionDispatcher.dispatch with none action.""" serializer = wsgi.ActionDispatcher() serializer.create = lambda x: x + ' pants' serializer.default = lambda x: x + ' trousers' self.assertEqual('Two trousers', serializer.dispatch('Two', action=None)) def test_dispatch_default(self): serializer = wsgi.ActionDispatcher() serializer.create = lambda x: x + ' pants' serializer.default = lambda x: x + ' trousers' self.assertEqual('Two trousers', serializer.dispatch('Two', action='update')) class ResponseHeadersSerializerTest(base.BaseTestCase): def test_default(self): serializer = wsgi.ResponseHeaderSerializer() response = webob.Response() serializer.serialize(response, {'v': '123'}, 'fake') self.assertEqual(200, response.status_int) def test_custom(self): class Serializer(wsgi.ResponseHeaderSerializer): def update(self, response, data): response.status_int = 404 response.headers['X-Custom-Header'] = data['v'] serializer = Serializer() response = webob.Response() serializer.serialize(response, {'v': '123'}, 'update') self.assertEqual(404, response.status_int) self.assertEqual('123', response.headers['X-Custom-Header']) class DictSerializerTest(base.BaseTestCase): def test_dispatch_default(self): serializer = wsgi.DictSerializer() self.assertEqual('', serializer.serialize({}, 'NonExistentAction')) class JSONDictSerializerTest(base.BaseTestCase): def test_json(self): input_dict = dict(servers=dict(a=(2, 3))) expected_json = '{"servers":{"a":[2,3]}}' serializer = wsgi.JSONDictSerializer() result = serializer.serialize(input_dict) result = result.replace('\n', '').replace(' ', '') self.assertEqual(expected_json, result) def test_json_with_utf8(self): input_dict = dict(servers=dict(a=(2, '\xe7\xbd\x91\xe7\xbb\x9c'))) expected_json = '{"servers":{"a":[2,"\\u7f51\\u7edc"]}}' serializer = wsgi.JSONDictSerializer() result = serializer.serialize(input_dict) result = result.replace('\n', '').replace(' ', '') self.assertEqual(expected_json, result) def test_json_with_unicode(self): input_dict = dict(servers=dict(a=(2, u'\u7f51\u7edc'))) expected_json = '{"servers":{"a":[2,"\\u7f51\\u7edc"]}}' serializer = wsgi.JSONDictSerializer() result = serializer.serialize(input_dict) result = result.replace('\n', '').replace(' ', '') self.assertEqual(expected_json, result) class TextDeserializerTest(base.BaseTestCase): def test_dispatch_default(self): deserializer = wsgi.TextDeserializer() self.assertEqual({}, deserializer.deserialize({}, 'update')) class JSONDeserializerTest(base.BaseTestCase): def test_json(self): data = """{"a": { "a1": "1", "a2": "2", "bs": ["1", "2", "3", {"c": {"c1": "1"}}], "d": {"e": "1"}, "f": "1"}}""" as_dict = { 'body': { 'a': { 'a1': '1', 'a2': '2', 'bs': ['1', '2', '3', {'c': {'c1': '1'}}], 'd': {'e': '1'}, 'f': '1'}}} deserializer = wsgi.JSONDeserializer() self.assertEqual(as_dict, deserializer.deserialize(data)) def test_default_raise_Malformed_Exception(self): """Test JsonDeserializer.default. Test verifies JsonDeserializer.default raises exception MalformedRequestBody correctly. """ data_string = "" deserializer = wsgi.JSONDeserializer() self.assertRaises( exception.MalformedRequestBody, deserializer.default, data_string) def test_json_with_utf8(self): data = '{"a": "\xe7\xbd\x91\xe7\xbb\x9c"}' as_dict = {'body': {'a': u'\u7f51\u7edc'}} deserializer = wsgi.JSONDeserializer() self.assertEqual(as_dict, deserializer.deserialize(data)) def test_json_with_unicode(self): data = '{"a": "\u7f51\u7edc"}' as_dict = {'body': {'a': u'\u7f51\u7edc'}} deserializer = wsgi.JSONDeserializer() self.assertEqual(as_dict, deserializer.deserialize(data)) class RequestHeadersDeserializerTest(base.BaseTestCase): def test_default(self): deserializer = wsgi.RequestHeadersDeserializer() req = wsgi.Request.blank('/') self.assertEqual({}, deserializer.deserialize(req, 'nonExistent')) def test_custom(self): class Deserializer(wsgi.RequestHeadersDeserializer): def update(self, request): return {'a': request.headers['X-Custom-Header']} deserializer = Deserializer() req = wsgi.Request.blank('/') req.headers['X-Custom-Header'] = 'b' self.assertEqual({'a': 'b'}, deserializer.deserialize(req, 'update')) class ResourceTest(base.BaseTestCase): @staticmethod def my_fault_body_function(): return 'off' class Controller(object): def index(self, request, index=None): return index def test_dispatch(self): resource = wsgi.Resource(self.Controller(), self.my_fault_body_function) actual = resource.dispatch( resource.controller, 'index', action_args={'index': 'off'}) expected = 'off' self.assertEqual(expected, actual) def test_dispatch_unknown_controller_action(self): resource = wsgi.Resource(self.Controller(), self.my_fault_body_function) self.assertRaises( AttributeError, resource.dispatch, resource.controller, 'create', {}) def test_malformed_request_body_throws_bad_request(self): resource = wsgi.Resource(None, self.my_fault_body_function) request = wsgi.Request.blank( "/", body="{mal:formed", method='POST', headers={'Content-Type': "application/json"}) response = resource(request) self.assertEqual(400, response.status_int) def test_wrong_content_type_throws_unsupported_media_type_error(self): resource = wsgi.Resource(None, self.my_fault_body_function) request = wsgi.Request.blank( "/", body="{some:json}", method='POST', headers={'Content-Type': "xxx"}) response = resource(request) self.assertEqual(400, response.status_int) def test_wrong_content_type_server_error(self): resource = wsgi.Resource(None, self.my_fault_body_function) request = wsgi.Request.blank( "/", method='POST', headers={'Content-Type': "unknow"}) response = resource(request) self.assertEqual(500, response.status_int) def test_call_resource_class_bad_request(self): class FakeRequest(object): def __init__(self): self.url = 'http://where.no' self.environ = 'environ' self.body = 'body' def method(self): pass def best_match_content_type(self): return 'best_match_content_type' resource = wsgi.Resource(self.Controller(), self.my_fault_body_function) request = FakeRequest() result = resource(request) self.assertEqual(400, result.status_int) def test_type_error(self): resource = wsgi.Resource(self.Controller(), self.my_fault_body_function) request = wsgi.Request.blank( "/", method='POST', headers={'Content-Type': "json"}) response = resource.dispatch( request, action='index', action_args='test') self.assertEqual(400, response.status_int) def test_call_resource_class_internal_error(self): class FakeRequest(object): def __init__(self): self.url = 'http://where.no' self.environ = 'environ' self.body = '{"Content-Type": "json"}' def method(self): pass def best_match_content_type(self): return 'application/json' resource = wsgi.Resource(self.Controller(), self.my_fault_body_function) request = FakeRequest() result = resource(request) self.assertEqual(500, result.status_int) class MiddlewareTest(base.BaseTestCase): def test_process_response(self): def application(environ, start_response): response = 'Success' return response response = application('test', 'fake') result = wsgi.Middleware(application).process_response(response) self.assertEqual('Success', result) class FaultTest(base.BaseTestCase): def test_call_fault(self): class MyException(object): status_int = 415 explanation = 'test' my_exceptions = MyException() my_fault = wsgi.Fault(exception=my_exceptions) request = wsgi.Request.blank( "/", method='POST', headers={'Content-Type': "unknow"}) response = my_fault(request) self.assertEqual(415, response.status_int) class TestWSGIServerWithSSL(base.BaseTestCase): """WSGI server tests.""" def test_app_using_ssl(self): CONF.set_default('use_ssl', True) CONF.set_default("ssl_cert_file", os.path.join(TEST_VAR_DIR, 'certificate.crt')) CONF.set_default("ssl_key_file", os.path.join(TEST_VAR_DIR, 'privatekey.key')) greetings = 'Hello, World!!!' @webob.dec.wsgify def hello_world(req): return greetings server = wsgi.Server("test_app") server.start(hello_world, 0, host="127.0.0.1") response = open_no_proxy('https://127.0.0.1:%d/' % server.port) self.assertEqual(greetings, response.read()) server.stop() def test_app_using_ssl_combined_cert_and_key(self): CONF.set_default('use_ssl', True) CONF.set_default("ssl_cert_file", os.path.join(TEST_VAR_DIR, 'certandkey.pem')) greetings = 'Hello, World!!!' @webob.dec.wsgify def hello_world(req): return greetings server = wsgi.Server("test_app") server.start(hello_world, 0, host="127.0.0.1") response = open_no_proxy('https://127.0.0.1:%d/' % server.port) self.assertEqual(greetings, response.read()) server.stop() def test_app_using_ipv6_and_ssl(self): CONF.set_default('use_ssl', True) CONF.set_default("ssl_cert_file", os.path.join(TEST_VAR_DIR, 'certificate.crt')) CONF.set_default("ssl_key_file", os.path.join(TEST_VAR_DIR, 'privatekey.key')) greetings = 'Hello, World!!!' @webob.dec.wsgify def hello_world(req): return greetings server = wsgi.Server("test_app") server.start(hello_world, 0, host="::1") response = open_no_proxy('https://[::1]:%d/' % server.port) self.assertEqual(greetings, response.read()) server.stop()
pnavarro/neutron
neutron/tests/unit/test_wsgi.py
Python
apache-2.0
26,842
/** * Licensed to the Rhiot under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The licenses this file to You 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. */ package io.rhiot.component.pi4j.i2c.driver; /** * */ public class BMP180Value { private int pressure; private double temperature; public int getPressure() { return pressure; } public void setPressure(int pressure) { this.pressure = pressure; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } public String toString() { return "[temperature:" + temperature + ",pressure:" + pressure + "]"; } }
jasonchaffee/camel-labs
gateway/components/camel-pi4j/src/main/java/io/rhiot/component/pi4j/i2c/driver/BMP180Value.java
Java
apache-2.0
1,355
# Copyright 2014, Rackspace, US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf import urls urlpatterns = [] # to register the URLs for your API endpoints, decorate the view class with # @register below, and the import the endpoint module in the # rest_api/__init__.py module def register(view): """Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL regex pattern. """ p = urls.url(view.url_regex, view.as_view()) urlpatterns.append(p) return view
BiznetGIO/horizon
openstack_dashboard/api/rest/urls.py
Python
apache-2.0
1,231
/* * Copyright 2012-2021 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.build.test; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.testing.Test; import org.gradle.language.base.plugins.LifecycleBasePlugin; import org.gradle.plugins.ide.eclipse.EclipsePlugin; import org.gradle.plugins.ide.eclipse.model.EclipseModel; /** * A {@link Plugin} to configure integration testing support in a {@link Project}. * * @author Andy Wilkinson */ public class IntegrationTestPlugin implements Plugin<Project> { /** * Name of the {@code intTest} task. */ public static String INT_TEST_TASK_NAME = "intTest"; /** * Name of the {@code intTest} source set. */ public static String INT_TEST_SOURCE_SET_NAME = "intTest"; @Override public void apply(Project project) { project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> configureIntegrationTesting(project)); } private void configureIntegrationTesting(Project project) { SourceSet intTestSourceSet = createSourceSet(project); Test intTest = createTestTask(project, intTestSourceSet); project.getTasks().getByName(LifecycleBasePlugin.CHECK_TASK_NAME).dependsOn(intTest); project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> { EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add( project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName()))); }); } private SourceSet createSourceSet(Project project) { SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets(); SourceSet intTestSourceSet = sourceSets.create(INT_TEST_SOURCE_SET_NAME); SourceSet main = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); intTestSourceSet.setCompileClasspath(intTestSourceSet.getCompileClasspath().plus(main.getOutput())); intTestSourceSet.setRuntimeClasspath(intTestSourceSet.getRuntimeClasspath().plus(main.getOutput())); return intTestSourceSet; } private Test createTestTask(Project project, SourceSet intTestSourceSet) { Test intTest = project.getTasks().create(INT_TEST_TASK_NAME, Test.class); intTest.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); intTest.setDescription("Runs integration tests."); intTest.setTestClassesDirs(intTestSourceSet.getOutput().getClassesDirs()); intTest.setClasspath(intTestSourceSet.getRuntimeClasspath()); intTest.shouldRunAfter(JavaPlugin.TEST_TASK_NAME); return intTest; } }
spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java
Java
apache-2.0
3,330
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package gobblin.writer; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import com.google.common.base.Optional; import gobblin.source.extractor.CheckpointableWatermark; /** * A helper class that tracks committed and uncommitted watermarks. * Useful for implementing {@link WatermarkAwareWriter}s that wrap other {@link WatermarkAwareWriter}s. * * Note: The current implementation is not meant to be used in a high-throughput scenario * (e.g. in the path of a write or a callback). See {@link LastWatermarkTracker}. */ public class MultiWriterWatermarkTracker implements WatermarkTracker { private final ConcurrentHashMap<String, Set<CheckpointableWatermark>> candidateCommittables = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Set<CheckpointableWatermark>> unacknowledgedWatermarks = new ConcurrentHashMap<>(); /** * Reset current state */ public synchronized void reset() { candidateCommittables.clear(); unacknowledgedWatermarks.clear(); } private synchronized Set<CheckpointableWatermark> getOrCreate(Map<String, Set<CheckpointableWatermark>> map, String key) { if (map.containsKey(key)) { return map.get(key); } else { Set<CheckpointableWatermark> set = new TreeSet<>(); map.put(key, set); return set; } } @Override public void committedWatermarks(Map<String, CheckpointableWatermark> committedMap) { committedWatermarks(committedMap.values()); } public void committedWatermarks(Iterable<CheckpointableWatermark> committedStream) { for (CheckpointableWatermark committed: committedStream) { committedWatermark(committed); } } @Override public void committedWatermark(CheckpointableWatermark committed) { getOrCreate(candidateCommittables, committed.getSource()).add(committed); } @Override public void unacknowledgedWatermark(CheckpointableWatermark unacked) { getOrCreate(unacknowledgedWatermarks, unacked.getSource()).add(unacked); } @Override public void unacknowledgedWatermarks(Map<String, CheckpointableWatermark> unackedMap) { for (CheckpointableWatermark unacked: unackedMap.values()) { unacknowledgedWatermark(unacked); } } @Override public Map<String, CheckpointableWatermark> getAllCommitableWatermarks() { Map<String, CheckpointableWatermark> commitables = new HashMap<>(candidateCommittables.size()); for (String source: candidateCommittables.keySet()) { Optional<CheckpointableWatermark> commitable = getCommittableWatermark(source); if (commitable.isPresent()) { commitables.put(commitable.get().getSource(), commitable.get()); } } return commitables; } @Override public Map<String, CheckpointableWatermark> getAllUnacknowledgedWatermarks() { Map<String, CheckpointableWatermark> unackedMap = new HashMap<>(unacknowledgedWatermarks.size()); for (String source: unacknowledgedWatermarks.keySet()) { Optional<CheckpointableWatermark> unacked = getUnacknowledgedWatermark(source); if (unacked.isPresent()) { unackedMap.put(unacked.get().getSource(), unacked.get()); } } return unackedMap; } public Optional<CheckpointableWatermark> getCommittableWatermark(String source) { Set<CheckpointableWatermark> unacked = unacknowledgedWatermarks.get(source); CheckpointableWatermark minUnacknowledgedWatermark = (unacked == null || unacked.isEmpty())? null: unacked.iterator().next(); CheckpointableWatermark highestCommitableWatermark = null; for (CheckpointableWatermark commitableWatermark : candidateCommittables.get(source)) { if ((minUnacknowledgedWatermark == null) || (commitableWatermark.compareTo(minUnacknowledgedWatermark) < 0)) { // commitableWatermark < minUnacknowledgedWatermark highestCommitableWatermark = commitableWatermark; } } if (highestCommitableWatermark == null) { return Optional.absent(); } else { return Optional.of(highestCommitableWatermark); } } public Optional<CheckpointableWatermark> getUnacknowledgedWatermark(String source) { Set<CheckpointableWatermark> unacked = unacknowledgedWatermarks.get(source); if (unacked.isEmpty()) { return Optional.absent(); } else { return Optional.of(unacked.iterator().next()); } } }
ydai1124/gobblin-1
gobblin-core-base/src/main/java/gobblin/writer/MultiWriterWatermarkTracker.java
Java
apache-2.0
5,266
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.mnemonic.service.memory.internal; import java.nio.ByteBuffer; import java.util.BitSet; import java.util.HashMap; import java.util.Map; public class BufferBlockInfo { long bufferBlockBaseAddress = 0L; int bufferBlockSize; ByteBuffer bufferBlock = null; BitSet bufferBlockChunksMap = null; Map<Long, Integer> chunkSizeMap = new HashMap<>(); public ByteBuffer getBufferBlock() { return bufferBlock; } public void setBufferBlock(ByteBuffer byteBufferBlock) { this.bufferBlock = byteBufferBlock; } public BitSet getBufferBlockChunksMap() { return bufferBlockChunksMap; } public void setBufferBlockChunksMap(BitSet chunksMap) { this.bufferBlockChunksMap = chunksMap; } public long getBufferBlockBaseAddress() { return bufferBlockBaseAddress; } public void setBufferBlockBaseAddress(long bufferBlockBaseAddress) { this.bufferBlockBaseAddress = bufferBlockBaseAddress; } public int getBufferBlockSize() { return bufferBlockSize; } public void setBufferBlockSize(int blockSize) { this.bufferBlockSize = blockSize; } public Map<Long, Integer> getChunkSizeMap() { return chunkSizeMap; } public void setChunkSizeMap(long chunkHandler, int chunkSize) { chunkSizeMap.put(chunkHandler, chunkSize); } }
lql5083psu/incubator-mnemonic
mnemonic-memory-services/mnemonic-java-vmem-service/src/main/java/org/apache/mnemonic/service/memory/internal/BufferBlockInfo.java
Java
apache-2.0
2,204
/* Copyright 2017 The Kubernetes Authors. 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. */ package integration import ( "context" "testing" "time" "github.com/stretchr/testify/require" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apiextensions-apiserver/test/integration/fixtures" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" ) func TestFinalization(t *testing.T) { tearDown, apiExtensionClient, dynamicClient, err := fixtures.StartDefaultServerWithClients(t) require.NoError(t, err) defer tearDown() noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped) noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) require.NoError(t, err) ns := "not-the-default" name := "foo123" noxuResourceClient := newNamespacedCustomResourceClient(ns, dynamicClient, noxuDefinition) instance := fixtures.NewNoxuInstance(ns, name) instance.SetFinalizers([]string{"noxu.example.com/finalizer"}) createdNoxuInstance, err := instantiateCustomResource(t, instance, noxuResourceClient, noxuDefinition) require.NoError(t, err) uid := createdNoxuInstance.GetUID() err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{ Preconditions: &metav1.Preconditions{ UID: &uid, }, }) require.NoError(t, err) // Deleting something with a finalizer sets deletion timestamp to a not-nil value but does not // remove the object from the API server. Here we read it to confirm this. gottenNoxuInstance, err := noxuResourceClient.Get(name, metav1.GetOptions{}) require.NoError(t, err) require.NotNil(t, gottenNoxuInstance.GetDeletionTimestamp()) // Trying to delete it again to confirm it will not remove the object because finalizer is still there. err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{ Preconditions: &metav1.Preconditions{ UID: &uid, }, }) require.NoError(t, err) // Removing the finalizers to allow the following delete remove the object. // This step will fail if previous delete wrongly removed the object. The // object will be deleted as part of the finalizer update. for { gottenNoxuInstance.SetFinalizers(nil) _, err = noxuResourceClient.Update(gottenNoxuInstance, metav1.UpdateOptions{}) if err == nil { break } if !errors.IsConflict(err) { require.NoError(t, err) // Fail on unexpected error } gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{}) require.NoError(t, err) } // Check that the object is actually gone. _, err = noxuResourceClient.Get(name, metav1.GetOptions{}) require.Error(t, err) require.True(t, errors.IsNotFound(err), "%#v", err) } func TestFinalizationAndDeletion(t *testing.T) { tearDown, apiExtensionClient, dynamicClient, err := fixtures.StartDefaultServerWithClients(t) require.NoError(t, err) defer tearDown() // Create a CRD. noxuDefinition := fixtures.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped) noxuDefinition, err = fixtures.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, dynamicClient) require.NoError(t, err) // Create a CR with a finalizer. ns := "not-the-default" name := "foo123" noxuResourceClient := newNamespacedCustomResourceClient(ns, dynamicClient, noxuDefinition) instance := fixtures.NewNoxuInstance(ns, name) instance.SetFinalizers([]string{"noxu.example.com/finalizer"}) createdNoxuInstance, err := instantiateCustomResource(t, instance, noxuResourceClient, noxuDefinition) require.NoError(t, err) // Delete a CR. Because there's a finalizer, it will not get deleted now. uid := createdNoxuInstance.GetUID() err = noxuResourceClient.Delete(name, &metav1.DeleteOptions{ Preconditions: &metav1.Preconditions{ UID: &uid, }, }) require.NoError(t, err) // Check is the CR scheduled for deletion. gottenNoxuInstance, err := noxuResourceClient.Get(name, metav1.GetOptions{}) require.NoError(t, err) require.NotNil(t, gottenNoxuInstance.GetDeletionTimestamp()) // Delete the CRD. fixtures.DeleteCustomResourceDefinition(noxuDefinition, apiExtensionClient) // Check is CR still there after the CRD deletion. gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{}) require.NoError(t, err) // Update the CR to remove the finalizer. for { gottenNoxuInstance.SetFinalizers(nil) _, err = noxuResourceClient.Update(gottenNoxuInstance, metav1.UpdateOptions{}) if err == nil { break } if !errors.IsConflict(err) { require.NoError(t, err) // Fail on unexpected error } gottenNoxuInstance, err = noxuResourceClient.Get(name, metav1.GetOptions{}) require.NoError(t, err) } // Verify the CR is gone. // It should return the NonFound error. _, err = noxuResourceClient.Get(name, metav1.GetOptions{}) if !errors.IsNotFound(err) { t.Fatalf("unable to delete cr: %v", err) } err = wait.Poll(500*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) { _, err = apiExtensionClient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(context.TODO(), noxuDefinition.Name, metav1.GetOptions{}) return errors.IsNotFound(err), err }) if !errors.IsNotFound(err) { t.Fatalf("unable to delete crd: %v", err) } }
jfrazelle/kubernetes
staging/src/k8s.io/apiextensions-apiserver/test/integration/finalization_test.go
GO
apache-2.0
5,811
// Code generated by counterfeiter. DO NOT EDIT. package mock import ( "sync" ) type Writer struct { WriteFileStub func(string, string, []byte) error writeFileMutex sync.RWMutex writeFileArgsForCall []struct { arg1 string arg2 string arg3 []byte } writeFileReturns struct { result1 error } writeFileReturnsOnCall map[int]struct { result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *Writer) WriteFile(arg1 string, arg2 string, arg3 []byte) error { var arg3Copy []byte if arg3 != nil { arg3Copy = make([]byte, len(arg3)) copy(arg3Copy, arg3) } fake.writeFileMutex.Lock() ret, specificReturn := fake.writeFileReturnsOnCall[len(fake.writeFileArgsForCall)] fake.writeFileArgsForCall = append(fake.writeFileArgsForCall, struct { arg1 string arg2 string arg3 []byte }{arg1, arg2, arg3Copy}) fake.recordInvocation("WriteFile", []interface{}{arg1, arg2, arg3Copy}) fake.writeFileMutex.Unlock() if fake.WriteFileStub != nil { return fake.WriteFileStub(arg1, arg2, arg3) } if specificReturn { return ret.result1 } fakeReturns := fake.writeFileReturns return fakeReturns.result1 } func (fake *Writer) WriteFileCallCount() int { fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() return len(fake.writeFileArgsForCall) } func (fake *Writer) WriteFileCalls(stub func(string, string, []byte) error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = stub } func (fake *Writer) WriteFileArgsForCall(i int) (string, string, []byte) { fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() argsForCall := fake.writeFileArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *Writer) WriteFileReturns(result1 error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = nil fake.writeFileReturns = struct { result1 error }{result1} } func (fake *Writer) WriteFileReturnsOnCall(i int, result1 error) { fake.writeFileMutex.Lock() defer fake.writeFileMutex.Unlock() fake.WriteFileStub = nil if fake.writeFileReturnsOnCall == nil { fake.writeFileReturnsOnCall = make(map[int]struct { result1 error }) } fake.writeFileReturnsOnCall[i] = struct { result1 error }{result1} } func (fake *Writer) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.writeFileMutex.RLock() defer fake.writeFileMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *Writer) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) }
stemlending/fabric
internal/peer/lifecycle/chaincode/mock/writer.go
GO
apache-2.0
3,051
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.ode.karaf.commands; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.management.*; import org.apache.felix.karaf.shell.console.OsgiCommandSupport; import org.apache.ode.bpel.pmapi.*; import org.apache.ode.jbi.OdeContext; public abstract class OdeCommandsBase extends OsgiCommandSupport { protected static String COMPONENT_NAME = "org.apache.servicemix:Type=Component,Name=OdeBpelEngine,SubType=Management"; protected static final String LIST_ALL_PROCESSES = "listAllProcesses"; protected static final String LIST_ALL_INSTANCES = "listAllInstances"; protected static final String TERMINATE = "terminate"; protected MBeanServer getMBeanServer() { OdeContext ode = OdeContext.getInstance(); if (ode != null) { return ode.getContext().getMBeanServer(); } return null; } /** * Invokes an operation on the ODE MBean server * * @param <T> * @param operationName * @param args * @param T * @return */ @SuppressWarnings("unchecked") protected <T> T invoke(final String operationName, final Object[] params, final String[] signature, Class<?> T, long timeoutInSeconds) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<T> callable = new Callable<T>() { public T call() throws Exception { MBeanServer server = getMBeanServer(); if (server != null) { return (T) server.invoke(new ObjectName(COMPONENT_NAME), operationName, params, signature); } return null; } }; Future<T> future = executor.submit(callable); executor.shutdown(); return future.get(timeoutInSeconds, TimeUnit.SECONDS); } protected List<TProcessInfo> getProcesses(long timeoutInSeconds) throws Exception { ProcessInfoListDocument result = invoke(LIST_ALL_PROCESSES, null, null, ProcessInfoListDocument.class, timeoutInSeconds); if (result != null) { return result.getProcessInfoList().getProcessInfoList(); } return null; } protected List<TInstanceInfo> getActiveInstances(long timeoutInSeconds) throws Exception { InstanceInfoListDocument instances = invoke(LIST_ALL_INSTANCES, null, null, InstanceInfoListDocument.class, timeoutInSeconds); if (instances != null) { return instances.getInstanceInfoList().getInstanceInfoList(); } return null; } protected void terminate(Long iid, long timeoutInSeconds) throws Exception { invoke(TERMINATE, new Long[] { iid }, new String[] { Long.class .getName() }, InstanceInfoDocument.class, timeoutInSeconds); } }
firzhan/wso2-ode
jbi-karaf-commands/src/main/java/org/apache/ode/karaf/commands/OdeCommandsBase.java
Java
apache-2.0
3,894
package com.taobao.zeus.jobs.sub; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.ToolRunner; import com.taobao.zeus.jobs.JobContext; import com.taobao.zeus.jobs.sub.conf.ConfUtil; import com.taobao.zeus.jobs.sub.main.MapReduceMain; import com.taobao.zeus.jobs.sub.tool.DownloadHdfsFileJob; import com.taobao.zeus.store.HierarchyProperties; import com.taobao.zeus.util.RunningJobKeys; public class MapReduceJob extends JavaJob{ public MapReduceJob(JobContext jobContext) { super(jobContext); String main=getJavaClass(); String args=getMainArguments(); String classpath=getClassPaths(); jobContext.getProperties().setProperty(RunningJobKeys.RUN_JAVA_MAIN_CLASS, "com.taobao.zeus.jobs.sub.main.MapReduceMain"); classpath=getMRClassPath(classpath); jobContext.getProperties().setProperty(RunningJobKeys.RUN_CLASSPATH, classpath+ File.pathSeparator+getSourcePathFromClass(MapReduceMain.class)); jobContext.getProperties().setProperty(RunningJobKeys.RUN_JAVA_MAIN_ARGS, main+" "+args); jobContext.getProperties().setProperty(RunningJobKeys.JOB_RUN_TYPE, "MapReduceJob"); } //hadoop2依赖的JAR包,Apache需要的jar在${HADOOP_HOME}/libs/目录下,其他版本可能在${HADOOP_HOME}/lib public String getMRClassPath(String classpath){ StringBuilder sb=new StringBuilder(classpath); String hadoophome=System.getenv("HADOOP_HOME"); if(hadoophome!=null && !"".equals(hadoophome)){ File f1=new File(hadoophome+"/libs"); if(f1.exists()){ sb.append(File.pathSeparator); sb.append(hadoophome); sb.append("/libs/*"); } File f2=new File(hadoophome+"/lib"); if(f2.exists()){ sb.append(File.pathSeparator); sb.append(hadoophome); sb.append("/lib/*"); } } return sb.toString(); } @Override public Integer run() throws Exception { List<Map<String, String>> resources=jobContext.getResources(); if(resources!=null && !resources.isEmpty()){ StringBuffer sb=new StringBuffer(); for(Map<String, String> map:jobContext.getResources()){ if(map.get("uri")!=null){ String uri=map.get("uri"); if(uri.startsWith("hdfs://") && uri.endsWith(".jar")){ sb.append(uri.substring("hdfs://".length())).append(","); } } } jobContext.getProperties().setProperty("core-site.tmpjars", sb.toString().substring(0, sb.toString().length()-1)); } return super.run(); } public static void main(String[] args) { JobContext context=JobContext.getTempJobContext(JobContext.SYSTEM_RUN); Map<String, String> map=new HashMap<String, String>(); map.put("hadoop.ugi.name", "uginame"); HierarchyProperties properties=new HierarchyProperties(map); context.setProperties(properties); new MapReduceJob(context); } }
wwzhe/dataworks-zeus
web/.externalToolBuilders/schedule/src/main/java/com/taobao/zeus/jobs/sub/MapReduceJob.java
Java
apache-2.0
3,072
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package com.google.wave.api.data.converter.v22; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.collect.Lists; import com.google.wave.api.BlipData; import com.google.wave.api.BlipThread; import com.google.wave.api.impl.EventMessageBundle; import junit.framework.TestCase; import org.waveprotocol.wave.model.conversation.Blips; import org.waveprotocol.wave.model.conversation.Conversation; import org.waveprotocol.wave.model.conversation.ConversationBlip; import org.waveprotocol.wave.model.conversation.ConversationView; import org.waveprotocol.wave.model.conversation.WaveBasedConversationView; import org.waveprotocol.wave.model.document.Document; import org.waveprotocol.wave.model.document.operation.impl.DocInitializationBuilder; import org.waveprotocol.wave.model.id.IdGenerator; import org.waveprotocol.wave.model.id.WaveId; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.testing.BasicFactories; import org.waveprotocol.wave.model.testing.FakeIdGenerator; import org.waveprotocol.wave.model.wave.Wavelet; import org.waveprotocol.wave.model.wave.opbased.ObservableWaveView; import java.util.List; import java.util.Map; /** * Test cases for {@link EventDataConverterV22}. * */ public class EventDataConverterV22Test extends TestCase { private static final WaveId WAVE_ID = WaveId.of("example.com", "123"); private static final WaveletId WAVELET_ID = WaveletId.of("example.com", "conv+root"); private Conversation conversation; @Override protected void setUp() throws Exception { Blips.init(); conversation = makeConversation(); } public void testToBlipData() throws Exception { Wavelet wavelet = mock(Wavelet.class); when(wavelet.getWaveId()).thenReturn(WAVE_ID); when(wavelet.getId()).thenReturn(WAVELET_ID); ConversationBlip blip = conversation.getRootThread().getFirstBlip(); String replyThreadId = blip.addReplyThread(3).getId(); EventDataConverterV22 converter = new EventDataConverterV22(); EventMessageBundle eventMessageBundle = new EventMessageBundle(null, null); BlipData blipData = converter.toBlipData(blip, wavelet, eventMessageBundle); assertEquals(blip.getThread().getId(), blipData.getThreadId()); assertEquals(Lists.newArrayList(replyThreadId), blipData.getReplyThreadIds()); Map<String, BlipThread> threads = eventMessageBundle.getThreads(); assertEquals(1, threads.size()); assertEquals(1, threads.get(replyThreadId).getLocation()); } public void testFindBlipParent() { ConversationBlip first = conversation.getRootThread().getFirstBlip(); ConversationBlip second = conversation.getRootThread().appendBlip(); ConversationBlip reply = first.addReplyThread().appendBlip(); ConversationBlip secondReply = reply.getThread().appendBlip(); ConversationBlip inlineReply = first.addReplyThread(3).appendBlip(); EventDataConverterV22 converter = new EventDataConverterV22(); assertNull(converter.findBlipParent(first)); assertNull(converter.findBlipParent(second)); assertSame(first, converter.findBlipParent(reply)); assertSame(first, converter.findBlipParent(inlineReply)); assertSame(first, converter.findBlipParent(secondReply)); } public void testFindBlipChildren() { ConversationBlip first = conversation.getRootThread().getFirstBlip(); ConversationBlip second = conversation.getRootThread().appendBlip(); ConversationBlip reply = first.addReplyThread().appendBlip(); ConversationBlip secondReply = reply.getThread().appendBlip(); ConversationBlip inlineReply = first.addReplyThread(3).appendBlip(); EventDataConverterV22 converter = new EventDataConverterV22(); assertEquals(0, converter.findBlipChildren(second).size()); List<ConversationBlip> children = converter.findBlipChildren(first); assertEquals(3, children.size()); assertEquals(inlineReply.getId(), children.get(0).getId()); assertEquals(reply.getId(), children.get(1).getId()); assertEquals(secondReply.getId(), children.get(2).getId()); } private static Conversation makeConversation() { IdGenerator idGenerator = FakeIdGenerator.create(); ObservableWaveView waveView = BasicFactories.fakeWaveViewBuilder().with(idGenerator).build(); ConversationView convView = WaveBasedConversationView.create(waveView, idGenerator); Conversation conversation = convView.createRoot(); // Force empty document. ConversationBlip blip = conversation.getRootThread().appendBlip( new DocInitializationBuilder().build()); Document document = blip.getContent(); document.appendXml(Blips.INITIAL_BODY); return conversation; } }
vega113/incubator-wave
wave/src/test/java/com/google/wave/api/data/converter/v22/EventDataConverterV22Test.java
Java
apache-2.0
5,547
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you 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. */ package org.elasticsearch.threadpool; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor; import org.elasticsearch.test.ElasticsearchTestCase; import org.elasticsearch.threadpool.ThreadPool.Names; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.hamcrest.Matchers.*; /** */ public class UpdateThreadPoolSettingsTests extends ElasticsearchTestCase { private ThreadPool.Info info(ThreadPool threadPool, String name) { for (ThreadPool.Info info : threadPool.info()) { if (info.getName().equals(name)) { return info; } } return null; } @Test public void testCachedExecutorType() throws InterruptedException { ThreadPool threadPool = new ThreadPool( ImmutableSettings.settingsBuilder() .put("threadpool.search.type", "cached") .put("name","testCachedExecutorType").build(), null); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("cached")); assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(5L)); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); // Replace with different type threadPool.updateSettings(settingsBuilder().put("threadpool.search.type", "same").build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("same")); assertThat(threadPool.executor(Names.SEARCH), instanceOf(MoreExecutors.directExecutor().getClass())); // Replace with different type again threadPool.updateSettings(settingsBuilder() .put("threadpool.search.type", "scaling") .put("threadpool.search.keep_alive", "10m") .build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("scaling")); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getCorePoolSize(), equalTo(1)); // Make sure keep alive value changed assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(10L)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getKeepAliveTime(TimeUnit.MINUTES), equalTo(10L)); // Put old type back threadPool.updateSettings(settingsBuilder().put("threadpool.search.type", "cached").build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("cached")); // Make sure keep alive value reused assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(10L)); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); // Change keep alive Executor oldExecutor = threadPool.executor(Names.SEARCH); threadPool.updateSettings(settingsBuilder().put("threadpool.search.keep_alive", "1m").build()); // Make sure keep alive value changed assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(1L)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getKeepAliveTime(TimeUnit.MINUTES), equalTo(1L)); // Make sure executor didn't change assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("cached")); assertThat(threadPool.executor(Names.SEARCH), sameInstance(oldExecutor)); // Set the same keep alive threadPool.updateSettings(settingsBuilder().put("threadpool.search.keep_alive", "1m").build()); // Make sure keep alive value didn't change assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(1L)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getKeepAliveTime(TimeUnit.MINUTES), equalTo(1L)); // Make sure executor didn't change assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("cached")); assertThat(threadPool.executor(Names.SEARCH), sameInstance(oldExecutor)); terminate(threadPool); } @Test public void testFixedExecutorType() throws InterruptedException { ThreadPool threadPool = new ThreadPool(settingsBuilder() .put("threadpool.search.type", "fixed") .put("name","testCachedExecutorType").build(), null); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); // Replace with different type threadPool.updateSettings(settingsBuilder() .put("threadpool.search.type", "scaling") .put("threadpool.search.keep_alive", "10m") .put("threadpool.search.min", "2") .put("threadpool.search.size", "15") .build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("scaling")); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getCorePoolSize(), equalTo(2)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getMaximumPoolSize(), equalTo(15)); assertThat(info(threadPool, Names.SEARCH).getMin(), equalTo(2)); assertThat(info(threadPool, Names.SEARCH).getMax(), equalTo(15)); // Make sure keep alive value changed assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(10L)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getKeepAliveTime(TimeUnit.MINUTES), equalTo(10L)); // Put old type back threadPool.updateSettings(settingsBuilder() .put("threadpool.search.type", "fixed") .build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("fixed")); // Make sure keep alive value is not used assertThat(info(threadPool, Names.SEARCH).getKeepAlive(), nullValue()); // Make sure keep pool size value were reused assertThat(info(threadPool, Names.SEARCH).getMin(), equalTo(15)); assertThat(info(threadPool, Names.SEARCH).getMax(), equalTo(15)); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getCorePoolSize(), equalTo(15)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getMaximumPoolSize(), equalTo(15)); // Change size Executor oldExecutor = threadPool.executor(Names.SEARCH); threadPool.updateSettings(settingsBuilder().put("threadpool.search.size", "10").build()); // Make sure size values changed assertThat(info(threadPool, Names.SEARCH).getMax(), equalTo(10)); assertThat(info(threadPool, Names.SEARCH).getMin(), equalTo(10)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getMaximumPoolSize(), equalTo(10)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getCorePoolSize(), equalTo(10)); // Make sure executor didn't change assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("fixed")); assertThat(threadPool.executor(Names.SEARCH), sameInstance(oldExecutor)); // Change queue capacity threadPool.updateSettings(settingsBuilder() .put("threadpool.search.queue", "500") .build()); terminate(threadPool); } @Test public void testScalingExecutorType() throws InterruptedException { ThreadPool threadPool = new ThreadPool(settingsBuilder() .put("threadpool.search.type", "scaling") .put("threadpool.search.size", 10) .put("name","testCachedExecutorType").build(), null); assertThat(info(threadPool, Names.SEARCH).getMin(), equalTo(1)); assertThat(info(threadPool, Names.SEARCH).getMax(), equalTo(10)); assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(5L)); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("scaling")); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); // Change settings that doesn't require pool replacement Executor oldExecutor = threadPool.executor(Names.SEARCH); threadPool.updateSettings(settingsBuilder() .put("threadpool.search.type", "scaling") .put("threadpool.search.keep_alive", "10m") .put("threadpool.search.min", "2") .put("threadpool.search.size", "15") .build()); assertThat(info(threadPool, Names.SEARCH).getType(), equalTo("scaling")); assertThat(threadPool.executor(Names.SEARCH), instanceOf(EsThreadPoolExecutor.class)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getCorePoolSize(), equalTo(2)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getMaximumPoolSize(), equalTo(15)); assertThat(info(threadPool, Names.SEARCH).getMin(), equalTo(2)); assertThat(info(threadPool, Names.SEARCH).getMax(), equalTo(15)); // Make sure keep alive value changed assertThat(info(threadPool, Names.SEARCH).getKeepAlive().minutes(), equalTo(10L)); assertThat(((EsThreadPoolExecutor) threadPool.executor(Names.SEARCH)).getKeepAliveTime(TimeUnit.MINUTES), equalTo(10L)); assertThat(threadPool.executor(Names.SEARCH), sameInstance(oldExecutor)); terminate(threadPool); } @Test(timeout = 10000) public void testShutdownDownNowDoesntBlock() throws Exception { ThreadPool threadPool = new ThreadPool(ImmutableSettings.settingsBuilder() .put("threadpool.search.type", "cached") .put("name","testCachedExecutorType").build(), null); final CountDownLatch latch = new CountDownLatch(1); Executor oldExecutor = threadPool.executor(Names.SEARCH); threadPool.executor(Names.SEARCH).execute(new Runnable() { @Override public void run() { try { Thread.sleep(20000); } catch (InterruptedException ex) { latch.countDown(); Thread.currentThread().interrupt(); } } }); threadPool.updateSettings(settingsBuilder().put("threadpool.search.type", "fixed").build()); assertThat(threadPool.executor(Names.SEARCH), not(sameInstance(oldExecutor))); assertThat(((ThreadPoolExecutor) oldExecutor).isShutdown(), equalTo(true)); assertThat(((ThreadPoolExecutor) oldExecutor).isTerminating(), equalTo(true)); assertThat(((ThreadPoolExecutor) oldExecutor).isTerminated(), equalTo(false)); threadPool.shutdownNow(); // interrupt the thread latch.await(); terminate(threadPool); } }
johtani/elasticsearch
src/test/java/org/elasticsearch/threadpool/UpdateThreadPoolSettingsTests.java
Java
apache-2.0
12,249
/* * 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. */ package io.trino.operator; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.trino.connector.CatalogName; import static java.util.Objects.requireNonNull; public class SplitOperatorInfo implements OperatorInfo { private final CatalogName catalogName; // NOTE: this deserializes to a map instead of the expected type private final Object splitInfo; @JsonCreator public SplitOperatorInfo( @JsonProperty("catalogName") CatalogName catalogName, @JsonProperty("splitInfo") Object splitInfo) { this.catalogName = requireNonNull(catalogName, "catalogName is null"); this.splitInfo = splitInfo; } @Override public boolean isFinal() { return true; } @JsonProperty public Object getSplitInfo() { return splitInfo; } @JsonProperty public CatalogName getCatalogName() { return catalogName; } }
electrum/presto
core/trino-main/src/main/java/io/trino/operator/SplitOperatorInfo.java
Java
apache-2.0
1,565
package org.grobid.core.utilities; /** * This class contains all the keys of the properties files. * * @author Damien Ridereau */ public interface GrobidPropertyKeys { public static final String PROP_GROBID_IS_CONTEXT_SERVER = "grobid.is.context.server"; public static final String PROP_TMP_PATH = "grobid.temp.path"; // public static final String PROP_BIN_PATH = "grobid.bin.path"; public static final String PROP_NATIVE_LIB_PATH = "grobid.nativelibrary.path"; public static final String PROP_3RD_PARTY_PDF2XML = "grobid.3rdparty.pdf2xml.path"; public static final String PROP_3RD_PARTY_PDF2XML_MEMORY_LIMIT = "grobid.3rdparty.pdf2xml.memory.limit.mb"; public static final String PROP_GROBID_CRF_ENGINE = "grobid.crf.engine"; public static final String PROP_USE_LANG_ID = "grobid.use_language_id"; public static final String PROP_LANG_DETECTOR_FACTORY = "grobid.language_detector_factory"; public static final String PROP_CROSSREF_ID = "grobid.crossref_id"; public static final String PROP_CROSSREF_PW = "grobid.crossref_pw"; public static final String PROP_CROSSREF_HOST = "grobid.crossref_host"; public static final String PROP_CROSSREF_PORT = "grobid.crossref_port"; public static final String PROP_MYSQL_HOST = "grobid.mysql_host"; public static final String PROP_MYSQL_PORT = "grobid.mysql_port"; public static final String PROP_MYSQL_USERNAME = "grobid.mysql_username"; public static final String PROP_MYSQL_PW = "grobid.mysql_passwd"; public static final String PROP_MYSQL_DB_NAME = "grobid.mysql_db_name"; public static final String PROP_PROXY_HOST = "grobid.proxy_host"; public static final String PROP_PROXY_PORT = "grobid.proxy_port"; public static final String PROP_NB_THREADS = "grobid.nb_threads"; public static final String PROP_GROBID_MAX_CONNECTIONS = "org.grobid.max.connections"; public static final String PROP_GROBID_POOL_MAX_WAIT = "org.grobid.pool.max.wait"; /** * Determines if properties like the firstnames, lastnames country codes and * dictionaries are supposed to be read from $GROBID_HOME path or not * (possible values (true|false) default is false) */ public static final String PROP_RESOURCE_INHOME = "grobid.resources.inHome"; /** * The name of the env-entry located in the web.xml, via which the * grobid-service.propeties path is set. */ public static final String PROP_GROBID_HOME = "org.grobid.home"; /** * The name of the env-entry located in the web.xml, via which the * grobid.propeties path is set. */ public static final String PROP_GROBID_PROPERTY = "org.grobid.property"; /** * The name of the system property, via which the grobid home folder can be * located. */ public static final String PROP_GROBID_SERVICE_PROPERTY = "org.grobid.property.service"; /** * name of the property setting the admin password */ public static final String PROP_GROBID_SERVICE_ADMIN_PW = "org.grobid.service.admin.pw"; /** * If set to true, parallel execution will be done, else a queuing of * requests will be done. */ public static final String PROP_GROBID_SERVICE_IS_PARALLEL_EXEC = "org.grobid.service.is.parallel.execution"; /** * The defined paths to create. */ public static final String[] PATHES_TO_CREATE = {PROP_TMP_PATH}; }
Lilykos/grobid
grobid-core/src/main/java/org/grobid/core/utilities/GrobidPropertyKeys.java
Java
apache-2.0
3,430
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * 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. */ package org.drools.workbench.screens.dtablexls.backend.server.conversion.builders; import org.drools.decisiontable.parser.ActionType; import org.drools.workbench.models.datamodel.rule.Attribute; import org.drools.workbench.models.guided.dtable.shared.conversion.ConversionResult; import org.drools.workbench.models.guided.dtable.shared.model.AttributeCol52; import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52; import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52; /** * Builder for ActivationGroup Attribute columns */ public class GuidedDecisionTableActivationGroupBuilder extends AbstractGuidedDecisionTableAttributeBuilder { public GuidedDecisionTableActivationGroupBuilder( final int row, final int column, final ConversionResult conversionResult ) { super( row, column, ActionType.Code.ACTIVATIONGROUP, conversionResult ); } @Override public void populateDecisionTable( final GuidedDecisionTable52 dtable, final int maxRowCount ) { final AttributeCol52 column = new AttributeCol52(); column.setAttribute(Attribute.ACTIVATION_GROUP.getAttributeName()); dtable.getAttributeCols().add( column ); if ( this.values.size() < maxRowCount ) { for ( int iRow = this.values.size(); iRow < maxRowCount; iRow++ ) { this.values.add( new DTCellValue52( "" ) ); } } addColumnData( dtable, column ); } @Override public void addCellValue( final int row, final int column, final String value ) { final DTCellValue52 dcv = new DTCellValue52( value ); this.values.add( dcv ); } }
mbiarnes/drools-wb
drools-wb-screens/drools-wb-dtable-xls-editor/drools-wb-dtable-xls-editor-backend/src/main/java/org/drools/workbench/screens/dtablexls/backend/server/conversion/builders/GuidedDecisionTableActivationGroupBuilder.java
Java
apache-2.0
2,570
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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. */ package org.commonjava.indy.core.inject; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.commonjava.indy.conf.DefaultIndyConfiguration; import org.commonjava.maven.galley.model.ConcreteResource; import org.commonjava.maven.galley.model.Location; import org.commonjava.maven.galley.model.SimpleLocation; import org.junit.Test; public class ExpiringMemoryNotFoundCacheTest { @Test public void expireUsingConfiguredValue() throws Exception { final DefaultIndyConfiguration config = new DefaultIndyConfiguration(); config.setNotFoundCacheTimeoutSeconds( 1 ); final ExpiringMemoryNotFoundCache nfc = new ExpiringMemoryNotFoundCache( config ); final ConcreteResource res = new ConcreteResource( new SimpleLocation( "test:uri" ), "/path/to/expired/object" ); nfc.addMissing( res ); assertThat( nfc.isMissing( res ), equalTo( true ) ); Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) ); assertThat( nfc.isMissing( res ), equalTo( false ) ); final Set<String> locMissing = nfc.getMissing( res.getLocation() ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); final Map<Location, Set<String>> allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); } @Test public void expireUsingConfiguredValue_DirectCheckDoesntAffectAggregateChecks() throws Exception { final DefaultIndyConfiguration config = new DefaultIndyConfiguration(); config.setNotFoundCacheTimeoutSeconds( 1 ); final ExpiringMemoryNotFoundCache nfc = new ExpiringMemoryNotFoundCache( config ); final ConcreteResource res = new ConcreteResource( new SimpleLocation( "test:uri" ), "/path/to/expired/object" ); nfc.addMissing( res ); assertThat( nfc.isMissing( res ), equalTo( true ) ); Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) ); Set<String> locMissing = nfc.getMissing( res.getLocation() ); System.out.println( locMissing ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); Map<Location, Set<String>> allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); assertThat( nfc.isMissing( res ), equalTo( false ) ); locMissing = nfc.getMissing( res.getLocation() ); assertThat( locMissing == null || locMissing.isEmpty(), equalTo( true ) ); allMissing = nfc.getAllMissing(); assertThat( allMissing == null || allMissing.isEmpty(), equalTo( true ) ); } }
pkocandr/indy
core/src/test/java/org/commonjava/indy/core/inject/ExpiringMemoryNotFoundCacheTest.java
Java
apache-2.0
3,446
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.ignite.internal.processors.cache.distributed; import java.util.Collection; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException; import org.apache.ignite.internal.processors.cache.GridCacheFuture; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.util.GridLeanMap; import org.apache.ignite.internal.util.future.GridCompoundIdentityFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteUuid; import org.jetbrains.annotations.Nullable; /** * Future verifying that all remote transactions related to transaction were prepared or committed. */ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolean> implements GridCacheFuture<Boolean> { /** */ private static final long serialVersionUID = 0L; /** Logger reference. */ private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>(); /** Logger. */ private static IgniteLogger log; /** Trackable flag. */ private boolean trackable = true; /** Context. */ private final GridCacheSharedContext<?, ?> cctx; /** Future ID. */ private final IgniteUuid futId = IgniteUuid.randomUuid(); /** Transaction. */ private final IgniteInternalTx tx; /** All involved nodes. */ private final Map<UUID, ClusterNode> nodes; /** ID of failed node started transaction. */ private final UUID failedNodeId; /** Transaction nodes mapping. */ private final Map<UUID, Collection<UUID>> txNodes; /** */ private final boolean nearTxCheck; /** * @param cctx Context. * @param tx Transaction. * @param failedNodeId ID of failed node started transaction. * @param txNodes Transaction mapping. */ @SuppressWarnings("ConstantConditions") public GridCacheTxRecoveryFuture(GridCacheSharedContext<?, ?> cctx, IgniteInternalTx tx, UUID failedNodeId, Map<UUID, Collection<UUID>> txNodes) { super(cctx.kernalContext(), CU.boolReducer()); this.cctx = cctx; this.tx = tx; this.txNodes = txNodes; this.failedNodeId = failedNodeId; if (log == null) log = U.logger(cctx.kernalContext(), logRef, GridCacheTxRecoveryFuture.class); nodes = new GridLeanMap<>(); UUID locNodeId = cctx.localNodeId(); for (Map.Entry<UUID, Collection<UUID>> e : tx.transactionNodes().entrySet()) { if (!locNodeId.equals(e.getKey()) && !failedNodeId.equals(e.getKey()) && !nodes.containsKey(e.getKey())) { ClusterNode node = cctx.discovery().node(e.getKey()); if (node != null) nodes.put(node.id(), node); else if (log.isDebugEnabled()) log.debug("Transaction node left (will ignore) " + e.getKey()); } for (UUID nodeId : e.getValue()) { if (!locNodeId.equals(nodeId) && !failedNodeId.equals(nodeId) && !nodes.containsKey(nodeId)) { ClusterNode node = cctx.discovery().node(nodeId); if (node != null) nodes.put(node.id(), node); else if (log.isDebugEnabled()) log.debug("Transaction node left (will ignore) " + e.getKey()); } } } UUID nearNodeId = tx.eventNodeId(); nearTxCheck = !failedNodeId.equals(nearNodeId) && cctx.discovery().alive(nearNodeId); } /** * Initializes future. */ @SuppressWarnings("ConstantConditions") public void prepare() { if (nearTxCheck) { UUID nearNodeId = tx.eventNodeId(); if (cctx.localNodeId().equals(nearNodeId)) { IgniteInternalFuture<Boolean> fut = cctx.tm().txCommitted(tx.nearXidVersion()); fut.listen(new CI1<IgniteInternalFuture<Boolean>>() { @Override public void apply(IgniteInternalFuture<Boolean> fut) { try { onDone(fut.get()); } catch (IgniteCheckedException e) { onDone(e); } } }); } else { MiniFuture fut = new MiniFuture(tx.eventNodeId()); add(fut); GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest( tx, 0, true, futureId(), fut.futureId()); try { cctx.io().send(nearNodeId, req, tx.ioPolicy()); } catch (ClusterTopologyCheckedException ignore) { fut.onNodeLeft(); } catch (IgniteCheckedException e) { fut.onError(e); } markInitialized(); } return; } // First check transactions on local node. int locTxNum = nodeTransactions(cctx.localNodeId()); if (locTxNum > 1) { IgniteInternalFuture<Boolean> fut = cctx.tm().txsPreparedOrCommitted(tx.nearXidVersion(), locTxNum); if (fut == null || fut.isDone()) { boolean prepared; try { prepared = fut == null ? true : fut.get(); } catch (IgniteCheckedException e) { U.error(log, "Check prepared transaction future failed: " + e, e); prepared = false; } if (!prepared) { onDone(false); markInitialized(); return; } } else { fut.listen(new CI1<IgniteInternalFuture<Boolean>>() { @Override public void apply(IgniteInternalFuture<Boolean> fut) { boolean prepared; try { prepared = fut.get(); } catch (IgniteCheckedException e) { U.error(log, "Check prepared transaction future failed: " + e, e); prepared = false; } if (!prepared) { onDone(false); markInitialized(); } else proceedPrepare(); } }); return; } } proceedPrepare(); } /** * Process prepare after local check. */ private void proceedPrepare() { for (Map.Entry<UUID, Collection<UUID>> entry : txNodes.entrySet()) { UUID nodeId = entry.getKey(); // Skip left nodes and local node. if (!nodes.containsKey(nodeId) && nodeId.equals(cctx.localNodeId())) continue; /* * If primary node failed then send message to all backups, otherwise * send message only to primary node. */ if (nodeId.equals(failedNodeId)) { for (UUID id : entry.getValue()) { // Skip backup node if it is local node or if it is also was mapped as primary. if (txNodes.containsKey(id) || id.equals(cctx.localNodeId())) continue; MiniFuture fut = new MiniFuture(id); add(fut); GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest(tx, nodeTransactions(id), false, futureId(), fut.futureId()); try { cctx.io().send(id, req, tx.ioPolicy()); } catch (ClusterTopologyCheckedException ignored) { fut.onNodeLeft(); } catch (IgniteCheckedException e) { fut.onError(e); break; } } } else { MiniFuture fut = new MiniFuture(nodeId); add(fut); GridCacheTxRecoveryRequest req = new GridCacheTxRecoveryRequest( tx, nodeTransactions(nodeId), false, futureId(), fut.futureId()); try { cctx.io().send(nodeId, req, tx.ioPolicy()); } catch (ClusterTopologyCheckedException ignored) { fut.onNodeLeft(); } catch (IgniteCheckedException e) { fut.onError(e); break; } } } markInitialized(); } /** * @param nodeId Node ID. * @return Number of transactions on node. */ private int nodeTransactions(UUID nodeId) { int cnt = txNodes.containsKey(nodeId) ? 1 : 0; // +1 if node is primary. for (Collection<UUID> backups : txNodes.values()) { for (UUID backup : backups) { if (backup.equals(nodeId)) { cnt++; // +1 if node is backup. break; } } } return cnt; } /** * @param nodeId Node ID. * @param res Response. */ public void onResult(UUID nodeId, GridCacheTxRecoveryResponse res) { if (!isDone()) { for (IgniteInternalFuture<Boolean> fut : pending()) { if (isMini(fut)) { MiniFuture f = (MiniFuture)fut; if (f.futureId().equals(res.miniId())) { assert f.nodeId().equals(nodeId); f.onResult(res); break; } } } } } /** {@inheritDoc} */ @Override public IgniteUuid futureId() { return futId; } /** {@inheritDoc} */ @Override public GridCacheVersion version() { return tx.xidVersion(); } /** {@inheritDoc} */ @Override public Collection<? extends ClusterNode> nodes() { return nodes.values(); } /** {@inheritDoc} */ @Override public boolean onNodeLeft(UUID nodeId) { for (IgniteInternalFuture<?> fut : futures()) if (isMini(fut)) { MiniFuture f = (MiniFuture)fut; if (f.nodeId().equals(nodeId)) f.onNodeLeft(); } return true; } /** {@inheritDoc} */ @Override public boolean trackable() { return trackable; } /** {@inheritDoc} */ @Override public void markNotTrackable() { trackable = false; } /** {@inheritDoc} */ @Override public boolean onDone(@Nullable Boolean res, @Nullable Throwable err) { if (super.onDone(res, err)) { cctx.mvcc().removeFuture(this); if (err == null) { assert res != null; cctx.tm().finishTxOnRecovery(tx, res); } else { if (err instanceof ClusterTopologyCheckedException && nearTxCheck) { if (log.isDebugEnabled()) log.debug("Failed to check transaction on near node, " + "ignoring [err=" + err + ", tx=" + tx + ']'); } else { if (log.isDebugEnabled()) log.debug("Failed to check prepared transactions, " + "invalidating transaction [err=" + err + ", tx=" + tx + ']'); cctx.tm().salvageTx(tx); } } } return false; } /** * @param f Future. * @return {@code True} if mini-future. */ private boolean isMini(IgniteInternalFuture<?> f) { return f.getClass().equals(MiniFuture.class); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridCacheTxRecoveryFuture.class, this, "super", super.toString()); } /** * */ private class MiniFuture extends GridFutureAdapter<Boolean> { /** */ private static final long serialVersionUID = 0L; /** Mini future ID. */ private final IgniteUuid futId = IgniteUuid.randomUuid(); /** Node ID. */ private UUID nodeId; /** * @param nodeId Node ID. */ private MiniFuture(UUID nodeId) { this.nodeId = nodeId; } /** * @return Node ID. */ private UUID nodeId() { return nodeId; } /** * @return Future ID. */ private IgniteUuid futureId() { return futId; } /** * @param e Error. */ private void onError(Throwable e) { if (log.isDebugEnabled()) log.debug("Failed to get future result [fut=" + this + ", err=" + e + ']'); onDone(e); } /** */ private void onNodeLeft() { if (log.isDebugEnabled()) log.debug("Transaction node left grid (will ignore) [fut=" + this + ']'); if (nearTxCheck) { // Near and originating nodes left, need initiate tx check. cctx.tm().commitIfPrepared(tx); onDone(new ClusterTopologyCheckedException("Transaction node left grid (will ignore).")); } else onDone(true); } /** * @param res Result callback. */ private void onResult(GridCacheTxRecoveryResponse res) { onDone(res.success()); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(MiniFuture.class, this, "done", isDone(), "err", error()); } } }
dlnufox/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java
Java
apache-2.0
15,947
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if GOOGLE_CUDA #define EIGEN_USE_GPU #include "tensorflow/core/kernels/reduction_gpu_kernels.cu.h" namespace tensorflow { namespace functor { typedef Eigen::GpuDevice GPUDevice; // Derive Index type. int (32-bit) or long (64-bit) depending on the // compile-time configuration. "float" here is not relevant. // TODO(zhifengc): Moves the definition to TTypes. typedef TTypes<float>::Tensor::Index Index; // T: the data type // REDUCER: the reducer functor // NUM_AXES: the number of axes to reduce // IN_DIMS: the number of dimensions of the input tensor #define DEFINE(T, REDUCER, IN_DIMS, NUM_AXES) \ template void ReduceFunctor<GPUDevice, REDUCER>::Reduce( \ OpKernelContext* ctx, TTypes<T, IN_DIMS - NUM_AXES>::Tensor out, \ TTypes<T, IN_DIMS>::ConstTensor in, \ const Eigen::array<Index, NUM_AXES>& reduction_axes, \ const REDUCER& reducer); #define DEFINE_IDENTITY(T, REDUCER) \ template void ReduceFunctor<GPUDevice, REDUCER>::FillIdentity( \ const GPUDevice& d, TTypes<T>::Vec out, const REDUCER& reducer); #define DEFINE_FOR_TYPE_AND_R(T, R) \ DEFINE(T, R, 1, 1); \ DEFINE(T, R, 2, 1); \ DEFINE(T, R, 3, 1); \ DEFINE(T, R, 3, 2); \ DEFINE_IDENTITY(T, R) #define DEFINE_FOR_ALL_REDUCERS(T) \ DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::SumReducer<T>); \ DEFINE_FOR_TYPE_AND_R(T, functor::MeanReducer<T>); \ DEFINE_FOR_TYPE_AND_R(T, functor::EuclideanNormReducer<T>); \ DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::MinReducer<T>); \ DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::MaxReducer<T>); \ DEFINE_FOR_TYPE_AND_R(T, Eigen::internal::ProdReducer<T>) DEFINE_FOR_ALL_REDUCERS(int32); DEFINE_FOR_ALL_REDUCERS(int64); #undef DEFINE_FOR_ALL_REDUCERS #undef DEFINE_FOR_TYPE_AND_R #undef DEFINE } // end namespace functor } // end namespace tensorflow #endif // GOOGLE_CUDA
ghchinoy/tensorflow
tensorflow/core/kernels/reduction_ops_gpu_int.cu.cc
C++
apache-2.0
2,716
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("OSharp.Autofac")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("柳柳软件")] [assembly: AssemblyProduct("OSharp.Autofac")] [assembly: AssemblyCopyright("Copyright © 柳柳软件 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("50a2b6a0-8e08-4554-9595-6801f627e16b")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.3.0")] [assembly: AssemblyInformationalVersion("3.0.3")]
BiaoLiu/osharp-2015.8.28
src/OSharp.Autofac/Properties/AssemblyInfo.cs
C#
apache-2.0
1,374
/** * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.sesame.graph; /** * Provides IDs for function instances. * <p> * If two functions are logically equal they will be assigned the same ID. This is used by the caching mechanism * to allow safe sharing of values calculated by different functions. * <p> * Two function instances are considered to be logically equal if their {@link FunctionModelNode} instances are * equal. */ public interface FunctionIdProvider { /** * Returns the ID of a function instance. * * @param fn a function * @return the function's ID * @throws IllegalArgumentException if the function has no known ID */ FunctionId getFunctionId(Object fn); }
jeorme/OG-Platform
sesame/sesame-engine/src/main/java/com/opengamma/sesame/graph/FunctionIdProvider.java
Java
apache-2.0
810
/** * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ package org.apache.hadoop.hbase.client; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.mockito.Mockito.*; @Category(MediumTests.class) public class TestMetaScanner { final Log LOG = LogFactory.getLog(getClass()); private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); @BeforeClass public static void setUpBeforeClass() throws Exception { TEST_UTIL.startMiniCluster(1); } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { TEST_UTIL.shutdownMiniCluster(); } @Test public void testMetaScanner() throws Exception { LOG.info("Starting testMetaScanner"); final byte[] TABLENAME = Bytes.toBytes("testMetaScanner"); final byte[] FAMILY = Bytes.toBytes("family"); TEST_UTIL.createTable(TABLENAME, FAMILY); Configuration conf = TEST_UTIL.getConfiguration(); HTable table = new HTable(conf, TABLENAME); TEST_UTIL.createMultiRegions(conf, table, FAMILY, new byte[][]{ HConstants.EMPTY_START_ROW, Bytes.toBytes("region_a"), Bytes.toBytes("region_b")}); // Make sure all the regions are deployed TEST_UTIL.countRows(table); MetaScanner.MetaScannerVisitor visitor = mock(MetaScanner.MetaScannerVisitor.class); doReturn(true).when(visitor).processRow((Result)anyObject()); // Scanning the entire table should give us three rows MetaScanner.metaScan(conf, visitor, TABLENAME); verify(visitor, times(3)).processRow((Result)anyObject()); // Scanning the table with a specified empty start row should also // give us three META rows reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, HConstants.EMPTY_BYTE_ARRAY, 1000); verify(visitor, times(3)).processRow((Result)anyObject()); // Scanning the table starting in the middle should give us two rows: // region_a and region_b reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1000); verify(visitor, times(2)).processRow((Result)anyObject()); // Scanning with a limit of 1 should only give us one row reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1); verify(visitor, times(1)).processRow((Result)anyObject()); table.close(); } @org.junit.Rule public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu = new org.apache.hadoop.hbase.ResourceCheckerJUnitRule(); }
indi60/hbase-pmc
target/hbase-0.94.1/hbase-0.94.1/src/test/java/org/apache/hadoop/hbase/client/TestMetaScanner.java
Java
apache-2.0
3,874
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * 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. */ package org.kie.workbench.common.stunner.bpmn.project.backend.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.jboss.errai.bus.server.annotations.Service; import org.kie.soup.commons.util.Sets; import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm; import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueResourceIndexTerm; import org.kie.workbench.common.services.refactoring.service.RefactoringQueryService; import org.kie.workbench.common.services.refactoring.service.ResourceType; import org.kie.workbench.common.stunner.bpmn.project.backend.query.FindBpmnProcessIdsQuery; import org.kie.workbench.common.stunner.bpmn.project.service.ProjectOpenReusableSubprocessService; import org.uberfire.backend.vfs.Path; @ApplicationScoped @Service public class ProjectOpenReusableSubprocessServiceImpl implements ProjectOpenReusableSubprocessService { private final RefactoringQueryService queryService; private final Supplier<ResourceType> resourceType; private final Supplier<String> queryName; private final Set<ValueIndexTerm> queryTerms; // CDI proxy. protected ProjectOpenReusableSubprocessServiceImpl() { this(null); } @Inject public ProjectOpenReusableSubprocessServiceImpl(final RefactoringQueryService queryService) { this.queryService = queryService; this.resourceType = () -> ResourceType.BPMN2; this.queryName = () -> FindBpmnProcessIdsQuery.NAME; this.queryTerms = new Sets.Builder<ValueIndexTerm>() .add(new ValueResourceIndexTerm("*", resourceType.get(), ValueIndexTerm.TermSearchType.WILDCARD)) .build(); } String getQueryName() { return queryName.get(); } Set<ValueIndexTerm> createQueryTerms() { return queryTerms; } @Override @SuppressWarnings("unchecked") public List<String> openReusableSubprocess(String processId) { List<String> answer = new ArrayList<>(); Map<String, Path> subprocesses = queryService .query(getQueryName(), createQueryTerms()) .stream() .map(row -> (Map<String, Path>) row.getValue()) .filter(row -> row.get(processId) != null) .findFirst() .orElse(null); if (subprocesses == null) { return answer; } answer.add(subprocesses.get(processId).getFileName()); answer.add(subprocesses.get(processId).toURI()); return answer; } }
romartin/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-project-backend/src/main/java/org/kie/workbench/common/stunner/bpmn/project/backend/service/ProjectOpenReusableSubprocessServiceImpl.java
Java
apache-2.0
3,469
require('jasmine-beforeall'); var h = require('./helpers.js'); describe('', function() { afterAll(function(){ h.afterAllTeardown(); }); // This UI test suite expects to be run as part of hack/test-end-to-end.sh // It requires the example project be created with all of its resources in order to pass describe('unauthenticated user', function() { beforeEach(function() { h.commonSetup(); }); afterEach(function() { h.commonTeardown(); }); it('should be able to log in', function() { browser.get('/'); // The login page doesn't use angular, so we have to use the underlying WebDriver instance var driver = browser.driver; driver.wait(function() { return driver.isElementPresent(by.name("username")); }, 3000); expect(browser.driver.getCurrentUrl()).toMatch(/\/login/); expect(browser.driver.getTitle()).toMatch(/Login -/); h.login(true); expect(browser.getTitle()).toEqual("OpenShift Web Console"); expect(element(by.css(".navbar-utility .username")).getText()).toEqual("e2e-user"); }); }); describe('authenticated e2e-user', function() { beforeEach(function() { h.commonSetup(); h.login(); }); afterEach(function() { h.commonTeardown(); }); describe('with test project', function() { it('should be able to list the test project', function() { browser.get('/').then(function() { h.waitForPresence('h2.project', 'test'); }); }); it('should have access to the test project', function() { h.goToPage('/project/test'); h.waitForPresence('h1', 'test'); h.waitForPresence('.component .service', 'database'); h.waitForPresence('.component .service', 'frontend'); h.waitForPresence('.component .route', 'www.example.com'); h.waitForPresence('.pod-template-build a', '#1'); h.waitForPresence('.deployment-trigger', 'from image change'); // Check the pod count inside the donut chart for each rc. h.waitForPresence('#service-database .pod-count', '1'); h.waitForPresence('#service-frontend .pod-count', '2'); // TODO: validate correlated images, builds, source }); }); }); });
mnagy/origin
assets/test/integration/e2e.js
JavaScript
apache-2.0
2,284
class SearchController < ApplicationController using ArrayItemWrapper def index q, limit, type = search_params.values_at(:q, :limit, :type) respond_with perform_search(q, limit, type).merge(q: q) end private def perform_search(q, limit, *types) types = %w(template local_image remote_image) if types.compact.empty? {}.tap do |results| results[:templates] = wrapped_templates(q, limit) if types.include? 'template' results[:local_images] = wrapped_local_images(q, limit) if types.include? 'local_image' if types.include? 'remote_image' results[:remote_images], results[:errors] = wrapped_remote_images(q, limit) end end end def search_params # Coerce limit to an integer params[:limit] = params[:limit].to_i if params[:limit].present? params.permit(:q, :type, :limit) end def wrapped_templates(q, limit) Template.search(q, limit).wrap(TemplateSerializer) end def wrapped_local_images(q, limit) LocalImage.search(q, limit).wrap(LocalImageSearchResultSerializer) end def wrapped_remote_images(q, limit) images, errors = Registry.search(q, limit) return images.wrap(RemoteImageSearchResultSerializer), errors end end
rheinwein/panamax-api
app/controllers/search_controller.rb
Ruby
apache-2.0
1,231
/* * Copyright 2010 Utkin Dmitry * * 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. */ /* * This file is part of the WSF Staff project. * Please, visit http://code.google.com/p/staff for more information. */ #include <staff/utils/Log.h> #include <staff/utils/SharedPtr.h> #include <staff/utils/File.h> #include <staff/utils/DynamicLibrary.h> #include <staff/utils/PluginManager.h> #include <staff/common/Runtime.h> #include "ProviderFactory.h" namespace staff { namespace das { class ProviderFactory::ProviderFactoryImpl { public: typedef std::map<std::string, IProviderAllocator*> ProviderAllocatorMap; public: void Init() { const std::string sProvidersDir = Runtime::Inst().GetComponentHome("staff.das") + STAFF_PATH_SEPARATOR "providers"; StringList lsProviderDirs; // find directories with providers File(sProvidersDir).List(lsProviderDirs, "*", File::AttributeDirectory); if (lsProviderDirs.size() == 0) { LogDebug() << "providers is not found"; } for (StringList::const_iterator itDir = lsProviderDirs.begin(); itDir != lsProviderDirs.end(); ++itDir) { // finding libraries with providers StringList lsProvidersLibs; StringList lsProvidersNames; const std::string& sProviderDir = sProvidersDir + STAFF_PATH_SEPARATOR + *itDir + STAFF_PATH_SEPARATOR; File(sProviderDir).List(lsProvidersLibs, "*" STAFF_LIBRARY_VEREXT, File::AttributeRegularFile); for (StringList::const_iterator itProvider = lsProvidersLibs.begin(); itProvider != lsProvidersLibs.end(); ++itProvider) { const std::string& sProviderPluginPath = sProviderDir + *itProvider; try { // loading provider LogDebug() << "Loading DAS provider: " << sProviderPluginPath; IProviderAllocator* pAllocator = m_tPluginManager.Load(sProviderPluginPath, true); STAFF_ASSERT(pAllocator, "Can't get allocator for provider: " + *itProvider); pAllocator->GetProvidersList(lsProvidersNames); for (StringList::const_iterator itProviderName = lsProvidersNames.begin(); itProviderName != lsProvidersNames.end(); ++itProviderName) { LogDebug1() << "Setting DAS provider: " << *itProviderName; m_mAllocators[*itProviderName] = pAllocator; } } catch (const Exception& rEx) { LogWarning() << "Can't load provider: " << sProviderPluginPath << ": " << rEx.what(); continue; } } } } public: ProviderAllocatorMap m_mAllocators; PluginManager<IProviderAllocator> m_tPluginManager; }; ProviderFactory::ProviderFactory() { m_pImpl = new ProviderFactoryImpl; try { m_pImpl->Init(); } STAFF_CATCH_ALL } ProviderFactory::~ProviderFactory() { delete m_pImpl; } ProviderFactory& ProviderFactory::Inst() { static ProviderFactory tInst; return tInst; } void ProviderFactory::GetProviders(StringList& rlsProviders) { rlsProviders.clear(); for (ProviderFactoryImpl::ProviderAllocatorMap::const_iterator itProvider = m_pImpl->m_mAllocators.begin(); itProvider != m_pImpl->m_mAllocators.end(); ++itProvider) { rlsProviders.push_back(itProvider->first); } } PProvider ProviderFactory::Allocate(const std::string& sProvider) { ProviderFactoryImpl::ProviderAllocatorMap::iterator itProvider = m_pImpl->m_mAllocators.find(sProvider); STAFF_ASSERT(itProvider != m_pImpl->m_mAllocators.end(), "Can't get allocator for " + sProvider); return itProvider->second->Allocate(sProvider); } } }
gale320/staff
das/common/src/ProviderFactory.cpp
C++
apache-2.0
4,315
/* * This file is part of the select element layoutObject in WebCore. * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. * 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "core/layout/LayoutMenuList.h" #include "core/HTMLNames.h" #include "core/css/CSSFontSelector.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/AXObjectCache.h" #include "core/dom/NodeComputedStyle.h" #include "core/frame/FrameHost.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/frame/Settings.h" #include "core/html/HTMLOptGroupElement.h" #include "core/html/HTMLOptionElement.h" #include "core/html/HTMLSelectElement.h" #include "core/layout/LayoutBR.h" #include "core/layout/LayoutScrollbar.h" #include "core/layout/LayoutTheme.h" #include "core/layout/LayoutView.h" #include "core/page/ChromeClient.h" #include "platform/fonts/FontCache.h" #include "platform/geometry/IntSize.h" #include "platform/text/PlatformLocale.h" #include <math.h> namespace blink { using namespace HTMLNames; LayoutMenuList::LayoutMenuList(Element* element) : LayoutFlexibleBox(element) , m_buttonText(nullptr) , m_innerBlock(nullptr) , m_optionsChanged(true) , m_isEmpty(false) , m_hasUpdatedActiveOption(false) , m_popupIsVisible(false) , m_optionsWidth(0) , m_lastActiveIndex(-1) , m_indexToSelectOnCancel(-1) { ASSERT(isHTMLSelectElement(element)); } LayoutMenuList::~LayoutMenuList() { ASSERT(!m_popup); } void LayoutMenuList::willBeDestroyed() { if (m_popup) m_popup->disconnectClient(); m_popup = nullptr; LayoutFlexibleBox::willBeDestroyed(); } // FIXME: Instead of this hack we should add a ShadowRoot to <select> with no insertion point // to prevent children from rendering. bool LayoutMenuList::isChildAllowed(LayoutObject* object, const ComputedStyle&) const { return object->isAnonymous() && !object->isLayoutFullScreen(); } void LayoutMenuList::createInnerBlock() { if (m_innerBlock) { ASSERT(firstChild() == m_innerBlock); ASSERT(!m_innerBlock->nextSibling()); return; } // Create an anonymous block. ASSERT(!firstChild()); m_innerBlock = createAnonymousBlock(); m_buttonText = new LayoutText(&document(), StringImpl::empty()); // We need to set the text explicitly though it was specified in the // constructor because LayoutText doesn't refer to the text // specified in the constructor in a case of re-transforming. m_buttonText->setStyle(mutableStyle()); m_innerBlock->addChild(m_buttonText); adjustInnerStyle(); LayoutFlexibleBox::addChild(m_innerBlock); } void LayoutMenuList::adjustInnerStyle() { ComputedStyle& innerStyle = m_innerBlock->mutableStyleRef(); innerStyle.setFlexGrow(1); innerStyle.setFlexShrink(1); // min-width: 0; is needed for correct shrinking. innerStyle.setMinWidth(Length(0, Fixed)); // Use margin:auto instead of align-items:center to get safe centering, i.e. // when the content overflows, treat it the same as align-items: flex-start. // But we only do that for the cases where html.css would otherwise use center. if (style()->alignItemsPosition() == ItemPositionCenter) { innerStyle.setMarginTop(Length()); innerStyle.setMarginBottom(Length()); innerStyle.setAlignSelfPosition(ItemPositionFlexStart); } innerStyle.setPaddingLeft(Length(LayoutTheme::theme().popupInternalPaddingLeft(styleRef()), Fixed)); innerStyle.setPaddingRight(Length(LayoutTheme::theme().popupInternalPaddingRight(styleRef()), Fixed)); innerStyle.setPaddingTop(Length(LayoutTheme::theme().popupInternalPaddingTop(styleRef()), Fixed)); innerStyle.setPaddingBottom(Length(LayoutTheme::theme().popupInternalPaddingBottom(styleRef()), Fixed)); if (m_optionStyle) { if ((m_optionStyle->direction() != innerStyle.direction() || m_optionStyle->unicodeBidi() != innerStyle.unicodeBidi())) m_innerBlock->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::StyleChange); innerStyle.setTextAlign(style()->isLeftToRightDirection() ? LEFT : RIGHT); innerStyle.setDirection(m_optionStyle->direction()); innerStyle.setUnicodeBidi(m_optionStyle->unicodeBidi()); } } inline HTMLSelectElement* LayoutMenuList::selectElement() const { return toHTMLSelectElement(node()); } void LayoutMenuList::addChild(LayoutObject* newChild, LayoutObject* beforeChild) { m_innerBlock->addChild(newChild, beforeChild); ASSERT(m_innerBlock == firstChild()); if (AXObjectCache* cache = document().existingAXObjectCache()) cache->childrenChanged(this); } void LayoutMenuList::removeChild(LayoutObject* oldChild) { if (oldChild == m_innerBlock || !m_innerBlock) { LayoutFlexibleBox::removeChild(oldChild); m_innerBlock = nullptr; } else { m_innerBlock->removeChild(oldChild); } } void LayoutMenuList::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle) { LayoutBlock::styleDidChange(diff, oldStyle); if (!m_innerBlock) createInnerBlock(); m_buttonText->setStyle(mutableStyle()); adjustInnerStyle(); bool fontChanged = !oldStyle || oldStyle->font() != style()->font(); if (fontChanged) updateOptionsWidth(); } void LayoutMenuList::updateOptionsWidth() { float maxOptionWidth = 0; const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); int size = listItems.size(); for (int i = 0; i < size; ++i) { HTMLElement* element = listItems[i]; if (!isHTMLOptionElement(*element)) continue; String text = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel(); applyTextTransform(style(), text, ' '); if (LayoutTheme::theme().popupOptionSupportsTextIndent()) { // Add in the option's text indent. We can't calculate percentage values for now. float optionWidth = 0; if (const ComputedStyle* optionStyle = element->computedStyle()) optionWidth += minimumValueForLength(optionStyle->textIndent(), 0); if (!text.isEmpty()) optionWidth += style()->font().width(text); maxOptionWidth = std::max(maxOptionWidth, optionWidth); } else if (!text.isEmpty()) { maxOptionWidth = std::max(maxOptionWidth, style()->font().width(text)); } } int width = static_cast<int>(ceilf(maxOptionWidth)); if (m_optionsWidth == width) return; m_optionsWidth = width; if (parent()) setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::MenuWidthChanged); } void LayoutMenuList::updateFromElement() { if (m_optionsChanged) { updateOptionsWidth(); m_optionsChanged = false; } if (m_popupIsVisible) m_popup->updateFromElement(); updateText(); } void LayoutMenuList::setIndexToSelectOnCancel(int listIndex) { m_indexToSelectOnCancel = listIndex; updateText(); } void LayoutMenuList::updateText() { if (m_indexToSelectOnCancel >= 0) setTextFromOption(selectElement()->listToOptionIndex(m_indexToSelectOnCancel)); else if (selectElement()->suggestedIndex() >= 0) setTextFromOption(selectElement()->suggestedIndex()); else setTextFromOption(selectElement()->selectedIndex()); } void LayoutMenuList::setTextFromOption(int optionIndex) { HTMLSelectElement* select = selectElement(); const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = select->listItems(); const int size = listItems.size(); String text = emptyString(); m_optionStyle.clear(); if (multiple()) { unsigned selectedCount = 0; int firstSelectedIndex = -1; for (int i = 0; i < size; ++i) { Element* element = listItems[i]; if (!isHTMLOptionElement(*element)) continue; if (toHTMLOptionElement(element)->selected()) { if (++selectedCount == 1) firstSelectedIndex = i; } } if (selectedCount == 1) { ASSERT(0 <= firstSelectedIndex); ASSERT(firstSelectedIndex < size); HTMLOptionElement* selectedOptionElement = toHTMLOptionElement(listItems[firstSelectedIndex]); ASSERT(selectedOptionElement->selected()); text = selectedOptionElement->textIndentedToRespectGroupLabel(); m_optionStyle = selectedOptionElement->mutableComputedStyle(); } else { Locale& locale = select->locale(); String localizedNumberString = locale.convertToLocalizedNumber(String::number(selectedCount)); text = locale.queryString(WebLocalizedString::SelectMenuListText, localizedNumberString); ASSERT(!m_optionStyle); } } else { const int i = select->optionToListIndex(optionIndex); if (i >= 0 && i < size) { Element* element = listItems[i]; if (isHTMLOptionElement(*element)) { text = toHTMLOptionElement(element)->textIndentedToRespectGroupLabel(); m_optionStyle = element->mutableComputedStyle(); } } } setText(text.stripWhiteSpace()); didUpdateActiveOption(optionIndex); } void LayoutMenuList::setText(const String& s) { if (s.isEmpty()) { // FIXME: This is a hack. We need the select to have the same baseline positioning as // any surrounding text. Wihtout any content, we align the bottom of the select to the bottom // of the text. With content (In this case the faked " ") we correctly align the middle of // the select to the middle of the text. It should be possible to remove this, just set // s.impl() into the text and have things align correctly ... crbug.com/485982 m_isEmpty = true; m_buttonText->setText(StringImpl::create(" ", 1), true); } else { m_isEmpty = false; m_buttonText->setText(s.impl(), true); } adjustInnerStyle(); } String LayoutMenuList::text() const { return m_buttonText && !m_isEmpty ? m_buttonText->text() : String(); } LayoutRect LayoutMenuList::controlClipRect(const LayoutPoint& additionalOffset) const { // Clip to the intersection of the content box and the content box for the inner box // This will leave room for the arrows which sit in the inner box padding, // and if the inner box ever spills out of the outer box, that will get clipped too. LayoutRect outerBox = contentBoxRect(); outerBox.moveBy(additionalOffset); LayoutRect innerBox(additionalOffset + m_innerBlock->location() + LayoutSize(m_innerBlock->paddingLeft(), m_innerBlock->paddingTop()) , m_innerBlock->contentSize()); return intersection(outerBox, innerBox); } void LayoutMenuList::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const { maxLogicalWidth = std::max(m_optionsWidth, LayoutTheme::theme().minimumMenuListSize(styleRef())) + m_innerBlock->paddingLeft() + m_innerBlock->paddingRight(); if (!style()->width().hasPercent()) minLogicalWidth = maxLogicalWidth; } void LayoutMenuList::showPopup() { if (m_popupIsVisible) return; if (document().frameHost()->chromeClient().hasOpenedPopup()) return; if (!m_popup) m_popup = document().frameHost()->chromeClient().openPopupMenu(*document().frame(), this); m_popupIsVisible = true; FloatQuad quad(localToAbsoluteQuad(FloatQuad(borderBoundingBox()))); IntSize size = pixelSnappedIntRect(frameRect()).size(); HTMLSelectElement* select = selectElement(); m_popup->show(quad, size, select->optionToListIndex(select->selectedIndex())); if (AXObjectCache* cache = document().existingAXObjectCache()) cache->didShowMenuListPopup(this); } void LayoutMenuList::hidePopup() { if (m_popup) m_popup->hide(); } void LayoutMenuList::valueChanged(unsigned listIndex, bool fireOnChange) { // Check to ensure a page navigation has not occurred while // the popup was up. Document& doc = toElement(node())->document(); if (&doc != doc.frame()->document()) return; setIndexToSelectOnCancel(-1); HTMLSelectElement* select = selectElement(); select->optionSelectedByUser(select->listToOptionIndex(listIndex), fireOnChange); } void LayoutMenuList::listBoxSelectItem(int listIndex, bool allowMultiplySelections, bool shift, bool fireOnChangeNow) { selectElement()->listBoxSelectItem(listIndex, allowMultiplySelections, shift, fireOnChangeNow); } bool LayoutMenuList::multiple() const { return selectElement()->multiple(); } IntRect LayoutMenuList::elementRectRelativeToViewport() const { // We don't use absoluteBoundingBoxRect() because it can return an IntRect // larger the actual size by 1px. return selectElement()->document().view()->contentsToViewport(roundedIntRect(absoluteBoundingBoxFloatRect())); } Element& LayoutMenuList::ownerElement() const { return *selectElement(); } const ComputedStyle* LayoutMenuList::computedStyleForItem(Element& element) const { return element.computedStyle() ? element.computedStyle() : element.ensureComputedStyle(); } void LayoutMenuList::didSetSelectedIndex(int listIndex) { didUpdateActiveOption(selectElement()->listToOptionIndex(listIndex)); } void LayoutMenuList::didUpdateActiveOption(int optionIndex) { if (!document().existingAXObjectCache()) return; if (m_lastActiveIndex == optionIndex) return; m_lastActiveIndex = optionIndex; HTMLSelectElement* select = selectElement(); int listIndex = select->optionToListIndex(optionIndex); if (listIndex < 0 || listIndex >= static_cast<int>(select->listItems().size())) return; // We skip sending accessiblity notifications for the very first option, otherwise // we get extra focus and select events that are undesired. if (!m_hasUpdatedActiveOption) { m_hasUpdatedActiveOption = true; return; } document().existingAXObjectCache()->handleUpdateActiveMenuOption(this, optionIndex); } String LayoutMenuList::itemText(unsigned listIndex) const { HTMLSelectElement* select = selectElement(); const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = select->listItems(); if (listIndex >= listItems.size()) return String(); String itemString; Element* element = listItems[listIndex]; if (isHTMLOptGroupElement(*element)) itemString = toHTMLOptGroupElement(*element).groupLabelText(); else if (isHTMLOptionElement(*element)) itemString = toHTMLOptionElement(*element).textIndentedToRespectGroupLabel(); applyTextTransform(style(), itemString, ' '); return itemString; } String LayoutMenuList::itemAccessibilityText(unsigned listIndex) const { // Allow the accessible name be changed if necessary. const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) return String(); return listItems[listIndex]->fastGetAttribute(aria_labelAttr); } String LayoutMenuList::itemToolTip(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) return String(); return listItems[listIndex]->title(); } bool LayoutMenuList::itemIsEnabled(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) return false; HTMLElement* element = listItems[listIndex]; if (!isHTMLOptionElement(*element)) return false; bool groupEnabled = true; if (Element* parentElement = element->parentElement()) { if (isHTMLOptGroupElement(*parentElement)) groupEnabled = !parentElement->isDisabledFormControl(); } if (!groupEnabled) return false; return !element->isDisabledFormControl(); } PopupMenuStyle LayoutMenuList::itemStyle(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) { // If we are making an out of bounds access, then we want to use the style // of a different option element (index 0). However, if there isn't an option element // before at index 0, we fall back to the menu's style. if (!listIndex) return menuStyle(); // Try to retrieve the style of an option element we know exists (index 0). listIndex = 0; } HTMLElement* element = listItems[listIndex]; Color itemBackgroundColor; bool itemHasCustomBackgroundColor; getItemBackgroundColor(listIndex, itemBackgroundColor, itemHasCustomBackgroundColor); const ComputedStyle* style = element->computedStyle() ? element->computedStyle() : element->ensureComputedStyle(); return style ? PopupMenuStyle(resolveColor(*style, CSSPropertyColor), itemBackgroundColor, style->font(), style->visibility() == VISIBLE, isHTMLOptionElement(*element) ? toHTMLOptionElement(*element).isDisplayNone() : style->display() == NONE, style->textIndent(), style->direction(), isOverride(style->unicodeBidi()), itemHasCustomBackgroundColor ? PopupMenuStyle::CustomBackgroundColor : PopupMenuStyle::DefaultBackgroundColor) : menuStyle(); } void LayoutMenuList::getItemBackgroundColor(unsigned listIndex, Color& itemBackgroundColor, bool& itemHasCustomBackgroundColor) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) { itemBackgroundColor = resolveColor(CSSPropertyBackgroundColor); itemHasCustomBackgroundColor = false; return; } HTMLElement* element = listItems[listIndex]; Color backgroundColor; if (const ComputedStyle* style = element->computedStyle()) backgroundColor = resolveColor(*style, CSSPropertyBackgroundColor); itemHasCustomBackgroundColor = backgroundColor.alpha(); // If the item has an opaque background color, return that. if (!backgroundColor.hasAlpha()) { itemBackgroundColor = backgroundColor; return; } // Otherwise, the item's background is overlayed on top of the menu background. backgroundColor = resolveColor(CSSPropertyBackgroundColor).blend(backgroundColor); if (!backgroundColor.hasAlpha()) { itemBackgroundColor = backgroundColor; return; } // If the menu background is not opaque, then add an opaque white background behind. itemBackgroundColor = Color(Color::white).blend(backgroundColor); } PopupMenuStyle LayoutMenuList::menuStyle() const { const LayoutObject* o = m_innerBlock ? m_innerBlock : this; const ComputedStyle& style = o->styleRef(); return PopupMenuStyle(o->resolveColor(CSSPropertyColor), o->resolveColor(CSSPropertyBackgroundColor), style.font(), style.visibility() == VISIBLE, style.display() == NONE, style.textIndent(), style.direction(), isOverride(style.unicodeBidi())); } LayoutUnit LayoutMenuList::clientPaddingLeft() const { return paddingLeft() + m_innerBlock->paddingLeft(); } const int endOfLinePadding = 2; LayoutUnit LayoutMenuList::clientPaddingRight() const { if (style()->appearance() == MenulistPart || style()->appearance() == MenulistButtonPart) { // For these appearance values, the theme applies padding to leave room for the // drop-down button. But leaving room for the button inside the popup menu itself // looks strange, so we return a small default padding to avoid having a large empty // space appear on the side of the popup menu. return endOfLinePadding; } // If the appearance isn't MenulistPart, then the select is styled (non-native), so // we want to return the user specified padding. return paddingRight() + m_innerBlock->paddingRight(); } int LayoutMenuList::listSize() const { return selectElement()->listItems().size(); } int LayoutMenuList::selectedIndex() const { HTMLSelectElement* select = selectElement(); return select->optionToListIndex(select->selectedIndex()); } void LayoutMenuList::popupDidHide() { m_popupIsVisible = false; if (AXObjectCache* cache = document().existingAXObjectCache()) cache->didHideMenuListPopup(this); } void LayoutMenuList::popupDidCancel() { if (m_indexToSelectOnCancel >= 0) valueChanged(m_indexToSelectOnCancel); } bool LayoutMenuList::itemIsSeparator(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); return listIndex < listItems.size() && isHTMLHRElement(*listItems[listIndex]); } bool LayoutMenuList::itemIsLabel(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); return listIndex < listItems.size() && isHTMLOptGroupElement(*listItems[listIndex]); } bool LayoutMenuList::itemIsSelected(unsigned listIndex) const { const WillBeHeapVector<RawPtrWillBeMember<HTMLElement>>& listItems = selectElement()->listItems(); if (listIndex >= listItems.size()) return false; HTMLElement* element = listItems[listIndex]; return isHTMLOptionElement(*element) && toHTMLOptionElement(*element).selected(); } void LayoutMenuList::provisionalSelectionChanged(unsigned listIndex) { setIndexToSelectOnCancel(listIndex); } } // namespace blink
zero-rp/miniblink49
third_party/WebKit/Source/core/layout/LayoutMenuList.cpp
C++
apache-2.0
22,827
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.camel.component.dropbox.integration.producer; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.dropbox.integration.DropboxTestSupport; import org.apache.camel.component.dropbox.util.DropboxConstants; import org.apache.camel.component.dropbox.util.DropboxResultHeader; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Test; public class DropboxProducerGetFolderTest extends DropboxTestSupport { public DropboxProducerGetFolderTest() throws Exception { } @Test public void testCamelDropbox() throws Exception { template.send("direct:start", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("test", "test"); } }); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); assertMockEndpointsSatisfied(); List<Exchange> exchanges = mock.getReceivedExchanges(); Exchange exchange = exchanges.get(0); Object header = exchange.getIn().getHeader(DropboxResultHeader.DOWNLOADED_FILES.name()); Object body = exchange.getIn().getBody(); assertNotNull(header); assertNotNull(body); } @Test public void testCamelDropboxWithOptionInHeader() throws Exception { template.send("direct:start2", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("test", "test"); } }); template.send("direct:start3", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("test", "test"); exchange.getIn().setHeader(DropboxConstants.HEADER_REMOTE_PATH, "/XXX"); } }); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); assertMockEndpointsSatisfied(); List<Exchange> exchanges = mock.getReceivedExchanges(); Exchange exchange = exchanges.get(0); Object header = exchange.getIn().getHeader(DropboxResultHeader.DOWNLOADED_FILES.name()); Object body = exchange.getIn().getBody(); assertNotNull(header); assertNotNull(body); exchange = exchanges.get(1); header = exchange.getIn().getHeader(DropboxResultHeader.DOWNLOADED_FILES.name()); body = exchange.getIn().getBody(); assertNotNull(header); assertNotNull(body); } @Test public void testCamelDropboxHeaderHasPriorityOnParameter() throws Exception { template.send("direct:start4", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("test", "test"); } }); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); assertMockEndpointsSatisfied(); List<Exchange> exchanges = mock.getReceivedExchanges(); Exchange exchange = exchanges.get(0); Object header = exchange.getIn().getHeader(DropboxResultHeader.DOWNLOADED_FILES.name()); Object body = exchange.getIn().getBody(); assertNotNull(header); assertNotNull(body); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from("direct:start") .to("dropbox://get?accessToken={{accessToken}}&clientIdentifier={{clientIdentifier}}&remotePath=/XXX") .to("mock:result"); from("direct:start2") .setHeader(DropboxConstants.HEADER_REMOTE_PATH, constant("/XXX")) .to("dropbox://get?accessToken={{accessToken}}&clientIdentifier={{clientIdentifier}}") .to("mock:result"); from("direct:start3") .to("dropbox://get?accessToken={{accessToken}}&clientIdentifier={{clientIdentifier}}") .to("mock:result"); from("direct:start4") .setHeader(DropboxConstants.HEADER_REMOTE_PATH, constant("/XXX")) .to("dropbox://get?accessToken={{accessToken}}&clientIdentifier={{clientIdentifier}}&remotePath=/aWrongPath") .to("mock:result"); } }; } }
pkletsko/camel
components/camel-dropbox/src/test/java/org/apache/camel/component/dropbox/integration/producer/DropboxProducerGetFolderTest.java
Java
apache-2.0
5,497
/* * Copyright 2018, OpenCensus Authors * * 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. */ package io.opencensus.contrib.appengine.standard.util; import static com.google.common.base.Preconditions.checkNotNull; import com.google.apphosting.api.CloudTraceContext; import com.google.common.annotations.VisibleForTesting; import io.opencensus.trace.SpanContext; import io.opencensus.trace.SpanId; import io.opencensus.trace.TraceId; import io.opencensus.trace.TraceOptions; import io.opencensus.trace.Tracestate; import java.nio.ByteBuffer; /** * Utility class to convert between {@link io.opencensus.trace.SpanContext} and {@link * CloudTraceContext}. * * @since 0.14 */ public final class AppEngineCloudTraceContextUtils { private static final byte[] INVALID_TRACE_ID = TraceIdProto.newBuilder().setHi(0).setLo(0).build().toByteArray(); private static final long INVALID_SPAN_ID = 0L; private static final long INVALID_TRACE_MASK = 0L; private static final Tracestate TRACESTATE_DEFAULT = Tracestate.builder().build(); @VisibleForTesting static final CloudTraceContext INVALID_CLOUD_TRACE_CONTEXT = new CloudTraceContext(INVALID_TRACE_ID, INVALID_SPAN_ID, INVALID_TRACE_MASK); /** * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}. * * @param cloudTraceContext the AppEngine {@code CloudTraceContext}. * @return the converted {@code SpanContext}. * @since 0.14 */ public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) { checkNotNull(cloudTraceContext, "cloudTraceContext"); try { // Extract the trace ID from the binary protobuf CloudTraceContext#traceId. TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId()); ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE); traceIdBuf.putLong(traceIdProto.getHi()); traceIdBuf.putLong(traceIdProto.getLo()); ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE); spanIdBuf.putLong(cloudTraceContext.getSpanId()); return SpanContext.create( TraceId.fromBytes(traceIdBuf.array()), SpanId.fromBytes(spanIdBuf.array()), TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(), TRACESTATE_DEFAULT); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e); } } /** * Converts {@code SpanContext} to AppEngine {@code CloudTraceContext}. * * @param spanContext the {@code SpanContext}. * @return the converted AppEngine {@code CloudTraceContext}. * @since 0.14 */ public static CloudTraceContext toCloudTraceContext(SpanContext spanContext) { checkNotNull(spanContext, "spanContext"); ByteBuffer traceIdBuf = ByteBuffer.wrap(spanContext.getTraceId().getBytes()); TraceIdProto traceIdProto = TraceIdProto.newBuilder().setHi(traceIdBuf.getLong()).setLo(traceIdBuf.getLong()).build(); ByteBuffer spanIdBuf = ByteBuffer.wrap(spanContext.getSpanId().getBytes()); return new CloudTraceContext( traceIdProto.toByteArray(), spanIdBuf.getLong(), spanContext.getTraceOptions().isSampled() ? 1L : 0L); } private AppEngineCloudTraceContextUtils() {} }
bogdandrutu/opencensus-java
contrib/appengine_standard_util/src/main/java/io/opencensus/contrib/appengine/standard/util/AppEngineCloudTraceContextUtils.java
Java
apache-2.0
3,787