repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
n2n/n2n-web
src/app/n2n/web/dispatch/map/val/SimplePropertyValidator.php
1990
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the N2N FRAMEWORK. * * The N2N FRAMEWORK 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. * * N2N 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: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg.....: Architect, Lead Developer * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing * Thomas Günther.......: Developer, Hangar */ namespace n2n\web\dispatch\map\val; use n2n\web\dispatch\map\PropertyPathPart; use n2n\util\type\ArgUtils; abstract class SimplePropertyValidator extends SinglePropertyValidator { private $pathPart; protected function validateProperty($mapValue) { $managedProperty = $this->getManagedProperty(); if (!$managedProperty->isArray()) { $this->pathPart = new PropertyPathPart($managedProperty->getName()); $this->validateValue($mapValue); $this->pathPart = null; return; } ArgUtils::valArrayLike($mapValue); foreach ($mapValue as $aKey => $aValue) { $this->pathPart = new PropertyPathPart($managedProperty->getName(), true, $aKey); if ($this->getBindingErrors()->hasErrors($this->pathPart)) { continue; } $this->validateValue($aValue, $this->pathPart, $this->getBindingErrors()); $this->pathPart = null; } } protected function getPathPart() { return $this->pathPart; } protected abstract function validateValue($mapValue); }
lgpl-3.0
pcolby/libqtaws
src/sesv2/putconfigurationsetsendingoptionsrequest_p.h
1619
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_PUTCONFIGURATIONSETSENDINGOPTIONSREQUEST_P_H #define QTAWS_PUTCONFIGURATIONSETSENDINGOPTIONSREQUEST_P_H #include "sesv2request_p.h" #include "putconfigurationsetsendingoptionsrequest.h" namespace QtAws { namespace SESV2 { class PutConfigurationSetSendingOptionsRequest; class PutConfigurationSetSendingOptionsRequestPrivate : public Sesv2RequestPrivate { public: PutConfigurationSetSendingOptionsRequestPrivate(const Sesv2Request::Action action, PutConfigurationSetSendingOptionsRequest * const q); PutConfigurationSetSendingOptionsRequestPrivate(const PutConfigurationSetSendingOptionsRequestPrivate &other, PutConfigurationSetSendingOptionsRequest * const q); private: Q_DECLARE_PUBLIC(PutConfigurationSetSendingOptionsRequest) }; } // namespace SESV2 } // namespace QtAws #endif
lgpl-3.0
pcolby/libqtaws
src/forecastservice/listtagsforresourcerequest_p.h
1515
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_LISTTAGSFORRESOURCEREQUEST_P_H #define QTAWS_LISTTAGSFORRESOURCEREQUEST_P_H #include "forecastservicerequest_p.h" #include "listtagsforresourcerequest.h" namespace QtAws { namespace ForecastService { class ListTagsForResourceRequest; class ListTagsForResourceRequestPrivate : public ForecastServiceRequestPrivate { public: ListTagsForResourceRequestPrivate(const ForecastServiceRequest::Action action, ListTagsForResourceRequest * const q); ListTagsForResourceRequestPrivate(const ListTagsForResourceRequestPrivate &other, ListTagsForResourceRequest * const q); private: Q_DECLARE_PUBLIC(ListTagsForResourceRequest) }; } // namespace ForecastService } // namespace QtAws #endif
lgpl-3.0
sharwell/zgrnbviewer
org-tvl-netbeans-zgrviewer/src/fr/inria/zvtm/widgets/PieMenuR.java
6530
/* * AUTHOR : Emmanuel Pietriga ([email protected]) * Copyright (c) INRIA, 2008-2010. All Rights Reserved * Licensed under the GNU LGPL. For full terms see the file COPYING. * * $Id: PieMenuR.java 4280 2011-02-28 15:36:54Z rprimet $ */ package fr.inria.zvtm.widgets; import fr.inria.zvtm.animation.Animation; import fr.inria.zvtm.animation.interpolation.IdentityInterpolator; import fr.inria.zvtm.engine.Utils; import fr.inria.zvtm.engine.VirtualSpaceManager; import fr.inria.zvtm.glyphs.VCircle; import fr.inria.zvtm.glyphs.VRing; import fr.inria.zvtm.glyphs.VText; import fr.inria.zvtm.glyphs.VTextOr; import java.awt.Color; import java.awt.Font; import java.awt.geom.Point2D; /** * Circular pie menu with dead zone at its center. */ public class PieMenuR extends PieMenu { public static final int animStartSize = 5; /** * Pie Menu constructor - should not be used directly * * @param stringLabels text label of each menu item * @param menuCenterCoordinates (mouse cursor's coordinates in virtual space as a Point2D.Double) * @param vsName name of the virtual space in which to create the pie menu * @param vsm instance of VirtualSpaceManager * @param radius radius of pie menu * @param irr Inner ring boundary radius as a percentage of outer ring boundary radius * @param startAngle first menu item will have an offset of startAngle interpreted relative to the X horizontal axis (counter clockwise) * @param fillColors menu items' fill colors (this array should have the same length as the stringLabels array) * @param borderColors menu items' border colors (this array should have the same length as the stringLabels array) * @param fillSColors menu items' fill colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change * @param borderSColors menu items' border colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change * @param alphaT menu items' translucency value: between 0 (transparent) and 1.0 (opaque) * @param animDuration duration in ms of animation creating the menu (expansion) - 0 for instantaneous display * @param sensitRadius sensitivity radius (as a percentage of the menu's actual radius) * @param font font used for menu labels * @param labelOffsets x,y offset of each menu label w.r.t their default posisition, in virtual space units<br>(this array should have the same length as the labels array) */ public PieMenuR(String[] stringLabels, Point2D.Double menuCenterCoordinates, String vsName, VirtualSpaceManager vsm, double radius, float irr, double startAngle, double angleWidth, Color[] fillColors, Color[] borderColors, Color[] fillSColors, Color[] borderSColors, Color[] labelColors, float alphaT, int animDuration, double sensitRadius, Font font, Point2D.Double[] labelOffsets) { this.vs = vsm.getVirtualSpace(vsName); double vx = menuCenterCoordinates.x; double vy = menuCenterCoordinates.y; items = new VRing[stringLabels.length]; labels = new VTextOr[stringLabels.length]; double angle = startAngle; double angleDelta = angleWidth / ((double)stringLabels.length); double pieMenuRadius = radius; double textAngle; for (int i = 0; i < labels.length; i++) { angle += angleDelta; items[i] = new VRing(vx, vy, 0, (animDuration > 0) ? animStartSize : pieMenuRadius, angleDelta, irr, angle, fillColors[i], borderColors[i], alphaT); items[i].setCursorInsideFillColor(fillSColors[i]); items[i].setCursorInsideHighlightColor(borderSColors[i]); vs.addGlyph(items[i], false, false); if (stringLabels[i] != null && stringLabels[i].length() > 0) { if (orientText) { textAngle = angle; if (angle > Utils.HALF_PI) { if (angle > Math.PI) { if (angle < Utils.THREE_HALF_PI) { textAngle -= Math.PI; } } else { textAngle += Math.PI; } } labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x, vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y, 0, labelColors[i], stringLabels[i], textAngle, VText.TEXT_ANCHOR_MIDDLE); } else { labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x, vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y, 0, labelColors[i], stringLabels[i], 0, VText.TEXT_ANCHOR_MIDDLE); } labels[i].setBorderColor(borderColors[i]); labels[i].setFont(font); labels[i].setSensitivity(false); vs.addGlyph(labels[i]); } } if (animDuration > 0) { for (int i = 0; i < items.length; i++) { Animation sizeAnim = vsm.getAnimationManager().getAnimationFactory().createGlyphSizeAnim(animDuration, items[i], (float)pieMenuRadius, false, IdentityInterpolator.getInstance(), null); vsm.getAnimationManager().startAnimation(sizeAnim, false); } } boundary = new VCircle(vx, vy, 0, pieMenuRadius * sensitRadius * 2, Color.white); boundary.setVisible(false); vs.addGlyph(boundary); vs.atBottom(boundary); } }
lgpl-3.0
synesthesy/synesthesy-core
src/main/java/de/synesthesy/music/key/nn/IMusicKeyNN.java
369
package de.synesthesy.music.key.nn; import org.encog.neural.networks.BasicNetwork; import de.synesthesy.csv.CSVTestSetInOutput; public interface IMusicKeyNN { public BasicNetwork getNetwork(); public int getIns(); public int getOuts(); public int[] getHiddenNeurons(); public double[] compute(double[] input); public void train(CSVTestSetInOutput testSet); }
lgpl-3.0
yesan/Spacebuilder
Web/Scripts/jquery/masonry/jquery.infinitescroll.js
17301
(function (window, $, undefined) { $.infinitescroll = function infscr(options, callback, element) { this.element = $(element); this._create(options, callback); }; $.infinitescroll.defaults = { loading: { finished: undefined, finishedMsg: "", img: "http://www.infinite-scroll.com/loading.gif", msg: null, msgText: "<em>Loading the next set of posts...</em>", selector: null, speed: 'fast', start: undefined }, state: { isDuringAjax: false, isInvalidPage: false, isDestroyed: false, isDone: false, isPaused: false, currPage: 1 }, callback: undefined, debug: false, behavior: undefined, binder: $(window), nextSelector: "div.navigation a:first", navSelector: "div.navigation", contentSelector: null, extraScrollPx: 150, itemSelector: "div.post", animate: false, pathParse: undefined, dataType: 'html', appendCallback: true, bufferPx: 40, errorCallback: function () { }, infid: 0, pixelsFromNavToBottom: undefined, path: undefined }; $.infinitescroll.prototype = { _binding: function infscr_binding(binding) { var instance = this, opts = instance.options; if (!!opts.behavior && this['_binding_' + opts.behavior] !== undefined) { this['_binding_' + opts.behavior].call(this); return; } if (binding !== 'bind' && binding !== 'unbind') { this._debug('Binding value ' + binding + ' not valid') return false; } if (binding == 'unbind') { (this.options.binder).unbind('smartscroll.infscr.' + instance.options.infid); } else { (this.options.binder)[binding]('smartscroll.infscr.' + instance.options.infid, function () { instance.scroll(); }); }; this._debug('Binding', binding); }, //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö loadDataOnCreat: function () { var _this = this; setTimeout(function () { if ($(document).height() - $(window).height() < 20) { _this.scroll(); _this.loadDataOnCreat(); } }, 3000); }, _create: function infscr_create(options, callback) { if (!this._validate(options)) { return false; } var opts = this.options = $.extend(true, {}, $.infinitescroll.defaults, options), relurl = /(.*?\/\/).*?(\/.*)/, path = $(opts.nextSelector).attr('href'); opts.contentSelector = opts.contentSelector || this.element; opts.loading.selector = opts.loading.selector || opts.contentSelector; if (!path) { this._debug('Navigation selector not found'); return; } opts.path = this._determinepath(path); opts.loading.msg = $('<div id="infscr-loading" class="tn-loading"></div>'); (new Image()).src = opts.loading.img; opts.pixelsFromNavToBottom = $(document).height() - $(opts.navSelector).offset().top; opts.loading.start = opts.loading.start || function () { $(opts.navSelector).hide(); opts.loading.msg.appendTo(opts.loading.selector).show(opts.loading.speed, function () { beginAjax(opts); }); }; opts.loading.finished = opts.loading.finished || function () { opts.loading.msg.fadeOut('normal'); }; opts.callback = function (instance, data) { if (!!opts.behavior && instance['_callback_' + opts.behavior] !== undefined) { instance['_callback_' + opts.behavior].call($(opts.contentSelector)[0], data); } if (callback) { callback.call($(opts.contentSelector)[0], data); } }; this._setup(); //2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö this.loadDataOnCreat(); }, _debug: function infscr_debug() { if (this.options.debug) { return window.console && console.log.call(console, arguments); } }, _determinepath: function infscr_determinepath(path) { var opts = this.options; if (!!opts.behavior && this['_determinepath_' + opts.behavior] !== undefined) { this['_determinepath_' + opts.behavior].call(this, path); return; } if (!!opts.pathParse) { this._debug('pathParse manual'); return opts.pathParse; } else if (path.match(/^(.*?)\b2\b(.*?$)/)) { path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1); } else if (path.match(/^(.*?)2(.*?$)/)) { if (path.match(/^(.*?page=)2(\/.*|$)/)) { path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1); return path; } path = path.match(/^(.*?)2(.*?$)/).slice(1); } else { if (path.match(/^(.*?page=)1(\/.*|$)/)) { path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1); return path; } else { this._debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.'); opts.state.isInvalidPage = true; } } this._debug('determinePath', path); return path; }, _error: function infscr_error(xhr) { var opts = this.options; if (!!opts.behavior && this['_error_' + opts.behavior] !== undefined) { this['_error_' + opts.behavior].call(this, xhr); return; } if (xhr !== 'destroy' && xhr !== 'end') { xhr = 'unknown'; } this._debug('Error', xhr); if (xhr == 'end') { this._showdonemsg(); } opts.state.isDone = true; opts.state.currPage = 1; opts.state.isPaused = false; this._binding('unbind'); }, _loadcallback: function infscr_loadcallback(box, data) { var opts = this.options, callback = this.options.callback, result = (opts.state.isDone) ? 'done' : (!opts.appendCallback) ? 'no-append' : 'append', frag; if (!!opts.behavior && this['_loadcallback_' + opts.behavior] !== undefined) { this['_loadcallback_' + opts.behavior].call(this, box, data); return; } switch (result) { case 'done': this._showdonemsg(); return false; break; case 'no-append': if (opts.dataType == 'html') { data = '<div>' + data + '</div>'; data = $(data).find(opts.itemSelector); }; break; case 'append': var children = box.children(); if (children.length == 0) { return this._error('end'); } frag = document.createDocumentFragment(); while (box[0].firstChild) { frag.appendChild(box[0].firstChild); } this._debug('contentSelector', $(opts.contentSelector)[0]) $(opts.contentSelector)[0].appendChild(frag); data = children.get(); break; } opts.loading.finished.call($(opts.contentSelector)[0], opts) if (opts.animate) { var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px'; $('html,body').animate({ scrollTop: scrollTo }, 800, function () { opts.state.isDuringAjax = false; }); } if (!opts.animate) opts.state.isDuringAjax = false; callback(this, data); }, _nearbottom: function infscr_nearbottom() { var opts = this.options, pixelsFromWindowBottomToBottom = 0 + $(document).height() - (opts.binder.scrollTop()) - $(window).height(); if (!!opts.behavior && this['_nearbottom_' + opts.behavior] !== undefined) { this['_nearbottom_' + opts.behavior].call(this); return; } this._debug('math:', pixelsFromWindowBottomToBottom, opts.pixelsFromNavToBottom); return (pixelsFromWindowBottomToBottom - opts.bufferPx < opts.pixelsFromNavToBottom); }, _pausing: function infscr_pausing(pause) { var opts = this.options; if (!!opts.behavior && this['_pausing_' + opts.behavior] !== undefined) { this['_pausing_' + opts.behavior].call(this, pause); return; } if (pause !== 'pause' && pause !== 'resume' && pause !== null) { this._debug('Invalid argument. Toggling pause value instead'); }; pause = (pause && (pause == 'pause' || pause == 'resume')) ? pause : 'toggle'; switch (pause) { case 'pause': opts.state.isPaused = true; break; case 'resume': opts.state.isPaused = false; break; case 'toggle': opts.state.isPaused = !opts.state.isPaused; break; } this._debug('Paused', opts.state.isPaused); return false; }, _setup: function infscr_setup() { var opts = this.options; if (!!opts.behavior && this['_setup_' + opts.behavior] !== undefined) { this['_setup_' + opts.behavior].call(this); return; } this._binding('bind'); return false; }, _showdonemsg: function infscr_showdonemsg() { var opts = this.options; if (!!opts.behavior && this['_showdonemsg_' + opts.behavior] !== undefined) { this['_showdonemsg_' + opts.behavior].call(this); return; } opts.loading.msg.find('img').hide().parent().find('div').html(opts.loading.finishedMsg).animate({ opacity: 1 }, 2000, function () { $(this).parent().fadeOut('normal'); }); $('#infscr-loading').hide(); opts.errorCallback.call($(opts.contentSelector)[0], 'done'); }, _validate: function infscr_validate(opts) { for (var key in opts) { if (key.indexOf && key.indexOf('Selector') > -1 && $(opts[key]).length === 0) { this._debug('Your ' + key + ' found no elements.'); return false; } return true; } }, bind: function infscr_bind() { this._binding('bind'); }, destroy: function infscr_destroy() { this.options.state.isDestroyed = true; return this._error('destroy'); }, pause: function infscr_pause() { this._pausing('pause'); }, resume: function infscr_resume() { this._pausing('resume'); }, retrieve: function infscr_retrieve(pageNum) { var instance = this, opts = instance.options, path = opts.path, box, frag, desturl, method, condition, pageNum = pageNum || null, getPage = (!!pageNum) ? pageNum : opts.state.currPage; beginAjax = function infscr_ajax(opts) { opts.state.currPage++; instance._debug('heading into ajax', path); box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>'); desturl = path.join(opts.state.currPage); method = (opts.dataType == 'html' || opts.dataType == 'json') ? opts.dataType : 'html+callback'; if (opts.appendCallback && opts.dataType == 'html') method += '+callback' switch (method) { case 'html+callback': instance._debug('Using HTML via .load() method'); box.load(desturl + ' ' + opts.itemSelector, null, function infscr_ajax_callback(responseText) { instance._loadcallback(box, responseText); }); break; case 'html': case 'json': instance._debug('Using ' + (method.toUpperCase()) + ' via $.ajax() method'); $.ajax({ url: desturl, dataType: opts.dataType, complete: function infscr_ajax_callback(jqXHR, textStatus) { condition = (typeof (jqXHR.isResolved) !== 'undefined') ? (jqXHR.isResolved()) : (textStatus === "success" || textStatus === "notmodified"); (condition) ? instance._loadcallback(box, jqXHR.responseText) : instance._error('end'); } }); break; } }; if (!!opts.behavior && this['retrieve_' + opts.behavior] !== undefined) { this['retrieve_' + opts.behavior].call(this, pageNum); return; } if (opts.state.isDestroyed) { this._debug('Instance is destroyed'); return false; }; opts.state.isDuringAjax = true; opts.loading.start.call($(opts.contentSelector)[0], opts); }, scroll: function infscr_scroll() { var opts = this.options, state = opts.state; if (!!opts.behavior && this['scroll_' + opts.behavior] !== undefined) { this['scroll_' + opts.behavior].call(this); return; } if (state.isDuringAjax || state.isInvalidPage || state.isDone || state.isDestroyed || state.isPaused) return; if (!this._nearbottom()) return; this.retrieve(); }, toggle: function infscr_toggle() { this._pausing(); }, unbind: function infscr_unbind() { this._binding('unbind'); }, update: function infscr_options(key) { if ($.isPlainObject(key)) { this.options = $.extend(true, this.options, key); } } } $.fn.infinitescroll = function infscr_init(options, callback) { var thisCall = typeof options; switch (thisCall) { case 'string': var args = Array.prototype.slice.call(arguments, 1); this.each(function () { var instance = $.data(this, 'infinitescroll'); if (!instance) { return false; } if (!$.isFunction(instance[options]) || options.charAt(0) === "_") { return false; } instance[options].apply(instance, args); }); break; case 'object': this.each(function () { var instance = $.data(this, 'infinitescroll'); if (instance) { instance.update(options); } else { $.data(this, 'infinitescroll', new $.infinitescroll(options, callback, this)); } }); break; } return this; }; var event = $.event, scrollTimeout; event.special.smartscroll = { setup: function () { $(this).bind("scroll", event.special.smartscroll.handler); }, teardown: function () { $(this).unbind("scroll", event.special.smartscroll.handler); }, handler: function (event, execAsap) { var context = this, args = arguments; event.type = "smartscroll"; if (scrollTimeout) { clearTimeout(scrollTimeout); } scrollTimeout = setTimeout(function () { $.event.handle.apply(context, args); }, execAsap === "execAsap" ? 0 : 100); } }; $.fn.smartscroll = function (fn) { return fn ? this.bind("smartscroll", fn) : this.trigger("smartscroll", ["execAsap"]); }; })(window, jQuery);
lgpl-3.0
evangelistalab/forte
forte/api/rdms_api.cc
5090
/* * @BEGIN LICENSE * * Forte: an open-source plugin to Psi4 (https://github.com/psi4/psi4) * t hat implements a variety of quantum chemistry methods for strongly * correlated electrons. * * Copyright (c) 2012-2022 by its authors (see LICENSE, AUTHORS). * * The copyrights for code used from other parties are included in * the corresponding files. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * @END LICENSE */ #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include "helpers/helpers.h" #include "base_classes/rdms.h" namespace py = pybind11; using namespace pybind11::literals; namespace forte { /// Export the RDMs class void export_RDMs(py::module& m) { py::class_<RDMs>(m, "RDMs") .def("max_rdm_level", &RDMs::max_rdm_level, "Return the max RDM level") .def("ms_avg", &RDMs::ms_avg, "Return if RDMs setup is Ms-averaged") .def( "g1a", [](RDMs& rdm) { return ambit_to_np(rdm.g1a()); }, "Return the alpha 1RDM as a numpy array") .def( "g1b", [](RDMs& rdm) { return ambit_to_np(rdm.g1b()); }, "Return the beta 1RDM as a numpy array") .def( "g2aa", [](RDMs& rdm) { return ambit_to_np(rdm.g2aa()); }, "Return the alpha-alpha 2RDM as a numpy array") .def( "g2ab", [](RDMs& rdm) { return ambit_to_np(rdm.g2ab()); }, "Return the alpha-beta 2RDM as a numpy array") .def( "g2bb", [](RDMs& rdm) { return ambit_to_np(rdm.g2bb()); }, "Return the beta-beta 2RDM as a numpy array") .def( "g3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.g3aaa()); }, "Return the alpha-alpha-alpha 3RDM as a numpy array") .def( "g3aab", [](RDMs& rdm) { return ambit_to_np(rdm.g3aab()); }, "Return the alpha-alpha-beta 3RDM as a numpy array") .def( "g3abb", [](RDMs& rdm) { return ambit_to_np(rdm.g3abb()); }, "Return the alpha-beta-beta 3RDM as a numpy array") .def( "g3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.g3bbb()); }, "Return the beta-beta-beta 3RDM as a numpy array") .def( "L2aa", [](RDMs& rdm) { return ambit_to_np(rdm.L2aa()); }, "Return the alpha-alpha 2-cumulant as a numpy array") .def( "L2ab", [](RDMs& rdm) { return ambit_to_np(rdm.L2ab()); }, "Return the alpha-beta 2-cumulant as a numpy array") .def( "L2bb", [](RDMs& rdm) { return ambit_to_np(rdm.L2bb()); }, "Return the beta-beta 2-cumulant as a numpy array") .def( "L3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.L3aaa()); }, "Return the alpha-alpha-alpha 3-cumulant as a numpy array") .def( "L3aab", [](RDMs& rdm) { return ambit_to_np(rdm.L3aab()); }, "Return the alpha-alpha-beta 3-cumulant as a numpy array") .def( "L3abb", [](RDMs& rdm) { return ambit_to_np(rdm.L3abb()); }, "Return the alpha-beta-beta 3-cumulant as a numpy array") .def( "L3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.L3bbb()); }, "Return the beta-beta-beta 3-cumulant as a numpy array") .def("SF_G1mat", py::overload_cast<>(&RDMs::SF_G1mat), "Return the spin-free 1RDM as a Psi4 Matrix without symmetry") .def("SF_G1mat", py::overload_cast<const psi::Dimension&>(&RDMs::SF_G1mat), "Return the spin-free 1RDM as a Psi4 Matrix with symmetry given by input") .def( "SF_G1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G1()); }, "Return the spin-free 1RDM as a numpy array") .def( "SF_G2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G2()); }, "Return the spin-free 2RDM as a numpy array") .def( "SF_L1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L1()); }, "Return the spin-free 1RDM as a numpy array") .def( "SF_L2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L2()); }, "Return the spin-free (Ms-averaged) 2-cumulant as a numpy array") .def( "SF_L3", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L3()); }, "Return the spin-free (Ms-averaged) 2-cumulant as a numpy array") .def("rotate", &RDMs::rotate, "Ua"_a, "Ub"_a, "Rotate RDMs using the input unitary matrices"); } } // namespace forte
lgpl-3.0
pcolby/libqtaws
src/greengrass/deletefunctiondefinitionrequest.cpp
3578
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deletefunctiondefinitionrequest.h" #include "deletefunctiondefinitionrequest_p.h" #include "deletefunctiondefinitionresponse.h" #include "greengrassrequest_p.h" namespace QtAws { namespace Greengrass { /*! * \class QtAws::Greengrass::DeleteFunctionDefinitionRequest * \brief The DeleteFunctionDefinitionRequest class provides an interface for Greengrass DeleteFunctionDefinition requests. * * \inmodule QtAwsGreengrass * * AWS IoT Greengrass seamlessly extends AWS onto physical devices so they can act locally on the data they generate, while * still using the cloud for management, analytics, and durable storage. AWS IoT Greengrass ensures your devices can * respond quickly to local events and operate with intermittent connectivity. AWS IoT Greengrass minimizes the cost of * * \sa GreengrassClient::deleteFunctionDefinition */ /*! * Constructs a copy of \a other. */ DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest(const DeleteFunctionDefinitionRequest &other) : GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a DeleteFunctionDefinitionRequest object. */ DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest() : GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(GreengrassRequest::DeleteFunctionDefinitionAction, this)) { } /*! * \reimp */ bool DeleteFunctionDefinitionRequest::isValid() const { return false; } /*! * Returns a DeleteFunctionDefinitionResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * DeleteFunctionDefinitionRequest::response(QNetworkReply * const reply) const { return new DeleteFunctionDefinitionResponse(*this, reply); } /*! * \class QtAws::Greengrass::DeleteFunctionDefinitionRequestPrivate * \brief The DeleteFunctionDefinitionRequestPrivate class provides private implementation for DeleteFunctionDefinitionRequest. * \internal * * \inmodule QtAwsGreengrass */ /*! * Constructs a DeleteFunctionDefinitionRequestPrivate object for Greengrass \a action, * with public implementation \a q. */ DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate( const GreengrassRequest::Action action, DeleteFunctionDefinitionRequest * const q) : GreengrassRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the DeleteFunctionDefinitionRequest * class' copy constructor. */ DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate( const DeleteFunctionDefinitionRequestPrivate &other, DeleteFunctionDefinitionRequest * const q) : GreengrassRequestPrivate(other, q) { } } // namespace Greengrass } // namespace QtAws
lgpl-3.0
AKSW/topicmodeling
topicmodeling.io/src/main/java/org/dice_research/topicmodeling/io/xml/AbstractDocumentXmlReader.java
9108
/** * This file is part of topicmodeling.io. * * topicmodeling.io 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. * * topicmodeling.io 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 topicmodeling.io. If not, see <http://www.gnu.org/licenses/>. */ package org.dice_research.topicmodeling.io.xml; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.dice_research.topicmodeling.utils.doc.Document; import org.dice_research.topicmodeling.utils.doc.DocumentMultipleCategories; import org.dice_research.topicmodeling.utils.doc.DocumentText; import org.dice_research.topicmodeling.utils.doc.ParseableDocumentProperty; import org.dice_research.topicmodeling.utils.doc.ner.NamedEntitiesInText; import org.dice_research.topicmodeling.utils.doc.ner.NamedEntityInText; import org.dice_research.topicmodeling.utils.doc.ner.SignedNamedEntityInText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractDocumentXmlReader implements XMLParserObserver { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDocumentXmlReader.class); private Document currentDocument; private NamedEntityInText currentNamedEntity; private List<NamedEntityInText> namedEntities = new ArrayList<NamedEntityInText>(); private List<String> categories = new ArrayList<String>(); private StringBuilder textBuffer = new StringBuilder(); private String data; public AbstractDocumentXmlReader() { } @Override public void handleOpeningTag(String tagString) { // SHOULDN'T THIS METHOD SET data=""? Otherwise it is possible that a // closing tag gets data that was set // before its starting tag has been seen (in most cases this is "\n"). data = ""; // Ok, this is done and the JUnit test is green. This comment will // remain here if another problem should // arose. int pos = tagString.indexOf(' '); String tagName; if (pos == -1) { tagName = tagString; } else { tagName = tagString.substring(0, pos); } if (tagName.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) { currentDocument = new Document(); pos = tagString.indexOf(" id=\""); if (pos > 0) { pos += 5; int tmp = tagString.indexOf('"', pos + 1); if (tmp > 0) { try { tmp = Integer.parseInt(tagString.substring(pos, tmp)); currentDocument.setDocumentId(tmp); } catch (NumberFormatException e) { LOGGER.warn("Coudln't parse the document id from the document tag.", e); } } else { LOGGER.warn("Found a document tag without a document id attribute."); } } } else if (tagName.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME) || tagName.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) { currentNamedEntity = parseNamedEntityInText(tagString); currentNamedEntity.setStartPos(textBuffer.length()); } } @Override public void handleClosingTag(String tagString) { if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) { finishedDocument(currentDocument); currentDocument = null; } else if (tagString.equals(CorpusXmlTagHelper.TEXT_WITH_NAMED_ENTITIES_TAG_NAME) && (currentDocument != null)) { currentDocument.addProperty(new DocumentText(textBuffer.toString())); textBuffer.delete(0, textBuffer.length()); NamedEntitiesInText nes = new NamedEntitiesInText(namedEntities); currentDocument.addProperty(nes); namedEntities.clear(); } else if (tagString.equals(CorpusXmlTagHelper.TEXT_PART_TAG_NAME)) { textBuffer.append(data); data = ""; } else if (tagString.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME) || tagString.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) { if (currentNamedEntity != null) { currentNamedEntity.setLength(data.length()); namedEntities.add(currentNamedEntity); textBuffer.append(data); currentNamedEntity = null; data = ""; } } else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_TAG_NAME)) { currentDocument .addProperty(new DocumentMultipleCategories(categories.toArray(new String[categories.size()]))); categories.clear(); } else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_SINGLE_CATEGORY_TAG_NAME)) { categories.add(data); data = ""; } else { if (currentDocument != null) { Class<? extends ParseableDocumentProperty> propertyClazz = CorpusXmlTagHelper .getParseableDocumentPropertyClassForTagName(tagString); if (propertyClazz != null) { try { ParseableDocumentProperty property; Constructor<? extends ParseableDocumentProperty> constructor; try { constructor = propertyClazz.getConstructor(String.class); property = constructor.newInstance(data); } catch (NoSuchMethodException e) { // Couldn't get a constructor accepting a single // String. Lets try the normal constructor. constructor = propertyClazz.getConstructor(); property = constructor.newInstance(); property.parseValue(data); } currentDocument.addProperty(property); } catch (Exception e) { LOGGER.error("Couldn't parse property " + propertyClazz + " from the String \"" + data + "\".", e); } } data = ""; } } } @Override public void handleData(String data) { this.data = data; } @Override public void handleEmptyTag(String tagString) { // nothing to do } protected NamedEntityInText parseNamedEntityInText(String tag) { String namedEntityUri = null; String namedEntitySource = null; int startPos = -1; int length = -1; int start = 0, end = 0; try { start = tag.indexOf(' ') + 1; end = tag.indexOf('=', start); String key, value; while (end > 0) { key = tag.substring(start, end).trim(); end = tag.indexOf('"', end); start = tag.indexOf('"', end + 1); value = tag.substring(end + 1, start); if (key.equals(CorpusXmlTagHelper.URI_ATTRIBUTE_NAME)) { namedEntityUri = value; } else if (key.equals(CorpusXmlTagHelper.SOURCE_ATTRIBUTE_NAME)) { namedEntitySource = value; } /* * else if (key.equals("start")) { startPos = * Integer.parseInt(value); } else if (key.equals("length")) { * length = Integer.parseInt(value); } */ ++start; end = tag.indexOf('=', start); } if (namedEntitySource != null) { return new SignedNamedEntityInText(startPos, length, namedEntityUri, namedEntitySource); } else { return new NamedEntityInText(startPos, length, namedEntityUri); } } catch (Exception e) { LOGGER.error("Couldn't parse NamedEntityInText tag (" + tag + "). Returning null.", e); } return null; } public static void registerParseableDocumentProperty(Class<? extends ParseableDocumentProperty> clazz) { CorpusXmlTagHelper.registerParseableDocumentProperty(clazz); } protected abstract void finishedDocument(Document document); }
lgpl-3.0
OpenSoftwareSolutions/PDFReporter-Studio
com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/chart/property/widget/MeterIntervalsDialog.java
12609
/******************************************************************************* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * 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 ******************************************************************************/ package com.jaspersoft.studio.components.chart.property.widget; import java.util.List; import net.sf.jasperreports.charts.JRDataRange; import net.sf.jasperreports.charts.design.JRDesignDataRange; import net.sf.jasperreports.charts.util.JRMeterInterval; import net.sf.jasperreports.eclipse.ui.util.UIUtils; import net.sf.jasperreports.engine.JRExpression; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.views.properties.IPropertyDescriptor; import com.jaspersoft.studio.components.chart.messages.Messages; import com.jaspersoft.studio.editor.expression.ExpressionContext; import com.jaspersoft.studio.model.APropertyNode; import com.jaspersoft.studio.property.descriptor.NullEnum; import com.jaspersoft.studio.property.descriptor.color.ColorCellEditor; import com.jaspersoft.studio.property.descriptor.color.ColorLabelProvider; import com.jaspersoft.studio.property.descriptor.expression.JRExpressionCellEditor; import com.jaspersoft.studio.property.section.AbstractSection; import com.jaspersoft.studio.swt.widgets.table.DeleteButton; import com.jaspersoft.studio.swt.widgets.table.INewElement; import com.jaspersoft.studio.swt.widgets.table.ListContentProvider; import com.jaspersoft.studio.swt.widgets.table.ListOrderButtons; import com.jaspersoft.studio.swt.widgets.table.NewButton; import com.jaspersoft.studio.utils.AlfaRGB; import com.jaspersoft.studio.utils.Colors; import com.jaspersoft.studio.utils.Misc; /** * Dialog with a table that show all the meter intervals defined, and allow to edit, move * delete and add them * * @author Orlandin Marco * */ public class MeterIntervalsDialog extends Dialog { /** * Section used to get the selected element */ private AbstractSection section; /** * Descriptor of the property */ private IPropertyDescriptor pDescriptor; /** * List of the intervals actually shown in the table */ private List<JRMeterInterval> intervalsList; /** * Table where the intervals are shown */ private Table table; /** * Table viewer */ private TableViewer tableViewer; /** * Composite where the table is placed */ private Composite sectioncmp; /** * Cell editor for the low expression */ private JRExpressionCellEditor lowExp; /** * Cell editor for the high expression */ private JRExpressionCellEditor highExp; /** * Create the dialog * * @param parentShell parent shell * @param section section of the element * @param pDescriptor descriptor of the intervals property * @param intervalsList list of the intervals already inside the meter chart */ public MeterIntervalsDialog(Shell parentShell, AbstractSection section, IPropertyDescriptor pDescriptor, List<JRMeterInterval> intervalsList) { super(parentShell); this.pDescriptor = pDescriptor; this.intervalsList = intervalsList; this.section = section; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.MeterIntervalsDialog_dialogTitle); } /** * * Custom label provider for the table * */ private final class TLabelProvider extends LabelProvider implements ITableLabelProvider { private ColorLabelProvider colorLabel = new ColorLabelProvider(NullEnum.NULL); /** * Return an image only on the second column of the table, the one with the color. The * image show a sample of the color */ public Image getColumnImage(Object element, int columnIndex) { JRMeterInterval mi = (JRMeterInterval) element; switch (columnIndex) { case 1: AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor()); Double alfa = mi.getAlphaDouble(); color.setAlfa(alfa != null ? alfa : 1.0d); return colorLabel.getImage(color); } return null; } /** * Return an appropriate string for every column of the table */ public String getColumnText(Object element, int columnIndex) { JRMeterInterval mi = (JRMeterInterval) element; JRDataRange dataRange = mi.getDataRange(); switch (columnIndex) { case 0: return Misc.nvl(mi.getLabel(), ""); //$NON-NLS-1$ case 1: AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor()); Double alfa = mi.getAlphaDouble(); color.setAlfa(alfa != null ? alfa : 1.0d); RGB rgb = color.getRgb(); return "RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + color.getAlfa()+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ case 2: if (dataRange != null) { JRExpression lowe = dataRange.getLowExpression(); return lowe != null ? lowe.getText() : ""; //$NON-NLS-1$ } break; case 3: if (dataRange != null) { JRExpression highe = dataRange.getHighExpression(); return highe != null ? highe.getText() : ""; //$NON-NLS-1$ } break; } return ""; //$NON-NLS-1$ } } @Override protected Control createDialogArea(Composite parent) { sectioncmp = (Composite)super.createDialogArea(parent); sectioncmp = new Composite(sectioncmp, SWT.NONE); sectioncmp.setLayout(new GridLayout(2,false)); sectioncmp.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite bGroup = new Composite(sectioncmp, SWT.NONE); bGroup.setLayout(new GridLayout(1, false)); bGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL)); buildTable(sectioncmp); new NewButton().createNewButtons(bGroup, tableViewer, new INewElement() { public Object newElement(List<?> input, int pos) { NewMeterIntervalWizard wizard = new NewMeterIntervalWizard(); WizardDialog dialog = new WizardDialog(UIUtils.getShell(), wizard); if (dialog.open() == WizardDialog.OK){ return wizard.getMeterInterval(); } else return null; } }); new DeleteButton().createDeleteButton(bGroup, tableViewer); new ListOrderButtons().createOrderButtons(bGroup, tableViewer); table.setToolTipText(pDescriptor.getDescription()); //Set the content of the table APropertyNode selctedNode = section.getElement(); if (selctedNode != null) { ExpressionContext expContext = new ExpressionContext(selctedNode.getJasperConfiguration()); lowExp.setExpressionContext(expContext); highExp.setExpressionContext(expContext); } tableViewer.setInput(intervalsList); return sectioncmp; } /** * Create the table element with all the cell editors * * @param composite parent of the table */ private void buildTable(Composite composite) { table = new Table(composite, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); GridData gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 200; gd.widthHint = 580; table.setLayoutData(gd); table.setHeaderVisible(true); table.setLinesVisible(true); tableViewer = new TableViewer(table); tableViewer.setContentProvider(new ListContentProvider()); tableViewer.setLabelProvider(new TLabelProvider()); attachCellEditors(tableViewer, table); TableLayout tlayout = new TableLayout(); tlayout.addColumnData(new ColumnWeightData(25)); tlayout.addColumnData(new ColumnWeightData(25)); tlayout.addColumnData(new ColumnWeightData(25)); tlayout.addColumnData(new ColumnWeightData(25)); table.setLayout(tlayout); TableColumn[] column = new TableColumn[4]; column[0] = new TableColumn(table, SWT.NONE); column[0].setText(Messages.MeterIntervalsDialog_label); column[1] = new TableColumn(table, SWT.NONE); column[1].setText(Messages.MeterIntervalsDialog_background); column[2] = new TableColumn(table, SWT.NONE); column[2].setText(Messages.MeterIntervalsDialog_lowExpression); column[3] = new TableColumn(table, SWT.NONE); column[3].setText(Messages.MeterIntervalsDialog_highExpression); for (int i = 0, n = column.length; i < n; i++) column[i].pack(); } /** * Attach the cell editor to the table * * @param viewer viewer of the table * @param parent the table */ private void attachCellEditors(final TableViewer viewer, Composite parent) { viewer.setCellModifier(new ICellModifier() { //Every column can be modfied public boolean canModify(Object element, String property) { if (property.equals("LABEL")) //$NON-NLS-1$ return true; if (property.equals("COLOR")) //$NON-NLS-1$ return true; if (property.equals("HIGH")) //$NON-NLS-1$ return true; if (property.equals("LOW")) //$NON-NLS-1$ return true; return false; } public Object getValue(Object element, String property) { JRMeterInterval mi = (JRMeterInterval) element; if (property.equals("LABEL"))//$NON-NLS-1$ return mi.getLabel(); if (property.equals("COLOR")){//$NON-NLS-1$ AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor()); Double alfa = mi.getAlphaDouble(); color.setAlfa(alfa != null ? alfa : 1.0d); return color; } if (property.equals("HIGH"))//$NON-NLS-1$ return mi.getDataRange().getHighExpression(); if (property.equals("LOW"))//$NON-NLS-1$ return mi.getDataRange().getLowExpression(); return null; } public void modify(Object element, String property, Object value) { TableItem ti = (TableItem) element; JRMeterInterval mi = (JRMeterInterval) ti.getData(); if (property.equals("LABEL")) {//$NON-NLS-1$ mi.setLabel((String) value); } if (property.equals("COLOR")) {//$NON-NLS-1$ AlfaRGB argb = (AlfaRGB) value; mi.setBackgroundColor(Colors.getAWT4SWTRGBColor(argb)); mi.setAlpha(argb.getAlfa() / 255.0d); } if (property.equals("HIGH")) {//$NON-NLS-1$ ((JRDesignDataRange) mi.getDataRange()).setHighExpression((JRExpression) value); } if (property.equals("LOW")) {//$NON-NLS-1$ ((JRDesignDataRange) mi.getDataRange()).setLowExpression((JRExpression) value); } tableViewer.update(element, new String[] { property }); tableViewer.refresh(); propertyChange(); } }); lowExp = new JRExpressionCellEditor(parent, null); highExp = new JRExpressionCellEditor(parent, null); ColorCellEditor argbColor = new ColorCellEditor(parent){ @Override protected void updateContents(Object value) { AlfaRGB argb = (AlfaRGB) value; if (argb == null) { rgbLabel.setText(""); //$NON-NLS-1$ } else { RGB rgb = argb.getRgb(); rgbLabel.setText("RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + argb.getAlfa()+")");//$NON-NLS-4$ //$NON-NLS-5$//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ } } }; viewer.setCellEditors(new CellEditor[] { new TextCellEditor(parent), argbColor, lowExp, highExp }); viewer.setColumnProperties(new String[] { "LABEL", "COLOR", "LOW", "HIGH" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } /** * When something in the table change, the list of the element inside the table is update as well */ @SuppressWarnings("unchecked") private void propertyChange() { intervalsList = (List<JRMeterInterval>)tableViewer.getInput(); } /** * Return the list of the intervals actually shown in the table * * @return a list of intervals, can be null */ public List<JRMeterInterval> getIntervalsList(){ return intervalsList; } }
lgpl-3.0
jsitaraman/tioga
src/MeshBlock.C
35409
// // This file is part of the Tioga software library // // Tioga is a tool for overset grid assembly on parallel distributed systems // Copyright (C) 2015 Jay Sitaraman // // This library is TIOGA_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, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "codetypes.h" #include "MeshBlock.h" #include <cstring> #include <stdexcept> extern "C" { void findOBB(double *x,double xc[3],double dxc[3],double vec[3][3],int nnodes); double computeCellVolume(double xv[8][3],int nvert); void deallocateLinkList(DONORLIST *temp); void deallocateLinkList2(INTEGERLIST *temp); double tdot_product(double a[3],double b[3],double c[3]); void getobbcoords(double xc[3],double dxc[3],double vec[3][3],double xv[8][3]); void transform2OBB(double xv[3],double xc[3],double vec[3][3],double xd[3]); void writebbox(OBB *obb,int bid); void writebboxdiv(OBB *obb,int bid); } void MeshBlock::setData(int btag,int nnodesi,double *xyzi, int *ibli,int nwbci, int nobci, int *wbcnodei,int *obcnodei, int ntypesi,int *nvi,int *nci,int **vconni, uint64_t* cell_gid, uint64_t* node_gid) { int i; // // set internal pointers // meshtag=btag; nnodes=nnodesi; x=xyzi; iblank=ibli; nwbc=nwbci; nobc=nobci; wbcnode=wbcnodei; obcnode=obcnodei; // ntypes=ntypesi; // nv=nvi; nc=nci; vconn=vconni; cellGID = cell_gid; nodeGID = node_gid; // //TRACEI(nnodes); //for(i=0;i<ntypes;i++) TRACEI(nc[i]); ncells=0; for(i=0;i<ntypes;i++) ncells+=nc[i]; #ifdef TIOGA_HAS_NODEGID if (nodeGID == NULL) throw std::runtime_error("#tioga: global IDs for nodes not provided"); #endif } void MeshBlock::preprocess(void) { int i; // // set all iblanks = 1 // for(i=0;i<nnodes;i++) iblank[i]=1; // // find oriented bounding boxes // if (check_uniform_hex_flag) { check_for_uniform_hex(); if (uniform_hex) create_hex_cell_map(); } if (obb) TIOGA_FREE(obb); obb=(OBB *) malloc(sizeof(OBB)); findOBB(x,obb->xc,obb->dxc,obb->vec,nnodes); tagBoundary(); } void MeshBlock::tagBoundary(void) { int i,j,k,n,m,ii; int itag; int inode[8]; double xv[8][3]; double vol; int *iflag; int nvert,i3; FILE *fp; char intstring[7]; char fname[80]; int *iextmp,*iextmp1; int iex; // // do this only once // i.e. when the meshblock is first // initialized, cellRes would be NULL in this case // if(cellRes) TIOGA_FREE(cellRes); if(nodeRes) TIOGA_FREE(nodeRes); // cellRes=(double *) malloc(sizeof(double)*ncells); nodeRes=(double *) malloc(sizeof(double)*nnodes); // // this is a local array // iflag=(int *)malloc(sizeof(int)*nnodes); iextmp=(int *) malloc(sizeof(double)*nnodes); iextmp1=(int *) malloc(sizeof(double)*nnodes); // for(i=0;i<nnodes;i++) iflag[i]=0; // if (userSpecifiedNodeRes ==NULL && userSpecifiedCellRes ==NULL) { for(i=0;i<nnodes;i++) iflag[i]=0; for(i=0;i<nnodes;i++) nodeRes[i]=0.0; // k=0; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { for(m=0;m<nvert;m++) { inode[m]=vconn[n][nvert*i+m]-BASE; i3=3*inode[m]; for(j=0;j<3;j++) xv[m][j]=x[i3+j]; } vol=computeCellVolume(xv,nvert); cellRes[k++]=(vol*resolutionScale); for(m=0;m<nvert;m++) { iflag[inode[m]]++; nodeRes[inode[m]]+=(vol*resolutionScale); } } } } else { k=0; for(n=0;n<ntypes;n++) { for(i=0;i<nc[n];i++) { cellRes[k]=userSpecifiedCellRes[k]; k++; } } for(k=0;k<nnodes;k++) nodeRes[k]=userSpecifiedNodeRes[k]; } for(int j=0;j<3;j++) { mapdims[j]=10; mapdx[j]=2*obb->dxc[j]/mapdims[j]; } // // compute nodal resolution as the average of // all the cells associated with it. This takes care // of partition boundaries as well. // // Also create the inverse map of nodes // if (icft) TIOGA_FREE(icft); icft=(int *)malloc(sizeof(int)*(mapdims[2]*mapdims[1]*mapdims[0]+1)); if (invmap) TIOGA_FREE(invmap); invmap=(int *)malloc(sizeof(int)*nnodes); for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0]+1;i++) icft[i]=-1; icft[0]=0; int *iptr; iptr=(int *)malloc(sizeof(int)*nnodes); // for(i=0;i<nnodes;i++) { double xd[3]; int idx[3]; if (iflag[i]!=0) nodeRes[i]/=iflag[i]; iflag[i]=0; iextmp[i]=iextmp1[i]=0; for(int j=0;j<3;j++) { xd[j]=obb->dxc[j]; for(int k=0;k<3;k++) xd[j]+=(x[3*i+k]-obb->xc[k])*obb->vec[j][k]; idx[j]=xd[j]/mapdx[j]; } int indx=idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0]; iptr[i]=icft[indx+1]; icft[indx+1]=i; } int kc=0; for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++) { int ip=icft[i+1]; int m=0; while(ip != -1) { invmap[kc++]=ip; ip=iptr[ip]; m++; } icft[i+1]=icft[i]+m; } TIOGA_FREE(iptr); // // now tag the boundary nodes // reuse the iflag array // //TRACEI(nobc); for(i=0;i<nobc;i++) { ii=(obcnode[i]-BASE); iflag[(obcnode[i]-BASE)]=1; } // // now tag all the nodes of boundary cells // to be mandatory receptors // also make the inverse map mask if (mapmask) TIOGA_FREE(mapmask); mapmask=(int *)malloc(sizeof(int)*mapdims[2]*mapdims[1]*mapdims[0]); for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++) mapmask[i]=0; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { double xd[3],xc[3],xmin[3],xmax[3]; int idx[3]; itag=0; for(int j=0;j<3;j++) { xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;} for(m=0;m<nvert;m++) { inode[m]=vconn[n][nvert*i+m]-BASE; if (iflag[inode[m]]) itag=1; for(int j=0;j<3;j++) { xd[j]=obb->dxc[j]; for(int k=0;k<3;k++) xd[j]+=(x[3*inode[m]+k]-obb->xc[k])*obb->vec[j][k]; xmin[j]=TIOGA_MIN(xd[j],xmin[j]); xmax[j]=TIOGA_MAX(xd[j],xmax[j]); } } for(int j=0;j<3;j++) { xmin[j]-=TOL; xmax[j]+=TOL;} for(int j=xmin[0]/mapdx[0];j<=xmax[0]/mapdx[0];j++) for(int k=xmin[1]/mapdx[1];k<=xmax[1]/mapdx[1];k++) for(int l=xmin[2]/mapdx[2];l<=xmax[2]/mapdx[2];l++) { idx[0]=TIOGA_MAX(TIOGA_MIN(j,mapdims[0]-1),0); idx[1]=TIOGA_MAX(TIOGA_MIN(k,mapdims[1]-1),0); idx[2]=TIOGA_MAX(TIOGA_MIN(l,mapdims[2]-1),0); mapmask[idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0]]=1; } if (itag) { for(m=0;m<nvert;m++) { //iflag[inode[m]]=1; nodeRes[inode[m]]=BIGVALUE; iextmp[inode[m]]=iextmp1[inode[m]]=1; } } } } /* sprintf(intstring,"%d",100000+myid); sprintf(fname,"nodeRes%s.dat",&(intstring[1])); fp=fopen(fname,"w"); for(i=0;i<nnodes;i++) { if (nodeRes[i]==BIGVALUE) { fprintf(fp,"%e %e %e\n",x[3*i],x[3*i+1],x[3*i+2]); } } fclose(fp); */ // // now tag all the cells which have // mandatory receptors as nodes as not acceptable // donors // for(iex=0;iex<mexclude;iex++) { k=0; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { for(m=0;m<nvert;m++) { inode[m]=vconn[n][nvert*i+m]-BASE; if (iextmp[inode[m]]==1) //(iflag[inode[m]]) { cellRes[k]=BIGVALUE; break; } } if (cellRes[k]==BIGVALUE) { for(m=0;m<nvert;m++) { inode[m]=vconn[n][nvert*i+m]-BASE; if (iextmp[inode[m]]!=1) iextmp1[inode[m]]=1; } } k++; } } for(i=0;i<nnodes;i++) iextmp[i]=iextmp1[i]; } TIOGA_FREE(iflag); TIOGA_FREE(iextmp); TIOGA_FREE(iextmp1); } void MeshBlock::writeGridFile(int bid) { char fname[80]; char intstring[7]; char hash,c; int i,n,j; int bodytag; FILE *fp; int ba; int nvert; sprintf(intstring,"%d",100000+bid); sprintf(fname,"part%s.dat",&(intstring[1])); fp=fopen(fname,"w"); fprintf(fp,"TITLE =\"Tioga output\"\n"); fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\"\n"); fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes, ncells); for(i=0;i<nnodes;i++) { fprintf(fp,"%.14e %.14e %.14e %d\n",x[3*i],x[3*i+1],x[3*i+2],iblank[i]); } ba=1-BASE; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { if (nvert==4) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba); } else if (nvert==5) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba); } else if (nvert==6) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+5]+ba); } else if (nvert==8) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+6]+ba, vconn[n][nvert*i+7]+ba); } } } fclose(fp); return; } void MeshBlock::writeCellFile(int bid) { char fname[80]; char qstr[3]; char intstring[7]; char hash,c; int i,n,j; int bodytag; FILE *fp; int ba; int nvert; sprintf(intstring,"%d",100000+bid); sprintf(fname,"cell%s.dat",&(intstring[1])); fp=fopen(fname,"w"); fprintf(fp, "TITLE =\"Tioga output\"\n"); fprintf(fp, "VARIABLES = \"X\"\n"); fprintf(fp, "\"Y\"\n"); fprintf(fp, "\"Z\"\n"); fprintf(fp, "\"IBLANK\"\n"); fprintf(fp, "\"IBLANK_CELL\"\n"); fprintf(fp, "ZONE T=\"VOL_MIXED\"\n"); fprintf(fp, " Nodes=%d, Elements=%d, ZONETYPE=FEBrick\n", nnodes, ncells); fprintf(fp, " DATAPACKING=BLOCK\n"); fprintf(fp, " VARLOCATION=([5]=CELLCENTERED)\n"); fprintf(fp, " DT=(SINGLE SINGLE SINGLE SINGLE SINGLE)\n"); for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i]); for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+1]); for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+2]); for(i=0;i<nnodes;i++) fprintf(fp,"%d.0\n",iblank[i]); for(i=0;i<ncells;i++) fprintf(fp,"%d.0\n",iblank_cell[i]); ba=1-BASE; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { if (nvert==4) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba); } else if (nvert==5) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba); } else if (nvert==6) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+5]+ba); } else if (nvert==8) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+6]+ba, vconn[n][nvert*i+7]+ba); } } } fclose(fp); return; } void MeshBlock::writeFlowFile(int bid,double *q,int nvar,int type) { char fname[80]; char qstr[3]; char intstring[7]; char hash,c; int i,n,j; int bodytag; FILE *fp; int ba; int nvert; int *ibl; // // if fringes were reduced use // iblank_reduced // if (iblank_reduced) { ibl=iblank_reduced; } else { ibl=iblank; } // sprintf(intstring,"%d",100000+bid); sprintf(fname,"flow%s.dat",&(intstring[1])); fp=fopen(fname,"w"); fprintf(fp,"TITLE =\"Tioga output\"\n"); fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\",\"BTAG\" "); for(i=0;i<nvar;i++) { sprintf(qstr,"Q%d",i); fprintf(fp,"\"%s\",",qstr); } fprintf(fp,"\n"); fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes, ncells); if (type==0) { for(i=0;i<nnodes;i++) { fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag); for(j=0;j<nvar;j++) fprintf(fp,"%lf ",q[i*nvar+j]); //for(j=0;j<nvar;j++) // fprintf(fp,"%lf ", x[3*i]+x[3*i+1]+x[3*i+2]); fprintf(fp,"\n"); } } else { for(i=0;i<nnodes;i++) { fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag); for(j=0;j<nvar;j++) fprintf(fp,"%lf ",q[j*nnodes+i]); fprintf(fp,"\n"); } } ba=1-BASE; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { if (nvert==4) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+3]+ba); } else if (nvert==5) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+4]+ba); } else if (nvert==6) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+5]+ba); } else if (nvert==8) { fprintf(fp,"%d %d %d %d %d %d %d %d\n", vconn[n][nvert*i]+ba, vconn[n][nvert*i+1]+ba, vconn[n][nvert*i+2]+ba, vconn[n][nvert*i+3]+ba, vconn[n][nvert*i+4]+ba, vconn[n][nvert*i+5]+ba, vconn[n][nvert*i+6]+ba, vconn[n][nvert*i+7]+ba); } } } fprintf(fp,"%d\n",nwbc); for(i=0;i<nwbc;i++) fprintf(fp,"%d\n",wbcnode[i]); fprintf(fp,"%d\n",nobc); for(i=0;i<nobc;i++) fprintf(fp,"%d\n",obcnode[i]); fclose(fp); return; } void MeshBlock::getWallBounds(int *mtag,int *existWall, double wbox[6]) { int i,j,i3; int inode; *mtag=meshtag+(1-BASE); if (nwbc <=0) { *existWall=0; for(i=0;i<6;i++) wbox[i]=0; return; } *existWall=1; wbox[0]=wbox[1]=wbox[2]=BIGVALUE; wbox[3]=wbox[4]=wbox[5]=-BIGVALUE; for(i=0;i<nwbc;i++) { inode=wbcnode[i]-BASE; i3=3*inode; for(j=0;j<3;j++) { wbox[j]=TIOGA_MIN(wbox[j],x[i3+j]); wbox[j+3]=TIOGA_MAX(wbox[j+3],x[i3+j]); } } } void MeshBlock::markWallBoundary(int *sam,int nx[3],double extents[6]) { int i,j,k,m,n; int nvert; int ii,jj,kk,mm; int i3,iv; int *iflag; int *inode; char intstring[7]; char fname[80]; double ds[3]; double xv; int imin[3]; int imax[3]; FILE *fp; // iflag=(int *)malloc(sizeof(int)*ncells); inode=(int *) malloc(sizeof(int)*nnodes); /// //sprintf(intstring,"%d",100000+myid); //sprintf(fname,"wbc%s.dat",&(intstring[1])); //fp=fopen(fname,"w"); for(i=0;i<ncells;i++) iflag[i]=0; for(i=0;i<nnodes;i++) inode[i]=0; // for(i=0;i<nwbc;i++) { ii=wbcnode[i]-BASE; //fprintf(fp,"%e %e %e\n",x[3*ii],x[3*ii+1],x[3*ii+2]); inode[ii]=1; } //fclose(fp); // // mark wall boundary cells // m=0; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { for(j=0;j<nvert;j++) { ii=vconn[n][nvert*i+j]-BASE; if (inode[ii]==1) { iflag[m]=1; break; } } m++; } } // // find delta's in each directions // for(k=0;k<3;k++) ds[k]=(extents[k+3]-extents[k])/nx[k]; // // mark sam cells with wall boundary cells now // m=0; for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { if (iflag[m]==1) { // // find the index bounds of each wall boundary cell // bounding box // imin[0]=imin[1]=imin[2]=BIGINT; imax[0]=imax[1]=imax[2]=-BIGINT; for(j=0;j<nvert;j++) { i3=3*(vconn[n][nvert*i+j]-BASE); for(k=0;k<3;k++) { xv=x[i3+k]; iv=floor((xv-extents[k])/ds[k]); imin[k]=TIOGA_MIN(imin[k],iv); imax[k]=TIOGA_MAX(imax[k],iv); } } for(j=0;j<3;j++) { imin[j]=TIOGA_MAX(imin[j],0); imax[j]=TIOGA_MIN(imax[j],nx[j]-1); } // // mark sam to 1 // for(kk=imin[2];kk<imax[2]+1;kk++) for(jj=imin[1];jj<imax[1]+1;jj++) for (ii=imin[0];ii<imax[0]+1;ii++) { mm=kk*nx[1]*nx[0]+jj*nx[0]+ii; sam[mm]=2; } } m++; } } TIOGA_FREE(iflag); TIOGA_FREE(inode); } void MeshBlock::getReducedOBB(OBB *obc,double *realData) { int i,j,k,m,n,i3; int nvert; bool iflag; double bbox[6],xd[3]; /* for(j=0;j<3;j++) { realData[j]=obb->xc[j]; realData[j+3]=obb->dxc[j]; } return; */ for(j=0;j<3;j++) { realData[j]=BIGVALUE; realData[j+3]=-BIGVALUE; } for(n=0;n<ntypes;n++) { nvert=nv[n]; for(i=0;i<nc[n];i++) { bbox[0]=bbox[1]=bbox[2]=BIGVALUE; bbox[3]=bbox[4]=bbox[5]=-BIGVALUE; for(m=0;m<nvert;m++) { i3=3*(vconn[n][nvert*i+m]-BASE); for(j=0;j<3;j++) xd[j]=0; for(j=0;j<3;j++) for(k=0;k<3;k++) xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k]; for(j=0;j<3;j++) bbox[j]=TIOGA_MIN(bbox[j],xd[j]); for(j=0;j<3;j++) bbox[j+3]=TIOGA_MAX(bbox[j+3],xd[j]); } iflag=0; for(j=0;j<3;j++) iflag=(iflag || (bbox[j] > obc->dxc[j])); if (iflag) continue; iflag=0; for(j=0;j<3;j++) iflag=(iflag || (bbox[j+3] < -obc->dxc[j])); if (iflag) continue; for (m=0;m<nvert;m++) { i3=3*(vconn[n][nvert*i+m]-BASE); for(j=0;j<3;j++) xd[j]=0; for(j=0;j<3;j++) for(k=0;k<3;k++) xd[j]+=(x[i3+k]-obb->xc[k])*obb->vec[j][k]; for(j=0;j<3;j++) realData[j]=TIOGA_MIN(realData[j],xd[j]); for(j=0;j<3;j++) realData[j+3]=TIOGA_MAX(realData[j+3],xd[j]); } } } for(j=0;j<6;j++) bbox[j]=realData[j]; for(j=0;j<3;j++) { realData[j]=obb->xc[j]; for(k=0;k<3;k++) realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j]; realData[j+3]=(bbox[j+3]-bbox[j])*0.51; } return; } void MeshBlock::getReducedOBB2(OBB *obc,double *realData) { int i,j,k,l,m,n,i3,jmin,kmin,lmin,jmax,kmax,lmax,indx; double bbox[6],xd[3]; double xmin[3],xmax[3],xv[8][3]; double delta; int imin[3],imax[3]; getobbcoords(obc->xc,obc->dxc,obc->vec,xv); for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}; for(n=0;n<8;n++) { transform2OBB(xv[n],obb->xc,obb->vec,xd); for(j=0;j<3;j++) { xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]); xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]); } } for(j=0;j<3;j++) { delta=0.01*(xmax[j]-xmin[j]); xmin[j]-=delta; xmax[j]+=delta; imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0); imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1); } lmin=mapdims[2]-1; kmin=mapdims[1]-1; jmin=mapdims[0]-1; lmax=kmax=jmax=0; for(l=imin[2];l<=imax[2];l++) for(k=imin[1];k<=imax[1];k++) for(j=imin[0];j<=imax[0];j++) { indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j; if (mapmask[indx]) { lmin=TIOGA_MIN(lmin,l); kmin=TIOGA_MIN(kmin,k); jmin=TIOGA_MIN(jmin,j); lmax=TIOGA_MAX(lmax,l); kmax=TIOGA_MAX(kmax,k); jmax=TIOGA_MAX(jmax,j); } } bbox[0]=-obb->dxc[0]+jmin*mapdx[0]; bbox[1]=-obb->dxc[1]+kmin*mapdx[1]; bbox[2]=-obb->dxc[2]+lmin*mapdx[2]; bbox[3]=-obb->dxc[0]+(jmax+1)*mapdx[0]; bbox[4]=-obb->dxc[1]+(kmax+1)*mapdx[1]; bbox[5]=-obb->dxc[2]+(lmax+1)*mapdx[2]; for(j=0;j<3;j++) { realData[j]=obb->xc[j]; for(k=0;k<3;k++) realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j]; realData[j+3]=(bbox[j+3]-bbox[j])*0.5; } return; } void MeshBlock::getQueryPoints(OBB *obc, int *nints,int **intData, int *nreals, double **realData) { int i,j,k; int i3; double xd[3]; int *inode; int iptr; int m; inode=(int *)malloc(sizeof(int)*nnodes); *nints=*nreals=0; for(i=0;i<nnodes;i++) { i3=3*i; for(j=0;j<3;j++) xd[j]=0; for(j=0;j<3;j++) for(k=0;k<3;k++) xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k]; if (fabs(xd[0]) <= obc->dxc[0] && fabs(xd[1]) <= obc->dxc[1] && fabs(xd[2]) <= obc->dxc[2]) { inode[*nints]=i; (*nints)++; (*nreals)+=4; } } if (myid==0 && meshtag==1) {TRACEI(*nints);} (*intData)=(int *)malloc(sizeof(int)*(*nints)); (*realData)=(double *)malloc(sizeof(double)*(*nreals)); // m=0; for(i=0;i<*nints;i++) { i3=3*inode[i]; (*intData)[i]=inode[i]; (*realData)[m++]=x[i3]; (*realData)[m++]=x[i3+1]; (*realData)[m++]=x[i3+2]; (*realData)[m++]=nodeRes[inode[i]]; } // TIOGA_FREE(inode); } void MeshBlock::getQueryPoints2(OBB *obc, int *nints,int **intData, int *nreals, double **realData) { int i,j,k,l,il,ik,ij,n,m,i3,iflag; int indx,iptr; int *inode; double delta; double xv[8][3],mdx[3],xd[3],xc[3]; double xmax[3],xmin[3]; int imin[3],imax[3]; // inode=(int *)malloc(sizeof(int)*nnodes); *nints=*nreals=0; getobbcoords(obc->xc,obc->dxc,obc->vec,xv); for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}; //writebbox(obc,1); //writebbox(obb,2); //writebboxdiv(obb,1); // for(n=0;n<8;n++) { transform2OBB(xv[n],obb->xc,obb->vec,xd); for(j=0;j<3;j++) { xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]); xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]); } } for(j=0;j<3;j++) { delta=0.01*(xmax[j]-xmin[j]); xmin[j]-=delta; xmax[j]+=delta; imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0); imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1); mdx[j]=0.5*mapdx[j]; } // // find min/max extends of a single sub-block // in OBC axes // getobbcoords(obc->xc,mdx,obb->vec,xv); for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;} for(m=0;m<8;m++) { transform2OBB(xv[m],obc->xc,obc->vec,xd); for(j=0;j<3;j++) { xmin[j]=TIOGA_MIN(xmin[j],xd[j]); xmax[j]=TIOGA_MAX(xmax[j],xd[j]); } } //printf("xmin :%f %f %f\n",xmin[0],xmin[1],xmin[2]); //printf("xmax :%f %f %f\n",xmax[0],xmax[1],xmax[2]); // // now find the actual number of points // that are within OBC using only the // sub-blocks with potential bbox overlap // //FILE *fp,*fp2,*fp3,*fp4; //fp=fopen("v.dat","w"); //fp2=fopen("v2.dat","w"); //fp3=fopen("v3.dat","w"); //fp4=fopen("v4.dat","w"); for(l=imin[2];l<=imax[2];l++) for(k=imin[1];k<=imax[1];k++) for(j=imin[0];j<=imax[0];j++) { // // centroid of each sub-block // in OBC axes // xd[0]=-obb->dxc[0]+j*mapdx[0]+mapdx[0]*0.5; xd[1]=-obb->dxc[1]+k*mapdx[1]+mapdx[1]*0.5; xd[2]=-obb->dxc[2]+l*mapdx[2]+mapdx[2]*0.5; for(n=0;n<3;n++) { xc[n]=obb->xc[n]; for(ij=0;ij<3;ij++) xc[n]+=(xd[ij]*obb->vec[ij][n]); } //if (j==0 && k==0 & l==0) { //printf("%f %f %f\n",obc->vec[0][0],obc->vec[1][0],obc->vec[2][0]); //printf("%f %f %f\n",obc->vec[0][1],obc->vec[1][1],obc->vec[2][1]); //printf("%f %f %f\n",obc->vec[0][2],obc->vec[1][2],obc->vec[2][2]); //printf("%f %f %f\n",obc->xc[0],obc->xc[1],obc->xc[2]); //} //fprintf(fp,"%f %f %f\n",xc[0],xc[1],xc[2]); transform2OBB(xc,obc->xc,obc->vec,xd); //fprintf(fp2,"%f %f %f\n",xd[0],xd[1],xd[2]); //if (fabs(xd[0]) <= obc->dxc[0] && // fabs(xd[1]) <= obc->dxc[1] && // fabs(xd[2]) <= obc->dxc[2]) // { // fprintf(fp3,"%f %f %f\n",xc[0],xc[1],xc[2]); // } // // check if this sub-block overlaps OBC // iflag=0; for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmin[ij]+xd[ij] > obc->dxc[ij])); if (iflag) continue; iflag=0; for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmax[ij]+xd[ij] < -obc->dxc[ij])); if (iflag) continue; //fprintf(fp4,"%f %f %f\n",xc[0],xc[1],xc[2]); // // if there overlap // go through points within the sub-block // to figure out what needs to be send // indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j; for(m=icft[indx];m<icft[indx+1];m++) { i3=3*invmap[m]; for(ik=0;ik<3;ik++) xc[ik]=x[i3+ik]; transform2OBB(xc,obc->xc,obc->vec,xd); if (fabs(xd[0]) <= obc->dxc[0] && fabs(xd[1]) <= obc->dxc[1] && fabs(xd[2]) <= obc->dxc[2]) { inode[*nints]=invmap[m]; (*nints)++; (*nreals)+=4; } } } // TRACEI(*nints); // fclose(fp); // fclose(fp2); // fclose(fp3); // fclose(fp4); // int ierr; // MPI_Abort(MPI_COMM_WORLD,ierr); // #ifdef TIOGA_HAS_NODEGID int nintsPerNode = 3; #else int nintsPerNode = 1; #endif (*intData)=(int *)malloc(sizeof(int)*(*nints) * nintsPerNode); (*realData)=(double *)malloc(sizeof(double)*(*nreals)); // m=0; int iidx = 0; for(i=0;i<*nints;i++) { i3=3*inode[i]; (*intData)[iidx++]=inode[i]; #ifdef TIOGA_HAS_NODEGID std::memcpy(&(*intData)[iidx],&nodeGID[inode[i]], sizeof(uint64_t)); iidx += 2; #endif (*realData)[m++]=x[i3]; (*realData)[m++]=x[i3+1]; (*realData)[m++]=x[i3+2]; (*realData)[m++]=nodeRes[inode[i]]; } // Adjust nints to the proper array size *nints *= nintsPerNode; // TIOGA_FREE(inode); } void MeshBlock::writeOBB(int bid) { FILE *fp; char intstring[7]; char fname[80]; int l,k,j,m,il,ik,ij; REAL xx[3]; sprintf(intstring,"%d",100000+bid); sprintf(fname,"box%s.dat",&(intstring[1])); fp=fopen(fname,"w"); fprintf(fp,"TITLE =\"Box file\"\n"); fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\"\n"); fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",8, 1); for(l=0;l<2;l++) { il=2*(l%2)-1; for(k=0;k<2;k++) { ik=2*(k%2)-1; for(j=0;j<2;j++) { ij=2*(j%2)-1; xx[0]=xx[1]=xx[2]=0; for(m=0;m<3;m++) xx[m]=obb->xc[m]+ij*obb->vec[0][m]*obb->dxc[0] +ik*obb->vec[1][m]*obb->dxc[1] +il*obb->vec[2][m]*obb->dxc[2]; fprintf(fp,"%f %f %f\n",xx[0],xx[1],xx[2]); } } } fprintf(fp,"1 2 4 3 5 6 8 7\n"); fprintf(fp,"%e %e %e\n",obb->xc[0],obb->xc[1],obb->xc[2]); for(k=0;k<3;k++) fprintf(fp,"%e %e %e\n",obb->vec[0][k],obb->vec[1][k],obb->vec[2][k]); fprintf(fp,"%e %e %e\n",obb->dxc[0],obb->dxc[1],obb->dxc[2]); fclose(fp); } // // destructor that deallocates all the // the dynamic objects inside // MeshBlock::~MeshBlock() { int i; // // TIOGA_FREE all data that is owned by this MeshBlock // i.e not the pointers of the external code. // if (cellRes) TIOGA_FREE(cellRes); if (nodeRes) TIOGA_FREE(nodeRes); if (elementBbox) TIOGA_FREE(elementBbox); if (elementList) TIOGA_FREE(elementList); if (adt) delete[] adt; if (donorList) { for(i=0;i<nnodes;i++) deallocateLinkList(donorList[i]); TIOGA_FREE(donorList); } if (interpList) { for(i=0;i<interpListSize;i++) { if (interpList[i].inode) TIOGA_FREE(interpList[i].inode); if (interpList[i].weights) TIOGA_FREE(interpList[i].weights); } TIOGA_FREE(interpList); } if (interpList2) { for(i=0;i<interp2ListSize;i++) { if (interpList2[i].inode) TIOGA_FREE(interpList2[i].inode); if (interpList2[i].weights) TIOGA_FREE(interpList2[i].weights); } TIOGA_FREE(interpList2); } if (interpListCart) { for(i=0;i<interpListCartSize;i++) { if (interpListCart[i].inode) TIOGA_FREE(interpListCart[i].inode); if (interpListCart[i].weights) TIOGA_FREE(interpListCart[i].weights); } TIOGA_FREE(interpListCart); } // For nalu-wind API the iblank_cell array is managed on the nalu side // if (!ihigh) { // if (iblank_cell) TIOGA_FREE(iblank_cell); // } if (obb) TIOGA_FREE(obb); if (obh) TIOGA_FREE(obh); if (isearch) TIOGA_FREE(isearch); if (xsearch) TIOGA_FREE(xsearch); if (res_search) TIOGA_FREE(res_search); if (xtag) TIOGA_FREE(xtag); if (rst) TIOGA_FREE(rst); if (interp2donor) TIOGA_FREE(interp2donor); if (cancelList) deallocateLinkList2(cancelList); if (ctag) TIOGA_FREE(ctag); if (pointsPerCell) TIOGA_FREE(pointsPerCell); if (rxyz) TIOGA_FREE(rxyz); if (picked) TIOGA_FREE(picked); if (rxyzCart) TIOGA_FREE(rxyzCart); if (donorIdCart) TIOGA_FREE(donorIdCart); if (pickedCart) TIOGA_FREE(pickedCart); if (ctag_cart) TIOGA_FREE(ctag_cart); if (tagsearch) TIOGA_FREE(tagsearch); if (donorId) TIOGA_FREE(donorId); if (receptorIdCart) TIOGA_FREE(receptorIdCart); if (icft) TIOGA_FREE(icft); if (mapmask) TIOGA_FREE(mapmask); if (uindx) TIOGA_FREE(uindx); if (invmap) TIOGA_FREE(invmap); // need to add code here for other objects as and // when they become part of MeshBlock object }; // // set user specified node and cell resolutions // void MeshBlock::setResolutions(double *nres,double *cres) { userSpecifiedNodeRes=nres; userSpecifiedCellRes=cres; } // // detect if a given meshblock is a uniform hex // and create a data structure that will enable faster // searching // void MeshBlock::check_for_uniform_hex(void) { double xv[8][3]; int hex_present=0; if (ntypes > 1) return; for(int n=0;n<ntypes;n++) { int nvert=nv[n]; if (nvert==8) { hex_present=1; for(int i=0;i<nc[n];i++) { int vold=-1; for(int m=0;m<nvert;m++) { if (vconn[n][nvert*i+m]==vold) return; // degenerated hex are not uniform vold=vconn[n][nvert*i+m]; int i3=3*(vconn[n][nvert*i+m]-BASE); for(int k=0;k<3;k++) xv[m][k]=x[i3+k]; } // // check angles to see if sides are // rectangles // // z=0 side // if (fabs(tdot_product(xv[1],xv[3],xv[0])) > TOL) return; if (fabs(tdot_product(xv[1],xv[3],xv[2])) > TOL) return; // // x=0 side // if (fabs(tdot_product(xv[3],xv[4],xv[0])) > TOL) return; if (fabs(tdot_product(xv[3],xv[4],xv[7])) > TOL) return; // // y=0 side // if (fabs(tdot_product(xv[4],xv[1],xv[0])) > TOL) return; if (fabs(tdot_product(xv[4],xv[1],xv[5])) > TOL) return; // // need to check just one more angle on // on the corner against 0 (6) // if (fabs(tdot_product(xv[5],xv[7],xv[6])) > TOL) return; // // so this is a hex // check if it has the same size as the previous hex // if not return // if (i==0){ dx[0]=tdot_product(xv[1],xv[1],xv[0]); dx[1]=tdot_product(xv[3],xv[3],xv[0]); dx[2]=tdot_product(xv[4],xv[4],xv[0]); } else { if (fabs(dx[0]-tdot_product(xv[1],xv[1],xv[0])) > TOL) return; if (fabs(dx[1]-tdot_product(xv[3],xv[3],xv[0])) > TOL) return; if (fabs(dx[2]-tdot_product(xv[4],xv[4],xv[0])) > TOL) return; } } } } if (hex_present) { for(int j=0;j<3;j++) dx[j]=sqrt(dx[j]); uniform_hex=1; if (obh) TIOGA_FREE(obh); obh=(OBB *) malloc(sizeof(OBB)); for(int j=0;j<3;j++) for(int k=0;k<3;k++) obh->vec[j][k]=0; for(int k=0;k<3;k++) obh->vec[0][k]=(xv[1][k]-xv[0][k])/dx[0]; for(int k=0;k<3;k++) obh->vec[1][k]=(xv[3][k]-xv[0][k])/dx[1]; for(int k=0;k<3;k++) obh->vec[2][k]=(xv[4][k]-xv[0][k])/dx[2]; //obh->vec[0][0]=obh->vec[1][1]=obh->vec[2][2]=1; // double xd[3]; double xmax[3]; double xmin[3]; xmax[0]=xmax[1]=xmax[2]=-BIGVALUE; xmin[0]=xmin[1]=xmin[2]=BIGVALUE; // for(int i=0;i<nnodes;i++) { int i3=3*i; for(int j=0;j<3;j++) xd[j]=0; // for(int j=0;j<3;j++) for(int k=0;k<3;k++) xd[j]+=x[i3+k]*obh->vec[j][k]; // for(int j=0;j<3;j++) { xmax[j]=TIOGA_MAX(xmax[j],xd[j]); xmin[j]=TIOGA_MIN(xmin[j],xd[j]); } } // // find the extents of the box // and coordinates of the center w.r.t. xc // increase extents by 1% for tolerance // for(int j=0;j<3;j++) { xmax[j]+=TOL; xmin[j]-=TOL; obh->dxc[j]=(xmax[j]-xmin[j])*0.5; xd[j]=(xmax[j]+xmin[j])*0.5; } // // find the center of the box in // actual cartesian coordinates // for(int j=0;j<3;j++) { obh->xc[j]=0.0; for(int k=0;k<3;k++) obh->xc[j]+=(xd[k]*obh->vec[k][j]); } } return; } void MeshBlock::create_hex_cell_map(void) { for(int j=0;j<3;j++) { xlow[j]=obh->xc[j]; for (int k=0;k<3;k++) xlow[j]-=(obh->dxc[k]*obh->vec[k][j]); idims[j]=round(2*obh->dxc[j]/dx[j]); dx[j]=(2*obh->dxc[j])/idims[j]; } // if (uindx) TIOGA_FREE(uindx); uindx=(int *)malloc(sizeof(int)*idims[0]*idims[1]*idims[2]); for(int i=0;i<idims[0]*idims[1]*idims[2];uindx[i++]=-1); // for(int i=0;i<nc[0];i++) { double xc[3]; double xd[3]; int idx[3]; for(int j=0;j<3;j++) { int lnode=vconn[0][8*i]-BASE; int tnode=vconn[0][8*i+6]-BASE; xc[j]=0.5*(x[3*lnode+j]+x[3*tnode+j]); } for(int j=0;j<3;j++) { xd[j]=0; for(int k=0;k<3;k++) xd[j]+=(xc[k]-xlow[k])*obh->vec[j][k]; idx[j]=xd[j]/dx[j]; } uindx[idx[2]*idims[1]*idims[0]+idx[1]*idims[0]+idx[0]]=i; } }
lgpl-3.0
tgrochow/gemini
daemon/descriptor.cpp
2965
#include <algorithm> #include <descriptor.hpp> namespace gemini { descriptor:: descriptor(unsigned short bus, unsigned short port, unsigned short product_id, unsigned short vendor_id, unsigned short interface_class) : info_(std::array<unsigned short,DESCRIPTOR_SIZE> {bus,port,vendor_id,product_id,interface_class}) {} descriptor:: descriptor(std::array<unsigned short,DESCRIPTOR_SIZE> const& info) : info_(info) {} bool descriptor::relevant(descriptor const& descriptor) const { bool relevant = true; for(unsigned short index = BUS ; index != UNDEFINED ; ++index) { if(info_[index] != MASKED && info_[index] != descriptor[index]) { relevant = false; } } return relevant; } void descriptor:: read_device_address(libusb_device * device) { info_[BUS] = libusb_get_bus_number(device); info_[PORT] = libusb_get_port_number(device); } void descriptor:: read_device_descriptor(libusb_device_descriptor const& dev_desc) { info_[VENDOR_ID] = dev_desc.idVendor; info_[PRODUCT_ID] = dev_desc.idProduct; } void descriptor:: read_interface_descriptor(libusb_interface_descriptor const& intf_desc) { info_[INTERFACE_CLASS] = intf_desc.bInterfaceClass; } std::string const descriptor::info(bool readable) const { std::string descriptor_info; for(unsigned short index = BUS ; index != UNDEFINED ; ++index) { if(index > 0) descriptor_info += " "; if(readable) { switch(index) { case BUS : descriptor_info += "[BUS:"; break; case PORT : descriptor_info += "[PORT:"; break; case VENDOR_ID : descriptor_info += "[VENDOR ID:"; break; case PRODUCT_ID : descriptor_info += "[PRODUCT ID:"; break; case INTERFACE_CLASS : descriptor_info += "[INTERFACE CLASS:"; break; } } descriptor_info += std::to_string(info_[index]) + "]"; } return descriptor_info; } std::string const descriptor::device_info() const { std::string device_info; for(unsigned short index = BUS ; index != INTERFACE_CLASS ; ++index) { device_info += " "; device_info += std::to_string(info_[index]); } return device_info; } unsigned short descriptor::operator [] (unsigned short index) const { return info_[index]; } unsigned short & descriptor::operator [] (unsigned short index) { return info_[index]; } bool operator == (descriptor const& i1,descriptor const& i2) { bool equal = true; for(unsigned short index = BUS ; index != UNDEFINED ; ++index) { if(i1[index] != i2[index]) equal = false; } return equal; } // stream operator std::ostream & operator << (std::ostream & out,descriptor const& intf_info) { // write descriptor informations readable in stream out << intf_info.info(true); return out; } } // end namespace gemini
lgpl-3.0
KHIEM2812/libhl
src/queue.c
13383
/* linked queue management library - by xant */ #include <stdio.h> #include <string.h> #include <errno.h> #include <limits.h> #include <sched.h> #include "queue.h" #include "refcnt.h" #include "rqueue.h" #include "atomic_defs.h" #pragma pack(push, 1) // size is 32 bytes on 32bit systems and 64 bytes on 64bit ones typedef struct __queue_entry { refcnt_node_t *node; refcnt_node_t *prev; refcnt_node_t *next; void *value; queue_t *queue; } queue_entry_t; // size is 32 bytes on 32bit systems and 64 bytes on 64bit ones struct __queue { refcnt_t *refcnt; queue_entry_t *head; queue_entry_t *tail; uint32_t length; int free; queue_free_value_callback_t free_value_cb; rqueue_t *bpool; uint32_t bpool_size; }; #pragma pack(pop) /* * Create a new queue_t. Allocates resources and returns * a queue_t opaque structure for later use */ queue_t * queue_create() { queue_t *q = (queue_t *)malloc(sizeof(queue_t)); if(q) { queue_init(q); q->free = 1; } else { return NULL; } return q; } uint32_t queue_set_bpool_size(queue_t *q, uint32_t size) { rqueue_t *new_queue = rqueue_create(size, RQUEUE_MODE_BLOCKING); rqueue_set_free_value_callback(new_queue, free); uint32_t old_size = ATOMIC_READ(q->bpool_size); if (old_size == size) { rqueue_destroy(new_queue); return old_size; } rqueue_t *old_queue = ATOMIC_READ(q->bpool); if (ATOMIC_CAS(q->bpool, old_queue, new_queue)) { ATOMIC_CAS(q->bpool_size, old_size, size); if (old_queue) rqueue_destroy(old_queue); } else { rqueue_destroy(new_queue); } return old_size; } /* static void terminate_node_callback(refcnt_node_t *node, void *priv) { } */ /* * Create a new queue_entry_t structure. Allocates resources and returns * a pointer to the just created queue_entry_t opaque structure */ static inline queue_entry_t * create_entry(queue_t *q) { queue_entry_t *new_entry = (queue_entry_t *)calloc(1, sizeof(queue_entry_t)); new_entry->node = new_node(q->refcnt, new_entry, NULL); new_entry->queue = q; return new_entry; } queue_entry_t *dequeue_reusable_entry(queue_t *q) { rqueue_t *pool = ATOMIC_READ(q->bpool); queue_entry_t *entry = pool ? rqueue_read(pool) : NULL; if (entry) entry->node = new_node(q->refcnt, entry, NULL); else entry = create_entry(q); return entry; } void queue_reusable_entry(queue_entry_t *entry) { entry->node = NULL; rqueue_t *pool = ATOMIC_READ(entry->queue->bpool); if (!pool || rqueue_write(pool, entry) != 0) free(entry); } /* * Initialize a preallocated queue_t pointed by q * useful when using static queue handlers */ void queue_init(queue_t *q) { memset(q, 0, sizeof(queue_t)); if (!q->refcnt) q->refcnt = refcnt_create(1<<10, NULL, (refcnt_free_node_ptr_callback_t)queue_reusable_entry); if (!q->head) q->head = create_entry(q); if (!q->tail) q->tail = create_entry(q); store_ref(q->refcnt, &q->head->next, q->tail->node); store_ref(q->refcnt, &q->tail->prev, q->head->node); } /* * Free resources allocated for a queue_entry_t structure. * If the entry is linked in a queue this routine will also unlink correctly * the entry from the queue. */ static inline void destroy_entry(refcnt_t *refcnt, queue_entry_t *entry) { if(entry) release_ref(refcnt, ATOMIC_READ(entry->node)); // this will also release the entry itself } /* * Destroy a queue_t. Free resources allocated for q */ void queue_destroy(queue_t *q) { if(q) { if (q->bpool) { rqueue_destroy(q->bpool); q->bpool = NULL; } queue_clear(q); store_ref(q->refcnt, &q->head->next, NULL); destroy_entry(q->refcnt, q->head); store_ref(q->refcnt, &q->tail->prev, NULL); destroy_entry(q->refcnt, q->tail); if (q->bpool) rqueue_destroy(q->bpool); refcnt_destroy(q->refcnt); if(q->free) free(q); } } /* * Clear a queue_t. Removes all entries in q * if values are associated to entries, resources for those will not be freed. * queue_clear() can be used safely with entry-based and tagged-based api, * otherwise you must really know what you are doing */ void queue_clear(queue_t *q) { void *v; /* Destroy all entries still in q */ while((v = queue_pop_left(q)) != NULL) { /* if there is a tagged_value_t associated to the entry, * let's free memory also for it */ if (q->free_value_cb) q->free_value_cb(v); } } /* Returns actual lenght of queue_t pointed by l */ uint32_t queue_count(queue_t *q) { uint32_t len; len = ATOMIC_READ(q->length); return len; } void queue_set_free_value_callback(queue_t *q, queue_free_value_callback_t free_value_cb) { q->free_value_cb = free_value_cb; } static inline void mark_prev(queue_entry_t *entry) { do { refcnt_node_t *link = ATOMIC_READ(entry->prev); if (link == REFCNT_MARK_ON(link)) break; if (ATOMIC_CAS(entry->prev, link, REFCNT_MARK_ON(link))) break; } while (1); } /* * Insert a queue_entry_t at the beginning of a queue (or at the top if the stack) */ int queue_push_left(queue_t *q, void *value) { queue_entry_t *entry = create_entry(q); entry->value = value; queue_entry_t *prev = ATOMIC_READ(q->head); while (1) { queue_entry_t *next = get_node_ptr(deref_link(q->refcnt, &prev->next)); if (!next) { continue; } store_ref(q->refcnt, &entry->prev, ATOMIC_READ(prev->node)); store_ref(q->refcnt, &entry->next, ATOMIC_READ(next->node)); if (ATOMIC_CAS(next->prev, REFCNT_MARK_OFF(entry->prev), entry->node)) { release_ref(q->refcnt, ATOMIC_READ(prev->node)); retain_ref(q->refcnt, ATOMIC_READ(entry->node)); while (!ATOMIC_CAS(prev->next, ATOMIC_READ(next->node), ATOMIC_READ(entry->node))) { release_ref(q->refcnt, next->node); sched_yield(); queue_entry_t *next2 = get_node_ptr(deref_link(q->refcnt, &prev->next)); next = next2; store_ref(q->refcnt, &entry->next, ATOMIC_READ(next->node)); } release_ref(q->refcnt, ATOMIC_READ(next->node)); retain_ref(q->refcnt, ATOMIC_READ(entry->node)); release_ref(q->refcnt, ATOMIC_READ(next->node)); break; } if (next) release_ref(q->refcnt, ATOMIC_READ(next->node)); store_ref(q->refcnt, &entry->next, NULL); store_ref(q->refcnt, &entry->prev, NULL); } ATOMIC_INCREMENT(q->length); return 0; } /* * Pushs a queue_entry_t at the end of a queue */ int queue_push_right(queue_t *q, void *value) { queue_entry_t *entry = create_entry(q); entry->value = value; queue_entry_t *next = ATOMIC_READ(q->tail); while (1) { queue_entry_t *prev = get_node_ptr(deref_link(q->refcnt, &next->prev)); if (!prev) { continue; } store_ref(q->refcnt, &entry->next, ATOMIC_READ(next->node)); store_ref(q->refcnt, &entry->prev, ATOMIC_READ(prev->node)); if (ATOMIC_CAS(prev->next, REFCNT_MARK_OFF(entry->next), entry->node)) { release_ref(q->refcnt, ATOMIC_READ(next->node)); retain_ref(q->refcnt, ATOMIC_READ(entry->node)); while (!ATOMIC_CAS(next->prev, ATOMIC_READ(prev->node), ATOMIC_READ(entry->node))) { release_ref(q->refcnt, prev->node); sched_yield(); queue_entry_t *prev2 = get_node_ptr(deref_link(q->refcnt, &next->prev)); prev = prev2; store_ref(q->refcnt, &entry->prev, ATOMIC_READ(prev->node)); } release_ref(q->refcnt, ATOMIC_READ(prev->node)); retain_ref(q->refcnt, ATOMIC_READ(entry->node)); release_ref(q->refcnt, ATOMIC_READ(prev->node)); break; } if (prev) release_ref(q->refcnt, ATOMIC_READ(prev->node)); store_ref(q->refcnt, &entry->next, NULL); store_ref(q->refcnt, &entry->prev, NULL); } ATOMIC_INCREMENT(q->length); return 0; } /* * Retreive a queue_entry_t from the beginning of a queue (or top of the stack * if you are using the queue as a stack) */ void * queue_pop_left(queue_t *q) { void *v = NULL; queue_entry_t *entry = NULL; queue_entry_t *prev = ATOMIC_READ(q->head); if (!prev) return NULL; while(1) { refcnt_node_t *entry_node = deref_link(q->refcnt, &prev->next); entry = get_node_ptr(entry_node); if (!entry || entry == ATOMIC_READ(q->tail)) { if (entry_node) release_ref(q->refcnt, entry_node); return NULL; } if (ATOMIC_READ(entry->prev) != ATOMIC_READ(prev->node)) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); continue; } refcnt_node_t *link1 = ATOMIC_READ(entry->next); if (!REFCNT_MARK_OFF(link1)) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); continue; } if (ATOMIC_CAS(entry->next, REFCNT_MARK_OFF(link1), REFCNT_MARK_ON(link1))) { refcnt_node_t *link2; do { link2 = ATOMIC_READ(entry->prev); } while (!link2 || !ATOMIC_CAS(entry->prev, link2, REFCNT_MARK_ON(link2))); queue_entry_t *next = NULL; do { if (next) release_ref(q->refcnt, ATOMIC_READ(next->node)); next = get_node_ptr(deref_link_d(q->refcnt, &entry->next)); } while(!next || !ATOMIC_CAS(next->prev, ATOMIC_READ(entry->node), ATOMIC_READ(prev->node))); release_ref(q->refcnt, ATOMIC_READ(entry->node)); retain_ref(q->refcnt, ATOMIC_READ(prev->node)); if (ATOMIC_CAS(prev->next, ATOMIC_READ(entry->node), ATOMIC_READ(next->node))) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); retain_ref(q->refcnt, ATOMIC_READ(next->node)); } release_ref(q->refcnt, ATOMIC_READ(next->node)); v = entry->value; release_ref(q->refcnt, ATOMIC_READ(entry->node)); break; } release_ref(q->refcnt, ATOMIC_READ(entry->node)); } if (entry) { ATOMIC_DECREMENT(q->length); store_ref(q->refcnt, &entry->next, NULL); store_ref(q->refcnt, &entry->prev, NULL); sched_yield(); destroy_entry(q->refcnt, entry); } return v; } /* * Pops a queue_entry_t from the end of the queue (or bottom of the stack * if you are using the queue as a stack) */ void * queue_pop_right(queue_t *q) { void *v = NULL; queue_entry_t *entry = NULL; queue_entry_t *next = ATOMIC_READ(q->tail); if (!next) return NULL; while(1) { refcnt_node_t *entry_node = deref_link(q->refcnt, &next->prev); entry = get_node_ptr(entry_node); if (!entry || entry == ATOMIC_READ(q->head)) { if (entry_node) release_ref(q->refcnt, entry_node); return NULL; } if (ATOMIC_READ(entry->next) != ATOMIC_READ(next->node)) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); continue; } refcnt_node_t *link1 = ATOMIC_READ(entry->prev); if (!REFCNT_MARK_OFF(link1)) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); continue; } if (ATOMIC_CAS(entry->prev, REFCNT_MARK_OFF(link1), REFCNT_MARK_ON(link1))) { refcnt_node_t *link2; do { link2 = ATOMIC_READ(entry->next); } while (!ATOMIC_CAS(entry->next, link2, REFCNT_MARK_ON(link2))); queue_entry_t *prev = NULL; do { if (prev) release_ref(q->refcnt, ATOMIC_READ(prev->node)); prev = get_node_ptr(deref_link_d(q->refcnt, &entry->prev)); } while(!prev || !ATOMIC_CAS(prev->next, ATOMIC_READ(entry->node), ATOMIC_READ(next->node))); release_ref(q->refcnt, ATOMIC_READ(entry->node)); retain_ref(q->refcnt, ATOMIC_READ(next->node)); if (ATOMIC_CAS(next->prev, ATOMIC_READ(entry->node), ATOMIC_READ(prev->node))) { release_ref(q->refcnt, ATOMIC_READ(entry->node)); retain_ref(q->refcnt, ATOMIC_READ(prev->node)); } release_ref(q->refcnt, ATOMIC_READ(prev->node)); v = entry->value; release_ref(q->refcnt, ATOMIC_READ(entry->node)); break; } release_ref(q->refcnt, ATOMIC_READ(entry->node)); } if (entry) { ATOMIC_DECREMENT(q->length); store_ref(q->refcnt, &entry->next, NULL); store_ref(q->refcnt, &entry->prev, NULL); sched_yield(); destroy_entry(q->refcnt, entry); } return v; } // vim: tabstop=4 shiftwidth=4 expandtab: /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
lgpl-3.0
UbiCastTeam/candies
candies2/clock.py
3642
#!/usr/bin/env python # -*- coding: utf-8 -* import clutter from clutter import cogl import math class Clock(clutter.Actor): __gtype_name__ = 'Clock' """ A clock widget """ def __init__(self, date=None, texture=None): clutter.Actor.__init__(self) self._date = date self._texture = texture self._color = clutter.color_from_string('Black') def set_color(self, color): self._color = clutter.color_from_string(color) self.queue_redraw() def set_texture(self, texture): self._texture = texture self.queue_redraw() def set_date(self, date=None): self._date = date if date is not None: self.queue_redraw() def do_paint(self): #clutter.Texture.do_paint(self) (x1, y1, x2, y2) = self.get_allocation_box() width = x2 - x1 height = y2 - y1 hw = width / 2 hh = height / 2 center_x = hw center_y = hh # texture if self._texture is not None: cogl.path_rectangle(0, 0, width, height) cogl.path_close() cogl.set_source_texture(self._texture) cogl.path_fill() # clock hands if self._date is not None: hour = self._date.hour minute = self._date.minute # hour angle = (60 * hour + minute) / 2 + 270 left = angle - 14 right = angle + 14 angle = angle * (math.pi / 180) left = left * (math.pi / 180) right = right * (math.pi / 180) cogl.path_move_to(center_x, center_y) cogl.path_line_to(center_x + (hw/4) * math.cos(left), center_y + (hh/4) * math.sin(left)) cogl.path_line_to(center_x + (2*hw/3) * math.cos(angle), center_y + (2*hh/3) * math.sin(angle)) cogl.path_line_to(center_x + (hw/4) * math.cos(right), center_y + (hh/4) * math.sin(right)) cogl.path_line_to(center_x, center_y) cogl.path_close() cogl.set_source_color(self._color) cogl.path_fill() # minute angle = 6 * minute + 270 left = angle - 10 right = angle + 10 angle = angle * (math.pi / 180) left = left * (math.pi / 180) right = right * (math.pi / 180) cogl.path_move_to(center_x, center_y) cogl.path_line_to(center_x + (hw/3) * math.cos(left), center_y + (hh/3) * math.sin(left)) cogl.path_line_to(center_x + hw * math.cos(angle), center_y + hh * math.sin(angle)) cogl.path_line_to(center_x + (hw/3) * math.cos(right), center_y + (hh/3) * math.sin(right)) cogl.path_line_to(center_x, center_y) cogl.path_close() cogl.set_source_color(self._color) cogl.path_fill() #main to test if __name__ == '__main__': stage = clutter.Stage() stage.connect('destroy',clutter.main_quit) import gobject, datetime t = cogl.texture_new_from_file('clock.png', clutter.cogl.TEXTURE_NO_SLICING, clutter.cogl.PIXEL_FORMAT_ANY) c = Clock() c.set_texture(t) c.set_size(400, 400) c.set_position(50, 50) stage.add(c) def update(): today = datetime.datetime.today() #self.actor.set_text(today.strftime('%H:%M\n%d / %m')) c.set_date(today) return True gobject.timeout_add_seconds(60, update) stage.show() clutter.main()
lgpl-3.0
imasahiro/konohascript
package/konoha.qt4/include/KQAccessibleBridge.hpp
810
#ifndef QACCESSIBLEBRIDGE #define QACCESSIBLEBRIDGE class DummyQAccessibleBridge { // Q_OBJECT; public: knh_RawPtr_t *self; std::map<std::string, knh_Func_t *> *event_map; std::map<std::string, knh_Func_t *> *slot_map; DummyQAccessibleBridge(); virtual ~DummyQAccessibleBridge(); void setSelf(knh_RawPtr_t *ptr); bool eventDispatcher(QEvent *event); bool addEvent(knh_Func_t *callback_func, std::string str); bool signalConnect(knh_Func_t *callback_func, std::string str); knh_Object_t** reftrace(CTX ctx, knh_RawPtr_t *p FTRARG); void connection(QObject *o); }; class KQAccessibleBridge : public QAccessibleBridge { // Q_OBJECT; public: int magic_num; knh_RawPtr_t *self; DummyQAccessibleBridge *dummy; ~KQAccessibleBridge(); void setSelf(knh_RawPtr_t *ptr); }; #endif //QACCESSIBLEBRIDGE
lgpl-3.0
onebeartoe/java-libraries
system/src/main/java/org/onebeartoe/filesystem/FileSystemSearcher.java
4892
package org.onebeartoe.filesystem; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * @author Roberto Marquez */ public class FileSystemSearcher { File dir; List<FileType> targets; FileType type; boolean recursive; public FileSystemSearcher(File dir, List<FileType> targets) { this(dir, targets, false); } public FileSystemSearcher(File dir, List<FileType> targets, boolean recursive) { if (dir == null) { throw new NullPointerException("search directory can't have a null value"); } if (targets == null) { throw new NullPointerException("target list can't have a null value"); } this.dir = dir; this.targets = targets; this.recursive = recursive; } public List<File> findTargetDirectories() { ArrayList<File> targetDirs = new ArrayList<File>(); Vector<File> directories = new Vector<File>(); directories.add(dir); while (!directories.isEmpty()) { File currentDir = directories.remove(0); boolean currentContainsTargets = findTargetDirectoriesOneLevel(currentDir, directories); if (currentContainsTargets) { targetDirs.add(currentDir); } } return targetDirs; } private boolean findTargetDirectoriesOneLevel(File currentDir, Vector<File> directories) { boolean currentContainsTargets = false; File[] dirContents = currentDir.listFiles(); if (dirContents != null) { currentContainsTargets = findTargetDirectoriesOneLevelExecute(dirContents, directories); } return currentContainsTargets; } private boolean findTargetDirectoriesOneLevelExecute(File[] dirContents, Vector<File> directories) { boolean currentContainsTargets = false; boolean targetNotFoundYet = true; for (File file : dirContents) { if (file.isDirectory() && recursive) { directories.add(file); } else { if (targetNotFoundYet) { // Only come here if a target has not been found. FileType type = determinFileType(file); if (targets.contains(type)) { currentContainsTargets = true; // If a target has been found in the current dir, we can skip the next file check targetNotFoundYet = false; } } } } return currentContainsTargets; } public List<File> findTargetFiles() { List<File> targetFiles = new ArrayList<File>(); Vector<File> directories = new Vector<File>(); directories.add(dir); while (!directories.isEmpty()) { findTargetFilesOneLevel(directories, targetFiles); } return targetFiles; } private void findTargetFilesOneLevel(Vector<File> directories, List<File> targetFiles) { File currentDir = directories.remove(0); File[] dirContents = currentDir.listFiles(); if (dirContents != null) { for (File file : dirContents) { if (file.isDirectory() && recursive) { directories.add(file); } else { FileType type = determinFileType(file); if (targets.contains(type)) { targetFiles.add(file); } } } } } private FileType determinFileType(File file) { FileType type = FileType.UNKNOWN; String name = file.getName(); if (FileHelper.isAudioFile(name)) { type = FileType.AUDIO; } if (FileHelper.isZipFormatFile(name)) { type = FileType.ZIP; } if (FileHelper.isMultimediaFile(name)) { type = FileType.MULTIMEDIA; } if (FileHelper.isImageFile(name)) { type = FileType.IMAGE; } if (FileHelper.isTextFile(name)) { type = FileType.TEXT; } return type; } }
lgpl-3.0
k0zmo/live555
liveMedia/include/H265VideoStreamFramer.hh
1732
/********** 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 3 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2021 Live Networks, Inc. All rights reserved. // A filter that breaks up a H.265 Video Elementary Stream into NAL units. // C++ header #ifndef _H265_VIDEO_STREAM_FRAMER_HH #define _H265_VIDEO_STREAM_FRAMER_HH #ifndef _H264_OR_5_VIDEO_STREAM_FRAMER_HH #include "H264or5VideoStreamFramer.hh" #endif class H265VideoStreamFramer: public H264or5VideoStreamFramer { public: static H265VideoStreamFramer* createNew(UsageEnvironment& env, FramedSource* inputSource, Boolean includeStartCodeInOutput = False, Boolean insertAccessUnitDelimiters = False); protected: H265VideoStreamFramer(UsageEnvironment& env, FramedSource* inputSource, Boolean createParser, Boolean includeStartCodeInOutput, Boolean insertAccessUnitDelimiters); // called only by "createNew()" virtual ~H265VideoStreamFramer(); // redefined virtual functions: virtual Boolean isH265VideoStreamFramer() const; }; #endif
lgpl-3.0
SonarSource/sonarqube
server/sonar-process/src/test/java/org/sonar/process/PluginFileWriteRuleTest.java
2479
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process; import java.io.FilePermission; import java.nio.file.Path; import java.nio.file.Paths; import java.util.PropertyPermission; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PluginFileWriteRuleTest { private final Path home = Paths.get("/path/to/home"); private final Path tmp = Paths.get("/path/to/home/tmp"); private final PluginFileWriteRule rule = new PluginFileWriteRule(home, tmp); @Test public void policy_restricts_modifying_home() { assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "write"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "execute"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "delete"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "read"))).isTrue(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "readlink"))).isTrue(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/extensions/file").toAbsolutePath().toString(), "write"))).isFalse(); assertThat(rule.implies(new FilePermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue(); } @Test public void policy_implies_other_permissions() { assertThat(rule.implies(new PropertyPermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue(); } }
lgpl-3.0
B3Partners/gisviewerConfig
src/main/webapp/scripts/commonfunctions.js
24486
/* Copyright 2007-2011 B3Partners BV. This program is distributed under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License along with this software. If not, see http://www.gnu.org/licenses/gpl.html This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /*Hulp functions*/ //contains on array function function arrayContains(array,element) { for (var i = 0; i < array.length; i++) { if (array[i] == element) { return true; } } return false; } // jQuery gives problems with DWR - util.js, so noConflict mode. Usage for jQuery selecter becomes $j() instead of $() $j = jQuery.noConflict(); // Trim polyfill if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } attachOnload = function(onloadfunction) { if(typeof(onloadfunction) == 'function') { var oldonload=window.onload; if(typeof(oldonload) == 'function') { window.onload = function() { oldonload(); onloadfunction(); } } else { window.onload = function() { onloadfunction(); } } } } var resizeFunctions = new Array(); resizeFunction = function() { for(i in resizeFunctions) { resizeFunctions[i](); } } window.onresize = resizeFunction; attachOnresize = function(onresizefunction) { if(typeof(onresizefunction) == 'function') { resizeFunctions[resizeFunctions.length] = onresizefunction; } } checkLocation = function() { if (top.location != self.location) top.location = self.location; } checkLocationPopup = function() { if(!usePopup) { if (top.location == self.location) { top.location = '/gisviewerconfig/index.do'; } } } getIEVersionNumber = function() { var ua = navigator.userAgent; var MSIEOffset = ua.indexOf("MSIE "); if (MSIEOffset == -1) { return -1; } else { return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset))); } } var ieVersion = getIEVersionNumber(); function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; } function showHelpDialog(divid) { $j("#" + divid).dialog({ resizable: true, draggable: true, show: 'slide', hide: 'slide', autoOpen: false }); $j("#" + divid).dialog('open'); return false; } (function(B3PConfig) { B3PConfig.cookie = { createCookie: function(name,value,days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }, readCookie: function(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length); } return null; }, eraseCookie: function(name) { this.createCookie(name,"",-1); } }; })(window.B3PConfig || (window.B3PConfig = {})); (function(B3PConfig, $) { B3PConfig.advancedToggle = { config: { advancedclass: '.configadvanced', advancedtoggle: '#advancedToggle', cookiename: 'advancedtoggle' }, advancedToggle: null, advancedItems: [], init: function() { var me = this, useAdvancedToggle = false; me.advancedToggle = $(me.config.advancedtoggle); me.advancedItems = $(me.config.advancedclass); me.advancedItems.each(function() { if($(this).html().trim() !== '') useAdvancedToggle = true; }); if(B3PConfig.cookie.readCookie(me.getCookiename()) !== null) { me.advancedToggle[0].checked = B3PConfig.cookie.readCookie(me.getCookiename()) === 'on'; } if(useAdvancedToggle) { me.advancedToggle.click(function(){ me.showHideAdvanced(); }); me.showHideAdvanced(); } else { me.advancedToggle.parent().hide(); } }, showHideAdvanced: function () { var showAdvancedOptions = this.advancedToggle.is(':checked'); B3PConfig.cookie.createCookie(this.getCookiename(), showAdvancedOptions ? 'on' : 'off', 7); showAdvancedOptions ? this.advancedItems.show() : this.advancedItems.hide(); }, getCookiename: function() { return this.config.cookiename + (this.advancedToggle.data('cookie-key') ? '-' + this.advancedToggle.data('cookie-key') : ''); } }; })(window.B3PConfig || (window.B3PConfig = {}), jQuery); var prevTab = null; var fbLbl; function labelClick($lbl) { if(prevTab != null) prevTab.hide(); prevTab = $j(".content_"+$lbl.attr("id").replace("label_", "")); prevTab.show(); $j(".tablabel").removeClass("active"); $lbl.addClass("active"); } var showAdvancedOptions = false; var contentMinHeight = 300; $j(document).ready(function() { contentMinHeight = $j(".tablabels").outerHeight(true)+20; if($j("#treedivContainer").length > 0) contentMinHeight = $j("#treedivContainer").outerHeight(true)+20; $j(".tabcontent").each(function (){ var counter = 0; $j(this).find(".configrow").each(function() { var $this = $j(this); if(counter%2==1) $this.addClass("odd"); counter++; $this.find(".helpLink").each(function (){ if($j(this).attr("id") && $j(this).attr("id") != 'undefined') { var $helpContentDiv = $j("#" + $j(this).attr("id").replace("helpLink_", "")); var helpContent = $helpContentDiv.html(); var helpTitle = $helpContentDiv.attr("title"); $j(this).qtip({ content: { text: helpContent, title: helpTitle }, hide: { event: 'mouseout' }, show: { event: 'click mouseenter' }, position: { my: 'right top', at: 'left middle', target: $j(this), viewport: $j(window), adjust: { x: -10 } } }); } }); }); if(!$j(this).hasClass("defaulttab")) $j(this).hide(); }); $j(".tablabel").each(function() { $j(this).click(function() { labelClick($j(this)); }); }); B3PConfig.advancedToggle.init(); $j(".tabcontent").css("min-height", contentMinHeight); if($j(".tablabel").length != 0) labelClick($j(".tablabel").first()); // Datatables var tables = []; jQuery('.dataTable').each(function() { tables.push(new B3PDataTable(this)); }); jQuery('.postCheckboxTable').click(function() { for(var x in tables) { tables[x].showAllRows(); } }); }); /** * B3P wrapper for the jQuery DataTables plugin * @requires jQuery * @requires jQuery.dataTables * @param {HTMLElement} table * @returns {B3PDataTable} */ function B3PDataTable(table) { /** * Setting to preserve table height even when there are less items * @type boolean */ this.preserveHeight = true; /** * The jQuery object of the table * @type jQuery */ this.table = jQuery(table); /** * Container for the creation of the DataTable object * @type DataTable */ this.dataTableObj = null; /** * Container for the column settings * @type Array */ this.columnSettings = []; /** * Widths for each column * @type Array */ this.columnWidths = []; /** * Header row to hold the filters * @type jQuery */ this.filters = jQuery('<tr class="filter"></tr>'); /** * The selected row object * @type jQuery */ this.selectedRow = this.table.find('.row_selected'); /** * Container for the DataTable settings * @type Object */ this.tableSettings = null; /** * Initializes a B3PDataTable object to create a sortable, filterable DataTable * @returns {Boolean} */ this.init = function() { // We compute the column widths as soon as possible this.columnWidths = this.getColumnWidths(); var filterCount = this.initHeaders(); if(this.preserveHeight) var tableHeight = this.calculatePageHeight(filterCount); var tableSettings = this.initDataTable(); // If there is no saved state (first time view) go to selected row if(tableSettings.oLoadedState === null) { this.showSelectedRow(); } this.appendSelectedRowButton(); if(filterCount !== 0) { this.appendFilters(); } this.initRowClick(); if(this.preserveHeight) this.setWrapperHeight(tableHeight); this.showTable(); return true; }; /** * Calculate the height of the table header and first 10 rows (first page) * @param {int} number of filters * @returns {int} */ this.calculatePageHeight = function(filterCount) { // Border margin of table var borderMargin = 2; // Calc header height var headerHeight = this.table.find('thead').outerHeight(true) + borderMargin; // If there are filters, multiply headerheight by 2 if(filterCount !== 0) headerHeight = headerHeight * 2; // Calc content height var contentHeight = 0; // Use first 10 rows var count = 1; this.table.find('tbody').children().slice(0, 10).each(function() { contentHeight += jQuery(this).outerHeight(true) + borderMargin; }); var tableHeight = headerHeight + contentHeight + 16; // margin; return tableHeight; }; /** * Sets the minimum height of the wrapper, causing the table to preserve height * @param {int} tableHeight * @returns {Boolean} */ this.setWrapperHeight = function(tableHeight) { var wrapper = this.table.parent(); // Calculate height of search box and pagination var childHeight = 0; wrapper.find('.dataTables_filter, .dataTables_paginate').each(function() { childHeight += jQuery(this).outerHeight(true); }); // Move info and pagination to the bottom jQuery('.dataTables_info, .dataTables_paginate').each(function() { var obj = jQuery(this); obj.css({ 'position': 'absolute', 'bottom': '0px' }); if(obj.hasClass('dataTables_paginate')) obj.css('right', '15px'); }); // Set wrapper min-height wrapper.css({ 'min-height': (childHeight + tableHeight - 19 + 'px') // Subtract 19 pixels for wrapper margin }); return true; }; /** * Initializes the headers: create column settings and append a filter. * Returns the amount of filters created. * @returns {int} */ this.initHeaders = function() { var me = this, filterCount = 0; this.table.find('thead tr').first().find('th').each(function(index) { me.columnSettings.push(me.getColumnSettings(this)); var hasFilter = me.createFilter(this, index); if(hasFilter) filterCount++; }); return filterCount; }; /** * Creates a DataTables column settings object based on some options * @param {type} the table header object * @returns {Object} */ this.getColumnSettings = function(column) { var colSetting = {}; var sortType = "string"; if(column.className.match(/sorter\:[ ]?[']?digit[']?/)) { sortType = "numeric"; } if(column.className.match(/sorter\:[ ]?[']?dutchdates[']?/)) { sortType = "dutchdates"; } if(column.className.match(/sorter\:[ ]?[']?false[']?/)) { colSetting.bSortable = false; } colSetting.sType = sortType; colSetting.mRender = function(content, type) { if(type === 'filter') { // Remove all HTML tags from content to improve filtering return content.replace(/<\/?[^>]+>/g, '').trim(); } return content; }; return colSetting; }; /** * Compute the default width of all columns in the table * @returns {Object} */ this.getColumnWidths = function() { var i = 0, me = this, columnWidths = []; // Wrap all td's in the body in a .tablespan class (taking care of text-overflow and set width to 1px) // So we can use the percentages set for the columns as widths this.table.find('tbody td').wrapInner(jQuery('<span class="tablespan" style="width: 1px;"></span>')); // Set the table to the maximum width (wrapper - 30px padding) this.table.css('width', this.table.parent().width() - 30); // Loop over first row and add width of each td to array this.table.find('tbody tr:first-child td').each(function() { columnWidths[i++] = jQuery(this).width(); }); // Reset width of table this.table.css('width', 'auto'); // Return array with column widths return columnWidths; }; /** * Sets width on each column to prevent large texts from pushing table off screen * @returns {Boolean} */ this.setTablecellWidth = function() { var me = this; // Loop over all rows this.table.find('tbody tr').each(function() { // Set index var var i = 0; // Loop over all cells jQuery(this).find('td').each(function() { var td = jQuery(this); // Add tablespan container when td is empty so widths are consistant if(td.is(':empty')) { td.append('<span class="tablespan"></span>'); } // Set the max width td.find('.tablespan').css('width', me.columnWidths[i++]); }); }); return true; }; /** * Creates a filter box for a column. Returns true if a filter is created * @param {type} the table header object * @param {type} the column index * @returns {Boolean} */ this.createFilter = function(column, index) { var me = this, col = jQuery(column); if(col.hasClass('no-filter')) { // Column has no-filter class, so create empty header this.filters.append('<th>&nbsp;</th>'); return false; } else { var filter = jQuery('<input type="text" name="filter" title="' + col.text() + '" value="" />').keyup(function(e) { me.filterColumn(this.value, index); }); var header = jQuery('<th></th>').append(filter); this.filters.append(header); } return true; }; /** * Initializes the DataTables plugin and returns the creation settings * @returns {Object} */ this.initDataTable = function() { var me = this; this.dataTableObj = this.table.dataTable({ "iDisplayLength": 10, "bSortClasses": false, "aoColumns": this.columnSettings, "aaSorting": [], "bStateSave": true, "sPaginationType": "full_numbers", "oLanguage": { "sLengthMenu": "_MENU_ items per pagina", "sSearch": "Zoeken:", "oPaginate": { "sFirst": "Begin", "sNext": "Volgende", "sPrevious": "Vorige", "sLast": "Einde" }, "sInfo": "Items _START_ tot _END_ van _TOTAL_ getoond", "sInfoEmpty": "Geen items gevonden", "sInfoFiltered": " - gefilterd (in totaal _MAX_ items)", "sEmptyTable": "Geen items gevonden", "sZeroRecords": "Geen items gevonden" }, "fnDrawCallback": function() { me.setTablecellWidth(); } }); this.tableSettings = this.dataTableObj.fnSettings(); return this.tableSettings; }; /** * Append the button to go to the selected row to the paginiation * @returns {Boolean} */ this.appendSelectedRowButton = function() { var me = this; me.table.parent().find('.dataTables_paginate').append(jQuery('<a>Geselecteerd</a>').addClass('paginate_button').click(function(e){ e.preventDefault(); me.showSelectedRow(); })); return true; }; /** * Append the filter boxes to the table header * @returns {Boolean} */ this.appendFilters = function() { var me = this; // Get saved searches to repopulate field with search value me.filters.find('th').each(function(index) { var searchCol = me.tableSettings.aoPreSearchCols[index]; if(searchCol.hasOwnProperty('sSearch') && searchCol.sSearch.length !== 0) { jQuery('input', this).val(searchCol.sSearch); } }); // Add filters to table me.table.find('thead').append(me.filters); return true; }; /** * Attach handlers for clicking a row in the table * @returns {Boolean} */ this.initRowClick = function() { this.table.find('tbody').delegate("td", "click", function() { var row = jQuery(this); // Check if there is a link or input (button, checkbox, etc.) present if(row.find('a, input').length === 0) { // No link or input so navigate to the attached URL var link = row.parent().attr('data-link'); if(link) window.location.href = link; } }); return true; }; /** * Search a single column for a string * @param {String} the string to search on * @param {int} the index of the columns that needs to be filtered * @returns {Boolean} */ this.filterColumn = function(filter, colindex) { if(this.dataTableObj === null) return; this.dataTableObj.fnFilter( filter, colindex ); return true; }; /** * Shows the currently selected row * @returns {Boolean} */ this.showSelectedRow = function() { if(this.dataTableObj === null) return false; this.dataTableObj.fnDisplayRow( this.selectedRow[0] ); return true; }; /** * Makes the table visible (table is hidden using CSS and positioning to prevent flicker) * @returns {Boolean} */ this.showTable = function() { this.table.css({ 'position': 'static', 'left': '0px' }); return true; }; /** * Function to show all rows (remove pagination). * This is mainly used to post all input fields in a tables * @returns {Boolean} */ this.showAllRows = function() { var wrapper = this.table.parent(), wrapperHeight = wrapper.height(); wrapper.css({ 'height': wrapperHeight + 'px', 'overflow': 'hidden' }); this.table.css({ 'position': 'absolute', 'left': '-99999px' }); jQuery('<div>Bezig met opslaan...</div>') .css({ 'clear': 'both', 'margin-top': '15px;' }) .insertAfter(jQuery('.dataTables_filter', wrapper)); jQuery('tbody', this.table).append( this.dataTableObj.fnGetHiddenNodes() ); }; /** * Install dataTable extensions, needed for some functionality */ (function() { if(typeof jQuery.fn.dataTableExt.oSort['dutchdates-asc'] === "undefined") { /** * Extension to support sorting of dutch formatted dates (dd-mm-yyyy) */ jQuery.fn.dataTableExt.oSort['dutchdates-asc'] = function(a,b) { var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b)); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['dutchdates-desc'] = function(a,b) { var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b)); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; var parseDutchDate = function(obj) { var s = obj.text(); var hit = s.match(/(\d{2})-(\d{2})-(\d{4})/); if (hit && hit.length === 4) return new Date(hit[3], hit[2], hit[1]); return new Date(s); }; } if(typeof jQuery.fn.dataTableExt.oApi.fnDisplayRow === "undefined") { /** * Extension to go to the page containing a specific row * We use this extension to go to the selected row */ jQuery.fn.dataTableExt.oApi.fnDisplayRow = function ( oSettings, nRow ) { // Account for the "display" all case - row is already displayed if ( oSettings._iDisplayLength === -1 ) return; // Find the node in the table var iPos = -1, iLen=oSettings.aiDisplay.length; for( var i=0; i < iLen; i++ ) { if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr === nRow ) { iPos = i; break; } } // Alter the start point of the paging display if( iPos >= 0 ) { oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength; this.oApi._fnCalculateEnd( oSettings ); } this.oApi._fnDraw( oSettings ); }; } if(typeof jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes === "undefined") { jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes = function ( oSettings ) { /* Note the use of a DataTables 'private' function thought the 'oApi' object */ var anNodes = this.oApi._fnGetTrNodes( oSettings ); var anDisplay = jQuery('tbody tr', oSettings.nTable); /* Remove nodes which are being displayed */ for ( var i=0 ; i<anDisplay.length ; i++ ) { var iIndex = jQuery.inArray( anDisplay[i], anNodes ); if ( iIndex != -1 ) { anNodes.splice( iIndex, 1 ); } } /* Fire back the array to the caller */ return anNodes; }; } })(); /** * Execute initialize function */ this.init(); }
lgpl-3.0
kidaa/Awakening-Core3
doc/html/functions_rela_0x69.html
7916
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: Class Members - Related Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> <li><a href="functions_eval.html"><span>Enumerator</span></a></li> <li class="current"><a href="functions_rela.html"><span>Related&#160;Functions</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions_rela.html#index_a"><span>a</span></a></li> <li><a href="functions_rela_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_rela_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_rela_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_rela_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_rela_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_rela_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_rela_0x68.html#index_h"><span>h</span></a></li> <li class="current"><a href="functions_rela_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_rela_0x6a.html#index_j"><span>j</span></a></li> <li><a href="functions_rela_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_rela_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_rela_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_rela_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_rela_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_rela_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_rela_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_rela_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_rela_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_rela_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_rela_0x7a.html#index_z"><span>z</span></a></li> </ul> </div> </div><!-- top --> <div class="contents"> &#160; <h3><a class="anchor" id="index_i"></a>- i -</h3><ul> <li>ImageDesignPositionObserver : <a class="el" href="classserver_1_1zone_1_1objects_1_1player_1_1sessions_1_1_image_design_position_observer_implementation.html#ad867e9b529106bce5e7c1cd81023532d">server::zone::objects::player::sessions::ImageDesignPositionObserverImplementation</a> </li> <li>ImageDesignPositionObserverHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1player_1_1sessions_1_1_image_design_position_observer.html#aba46c5ad153cb501f2a905ed486bc630">server::zone::objects::player::sessions::ImageDesignPositionObserver</a> </li> <li>ImageDesignSession : <a class="el" href="classserver_1_1zone_1_1objects_1_1player_1_1sessions_1_1_image_design_session_implementation.html#afefc38519201ec3234ea4419797a744e">server::zone::objects::player::sessions::ImageDesignSessionImplementation</a> </li> <li>ImageDesignSessionHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1player_1_1sessions_1_1_image_design_session.html#ad206a6c4f404757737a6634ddbbc4840">server::zone::objects::player::sessions::ImageDesignSession</a> </li> <li>InformantMissionConversationObserver : <a class="el" href="classserver_1_1zone_1_1objects_1_1creature_1_1conversation_1_1_informant_mission_conversation_observer_implementation.html#ab9f70b30981ce3df2f3b97949193dc35">server::zone::objects::creature::conversation::InformantMissionConversationObserverImplementation</a> </li> <li>InformantMissionConversationObserverHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1creature_1_1conversation_1_1_informant_mission_conversation_observer.html#a698fabfaed9bd5d2cf1b35891be341ed">server::zone::objects::creature::conversation::InformantMissionConversationObserver</a> </li> <li>InstallationObject : <a class="el" href="classserver_1_1zone_1_1objects_1_1installation_1_1_installation_object_implementation.html#ac8af135b61ccdaaf4dcbe0501b9078d0">server::zone::objects::installation::InstallationObjectImplementation</a> </li> <li>InstallationObjectHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1installation_1_1_installation_object.html#a13a06ada221c19555bebf432727f1a30">server::zone::objects::installation::InstallationObject</a> </li> <li>Instrument : <a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1_instrument_implementation.html#a2ff0e65835bfc4a6510c2a5e3c1fe8fb">server::zone::objects::tangible::InstrumentImplementation</a> </li> <li>InstrumentHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1_instrument.html#a7edd4829c91bd4587aef0dd87ae96493">server::zone::objects::tangible::Instrument</a> </li> <li>InstrumentObserver : <a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1_instrument_observer_implementation.html#aa45a920f2be21d3a377db37b86c92e56">server::zone::objects::tangible::InstrumentObserverImplementation</a> </li> <li>InstrumentObserverHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1_instrument_observer.html#adbe20533c3c9450745041a9c9e4f8649">server::zone::objects::tangible::InstrumentObserver</a> </li> <li>IntangibleObject : <a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_intangible_object_implementation.html#a5bcb27628f070e4b9f77d3b6150d7f0d">server::zone::objects::intangible::IntangibleObjectImplementation</a> </li> <li>IntangibleObjectHelper : <a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_intangible_object.html#a885dafb3450d058a3e012ad9eee9060d">server::zone::objects::intangible::IntangibleObject</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:30:15 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
lgpl-3.0
claudejin/evosuite
client/src/main/java/org/evosuite/graphs/ccfg/CCFGFrameEdge.java
1011
/** * Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.graphs.ccfg; public class CCFGFrameEdge extends CCFGEdge { private static final long serialVersionUID = 8223049010545407697L; /** {@inheritDoc} */ @Override public String toString() { return ""; } }
lgpl-3.0
taniwha/AdvancedInput
Source/ButtonBindings/TranslateBack.cs
1131
/* This file is part of Advanced Input. Advanced Input 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. Advanced Input 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 Advanced Input. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace AdvancedInput.ButtonBindings { public class AI_BB_TranslateBack: IButtonBinding { public string name { get { return "TranslateBack"; } } public ControlTypes lockMask { get { return ControlTypes.LINEAR; } } public bool locked { get; set; } public void Update (int state, bool edge) { if (state > 0) { FlightInputHandler.state.Z = 1; } } public AI_BB_TranslateBack (ConfigNode node) { } } }
lgpl-3.0
courros/hnco
examples/onemax.c
950
/* Copyright (C) 2016, 2017, 2018, 2019, 2020, 2021, 2022 Arnaud Berny This file is part of HNCO. HNCO 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. HNCO 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 HNCO. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> /* size_t */ double onemax(const char *data, size_t len) { int result = 0; size_t i; for (i = 0; i < len; i++) if (data[i]) result++; return result; }
lgpl-3.0
kidaa/Awakening-Core3
doc/html/classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html
24615
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: server::zone::objects::intangible::LuaControlDevice Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceserver.html">server</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone.html">zone</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone_1_1objects.html">objects</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone_1_1objects_1_1intangible.html">intangible</a></li><li class="navelem"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html">LuaControlDevice</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pub-attribs">Public Attributes</a> &#124; <a href="#pub-static-attribs">Static Public Attributes</a> &#124; <a href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">server::zone::objects::intangible::LuaControlDevice Class Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="_control_device_8h_source.html">ControlDevice.h</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:aab61d2411f764610729b67b5a7375d07"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#aab61d2411f764610729b67b5a7375d07">LuaControlDevice</a> (lua_State *L)</td></tr> <tr class="separator:aab61d2411f764610729b67b5a7375d07"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a85b4d2032938d3f71463416bc6cedce4"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a85b4d2032938d3f71463416bc6cedce4">~LuaControlDevice</a> ()</td></tr> <tr class="separator:a85b4d2032938d3f71463416bc6cedce4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae2ccafbe9975032956fda8f5ed39ab50"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#ae2ccafbe9975032956fda8f5ed39ab50">_setObject</a> (lua_State *L)</td></tr> <tr class="separator:ae2ccafbe9975032956fda8f5ed39ab50"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a075594f720ce7c9acdbc8557242c618a"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a075594f720ce7c9acdbc8557242c618a">_getObject</a> (lua_State *L)</td></tr> <tr class="separator:a075594f720ce7c9acdbc8557242c618a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a736b40a35d6b7f7d25c20ae67cc7fc79"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a736b40a35d6b7f7d25c20ae67cc7fc79">updateToDatabaseAllObjects</a> (lua_State *L)</td></tr> <tr class="separator:a736b40a35d6b7f7d25c20ae67cc7fc79"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4b72579d4781a7bb9f631e861072f138"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a4b72579d4781a7bb9f631e861072f138">storeObject</a> (lua_State *L)</td></tr> <tr class="separator:a4b72579d4781a7bb9f631e861072f138"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad455976aeb48ca36d2af0e0a0708aace"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#ad455976aeb48ca36d2af0e0a0708aace">generateObject</a> (lua_State *L)</td></tr> <tr class="separator:ad455976aeb48ca36d2af0e0a0708aace"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a42d82f2b479f22698969d0eedcd77eed"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a42d82f2b479f22698969d0eedcd77eed">callObject</a> (lua_State *L)</td></tr> <tr class="separator:a42d82f2b479f22698969d0eedcd77eed"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af58220ef8db3170822408d20e61da3d9"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#af58220ef8db3170822408d20e61da3d9">setControlledObject</a> (lua_State *L)</td></tr> <tr class="separator:af58220ef8db3170822408d20e61da3d9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3d9b1b61839ac076e9633bc85776d812"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a3d9b1b61839ac076e9633bc85776d812">getControlledObject</a> (lua_State *L)</td></tr> <tr class="separator:a3d9b1b61839ac076e9633bc85776d812"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3efb386471803c082aff3043e59d80c4"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a3efb386471803c082aff3043e59d80c4">isControlDevice</a> (lua_State *L)</td></tr> <tr class="separator:a3efb386471803c082aff3043e59d80c4"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:a428b800accf8012a8ed889615c9c6157"><td class="memItemLeft" align="right" valign="top">Reference&lt; <a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_control_device.html">ControlDevice</a> * &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a428b800accf8012a8ed889615c9c6157">realObject</a></td></tr> <tr class="separator:a428b800accf8012a8ed889615c9c6157"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-attribs"></a> Static Public Attributes</h2></td></tr> <tr class="memitem:a12b36eb054f8f45d558eaf1998d5c922"><td class="memItemLeft" align="right" valign="top">static const char&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a12b36eb054f8f45d558eaf1998d5c922">className</a> [] = &quot;LuaControlDevice&quot;</td></tr> <tr class="separator:a12b36eb054f8f45d558eaf1998d5c922"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a016808451acca52d5d1ccd551cbd8660"><td class="memItemLeft" align="right" valign="top">static Luna&lt; <a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html">LuaControlDevice</a> &gt;<br class="typebreak"/> ::RegType&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a016808451acca52d5d1ccd551cbd8660">Register</a> []</td></tr> <tr class="separator:a016808451acca52d5d1ccd551cbd8660"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"> <p>Definition at line <a class="el" href="_control_device_8h_source.html#l00263">263</a> of file <a class="el" href="_control_device_8h_source.html">ControlDevice.h</a>.</p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="aab61d2411f764610729b67b5a7375d07"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">LuaControlDevice::LuaControlDevice </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00483">483</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a85b4d2032938d3f71463416bc6cedce4"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">LuaControlDevice::~LuaControlDevice </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00487">487</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a075594f720ce7c9acdbc8557242c618a"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::_getObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00496">496</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="ae2ccafbe9975032956fda8f5ed39ab50"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::_setObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00490">490</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a42d82f2b479f22698969d0eedcd77eed"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::callObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00559">559</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="ad455976aeb48ca36d2af0e0a0708aace"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::generateObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00540">540</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a3d9b1b61839ac076e9633bc85776d812"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::getControlledObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00597">597</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a3efb386471803c082aff3043e59d80c4"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::isControlDevice </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00614">614</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="af58220ef8db3170822408d20e61da3d9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::setControlledObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00578">578</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a4b72579d4781a7bb9f631e861072f138"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::storeObject </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00521">521</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <a class="anchor" id="a736b40a35d6b7f7d25c20ae67cc7fc79"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int LuaControlDevice::updateToDatabaseAllObjects </td> <td>(</td> <td class="paramtype">lua_State *&#160;</td> <td class="paramname"><em>L</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8cpp_source.html#l00502">502</a> of file <a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a>.</p> <p>References <a class="el" href="_control_device_8h_source.html#l00281">realObject</a>.</p> </div> </div> <h2 class="groupheader">Member Data Documentation</h2> <a class="anchor" id="a12b36eb054f8f45d558eaf1998d5c922"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">const char LuaControlDevice::className = &quot;LuaControlDevice&quot;</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8h_source.html#l00265">265</a> of file <a class="el" href="_control_device_8h_source.html">ControlDevice.h</a>.</p> </div> </div> <a class="anchor" id="a428b800accf8012a8ed889615c9c6157"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">Reference&lt;<a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_control_device.html">ControlDevice</a>*&gt; server::zone::objects::intangible::LuaControlDevice::realObject</td> </tr> </table> </div><div class="memdoc"> <p>Definition at line <a class="el" href="_control_device_8h_source.html#l00281">281</a> of file <a class="el" href="_control_device_8h_source.html">ControlDevice.h</a>.</p> <p>Referenced by <a class="el" href="_control_device_8cpp_source.html#l00496">_getObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00490">_setObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00559">callObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00540">generateObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00597">getControlledObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00614">isControlDevice()</a>, <a class="el" href="_control_device_8cpp_source.html#l00483">LuaControlDevice()</a>, <a class="el" href="_control_device_8cpp_source.html#l00578">setControlledObject()</a>, <a class="el" href="_control_device_8cpp_source.html#l00521">storeObject()</a>, and <a class="el" href="_control_device_8cpp_source.html#l00502">updateToDatabaseAllObjects()</a>.</p> </div> </div> <a class="anchor" id="a016808451acca52d5d1ccd551cbd8660"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">Luna&lt; <a class="el" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html">LuaControlDevice</a> &gt;::RegType LuaControlDevice::Register</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span></span> </td> </tr> </table> </div><div class="memdoc"> <b>Initial value:</b><div class="fragment"><div class="line">= {</div> <div class="line"> { <span class="stringliteral">&quot;_setObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#ae2ccafbe9975032956fda8f5ed39ab50">LuaControlDevice::_setObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;_getObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a075594f720ce7c9acdbc8557242c618a">LuaControlDevice::_getObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;updateToDatabaseAllObjects&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a736b40a35d6b7f7d25c20ae67cc7fc79">LuaControlDevice::updateToDatabaseAllObjects</a> },</div> <div class="line"> { <span class="stringliteral">&quot;storeObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a4b72579d4781a7bb9f631e861072f138">LuaControlDevice::storeObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;generateObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#ad455976aeb48ca36d2af0e0a0708aace">LuaControlDevice::generateObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;callObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a42d82f2b479f22698969d0eedcd77eed">LuaControlDevice::callObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;setControlledObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#af58220ef8db3170822408d20e61da3d9">LuaControlDevice::setControlledObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;getControlledObject&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a3d9b1b61839ac076e9633bc85776d812">LuaControlDevice::getControlledObject</a> },</div> <div class="line"> { <span class="stringliteral">&quot;isControlDevice&quot;</span>, &amp;<a class="code" href="classserver_1_1zone_1_1objects_1_1intangible_1_1_lua_control_device.html#a3efb386471803c082aff3043e59d80c4">LuaControlDevice::isControlDevice</a> },</div> <div class="line"> { 0, 0 }</div> <div class="line">}</div> </div><!-- fragment --> <p>Definition at line <a class="el" href="_control_device_8h_source.html#l00266">266</a> of file <a class="el" href="_control_device_8h_source.html">ControlDevice.h</a>.</p> </div> </div> <hr/>The documentation for this class was generated from the following files:<ul> <li>/Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/objects/intangible/<a class="el" href="_control_device_8h_source.html">ControlDevice.h</a></li> <li>/Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/objects/intangible/<a class="el" href="_control_device_8cpp_source.html">ControlDevice.cpp</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:29:56 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
lgpl-3.0
Perolize/MyBrowser
app/src/js/urlLoad.ts
307
import { ipcRenderer } from 'electron'; import * as normalizeUrl from 'normalize-url'; $(document).ready(() => { ipcRenderer.send('ready'); }); ipcRenderer.on('open-url', (e: any, msg: any) => { const url = normalizeUrl(msg); (document.querySelector('webview.active') as any).loadURL(url); });
lgpl-3.0
LoyaltyNZ/hoodoo
lib/hoodoo/presenters.rb
1391
######################################################################## # File:: presenters.rb # (C):: Loyalty New Zealand 2014 # # Purpose:: Include the schema based data validation and rendering code. # ---------------------------------------------------------------------- # 26-Jan-2015 (ADH): Split from top-level inclusion file. ######################################################################## module Hoodoo # Module providing a namespace for schema-based data rendering and # validation code. # module Presenters end end # Dependencies require 'hoodoo/utilities' # Presenters require 'hoodoo/presenters/base' require 'hoodoo/presenters/base_dsl' require 'hoodoo/presenters/embedding' require 'hoodoo/presenters/types/field' require 'hoodoo/presenters/types/object' require 'hoodoo/presenters/types/array' require 'hoodoo/presenters/types/hash' require 'hoodoo/presenters/types/string' require 'hoodoo/presenters/types/text' require 'hoodoo/presenters/types/enum' require 'hoodoo/presenters/types/boolean' require 'hoodoo/presenters/types/float' require 'hoodoo/presenters/types/integer' require 'hoodoo/presenters/types/decimal' require 'hoodoo/presenters/types/date' require 'hoodoo/presenters/types/date_time' require 'hoodoo/presenters/types/tags' require 'hoodoo/presenters/types/uuid' require 'hoodoo/presenters/common_resource_fields'
lgpl-3.0
claytontstanley/dissertation
dissProject/scrapeUsers.py
18399
import itertools import re import random import time import urllib2 from bs4 import BeautifulSoup import csv import os import os.path import string import pg from collections import OrderedDict import tweepy import sys # lint_ignore=E302,E501 _dir = os.path.dirname(os.path.abspath(__file__)) _cur = pg.connect(host="127.0.0.1") _topHashtagsDir = "%s/dissertationData/topHashtags" % (_dir) def getTweepyAPI(): consumer_key = "vKbz24SqytZnYO33FNkR7w" consumer_secret = "jjobro8Chy9aKMzo8szYMz9tHftONLRkjNnrxk0" access_key = "363361813-FKSdmwSbzuUzHWg326fTGJM7Bu2hTviqEetjMgu8" access_secret = "VKgzDnTvDUWR1csliUR3BiMOI2oqO9NzocNKX1jPd4" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) return tweepy.API(auth) _api = getTweepyAPI() def isRetweet(tweet): return hasattr(tweet, 'retweeted_status') def write2csv(res, file): print "writing %s results to file: %s" % (len(res), file) with open(file, 'wb') as f: writer = csv.writer(f, quoting=csv.QUOTE_ALL) writer.writerows(res) def myQuery(query): print "running query: %s" % (query) res = _cur.query(query) print "finished running query" return(res) def getTweetObj(tweet): tweetObj = [tweet.id_str, tweet.user.id, tweet.user.screen_name.lower(), tweet.created_at, isRetweet(tweet), tweet.in_reply_to_status_id_str, tweet.lang, tweet.truncated, tweet.text.encode("utf-8")] return tweetObj class CustomStreamListener(tweepy.StreamListener): def __init__(self, group): self.group = group self.curTweets = [] # http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods super(CustomStreamListener, self).__init__() def addTweet(self, tweet): tweetObj = getTweetObj(tweet) tweetObj.append(self.group) self.curTweets.append(tweetObj) if len(self.curTweets) == 1000: self.saveResults() self.curTweets = [] def saveResults(self): sys.stdout.write('\n') file = '/tmp/topHashtags.csv' % () ids = [tweet[0] for tweet in self.curTweets] ids = list(OrderedDict.fromkeys(ids)) ids = [[id] for id in ids] myQuery('truncate temp_tweets_id') write2csv(ids, file) myQuery("copy temp_tweets_id (id) from '%s' delimiters ',' csv" % (file)) newIds = myQuery("select id from temp_tweets_id as t where t.id not in (select id from top_hashtag_tweets where top_hashtag_tweets.id >= (select min(id) from temp_tweets_id))").getresult() newIds = [id[0] for id in newIds] newIds = [str(id) for id in newIds] newTweets = [tweet for tweet in self.curTweets if tweet[0] in newIds] newTweets = dict((tweet[0], tweet) for tweet in newTweets).values() write2csv(newTweets, file) myQuery("copy top_hashtag_tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated, text, hashtag_group) from '%s' delimiters ',' csv" % (file)) def on_status(self, status): sys.stdout.write('.') sys.stdout.flush() self.addTweet(status) def on_error(self, status_code): print >> sys.stderr, 'error: %s' % (repr(status_code)) return True def on_timeout(self): print >> sys.stderr, 'Timeout...' return True def scrapeTrendsmap(): baseUrl = 'http://trendsmap.com' url = baseUrl + '/local' soup = BeautifulSoup(urllib2.urlopen(url).read()) #res = soup.findAll('div', {'class': 'location'}) res = soup.findAll('a', {'href': re.compile('^\/local\/us')}) cityUrls = [baseUrl + item['href'] for item in res] allHashtags = [] for rank, url in enumerate(cityUrls): print "working url %s, %s/%s" % (url, rank, len(cityUrls)) soup = BeautifulSoup(urllib2.urlopen(url).read()) res = soup.findAll('a', {'class': 'obscure-text', 'title': re.compile('^#')}) hashtags = [item['title'].encode('utf-8') for item in res] allHashtags.extend(hashtags) time.sleep(2 + random.random()) allHashtags = list(OrderedDict.fromkeys(allHashtags)) random.shuffle(allHashtags) return allHashtags def generateTopHashtagsTrendsmap(): res = scrapeTrendsmap() return res def scrapeStatweestics(): url = 'http://statweestics.com/stats/hashtags/day' soup = BeautifulSoup(urllib2.urlopen(url).read()) res = [] for hrefEl in soup.findAll('a', {'href': re.compile('^\/stats\/show')}): res.append(hrefEl.contents[0].encode('utf-8')) return res def generateTopHashtagsStatweestics(): res = scrapeStatweestics() return res def generateTopHashtagsCSV(scrapeFun, group): res = [] for rank, item in enumerate(scrapeFun()): res.append([item, rank, group]) file = "%s/%s.csv" % (_topHashtagsDir, group) write2csv(res, file) def storeTopHashtags(topHashtagsFile): cmd = "copy top_hashtag_hashtags (hashtag, rank, hashtag_group) from '%s/%s.csv' delimiters ',' csv" % (_topHashtagsDir, topHashtagsFile) myQuery(cmd) def generateTopHashtags(scrapeFun=generateTopHashtagsTrendsmap, groupID='trendsmap'): hashtagGroup = '%s %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), groupID) generateTopHashtagsCSV(scrapeFun, hashtagGroup) storeTopHashtags(hashtagGroup) def getHashtagsFrom(group): res = myQuery("select hashtag from top_hashtag_hashtags where hashtag_group = '%s' order by rank asc" % (group)).getresult() res = [item[0] for item in res] res = [hashtag for hashtag in res if sys.getsizeof(hashtag) <= 60] res = res[-400:] return res def streamHashtags(hashtagGroup): while True: try: sapi = tweepy.streaming.Stream(_api.auth, CustomStreamListener(hashtagGroup)) sapi.filter(languages=['en'], track=getHashtagsFrom('%s' % (hashtagGroup))) except Exception as e: print "couldn't do it for %s:" % (e) time.sleep(1) pass def streamHashtagsCurrent(): #hashtagGroup = '2014-02-27 17:13:30 initial' #hashtagGroup = '2014-03-17 11:28:15 trendsmap' #hashtagGroup = '2014-03-24 13:06:19 trendsmap' hashtagGroup = '2014-04-04 15:03:59 trendsmap' streamHashtags(hashtagGroup) def scrape_socialbakers(url): soup = BeautifulSoup(urllib2.urlopen(url).read()) res = [] for div in soup.findAll('div', {'id': 'snippet-bookmarkToggle-bookmarkToggle'}): res.append(div.findAll('div')[0]['id'].split('-')[-1]) print "grabbed %s results from url %s" % (len(res), url) return res def scrape_twitaholic(url): soup = BeautifulSoup(urllib2.urlopen(url).read()) res = [] for tr in soup.findAll('tr', {'style': 'border-top:1px solid black;'}): temp = tr.find('td', {'class': 'statcol_name'}) res.append(temp.a['title'].split('(')[1][4:-1]) return res def generateTopUsersTwitaholic(): res = [] for i in range(10): i = i + 1 url = 'http://twitaholic.com/top' + str(i) + '00/followers/' res.append(scrape_twitaholic(url)) return res def generateTopUsersSocialBakers(numUsers=10000): res = [] for i in range(numUsers / 50): url = 'http://socialbakers.com/twitter/page-' + str(i + 1) + '/' res.append(scrape_socialbakers(url)) return res _topUsersDir = "%s/dissertationData/topRankedUsers" % (_dir) def generateTopUsersCSV(scrapeFun, topUsersFile): res = scrapeFun() res = list(itertools.chain(*res)) res = [x.lower() for x in res] res = OrderedDict.fromkeys(res) res = filter(None, res) with open("%s/%s" % (_topUsersDir, topUsersFile), 'wb') as csvfile: csvWriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL) rank = 0 for item in res: rank = rank + 1 csvWriter.writerow([item, rank]) def storeTopUsers(topUsersFile): topUsersDir = _topUsersDir cmd = "copy topUsers (user_screen_name, rank) from '${topUsersDir}/${topUsersFile}' delimiters ',' csv" cmd = string.Template(cmd).substitute(locals()) myQuery(cmd) def generateTopUsers(scrapeFun=generateTopUsersTwitaholic, topUsersFile='top1000Twitaholic.csv'): generateTopUsersCSV(scrapeFun=scrapeFun, topUsersFile=topUsersFile) storeTopUsers(topUsersFile=topUsersFile) def storeTagSynonyms(synonymsFile): cmd = "copy tag_synonyms (%s) from '%s/dissertationData/tagSynonyms/%s' delimiters ',' csv header" % ( "id, Source_Tag_Name, Target_Tag_Name, Creation_Date, Owner_User_Id, Auto_Rename_Count, Last_Auto_Rename, Score, Approved_By_User_Id, Approval_Date", _dir, synonymsFile) myQuery(cmd) def storeCurTagSynonyms(): storeTagSynonyms('synonyms-2014-01-30.csv') def backupTables(tableNames=['topUsers', 'tweets', 'top_hashtag_hashtags', 'top_hashtag_tweets', 'post_subsets', 'top_hashtag_subsets', 'post_tokenized', 'top_hashtag_tokenized', 'post_filtered', 'twitter_users', 'tag_synonyms', 'users', 'posts', 'post_tokenized_type_types', 'top_hashtag_tokenized_type_types', 'post_tokenized_chunk_types', 'top_hashtag_tokenized_chunk_types', 'tweets_tokenized', 'tweets_tokenized_chunk_types', 'tweets_tokenized_type_types']): for tableName in tableNames: file = "%s/dissertationData/tables/%s.csv" % (_dir, tableName) cmd = string.Template("copy ${tableName} to '${file}' delimiter ',' csv header").substitute(locals()) myQuery(cmd) def getRemainingHitsUserTimeline(): stat = _api.rate_limit_status() return stat['resources']['statuses']['/statuses/user_timeline']['remaining'] def getRemainingHitsGetUser(): stat = _api.rate_limit_status() return stat['resources']['users']['/users/lookup']['remaining'] def getTweets(screen_name, **kwargs): # w.r.t include_rts: ref: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline # When set to false, the timeline will strip any native retweets (though they # will still count toward both the maximal length of the timeline and the slice # selected by the count parameter). return _api.user_timeline(screen_name=screen_name, include_rts=True, **kwargs) def getInfoForUser(screenNames): users = _api.lookup_users(screen_names=screenNames) res = [[user.id, user.created_at, user.description.encode('utf-8'), user.followers_count, user.friends_count, user.lang, user.location.encode('utf-8'), user.name.encode('utf-8'), user.screen_name.lower(), user.verified, user.statuses_count] for user in users] file = '/tmp/%s..%s_user.csv' % (screenNames[0], screenNames[-1]) write2csv(res, file) myQuery("copy twitter_users (id,created_at,description,followers_count,friends_count,lang,location,name,user_screen_name,verified,statuses_count) from '%s' delimiters ',' csv" % (file)) def getAllTweets(screenNames): def getTweetsBetween(greaterThanID, lessThanID): alltweets = [] while True: print "getting tweets from %s that are later than %s but before %s" % (screen_name, greaterThanID, lessThanID) newTweets = getTweets(screen_name, count=200, max_id=lessThanID - 1, since_id=greaterThanID + 1) if len(newTweets) == 0: break alltweets.extend(newTweets) lessThanID = alltweets[-1].id print "...%s tweets downloaded so far" % (len(alltweets)) return alltweets assert len(screenNames) == 1, "Passed more than one screen name into function" screen_name = screenNames[0] print "getting tweets for %s" % (screen_name) alltweets = [] lessThanID = getTweets(screen_name, count=1)[-1].id + 1 cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id desc").substitute(locals()) res = myQuery(cmd).getresult() if len(res) == 0: newestGrabbed = 0 else: newestGrabbed = int(res[0][0]) res = getTweetsBetween(newestGrabbed, lessThanID) alltweets.extend(res) cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id asc").substitute(locals()) res = myQuery(cmd).getresult() if len(res) == 0: lessThanID = 0 else: lessThanID = int(res[0][0]) alltweets.extend(getTweetsBetween(0, lessThanID)) outTweets = [getTweetObj(tweet) for tweet in alltweets] file = '/tmp/%s_tweets.csv' % screen_name write2csv(outTweets, file) myQuery("copy tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated,text) from '%s' delimiters ',' csv" % (file)) def userAlreadyCollected(user_screen_name): res = myQuery(string.Template("select * from tweets where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult() return len(res) > 0 def userInfoAlreadyCollected(user_screen_name): res = myQuery(string.Template("select * from twitter_users where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult() return len(res) > 0 # ref: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411#434411 def chunker(seq, size): return (seq[pos:pos + size] for pos in xrange(0, len(seq), size)) def getForTopUsers(alreadyCollectedFun, getForUserFun, getRemainingHitsFun, hitsAlwaysGreaterThan, userQuery, groupFun=lambda x: chunker(x, 1)): res = myQuery(userQuery).getresult() screenNames = [[user[0]] for user in res] screenNames = list(itertools.chain(*screenNames)) print "getting tweets for %s users" % len(screenNames) screenNameGroups = groupFun(screenNames) for screenNameGroup in screenNameGroups: newScreenNames = [] for screenName in screenNameGroup: if alreadyCollectedFun(screenName): print "already collected tweets for %s; moving to next user" % (screenName) continue newScreenNames.append(screenName) if len(newScreenNames) == 0: continue try: while True: remainingHits = getRemainingHitsFun() if remainingHits > hitsAlwaysGreaterThan: break print "only %s remaining hits; waiting until greater than %s" % (remainingHits, hitsAlwaysGreaterThan) time.sleep(60) print "calling %s with %s at %s remaining hits" % (getForUserFun, newScreenNames, remainingHits) getForUserFun(newScreenNames) except Exception as e: print "couldn't do it for %s: %s" % (newScreenNames, e) time.sleep(1) pass def getAllTweetsDefault(userQuery): return getForTopUsers(alreadyCollectedFun=userAlreadyCollected, getForUserFun=getAllTweets, getRemainingHitsFun=getRemainingHitsUserTimeline, hitsAlwaysGreaterThan=30, userQuery=userQuery) def makeUserQuery(val, col): return 'select user_screen_name from twitter_users where %s > %d order by %s asc limit 1000' % (col, val, col) def makeUserQueryFollowers(val): return makeUserQuery(val, 'followers_count') def makeUserQueryTweets(val): return makeUserQuery(val, 'statuses_count') def getAllTweetsFor10MUsers(): return getAllTweetsDefault(makeUserQueryFollowers(10000000)) def getAllTweetsFor1MUsers(): return getAllTweetsDefault(makeUserQueryFollowers(1000000)) def getAllTweetsFor100kUsers(): return getAllTweetsDefault(makeUserQueryFollowers(100000)) def getAllTweetsFor10kUsers(): return getAllTweetsDefault(makeUserQueryFollowers(10000)) def getAllTweetsFor5kUsers(): return getAllTweetsDefault(makeUserQueryFollowers(5000)) def getAllTweetsFor1kUsers(): return getAllTweetsDefault(makeUserQueryFollowers(1000)) def getAllTweetsForS1e2Users(): return getAllTweetsDefault(makeUserQueryTweets(100)) def getAllTweetsForS5e2Users(): return getAllTweetsDefault(makeUserQueryTweets(500)) def getAllTweetsForS1e3Users(): return getAllTweetsDefault(makeUserQueryTweets(1000)) def getAllTweetsForS5e3Users(): return getAllTweetsDefault(makeUserQueryTweets(5000)) def getAllTweetsForS1e4Users(): return getAllTweetsDefault(makeUserQueryTweets(10000)) def getAllTweetsForS5e4Users(): return getAllTweetsDefault(makeUserQueryTweets(50000)) def getAllTweetsForTopUsersByFollowers(): getAllTweetsFor10MUsers() getAllTweetsFor1MUsers() getAllTweetsFor100kUsers() getAllTweetsFor10kUsers() getAllTweetsFor1kUsers() getAllTweetsFor5kUsers() def getAllTweetsForTopUsersByTweets(): getAllTweetsForS1e2Users() getAllTweetsForS5e2Users() getAllTweetsForS1e3Users() getAllTweetsForS5e3Users() getAllTweetsForS1e4Users() getAllTweetsForS5e4Users() def getUserInfoForTopUsers(): getForTopUsers(alreadyCollectedFun=userInfoAlreadyCollected, getForUserFun=getInfoForUser, getRemainingHitsFun=getRemainingHitsGetUser, hitsAlwaysGreaterThan=30, groupFun=lambda x: chunker(x, 100), userQuery='select (user_screen_name) from topUsers order by rank asc limit 100000') def generateTopUsers100k(): generateTopUsers(scrapeFun=lambda: generateTopUsersSocialBakers(numUsers=100000), topUsersFile='top100000SocialBakers.csv') def backupTopHashtags(): backupTables(tableNames=['top_hashtag_hashtags', 'top_hashtag_subsets', 'top_hashtag_tokenized', 'top_hashtag_tokenized_chunk_types', 'top_hashtag_tokenized_type_types', 'top_hashtag_tweets']) def backupTweets(): backupTables(tableNames=['tweets', 'tweets_tokenized', 'tweets_tokenized_chunk_types', 'tweets_tokenized_type_types']) # Current run selections #generateTopUsers100k() #getAllTweetsForTopUsersByFollowers() #getAllTweetsForTopUsersByTweets() #getUserInfoForTopUsers() #storeCurTagSynonyms() #backupTopHashtags() #backupTables() #generateTopHashtags() #streamHashtagsCurrent() if __name__ == "__main__": command = " ".join(sys.argv[1:]) print('running command %s') % (command) eval(command)
lgpl-3.0
parmerasa-uau/parallelism-optimization
ParallelismAnalysisJMetal/src/parallelismanalysis/util/Permutations.java
1677
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package parallelismanalysis.util; /************************************************************************* * Compilation: javac Permutations.java * Execution: java Permutations N * * Enumerates all permutations on N elements. * * % java Permutations 3 * bca * cba * cab * acb * bac * abc * * % java Permutations 3 | sort * abc * acb * bac * bca * cab * cba * * http://www.comscigate.com/cs/IntroSedgewick/20elements/27recursion/Permutations.java *************************************************************************/ public class Permutations { // swap the characters at indices i and j public static void swap(char[] a, int i, int j) { char c; c = a[i]; a[i] = a[j]; a[j] = c; } // print n! permutation of the characters of a public static void enumerate(char[] a, int n) { if (n == 1) { System.out.println(a); return; } for (int i = 0; i < n; i++) { swap(a, i, n - 1); enumerate(a, n - 1); swap(a, i, n - 1); } } public static void main(String[] args) { int N = 6; // Integer.parseInt(args[0]); String elements = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // initialize a[i] to ith letter, starting at 'a' char[] a = new char[N]; for (int i = 0; i < N; i++) { a[i] = elements.charAt(i); } enumerate(a, N); } }
lgpl-3.0
Enterprize-1701/robot
Algo/Testing/EmulationMessageAdapter.cs
2581
namespace StockSharp.Algo.Testing { using System; using Ecng.Common; using StockSharp.Messages; /// <summary> /// Адаптер, исполняющий сообщения в <see cref="IMarketEmulator"/>. /// </summary> public class EmulationMessageAdapter : MessageAdapter<IMessageSessionHolder> { /// <summary> /// Создать <see cref="EmulationMessageAdapter"/>. /// </summary> /// <param name="sessionHolder">Контейнер для сессии.</param> public EmulationMessageAdapter(IMessageSessionHolder sessionHolder) : this(new MarketEmulator(), sessionHolder) { } /// <summary> /// Создать <see cref="EmulationMessageAdapter"/>. /// </summary> /// <param name="emulator">Эмулятор торгов.</param> /// <param name="sessionHolder">Контейнер для сессии.</param> public EmulationMessageAdapter(IMarketEmulator emulator, IMessageSessionHolder sessionHolder) : base(MessageAdapterTypes.Transaction, sessionHolder) { Emulator = emulator; } private IMarketEmulator _emulator; /// <summary> /// Эмулятор торгов. /// </summary> public IMarketEmulator Emulator { get { return _emulator; } set { if (value == null) throw new ArgumentNullException("value"); if (value == _emulator) return; if (_emulator != null) { _emulator.NewOutMessage -= SendOutMessage; _emulator.Parent = null; } _emulator = value; _emulator.Parent = SessionHolder; _emulator.NewOutMessage += SendOutMessage; } } /// <summary> /// Запустить таймер генерации с интервалом <see cref="MessageSessionHolder.MarketTimeChangedInterval"/> сообщений <see cref="TimeMessage"/>. /// </summary> protected override void StartMarketTimer() { } /// <summary> /// Отправить сообщение. /// </summary> /// <param name="message">Сообщение.</param> protected override void OnSendInMessage(Message message) { SessionHolder.DoIf<IMessageSessionHolder, HistorySessionHolder>(s => s.UpdateCurrentTime(message.GetServerTime())); switch (message.Type) { case MessageTypes.Connect: _emulator.SendInMessage(new ResetMessage()); SendOutMessage(new ConnectMessage()); return; case MessageTypes.Disconnect: SendOutMessage(new DisconnectMessage()); return; case ExtendedMessageTypes.EmulationState: SendOutMessage(message.Clone()); return; } _emulator.SendInMessage(message); } } }
lgpl-3.0
erelsgl/erel-sites
tnk1/ktuv/mj/28-22.html
14365
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1255' /> <meta charset='windows-1255' /> <meta http-equiv='Content-Script-Type' content='text/javascript' /> <meta http-equiv='revisit-after' content='15 days' /> <title>ðáäì ìäåï àéù øò òéï, åìà éãò ëé çñø éáåàðå</title> <link rel='stylesheet' type='text/css' href='../../../_script/klli.css' /> <link rel='stylesheet' type='text/css' href='../../../tnk1/_themes/klli.css' /> <meta property='og:url' content='https://tora.us.fm/tnk1/ktuv/mj/28-22.html'/> <meta name='author' content="àøàì" /> <meta name='receiver' content="ñâìåú îùìé" /> <meta name='jmQovc' content="tnk1/ktuv/mj/28-22.html" /> <meta name='tvnit' content="" /> <link rel='canonical' href='https://tora.us.fm/tnk1/ktuv/mj/28-22.html' /> </head> <!-- PHP Programming by Erel Segal-Halevi --> <body lang='he' dir='rtl' id = 'tnk1_ktuv_mj_28_22' class='dywn1 '> <div class='pnim'> <script type='text/javascript' src='../../../_script/vars.js'></script> <!--NiwutElyon0--> <div class='NiwutElyon'> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/msr/3.html'>áéï àãí ìçáøå</a>&gt;<a href='../../../tnk1/msr/3anyim.html'>äéçñ ìòðééí</a>&gt;<a href='../../../tnk1/ktuv/mjly/ojr_oni.html'>òåùø áñôø îùìé</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/prqim/ktuv.html'>ëúåáéí</a>&gt;<a href='../../../tnk1/prqim/t28.htm'>îùìé</a>&gt;<a href='../../../tnk1/ktuv/mjly/sgulot.html'>ñâìåú îùìé ìôé ôø÷éí</a>&gt;<a href='../../../tnk1/ktuv/mjly/sgulot28.html'>ñâìåú îùìé ëç</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/ljon/index.html'>ìùåï äî÷øà</a>&gt;<a href='../../../tnk1/ljon/jorj/bhl.html'>áäì</a>&gt;<a href='../../../tnk1/kma/qjrim1/bhl.html'>áäì=</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/msr/9science.html'>îãò åèáò</a>&gt;<a href='../../../tnk1/msr/3xvra.html'>úåôòåú çáøúéåú</a>&gt;<a href='../../../tnk1/ktuv/mjly/ydidut.html'>éãéãåú áñôø îùìé</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/msr/3.html'>áéï àãí ìçáøå</a>&gt;<a href='../../../tnk1/msr/3qmcn.html'>îéãú ä÷îöðåú</a>&gt;</div> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/msr/9science.html'>îãò åèáò</a>&gt;<a href='../../../tnk1/msr/3xvra.html'>úåôòåú çáøúéåú</a>&gt;<a href='../../../tnk1/kma/qjrim1/ayn.html'>òéï äøò=</a>&gt;</div> </div> <!--NiwutElyon1--> <h1 id='h1'>ðáäì ìäåï àéù øò òéï, åìà éãò ëé çñø éáåàðå</h1> <div id='idfields'> <p>÷åã: áéàåø:îùìé ëç22 áúð"ê</p> <p>ñåâ: ãéåï1</p> <p>îàú: àøàì</p> <p>àì: ñâìåú îùìé</p> </div> <script type='text/javascript'>kotrt()</script> <div id='tokn'> <table class='inner_navigation'> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<a href='18-00.html'>éç</a>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<a href='24-00.html'>ëã</a>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<b>ëç</b>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> <tr><td> &nbsp;<a href='28-00.html'>ôø÷ ëç</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='28-01.html'>1</a>&nbsp; &nbsp;<a href='28-02.html'>2</a>&nbsp; &nbsp;<a href='28-03.html'>3</a>&nbsp; &nbsp;<a href='28-04.html'>4</a>&nbsp; &nbsp;<a href='28-05.html'>5</a>&nbsp; &nbsp;<a href='28-06.html'>6</a>&nbsp; &nbsp;<a href='28-07.html'>7</a>&nbsp; &nbsp;<a href='28-08.html'>8</a>&nbsp; &nbsp;<a href='28-09.html'>9</a>&nbsp; &nbsp;<a href='28-10.html'>10</a>&nbsp; &nbsp;<a href='28-11.html'>11</a>&nbsp; &nbsp;<a href='28-12.html'>12</a>&nbsp; &nbsp;<a href='28-13.html'>13</a>&nbsp; &nbsp;<a href='28-14.html'>14</a>&nbsp; &nbsp;<a href='28-15.html'>15</a>&nbsp; &nbsp;<a href='28-16.html'>16</a>&nbsp; &nbsp;<a href='28-17.html'>17</a>&nbsp; &nbsp;<a href='28-18.html'>18</a>&nbsp; &nbsp;<a href='28-19.html'>19</a>&nbsp; &nbsp;<a href='28-20.html'>20</a>&nbsp; &nbsp;<a href='28-21.html'>21</a>&nbsp; &nbsp;<b>22</b>&nbsp; &nbsp;<a href='28-23.html'>23</a>&nbsp; &nbsp;<a href='28-24.html'>24</a>&nbsp; &nbsp;<a href='28-25.html'>25</a>&nbsp; &nbsp;<a href='28-26.html'>26</a>&nbsp; &nbsp;<a href='28-27.html'>27</a>&nbsp; &nbsp;<a href='28-28.html'>28</a>&nbsp; </td></tr> </table><!-- inner_navigation --> <div class='page single_height'> <div class='verse_and_tirgumim'> <div class='verse'> <span class='verse_number'> ëç22</span> <span class='verse_text'>ðÄáÃäÈì ìÇäåÉï àÄéùÑ øÇò òÈéÄï, åÀìÉà éÅãÇò ëÌÄé çÆñÆø éÀáÉàÆðÌåÌ.</span> </div> <div class='short'> <div class='cell tirgum longcell'> <h2 class='subtitle'> &nbsp;ñâåìåú </h2> <div class='cellcontent'> <p> <strong>äðáäì</strong> (çøã) ùîà éàáã <strong>äåðå</strong> ðòùä <strong>àéù øò òéï</strong>, <strong>øò</strong> ìå ìøàåú <strong>áòéðéå</strong> ùàðùéí àçøéí ðäðéí îøëåùå åìëï àéðå îùúó ôòåìä òí äæåìú;&#160;&#160; àáì îùåí ëê âí àéï ìå òí îé ìäúééòõ, äåà <strong>ìà</strong> éåëì <strong>ìãòú</strong> ìáãå àú ëì äîéãò äãøåù ëãé ìäù÷éò áúáåðä, å<strong>éáåà</strong> òìéå <strong>îçñåø</strong>.</p> </div><!--cellcontent--> </div> <div class='cell mcudot longcell'> <h2 class='subtitle'> &nbsp;îöåãåú </h2> <div class='cellcontent'> <p>ä<strong>áäåì ì</strong>äøáåú <strong>äåï</strong>, áååãàé äåà <strong>øò òéï</strong>, ëé éøò òéðå ìúú öã÷ä îäåðå, <strong>åìà</strong> éúï ìá <strong>ìãòú</strong> ùáòáåø îðéòú äöã÷ä <strong>éáåà çñøåï</strong> áòùøå.</p> </div><!--cellcontent--> </div> </div><!--short--> </div><!--verse_and_tirgumim--> <br style='clear:both; line-height:0' /> <div class='long'> <div class='cell ecot longcell'> <h2 class='subtitle'> &nbsp;òöåú </h2> <div class='cellcontent'> <p> ëãé ìäù÷éò éù ìùúó ôòåìä òí àçøéí, äéëåìéí ìäåñéó ìê éãò ùéòæåø ìê ìäøååéç éåúø. ñôø îùìé îúééçñ ìàðùéí äçåùùéí ìùúó ôòåìä: </p> <p> <strong>ðáäì ìäåï</strong> = çøã òì øëåùå, ùîà éàáã;&#160; <strong>øò òéï</strong> <a href="/tnk1/kma/qjrim1/ayn.html">= îøâéù öòø ëùäåà øåàä ùàçøéí ðäðéí, åìà øåöä ìùúó àåúí áøëåùå</a>;&#160;&#160;&#160; <strong>ðáäì ìäåï àéù øò òéï</strong> = ëùàãí çøã ùîà éàáã øëåùå, äôçã îùú÷ àåúå, äåà ìà îñåâì ìùúó ôòåìä òí àçøéí åìøàåú àéê äí ðäðéí îøëåùå. </p> <p> <strong>åìà éãò ëé çñø éáåàðå</strong> = ëùäàãí àéðå îùúó ôòåìä òí àçøéí, çñø ìå éãò, äåà ìà éåãò àéìå öøåú åàñåðåú òìåìéí ìáåà òìéå åòì øëåùå, àéìå ú÷ìåú òìåìåú ì÷øåú åìâøåí ìå ìîçñåø. </p> <p>äãáø ðëåï ìà ø÷ ìâáé øëåù çåîøé àìà âí ìâáé ÷ðééï øåçðé: ëùàãí <strong>ðáäì</strong> ìùîåø òì éãéòåúéå åòì çéãåùéå áúåøä, ðåäâ <strong>ëàéù øò òéï</strong> åàéðå îåëï ìùúó àðùéí àçøéí áéãéòåúéå, ìà é÷áì îäí îùåá, <strong>åìà éãò ëé çñø éáåàðå</strong> áçëîúå åúåøúå. </p> </div><!--cellcontent--> </div> <div class='cell hqblot longright'> <h2 class='subtitle'> &nbsp;ä÷áìåú </h2> <div class='cellcontent'> <p>øòéåï ãåîä ðîöà á<a class="psuq" href="/tnk1/prqim/t2820.htm#21">îùìé ë21</a>: "<q class="psuq">ðÇçÂìÈä <strong>îáçìú[îÀáÉäÆìÆú] </strong> áÌÈøÄàùÑÉðÈä, åÀàÇçÂøÄéúÈäÌ ìÉà úÀáÉøÈêÀ</q>" (<a href="/tnk1/ktuv/mj/20-21.html">ôéøåè</a>) = ðçìä ùîâéòä áîäéøåú åôúàåîéåú, áñåôä ìà úäéä áøëä (<a href="/tnk1/ktuv/mj/20-21.html">ôéøåè</a>). </p><p>áéèåé îðåâã ìáéèåé <strong>øò òéï</strong> ðîöà á<a class="psuq" href="/tnk1/prqim/t2822.htm#9">îùìé ëá9</a>: "<q class="psuq"><strong>èåÉá òÇéÄï</strong> äåÌà éÀáÉøÈêÀ, ëÌÄé ðÈúÇï îÄìÌÇçÀîåÉ ìÇãÌÈì</q>" (<a href="/tnk1/ktuv/mj/22-09.html">ôéøåè</a>).</p> </div><!--cellcontent--> </div> <div class='cell mqorot longbig'> <h2 class='subtitle'> &nbsp;ã÷åéåú </h2> <div class='cellcontent'> <h3>îä æä <strong>ðáäì ìäåï</strong>? </h3><p> 1. <strong>ðáäì</strong> <a href="/tnk1/kma/qjrim1/bhl.html">äåà îùåú÷ îøåá ôçã</a>;&#160;&#160; <strong>ðáäì ìäåï</strong> = îùåú÷ îøåá ôçã ùîà éàáã øëåùå. </p><p>2. <strong>ðáäì</strong> äåà îîäø îàã;&#160;&#160; <strong>ðáäì ìäåï</strong> = øåöä ìäùéâ äåï áîäéøåú. àãí ùøåöä ìäùéâ øëåù áîäéøåú ðòùä <strong>øò òéï</strong> <a href="/tnk1/kma/qjrim1/ayn.html">- îøâéù öòø ëùäåà øåàä ùàçøéí ðäðéí, åìà øåöä ìùúó àåúí áøëåùå</a>; îöèòø ëùäåà øåàä ùìàçøéí éù éåúø îîðå, ùäí "îùéâéí" àåúå á"úçøåú"; åëï îöèòø ëùäåà ðàìõ ìúú ìàçøéí, ëé äãáø ëáéëåì "îòëá" àåúå á"úçøåú" <small>(îöåãú ãåã)</small>. <br /> </p> <h3>îä æä <strong>åìà éãò</strong>?</h3><p>1. äáéèåé <strong>ìà éãò</strong> îúàø àú äèòåú ùì <strong>ðáäì ìäåï àéù øò òéï</strong> - äåà ìà éåãò, ìà îáéï, ùàí öøéê ìáåà îçñåø, äåà éáåà òìéå áëì î÷øä; àå: äåà ìà îáéï, ùëúåöàä îä÷îöðåú ùìå úáåà òìéå ÷ììä <small>(îöåãú ãåã)</small>.</p><p>2. äáéèåé <strong>ìà éãò</strong> îúàø âí àú äðæ÷ äðâøí ì<strong>ðáäì ìäåï àéù øò òéï</strong> - îàçø ùàéðå îùúó àçøéí áòñ÷éå, àéï ìå îñôé÷ éÆãÇò ëãé ìäéæäø îîçñåø.</p><p> ëãé ìäù÷éò éù ìùúó ôòåìä òí àçøéí, äéëåìéí ìäåñéó ìê éãò ùéòæåø ìê ìäøååéç éåúø. ëùàãí <strong>ðáäì ìäåï</strong> - çøã ùîà éàáã øëåùå - äôçã îùú÷ àåúå, äåà ìà îñåâì ìùúó ôòåìä òí àçøéí åìøàåú àéê äí ðäðéí îøëåùå.&#160;&#160; àåìí ììà ùéúåó ôòåìä, çñø ìå éãò - äåà <strong>ìà éåãò</strong> àéìå öøåú åàñåðåú òìåìéí ìáåà òìéå åòì øëåùå, àéìå ú÷ìåú òìåìåú ì÷øåú åìâøåí ìå ìîçñåø. </p> <p>äãáø ðëåï ìà ø÷ ìâáé øëåù çåîøé àìà âí ìâáé ÷ðééï øåçðé: ëùàãí <strong>ðáäì</strong> ìùîåø òì éãéòåúéå åòì çéãåùéå áúåøä, ðåäâ <strong>ëàéù øò òéï</strong> åàéðå îåëï ìùúó àðùéí àçøéí áéãéòåúéå, ìà é÷áì îäí îùåá, <strong>åìà éãò ëé çñø éáåàðå</strong> áçëîúå åúåøúå.</p> </div><!--cellcontent--> </div> </div><!--long--> </div><!--page--> <table class='inner_navigation'> <tr><td> &nbsp;<a href='28-00.html'>ôø÷ ëç</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='28-01.html'>1</a>&nbsp; &nbsp;<a href='28-02.html'>2</a>&nbsp; &nbsp;<a href='28-03.html'>3</a>&nbsp; &nbsp;<a href='28-04.html'>4</a>&nbsp; &nbsp;<a href='28-05.html'>5</a>&nbsp; &nbsp;<a href='28-06.html'>6</a>&nbsp; &nbsp;<a href='28-07.html'>7</a>&nbsp; &nbsp;<a href='28-08.html'>8</a>&nbsp; &nbsp;<a href='28-09.html'>9</a>&nbsp; &nbsp;<a href='28-10.html'>10</a>&nbsp; &nbsp;<a href='28-11.html'>11</a>&nbsp; &nbsp;<a href='28-12.html'>12</a>&nbsp; &nbsp;<a href='28-13.html'>13</a>&nbsp; &nbsp;<a href='28-14.html'>14</a>&nbsp; &nbsp;<a href='28-15.html'>15</a>&nbsp; &nbsp;<a href='28-16.html'>16</a>&nbsp; &nbsp;<a href='28-17.html'>17</a>&nbsp; &nbsp;<a href='28-18.html'>18</a>&nbsp; &nbsp;<a href='28-19.html'>19</a>&nbsp; &nbsp;<a href='28-20.html'>20</a>&nbsp; &nbsp;<a href='28-21.html'>21</a>&nbsp; &nbsp;<b>22</b>&nbsp; &nbsp;<a href='28-23.html'>23</a>&nbsp; &nbsp;<a href='28-24.html'>24</a>&nbsp; &nbsp;<a href='28-25.html'>25</a>&nbsp; &nbsp;<a href='28-26.html'>26</a>&nbsp; &nbsp;<a href='28-27.html'>27</a>&nbsp; &nbsp;<a href='28-28.html'>28</a>&nbsp; </td></tr> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<a href='18-00.html'>éç</a>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<a href='24-00.html'>ëã</a>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<b>ëç</b>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> </table><!-- inner_navigation --> </div><!--tokn--> <h2 id='tguvot'>úâåáåú</h2> <ul id='ultguvot'> <li></li> </ul><!--end--> <script type='text/javascript'>tguva(); txtit()</script> </div><!--pnim--> </body> </html>
lgpl-3.0
KalimochoAz/facturacion_base
model/core/factura_proveedor.php
40486
<?php /* * This file is part of facturacion_base * Copyright (C) 2013-2017 Carlos Garcia Gomez [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace FacturaScripts\model; require_model('asiento.php'); require_model('ejercicio.php'); require_model('linea_iva_factura_proveedor.php'); require_model('linea_factura_proveedor.php'); require_model('regularizacion_iva.php'); require_model('secuencia.php'); require_model('serie.php'); /** * Factura de un proveedor. * * @author Carlos García Gómez <[email protected]> */ class factura_proveedor extends \fs_model { /** * Clave primaria. * @var type */ public $idfactura; /** * ID de la factura a la que rectifica. * @var type */ public $idfacturarect; /** * ID del asiento relacionado, si lo hay. * @var type */ public $idasiento; /** * ID del asiento de pago relacionado, si lo hay. * @var type */ public $idasientop; public $cifnif; /** * Empleado que ha creado la factura. * Modelo agente. * @var type */ public $codagente; /** * Almacén en el que entra la mercancía. * @var type */ public $codalmacen; /** * Divisa de la factura. * @var type */ public $coddivisa; /** * Ejercicio relacionado. El que corresponde a la fecha. * @var type */ public $codejercicio; /** * Código único de la factura. Para humanos. * @var type */ public $codigo; /** * Código de la factura a la que rectifica. * @var type */ public $codigorect; /** * Forma d epago usada. * @var type */ public $codpago; /** * Proveedor de la factura. * @var type */ public $codproveedor; /** * Serie de la factura. * @var type */ public $codserie; public $fecha; public $hora; /** * % de retención IRPF de la factura. * Cada línea puede tener uno distinto. * @var type */ public $irpf; /** * Suma total antes de impuestos. * @var type */ public $neto; /** * Nombre del proveedor. * @var type */ public $nombre; /** * Número de la factura. * Único dentro de serie+ejercicio. * @var type */ public $numero; /** * Número de factura del proveedor, si lo hay. * @var type */ public $numproveedor; public $observaciones; public $pagada; /** * Tasa de conversión a Euros de la divisa de la factura. * @var type */ public $tasaconv; /** * Importe total de la factura, con impuestos. * @var type */ public $total; /** * Total expresado en euros, por si no fuese la divisa de la factura. * totaleuros = total/tasaconv * No hace falta rellenarlo, al hacer save() se calcula el valor. * @var type */ public $totaleuros; /** * Suma total de retenciones IRPF de las líneas. * @var type */ public $totalirpf; /** * Suma total del IVA de las líneas. * @var type */ public $totaliva; /** * Suma del recargo de equivalencia de las líneas. * @var type */ public $totalrecargo; public $anulada; /** * Número de documentos adjuntos. * @var integer */ public $numdocs; public function __construct($f = FALSE) { parent::__construct('facturasprov'); if($f) { $this->anulada = $this->str2bool($f['anulada']); $this->cifnif = $f['cifnif']; $this->codagente = $f['codagente']; $this->codalmacen = $f['codalmacen']; $this->coddivisa = $f['coddivisa']; $this->codejercicio = $f['codejercicio']; $this->codigo = $f['codigo']; $this->codigorect = $f['codigorect']; $this->codpago = $f['codpago']; $this->codproveedor = $f['codproveedor']; $this->codserie = $f['codserie']; $this->fecha = Date('d-m-Y', strtotime($f['fecha'])); $this->hora = '00:00:00'; if( !is_null($f['hora']) ) { $this->hora = date('H:i:s', strtotime($f['hora'])); } $this->idasiento = $this->intval($f['idasiento']); $this->idasientop = $this->intval($f['idasientop']); $this->idfactura = $this->intval($f['idfactura']); $this->idfacturarect = $this->intval($f['idfacturarect']); $this->irpf = floatval($f['irpf']); $this->neto = floatval($f['neto']); $this->nombre = $f['nombre']; $this->numero = $f['numero']; $this->numproveedor = $f['numproveedor']; $this->observaciones = $this->no_html($f['observaciones']); $this->pagada = $this->str2bool($f['pagada']); $this->tasaconv = floatval($f['tasaconv']); $this->total = floatval($f['total']); $this->totaleuros = floatval($f['totaleuros']); $this->totalirpf = floatval($f['totalirpf']); $this->totaliva = floatval($f['totaliva']); $this->totalrecargo = floatval($f['totalrecargo']); $this->numdocs = intval($f['numdocs']); } else { $this->anulada = FALSE; $this->cifnif = ''; $this->codagente = NULL; $this->codalmacen = $this->default_items->codalmacen(); $this->coddivisa = NULL; $this->codejercicio = NULL; $this->codigo = NULL; $this->codigorect = NULL; $this->codpago = $this->default_items->codpago(); $this->codproveedor = NULL; $this->codserie = $this->default_items->codserie(); $this->fecha = Date('d-m-Y'); $this->hora = Date('H:i:s'); $this->idasiento = NULL; $this->idasientop = NULL; $this->idfactura = NULL; $this->idfacturarect = NULL; $this->irpf = 0; $this->neto = 0; $this->nombre = ''; $this->numero = NULL; $this->numproveedor = NULL; $this->observaciones = NULL; $this->pagada = FALSE; $this->tasaconv = 1; $this->total = 0; $this->totaleuros = 0; $this->totalirpf = 0; $this->totaliva = 0; $this->totalrecargo = 0; $this->numdocs = 0; } } protected function install() { new \serie(); new \asiento(); return ''; } public function observaciones_resume() { if($this->observaciones == '') { return '-'; } else if( strlen($this->observaciones) < 60 ) { return $this->observaciones; } else return substr($this->observaciones, 0, 50).'...'; } /** * Establece la fecha y la hora, pero respetando el ejercicio y las * regularizaciones de IVA. * Devuelve TRUE si se asigna una fecha u hora distinta a los solicitados. * @param type $fecha * @param type $hora * @return boolean */ public function set_fecha_hora($fecha, $hora) { $cambio = FALSE; if( is_null($this->numero) ) /// nueva factura { $this->fecha = $fecha; $this->hora = $hora; } else if($fecha != $this->fecha) /// factura existente y cambiamos fecha { $cambio = TRUE; $eje0 = new \ejercicio(); $ejercicio = $eje0->get($this->codejercicio); if($ejercicio) { /// ¿El ejercicio actual está abierto? if( $ejercicio->abierto() ) { $eje2 = $eje0->get_by_fecha($fecha); if($eje2) { if( $eje2->abierto() ) { /// ¿La factura está dentro de alguna regularización? $regiva0 = new \regularizacion_iva(); if( $regiva0->get_fecha_inside($this->fecha) ) { $this->new_error_msg('La factura se encuentra dentro de una regularización de ' .FS_IVA.'. No se puede modificar la fecha.'); } else if( $regiva0->get_fecha_inside($fecha) ) { $this->new_error_msg('No se puede asignar la fecha '.$fecha.' porque ya hay' . ' una regularización de '.FS_IVA.' para ese periodo.'); } else { $cambio = FALSE; $this->fecha = $fecha; $this->hora = $hora; /// ¿El ejercicio es distinto? if($this->codejercicio != $eje2->codejercicio) { $this->codejercicio = $eje2->codejercicio; $this->new_codigo(); } } } else { $this->new_error_msg('El ejercicio '.$eje2->nombre.' está cerrado. No se puede modificar la fecha.'); } } } else { $this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado. No se puede modificar la fecha.'); } } else { $this->new_error_msg('Ejercicio no encontrado.'); } } else if($hora != $this->hora) /// factura existente y cambiamos hora { $this->hora = $hora; } return $cambio; } public function url() { if( is_null($this->idfactura) ) { return 'index.php?page=compras_facturas'; } else return 'index.php?page=compras_factura&id='.$this->idfactura; } public function asiento_url() { if( is_null($this->idasiento) ) { return 'index.php?page=contabilidad_asientos'; } else return 'index.php?page=contabilidad_asiento&id='.$this->idasiento; } public function asiento_pago_url() { if( is_null($this->idasientop) ) { return 'index.php?page=contabilidad_asientos'; } else return 'index.php?page=contabilidad_asiento&id='.$this->idasientop; } public function agente_url() { if( is_null($this->codagente) ) { return "index.php?page=admin_agentes"; } else return "index.php?page=admin_agente&cod=".$this->codagente; } public function proveedor_url() { if( is_null($this->codproveedor) ) { return "index.php?page=compras_proveedores"; } else return "index.php?page=compras_proveedor&cod=".$this->codproveedor; } /** * Devuelve las líneas de la factura. * @return line_factura_proveedor */ public function get_lineas() { $linea = new \linea_factura_proveedor(); return $linea->all_from_factura($this->idfactura); } /** * Devuelve las líneas de IVA de la factura. * Si no hay, las crea. * @return \linea_iva_factura_proveedor */ public function get_lineas_iva() { $linea_iva = new \linea_iva_factura_proveedor(); $lineasi = $linea_iva->all_from_factura($this->idfactura); /// si no hay lineas de IVA las generamos if( !$lineasi ) { $lineas = $this->get_lineas(); if($lineas) { foreach($lineas as $l) { $i = 0; $encontrada = FALSE; while($i < count($lineasi)) { if($l->iva == $lineasi[$i]->iva AND $l->recargo == $lineasi[$i]->recargo) { $encontrada = TRUE; $lineasi[$i]->neto += $l->pvptotal; $lineasi[$i]->totaliva += ($l->pvptotal*$l->iva)/100; $lineasi[$i]->totalrecargo += ($l->pvptotal*$l->recargo)/100; } $i++; } if( !$encontrada ) { $lineasi[$i] = new \linea_iva_factura_proveedor(); $lineasi[$i]->idfactura = $this->idfactura; $lineasi[$i]->codimpuesto = $l->codimpuesto; $lineasi[$i]->iva = $l->iva; $lineasi[$i]->recargo = $l->recargo; $lineasi[$i]->neto = $l->pvptotal; $lineasi[$i]->totaliva = ($l->pvptotal*$l->iva)/100; $lineasi[$i]->totalrecargo = ($l->pvptotal*$l->recargo)/100; } } /// redondeamos y guardamos if( count($lineasi) == 1 ) { $lineasi[0]->neto = round($lineasi[0]->neto, FS_NF0); $lineasi[0]->totaliva = round($lineasi[0]->totaliva, FS_NF0); $lineasi[0]->totalrecargo = round($lineasi[0]->totalrecargo, FS_NF0); $lineasi[0]->totallinea = $lineasi[0]->neto + $lineasi[0]->totaliva + $lineasi[0]->totalrecargo; $lineasi[0]->save(); } else { /* * Como el neto y el iva se redondean en la factura, al dividirlo * en líneas de iva podemos encontrarnos con un descuadre que * hay que calcular y solucionar. */ $t_neto = 0; $t_iva = 0; foreach($lineasi as $li) { $li->neto = bround($li->neto, FS_NF0); $li->totaliva = bround($li->totaliva, FS_NF0); $li->totallinea = $li->neto + $li->totaliva + $li->totalrecargo; $t_neto += $li->neto; $t_iva += $li->totaliva; } if( !$this->floatcmp($this->neto, $t_neto) ) { /* * Sumamos o restamos un céntimo a los netos más altos * hasta que desaparezca el descuadre */ $diferencia = round( ($this->neto-$t_neto) * 100 ); usort($lineasi, function($a, $b) { if($a->totallinea == $b->totallinea) { return 0; } else if($this->total < 0) { return ($a->totallinea < $b->totallinea) ? -1 : 1; } else { return ($a->totallinea < $b->totallinea) ? 1 : -1; } }); foreach($lineasi as $i => $value) { if($diferencia > 0) { $lineasi[$i]->neto += .01; $diferencia--; } else if($diferencia < 0) { $lineasi[$i]->neto -= .01; $diferencia++; } else break; } } if( !$this->floatcmp($this->totaliva, $t_iva) ) { /* * Sumamos o restamos un céntimo a los importes más altos * hasta que desaparezca el descuadre */ $diferencia = round( ($this->totaliva-$t_iva) * 100 ); usort($lineasi, function($a, $b) { if($a->totaliva == $b->totaliva) { return 0; } else if($this->total < 0) { return ($a->totaliva < $b->totaliva) ? -1 : 1; } else { return ($a->totaliva < $b->totaliva) ? 1 : -1; } }); foreach($lineasi as $i => $value) { if($diferencia > 0) { $lineasi[$i]->totaliva += .01; $diferencia--; } else if($diferencia < 0) { $lineasi[$i]->totaliva -= .01; $diferencia++; } else break; } } foreach($lineasi as $i => $value) { $lineasi[$i]->totallinea = $value->neto + $value->totaliva + $value->totalrecargo; $lineasi[$i]->save(); } } } } return $lineasi; } public function get_asiento() { $asiento = new \asiento(); return $asiento->get($this->idasiento); } public function get_asiento_pago() { $asiento = new \asiento(); return $asiento->get($this->idasientop); } /** * Devuelve un array con todas las facturas rectificativas de esta factura. * @return \factura_proveedor */ public function get_rectificativas() { $devoluciones = array(); $data = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfacturarect = ".$this->var2str($this->idfactura).";"); if($data) { foreach($data as $d) { $devoluciones[] = new \factura_proveedor($d); } } return $devoluciones; } /** * Devuelve la factura de compra con el id proporcionado. * @param type $id * @return boolean|\factura_proveedor */ public function get($id) { $fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($id).";"); if($fact) { return new \factura_proveedor($fact[0]); } else return FALSE; } public function get_by_codigo($cod) { $fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE codigo = ".$this->var2str($cod).";"); if($fact) { return new \factura_proveedor($fact[0]); } else return FALSE; } public function exists() { if( is_null($this->idfactura) ) { return FALSE; } else return $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";"); } /** * Genera el número y código de la factura. */ public function new_codigo() { /// buscamos un hueco o el siguiente número disponible $encontrado = FALSE; $num = 1; $sql = "SELECT ".$this->db->sql_to_int('numero')." as numero,fecha,hora FROM ".$this->table_name ." WHERE codejercicio = ".$this->var2str($this->codejercicio) ." AND codserie = ".$this->var2str($this->codserie) ." ORDER BY numero ASC;"; $data = $this->db->select($sql); if($data) { foreach($data as $d) { if( intval($d['numero']) < $num ) { /** * El número de la factura es menor que el inicial. * El usuario ha cambiado el número inicial después de hacer * facturas. */ } else if( intval($d['numero']) == $num ) { /// el número es correcto, avanzamos $num++; } else { /// Hemos encontrado un hueco $encontrado = TRUE; break; } } } if($encontrado) { $this->numero = $num; } else { $this->numero = $num; /// nos guardamos la secuencia para abanq/eneboo $sec = new \secuencia(); $sec = $sec->get_by_params2($this->codejercicio, $this->codserie, 'nfacturaprov'); if($sec) { if($sec->valorout <= $this->numero) { $sec->valorout = 1 + $this->numero; $sec->save(); } } } if(FS_NEW_CODIGO == 'eneboo') { $this->codigo = $this->codejercicio.sprintf('%02s', $this->codserie).sprintf('%06s', $this->numero); } else { $this->codigo = 'FAC'.$this->codejercicio.$this->codserie.$this->numero.'C'; } } /** * Comprueba los datos de la factura, devuelve TRUE si está todo correcto * @return boolean */ public function test() { $this->nombre = $this->no_html($this->nombre); if($this->nombre == '') { $this->nombre = '-'; } $this->numproveedor = $this->no_html($this->numproveedor); $this->observaciones = $this->no_html($this->observaciones); /** * Usamos el euro como divisa puente a la hora de sumar, comparar * o convertir cantidades en varias divisas. Por este motivo necesimos * muchos decimales. */ $this->totaleuros = round($this->total / $this->tasaconv, 5); if( $this->floatcmp($this->total, $this->neto+$this->totaliva-$this->totalirpf+$this->totalrecargo, FS_NF0, TRUE) ) { return TRUE; } else { $this->new_error_msg("Error grave: El total está mal calculado. ¡Informa del error!"); return FALSE; } } public function full_test($duplicados = TRUE) { $status = TRUE; /// comprobamos la fecha de la factura $ejercicio = new \ejercicio(); $eje0 = $ejercicio->get($this->codejercicio); if($eje0) { if( strtotime($this->fecha) < strtotime($eje0->fechainicio) OR strtotime($this->fecha) > strtotime($eje0->fechafin) ) { $status = FALSE; $this->new_error_msg("La fecha de esta factura está fuera del rango del" . " <a target='_blank' href='".$eje0->url()."'>ejercicio</a>."); } } /// comprobamos las líneas $neto = 0; $iva = 0; $irpf = 0; $recargo = 0; foreach($this->get_lineas() as $l) { if( !$l->test() ) { $status = FALSE; } $neto += $l->pvptotal; $iva += $l->pvptotal * $l->iva / 100; $irpf += $l->pvptotal * $l->irpf / 100; $recargo += $l->pvptotal * $l->recargo / 100; } $neto = round($neto, FS_NF0); $iva = round($iva, FS_NF0); $irpf = round($irpf, FS_NF0); $recargo = round($recargo, FS_NF0); $total = $neto + $iva - $irpf + $recargo; if( !$this->floatcmp($this->neto, $neto, FS_NF0, TRUE) ) { $this->new_error_msg("Valor neto de la factura ".$this->codigo." incorrecto. Valor correcto: ".$neto); $status = FALSE; } else if( !$this->floatcmp($this->totaliva, $iva, FS_NF0, TRUE) ) { $this->new_error_msg("Valor totaliva de la factura ".$this->codigo." incorrecto. Valor correcto: ".$iva); $status = FALSE; } else if( !$this->floatcmp($this->totalirpf, $irpf, FS_NF0, TRUE) ) { $this->new_error_msg("Valor totalirpf de la factura ".$this->codigo." incorrecto. Valor correcto: ".$irpf); $status = FALSE; } else if( !$this->floatcmp($this->totalrecargo, $recargo, FS_NF0, TRUE) ) { $this->new_error_msg("Valor totalrecargo de la factura ".$this->codigo." incorrecto. Valor correcto: ".$recargo); $status = FALSE; } else if( !$this->floatcmp($this->total, $total, FS_NF0, TRUE) ) { $this->new_error_msg("Valor total de la factura ".$this->codigo." incorrecto. Valor correcto: ".$total); $status = FALSE; } /// comprobamos las líneas de IVA $this->get_lineas_iva(); $linea_iva = new \linea_iva_factura_proveedor(); if( !$linea_iva->factura_test($this->idfactura, $neto, $iva, $recargo) ) { $status = FALSE; } /// comprobamos el asiento if( isset($this->idasiento) ) { $asiento = $this->get_asiento(); if($asiento) { if($asiento->tipodocumento != 'Factura de proveedor' OR $asiento->documento != $this->codigo) { $this->new_error_msg("Esta factura apunta a un <a href='".$this->asiento_url()."'>asiento incorrecto</a>."); $status = FALSE; } else if($this->coddivisa == $this->default_items->coddivisa() AND (abs($asiento->importe) - abs($this->total+$this->totalirpf) >= .02) ) { $this->new_error_msg("El importe del asiento es distinto al de la factura."); $status = FALSE; } else { $asientop = $this->get_asiento_pago(); if($asientop) { if($this->totalirpf != 0) { /// excluimos la comprobación si la factura tiene IRPF } else if( !$this->floatcmp($asiento->importe, $asientop->importe) ) { $this->new_error_msg('No coinciden los importes de los asientos.'); $status = FALSE; } } } } else { $this->new_error_msg("Asiento no encontrado."); $status = FALSE; } } if($status AND $duplicados) { /// comprobamos si es un duplicado $facturas = $this->db->select("SELECT * FROM ".$this->table_name." WHERE fecha = ".$this->var2str($this->fecha) ." AND codproveedor = ".$this->var2str($this->codproveedor) ." AND total = ".$this->var2str($this->total) ." AND codagente = ".$this->var2str($this->codagente) ." AND numproveedor = ".$this->var2str($this->numproveedor) ." AND observaciones = ".$this->var2str($this->observaciones) ." AND idfactura != ".$this->var2str($this->idfactura).";"); if($facturas) { foreach($facturas as $fac) { /// comprobamos las líneas $aux = $this->db->select("SELECT referencia FROM lineasfacturasprov WHERE idfactura = ".$this->var2str($this->idfactura)." AND referencia NOT IN (SELECT referencia FROM lineasfacturasprov WHERE idfactura = ".$this->var2str($fac['idfactura']).");"); if( !$aux ) { $this->new_error_msg("Esta factura es un posible duplicado de <a href='index.php?page=compras_factura&id=".$fac['idfactura']."'>esta otra</a>. Si no lo es, para evitar este mensaje, simplemente modifica las observaciones."); $status = FALSE; } } } } return $status; } public function save() { if( $this->test() ) { if( $this->exists() ) { $sql = "UPDATE ".$this->table_name." SET codigo = ".$this->var2str($this->codigo) .", total = ".$this->var2str($this->total) .", neto = ".$this->var2str($this->neto) .", cifnif = ".$this->var2str($this->cifnif) .", pagada = ".$this->var2str($this->pagada) .", anulada = ".$this->var2str($this->anulada) .", observaciones = ".$this->var2str($this->observaciones) .", codagente = ".$this->var2str($this->codagente) .", codalmacen = ".$this->var2str($this->codalmacen) .", irpf = ".$this->var2str($this->irpf) .", totaleuros = ".$this->var2str($this->totaleuros) .", nombre = ".$this->var2str($this->nombre) .", codpago = ".$this->var2str($this->codpago) .", codproveedor = ".$this->var2str($this->codproveedor) .", idfacturarect = ".$this->var2str($this->idfacturarect) .", numproveedor = ".$this->var2str($this->numproveedor) .", codigorect = ".$this->var2str($this->codigorect) .", codserie = ".$this->var2str($this->codserie) .", idasiento = ".$this->var2str($this->idasiento) .", idasientop = ".$this->var2str($this->idasientop) .", totalirpf = ".$this->var2str($this->totalirpf) .", totaliva = ".$this->var2str($this->totaliva) .", coddivisa = ".$this->var2str($this->coddivisa) .", numero = ".$this->var2str($this->numero) .", codejercicio = ".$this->var2str($this->codejercicio) .", tasaconv = ".$this->var2str($this->tasaconv) .", totalrecargo = ".$this->var2str($this->totalrecargo) .", fecha = ".$this->var2str($this->fecha) .", hora = ".$this->var2str($this->hora) .", numdocs = ".$this->var2str($this->numdocs) ." WHERE idfactura = ".$this->var2str($this->idfactura).";"; return $this->db->exec($sql); } else { $this->new_codigo(); $sql = "INSERT INTO ".$this->table_name." (codigo,total,neto,cifnif,pagada,anulada,observaciones, codagente,codalmacen,irpf,totaleuros,nombre,codpago,codproveedor,idfacturarect,numproveedor, codigorect,codserie,idasiento,idasientop,totalirpf,totaliva,coddivisa,numero,codejercicio,tasaconv, totalrecargo,fecha,hora,numdocs) VALUES (".$this->var2str($this->codigo) .",".$this->var2str($this->total) .",".$this->var2str($this->neto) .",".$this->var2str($this->cifnif) .",".$this->var2str($this->pagada) .",".$this->var2str($this->anulada) .",".$this->var2str($this->observaciones) .",".$this->var2str($this->codagente) .",".$this->var2str($this->codalmacen) .",".$this->var2str($this->irpf) .",".$this->var2str($this->totaleuros) .",".$this->var2str($this->nombre) .",".$this->var2str($this->codpago) .",".$this->var2str($this->codproveedor) .",".$this->var2str($this->idfacturarect) .",".$this->var2str($this->numproveedor) .",".$this->var2str($this->codigorect) .",".$this->var2str($this->codserie) .",".$this->var2str($this->idasiento) .",".$this->var2str($this->idasientop) .",".$this->var2str($this->totalirpf) .",".$this->var2str($this->totaliva) .",".$this->var2str($this->coddivisa) .",".$this->var2str($this->numero) .",".$this->var2str($this->codejercicio) .",".$this->var2str($this->tasaconv) .",".$this->var2str($this->totalrecargo) .",".$this->var2str($this->fecha) .",".$this->var2str($this->hora) .",".$this->var2str($this->numdocs).");"; if( $this->db->exec($sql) ) { $this->idfactura = $this->db->lastval(); return TRUE; } else return FALSE; } } else return FALSE; } /** * Elimina la factura de la base de datos. * @return boolean */ public function delete() { $bloquear = FALSE; $eje0 = new \ejercicio(); $ejercicio = $eje0->get($this->codejercicio); if($ejercicio) { if( $ejercicio->abierto() ) { $reg0 = new \regularizacion_iva(); if( $reg0->get_fecha_inside($this->fecha) ) { $this->new_error_msg('La factura se encuentra dentro de una regularización de ' .FS_IVA.'. No se puede eliminar.'); $bloquear = TRUE; } else { foreach($this->get_rectificativas() as $rect) { $this->new_error_msg('La factura ya tiene una rectificativa. No se puede eliminar.'); $bloquear = TRUE; break; } } } else { $this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado.'); $bloquear = TRUE; } } /// desvincular albaranes asociados y eliminar factura $sql = "UPDATE albaranesprov SET idfactura = NULL, ptefactura = TRUE WHERE idfactura = ".$this->var2str($this->idfactura).";" . "DELETE FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";"; if($bloquear) { return FALSE; } else if( $this->db->exec($sql) ) { if($this->idasiento) { /** * Delegamos la eliminación del asiento en la clase correspondiente. */ $asiento = new \asiento(); $asi0 = $asiento->get($this->idasiento); if($asi0) { $asi0->delete(); } $asi1 = $asiento->get($this->idasientop); if($asi1) { $asi1->delete(); } } $this->new_message(ucfirst(FS_FACTURA)." de compra ".$this->codigo." eliminada correctamente."); return TRUE; } else return FALSE; } /** * Devuelve un array con las últimas facturas * @param type $offset * @param type $limit * @param type $order * @return \factura_proveedor */ public function all($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha DESC, codigo DESC') { $faclist = array(); $sql = "SELECT * FROM ".$this->table_name." ORDER BY ".$order; $data = $this->db->select_limit($sql, $limit, $offset); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } /** * Devuelve un array con las facturas sin pagar. * @param type $offset * @param type $limit * @param type $order * @return \factura_proveedor */ public function all_sin_pagar($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha ASC, codigo ASC') { $faclist = array(); $sql = "SELECT * FROM ".$this->table_name." WHERE pagada = false ORDER BY ".$order; $data = $this->db->select_limit($sql, $limit, $offset); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } /** * Devuelve un array con las facturas del agente/empleado * @param type $codagente * @param type $offset * @return \factura_proveedor */ public function all_from_agente($codagente, $offset = 0) { $faclist = array(); $sql = "SELECT * FROM ".$this->table_name. " WHERE codagente = ".$this->var2str($codagente). " ORDER BY fecha DESC, codigo DESC"; $data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } /** * Devuelve un array con las facturas del proveedor * @param type $codproveedor * @param type $offset * @return \factura_proveedor */ public function all_from_proveedor($codproveedor, $offset = 0) { $faclist = array(); $sql = "SELECT * FROM ".$this->table_name. " WHERE codproveedor = ".$this->var2str($codproveedor). " ORDER BY fecha DESC, codigo DESC"; $data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } /** * Devuelve un array con las facturas comprendidas entre $desde y $hasta * @param type $desde * @param type $hasta * @param type $codserie * @param type $codagente * @param type $codproveedor * @param type $estado * @return \factura_proveedor */ public function all_desde($desde, $hasta, $codserie = FALSE, $codagente = FALSE, $codproveedor = FALSE, $estado = FALSE, $forma_pago = FALSE) { $faclist = array(); $sql = "SELECT * FROM ".$this->table_name." WHERE fecha >= ".$this->var2str($desde)." AND fecha <= ".$this->var2str($hasta); if($codserie) { $sql .= " AND codserie = ".$this->var2str($codserie); } if($codagente) { $sql .= " AND codagente = ".$this->var2str($codagente); } if($codproveedor) { $sql .= " AND codproveedor = ".$this->var2str($codproveedor); } if($estado) { if($estado == 'pagada') { $sql .= " AND pagada = true"; } else { $sql .= " AND pagada = false"; } } if($forma_pago) { $sql .= " AND codpago = ".$this->var2str($forma_pago); } $sql .= " ORDER BY fecha ASC, codigo ASC;"; $data = $this->db->select($sql); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } /** * Devuelve un array con las facturas coincidentes con $query * @param type $query * @param type $offset * @return \factura_proveedor */ public function search($query, $offset = 0) { $faclist = array(); $query = mb_strtolower( $this->no_html($query), 'UTF8' ); $consulta = "SELECT * FROM ".$this->table_name." WHERE "; if( is_numeric($query) ) { $consulta .= "codigo LIKE '%".$query."%' OR numproveedor LIKE '%".$query ."%' OR observaciones LIKE '%".$query."%'"; } else { $consulta .= "lower(codigo) LIKE '%".$query."%' OR lower(numproveedor) LIKE '%".$query."%' " . "OR lower(observaciones) LIKE '%".str_replace(' ', '%', $query)."%'"; } $consulta .= " ORDER BY fecha DESC, codigo DESC"; $data = $this->db->select_limit($consulta, FS_ITEM_LIMIT, $offset); if($data) { foreach($data as $f) { $faclist[] = new \factura_proveedor($f); } } return $faclist; } public function cron_job() { } }
lgpl-3.0
billowen/GDSCanvas
gadgets.h
1882
/* * This file is part of GDSCanvas. * * gadgets.h -- The header file which declare the funtions for GDS canvas. * * Copyright (c) 2015 Kangpeng Shao <[email protected]> * * GDSII 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 you option) any later version. * * GDSII is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABLILTY 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 GDSII. If not, see <http://www.gnu.org/licenses/>. **/ #ifndef CANVASGADGETS_H #define CANVASGADGETS_H #include "GDS/boundary.h" #include "GDS/path.h" #include "GDS/sref.h" #include "GDS/aref.h" #include "GDS/structures.h" class QPainter; class QStyleOptionGraphicsItem; namespace CANVAS { void initPen(QPainter* painter, const QStyleOptionGraphicsItem* option, int num, int data_type); void initBrush(QPainter* painter, int num, int data_type); void paintBoundary(QPainter* painter, const QStyleOptionGraphicsItem* option, GDS::Boundary* data); void paintPath(QPainter* painter, const QStyleOptionGraphicsItem* option, GDS::Path* data); void paintSRef(QPainter* painter, const QStyleOptionGraphicsItem* option, GDS::SRef* data, int level = 99); void paintARef(QPainter* painter, const QStyleOptionGraphicsItem* option, GDS::ARef* data, int level = 99); void paintStructure(QPainter* painter, const QStyleOptionGraphicsItem* option, GDS::Structure* data, int level = 99, int offset_x = 0, int offset_y = 0, bool reflect = false, double mag = 1, double angle = 0); } #endif // !CANVASGADGETS_H
lgpl-3.0
imasahiro/konohascript
package/konoha.qt4/src/KQPen.cpp
11262
//QPen QPen.new(); KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; KQPen *ret_v = new KQPen(); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } /* //QPen QPen.new(int style); KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]); KQPen *ret_v = new KQPen(style); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } */ /* //QPen QPen.new(QColor color); KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; const QColor color = *RawPtr_to(const QColor *, sfp[1]); KQPen *ret_v = new KQPen(color); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } */ /* //QPen QPen.new(QBrush brush, float width, int style, int cap, int join); KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]); qreal width = Float_to(qreal, sfp[2]); Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[3]); Qt::PenCapStyle cap = Int_to(Qt::PenCapStyle, sfp[4]); Qt::PenJoinStyle join = Int_to(Qt::PenJoinStyle, sfp[5]); KQPen *ret_v = new KQPen(brush, width, style, cap, join); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } */ /* //QPen QPen.new(QPen pen); KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; const QPen pen = *RawPtr_to(const QPen *, sfp[1]); KQPen *ret_v = new KQPen(pen); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } */ //QBrush QPen.getBrush(); KMETHOD QPen_getBrush(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { QBrush ret_v = qp->brush(); QBrush *ret_v_ = new QBrush(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //int QPen.getCapStyle(); KMETHOD QPen_getCapStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenCapStyle ret_v = qp->capStyle(); RETURNi_(ret_v); } else { RETURNi_(0); } } //QColor QPen.getColor(); KMETHOD QPen_getColor(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { QColor ret_v = qp->color(); QColor *ret_v_ = new QColor(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //float QPen.dashOffset(); KMETHOD QPen_dashOffset(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal ret_v = qp->dashOffset(); RETURNf_(ret_v); } else { RETURNf_(0.0f); } } //boolean QPen.isCosmetic(); KMETHOD QPen_isCosmetic(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { bool ret_v = qp->isCosmetic(); RETURNb_(ret_v); } else { RETURNb_(false); } } //boolean QPen.isSolid(); KMETHOD QPen_isSolid(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { bool ret_v = qp->isSolid(); RETURNb_(ret_v); } else { RETURNb_(false); } } //int QPen.getJoinStyle(); KMETHOD QPen_getJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenJoinStyle ret_v = qp->joinStyle(); RETURNi_(ret_v); } else { RETURNi_(0); } } //float QPen.getMiterLimit(); KMETHOD QPen_getMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal ret_v = qp->miterLimit(); RETURNf_(ret_v); } else { RETURNf_(0.0f); } } //void QPen.setBrush(QBrush brush); KMETHOD QPen_setBrush(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]); qp->setBrush(brush); } RETURNvoid_(); } //void QPen.setCapStyle(int style); KMETHOD QPen_setCapStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenCapStyle style = Int_to(Qt::PenCapStyle, sfp[1]); qp->setCapStyle(style); } RETURNvoid_(); } //void QPen.setColor(QColor color); KMETHOD QPen_setColor(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { const QColor color = *RawPtr_to(const QColor *, sfp[1]); qp->setColor(color); } RETURNvoid_(); } //void QPen.setCosmetic(boolean cosmetic); KMETHOD QPen_setCosmetic(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { bool cosmetic = Boolean_to(bool, sfp[1]); qp->setCosmetic(cosmetic); } RETURNvoid_(); } //void QPen.setDashOffset(float offset); KMETHOD QPen_setDashOffset(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal offset = Float_to(qreal, sfp[1]); qp->setDashOffset(offset); } RETURNvoid_(); } //void QPen.setJoinStyle(int style); KMETHOD QPen_setJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenJoinStyle style = Int_to(Qt::PenJoinStyle, sfp[1]); qp->setJoinStyle(style); } RETURNvoid_(); } //void QPen.setMiterLimit(float limit); KMETHOD QPen_setMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal limit = Float_to(qreal, sfp[1]); qp->setMiterLimit(limit); } RETURNvoid_(); } //void QPen.setStyle(int style); KMETHOD QPen_setStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]); qp->setStyle(style); } RETURNvoid_(); } //void QPen.setWidth(int width); KMETHOD QPen_setWidth(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { int width = Int_to(int, sfp[1]); qp->setWidth(width); } RETURNvoid_(); } //void QPen.setWidthF(float width); KMETHOD QPen_setWidthF(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal width = Float_to(qreal, sfp[1]); qp->setWidthF(width); } RETURNvoid_(); } //int QPen.getStyle(); KMETHOD QPen_getStyle(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { Qt::PenStyle ret_v = qp->style(); RETURNi_(ret_v); } else { RETURNi_(0); } } //int QPen.getWidth(); KMETHOD QPen_getWidth(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { int ret_v = qp->width(); RETURNi_(ret_v); } else { RETURNi_(0); } } //float QPen.getWidthF(); KMETHOD QPen_getWidthF(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen * qp = RawPtr_to(QPen *, sfp[0]); if (qp) { qreal ret_v = qp->widthF(); RETURNf_(ret_v); } else { RETURNf_(0.0f); } } //Array<String> QPen.parents(); KMETHOD QPen_parents(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QPen *qp = RawPtr_to(QPen*, sfp[0]); if (qp != NULL) { int size = 10; knh_Array_t *a = new_Array0(ctx, size); const knh_ClassTBL_t *ct = sfp[0].p->h.cTBL; while(ct->supcid != CLASS_Object) { ct = ct->supTBL; knh_Array_add(ctx, a, (knh_Object_t *)ct->lname); } RETURN_(a); } else { RETURN_(KNH_NULL); } } DummyQPen::DummyQPen() { CTX lctx = knh_getCurrentContext(); (void)lctx; self = NULL; event_map = new map<string, knh_Func_t *>(); slot_map = new map<string, knh_Func_t *>(); } DummyQPen::~DummyQPen() { delete event_map; delete slot_map; event_map = NULL; slot_map = NULL; } void DummyQPen::setSelf(knh_RawPtr_t *ptr) { DummyQPen::self = ptr; } bool DummyQPen::eventDispatcher(QEvent *event) { bool ret = true; switch (event->type()) { default: ret = false; break; } return ret; } bool DummyQPen::addEvent(knh_Func_t *callback_func, string str) { std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::event_map->bigin(); if ((itr = DummyQPen::event_map->find(str)) == DummyQPen::event_map->end()) { bool ret = false; return ret; } else { KNH_INITv((*event_map)[str], callback_func); return true; } } bool DummyQPen::signalConnect(knh_Func_t *callback_func, string str) { std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::slot_map->bigin(); if ((itr = DummyQPen::slot_map->find(str)) == DummyQPen::slot_map->end()) { bool ret = false; return ret; } else { KNH_INITv((*slot_map)[str], callback_func); return true; } } knh_Object_t** DummyQPen::reftrace(CTX ctx, knh_RawPtr_t *p FTRARG) { (void)ctx; (void)p; (void)tail_; // fprintf(stderr, "DummyQPen::reftrace p->rawptr=[%p]\n", p->rawptr); return tail_; } void DummyQPen::connection(QObject *o) { QPen *p = dynamic_cast<QPen*>(o); if (p != NULL) { } } KQPen::KQPen() : QPen() { magic_num = G_MAGIC_NUM; self = NULL; dummy = new DummyQPen(); } KQPen::~KQPen() { delete dummy; dummy = NULL; } KMETHOD QPen_addEvent(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; KQPen *qp = RawPtr_to(KQPen *, sfp[0]); const char *event_name = String_to(const char *, sfp[1]); knh_Func_t *callback_func = sfp[2].fo; if (qp != NULL) { // if (qp->event_map->find(event_name) == qp->event_map->end()) { // fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name); // return; // } string str = string(event_name); // KNH_INITv((*(qp->event_map))[event_name], callback_func); if (!qp->dummy->addEvent(callback_func, str)) { fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name); return; } } RETURNvoid_(); } KMETHOD QPen_signalConnect(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; KQPen *qp = RawPtr_to(KQPen *, sfp[0]); const char *signal_name = String_to(const char *, sfp[1]); knh_Func_t *callback_func = sfp[2].fo; if (qp != NULL) { // if (qp->slot_map->find(signal_name) == qp->slot_map->end()) { // fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name); // return; // } string str = string(signal_name); // KNH_INITv((*(qp->slot_map))[signal_name], callback_func); if (!qp->dummy->signalConnect(callback_func, str)) { fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name); return; } } RETURNvoid_(); } static void QPen_free(CTX ctx, knh_RawPtr_t *p) { (void)ctx; if (!exec_flag) return; if (p->rawptr != NULL) { KQPen *qp = (KQPen *)p->rawptr; if (qp->magic_num == G_MAGIC_NUM) { delete qp; p->rawptr = NULL; } else { delete (QPen*)qp; p->rawptr = NULL; } } } static void QPen_reftrace(CTX ctx, knh_RawPtr_t *p FTRARG) { if (p->rawptr != NULL) { // KQPen *qp = (KQPen *)p->rawptr; KQPen *qp = static_cast<KQPen*>(p->rawptr); qp->dummy->reftrace(ctx, p, tail_); } } static int QPen_compareTo(knh_RawPtr_t *p1, knh_RawPtr_t *p2) { return (*static_cast<QPen*>(p1->rawptr) == *static_cast<QPen*>(p2->rawptr) ? 0 : 1); } void KQPen::setSelf(knh_RawPtr_t *ptr) { self = ptr; dummy->setSelf(ptr); } DEFAPI(void) defQPen(CTX ctx, knh_class_t cid, knh_ClassDef_t *cdef) { (void)ctx; (void) cid; cdef->name = "QPen"; cdef->free = QPen_free; cdef->reftrace = QPen_reftrace; cdef->compareTo = QPen_compareTo; }
lgpl-3.0
GRAM-shuzo/TireDataAnalyzer
TireDataAnalyzer/TireDataAnalyzer/UserControls/FittingWizard/FittingWizard.Designer.cs
1503
namespace TireDataAnalyzer.UserControls.FittingWizard { partial class FittingWizard { /// <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() { this.SuspendLayout(); // // FittingWizard // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1023, 684); this.Name = "FittingWizard"; this.Text = "FittingWizard"; this.Load += new System.EventHandler(this.FittingWizard_Load); this.ResumeLayout(false); } #endregion } }
lgpl-3.0
ha-jdbc/ha-jdbc
core/src/main/java/net/sf/hajdbc/sql/RefProxyFactoryFactory.java
1563
/* * HA-JDBC: High-Availability JDBC * Copyright (C) 2013 Paul Ferraro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 program. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.hajdbc.sql; import java.sql.Ref; import java.sql.SQLException; import java.util.Map; import net.sf.hajdbc.Database; import net.sf.hajdbc.invocation.Invoker; /** * * @author Paul Ferraro */ public class RefProxyFactoryFactory<Z, D extends Database<Z>, P> implements ProxyFactoryFactory<Z, D, P, SQLException, Ref, SQLException> { private final boolean locatorsUpdateCopy; public RefProxyFactoryFactory(boolean locatorsUpdateCopy) { this.locatorsUpdateCopy = locatorsUpdateCopy; } @Override public ProxyFactory<Z, D, Ref, SQLException> createProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, Ref, SQLException> invoker, Map<D, Ref> structs) { return new RefProxyFactory<>(parentProxy, parent, invoker, structs, this.locatorsUpdateCopy); } }
lgpl-3.0
RBastianini/polygen-php
src/Grammar/Definition.php
1761
<?php namespace Polygen\Grammar; use Polygen\Grammar\Interfaces\DeclarationInterface; use Polygen\Grammar\Interfaces\Node; use Polygen\Language\AbstractSyntaxWalker; use Webmozart\Assert\Assert; /** * Definition Polygen node */ class Definition implements DeclarationInterface, Node { /** * @var string */ private $name; /** * @var ProductionCollection */ private $productions; /** * @param string $name */ public function __construct($name, ProductionCollection $productions) { Assert::string($name); $this->name = $name; $this->productions = $productions; } /** * @return string */ public function getName() { return $this->name; } /** * Allows a node to pass itself back to the walker using the method most appropriate to walk on it. * * @param mixed|null $context Data that you want to be passed back to the walker. * @return mixed|null */ public function traverse(AbstractSyntaxWalker $walker, $context = null) { return $walker->walkDefinition($this, $context); } /** * @deprecated * @return Production[] */ public function getProductions() { return $this->productions->getProductions(); } /** * @return \Polygen\Grammar\ProductionCollection */ public function getProductionSet() { return $this->productions; } /** * Returns a new instance of this object with the same properties, but with the specified productions. * * @return static */ public function withProductions(ProductionCollection $productions) { return new static($this->name, $productions); } }
lgpl-3.0
InfectedPacket/TerrorCat
UI.py
32143
#!/usr/bin/env python # # Copyright (C) 2015 Jonathan Racicot # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http:#www.gnu.org/licenses/>. # # You are free to use and modify this code for your own software # as long as you retain information about the original author # in your code as shown below. # # <author>Jonathan Racicot</author> # <email>[email protected]</email> # <date>2015-03-26</date> # <url>https://github.com/infectedpacket</url> #////////////////////////////////////////////////////////// # Program Information # PROGRAM_NAME = "vmfcat" PROGRAM_DESC = "" PROGRAM_USAGE = "%(prog)s [-i] [-h|--help] (OPTIONS)" __version_info__ = ('0','1','0') __version__ = '.'.join(__version_info__) #////////////////////////////////////////////////////////// #////////////////////////////////////////////////////////// # Imports Statements import re import sys import json import argparse import traceback from Factory import * from Logger import * from bitstring import * #////////////////////////////////////////////////////////// # ============================================================================= # Parameter information class Params: parameters = { "debug" : { "cmd" : "debug", "help" : "Enables debug mode.", "choices" : [True, False] }, "data" : { "cmd" : "data", "help" : "Specifies a file containing data to be included in the VMF message.", "choices" : [] }, "vmfversion" : { "cmd" : "vmfversion", "help" : """Field representing the version of the MIL-STD-2045-47001 header being used for the message.""", "choices" : ["std47001", "std47001b","std47001c","std47001d","std47001d_change"] }, "compress" : { "cmd" : "compress", "help" : """This field represents whether the message or messages contained in the User Data portion of the Application PDU have been UNIX compressed or compressed using GZIP.""", "choices" : ["unix", "gzip"] }, "headersize" : { "cmd" : "headersize", "help" : """Indicates the size in octets of the header""", "choices" : [] }, "originator_urn" : { "cmd" : "originator_urn", "help" : """24-bit code used to uniquely identify friendly military units, broadcast networks and multicast groups.""", "choices" : [] }, "originator_unitname" : { "cmd" : "originator_unitname", "help" : """Specify the name of the unit sending the message.""", "choices" : [] }, "rcpt_urns" : { "cmd" : "rcpt_urns", "help" : """List of 24-bit codes used to uniquely identify friendly units.""", "choices" : [] }, "rcpt_unitnames" : { "cmd" : "rcpt_unitnames", "help" : """ List of variable size fields of character-coded identifiers for friendly units. """, "choices" : [] }, "info_urns" : { "cmd" : "info_urns", "help" : """List of 24-bit codes used to uniquely identify friendly units.""", "choices" : [] }, "info_unitnames" : { "cmd" : "info_unitnames", "help" : """ List of variable size fields of character-coded identifiers for friendly units. """, "choices" : [] }, "umf" : { "cmd" : "umf", "choices" : ["link16", "binary", "vmf", "nitfs", "rdm", "usmtf", "doi103", "xml-mtf", "xml-vmf"], "help" : """ Indicates the format of the message contained in the user data field.""" }, "messagevers" : { "cmd" : "messagevers", "choices" : [], "help" : """Represents the version of the message standard contained in the user data field.""" }, "fad" : { "cmd" : "fad", "choices" : ["netcon", "geninfo", "firesp", "airops", "intops", "landops","marops", "css", "specialops", "jtfopsctl", "airdef"], "help" : "Identifies the functional area of a specific VMF message using code words." }, "msgnumber" : { "cmd" : "msgnumber", "choices" : [], "help" : """Represents the number that identifies a specific VMF message within a functional area.""" }, "msgsubtype" : { "cmd" : "msgsubtype", "choices" : [], "help" : """Represents a specific case within a VMF message, which depends on the UMF, FAD and message number.""" }, "filename" : { "cmd" : "filename", "choices" : [], "help" : """Indicates the name of the computer file or data block contained in the User Data portion of the application PDU.""" }, "msgsize" : { "cmd" : "msgsize", "choices" : [], "help" : """Indicates the size(in bytes) of the associated message within the User Data field.""" }, "opind" : { "cmd" : "opind", "choices" : ["op", "ex", "sim", "test"], "help" : "Indicates the operational function of the message." }, "retransmission" : { "cmd" : "retransmission", "choices" : [1, 0], "help" : """Indicates whether a message is a retransmission.""" }, "msgprecedence" : { "cmd" : "msgprecedence", "choices" : ["reserved", "critic", "flashover", "flash", "imm", "pri", "routine"], "help" : """Indicates relative precedence of a message.""" }, "classification" : { "cmd" : "classification", "choices" : ["unclass", "conf", "secret", "topsecret"], "help" : """Security classification of the message.""" }, "releasemark" : { "cmd" : "releasemark", "choices" : [], "help" : """Support the exchange of a list of up to 16 country codes with which the message can be release.""" }, "originatordtg" : { "cmd" : "originatordtg", "choices" : [], "help" : """ Contains the date and time in Zulu Time that the message was prepared.""" }, "perishdtg" : { "cmd" : "perishdtg", "choices" : [], "help" : """Provides the latest time the message is still of value.""" }, "ackmachine" : { "cmd" : "ackmachine", "choices" : [1, 0], "help" : """Indicates whether the originator of a machine requires a machine acknowledgement for the message.""" }, "ackop" : { "cmd" : "ackop", "choices" : [1, 0], "help" : """Indicates whether the originator of the message requires an acknowledgement for the message from the recipient.""" }, "ackdtg" : { "cmd" : "ackdtg", "choices" : [], "help" : """Provides the date and time of the original message that is being acknowledged.""" }, "rc" : { "cmd" : "rc", "choices" : ["mr", "cantpro", "oprack", "wilco", "havco", "cantco", "undef"], "help" : """Codeword representing the Receipt/Compliance answer to the acknowledgement request.""" }, "cantpro" : { "cmd" : "cantpro", "choices" : [], "help" : """Indicates the reason that a particular message cannot be processed by a recipient or information address.""" }, "reply" : { "cmd" : "reply", "choices" : [1, 0], "help" : """Indicates whether the originator of the message requires an operator reply to the message.""" }, "cantco" : { "cmd" : "cantco", "choices" : ["comm", "ammo", "pers", "fuel", "env", "equip", "tac", "other"], "help" : """Indicates the reason that a particular recipient cannot comply with a particular message.""" }, "replyamp" : { "cmd" : "replyamp", "choices" : [], "help" : """Provide textual data an amplification of the recipient's reply to a message.""" }, "ref_urn" : { "cmd" : "ref_urn", "choices" : [], "help" : """URN of the reference message.""" }, "ref_unitname" : { "cmd" : "ref_unitname", "choices" : [], "help" : """Name of the unit of the reference message.""" }, "refdtg" : { "cmd" : "refdtg", "choices" : [], "help" : """Date time group of the reference message.""" }, "secparam" : { "cmd" : "secparam", "choices" : ['auth', 'undef'], "help" : """Indicate the identities of the parameters and algorithms that enable security processing.""" }, "keymatlen" : { "cmd" : "keymatlen", "choices" : [], "help" : """Defines the size in octets of the Keying Material ID field.""" }, "keymatid" : { "cmd" : "keymatid", "choices" : [], "help" : """Identifies the key which was used for encryption.""" }, "crypto_init_len" : { "cmd" : "crypto_init_len", "choices" : [], "help" : """Defines the size, in 64-bit blocks, of the Crypto Initialization field.""" }, "crypto_init" : { "cmd" : "crypto_init", "choices" : [], "help" : """Sequence of bits used by the originator and recipient to initialize the encryption/decryption process.""" }, "keytok_len" : { "cmd" : "keytok_len", "choices" : [], "help" : """Defines the size, in 64-bit blocks, of the Key Token field.""" }, "keytok" : { "cmd" : "keytok", "choices" : [], "help" : """Contains information enabling each member of each address group to decrypt the user data associated with this message header.""" }, "autha-len" : { "cmd" : "autha-len", "choices" : [], "help" : """Defines the size, in 64-bit blocks, of the Authentification Data (A) field.""" }, "authb-len" : { "cmd" : "authb-len", "choices" : [], "help" : """Defines the size, in 64-bit blocks, of the Authentification Data (B) field.""" }, "autha" : { "cmd" : "autha", "choices" : [], "help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (A).""" }, "authb" : { "cmd" : "authb", "choices" : [], "help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (B).""" }, "acksigned" : { "cmd" : "acksigned", "choices" : [], "help" : """Indicates whether the originator of a message requires a signed response from the recipient.""" }, "pad_len" : { "cmd" : "pad_len", "choices" : [], "help" : """Defines the size, in octets, of the message security padding field.""" }, "padding" : { "cmd" : "padding", "choices" : [], "help" : """Necessary for a block encryption algorithm so the content of the message is a multiple of the encryption block length.""" }, } #////////////////////////////////////////////////////////////////////////////// # Argument Parser Declaration # usage = "%(prog)s [options] data" parser = argparse.ArgumentParser(usage=usage, prog="vmfcat", version="%(prog)s "+__version__, description="Allows crafting of Variable Message Format (VMF) messages.") io_options = parser.add_argument_group( "Input/Output Options", "Types of I/O supported.") io_options.add_argument("-d", "--debug", dest=Params.parameters['debug']['cmd'], action="store_true", help=Params.parameters['debug']['help']) io_options.add_argument("-i", "--interactive", dest="interactive", action="store_true", help="Create and send VMF messages interactively.") io_options.add_argument("-of", "--ofile", dest="outputfile", nargs="?", type=argparse.FileType('w'), default=sys.stdout, help="File to output the results. STDOUT by default.") io_options.add_argument("--data", dest=Params.parameters['data']['cmd'], help=Params.parameters['data']['help']) # ============================================================================= # Application Header Arguments header_options = parser.add_argument_group( "Application Header", "Flags and Fields of the application header.") header_options.add_argument("--vmf-version", dest=Params.parameters["vmfversion"]["cmd"], action="store", choices=Params.parameters["vmfversion"]["choices"], default="std47001c", help=Params.parameters["vmfversion"]["help"]) header_options.add_argument("--compress", dest=Params.parameters["compress"]["cmd"], action="store", choices=Params.parameters["compress"]["choices"], help=Params.parameters["compress"]["help"]) header_options.add_argument("--header-size", dest=Params.parameters["headersize"]["cmd"], action="store", type=int, help=Params.parameters["headersize"]["help"]) # ============================================================================= # Originator Address Group Arguments orig_addr_options = parser.add_argument_group( "Originator Address Group", "Fields of the originator address group.") orig_addr_options.add_argument("--orig-urn", dest=Params.parameters["originator_urn"]["cmd"], metavar="URN", type=int, action="store", help=Params.parameters["originator_urn"]["help"]) orig_addr_options.add_argument("--orig-unit", dest=Params.parameters["originator_unitname"]["cmd"], metavar="STRING", action="store", help=Params.parameters["originator_unitname"]["help"]) # ============================================================================= # ============================================================================= # Recipient Address Group Arguments recp_addr_options = parser.add_argument_group( "Recipient Address Group", "Fields of the recipient address group.") recp_addr_options.add_argument("--rcpt-urns", nargs="+", dest=Params.parameters['rcpt_urns']['cmd'], metavar="URNs", help=Params.parameters['rcpt_urns']['help']) recp_addr_options.add_argument("--rcpt-unitnames", nargs="+", dest=Params.parameters['rcpt_unitnames']['cmd'], metavar="UNITNAMES", help=Params.parameters['rcpt_unitnames']['help']) # ============================================================================= # ============================================================================= # Information Address Group Arguments info_addr_options = parser.add_argument_group( "Information Address Group", "Fields of the information address group.") info_addr_options.add_argument("--info-urns", dest=Params.parameters["info_urns"]["cmd"], metavar="URNs", nargs="+", action="store", help=Params.parameters["info_urns"]["help"]) info_addr_options.add_argument("--info-units", dest="info_unitnames", metavar="UNITNAMES", action="store", help="Specify the name of the unit of the reference message.") # ============================================================================= # ============================================================================= # Message Handling Group Arguments msg_handling_options = parser.add_argument_group( "Message Handling Group", "Fields of the message handling group.") msg_handling_options.add_argument("--umf", dest=Params.parameters["umf"]["cmd"], action="store", choices=Params.parameters["umf"]["choices"], help=Params.parameters["umf"]["help"]) msg_handling_options.add_argument("--msg-version", dest=Params.parameters["messagevers"]["cmd"], action="store", metavar="VERSION", type=int, help=Params.parameters["messagevers"]["help"]) msg_handling_options.add_argument("--fad", dest=Params.parameters["fad"]["cmd"], action="store", choices=Params.parameters["fad"]["choices"], help=Params.parameters["fad"]["help"]) msg_handling_options.add_argument("--msg-number", dest=Params.parameters["msgnumber"]["cmd"], action="store", type=int, metavar="1-127", help=Params.parameters["msgnumber"]["help"]) msg_handling_options.add_argument("--msg-subtype", dest=Params.parameters["msgsubtype"]["cmd"], action="store", type=int, metavar="1-127", help=Params.parameters["msgsubtype"]["help"]) msg_handling_options.add_argument("--filename", dest=Params.parameters["filename"]["cmd"], action="store", help=Params.parameters["filename"]["help"]) msg_handling_options.add_argument("--msg-size", dest=Params.parameters["msgsize"]["cmd"], action="store", type=int, metavar="SIZE", help=Params.parameters["msgsize"]["help"]) msg_handling_options.add_argument("--opind", dest=Params.parameters["opind"]["cmd"], action="store", choices=Params.parameters["opind"]["choices"], help=Params.parameters["opind"]["help"]) msg_handling_options.add_argument("--retrans", dest=Params.parameters["retransmission"]["cmd"], action="store_true", help=Params.parameters["retransmission"]["help"]) msg_handling_options.add_argument("--msg-prec", dest=Params.parameters["msgprecedence"]["cmd"], action="store", choices=Params.parameters["msgprecedence"]["choices"], help=Params.parameters["msgprecedence"]["help"]) msg_handling_options.add_argument("--class", dest=Params.parameters["classification"]["cmd"], action="store", nargs="+", choices=Params.parameters["classification"]["choices"], help=Params.parameters["classification"]["cmd"]) msg_handling_options.add_argument("--release", dest=Params.parameters["releasemark"]["cmd"], action="store", metavar="COUNTRIES", help=Params.parameters["releasemark"]["help"]) msg_handling_options.add_argument("--orig-dtg", dest=Params.parameters["originatordtg"]["cmd"], action="store", metavar="YYYY-MM-DD HH:mm[:ss] [extension]", help=Params.parameters["originatordtg"]["cmd"]) msg_handling_options.add_argument("--perish-dtg", dest=Params.parameters["perishdtg"]["cmd"], action="store", metavar="YYYY-MM-DD HH:mm[:ss]", help=Params.parameters["perishdtg"]["cmd"]) # ===================================================================================== # ===================================================================================== # Acknowledge Request Group Arguments ack_options = parser.add_argument_group( "Acknowledgement Request Group", "Options to request acknowledgement and replies.") ack_options.add_argument("--ack-machine", dest=Params.parameters["ackmachine"]["cmd"], action="store_true", help=Params.parameters["ackmachine"]["help"]) ack_options.add_argument("--ack-op", dest=Params.parameters["ackop"]["cmd"], action="store_true", help=Params.parameters["ackop"]["help"]) ack_options.add_argument("--reply", dest=Params.parameters["reply"]["cmd"], action="store_true", help=Params.parameters["reply"]["help"]) # ===================================================================================== # ===================================================================================== # Response Data Group Arguments # resp_options = parser.add_argument_group( "Response Data Options", "Fields for the response data group.") resp_options.add_argument("--ack-dtg", dest=Params.parameters["ackdtg"]["cmd"], help=Params.parameters["ackdtg"]["help"], action="store", metavar="YYYY-MM-DD HH:mm[:ss] [extension]") resp_options.add_argument("--rc", dest=Params.parameters["rc"]["cmd"], help=Params.parameters["rc"]["help"], choices=Params.parameters["rc"]["choices"], action="store") resp_options.add_argument("--cantpro", dest=Params.parameters["cantpro"]["cmd"], help=Params.parameters["cantpro"]["help"], action="store", type=int, metavar="1-32") resp_options.add_argument("--cantco", dest=Params.parameters["cantco"]["cmd"], help=Params.parameters["cantco"]["help"], choices=Params.parameters["cantco"]["choices"], action="store") resp_options.add_argument("--reply-amp", dest=Params.parameters["replyamp"]["cmd"], help=Params.parameters["replyamp"]["help"], action="store") # ===================================================================================== # ===================================================================================== # Reference Message Data Group Arguments # ref_msg_options = parser.add_argument_group( "Reference Message Data Group", "Fields of the reference message data group.") ref_msg_options.add_argument("--ref-urn", dest=Params.parameters["ref_urn"]["cmd"], help=Params.parameters["ref_urn"]["help"], metavar="URN", action="store") ref_msg_options.add_argument("--ref-unit", dest=Params.parameters["ref_unitname"]["cmd"], help=Params.parameters["ref_unitname"]["help"], metavar="STRING", action="store") ref_msg_options.add_argument("--ref-dtg", dest=Params.parameters["refdtg"]["cmd"], help=Params.parameters["refdtg"]["help"], action="store", metavar="YYYY-MM-DD HH:mm[:ss] [extension]") # ===================================================================================== # ===================================================================================== # Message Security Data Group Arguments # msg_sec_grp = parser.add_argument_group( "Message Security Group", "Fields of the message security group.") msg_sec_grp.add_argument("--sec-param", dest=Params.parameters["secparam"]["cmd"], help=Params.parameters["secparam"]["help"], choices=Params.parameters["secparam"]["choices"], action="store") msg_sec_grp.add_argument("--keymat-len", dest=Params.parameters["keymatlen"]["cmd"], help=Params.parameters["keymatlen"]["help"], action="store", type=int) msg_sec_grp.add_argument("--keymat-id", dest=Params.parameters["keymatid"]["cmd"], help=Params.parameters["keymatid"]["help"], action="store", type=int) msg_sec_grp.add_argument("--crypto-init-len", dest=Params.parameters["crypto_init_len"]["cmd"], help=Params.parameters["crypto_init_len"]["help"], action="store", type=int) msg_sec_grp.add_argument("--crypto-init", dest=Params.parameters["crypto_init"]["cmd"], help=Params.parameters["crypto_init"]["help"], action="store", type=int) msg_sec_grp.add_argument("--keytok-len", dest=Params.parameters["keytok_len"]["cmd"], help=Params.parameters["keytok_len"]["help"], action="store", type=int) msg_sec_grp.add_argument("--keytok", dest=Params.parameters["keytok"]["cmd"], help=Params.parameters["keytok"]["help"], action="store", type=int) msg_sec_grp.add_argument("--autha-len", dest=Params.parameters["autha-len"]["cmd"], help=Params.parameters["autha-len"]["help"], action="store", type=int, metavar="LENGTH") msg_sec_grp.add_argument("--authb-len", dest=Params.parameters["authb-len"]["cmd"], help=Params.parameters["authb-len"]["help"], action="store", type=int, metavar="LENGTH") msg_sec_grp.add_argument("--autha", dest=Params.parameters["autha"]["cmd"], help=Params.parameters["autha"]["help"], action="store", type=int) msg_sec_grp.add_argument("--authb", dest=Params.parameters["authb"]["cmd"], help=Params.parameters["authb"]["help"], action="store", type=int) msg_sec_grp.add_argument("--ack-signed", dest=Params.parameters["acksigned"]["cmd"], help=Params.parameters["acksigned"]["help"], action="store_true") msg_sec_grp.add_argument("--pad-len", dest=Params.parameters["pad_len"]["cmd"], help=Params.parameters["pad_len"]["help"], action="store", type=int, metavar="LENGTH") msg_sec_grp.add_argument("--padding", dest=Params.parameters["padding"]["cmd"], help=Params.parameters["padding"]["help"], action="store", type=int) # ============================================================================= #////////////////////////////////////////////////////////////////////////////// class VmfShell(object): """ Interative shell to Vmfcat. The shell can be use to build a VMF message. """ CMD_SAVE = 'save' CMD_LOAD = 'load' CMD_SEARCH = 'search' CMD_SET = 'set' CMD_SHOW = 'show' CMD_HEADER = 'header' CMD_HELP = 'help' CMD_QUIT = 'quit' PROMPT = "<<< " def __init__(self, _output=sys.stdout): """ Initializes the user interface by defining a Logger object and defining the standard output. """ self.output = _output self.logger = Logger(_output, _debug=True) def start(self): """ Starts the main loop of the interactive shell. """ # Command entered by the user cmd = "" self.logger.print_info("Type 'help' to show a list of available commands.") while (cmd.lower() != VmfShell.CMD_QUIT): try: self.output.write(VmfShell.PROMPT) user_input = sys.stdin.readline() tokens = user_input.rstrip().split() cmd = tokens[0] if (cmd.lower() == VmfShell.CMD_QUIT): pass elif (cmd.lower() == VmfShell.CMD_HELP): if (len(tokens) == 1): self.logger.print_info("{:s} <field>|all".format(VmfShell.CMD_SHOW)) self.logger.print_info("{:s} <field> <value>".format(VmfShell.CMD_SET)) self.logger.print_info("{:s} [field] {{bin, hex}}".format(VmfShell.CMD_HEADER)) self.logger.print_info("{:s} <field>".format(VmfShell.CMD_HELP)) self.logger.print_info("{:s} <field>".format(VmfShell.CMD_SEARCH)) self.logger.print_info("{:s} <file>".format(VmfShell.CMD_SAVE)) self.logger.print_info("{:s} <file>".format(VmfShell.CMD_LOAD)) self.logger.print_info("{:s}".format(VmfShell.CMD_QUIT)) else: param = tokens[1] if (param in Params.__dict__.keys()): help_msg = Params.parameters[param]['help'] self.logger.print_info(help_msg) if (len(Params.parameters[param]['choices']) > 0): choices_msg = ', '.join([ choice for choice in Params.parameters[param]['choices']]) self.logger.print_info("Available values: {:s}".format(choices_msg)) else: self.logger.print_error("Unknown parameter/option: {:s}.".format(param)) elif (cmd.lower() == VmfShell.CMD_SHOW): # # Displays the value of the given field # if (len(tokens) == 2): param = tokens[1] if (param in Params.parameters.keys()): value = Params.__dict__[param] if (isinstance(value, int)): value = "0x{:02x}".format(value) self.logger.print_info("{} = {}".format(param, value)) elif param.lower() == "all": for p in Params.parameters.keys(): value = Params.__dict__[p] self.logger.print_info("{} = {}".format(p, value)) else: self.logger.print_error("Unknown parameter/option {:s}.".format(param)) else: self.logger.print_error("Usage: {s} <field>".format(VmfShell.CMD_SHOW)) elif (cmd.lower() == VmfShell.CMD_SET): # # Sets a field with the given value # # TODO: Issues with parameters with boolean values if (len(tokens) >= 3): param = tokens[1] value = ' '.join(tokens[2:]) if (param in Params.__dict__.keys()): if (Params.parameters[param]["choices"]): if (value in Params.parameters[param]["choices"]): Params.__dict__[param] = value new_value = Params.__dict__[param] self.logger.print_success("{:s} = {:s}".format(param, new_value)) else: self.logger.print_error("Invalid value ({:s}) for field {:s}.".format(value, param)) self.logger.print_info("Values for field are : {:s}.".format(','.join(str(Params.parameters[param]["choices"])))) else: Params.__dict__[param] = value new_value = Params.__dict__[param] self.logger.print_success("{:s} = {:s}".format(param, new_value)) else: self.logger.print_error("Unknown parameter {:s}.".format(param)) else: self.logger.print_error("Usage: {:s} <field> <value>".format(VmfShell.CMD_SET)) elif (cmd.lower() == VmfShell.CMD_HEADER): field = "vmfversion" fmt = "bin" if (len(tokens) >= 2): field = tokens[1] if (len(tokens) == 3): fmt = tokens[2] vmf_factory = Factory(_logger=self.logger) vmf_message = vmf_factory.new_message(Params) vmf_elem = vmf_message.header.elements[field] if (isinstance(vmf_elem, Field)): vmf_value = vmf_elem.value elif (isinstance(vmf_elem, Group)): vmf_value = "n/a" else: raise Exception("Unknown type for element '{:s}'.".format(field)) vmf_bits = vmf_elem.get_bit_array() output = vmf_bits if (fmt == "bin"): output = vmf_bits.bin if (fmt == "hex"): output = vmf_bits.hex self.logger.print_success("{}\t{}\t{}".format(field, vmf_value, output)) elif (cmd.lower() == VmfShell.CMD_SEARCH): keyword = ' '.join(tokens[1:]).lower() for p in Params.parameters.keys(): help = Params.parameters[p]['help'] if (p.lower() == keyword or keyword in help.lower()): self.logger.print_success("{:s}: {:s}".format(p, help)) elif (cmd.lower() == VmfShell.CMD_SAVE): if len(tokens) == 2: file = tokens[1] tmpdict = {} for param in Params.parameters.keys(): value = Params.__dict__[param] tmpdict[param] = value with open(file, 'w') as f: json.dump(tmpdict, f) self.logger.print_success("Saved VMF message to {:s}.".format(file)) else: self.logger.print_error("Specify a file to save the configuration to.") elif (cmd.lower() == "test"): if (len(tokens) == 2): vmf_params = tokens[1] else: vmf_params = '0x4023' s = BitStream(vmf_params) bstream = BitStream('0x4023') vmf_factory = Factory(_logger=self.logger) vmf_message = vmf_factory.read_message(bstream) elif (cmd.lower() == VmfShell.CMD_LOAD): if len(tokens) == 2: file = tokens[1] with open(file, 'r') as f: param_dict = json.load(f) for (param, value) in param_dict.iteritems(): Params.__dict__[param] = value self.logger.print_success("Loaded VMF message from {:s}.".format(file)) else: self.logger.print_error("Specify a file to load the configuration from.") else: self.logger.print_error("Unknown command {:s}.".format(cmd)) except Exception as e: self.logger.print_error("An exception as occured: {:s}".format(e.message)) traceback.print_exc(file=sys.stdout)
lgpl-3.0
vrichomme/posix4msvc
src/init_devblk.c
5258
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <Shlobj.h> #include <Shlwapi.h> #include <Strsafe.h> #include <sys/file.h> #include <stdint.h> #include <malloc.h> #include "windevblk.h" void init_devblk(void); void cleanup_devblk(void); #define ROOTFS "\\Smartmobili\\Posix4Win\\" typedef struct _root_name { CHAR name[MAX_PATH]; } root_name; root_name g_rootNames[] = { { "proc" }, { "dev" }, { "etc" }, }; typedef struct _proc_partitions { UINT major; UINT minor; ULONG blocks; CHAR name[128]; } proc_partitions; proc_partitions g_ProcPartions[] = { { 1 , 0 , 65536, "ram0" }, { 1 , 1 , 65536, "ram1" }, { 1 , 2 , 65536, "ram2" }, { 1 , 3 , 65536, "ram3" }, { 1 , 4 , 65536, "ram4" }, { 1 , 5 , 65536, "ram5" }, { 1 , 6 , 65536, "ram6" }, { 1 , 7 , 65536, "ram7" }, { 1 , 8 , 65536, "ram8" }, { 1 , 9 , 65536, "ram9" }, { 1 , 10 , 65536, "ram10" }, { 1 , 11 , 65536, "ram11" }, { 1 , 12 , 65536, "ram12" }, { 1 , 13 , 65536, "ram13" }, { 1 , 14 , 65536, "ram14" }, { 1 , 15 , 65536, "ram15" }, { 11 , 0 , 1048575, "sr0" }, { 8 , 0 , 125034840, "sda" }, { 8 , 1 , 102400, "sda1" }, { 8 , 2 , 95666195, "sda2" }, { 8 , 3 , 1, "sda3" }, { 8 , 5 , 3142656, "sda5" }, { 8 , 6 , 26121216, "sda6" }, { 8 , 16 , 2014208, "sdb" }, { 8 , 17 , 204800, "sdb1" }, { 8 , 18 , 51200, "sdb2" }, { 8 , 19 , 51200, "sdb3" }, { 8 , 20 , 51200, "sdb4" }, { 8 , 21 , 51200, "sdb5" }, { 8 , 22 , 51200, "sdb6" }, { 8 , 23 , 51200, "sdb7" }, }; BOOL FolderExists(LPTSTR pszPath) { BOOL bRet = FALSE; DWORD dwAttr = GetFileAttributes(pszPath); if (dwAttr != INVALID_FILE_ATTRIBUTES && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) { bRet = TRUE; } return bRet; } BOOL CreateFolderIfNotExists(LPTSTR pszPath) { BOOL bRet = FALSE; if (FolderExists(pszPath)) { bRet = TRUE; } else { if (SUCCEEDED(SHCreateDirectoryEx(NULL,pszPath, NULL))) { bRet = TRUE; } } return bRet; } BOOL create_rootfs() { BOOL bRet = FALSE; TCHAR szPath[MAX_PATH]; TCHAR szRootPath[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szRootPath))) { PathAppend(szRootPath, TEXT(ROOTFS)); for (int i = 0; i < _countof(g_rootNames); i++) { StringCchCopy(szPath, MAX_PATH, szRootPath); PathAppend(szPath, g_rootNames[i].name); CreateFolderIfNotExists(szPath); } bRet = TRUE; } return bRet; } void init_devblk(void) { BOOL bRet; DWORD dwcbNeeded, dwCount; TCHAR szProcPartPath[MAX_PATH]; TCHAR szBuffer[MAX_PATH]; TCHAR szBlockName[MAX_PATH]; int fd, lock; int blocks, major, minor; FILE* f; bRet = create_rootfs(); if (bRet) { bRet = DevBlkEnumDevices(NULL, 0, &dwcbNeeded, NULL); if (bRet) { SMI_DEVBLK_INFO* pDriveInfoArray = malloc(dwcbNeeded); bRet = DevBlkEnumDevices((LPBYTE)pDriveInfoArray, dwcbNeeded, &dwcbNeeded, &dwCount); if (bRet) { SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szProcPartPath); PathAppend(szProcPartPath, TEXT(ROOTFS)); PathAppend(szProcPartPath, TEXT("proc")); PathAppend(szProcPartPath, TEXT("partitions")); FILE* f = fopen(szProcPartPath, "w+"); int lock = flock(_fileno(f), LOCK_SH); //fd = open(szProcPartPath, O_CREAT | O_TRUNC); //int lock = flock(fd, LOCK_SH); if (lock == 0) { fprintf(f, "major minor #blocks name\n"); fprintf(f, "\n"); for (int i = 0; i < dwCount; i++) { PSMI_DEVBLK_INFO pEntry = &(pDriveInfoArray[i]); if (pEntry) { major = major(pEntry->RootDev); minor = minor(pEntry->RootDev); blocks = pEntry->PartitionLength.QuadPart / 1024; fprintf(f, "%4d %8d %10d %s\n", major, minor, blocks, pEntry->PosixName); //OutputDebugString(""); } } lock = flock(_fileno(f), LOCK_UN); fclose(f); } } } } } void cleanup_devblk(void) { }
lgpl-3.0
jbzdak/query-builder
sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/expression/BinaryExpressionType.java
1760
/* * Copyright (c) 2011 for Jacek Bzdak * * This file is part of query builder. * * Query builder 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. * * Query builder 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 Query builder. If not, see <http://www.gnu.org/licenses/>. */ package cx.ath.jbzdak.sqlbuilder.expression; import fakeEnum.FakeEnum; import java.util.Collection; /** * Created by: Jacek Bzdak */ public class BinaryExpressionType { public static final String LIKE = "LIKE"; public static final String EQUALS = "="; public static final String NE = "<>"; public static final String LT = "<"; public static final String GT = ">"; public static final String LTE = "<="; public static final String GTE = ">="; public static final String IN = "IN"; public static final String MINUS = "-"; public static final String DIVIDE = "/"; public static final FakeEnum<String> FAKE_ENUM = new FakeEnum<String>(BinaryExpressionType.class, String.class); public static String nameOf(String value) { return FAKE_ENUM.nameOf(value); } public static Collection<? extends String> values() { return FAKE_ENUM.values(); } public static String valueOf(String s) { return FAKE_ENUM.valueOf(s); } }
lgpl-3.0
noahvans/mariadb-connector-net
Legacy/Tests/MariaDB.Web.Tests/UserManagement.cs
23494
// 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; 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 Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using NUnit.Framework; using System.Web.Security; using System.Collections.Specialized; using System.Data; using System; using System.Configuration.Provider; using MariaDB.Web.Security; using MariaDB.Data.MySqlClient; namespace MariaDB.Web.Tests { [TestFixture] public class UserManagement : BaseWebTest { private MySQLMembershipProvider provider; [SetUp] public override void Setup() { base.Setup(); execSQL("DROP TABLE IF EXISTS mysql_membership"); } private void CreateUserWithFormat(MembershipPasswordFormat format) { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", format.ToString()); provider.Initialize(null, config); // create the user MembershipCreateStatus status; provider.CreateUser("foo", "barbar!", "[email protected]", null, null, true, null, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); // verify that the password format is hashed. DataTable table = FillTable("SELECT * FROM my_aspnet_Membership"); MembershipPasswordFormat rowFormat = (MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]); Assert.AreEqual(format, rowFormat); // then attempt to verify the user Assert.IsTrue(provider.ValidateUser("foo", "barbar!")); } [Test] public void CreateUserWithHashedPassword() { CreateUserWithFormat(MembershipPasswordFormat.Hashed); } [Test] public void CreateUserWithEncryptedPasswordWithAutoGenKeys() { try { CreateUserWithFormat(MembershipPasswordFormat.Encrypted); } catch (ProviderException) { } } [Test] public void CreateUserWithClearPassword() { CreateUserWithFormat(MembershipPasswordFormat.Clear); } /// <summary> /// Bug #34792 New User/Changing Password Validation Not working. /// </summary> [Test] public void ChangePassword() { CreateUserWithHashedPassword(); try { provider.ChangePassword("foo", "barbar!", "bar2"); Assert.Fail(); } catch (ArgumentException ae1) { Assert.AreEqual("newPassword", ae1.ParamName); Assert.IsTrue(ae1.Message.Contains("length of parameter")); } try { provider.ChangePassword("foo", "barbar!", "barbar2"); Assert.Fail(); } catch (ArgumentException ae1) { Assert.AreEqual("newPassword", ae1.ParamName); Assert.IsTrue(ae1.Message.Contains("alpha numeric")); } // now test regex strength testing bool result = provider.ChangePassword("foo", "barbar!", "zzzxxx!"); Assert.IsFalse(result); // now do one that should work result = provider.ChangePassword("foo", "barbar!", "barfoo!"); Assert.IsTrue(result); provider.ValidateUser("foo", "barfoo!"); } /// <summary> /// Bug #34792 New User/Changing Password Validation Not working. /// </summary> [Test] public void CreateUserWithErrors() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Hashed"); provider.Initialize(null, config); // first try to create a user with a password not long enough MembershipCreateStatus status; MembershipUser user = provider.CreateUser("foo", "xyz", "[email protected]", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now with not enough non-alphas user = provider.CreateUser("foo", "xyz1234", "[email protected]", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now one that doesn't pass the regex test user = provider.CreateUser("foo", "xyzxyz!", "[email protected]", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now one that works user = provider.CreateUser("foo", "barbar!", "[email protected]", null, null, true, null, out status); Assert.IsNotNull(user); Assert.AreEqual(MembershipCreateStatus.Success, status); } [Test] public void DeleteUser() { CreateUserWithHashedPassword(); Assert.IsTrue(provider.DeleteUser("foo", true)); DataTable table = FillTable("SELECT * FROM my_aspnet_Membership"); Assert.AreEqual(0, table.Rows.Count); table = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(0, table.Rows.Count); CreateUserWithHashedPassword(); provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); provider.Initialize(null, config); Assert.IsTrue(Membership.DeleteUser("foo", false)); table = FillTable("SELECT * FROM my_aspnet_Membership"); Assert.AreEqual(0, table.Rows.Count); table = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(1, table.Rows.Count); } [Test] public void FindUsersByName() { CreateUserWithHashedPassword(); int records; MembershipUserCollection users = provider.FindUsersByName("F%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); } [Test] public void FindUsersByEmail() { CreateUserWithHashedPassword(); int records; MembershipUserCollection users = provider.FindUsersByEmail("[email protected]", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); } [Test] public void TestCreateUserOverrides() { try { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); int records; MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); Membership.CreateUser("test", "barbar!", "[email protected]", "question", "answer", true, out status); users = Membership.FindUsersByName("T%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("test", users["test"].UserName); } catch (Exception ex) { Assert.Fail(ex.Message); } } [Test] public void NumberOfUsersOnline() { int numOnline = Membership.GetNumberOfUsersOnline(); Assert.AreEqual(0, numOnline); MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); Membership.CreateUser("foo2", "barbar!", null, "question", "answer", true, out status); numOnline = Membership.GetNumberOfUsersOnline(); Assert.AreEqual(2, numOnline); } [Test] public void UnlockUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); Assert.IsFalse(Membership.ValidateUser("foo", "bar2")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); // the user should be locked now so the right password should fail Assert.IsFalse(Membership.ValidateUser("foo", "barbar!")); MembershipUser user = Membership.GetUser("foo"); Assert.IsTrue(user.IsLockedOut); Assert.IsTrue(user.UnlockUser()); user = Membership.GetUser("foo"); Assert.IsFalse(user.IsLockedOut); Assert.IsTrue(Membership.ValidateUser("foo", "barbar!")); } [Test] public void GetUsernameByEmail() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "[email protected]", "question", "answer", true, out status); string username = Membership.GetUserNameByEmail("[email protected]"); Assert.AreEqual("foo", username); username = Membership.GetUserNameByEmail("[email protected]"); Assert.IsNull(username); username = Membership.GetUserNameByEmail(" [email protected] "); Assert.AreEqual("foo", username); } [Test] public void UpdateUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "[email protected]", "color", "blue", true, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); MembershipUser user = Membership.GetUser("foo"); user.Comment = "my comment"; user.Email = "my email"; user.IsApproved = false; user.LastActivityDate = new DateTime(2008, 1, 1); user.LastLoginDate = new DateTime(2008, 2, 1); Membership.UpdateUser(user); MembershipUser newUser = Membership.GetUser("foo"); Assert.AreEqual(user.Comment, newUser.Comment); Assert.AreEqual(user.Email, newUser.Email); Assert.AreEqual(user.IsApproved, newUser.IsApproved); Assert.AreEqual(user.LastActivityDate, newUser.LastActivityDate); Assert.AreEqual(user.LastLoginDate, newUser.LastLoginDate); } private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA) { try { user.ChangePasswordQuestionAndAnswer(pw, newQ, newA); Assert.Fail("This should not work."); } catch (ArgumentNullException ane) { Assert.AreEqual("password", ane.ParamName); } catch (ArgumentException) { Assert.IsNotNull(pw); } } [Test] public void ChangePasswordQuestionAndAnswer() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "[email protected]", "color", "blue", true, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); MembershipUser user = Membership.GetUser("foo"); ChangePasswordQAHelper(user, "", "newQ", "newA"); ChangePasswordQAHelper(user, "barbar!", "", "newA"); ChangePasswordQAHelper(user, "barbar!", "newQ", ""); ChangePasswordQAHelper(user, null, "newQ", "newA"); bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA"); Assert.IsTrue(result); user = Membership.GetUser("foo"); Assert.AreEqual("newQ", user.PasswordQuestion); } [Test] public void GetAllUsers() { MembershipCreateStatus status; // first create a bunch of users for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null, "question", "answer", true, out status); MembershipUserCollection users = Membership.GetAllUsers(); Assert.AreEqual(100, users.Count); int index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo{0}", index++), user.UserName); int total; users = Membership.GetAllUsers(2, 10, out total); Assert.AreEqual(10, users.Count); Assert.AreEqual(100, total); index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName); } private void GetPasswordHelper(bool requireQA, bool enablePasswordRetrieval, string answer) { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", requireQA ? "true" : "false"); config.Add("enablePasswordRetrieval", enablePasswordRetrieval ? "true" : "false"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); config.Add("writeExceptionsToEventLog", "false"); provider.Initialize(null, config); provider.CreateUser("foo", "barbar!", "[email protected]", "color", "blue", true, null, out status); try { string password = provider.GetPassword("foo", answer); if (!enablePasswordRetrieval) Assert.Fail("This should have thrown an exception"); Assert.AreEqual("barbar!", password); } catch (MembershipPasswordException) { if (requireQA && answer != null) Assert.Fail("This should not have thrown an exception"); } catch (ProviderException) { if (requireQA && answer != null) Assert.Fail("This should not have thrown an exception"); } } [Test] public void GetPassword() { GetPasswordHelper(false, false, null); GetPasswordHelper(false, true, null); GetPasswordHelper(true, true, null); GetPasswordHelper(true, true, "blue"); } /// <summary> /// Bug #38939 MembershipUser.GetPassword(string answer) fails when incorrect answer is passed. /// </summary> [Test] public void GetPasswordWithWrongAnswer() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "true"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "Encrypted"); config.Add("applicationName", "/"); provider.Initialize(null, config); provider.CreateUser("foo", "barbar!", "[email protected]", "color", "blue", true, null, out status); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("requiresQuestionAndAnswer", "true"); config2.Add("enablePasswordRetrieval", "true"); config2.Add("passwordFormat", "Encrypted"); config2.Add("applicationName", "/"); provider2.Initialize(null, config2); try { string pw = provider2.GetPassword("foo", "wrong"); Assert.Fail("Should have failed"); } catch (MembershipPasswordException) { } } [Test] public void GetUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); MembershipUser user = Membership.GetUser(1); Assert.AreEqual("foo", user.UserName); // now move the activity date back outside the login // window user.LastActivityDate = new DateTime(2008, 1, 1); Membership.UpdateUser(user); user = Membership.GetUser("foo"); Assert.IsFalse(user.IsOnline); user = Membership.GetUser("foo", true); Assert.IsTrue(user.IsOnline); // now move the activity date back outside the login // window again user.LastActivityDate = new DateTime(2008, 1, 1); Membership.UpdateUser(user); user = Membership.GetUser(1); Assert.IsFalse(user.IsOnline); user = Membership.GetUser(1, true); Assert.IsTrue(user.IsOnline); } [Test] public void FindUsers() { MembershipCreateStatus status; for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("boo{0}", i), "barbar!", null, "question", "answer", true, out status); for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null, "question", "answer", true, out status); for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("schmoo{0}", i), "barbar!", null, "question", "answer", true, out status); MembershipUserCollection users = Membership.FindUsersByName("fo%"); Assert.AreEqual(100, users.Count); int total; users = Membership.FindUsersByName("fo%", 2, 10, out total); Assert.AreEqual(10, users.Count); Assert.AreEqual(100, total); int index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName); } [Test] public void CreateUserWithNoQA() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "true"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); provider.Initialize(null, config); try { provider.CreateUser("foo", "barbar!", "[email protected]", "color", null, true, null, out status); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("Password answer supplied is invalid")); } try { provider.CreateUser("foo", "barbar!", "[email protected]", "", "blue", true, null, out status); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("Password question supplied is invalid")); } } [Test] public void MinRequiredAlpha() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("minRequiredNonalphanumericCharacters", "3"); provider.Initialize(null, config); MembershipCreateStatus status; MembershipUser user = provider.CreateUser("foo", "pw!pass", "email", null, null, true, null, out status); Assert.IsNull(user); user = provider.CreateUser("foo", "pw!pa!!", "email", null, null, true, null, out status); Assert.IsNotNull(user); } /// <summary> /// Bug #35332 GetPassword() don't working (when PasswordAnswer is NULL) /// </summary> [Test] public void GetPasswordWithNullValues() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "false"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); provider.Initialize(null, config); MembershipUser user = provider.CreateUser("foo", "barbar!", "[email protected]", null, null, true, null, out status); Assert.IsNotNull(user); string pw = provider.GetPassword("foo", null); Assert.AreEqual("barbar!", pw); } /// <summary> /// Bug #35336 GetPassword() return wrong password (when format is encrypted) /// </summary> [Test] public void GetEncryptedPassword() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "false"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "encrypted"); config.Add("applicationName", "/"); provider.Initialize(null, config); MembershipUser user = provider.CreateUser("foo", "barbar!", "[email protected]", null, null, true, null, out status); Assert.IsNotNull(user); string pw = provider.GetPassword("foo", null); Assert.AreEqual("barbar!", pw); } /// <summary> /// Bug #42574 ValidateUser does not use the application id, allowing cross application login /// </summary> [Test] public void CrossAppLogin() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("applicationName", "/myapp"); config2.Add("passwordStrengthRegularExpression", ".*"); config2.Add("passwordFormat", "Clear"); provider2.Initialize(null, config2); bool worked = provider2.ValidateUser("foo", "bar!bar"); Assert.AreEqual(false, worked); } /// <summary> /// Bug #41408 PasswordReset not possible when requiresQuestionAndAnswer="false" /// </summary> [Test] public void ResetPassword() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); config.Add("requiresQuestionAndAnswer", "false"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); MembershipUser u = provider.GetUser("foo", false); string newpw = provider.ResetPassword("foo", null); } /// <summary> /// Bug #59438 setting Membership.ApplicationName has no effect /// </summary> [Test] public void ChangeAppName() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); Assert.IsTrue(status == MembershipCreateStatus.Success); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("applicationName", "/myapp"); config2.Add("passwordStrengthRegularExpression", "foo.*"); config2.Add("passwordFormat", "Clear"); provider2.Initialize(null, config2); provider2.CreateUser("foo2", "foo!foo", null, null, null, true, null, out status); Assert.IsTrue(status == MembershipCreateStatus.Success); provider.ApplicationName = "/myapp"; Assert.IsFalse(provider.ValidateUser("foo", "bar!bar")); Assert.IsTrue(provider.ValidateUser("foo2", "foo!foo")); } [Test] public void GetUserLooksForExactUsername() { MembershipCreateStatus status; Membership.CreateUser("code", "thecode!", null, "question", "answer", true, out status); MembershipUser user = Membership.GetUser("code"); Assert.AreEqual("code", user.UserName); user = Membership.GetUser("co_e"); Assert.IsNull(user); } [Test] public void GetUserNameByEmailLooksForExactEmail() { MembershipCreateStatus status; Membership.CreateUser("code", "thecode!", "[email protected]", "question", "answer", true, out status); string username = Membership.GetUserNameByEmail("[email protected]"); Assert.AreEqual("code", username); username = Membership.GetUserNameByEmail("[email protected]"); Assert.IsNull(username); } } }
lgpl-3.0
pcolby/libqtaws
src/route53resolver/listresolverquerylogconfigassociationsresponse.h
1772
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_LISTRESOLVERQUERYLOGCONFIGASSOCIATIONSRESPONSE_H #define QTAWS_LISTRESOLVERQUERYLOGCONFIGASSOCIATIONSRESPONSE_H #include "route53resolverresponse.h" #include "listresolverquerylogconfigassociationsrequest.h" namespace QtAws { namespace Route53Resolver { class ListResolverQueryLogConfigAssociationsResponsePrivate; class QTAWSROUTE53RESOLVER_EXPORT ListResolverQueryLogConfigAssociationsResponse : public Route53ResolverResponse { Q_OBJECT public: ListResolverQueryLogConfigAssociationsResponse(const ListResolverQueryLogConfigAssociationsRequest &request, QNetworkReply * const reply, QObject * const parent = 0); virtual const ListResolverQueryLogConfigAssociationsRequest * request() const Q_DECL_OVERRIDE; protected slots: virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(ListResolverQueryLogConfigAssociationsResponse) Q_DISABLE_COPY(ListResolverQueryLogConfigAssociationsResponse) }; } // namespace Route53Resolver } // namespace QtAws #endif
lgpl-3.0
SirmaITT/conservation-space-1.7.0
docker/sirma-platform/platform/seip-parent/model-management/definition-core/src/main/java/com/sirma/itt/seip/definition/InstancePropertyNameResolverImpl.java
2269
package com.sirma.itt.seip.definition; import java.lang.invoke.MethodHandles; import java.util.function.Function; import java.util.function.Supplier; import javax.enterprise.context.ContextNotActiveException; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sirma.itt.seip.domain.definition.DefinitionModel; import com.sirma.itt.seip.domain.definition.PropertyDefinition; import com.sirma.itt.seip.domain.instance.Instance; import com.sirma.itt.seip.domain.instance.InstancePropertyNameResolver; /** * Default implementation of the {@link InstancePropertyNameResolver} that uses a request scoped cache to store already * resolved definitions for an instance in order to provide better performance. If request context is not available * then the resolver will fall back to on demand definition lookup. * * @author <a href="mailto:[email protected]">Borislav Bonev</a> * @since 19/07/2018 */ public class InstancePropertyNameResolverImpl implements InstancePropertyNameResolver { private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Inject private DefinitionService definitionService; @Inject private InstancePropertyNameResolverCache cache; @Override public String resolve(Instance instance, String fieldUri) { return getOrResolveModel(instance) .getField(fieldUri) .map(PropertyDefinition::getName) .orElse(fieldUri); } private DefinitionModel getOrResolveModel(Instance instance) { try { return cache.getOrResolveModel(instance.getId(), resolveDefinition(instance)); } catch (ContextNotActiveException e) { // for the cases when this is used outside of a transaction like parallel stream processing return resolveDefinition(instance).get(); } } @Override public Function<String, String> resolverFor(Instance instance) { DefinitionModel model = getOrResolveModel(instance); return property -> model.getField(property) .map(PropertyDefinition::getName) .orElse(property); } private Supplier<DefinitionModel> resolveDefinition(Instance instance) { return () -> { LOGGER.trace("Resolving model for {}", instance.getId()); return definitionService.getInstanceDefinition(instance); }; } }
lgpl-3.0
andrepuschmann/iris_fll_modules
components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp
9079
/** * \file components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp * \version 1.0 * * \section COPYRIGHT * * Copyright 2012 The Iris Project Developers. See the * COPYRIGHT file at the top-level directory of this distribution * and at http://www.softwareradiosystems.com/iris/copyright.html. * * \section LICENSE * * This file is part of the Iris Project. * * Iris 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. * * Iris 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. * * A copy of the GNU General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * * \section DESCRIPTION * * Implementation of a mobility protocol that has a coordinator that * determines a backup channel for a set of follower nodes. * */ #include "irisapi/LibraryDefs.h" #include "irisapi/Version.h" #include "CoordinatorMobilityComponent.h" using namespace std; using namespace boost; namespace iris { // export library symbols IRIS_COMPONENT_EXPORTS(StackComponent, CoordinatorMobilityComponent); CoordinatorMobilityComponent::CoordinatorMobilityComponent(std::string name) : FllStackComponent(name, "coordinatorcstackcomponent", "A very simple mobility protocol with coordinator/follower roles", "Andre Puschmann", "0.1") { //Format: registerParameter(name, description, default, dynamic?, parameter, allowed values); registerParameter("role", "Role of node", "coordinator", false, role_x); registerParameter("updateinterval", "Interval between BC updates", "1000", true, updateInterval_x); registerParameter("querydrm", "Whether to use DRM to determine backupchannel", "false", true, queryDrm_x); //Format: registerEvent(name, description, data type); registerEvent("EvGetAvailableChannelsRequest", "Retrieve list of available channels from FllController", TypeInfo< int32_t >::identifier); registerEvent("EvGetOperatingChannelRequest", "Retrieve current operating channel from FllController", TypeInfo< int32_t >::identifier); registerEvent("EvUpdateBackupChannel", "Set new backup channel", TypeInfo< int32_t >::identifier); } CoordinatorMobilityComponent::~CoordinatorMobilityComponent() { } void CoordinatorMobilityComponent::initialize() { // turn off logging to file, system will take care of closing file handle //LoggingPolicy::getPolicyInstance()->setFileStream(NULL); } void CoordinatorMobilityComponent::processMessageFromAbove(boost::shared_ptr<StackDataSet> incomingFrame) { //StackHelper::printDataset(incomingFrame, "vanilla from above"); } void CoordinatorMobilityComponent::processMessageFromBelow(boost::shared_ptr<StackDataSet> incomingFrame) { //StackHelper::printDataset(incomingFrame, "vanilla from below"); MobilityPacket updatePacket; StackHelper::deserializeAndStripDataset(incomingFrame, updatePacket); switch(updatePacket.type()) { case MobilityPacket::UPDATE_BC: { if (updatePacket.source() == MobilityPacket::COORDINATOR) { // take first channel in update packet as backup channel if (updatePacket.channelmap_size() > 0) { MobilityChannel *mobilityChannel = updatePacket.mutable_channelmap(0); FllChannel fllChannel = MobilityChannelToFllChannel(mobilityChannel); LOG(LINFO) << "Received new backup channel from coordinator: " << fllChannel.getFreq() << "Hz."; setBackupChannel(fllChannel); } } break; } default: LOG(LERROR) << "Undefined packet type."; break; } // switch } void CoordinatorMobilityComponent::start() { // start beaconing thread in coordinator mode LOG(LINFO) << "I am a " << role_x << " node."; if (role_x == "coordinator") { LOG(LINFO) << "Start beaconing thread .."; beaconingThread_.reset(new boost::thread(boost::bind( &CoordinatorMobilityComponent::beaconingThreadFunction, this))); } else if (role_x == "follower") { LOG(LINFO) << "I am waiting for beacons .."; } else { LOG(LERROR) << "Mode is not defined: " << role_x; } FllChannelVector channels = getAvailableChannels(); LOG(LINFO) << "No of channels: " << channels.size(); } void CoordinatorMobilityComponent::stop() { // stop threads if (beaconingThread_) { beaconingThread_->interrupt(); beaconingThread_->join(); } } void CoordinatorMobilityComponent::beaconingThreadFunction() { boost::this_thread::sleep(boost::posix_time::seconds(1)); LOG(LINFO) << "Beaconing thread started."; try { while(true) { boost::this_thread::interruption_point(); // determine backup channel and transmit beacon FllChannel bc; if (findBackupChannel(bc) == true) { setBackupChannel(bc); sendUpdateBackupChannelPacket(bc); } // sleep until next beacon boost::this_thread::sleep(boost::posix_time::milliseconds(updateInterval_x)); } // while } catch(IrisException& ex) { LOG(LFATAL) << "Error in CoordinatorMobility component: " << ex.what() << " - Beaconing thread exiting."; } catch(boost::thread_interrupted) { LOG(LINFO) << "Thread " << boost::this_thread::get_id() << " in stack component interrupted."; } } void CoordinatorMobilityComponent::sendUpdateBackupChannelPacket(FllChannel backupChannel) { MobilityPacket updatePacket; updatePacket.set_source(MobilityPacket::COORDINATOR); updatePacket.set_destination(MobilityPacket::FOLLOWER); updatePacket.set_type(MobilityPacket::UPDATE_BC); MobilityChannel *channel = updatePacket.add_channelmap(); FllChannelToMobilityChannel(backupChannel, channel); shared_ptr<StackDataSet> buffer(new StackDataSet); StackHelper::mergeAndSerializeDataset(buffer, updatePacket); //StackHelper::printDataset(buffer, "UpdateBC packet Tx"); sendDownwards(buffer); LOG(LINFO) << "Tx UpdateBC packet "; } void CoordinatorMobilityComponent::FllChannelToMobilityChannel(const FllChannel fllchannel, MobilityChannel *mobilityChannel) { mobilityChannel->set_f_center(fllchannel.getFreq()); mobilityChannel->set_bandwidth(fllchannel.getBandwidth()); switch (fllchannel.getState()) { case FREE: mobilityChannel->set_status(MobilityChannel_Status_FREE); break; case BUSY_SU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_SU); break; case BUSY_PU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_PU); break; default: LOG(LERROR) << "Unknown channel state."; } } FllChannel CoordinatorMobilityComponent::MobilityChannelToFllChannel(MobilityChannel *mobilityChannel) { FllChannel channel; channel.setFreq(mobilityChannel->f_center()); channel.setBandwidth(mobilityChannel->bandwidth()); switch (mobilityChannel->status()) { case MobilityChannel_Status_FREE: channel.setState(FREE); break; case MobilityChannel_Status_BUSY_SU: channel.setState(BUSY_SU); break; case MobilityChannel_Status_BUSY_PU: channel.setState(BUSY_PU); break; default: LOG(LERROR) << "Unknown channel state."; } return channel; } bool CoordinatorMobilityComponent::findBackupChannel(FllChannel& bc) { FllChannelVector channels = getAvailableChannels(); FllChannel operatingChannel = getOperatingChannel(0); // get operating channel of primary receiver, i.e. trx 0 #if OSPECORR if (queryDrm_x) { bool ret = FllDrmHelper::getChannel(bc); if (ret == true && bc != operatingChannel) { // success, got valid backup channel from DRM LOG(LINFO) << "Got backup channel at " << bc.getFreq() << " from DRM."; return true; } else { return false; } } #endif // find free channel other than operating channel in set of available channels FllChannelVector::iterator it; bool channelFound = false; for (it = channels.begin(); it != channels.end(); ++it) { if (it->getState() == FREE && *it != operatingChannel) { LOG(LINFO) << "Free channel found: " << it->getFreq() << "Hz."; bc = *it; channelFound = true; break; } } if (not channelFound) { LOG(LERROR) << "No free backup channel found. Skip update."; } return channelFound; } } /* namespace iris */
lgpl-3.0
luca1897/Lte-Game-Engine
src/CMetaTriangleSelector.h
2919
/* * LTE Game Engine * Copyright (C) 2006-2008 SiberianSTAR <[email protected]> * http://www.ltestudios.com * * The LTE Game Engine is based on Irrlicht 1.0 * Irrlicht Engine is Copyright (C) 2002-2006 Nikolaus Gebhardt * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ #ifndef __C_META_TRIANGLE_SELECTOR_H_INCLUDED__ #define __C_META_TRIANGLE_SELECTOR_H_INCLUDED__ #include "IMetaTriangleSelector.h" #include "engineArray.h" namespace engine { namespace scene { //! Interface for making multiple triangle selectors work as one big selector. class CMetaTriangleSelector : public IMetaTriangleSelector { public: //! constructor CMetaTriangleSelector(); //! destructor virtual ~CMetaTriangleSelector(); //! Returns amount of all available triangles in this selector virtual s32 getTriangleCount() const; //! Gets all triangles. virtual void getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::matrix4* transform=0); //! Gets all triangles which lie within a specific bounding box. virtual void getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::aabbox3d<f32>& box, const core::matrix4* transform=0); //! Gets all triangles which have or may have contact with a 3d line. virtual void getTriangles(core::triangle3df* triangles, s32 arraySize, s32& outTriangleCount, const core::line3d<f32>& line, const core::matrix4* transform=0); //! Adds a triangle selector to the collection of triangle selectors //! in this metaTriangleSelector. virtual void addTriangleSelector(ITriangleSelector* toAdd); //! Removes a specific triangle selector which was added before from the collection. virtual bool removeTriangleSelector(ITriangleSelector* toRemove); //! Removes all triangle selectors from the collection. virtual void removeAllTriangleSelectors(); private: core::array<ITriangleSelector*> TriangleSelectors; }; } // end namespace scene } // end namespace engine #endif
lgpl-3.0
OpenDA-Association/OpenDA
course/exercise_black_box_calibration_polution_NOT_WORKING/plot_cost.py
504
#! /usr/bin/python # -*- coding: utf-8 -*- """ Plot cost evolution @author: verlaanm """ # ex1 #load numpy and matplotlib if needed import matplotlib.pyplot as plt #load data import dud_results as dud # create plot of cost and parameter plt.close("all") f,ax = plt.subplots(2,1) ax[0].plot(dud.costTotal); ax[0].set_xlabel("model run"); ax[0].set_ylabel("cost function"); ax[1].plot(dud.evaluatedParameters); ax[1].set_xlabel('model run'); ax[1].set_ylabel('change of reaction\_time [seconds]');
lgpl-3.0
ethersphere/go-ethereum
network/stream/syncing_test.go
24602
// Copyright 2019 The Swarm Authors // This file is part of the Swarm library. // // The Swarm 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 3 of the License, or // (at your option) any later version. // // The Swarm library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the Swarm library. If not, see <http://www.gnu.org/licenses/>. package stream import ( "bytes" "context" "encoding/hex" "fmt" "io/ioutil" "os" "runtime" "sync" "testing" "time" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethersphere/swarm/chunk" "github.com/ethersphere/swarm/log" "github.com/ethersphere/swarm/network" "github.com/ethersphere/swarm/network/simulation" "github.com/ethersphere/swarm/p2p/protocols" "github.com/ethersphere/swarm/pot" "github.com/ethersphere/swarm/storage" "github.com/ethersphere/swarm/storage/localstore" "github.com/ethersphere/swarm/testutil" ) var timeout = 90 * time.Second // TestTwoNodesSyncWithGaps tests that syncing works with gaps in the localstore intervals func TestTwoNodesSyncWithGaps(t *testing.T) { // construct a pauser before simulation is started and reset it to nil after all streams are closed // to avoid the need for protecting handleMsgPauser with a lock in production code. handleMsgPauser = new(syncPauser) defer func() { handleMsgPauser = nil }() removeChunks := func(t *testing.T, ctx context.Context, store chunk.Store, gaps [][2]uint64, chunks []chunk.Address) (removedCount uint64) { t.Helper() for _, gap := range gaps { for i := gap[0]; i < gap[1]; i++ { c := chunks[i] if err := store.Set(ctx, chunk.ModeSetRemove, c); err != nil { t.Fatal(err) } removedCount++ } } return removedCount } for _, tc := range []struct { name string chunkCount uint64 gaps [][2]uint64 liveChunkCount uint64 liveGaps [][2]uint64 }{ { name: "no gaps", chunkCount: 100, gaps: nil, }, { name: "first chunk removed", chunkCount: 100, gaps: [][2]uint64{{0, 1}}, }, { name: "one chunk removed", chunkCount: 100, gaps: [][2]uint64{{60, 61}}, }, { name: "single gap at start", chunkCount: 100, gaps: [][2]uint64{{0, 5}}, }, { name: "single gap", chunkCount: 100, gaps: [][2]uint64{{5, 10}}, }, { name: "multiple gaps", chunkCount: 100, gaps: [][2]uint64{{0, 1}, {10, 21}}, }, { name: "big gaps", chunkCount: 100, gaps: [][2]uint64{{0, 1}, {10, 21}, {50, 91}}, }, { name: "remove all", chunkCount: 100, gaps: [][2]uint64{{0, 100}}, }, { name: "large db", chunkCount: 4000, }, { name: "large db with gap", chunkCount: 4000, gaps: [][2]uint64{{1000, 3000}}, }, { name: "live", liveChunkCount: 100, }, { name: "live and history", chunkCount: 100, liveChunkCount: 100, }, { name: "live and history with history gap", chunkCount: 100, gaps: [][2]uint64{{5, 10}}, liveChunkCount: 100, }, { name: "live and history with live gap", chunkCount: 100, liveChunkCount: 100, liveGaps: [][2]uint64{{105, 110}}, }, { name: "live and history with gaps", chunkCount: 100, gaps: [][2]uint64{{5, 10}}, liveChunkCount: 100, liveGaps: [][2]uint64{{105, 110}}, }, } { t.Run(tc.name, func(t *testing.T) { sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{ "bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}), }, false) defer sim.Close() defer catchDuplicateChunkSync(t)() ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() uploadNode, err := sim.AddNode() if err != nil { t.Fatal(err) } uploadStore := sim.MustNodeItem(uploadNode, bucketKeyFileStore).(chunk.Store) chunks := mustUploadChunks(ctx, t, uploadStore, tc.chunkCount) totalChunkCount, err := getChunkCount(uploadStore) if err != nil { t.Fatal(err) } if totalChunkCount != tc.chunkCount { t.Errorf("uploaded %v chunks, want %v", totalChunkCount, tc.chunkCount) } removedCount := removeChunks(t, ctx, uploadStore, tc.gaps, chunks) syncNode, err := sim.AddNode() if err != nil { t.Fatal(err) } err = sim.Net.Connect(uploadNode, syncNode) if err != nil { t.Fatal(err) } syncStore := sim.MustNodeItem(syncNode, bucketKeyFileStore).(chunk.Store) err = waitChunks(syncStore, totalChunkCount-removedCount, 10*time.Second) if err != nil { t.Fatal(err) } if tc.liveChunkCount > 0 { // pause syncing so that the chunks in the live gap // are not synced before they are removed handleMsgPauser.Pause() chunks = append(chunks, mustUploadChunks(ctx, t, uploadStore, tc.liveChunkCount)...) removedCount += removeChunks(t, ctx, uploadStore, tc.liveGaps, chunks) // resume syncing handleMsgPauser.Resume() err = waitChunks(syncStore, tc.chunkCount+tc.liveChunkCount-removedCount, time.Minute) if err != nil { t.Fatal(err) } } }) } } // TestTheeNodesUnionHistoricalSync brings up three nodes, uploads content too all of them and then // asserts that all of them have the union of all 3 local stores (depth is assumed to be 0) func TestThreeNodesUnionHistoricalSync(t *testing.T) { nodes := 3 chunkCount := 1000 sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{ "bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}), }, false) defer sim.Close() union := make(map[string]struct{}) nodeIDs := []enode.ID{} for i := 0; i < nodes; i++ { node, err := sim.AddNode() if err != nil { t.Fatal(err) } nodeIDs = append(nodeIDs, node) nodeStore := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore) mustUploadChunks(context.Background(), t, nodeStore, uint64(chunkCount)) uploadedChunks, err := getChunks(nodeStore.ChunkStore) if err != nil { t.Fatal(err) } for k := range uploadedChunks { if _, ok := union[k]; ok { t.Fatal("chunk already exists in union") } union[k] = struct{}{} } } err := sim.Net.ConnectNodesFull(nodeIDs) if err != nil { t.Fatal(err) } for _, n := range nodeIDs { nodeStore := sim.MustNodeItem(n, bucketKeyFileStore).(*storage.FileStore) if err := waitChunks(nodeStore, uint64(len(union)), 10*time.Second); err != nil { t.Fatal(err) } } } // TestFullSync performs a series of subtests where a number of nodes are // connected to the single (chunk uploading) node. func TestFullSync(t *testing.T) { for _, tc := range []struct { name string chunkCount uint64 syncNodeCount int history bool live bool }{ { name: "sync to two nodes history", chunkCount: 5000, syncNodeCount: 2, history: true, }, { name: "sync to two nodes live", chunkCount: 5000, syncNodeCount: 2, live: true, }, { name: "sync to two nodes history and live", chunkCount: 2500, syncNodeCount: 2, history: true, live: true, }, { name: "sync to 50 nodes history", chunkCount: 500, syncNodeCount: 50, history: true, }, { name: "sync to 50 nodes live", chunkCount: 500, syncNodeCount: 50, live: true, }, { name: "sync to 50 nodes history and live", chunkCount: 250, syncNodeCount: 50, history: true, live: true, }, } { t.Run(tc.name, func(t *testing.T) { if tc.syncNodeCount > 2 && runtime.GOARCH == "386" { t.Skip("skipping larger simulation on low memory architecture") } sim := simulation.NewInProc(map[string]simulation.ServiceFunc{ "bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}), }) defer sim.Close() defer catchDuplicateChunkSync(t)() uploaderNode, err := sim.AddNode() if err != nil { t.Fatal(err) } uploaderNodeStore := sim.MustNodeItem(uploaderNode, bucketKeyFileStore).(*storage.FileStore) if tc.history { mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount) } // add nodes to sync to ids, err := sim.AddNodes(tc.syncNodeCount) if err != nil { t.Fatal(err) } // connect every new node to the uploading one, so // every node will have depth 0 as only uploading node // will be in their kademlia tables err = sim.Net.ConnectNodesStar(ids, uploaderNode) if err != nil { t.Fatal(err) } // count the content in the bins again uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore) if err != nil { t.Fatal(err) } if tc.history && len(uploadedChunks) == 0 { t.Errorf("got empty uploader chunk store") } if !tc.history && len(uploadedChunks) != 0 { t.Errorf("got non empty uploader chunk store") } historicalChunks := make(map[enode.ID]map[string]struct{}) for _, id := range ids { wantChunks := make(map[string]struct{}, len(uploadedChunks)) for k, v := range uploadedChunks { wantChunks[k] = v } // wait for all chunks to be synced store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store) if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil { t.Fatal(err) } // validate that all and only all chunks are synced syncedChunks, err := getChunks(store) if err != nil { t.Fatal(err) } historicalChunks[id] = make(map[string]struct{}) for c := range wantChunks { if _, ok := syncedChunks[c]; !ok { t.Errorf("missing chunk %v", c) } delete(wantChunks, c) delete(syncedChunks, c) historicalChunks[id][c] = struct{}{} } if len(wantChunks) != 0 { t.Errorf("some of the uploaded chunks are not synced") } if len(syncedChunks) != 0 { t.Errorf("some of the synced chunks are not of uploaded ones") } } if tc.live { mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount) } uploadedChunks, err = getChunks(uploaderNodeStore.ChunkStore) if err != nil { t.Fatal(err) } for _, id := range ids { wantChunks := make(map[string]struct{}, len(uploadedChunks)) for k, v := range uploadedChunks { wantChunks[k] = v } store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store) // wait for all chunks to be synced if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil { t.Fatal(err) } // get all chunks from the syncing node syncedChunks, err := getChunks(store) if err != nil { t.Fatal(err) } // remove historical chunks from total uploaded and synced chunks for c := range historicalChunks[id] { if _, ok := wantChunks[c]; !ok { t.Errorf("missing uploaded historical chunk: %s", c) } delete(wantChunks, c) if _, ok := syncedChunks[c]; !ok { t.Errorf("missing synced historical chunk: %s", c) } delete(syncedChunks, c) } // validate that all and only all live chunks are synced for c := range wantChunks { if _, ok := syncedChunks[c]; !ok { t.Errorf("missing chunk %v", c) } delete(wantChunks, c) delete(syncedChunks, c) } if len(wantChunks) != 0 { t.Errorf("some of the uploaded live chunks are not synced") } if len(syncedChunks) != 0 { t.Errorf("some of the synced live chunks are not of uploaded ones") } } }) } } func waitChunks(store chunk.Store, want uint64, staledTimeout time.Duration) (err error) { start := time.Now() var ( count uint64 // total number of chunks prev uint64 // total number of chunks in previous check sleep time.Duration // duration until the next check staled time.Duration // duration for when the number of chunks is the same ) for staled < staledTimeout { // wait for some time while staled count, err = getChunkCount(store) if err != nil { return err } if count >= want { break } if count == prev { staled += sleep } else { staled = 0 } prev = count if count > 0 { // Calculate sleep time only if there is at least 1% of chunks available, // less may produce unreliable result. if count > want/100 { // Calculate the time required to pass for missing chunks to be available, // and divide it by half to perform a check earlier. sleep = time.Duration(float64(time.Since(start)) * float64(want-count) / float64(count) / 2) log.Debug("expecting all chunks", "in", sleep*2, "want", want, "have", count) } } switch { case sleep > time.Minute: // next check and speed calculation in some shorter time sleep = 500 * time.Millisecond case sleep > 5*time.Second: // upper limit for the check, do not check too slow sleep = 5 * time.Second case sleep < 50*time.Millisecond: // lower limit for the check, do not check too frequently sleep = 50 * time.Millisecond if staled > 0 { // slow down if chunks are stuck near the want value sleep *= 10 } } time.Sleep(sleep) } if count != want { return fmt.Errorf("got synced chunks %d, want %d", count, want) } return nil } func getChunkCount(store chunk.Store) (c uint64, err error) { for po := 0; po <= chunk.MaxPO; po++ { last, err := store.LastPullSubscriptionBinID(uint8(po)) if err != nil { return 0, err } c += last } return c, nil } func getChunks(store chunk.Store) (chunks map[string]struct{}, err error) { chunks = make(map[string]struct{}) for po := uint8(0); po <= chunk.MaxPO; po++ { last, err := store.LastPullSubscriptionBinID(po) if err != nil { return nil, err } if last == 0 { continue } ch, _ := store.SubscribePull(context.Background(), po, 0, last) for c := range ch { addr := c.Address.Hex() if _, ok := chunks[addr]; ok { return nil, fmt.Errorf("duplicate chunk %s", addr) } chunks[addr] = struct{}{} } } return chunks, nil } /* BenchmarkHistoricalStream measures syncing time after two nodes connect. go test -v github.com/ethersphere/swarm/network/stream/v2 -run="^$" -bench BenchmarkHistoricalStream -benchmem -loglevel 0 goos: darwin goarch: amd64 pkg: github.com/ethersphere/swarm/network/stream/v2 BenchmarkHistoricalStream/1000-chunks-8 10 133564663 ns/op 148289188 B/op 233646 allocs/op BenchmarkHistoricalStream/2000-chunks-8 5 290056259 ns/op 316599452 B/op 541507 allocs/op BenchmarkHistoricalStream/10000-chunks-8 1 1714618578 ns/op 1791108672 B/op 4133564 allocs/op BenchmarkHistoricalStream/20000-chunks-8 1 4724760666 ns/op 4133092720 B/op 11347504 allocs/op PASS */ func BenchmarkHistoricalStream(b *testing.B) { for _, c := range []uint64{ 1000, 2000, 10000, 20000, } { b.Run(fmt.Sprintf("%v-chunks", c), func(b *testing.B) { benchmarkHistoricalStream(b, c) }) } } func benchmarkHistoricalStream(b *testing.B, chunks uint64) { b.StopTimer() for i := 0; i < b.N; i++ { sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{ "bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}), }, false) uploaderNode, err := sim.AddNode() if err != nil { b.Fatal(err) } uploaderNodeStore := nodeFileStore(sim, uploaderNode) mustUploadChunks(context.Background(), b, uploaderNodeStore, chunks) uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore) if err != nil { b.Fatal(err) } syncingNode, err := sim.AddNode() if err != nil { b.Fatal(err) } b.StartTimer() err = sim.Net.Connect(syncingNode, uploaderNode) if err != nil { b.Fatal(err) } syncingNodeStore := sim.MustNodeItem(syncingNode, bucketKeyFileStore).(chunk.Store) if err := waitChunks(syncingNodeStore, uint64(len(uploadedChunks)), 10*time.Second); err != nil { b.Fatal(err) } b.StopTimer() err = sim.Net.Stop(syncingNode) if err != nil { b.Fatal(err) } sim.Close() } } // Function that uses putSeenTestHook to record and report // if there were duplicate chunk synced between Node id func catchDuplicateChunkSync(t *testing.T) (validate func()) { m := make(map[enode.ID]map[string]int) var mu sync.Mutex putSeenTestHook = func(addr chunk.Address, id enode.ID) { mu.Lock() defer mu.Unlock() if _, ok := m[id]; !ok { m[id] = make(map[string]int) } m[id][addr.Hex()]++ } return func() { // reset the test hook putSeenTestHook = nil // do the validation mu.Lock() defer mu.Unlock() for nodeID, addrs := range m { for addr, count := range addrs { t.Errorf("chunk synced %v times to node %s: %v", count, nodeID, addr) } } } } // TestStarNetworkSyncWithBogusNodes ests that syncing works on a more elaborate network topology // the test creates three real nodes in a star topology, then adds bogus nodes to the pivot (instead of using real nodes // this is in order to make the simulation be more CI friendly) // the pivot node will have neighbourhood depth > 0, which in turn means that from each // connected node, the pivot node should have only part of its chunks // The test checks that EVERY chunk that exists a node which is not the pivot, according to // its PO, and kademlia table of the pivot - exists on the pivot node and does not exist on other nodes func TestStarNetworkSyncWithBogusNodes(t *testing.T) { var ( chunkCount = 500 nodeCount = 12 minPivotDepth = 1 chunkSize = 4096 simTimeout = 60 * time.Second syncTime = 4 * time.Second filesize = chunkCount * chunkSize opts = &SyncSimServiceOptions{SyncOnlyWithinDepth: false, Autostart: true} ) sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{ "bzz-sync": newSyncSimServiceFunc(opts), }, false) defer sim.Close() ctx, cancel := context.WithTimeout(context.Background(), simTimeout) defer cancel() pivot, err := sim.AddNode() if err != nil { t.Fatal(err) } pivotKad := sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia) pivotBase := pivotKad.BaseAddr() log.Debug("started pivot node", "addr", hex.EncodeToString(pivotBase)) newNode, err := sim.AddNode() if err != nil { t.Fatal(err) } err = sim.Net.Connect(pivot, newNode) if err != nil { t.Fatal(err) } newNode2, err := sim.AddNode() if err != nil { t.Fatal(err) } err = sim.Net.Connect(pivot, newNode2) if err != nil { t.Fatal(err) } time.Sleep(50 * time.Millisecond) log.Trace(sim.MustNodeItem(newNode, simulation.BucketKeyKademlia).(*network.Kademlia).String()) pivotKad = sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia) pivotAddr := pot.NewAddressFromBytes(pivotBase) // add a few fictional nodes at higher POs to uploader so that uploader depth goes > 0 for i := 0; i < nodeCount; i++ { rw := &p2p.MsgPipeRW{} ptpPeer := p2p.NewPeer(enode.ID{}, "im just a lazy hobo", []p2p.Cap{}) protoPeer := protocols.NewPeer(ptpPeer, rw, &protocols.Spec{}) peerAddr := pot.RandomAddressAt(pivotAddr, i) bzzPeer := &network.BzzPeer{ Peer: protoPeer, BzzAddr: network.NewBzzAddr(peerAddr.Bytes(), nil), } peer := network.NewPeer(bzzPeer, pivotKad) pivotKad.On(peer) } time.Sleep(50 * time.Millisecond) log.Trace(pivotKad.String()) if d := pivotKad.NeighbourhoodDepth(); d < minPivotDepth { t.Skipf("too shallow. depth %d want %d", d, minPivotDepth) } pivotDepth := pivotKad.NeighbourhoodDepth() chunkProx := make(map[string]chunkProxData) result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) { nodeIDs := sim.UpNodeIDs() for _, node := range nodeIDs { node := node if bytes.Equal(pivot.Bytes(), node.Bytes()) { continue } nodeKad := sim.MustNodeItem(node, simulation.BucketKeyKademlia).(*network.Kademlia) nodePo := chunk.Proximity(nodeKad.BaseAddr(), pivotKad.BaseAddr()) seed := int(time.Now().UnixNano()) randomBytes := testutil.RandomBytes(seed, filesize) log.Debug("putting chunks to ephemeral localstore") chunkAddrs, err := getAllRefs(randomBytes[:]) if err != nil { return err } log.Debug("done getting all refs") for _, c := range chunkAddrs { proxData := chunkProxData{ addr: c, uploaderNodeToPivotNodePO: nodePo, chunkToUploaderPO: chunk.Proximity(nodeKad.BaseAddr(), c), pivotPO: chunk.Proximity(c, pivotKad.BaseAddr()), uploaderNode: node, } log.Debug("test putting chunk", "node", node, "addr", hex.EncodeToString(c), "uploaderToPivotPO", proxData.uploaderNodeToPivotNodePO, "c2uploaderPO", proxData.chunkToUploaderPO, "pivotDepth", pivotDepth) if _, ok := chunkProx[hex.EncodeToString(c)]; ok { return fmt.Errorf("chunk already found on another node %s", hex.EncodeToString(c)) } chunkProx[hex.EncodeToString(c)] = proxData } fs := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore) reader := bytes.NewReader(randomBytes[:]) _, wait1, err := fs.Store(ctx, reader, int64(len(randomBytes)), false) if err != nil { return fmt.Errorf("fileStore.Store: %v", err) } if err := wait1(ctx); err != nil { return err } } //according to old pull sync - if the node is outside of depth - it should have all chunks where po(chunk)==po(node) time.Sleep(syncTime) pivotLs := sim.MustNodeItem(pivot, bucketKeyLocalStore).(*localstore.DB) verifyCorrectChunksOnPivot(t, chunkProx, pivotDepth, pivotLs) return nil }) if result.Error != nil { t.Fatal(result.Error) } } // verifyCorrectChunksOnPivot checks which chunks should be present on the // pivot node from the perspective of the pivot node. All streams established // should be presumed from the point of view of the pivot and presence of // chunks should be assumed by po(chunk,uploader) // for example, if the pivot has depth==1 and the po(pivot,uploader)==1, then // all chunks that have po(chunk,uploader)==1 should be synced to the pivot func verifyCorrectChunksOnPivot(t *testing.T, chunkProx map[string]chunkProxData, pivotDepth int, pivotLs *localstore.DB) { t.Helper() for _, v := range chunkProx { // outside of depth if v.uploaderNodeToPivotNodePO < pivotDepth { // chunk PO to uploader == uploader node PO to pivot (i.e. chunk should be synced) - inclusive test if v.chunkToUploaderPO == v.uploaderNodeToPivotNodePO { //check that the chunk exists on the pivot when the chunkPo == uploaderPo _, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr) if err != nil { t.Errorf("chunk errored. err %v uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", err, v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr)) } } else { //chunk should not be synced - exclusion test _, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr) if err == nil { t.Errorf("chunk did not error but should have. uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr)) } } } } } type chunkProxData struct { addr chunk.Address uploaderNodeToPivotNodePO int chunkToUploaderPO int uploaderNode enode.ID pivotPO int } func getAllRefs(testData []byte) (storage.AddressCollection, error) { datadir, err := ioutil.TempDir("", "chunk-debug") if err != nil { return nil, fmt.Errorf("unable to create temp dir: %v", err) } defer os.RemoveAll(datadir) fileStore, cleanup, err := storage.NewLocalFileStore(datadir, make([]byte, 32), chunk.NewTags()) if err != nil { return nil, err } defer cleanup() reader := bytes.NewReader(testData) return fileStore.GetAllReferences(context.Background(), reader) }
lgpl-3.0
Arcavias/arcavias-core
lib/mshoplib/src/MShop/Order/Manager/Base/Service/Default.php
18575
<?php /** * @copyright Copyright (c) Metaways Infosystems GmbH, 2011 * @license LGPLv3, http://www.arcavias.com/en/license * @package MShop * @subpackage Order */ /** * Default Manager Order service * * @package MShop * @subpackage Order */ class MShop_Order_Manager_Base_Service_Default extends MShop_Common_Manager_Abstract implements MShop_Order_Manager_Base_Service_Interface { private $_searchConfig = array( 'order.base.service.id' => array( 'code' => 'order.base.service.id', 'internalcode' => 'mordbase."id"', 'internaldeps' => array( 'LEFT JOIN "mshop_order_base_service" AS mordbase ON ( mordba."id" = mordbase."baseid" )' ), 'label' => 'Order base service ID', 'type' => 'integer', 'internaltype' => MW_DB_Statement_Abstract::PARAM_INT, 'public' => false, ), 'order.base.service.siteid' => array( 'code' => 'order.base.service.siteid', 'internalcode' => 'mordbase."siteid"', 'label' => 'Order base service site ID', 'type' => 'integer', 'internaltype' => MW_DB_Statement_Abstract::PARAM_INT, 'public' => false, ), 'order.base.service.baseid' => array( 'code' => 'order.base.service.baseid', 'internalcode' => 'mordbase."baseid"', 'label' => 'Order base ID', 'type' => 'integer', 'internaltype' => MW_DB_Statement_Abstract::PARAM_INT, 'public' => false, ), 'order.base.service.serviceid' => array( 'code' => 'order.base.service.serviceid', 'internalcode' => 'mordbase."servid"', 'label' => 'Order base service original service ID', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.type' => array( 'code' => 'order.base.service.type', 'internalcode' => 'mordbase."type"', 'label' => 'Order base service type', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.code' => array( 'code' => 'order.base.service.code', 'internalcode' => 'mordbase."code"', 'label' => 'Order base service code', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.name' => array( 'code' => 'order.base.service.name', 'internalcode' => 'mordbase."name"', 'label' => 'Order base service name', 'type' => 'string', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.mediaurl' => array( 'code'=>'order.base.service.mediaurl', 'internalcode'=>'mordbase."mediaurl"', 'label'=>'Order base service media url', 'type'=> 'string', 'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.price' => array( 'code' => 'order.base.service.price', 'internalcode' => 'mordbase."price"', 'label' => 'Order base service price', 'type' => 'decimal', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.costs' => array( 'code' => 'order.base.service.costs', 'internalcode' => 'mordbase."costs"', 'label' => 'Order base service shipping', 'type' => 'decimal', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.rebate' => array( 'code' => 'order.base.service.rebate', 'internalcode' => 'mordbase."rebate"', 'label' => 'Order base service rebate', 'type' => 'decimal', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.taxrate' => array( 'code' => 'order.base.service.taxrate', 'internalcode' => 'mordbase."taxrate"', 'label' => 'Order base service taxrate', 'type' => 'decimal', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.mtime' => array( 'code' => 'order.base.service.mtime', 'internalcode' => 'mordbase."mtime"', 'label' => 'Order base service modification time', 'type' => 'datetime', 'internaltype' => MW_DB_Statement_Abstract::PARAM_STR, ), 'order.base.service.ctime'=> array( 'code'=>'order.base.service.ctime', 'internalcode'=>'mordbase."ctime"', 'label'=>'Order base service create date/time', 'type'=> 'datetime', 'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR ), 'order.base.service.editor'=> array( 'code'=>'order.base.service.editor', 'internalcode'=>'mordbase."editor"', 'label'=>'Order base service editor', 'type'=> 'string', 'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR ), ); /** * Initializes the object. * * @param MShop_Context_Item_Interface $context Context object */ public function __construct( MShop_Context_Item_Interface $context ) { parent::__construct( $context ); $this->_setResourceName( 'db-order' ); } /** * Removes old entries from the storage. * * @param integer[] $siteids List of IDs for sites whose entries should be deleted */ public function cleanup( array $siteids ) { $path = 'classes/order/manager/base/service/submanagers'; foreach( $this->_getContext()->getConfig()->get( $path, array( 'attribute' ) ) as $domain ) { $this->getSubManager( $domain )->cleanup( $siteids ); } $this->_cleanup( $siteids, 'mshop/order/manager/base/service/default/item/delete' ); } /** * Creates new order service item object. * * @return MShop_Order_Item_Base_Service_Interface New object */ public function createItem() { $context = $this->_getContext(); $priceManager = MShop_Factory::createManager( $context, 'price' ); $values = array( 'siteid'=> $context->getLocale()->getSiteId() ); return $this->_createItem( $priceManager->createItem(), $values ); } /** * Adds or updates an order base service item to the storage. * * @param MShop_Common_Item_Interface $item Order base service object * @param boolean $fetch True if the new ID should be returned in the item */ public function saveItem( MShop_Common_Item_Interface $item, $fetch = true ) { $iface = 'MShop_Order_Item_Base_Service_Interface'; if( !( $item instanceof $iface ) ) { throw new MShop_Order_Exception( sprintf( 'Object is not of required type "%1$s"', $iface ) ); } if( !$item->isModified() ) { return; } $context = $this->_getContext(); $dbm = $context->getDatabaseManager(); $dbname = $this->_getResourceName(); $conn = $dbm->acquire( $dbname ); try { $id = $item->getId(); $price = $item->getPrice(); $path = 'mshop/order/manager/base/service/default/item/'; $path .= ( $id === null ) ? 'insert' : 'update'; $stmt = $this->_getCachedStatement( $conn, $path ); $stmt->bind(1, $item->getBaseId(), MW_DB_Statement_Abstract::PARAM_INT); $stmt->bind(2, $context->getLocale()->getSiteId(), MW_DB_Statement_Abstract::PARAM_INT); $stmt->bind(3, $item->getServiceId(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(4, $item->getType(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(5, $item->getCode(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(6, $item->getName(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(7, $item->getMediaUrl(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(8, $price->getValue(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(9, $price->getCosts(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(10, $price->getRebate(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(11, $price->getTaxRate(), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(12, date('Y-m-d H:i:s', time()), MW_DB_Statement_Abstract::PARAM_STR); $stmt->bind(13, $context->getEditor() ); if ( $id !== null ) { $stmt->bind(14, $id, MW_DB_Statement_Abstract::PARAM_INT); } else { $stmt->bind(14, date( 'Y-m-d H:i:s', time() ), MW_DB_Statement_Abstract::PARAM_STR );// ctime } $stmt->execute()->finish(); if( $fetch === true ) { if( $id === null ) { $path = 'mshop/order/manager/base/service/default/item/newid'; $item->setId( $this->_newId( $conn, $context->getConfig()->get( $path, $path ) ) ); } else { $item->setId($id); } } $dbm->release( $conn, $dbname ); } catch ( Exception $e ) { $dbm->release( $conn, $dbname ); throw $e; } } /** * Removes multiple items specified by ids in the array. * * @param array $ids List of IDs */ public function deleteItems( array $ids ) { $path = 'mshop/order/manager/base/service/default/item/delete'; $this->_deleteItems( $ids, $this->_getContext()->getConfig()->get( $path, $path ) ); } /** * Returns the order service item object for the given ID. * * @param integer $id Order service ID * @param array $ref List of domains to fetch list items and referenced items for * @return MShop_Order_Item_Base_Service_Interface Returns order base service item of the given id * @throws MShop_Exception If item couldn't be found */ public function getItem( $id, array $ref = array() ) { return $this->_getItem( 'order.base.service.id', $id, $ref ); } /** * Searches for order service items based on the given criteria. * * @param MW_Common_Criteria_Interface $search Search object containing the conditions * @param array $ref Not used * @param integer &$total Number of items that are available in total * @return array List of items implementing MShop_Order_Item_Base_Service_Interface */ public function searchItems(MW_Common_Criteria_Interface $search, array $ref = array(), &$total = null) { $items = array(); $context = $this->_getContext(); $priceManager = MShop_Factory::createManager( $context, 'price' ); $dbm = $context->getDatabaseManager(); $dbname = $this->_getResourceName(); $conn = $dbm->acquire( $dbname ); try { $sitelevel = MShop_Locale_Manager_Abstract::SITE_SUBTREE; $cfgPathSearch = 'mshop/order/manager/base/service/default/item/search'; $cfgPathCount = 'mshop/order/manager/base/service/default/item/count'; $required = array( 'order.base.service' ); $results = $this->_searchItems( $conn, $search, $cfgPathSearch, $cfgPathCount, $required, $total, $sitelevel ); try { while( ( $row = $results->fetch() ) !== false ) { $price = $priceManager->createItem(); $price->setValue($row['price']); $price->setRebate($row['rebate']); $price->setCosts($row['costs']); $price->setTaxRate($row['taxrate']); $items[ $row['id'] ] = array( 'price' => $price, 'item' => $row ); } } catch( Exception $e ) { $results->finish(); throw $e; } $dbm->release( $conn, $dbname ); } catch( Exception $e ) { $dbm->release( $conn, $dbname ); throw $e; } $result = array(); $attributes = $this->_getAttributeItems( array_keys( $items ) ); foreach ( $items as $id => $row ) { $attrList = array(); if( isset( $attributes[$id] ) ) { $attrList = $attributes[$id]; } $result[ $id ] = $this->_createItem( $row['price'], $row['item'], $attrList ); } return $result; } /** * Returns the search attributes that can be used for searching. * * @param boolean $withsub Return also attributes of sub-managers if true * @return array List of attributes implementing MW_Common_Criteria_Attribute_Interface */ public function getSearchAttributes($withsub = true) { /** classes/order/manager/base/service/submanagers * List of manager names that can be instantiated by the order base service manager * * Managers provide a generic interface to the underlying storage. * Each manager has or can have sub-managers caring about particular * aspects. Each of these sub-managers can be instantiated by its * parent manager using the getSubManager() method. * * The search keys from sub-managers can be normally used in the * manager as well. It allows you to search for items of the manager * using the search keys of the sub-managers to further limit the * retrieved list of items. * * @param array List of sub-manager names * @since 2014.03 * @category Developer */ $path = 'classes/order/manager/base/service/submanagers'; return $this->_getSearchAttributes( $this->_searchConfig, $path, array( 'attribute' ), $withsub ); } /** * Returns a new manager for order service extensions. * * @param string $manager Name of the sub manager type in lower case * @param string|null $name Name of the implementation (from configuration or "Default" if null) * @return MShop_Common_Manager_Interface Manager for different extensions, e.g attribute */ public function getSubManager($manager, $name = null) { /** classes/order/manager/base/service/name * Class name of the used order base service manager implementation * * Each default order base service manager can be replaced by an alternative imlementation. * To use this implementation, you have to set the last part of the class * name as configuration value so the manager factory knows which class it * has to instantiate. * * For example, if the name of the default class is * * MShop_Order_Manager_Base_Service_Default * * and you want to replace it with your own version named * * MShop_Order_Manager_Base_Service_Myservice * * then you have to set the this configuration option: * * classes/order/manager/base/service/name = Myservice * * The value is the last part of your own class name and it's case sensitive, * so take care that the configuration value is exactly named like the last * part of the class name. * * The allowed characters of the class name are A-Z, a-z and 0-9. No other * characters are possible! You should always start the last part of the class * name with an upper case character and continue only with lower case characters * or numbers. Avoid chamel case names like "MyService"! * * @param string Last part of the class name * @since 2014.03 * @category Developer */ /** mshop/order/manager/base/service/decorators/excludes * Excludes decorators added by the "common" option from the order base service manager * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to remove a decorator added via * "mshop/common/manager/decorators/default" before they are wrapped * around the order base service manager. * * mshop/order/manager/base/service/decorators/excludes = array( 'decorator1' ) * * This would remove the decorator named "decorator1" from the list of * common decorators ("MShop_Common_Manager_Decorator_*") added via * "mshop/common/manager/decorators/default" for the order base service manager. * * @param array List of decorator names * @since 2014.03 * @category Developer * @see mshop/common/manager/decorators/default * @see mshop/order/manager/base/service/decorators/global * @see mshop/order/manager/base/service/decorators/local */ /** mshop/order/manager/base/service/decorators/global * Adds a list of globally available decorators only to the order base service manager * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to wrap global decorators * ("MShop_Common_Manager_Decorator_*") around the order base service manager. * * mshop/order/manager/base/service/decorators/global = array( 'decorator1' ) * * This would add the decorator named "decorator1" defined by * "MShop_Common_Manager_Decorator_Decorator1" only to the order controller. * * @param array List of decorator names * @since 2014.03 * @category Developer * @see mshop/common/manager/decorators/default * @see mshop/order/manager/base/service/decorators/excludes * @see mshop/order/manager/base/service/decorators/local */ /** mshop/order/manager/base/service/decorators/local * Adds a list of local decorators only to the order base service manager * * Decorators extend the functionality of a class by adding new aspects * (e.g. log what is currently done), executing the methods of the underlying * class only in certain conditions (e.g. only for logged in users) or * modify what is returned to the caller. * * This option allows you to wrap local decorators * ("MShop_Common_Manager_Decorator_*") around the order base service manager. * * mshop/order/manager/base/service/decorators/local = array( 'decorator2' ) * * This would add the decorator named "decorator2" defined by * "MShop_Common_Manager_Decorator_Decorator2" only to the order * controller. * * @param array List of decorator names * @since 2014.03 * @category Developer * @see mshop/common/manager/decorators/default * @see mshop/order/manager/base/service/decorators/excludes * @see mshop/order/manager/base/service/decorators/global */ return $this->_getSubManager( 'order', 'base/service/' . $manager, $name ); } /** * Creates a new order service item object initialized with given parameters. * * @param MShop_Price_Item_Interface $price Price object * @param array $values Associative list of values from the database * @param array $attributes List of order service attribute items * @return MShop_Order_Item_Base_Service_Interface Order item service object */ protected function _createItem( MShop_Price_Item_Interface $price, array $values = array(), array $attributes = array() ) { return new MShop_Order_Item_Base_Service_Default( $price, $values, $attributes ); } /** * Searches for attribute items connected with order service item. * * @param string[] $ids List of order service item IDs * @return array List of items implementing MShop_Order_Item_Base_Service_Attribute_Interface */ protected function _getAttributeItems( $ids ) { $manager = $this->getSubManager( 'attribute' ); $search = $manager->createSearch(); $search->setConditions( $search->compare( '==', 'order.base.service.attribute.serviceid', $ids ) ); $search->setSortations( array( $search->sort( '+', 'order.base.service.attribute.code' ) ) ); $search->setSlice( 0, 0x7fffffff ); $result = array(); foreach ($manager->searchItems( $search ) as $item) { $result[ $item->getServiceId() ][ $item->getId() ] = $item; } return $result; } }
lgpl-3.0
tango-controls/JTango
dao/src/main/java/fr/esrf/TangoApi/DevVarCmdArray.java
3880
//+====================================================================== // $Source$ // // Project: Tango // // Description: java source code for the TANGO client/server API. // // $Author: pascal_verdier $ // // Copyright (C) : 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014, // European Synchrotron Radiation Facility // BP 220, Grenoble 38043 // FRANCE // // This file is part of Tango. // // Tango 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. // // Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>. // // $Revision: 25297 $ // //-====================================================================== package fr.esrf.TangoApi; import fr.esrf.Tango.DevCmdInfo; import fr.esrf.Tango.DevFailed; import fr.esrf.TangoDs.Except; public class DevVarCmdArray { /** * manage an array of CommandInfo objects. */ protected CommandInfo[] cmd_info; /** * The device name */ protected String devname; //====================================================== //====================================================== public DevVarCmdArray(String devname, DevCmdInfo[] info) { this.devname = devname; cmd_info = new CommandInfo[info.length]; for (int i=0 ; i<info.length ; i++) cmd_info[i] = new CommandInfo(info[i]); } //====================================================== //====================================================== public DevVarCmdArray(String devname, CommandInfo[] info) { this.devname = devname; this.cmd_info = info; } //====================================================== //====================================================== public int size() { return cmd_info.length; } //====================================================== //====================================================== public CommandInfo elementAt(int i) { return cmd_info[i]; } //====================================================== //====================================================== public CommandInfo[] getInfoArray() { return cmd_info; } //====================================================== //====================================================== public int argoutType(String cmdname) throws DevFailed { for (CommandInfo info : cmd_info) if (cmdname.equals(info.cmd_name)) return info.out_type; Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE", cmdname + " command unknown for device " + devname, "DevVarCmdArray.argoutType()"); return -1; } //====================================================== //====================================================== public int arginType(String cmdname) throws DevFailed { for (CommandInfo info : cmd_info) if (cmdname.equals(info.cmd_name)) return info.in_type; Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE", cmdname + " command unknown for device " + devname, "DevVarCmdArray.arginType()"); return -1; } //====================================================== //====================================================== public String toString() { StringBuffer sb = new StringBuffer(); for (CommandInfo info : cmd_info) { sb.append(info.cmd_name); sb.append("(").append(info.in_type); sb.append(", ").append(info.out_type).append(")\n"); } return sb.toString(); } }
lgpl-3.0
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/doc/html/qvariant-qt3.html
13373
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qvariant.cpp --> <title>Qt 4.7: Qt 3 Support Members for QVariant</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="modules.html">Modules</a></li> <li><a href="qtcore.html">QtCore</a></li> <li>QVariant</li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">Qt 3 Support Members for QVariant</h1> <p><b>The following class members are part of the <a href="qt3support.html">Qt 3 support layer</a>.</b> They are provided to help you port old code to Qt 4. We advise against using them in new code.</p> <p><ul><li><a href="qvariant.html">QVariant class reference</a></li></ul></p> <h2>Public Functions</h2> <table class="alignedsummary"> <tr><td class="memItemLeft topAlign rightAlign"> </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#QVariant-40">QVariant</a></b> ( bool <i>b</i>, int <i>dummy</i> )</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QBitArray &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asBitArray">asBitArray</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> bool &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asBool">asBool</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QByteArray &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asByteArray">asByteArray</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QByteArray &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asCString">asCString</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QDate &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asDate">asDate</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QDateTime &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asDateTime">asDateTime</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> double &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asDouble">asDouble</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> int &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asInt">asInt</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QList&lt;QVariant&gt; &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asList">asList</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> qlonglong &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asLongLong">asLongLong</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QMap&lt;QString, QVariant&gt; &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asMap">asMap</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QPoint &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asPoint">asPoint</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QRect &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asRect">asRect</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QSize &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asSize">asSize</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QString &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asString">asString</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QStringList &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asStringList">asStringList</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> QTime &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asTime">asTime</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> uint &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asUInt">asUInt</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> qulonglong &amp; </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#asULongLong">asULongLong</a></b> ()</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#canCast">canCast</a></b> ( Type <i>t</i> ) const</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> bool </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#cast">cast</a></b> ( Type <i>t</i> )</td></tr> <tr><td class="memItemLeft topAlign rightAlign"> const QByteArray </td><td class="memItemRight bottomAlign"><b><a href="qvariant-qt3.html#toCString">toCString</a></b> () const</td></tr> </table> <h2>Member Function Documentation</h2> <!-- $$$QVariant$$$QVariantboolint --> <h3 class="fn"><a name="QVariant-40"></a>QVariant::<span class="name">QVariant</span> ( <span class="type">bool</span> <i>b</i>, <span class="type">int</span> <i>dummy</i> )</h3> <p>Use the <a href="qvariant.html">QVariant</a>(bool) constructor instead.</p> <!-- @@@QVariant --> <!-- $$$asBitArray[overload1]$$$asBitArray --> <h3 class="fn"><a name="asBitArray"></a><span class="type"><a href="qbitarray.html">QBitArray</a></span> &amp; QVariant::<span class="name">asBitArray</span> ()</h3> <p>Use <a href="qvariant.html#toBitArray">toBitArray</a>() instead.</p> <!-- @@@asBitArray --> <!-- $$$asBool[overload1]$$$asBool --> <h3 class="fn"><a name="asBool"></a><span class="type">bool</span> &amp; QVariant::<span class="name">asBool</span> ()</h3> <p>Use <a href="qvariant.html#toBool">toBool</a>() instead.</p> <!-- @@@asBool --> <!-- $$$asByteArray[overload1]$$$asByteArray --> <h3 class="fn"><a name="asByteArray"></a><span class="type"><a href="qbytearray.html">QByteArray</a></span> &amp; QVariant::<span class="name">asByteArray</span> ()</h3> <p>Use <a href="qvariant.html#toByteArray">toByteArray</a>() instead.</p> <!-- @@@asByteArray --> <!-- $$$asCString[overload1]$$$asCString --> <h3 class="fn"><a name="asCString"></a><span class="type"><a href="qbytearray.html">QByteArray</a></span> &amp; QVariant::<span class="name">asCString</span> ()</h3> <p>Use <a href="qvariant.html#toByteArray">toByteArray</a>() instead.</p> <!-- @@@asCString --> <!-- $$$asDate[overload1]$$$asDate --> <h3 class="fn"><a name="asDate"></a><span class="type"><a href="qdate.html">QDate</a></span> &amp; QVariant::<span class="name">asDate</span> ()</h3> <p>Use <a href="qvariant.html#toDate">toDate</a>() instead.</p> <!-- @@@asDate --> <!-- $$$asDateTime[overload1]$$$asDateTime --> <h3 class="fn"><a name="asDateTime"></a><span class="type"><a href="qdatetime.html">QDateTime</a></span> &amp; QVariant::<span class="name">asDateTime</span> ()</h3> <p>Use <a href="qvariant.html#toDateTime">toDateTime</a>() instead.</p> <!-- @@@asDateTime --> <!-- $$$asDouble[overload1]$$$asDouble --> <h3 class="fn"><a name="asDouble"></a><span class="type">double</span> &amp; QVariant::<span class="name">asDouble</span> ()</h3> <p>Use <a href="qvariant.html#toDouble">toDouble</a>() instead.</p> <!-- @@@asDouble --> <!-- $$$asInt[overload1]$$$asInt --> <h3 class="fn"><a name="asInt"></a><span class="type">int</span> &amp; QVariant::<span class="name">asInt</span> ()</h3> <p>Use <a href="qvariant.html#toInt">toInt</a>() instead.</p> <!-- @@@asInt --> <!-- $$$asList[overload1]$$$asList --> <h3 class="fn"><a name="asList"></a><span class="type"><a href="qlist.html">QList</a></span>&lt;<span class="type">QVariant</span>&gt; &amp; QVariant::<span class="name">asList</span> ()</h3> <p>Use <a href="qvariant.html#toList">toList</a>() instead.</p> <!-- @@@asList --> <!-- $$$asLongLong[overload1]$$$asLongLong --> <h3 class="fn"><a name="asLongLong"></a><span class="type"><a href="qtglobal.html#qlonglong-typedef">qlonglong</a></span> &amp; QVariant::<span class="name">asLongLong</span> ()</h3> <p>Use <a href="qvariant.html#toLongLong">toLongLong</a>() instead.</p> <!-- @@@asLongLong --> <!-- $$$asMap[overload1]$$$asMap --> <h3 class="fn"><a name="asMap"></a><span class="type"><a href="qmap.html">QMap</a></span>&lt;<span class="type"><a href="qstring.html">QString</a></span>, <span class="type">QVariant</span>&gt; &amp; QVariant::<span class="name">asMap</span> ()</h3> <p>Use <a href="qvariant.html#toMap">toMap</a>() instead.</p> <!-- @@@asMap --> <!-- $$$asPoint[overload1]$$$asPoint --> <h3 class="fn"><a name="asPoint"></a><span class="type"><a href="qpoint.html">QPoint</a></span> &amp; QVariant::<span class="name">asPoint</span> ()</h3> <p>Use <a href="qvariant.html#toPoint">toPoint</a>() instead.</p> <!-- @@@asPoint --> <!-- $$$asRect[overload1]$$$asRect --> <h3 class="fn"><a name="asRect"></a><span class="type"><a href="qrect.html">QRect</a></span> &amp; QVariant::<span class="name">asRect</span> ()</h3> <p>Use <a href="qvariant.html#toRect">toRect</a>() instead.</p> <!-- @@@asRect --> <!-- $$$asSize[overload1]$$$asSize --> <h3 class="fn"><a name="asSize"></a><span class="type"><a href="qsize.html">QSize</a></span> &amp; QVariant::<span class="name">asSize</span> ()</h3> <p>Use <a href="qvariant.html#toSize">toSize</a>() instead.</p> <!-- @@@asSize --> <!-- $$$asString[overload1]$$$asString --> <h3 class="fn"><a name="asString"></a><span class="type"><a href="qstring.html">QString</a></span> &amp; QVariant::<span class="name">asString</span> ()</h3> <p>Use <a href="qvariant.html#toString">toString</a>() instead.</p> <!-- @@@asString --> <!-- $$$asStringList[overload1]$$$asStringList --> <h3 class="fn"><a name="asStringList"></a><span class="type"><a href="qstringlist.html">QStringList</a></span> &amp; QVariant::<span class="name">asStringList</span> ()</h3> <p>Use <a href="qvariant.html#toStringList">toStringList</a>() instead.</p> <!-- @@@asStringList --> <!-- $$$asTime[overload1]$$$asTime --> <h3 class="fn"><a name="asTime"></a><span class="type"><a href="qtime.html">QTime</a></span> &amp; QVariant::<span class="name">asTime</span> ()</h3> <p>Use <a href="qvariant.html#toTime">toTime</a>() instead.</p> <!-- @@@asTime --> <!-- $$$asUInt[overload1]$$$asUInt --> <h3 class="fn"><a name="asUInt"></a><span class="type"><a href="qtglobal.html#uint-typedef">uint</a></span> &amp; QVariant::<span class="name">asUInt</span> ()</h3> <p>Use <a href="qvariant.html#toUInt">toUInt</a>() instead.</p> <!-- @@@asUInt --> <!-- $$$asULongLong[overload1]$$$asULongLong --> <h3 class="fn"><a name="asULongLong"></a><span class="type"><a href="qtglobal.html#qulonglong-typedef">qulonglong</a></span> &amp; QVariant::<span class="name">asULongLong</span> ()</h3> <p>Use <a href="qvariant.html#toULongLong">toULongLong</a>() instead.</p> <!-- @@@asULongLong --> <!-- $$$canCast[overload1]$$$canCastType --> <h3 class="fn"><a name="canCast"></a><span class="type">bool</span> QVariant::<span class="name">canCast</span> ( <span class="type"><a href="qvariant.html#Type-enum">Type</a></span> <i>t</i> ) const</h3> <p>Use <a href="qvariant.html#canConvert">canConvert</a>() instead.</p> <!-- @@@canCast --> <!-- $$$cast[overload1]$$$castType --> <h3 class="fn"><a name="cast"></a><span class="type">bool</span> QVariant::<span class="name">cast</span> ( <span class="type"><a href="qvariant.html#Type-enum">Type</a></span> <i>t</i> )</h3> <p>Use <a href="qvariant.html#convert">convert</a>() instead.</p> <!-- @@@cast --> <!-- $$$toCString[overload1]$$$toCString --> <h3 class="fn"><a name="toCString"></a>const <span class="type"><a href="qbytearray.html">QByteArray</a></span> QVariant::<span class="name">toCString</span> () const</h3> <p>Use <a href="qvariant.html#toByteArray">toByteArray</a>() instead.</p> <!-- @@@toCString --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
lgpl-3.0
SonarSource/sonarlint-visualstudio
src/Integration.Vsix.UnitTests/CFamily/VcxRequestFactoryTests.cs
17901
/* * SonarLint for Visual Studio * Copyright (C) 2016-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; using EnvDTE; using FluentAssertions; using VsShell = Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using SonarLint.VisualStudio.CFamily.Analysis; using SonarLint.VisualStudio.Core; using SonarLint.VisualStudio.Core.CFamily; using SonarLint.VisualStudio.Integration.Vsix.CFamily; using SonarLint.VisualStudio.Integration.Vsix.CFamily.VcxProject; using static SonarLint.VisualStudio.Integration.Vsix.CFamily.UnitTests.CFamilyTestUtility; using System.Threading.Tasks; using EnvDTE80; using Microsoft.VisualStudio.Shell.Interop; namespace SonarLint.VisualStudio.Integration.UnitTests.CFamily { [TestClass] public class VcxRequestFactoryTests { private static ProjectItem DummyProjectItem = Mock.Of<ProjectItem>(); private static CFamilyAnalyzerOptions DummyAnalyzerOptions = new CFamilyAnalyzerOptions(); [TestMethod] public void MefCtor_CheckIsExported() { MefTestHelpers.CheckTypeCanBeImported<VcxRequestFactory, IRequestFactory>(null, new[] { MefTestHelpers.CreateExport<VsShell.SVsServiceProvider>(Mock.Of<IServiceProvider>()), MefTestHelpers.CreateExport<ICFamilyRulesConfigProvider>(Mock.Of<ICFamilyRulesConfigProvider>()), MefTestHelpers.CreateExport<ILogger>(Mock.Of<ILogger>()) }); } [TestMethod] public async Task TryGet_RunsOnUIThread() { var fileConfigProvider = new Mock<IFileConfigProvider>(); var threadHandling = new Mock<IThreadHandling>(); threadHandling.Setup(x => x.RunOnUIThread(It.IsAny<Action>())) .Callback<Action>(op => { // Try to check that the product code is executed inside the "RunOnUIThread" call fileConfigProvider.Invocations.Count.Should().Be(0); op(); fileConfigProvider.Invocations.Count.Should().Be(1); }); var testSubject = CreateTestSubject(projectItem: DummyProjectItem, threadHandling: threadHandling.Object, fileConfigProvider: fileConfigProvider.Object); var request = await testSubject.TryCreateAsync("any", new CFamilyAnalyzerOptions()); threadHandling.Verify(x => x.RunOnUIThread(It.IsAny<Action>()), Times.Once); threadHandling.Verify(x => x.ThrowIfNotOnUIThread(), Times.Once); } [TestMethod] public async Task TryGet_NoProjectItem_Null() { var testSubject = CreateTestSubject(projectItem: null); var request = await testSubject.TryCreateAsync("path", new CFamilyAnalyzerOptions()); request.Should().BeNull(); } [TestMethod] public async Task TryGet_NoFileConfig_Null() { const string analyzedFilePath = "path"; var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, null); var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object); var request = await testSubject.TryCreateAsync("path", DummyAnalyzerOptions); request.Should().BeNull(); fileConfigProvider.Verify(x=> x.Get(DummyProjectItem, analyzedFilePath, DummyAnalyzerOptions), Times.Once); } [TestMethod] public async Task TryGet_RequestCreatedWithNoDetectedLanguage_Null() { const string analyzedFilePath = "c:\\notCFamilyFile.txt"; var fileConfig = CreateDummyFileConfig(analyzedFilePath); var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object); var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>(); var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object, cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object); var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions); request.Should().BeNull(); fileConfig.VerifyGet(x => x.AbsoluteFilePath, Times.Once); cFamilyRulesConfigProvider.Invocations.Count.Should().Be(0); } [TestMethod] public async Task TryGet_FailureParsing_NonCriticialException_Null() { const string analyzedFilePath = "c:\\test.cpp"; var fileConfig = CreateDummyFileConfig(analyzedFilePath); var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object); var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>(); cFamilyRulesConfigProvider .Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus)) .Throws<NotImplementedException>(); var logger = new TestLogger(); var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object, cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object, logger: logger); var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions); request.Should().BeNull(); logger.AssertPartialOutputStringExists(nameof(NotImplementedException)); } [TestMethod] public void TryGet_FailureParsing_CriticalException_ExceptionThrown() { const string analyzedFilePath = "c:\\test.cpp"; var fileConfig = CreateDummyFileConfig(analyzedFilePath); var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object); var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>(); cFamilyRulesConfigProvider .Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus)) .Throws<StackOverflowException>(); var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object, cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object); Func<Task> act = () => testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions); act.Should().ThrowExactly<StackOverflowException>(); } [TestMethod] public async Task TryGet_IRequestPropertiesAreSet() { var analyzerOptions = new CFamilyAnalyzerOptions(); var rulesConfig = Mock.Of<ICFamilyRulesConfig>(); var request = await GetSuccessfulRequest(analyzerOptions, "d:\\xxx\\fileToAnalyze.cpp", rulesConfig); request.Should().NotBeNull(); request.Context.File.Should().Be("d:\\xxx\\fileToAnalyze.cpp"); request.Context.PchFile.Should().Be(SubProcessFilePaths.PchFilePath); request.Context.AnalyzerOptions.Should().BeSameAs(analyzerOptions); request.Context.RulesConfiguration.Should().BeSameAs(rulesConfig); } [TestMethod] public async Task TryGet_FileConfigIsSet() { var request = await GetSuccessfulRequest(); request.Should().NotBeNull(); request.FileConfig.Should().NotBeNull(); } [TestMethod] public async Task TryGet_NonHeaderFile_IsSupported() { var request = await GetSuccessfulRequest(); request.Should().NotBeNull(); (request.Flags & Request.MainFileIsHeader).Should().Be(0); } [TestMethod] public async Task TryGet_HeaderFile_IsSupported() { var projectItemConfig = new ProjectItemConfig { ItemType = "ClInclude" }; var projectItemMock = CreateMockProjectItem("c:\\foo\\xxx.vcxproj", projectItemConfig); var fileConfig = CreateDummyFileConfig("c:\\dummy\\file.h"); fileConfig.Setup(x => x.CompileAs).Returns("CompileAsCpp"); fileConfig.Setup(x => x.ItemType).Returns("ClInclude"); var request = await GetSuccessfulRequest(fileToAnalyze: "c:\\dummy\\file.h", projectItem: projectItemMock.Object, fileConfig: fileConfig); request.Should().NotBeNull(); (request.Flags & Request.MainFileIsHeader).Should().NotBe(0); } [TestMethod] public async Task TryGet_NoAnalyzerOptions_RequestCreatedWithoutOptions() { var request = await GetSuccessfulRequest(analyzerOptions: null); request.Should().NotBeNull(); (request.Flags & Request.CreateReproducer).Should().Be(0); (request.Flags & Request.BuildPreamble).Should().Be(0); request.Context.AnalyzerOptions.Should().BeNull(); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithReproducerEnabled_RequestCreatedWithReproducerFlag() { var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = true }); request.Should().NotBeNull(); (request.Flags & Request.CreateReproducer).Should().NotBe(0); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithoutReproducerEnabled_RequestCreatedWithoutReproducerFlag() { var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = false }); request.Should().NotBeNull(); (request.Flags & Request.CreateReproducer).Should().Be(0); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithPCH_RequestCreatedWithPCHFlag() { var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true }); request.Should().NotBeNull(); (request.Flags & Request.BuildPreamble).Should().NotBe(0); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestCreatedWithoutPCHFlag() { var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false }); request.Should().NotBeNull(); (request.Flags & Request.BuildPreamble).Should().Be(0); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithPCH_RequestOptionsNotSet() { var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true }); request.Should().NotBeNull(); request.Context.RulesConfiguration.Should().BeNull(); request.Options.Should().BeEmpty(); } [TestMethod] public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestOptionsAreSet() { var rulesProtocolFormat = new RuleConfigProtocolFormat("some profile", new Dictionary<string, string> { {"rule1", "param1"}, {"rule2", "param2"} }); var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false }, protocolFormat: rulesProtocolFormat); request.Should().NotBeNull(); request.Context.RulesConfiguration.Should().NotBeNull(); request.Options.Should().BeEquivalentTo( "internal.qualityProfile=some profile", "rule1=param1", "rule2=param2"); } private static Mock<IFileConfigProvider> SetupFileConfigProvider(ProjectItem projectItem, CFamilyAnalyzerOptions analyzerOptions, string analyzedFilePath, IFileConfig fileConfigToReturn) { var fileConfigProvider = new Mock<IFileConfigProvider>(); fileConfigProvider .Setup(x => x.Get(projectItem, analyzedFilePath, analyzerOptions)) .Returns(fileConfigToReturn); return fileConfigProvider; } private VcxRequestFactory CreateTestSubject(ProjectItem projectItem, ICFamilyRulesConfigProvider cFamilyRulesConfigProvider = null, IFileConfigProvider fileConfigProvider = null, IRulesConfigProtocolFormatter rulesConfigProtocolFormatter = null, IThreadHandling threadHandling = null, ILogger logger = null) { var serviceProvider = CreateServiceProviderReturningProjectItem(projectItem); cFamilyRulesConfigProvider ??= Mock.Of<ICFamilyRulesConfigProvider>(); rulesConfigProtocolFormatter ??= Mock.Of<IRulesConfigProtocolFormatter>(); fileConfigProvider ??= Mock.Of<IFileConfigProvider>(); threadHandling ??= new NoOpThreadHandler(); logger ??= Mock.Of<ILogger>(); return new VcxRequestFactory(serviceProvider.Object, cFamilyRulesConfigProvider, rulesConfigProtocolFormatter, fileConfigProvider, logger, threadHandling); } private static Mock<IServiceProvider> CreateServiceProviderReturningProjectItem(ProjectItem projectItemToReturn) { var mockSolution = new Mock<Solution>(); mockSolution.Setup(s => s.FindProjectItem(It.IsAny<string>())).Returns(projectItemToReturn); var mockDTE = new Mock<DTE2>(); mockDTE.Setup(d => d.Solution).Returns(mockSolution.Object); var mockServiceProvider = new Mock<IServiceProvider>(); mockServiceProvider.Setup(s => s.GetService(typeof(SDTE))).Returns(mockDTE.Object); return mockServiceProvider; } private async Task<Request> GetSuccessfulRequest(CFamilyAnalyzerOptions analyzerOptions = null, string fileToAnalyze = "c:\\foo\\file.cpp", ICFamilyRulesConfig rulesConfig = null, ProjectItem projectItem = null, Mock<IFileConfig> fileConfig = null, RuleConfigProtocolFormat protocolFormat = null) { rulesConfig ??= Mock.Of<ICFamilyRulesConfig>(); var rulesConfigProviderMock = new Mock<ICFamilyRulesConfigProvider>(); rulesConfigProviderMock .Setup(x => x.GetRulesConfiguration(It.IsAny<string>())) .Returns(rulesConfig); projectItem ??= Mock.Of<ProjectItem>(); fileConfig ??= CreateDummyFileConfig(fileToAnalyze); var fileConfigProvider = SetupFileConfigProvider(projectItem, analyzerOptions, fileToAnalyze, fileConfig.Object); protocolFormat ??= new RuleConfigProtocolFormat("qp", new Dictionary<string, string>()); var rulesConfigProtocolFormatter = new Mock<IRulesConfigProtocolFormatter>(); rulesConfigProtocolFormatter .Setup(x => x.Format(rulesConfig)) .Returns(protocolFormat); var testSubject = CreateTestSubject(projectItem, rulesConfigProviderMock.Object, fileConfigProvider.Object, rulesConfigProtocolFormatter.Object); return await testSubject.TryCreateAsync(fileToAnalyze, analyzerOptions) as Request; } private Mock<IFileConfig> CreateDummyFileConfig(string filePath) { var fileConfig = new Mock<IFileConfig>(); fileConfig.SetupGet(x => x.PlatformName).Returns("Win32"); fileConfig.SetupGet(x => x.AdditionalIncludeDirectories).Returns(""); fileConfig.SetupGet(x => x.ForcedIncludeFiles).Returns(""); fileConfig.SetupGet(x => x.PrecompiledHeader).Returns(""); fileConfig.SetupGet(x => x.UndefinePreprocessorDefinitions).Returns(""); fileConfig.SetupGet(x => x.PreprocessorDefinitions).Returns(""); fileConfig.SetupGet(x => x.CompileAs).Returns(""); fileConfig.SetupGet(x => x.CompileAsManaged).Returns(""); fileConfig.SetupGet(x => x.RuntimeLibrary).Returns(""); fileConfig.SetupGet(x => x.ExceptionHandling).Returns(""); fileConfig.SetupGet(x => x.EnableEnhancedInstructionSet).Returns(""); fileConfig.SetupGet(x => x.BasicRuntimeChecks).Returns(""); fileConfig.SetupGet(x => x.LanguageStandard).Returns(""); fileConfig.SetupGet(x => x.AdditionalOptions).Returns(""); fileConfig.SetupGet(x => x.CompilerVersion).Returns("1.2.3.4"); fileConfig.SetupGet(x => x.AbsoluteProjectPath).Returns("c:\\test.vcxproj"); fileConfig.SetupGet(x => x.AbsoluteFilePath).Returns(filePath); return fileConfig; } } }
lgpl-3.0
Alfresco/alfresco-repository
src/main/java/org/alfresco/util/DBScriptUtil.java
3822
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2019 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * 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/>. * #L% */ package org.alfresco.util; import java.io.IOException; import java.io.LineNumberReader; import org.springframework.core.io.support.EncodedResource; public abstract class DBScriptUtil { private static final String DEFAULT_SCRIPT_COMMENT_PREFIX = "--"; /** * Read a script from the provided EncodedResource and build a String containing * the lines. * * @param resource * the resource (potentially associated with a specific encoding) to * load the SQL script from * @return a String containing the script lines */ public static String readScript(EncodedResource resource) throws IOException { return readScript(resource, DEFAULT_SCRIPT_COMMENT_PREFIX); } /** * Read a script from the provided EncodedResource, using the supplied line * comment prefix, and build a String containing the lines. * * @param resource * the resource (potentially associated with a specific encoding) to * load the SQL script from * @param lineCommentPrefix * the prefix that identifies comments in the SQL script (typically * "--") * @return a String containing the script lines */ private static String readScript(EncodedResource resource, String lineCommentPrefix) throws IOException { LineNumberReader lineNumberReader = new LineNumberReader(resource.getReader()); try { return readScript(lineNumberReader, lineCommentPrefix); } finally { lineNumberReader.close(); } } /** * Read a script from the provided LineNumberReader, using the supplied line * comment prefix, and build a String containing the lines. * * @param lineNumberReader * the LineNumberReader containing the script to be processed * @param lineCommentPrefix * the prefix that identifies comments in the SQL script (typically * "--") * @return a String containing the script lines */ private static String readScript(LineNumberReader lineNumberReader, String lineCommentPrefix) throws IOException { String statement = lineNumberReader.readLine(); StringBuilder scriptBuilder = new StringBuilder(); while (statement != null) { if (lineCommentPrefix != null && !statement.startsWith(lineCommentPrefix)) { if (scriptBuilder.length() > 0) { scriptBuilder.append('\n'); } scriptBuilder.append(statement); } statement = lineNumberReader.readLine(); } return scriptBuilder.toString(); } }
lgpl-3.0
jpakkane/stringstuff
readme.md
103
# Stringstuff A collection of header only simple string algorithms missing from the standard library.
lgpl-3.0
Bedrock-py/bedrock-core
validation/validationScript.py
17191
#!/usr/bin/env python from string import punctuation import argparse import fnmatch import os import shutil import sys import json sys.path.insert(1, '/var/www/bedrock/') sys.path.insert(0, '/var/www/bedrock/src/') import analytics.utils import dataloader.utils import visualization.utils from multiprocessing import Queue #function to determine if the file being checked has the appropriate imports def find_imports(fileToCheck, desiredInterface): importedList = [] asterikFound = False with open(fileToCheck, 'r') as pyFile: for line in pyFile: newFront = line.find("import") #finds the first occurence of the word import on the line if newFront != -1: #an occurence of import has been found line = line[newFront + 7:] #sets line to now start at the word after import possibleAs = line.find(" as") #used to find import states that have the structure (from x import y as z) if possibleAs != -1: line = line[possibleAs + 4:] if line.find("*") != -1 and len(line) == 2: #if the import is just the * importedList.extend(line) asterikFound = True line =[word.strip(punctuation) for word in line.split()] #correctly splits the inputs based on puncuation importedList.extend(line) #creates a single list of all the imports if desiredInterface == 1: if "Algorithm" not in importedList: return "Missing the Algorithm input, can be fixed using 'from ..analytics import Algorithm'.\n" else: return "" elif desiredInterface == 2: if "*" not in importedList: return "Missing the * input, can be fixed using 'from visualization.utils import *'.\n" else: return "" elif desiredInterface == 3: if "*" not in importedList: return "Missing the * input, can be fixed using 'from dataloader.utils import *'.\n" else: return "" elif desiredInterface == 4: if "*" not in importedList: return "Missing the * input, can be fixed using 'from dataloader.utils import *'\n" else: return "" def find_class(fileToCheck, desiredInterface): classesList = [] with open(fileToCheck, 'r') as pyFile: for line in pyFile: newFront = line.find("class") newEnd = line.find(")") if newFront == 0: line = line[newFront + 6: newEnd + 1] line.split() classesList.append(line) return classesList def find_functions(fileToCheck, desiredInterface): functionsList_with_inputs = [] with open(fileToCheck, 'r') as pyFile: for line in pyFile: newFront = line.find("def") newEnd = line.find(")") if newFront != -1: line = line[newFront + 3: newEnd + 1] line.split() functionsList_with_inputs.append(line) return functionsList_with_inputs def compare_fuctions(fileToCheck, desiredInterface): fList = find_functions(fileToCheck, desiredInterface) if desiredInterface == 1: if " __init__(self)" not in fList or " compute(self, filepath, **kwargs)" not in fList: return "Function/s and/or specific input/s missing in this file.\n" else: return "" elif desiredInterface == 2: if " __init__(self)" not in fList or " initialize(self, inputs)" not in fList or " create(self)" not in fList: return "Function/s and/or specific inputs/s missing in this file.\n" else: return "" elif desiredInterface == 3: if " __init__(self)" not in fList or " explore(self, filepath)" not in fList or " ingest(self, posted_data, src)" not in fList: return "Function/s and/or specific input/s missing in this file.\n" else: return "" elif desiredInterface == 4: if " __init__(self)" not in fList or (" check(self, name, sample)" not in fList and " check(self, name, col)" not in fList) or " apply(self, conf)" not in fList: return "Function/s and/or specific input/s missing in this file.\n" else: return "" def inheritance_check(fileToCheck, desiredInterface): class_name_list = find_class(fileToCheck, desiredInterface) inhertiance_name = "" if (len(class_name_list) > 0): if (desiredInterface == 1 and len(class_name_list) > 1): inhertiance_name = class_name_list[0] elif (len(class_name_list) > 1): inhertiance_name = class_name_list[len(class_name_list) - 1] else: inhertiance_name = class_name_list[0] newFront = inhertiance_name.find("(") newEnd = inhertiance_name.find(")") inhertiance_name = inhertiance_name[newFront + 1:newEnd] if desiredInterface == 1: if inhertiance_name != "Algorithm": return "Class must inherit from the Algorithm super class.\n" else: return "" elif desiredInterface == 2: if inhertiance_name != "Visualization": return "Class must inherit from the Visualization super class.\n" else: return "" elif desiredInterface == 3: if inhertiance_name != "Ingest": return "Class must inherit from the Ingest super class.\n" else: return "" elif desiredInterface == 4: if inhertiance_name != "Filter": return "Class must inherit from the Filter super class.\n" else: return "" else: return "There are no classes in this file.\n" def validate_file_name(fileToCheck, desiredInterface): class_name_list = find_class(fileToCheck, desiredInterface) class_name = "" if (len(class_name_list) > 0): if (desiredInterface == 1 and len(class_name_list) > 1): class_name = class_name_list[0] elif (len(class_name_list) > 1): class_name = class_name_list[len(class_name_list) - 1] else: class_name = class_name_list[0] trim = class_name.find("(") class_name = class_name[:trim] returnsList = list_returns(fileToCheck, desiredInterface) superStament = [] with open(fileToCheck, 'r') as pyFile: for line in pyFile: newFront = line.find("super") if newFront != -1: trimFront = line.find("(") trimBack = line.find(",") line = line[trimFront + 1: trimBack] superStament.append(line) if class_name not in superStament: return "File name does not match Class name\n" else: return "" def list_returns(fileToCheck, desiredInterface): returnsList = [] newLine = "" with open(fileToCheck, 'r') as pyFile: for line in pyFile: if line.find("#") == -1: newFront = line.find("return") if newFront != -1: possibleErrorMessageCheck1 = line.find("'") bracketBefore = line.find("{") lastBracket = line.find("}") newLine = line[possibleErrorMessageCheck1:] possibleErrorMessageCheck2 = newLine.find(" ") if possibleErrorMessageCheck2 == -1: line = line[newFront + 7:] line.split() line = [word.strip(punctuation) for word in line.split()] returnsList.extend(line) elif possibleErrorMessageCheck1 == bracketBefore + 1: line = line[newFront + 7:lastBracket + 1] line.split() returnsList.append(line) return returnsList def check_return_values(fileToCheck, desiredInterface): listOfReturns = list_returns(fileToCheck, desiredInterface) listOfClasses = find_class(fileToCheck, desiredInterface) firstElement = listOfClasses[0] for elem in listOfClasses: cutOff = elem.find("(") if cutOff != -1: elem = elem[:cutOff] firstElement = elem listOfClasses[0] = firstElement if desiredInterface == 1: listOfFunctions = find_functions(fileToCheck, desiredInterface) if len(listOfFunctions) == 2 and len(listOfReturns) > 0: return "Too many return values in this file.\n" else: return "" elif desiredInterface == 2: if len(listOfReturns) > 1: if listOfClasses[0] not in listOfReturns or listOfReturns[1].find("data") == -1 or listOfReturns[1].find("type") == -1 or listOfReturns[1].find("id") == -1: return "Missing or incorrectly named return values.\n" else: return "" elif listOfReturns[0].find("data") == -1 or listOfReturns[0].find("type") == -1 or listOfReturns[0].find("id") == -1: return "Missing or incorrectly named return values.\n" else: return "" elif desiredInterface == 3: if ("schema" not in listOfReturns and "schemas" not in listOfReturns and "collection:ret" not in listOfReturns) or "error" not in listOfReturns or "matrices" not in listOfReturns: return "Missing or incorrectly named return values.\n" else: return "" elif desiredInterface == 4: if ("True" not in listOfReturns and "False" not in listOfReturns) or ("matrix" not in listOfReturns and "None" not in listOfReturns): return "Missing or incorrectly named return values" else: return "" def hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs): specificErrorMessage = "" queue = Queue() lastOccurence = fileToCheck.rfind("/") file_name = fileToCheck[lastOccurence + 1:len(fileToCheck) - 3] print filter_specs if desiredInterface == 1: file_metaData = analytics.utils.get_metadata(file_name) elif desiredInterface == 2: file_metaData = visualization.utils.get_metadata(file_name) elif desiredInterface == 3: file_metaData = dataloader.utils.get_metadata(file_name, "ingest") elif desiredInterface == 4: file_metaData = dataloader.utils.get_metadata(file_name, "filters") inputList = [] if desiredInterface != 3 and desiredInterface != 4: for elem in file_metaData['inputs']: inputList.append(elem) inputDict = create_input_dict(my_dir, inputList) if desiredInterface == 1: count = 0 computeResult = analytics.utils.run_analysis(queue, file_name, file_metaData['parameters'], inputDict, output_directory, "Result") for file in os.listdir(my_dir): if fnmatch.fnmatch(file, "*.csv") or fnmatch.fnmatch(file, ".json"): count += 1 if (count < 1): specificErrorMessage += "Missing .csv or .json file, the compute function must create a new .csv or .json file." for file_name in os.listdir(output_directory): os.remove(os.path.join(output_directory, file_name)) elif desiredInterface == 2: createResult = visualization.utils.generate_vis(file_name, inputDict, file_metaData['parameters']) if (type(createResult) != dict): specificErrorMessage += "Missing a dict return, create function must return a dict item." elif desiredInterface == 3: filter_specs_dict = json.loads(str(filter_specs)) exploreResult = dataloader.utils.explore(file_name, my_dir, []) exploreResultList = list(exploreResult) count = 0 typeOfMatrix = [] matrix = "" nameOfSource = "" filterOfMatrix = [] for elem in exploreResult: if type(elem) == dict: for key in elem.keys(): nameOfSource = str(key) if len(elem.values()) == 1: for value in elem.values(): while count < len(value): for item in value[count].keys(): if item == "type": matrix = str(value[count]['type']) matrix = matrix[2:len(matrix) - 2] typeOfMatrix.append(matrix) if item == "key_usr": filterOfMatrix.append(str(value[count]['key_usr'])) count += 1 typeListExplore = [] posted_data = { 'matrixFilters':{}, 'matrixFeatures':[], 'matrixFeaturesOriginal':[], 'matrixName':"test", 'sourceName':nameOfSource, 'matrixTypes':[] } # posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"DocumentLEAN","filter_id":"DocumentLEAN","parameters":[],"stage":"before","type":"extract"}}) #for Text # posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"TweetDocumentLEAN","filter_id":"TweetDocumentLEAN","parameters":[{"attrname":"include","name":"Include the following keywords","type":"input","value":""},{"attrname":"sent","value":"No"},{"attrname":"exclude","name":"Exclude the following keywords","type":"input","value":""},{"attrname":"lang","name":"Language","type":"input","value":""},{"attrname":"limit","name":"Limit","type":"input","value":"10"},{"attrname":"start","name":"Start time","type":"input","value":""},{"attrname":"end","name":"End time","type":"input","value":""},{"attrname":"geo","name":"Geo","type":"input","value":""}],"stage":"before","type":"extract"}}) #for Mongo posted_data['matrixFilters'].update({filterOfMatrix[0]:filter_specs_dict}) # posted_data['matrixFilters'].update({filterOfMatrix[0]:{}}) #for spreadsheet posted_data['matrixFeatures'].append(filterOfMatrix[0]) posted_data['matrixFeaturesOriginal'].append(filterOfMatrix[0]) posted_data['matrixTypes'].append(typeOfMatrix[0]) secondToLastOccurence = my_dir.rfind("/", 0, my_dir.rfind("/")) my_dir = my_dir[:secondToLastOccurence + 1] src = { 'created':dataloader.utils.getCurrentTime(), 'host': "127.0.1.1", 'ingest_id':file_name, 'matrices':[], 'name': nameOfSource, 'rootdir':my_dir, 'src_id': "test_files", 'src_type':"file" } ingestResult = dataloader.utils.ingest(posted_data, src) ingestResultList = list(ingestResult) typeListIngest = [] for i in range(len(exploreResultList)): typeListExplore.append(type(exploreResultList[i])) for i in range(len(ingestResultList)): typeListIngest.append(type(ingestResultList[i])) for file in os.listdir(my_dir): if os.path.isdir(my_dir + file) and len(file) > 15: shutil.rmtree(my_dir + file + "/") if file.startswith("reduced_"): os.remove(os.path.join(my_dir, file)) if dict in typeListExplore and int not in typeListExplore: specificErrorMessage += "Missing a int, explore function must return both a dict and a int." elif dict not in typeListExplore and int in typeListExplore: specificErrorMessage += "Missing a dict, explore function must return both a dict and a int." elif dict not in typeListExplore and int not in typeListExplore: specificErrorMessage += "Missing a dict and int, explore function must return both a dict and a int." if bool in typeListIngest and list not in typeListIngest: specificErrorMessage += " Missing a list, ingest function must return both a boolean and a list." elif bool not in typeListIngest and list in typeListIngest: specificErrorMessage += " Missing a boolean value, ingest function must return both a boolean and a list." elif bool not in typeListIngest and list not in typeListIngest: specificErrorMessage += " Missing a boolean value and list, ingest function must return both a boolean and a list." elif desiredInterface == 4: conf = { 'mat_id':'27651d66d4cf4375a75208d3482476ac', 'storepath':'/home/vagrant/bedrock/bedrock-core/caa1a3105a22477f8f9b4a3124cd41b6/source/', 'src_id':'caa1a3105a22477f8f9b4a3124cd41b6', 'name':'iris' } checkResult = dataloader.utils.check(file_name, file_metaData['name'], conf) if type(checkResult) != bool: specificErrorMessage += "Missing boolean value, check funtion must return a boolean value." applyResult = dataloader.utils.apply(file_name, file_metaData['parameters'], conf) if type(applyResult) != dict: specificErrorMessage += " Missing a dict object, apply function must return a dict object." return specificErrorMessage def create_input_dict(my_dir, inputList): returnDict = {} i = 0 j = 1 length = len(inputList) for file in os.listdir(my_dir): if file in inputList: if length == 1 or (length > 1 and file != inputList[length - 1]) or (length > 1 and inputList[i] != inputList[i + 1]): returnDict.update({file:{'rootdir':my_dir}}) elif length > 1 and inputList[i] == inputList[i + 1]: firstNewFile = file + "_" + str(j) j += 1 returnDict.update({firstNewFile:{'rootdir':my_dir}}) if j > 1: secondNewFile = file + "_" + str(j) returnDict.update({secondNewFile:{'rootdir':my_dir}}) i += 1 length -= 1 return returnDict parser = argparse.ArgumentParser(description="Validate files being added to system.") parser.add_argument('--api', help="The API where the file is trying to be inserted.", action='store', required=True, metavar='api') parser.add_argument('--filename', help="Name of file inlcuding entire file path.", action='store', required=True, metavar='filename') parser.add_argument('--input_directory', help="Directory where necessary inputs are stored", action='store', required=True, metavar='input_directory') parser.add_argument('--filter_specs', help="Specifications for a used filter.", action='store', required=True, metavar='filter_specs') parser.add_argument('--output_directory', help='Directory where outputs are stored (type NA if there will be no outputs).', action='store', required=True, metavar='output_directory') args = parser.parse_args() desiredInterface = 0 fileToCheck = args.filename if args.api.lower() == "analytics": desiredInterface = 1 elif args.api.lower() == "visualization": desiredInterface = 2 elif args.api.lower() == "ingest": desiredInterface = 3 elif args.api.lower() == "filter": desiredInterface = 4 my_dir = args.input_directory output_directory = args.output_directory filter_specs = args.filter_specs errorMessage = "" errorMessage += str(find_imports(fileToCheck, desiredInterface)) errorMessage += str(compare_fuctions(fileToCheck, desiredInterface)) errorMessage += str(inheritance_check(fileToCheck, desiredInterface)) errorMessage += str(validate_file_name(fileToCheck, desiredInterface)) errorMessage += str(check_return_values(fileToCheck, desiredInterface)) if len(errorMessage) == 0: print("File has been validated and is ready for input") else: print("Error Log: ") print(errorMessage) print(hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs))
lgpl-3.0
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/PackageActionError.php
1058
<?php namespace Google\AdsApi\Dfp\v201711; /** * This file was generated from WSDL. DO NOT EDIT. */ class PackageActionError extends \Google\AdsApi\Dfp\v201711\ApiError { /** * @var string $reason */ protected $reason = null; /** * @param string $fieldPath * @param \Google\AdsApi\Dfp\v201711\FieldPathElement[] $fieldPathElements * @param string $trigger * @param string $errorString * @param string $reason */ public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null) { parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString); $this->reason = $reason; } /** * @return string */ public function getReason() { return $this->reason; } /** * @param string $reason * @return \Google\AdsApi\Dfp\v201711\PackageActionError */ public function setReason($reason) { $this->reason = $reason; return $this; } }
lgpl-3.0
kidaa/Awakening-Core3
src/server/zone/objects/creature/PatrolPoint.h
5091
/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. 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 program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #ifndef PATROLPOINT_H_ #define PATROLPOINT_H_ #include "system/lang.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/cell/CellObject.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/scene/WorldCoordinates.h" class PatrolPoint : public Serializable { WorldCoordinates position; bool reached; Time estimatedTimeOfArrival; public: PatrolPoint() { reached = true; addSerializableVariables(); } PatrolPoint(const Vector3& pos, SceneObject* cell = NULL) : position(pos, cell) { reached = false; addSerializableVariables(); } PatrolPoint(float posX, float posZ, float posY, SceneObject* cell = NULL) : position(Vector3(posX, posY, posZ), cell) { reached = false; addSerializableVariables(); } PatrolPoint(const PatrolPoint& point) : Object(), Serializable() { position = point.position; reached = point.reached; addSerializableVariables(); } PatrolPoint& operator=(const PatrolPoint& p) { if (this == &p) return *this; position = p.position; reached = p.reached; return *this; } inline void addSerializableVariables() { addSerializableVariable("position", &position); addSerializableVariable("reached", &reached); addSerializableVariable("estimatedTimeOfArrival", &estimatedTimeOfArrival); } Vector3 getWorldPosition() { return position.getWorldPosition(); } bool isInRange(SceneObject* obj, float range) { Vector3 thisWorldPos = getWorldPosition(); Vector3 objWorldPos = obj->getWorldPosition(); return thisWorldPos.squaredDistanceTo(objWorldPos) <= (range * range); } bool isInRange(PatrolPoint* obj, float range) { Vector3 thisWorldPos = getWorldPosition(); Vector3 objWorldPos = obj->getWorldPosition(); return thisWorldPos.squaredDistanceTo(objWorldPos) <= (range * range); } inline WorldCoordinates getCoordinates() { return position; } //getters inline float getPositionX() { return position.getX(); } inline float getPositionY() { return position.getY(); } inline float getPositionZ() { return position.getZ(); } inline SceneObject* getCell() { return position.getCell(); } inline Time* getEstimatedTimeOfArrival() { return &estimatedTimeOfArrival; } inline bool isReached() { return reached; } inline bool isPastTimeOfArrival() { return estimatedTimeOfArrival.isPast() || estimatedTimeOfArrival.isPresent(); } //setters inline void setPosition(float x, float z, float y) { position.setCoordinates(Vector3(x, y, z)); } inline void setPositionX(float x) { position.setX(x); } inline void setPositionZ(float z) { position.setZ(z); } inline void setPositionY(float y) { position.setY(y); } inline void setCell(SceneObject* cell) { if ((cell != NULL && cell->isCellObject()) || cell == NULL) position.setCell(cell); } inline void setReached(bool value) { reached = value; } inline void addEstimatedTimeOfArrival(uint32 mili) { estimatedTimeOfArrival.updateToCurrentTime(); estimatedTimeOfArrival.addMiliTime(mili); } }; #endif /*PATROLPOINT_H_*/
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/mobile/lair/creature_lair/endor_gurreck_cowardly_lair_neutral_small.lua
310
endor_gurreck_cowardly_lair_neutral_small = Lair:new { mobiles = {}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {}, } addLairTemplate("endor_gurreck_cowardly_lair_neutral_small", endor_gurreck_cowardly_lair_neutral_small)
lgpl-3.0
cugone/Abrams2012
Allegro2DEngine/Engine/Math/CShape.cpp
12152
/************************************************************************************************** // file: Engine\Math\CShape.cpp // A2DE // Copyright (c) 2013 Blisspoint Softworks and Casey Ugone. All rights reserved. // Contact [email protected] for questions or support. // summary: Implements the shape class **************************************************************************************************/ #include "CShape.h" #include "CPoint.h" #include "CLine.h" #include "CRectangle.h" #include "CCircle.h" #include "CEllipse.h" #include "CTriangle.h" #include "CArc.h" #include "CPolygon.h" #include "CSpline.h" #include "CSector.h" A2DE_BEGIN Shape::Shape() : _position(0.0, 0.0), _half_extents(0.0, 0.0), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(double x, double y) : _position(x, y), _half_extents(0.0, 0.0), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(const Vector2D& position) : _position(position), _half_extents(0.0, 0.0), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(double x, double y, double half_width, double half_height) : _position(x, y), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(const Vector2D& position, double half_width, double half_height) : _position(position), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(double x, double y, const Vector2D& half_extents) : _position(x, y), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(const Vector2D& position, const Vector2D& half_extents) : _position(position), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(al_map_rgb(0, 0, 0)), _filled(false) { } Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color) : _position(x, y), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(false) { } Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color) : _position(position), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(false) { } Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color) : _position(x, y), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(false) { } Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color) : _position(position), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(false) { } Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) : _position(x, y), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(filled) { } Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) : _position(position), _half_extents(half_width, half_height), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(filled) { } Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) : _position(x, y), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(filled) { } Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) : _position(position), _half_extents(half_extents), _area(0.0), _type(Shape::SHAPETYPE_SHAPE), _color(color), _filled(filled) { } Shape::Shape(const Shape& shape) : _position(shape._position), _half_extents(shape._half_extents), _area(shape._area), _type(Shape::SHAPETYPE_SHAPE), _color(shape._color), _filled(shape._filled) { } Shape& Shape::operator=(const Shape& rhs) { if(this == &rhs) return *this; this->_position = rhs._position; this->_half_extents = rhs._half_extents; this->_area = rhs._area; this->_type = rhs._type; this->_color = rhs._color; this->_filled = rhs._filled; return *this; } Shape::~Shape() { } const ALLEGRO_COLOR& Shape::GetColor() const { return _color; } ALLEGRO_COLOR& Shape::GetColor() { return const_cast<ALLEGRO_COLOR&>(static_cast<const Shape&>(*this).GetColor()); } bool Shape::IsFilled() const { return _filled; } void Shape::SetColor(const ALLEGRO_COLOR& color) { _color = color; } void Shape::SetFill(bool filled) { _filled = filled; } double Shape::GetHalfWidth() const { return _half_extents.GetX(); } double Shape::GetHalfWidth(){ return static_cast<const Shape&>(*this).GetHalfWidth(); } double Shape::GetHalfHeight() const { return _half_extents.GetY(); } double Shape::GetHalfHeight() { return static_cast<const Shape&>(*this).GetHalfHeight(); } const Vector2D& Shape::GetHalfExtents() const { return _half_extents; } Vector2D& Shape::GetHalfExtents() { return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetHalfExtents()); } const Vector2D& Shape::GetPosition() const { return _position; } Vector2D& Shape::GetPosition() { return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetPosition()); } double Shape::GetArea() const { return _area; } double Shape::GetArea() { return static_cast<const Shape&>(*this).GetArea(); } double Shape::GetX() const { return _position.GetX(); } double Shape::GetX() { return static_cast<const Shape&>(*this).GetX(); } double Shape::GetY() const { return _position.GetY(); } double Shape::GetY() { return static_cast<const Shape&>(*this).GetY(); } void Shape::SetX(double x) { SetPosition(x, GetY()); } void Shape::SetY(double y) { SetPosition(GetX(), y); } void Shape::SetPosition(double x, double y) { SetPosition(Vector2D(x, y)); } void Shape::SetPosition(const Vector2D& position) { _position = position; } void Shape::SetHalfWidth(double width) { SetHalfExtents(width, GetHalfHeight()); } void Shape::SetHalfHeight(double height) { SetHalfExtents(GetHalfWidth(), height); } void Shape::SetHalfExtents(double width, double height) { SetHalfExtents(Vector2D(width, height)); } void Shape::SetHalfExtents(const Vector2D& dimensions) { _half_extents = dimensions; } const Shape::SHAPE_TYPE& Shape::GetShapeType() const { return _type; } Shape::SHAPE_TYPE& Shape::GetShapeType() { return const_cast<Shape::SHAPE_TYPE&>(static_cast<const Shape&>(*this).GetShapeType()); } Shape* Shape::Clone(Shape* shape) { if(shape == nullptr) return nullptr; Shape::SHAPE_TYPE type = shape->GetShapeType(); switch(type) { case Shape::SHAPETYPE_POINT: return new Point(*dynamic_cast<Point*>(shape)); case Shape::SHAPETYPE_LINE: return new Line(*dynamic_cast<Line*>(shape)); case Shape::SHAPETYPE_RECTANGLE: return new Rectangle(*dynamic_cast<Rectangle*>(shape)); case Shape::SHAPETYPE_CIRCLE: return new Circle(*dynamic_cast<Circle*>(shape)); case Shape::SHAPETYPE_ELLIPSE: return new Ellipse(*dynamic_cast<Ellipse*>(shape)); case Shape::SHAPETYPE_TRIANGLE: return new Triangle(*dynamic_cast<Triangle*>(shape)); case Shape::SHAPETYPE_ARC: return new Arc(*dynamic_cast<Arc*>(shape)); case Shape::SHAPETYPE_POLYGON: return new Polygon(*dynamic_cast<Polygon*>(shape)); case Shape::SHAPETYPE_SPLINE: return new Spline(*dynamic_cast<Spline*>(shape)); case Shape::SHAPETYPE_SECTOR: return new Sector(*dynamic_cast<Sector*>(shape)); default: return nullptr; } } bool Shape::Contains(const Shape& shape) const { Shape::SHAPE_TYPE type = shape.GetShapeType(); switch(type) { case Shape::SHAPETYPE_POINT: return this->Contains(dynamic_cast<const Point&>(shape)); case Shape::SHAPETYPE_LINE: return this->Contains(dynamic_cast<const Line&>(shape)); case Shape::SHAPETYPE_RECTANGLE: return this->Contains(dynamic_cast<const Rectangle&>(shape)); case Shape::SHAPETYPE_CIRCLE: return this->Contains(dynamic_cast<const Circle&>(shape)); case Shape::SHAPETYPE_ELLIPSE: return this->Contains(dynamic_cast<const Ellipse&>(shape)); case Shape::SHAPETYPE_TRIANGLE: return this->Contains(dynamic_cast<const Triangle&>(shape)); case Shape::SHAPETYPE_ARC: return this->Contains(dynamic_cast<const Arc&>(shape)); case Shape::SHAPETYPE_POLYGON: return this->Contains(dynamic_cast<const Polygon&>(shape)); case Shape::SHAPETYPE_SPLINE: return this->Contains(dynamic_cast<const Spline&>(shape)); case Shape::SHAPETYPE_SECTOR: return this->Contains(dynamic_cast<const Sector&>(shape)); default: return false; } } bool Shape::Contains(const Point& point) const { return this->Intersects(point); } bool Shape::Contains(const Line& line) const { return this->Intersects(line.GetPointOne()) && this->Intersects(line.GetPointTwo()); } bool Shape::Contains(const Rectangle& rectangle) const { double rleft = rectangle.GetX(); double rtop = rectangle.GetY(); double rright = rleft + rectangle.GetHalfWidth(); double rbottom = rtop + rectangle.GetHalfHeight(); double tleft = this->GetX(); double ttop = this->GetY(); double tright = tleft + this->GetHalfWidth(); double tbottom = ttop + this->GetHalfHeight(); bool is_exact = a2de::Math::IsEqual(rtop, ttop) && a2de::Math::IsEqual(rleft, tleft) && a2de::Math::IsEqual(rbottom, tbottom) && a2de::Math::IsEqual(rright, tright); bool is_smaller = (rtop > ttop && rleft > tleft && rbottom < tbottom && rright < tright); return (is_exact || is_smaller); } bool Shape::Contains(const Circle& circle) const { double cdiameter = circle.GetDiameter(); double twidth = this->GetHalfWidth(); double theight = this->GetHalfHeight(); bool diameter_equal_to_width = a2de::Math::IsEqual(cdiameter, twidth); bool diameter_equal_to_height = a2de::Math::IsEqual(cdiameter, theight); bool diameter_less_than_width = cdiameter < twidth; bool diameter_less_than_height = cdiameter < theight; bool diameter_less_equal_width = diameter_less_than_width || diameter_equal_to_width; bool diameter_less_equal_height = diameter_less_than_height || diameter_equal_to_height; bool center_inside_shape = this->Intersects(Point(circle.GetPosition())); bool contains = center_inside_shape && diameter_less_equal_width && diameter_less_equal_height; return contains; } bool Shape::Contains(const Ellipse& ellipse) const { return this->Intersects(Point(ellipse.GetPosition())) && ellipse.GetHalfWidth() <= this->GetHalfWidth() && ellipse.GetHalfHeight() <= this->GetHalfHeight(); } bool Shape::Contains(const Triangle& triangle) const { return this->Intersects(Point(triangle.GetPointA())) && this->Intersects(Point(triangle.GetPointB())) && this->Intersects(Point(triangle.GetPointC())); } bool Shape::Contains(const Arc& arc) const { return this->Intersects(arc.GetStartPoint()) && this->Intersects(arc.GetEndPoint()); } bool Shape::Contains(const Polygon& polygon) const { int total_points = polygon.GetNumVertices(); for(int i = 0; i < total_points; ++i) { if(this->Intersects(polygon.GetVertices()[i])) continue; return false; } return true; } bool Shape::Contains(const Spline& /*spline*/) const { return false; } bool Shape::Contains(const Sector& sector) const { return this->Intersects(sector.GetStartPoint()) && this->Intersects(sector.GetEndPoint()) && this->Intersects(Point(sector.GetPosition())); } void Shape::Draw(ALLEGRO_BITMAP* dest) { this->Draw(dest, _color, _filled); } A2DE_END
lgpl-3.0
Venne/Venne-CMS-old
App/SecurityModule/AdminModule/presenters/DefaultPresenter.php
477
<?php /** * Venne:CMS (version 2.0-dev released on $WCDATE$) * * Copyright (c) 2011 Josef Kříž [email protected] * * For the full copyright and license information, please view * the file license.txt that was distributed with this source code. */ namespace App\SecurityModule\AdminModule; /** * @author Josef Kříž * @resource AdminModule\SecurityModule\Security */ class DefaultPresenter extends BasePresenter { public function renderDefault() { } }
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/dxguid/X64/d3dxguid000000E2.c
462
// Created file "Lib\src\dxguid\X64\d3dxguid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_ID3DXEffectCompiler, 0x51b8a949, 0x1a31, 0x47e6, 0xbe, 0xa0, 0x4b, 0x30, 0xdb, 0x53, 0xf1, 0xe0);
lgpl-3.0
DGLE-HQ/DGLE
src/tools/packer/TreeViewExtensions.cs
940
/** \author Shestakov Mikhail aka MIKE \date 12.12.2012 (c)Andrey Korotkov This file is a part of DGLE project and is distributed under the terms of the GNU Lesser General Public License. See "DGLE.h" for more details. */ using System; using System.Collections.Generic; using System.Linq; using Gtk; namespace Packer { public static class TreeViewExtensions { public static IEnumerable<TreeIter> GetSelected(this TreeView tree) { return tree.Selection.GetSelectedRows().ToList().Select(path => { TreeIter selectedIter; if (tree.Model.GetIter(out selectedIter, path)) return selectedIter; return TreeIter.Zero; }); } public static void SelectAndFocus(this TreeView tree, TreeIter iter) { tree.Selection.SelectIter(iter); tree.GrabFocus(); } public static void SelectAndFocus(this TreeView tree, TreePath path) { tree.Selection.SelectPath(path); tree.GrabFocus(); } } }
lgpl-3.0
BenjaminW3/vecadd
include/vecadd/vecadd.h
1211
//----------------------------------------------------------------------------- //! \file //! Copyright 2015 Benjamin Worpitz //! //! This file is part of vecadd. //! //! vecadd 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. //! //! vecadd 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 alpha copy of the GNU Lesser General Public License //! along with vecadd. //! If not, see <http://www.gnu.org/licenses/>. //----------------------------------------------------------------------------- #pragma once #include <vecadd/seq/Basic.h> #include <vecadd/par/Alpaka.h> #include <vecadd/par/Cuda.h> #include <vecadd/par/Omp.h> #include <vecadd/common/Alloc.h> #include <vecadd/common/Array.h> #include <vecadd/common/Config.h> #include <vecadd/common/Vec.h> #include <vecadd/common/Time.h>
lgpl-3.0
kidaa/Awakening-Core3
doc/html/_resource_tree_8h.html
4546
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: /Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/managers/resource/resourcespawner/resourcetree/ResourceTree.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_075bb3ff235063c77951cd176d15a741.html">server</a></li><li class="navelem"><a class="el" href="dir_9e27d73ba17b043ea65c9708c594875e.html">zone</a></li><li class="navelem"><a class="el" href="dir_09f2800c98a68987a1cd7da559bc6100.html">managers</a></li><li class="navelem"><a class="el" href="dir_867d52b0c818895b00ba000f478b19bb.html">resource</a></li><li class="navelem"><a class="el" href="dir_78d782cd574a03c21f0175f09125053d.html">resourcespawner</a></li><li class="navelem"><a class="el" href="dir_ef15fad82ca0d9895b177fe85cfcaded.html">resourcetree</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <div class="title">ResourceTree.h File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="_resource_tree_node_8h_source.html">ResourceTreeNode.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="_resource_tree_entry_8h_source.html">ResourceTreeEntry.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="_data_table_iff_8h_source.html">server/zone/templates/datatables/DataTableIff.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="_data_table_row_8h_source.html">server/zone/templates/datatables/DataTableRow.h</a>&quot;</code><br/> <code>#include &quot;<a class="el" href="_data_table_cell_8h_source.html">server/zone/templates/datatables/DataTableCell.h</a>&quot;</code><br/> </div> <p><a href="_resource_tree_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_resource_tree.html">ResourceTree</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><dl class="section author"><dt>Author</dt><dd>Kyle Burkhardt </dd></dl> <dl class="section date"><dt>Date</dt><dd>5-03-10 </dd></dl> <p>Definition in file <a class="el" href="_resource_tree_8h_source.html">ResourceTree.h</a>.</p> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:29:15 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
lgpl-3.0
ju1ius/pegasus
src/Parser/Exception/ParseError.php
122
<?php declare(strict_types=1); namespace ju1ius\Pegasus\Parser\Exception; class ParseError extends \RuntimeException {}
lgpl-3.0
consumentor/Server
trunk/docs/Releases/BETA/Database/Shopgun/Script/12.ImportCompanyAdvise - MentorInfoDB.sql
2837
DECLARE @search_object nvarchar(255), @mentor nvarchar(255), @semaphore nvarchar(255), @headline nvarchar(255),@introduction nvarchar(255), @runnning_text nvarchar(max), @last_updated datetime, @informer nvarchar(255), @initials nvarchar(255), @splitedRetVal nvarchar(max), @valAlreadyExists nvarchar(255) DECLARE mentor_advices_cursor CURSOR LOCAL FOR SELECT [MentorInfo].[dbo].[Advices].[Search objekt], [MentorInfo].[dbo].[Advices].[Mentor], [MentorInfo].[dbo].[Advices].[Colour signal], [MentorInfo].[dbo].[Advices].[Headline], [MentorInfo].[dbo].[Advices].Introduction, [MentorInfo].[dbo].[Advices].[Running Text], [MentorInfo].[dbo].[Advices].[Date], [MentorInfo].[dbo].[Advices].[Informer], [MentorInfo].[dbo].[Advices].[Initials] FROM [MentorInfo].[dbo].[Advices] WHERE [PA-level] = 'Företag' ORDER BY Mentor, [Date], [Search objekt] OPEN mentor_advices_cursor FETCH NEXT FROM mentor_advices_cursor INTO @search_object, @mentor, @semaphore, @headline,@introduction, @runnning_text, @last_updated, @informer, @initials DECLARE @companysId int, @mentorId int, @semaphoreId int WHILE @@FETCH_STATUS = 0 BEGIN SELECT @splitedRetVal = '', @valAlreadyExists = '' SELECT TOP 1 @splitedRetVal = val FROM [master].dbo.SPLIT(@search_object,1,0) --DEGUG : SELECT @splitedRetVal --SELECT @valAlreadyExists = [Shopgun].[dbo].Ingredients.IngredientName --FROM [Shopgun].[dbo].Ingredients --WHERE IngredientName = @splitedRetVal --DEGUG : SELECT @valAlreadyExists SELECT @mentorId = [Shopgun].[dbo].Mentors.Id FROM [Shopgun].[dbo].Mentors WHERE [Shopgun].[dbo].Mentors.MentorName = @mentor SELECT @companysId = [Shopgun].[dbo].Companies.Id FROM [Shopgun].[dbo].Companies WHERE [Shopgun].[dbo].Companies.Name = @splitedRetVal SELECT @semaphoreId = [Shopgun].[dbo].Semaphore.Id FROM [Shopgun].[dbo].Semaphore WHERE [Shopgun].[dbo].Semaphore.ColorName = @semaphore IF NOT (@mentorId IS NULL OR @companysId IS NULL OR @semaphoreId IS NULL) BEGIN INSERT INTO [Shopgun].[dbo].[Advices] ([CompanysId] , [AdviceType] ,[MentorId] ,[Label] ,[Introduction] ,[Advice] ,[KeyWords] ,[SemaphoreId] ,[Published] ,[PublishDate]) VALUES(@companysId,'CompanyAdvice',@mentorId, @headline, @introduction, @runnning_text, @search_object, @semaphoreId, 1, @last_updated) --DEGUG : SELECT @companysId, 'IngredientAdvice', @mentorId, @headline, @introduction, @runnning_text, --DEGUG : @search_object, @semaphoreId, 1, @last_updated END FETCH NEXT FROM mentor_advices_cursor INTO @search_object, @mentor, @semaphore, @headline,@introduction, @runnning_text, @last_updated, @informer, @initials END CLOSE mentor_advices_cursor DEALLOCATE mentor_advices_cursor
lgpl-3.0
Martin-P/OpenV2G
src/appHandshake/appHandEXIDatatypesDecoder.h
1490
/* * Copyright (C) 2007-2018 Siemens AG * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 program. If not, see <http://www.gnu.org/licenses/>. */ /******************************************************************* * * @author [email protected] * @version 0.9.4 * @contact [email protected] * * <p>Code generated by EXIdizer</p> * <p>Schema: V2G_CI_AppProtocol.xsd</p> * * ********************************************************************/ /** * \file EXIDatatypesDecoder.h * \brief Decoder for datatype definitions * */ #ifndef EXI_appHand_DATATYPES_DECODER_H #define EXI_appHand_DATATYPES_DECODER_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include "EXITypes.h" #include "appHandEXIDatatypes.h" int decode_appHandExiDocument(bitstream_t* stream, struct appHandEXIDocument* exiDoc); #ifdef __cplusplus } #endif #endif
lgpl-3.0
erelsgl/erel-sites
tnk1/kma/qjrim2/prs.html
31275
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1255' /> <meta charset='windows-1255' /> <meta http-equiv='Content-Script-Type' content='text/javascript' /> <meta http-equiv='revisit-after' content='15 days' /> <title>îìëé ôøñ áúð&quot;ê</title> <link rel='stylesheet' type='text/css' href='../../../_script/klli.css' /> <link rel='stylesheet' type='text/css' href='../../../tnk1/_themes/klli.css' /> <meta property='og:url' content='https://tora.us.fm/tnk1/kma/qjrim2/prs.html'/> <meta name='author' content="àøàì" /> <meta name='receiver' content="" /> <meta name='jmQovc' content="tnk1/kma/qjrim2/prs.html" /> <meta name='tvnit' content="" /> <link rel='canonical' href='https://tora.us.fm/tnk1/kma/qjrim2/prs.html' /> </head> <!-- PHP Programming by Erel Segal-Halevi --> <body lang='he' dir='rtl' id = 'tnk1_kma_qjrim2_prs' class='kll '> <div class='pnim'> <script type='text/javascript' src='../../../_script/vars.js'></script> <!--NiwutElyon0--> <div class='NiwutElyon'> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tryg/index.html'>äàúø ìî÷åøéåú áîöååú</a>&gt;<a href='../../../tryg/sug/rayon.html'>îöååú ìôé øòéåï</a>&gt;<a href='../../../tryg/sug/rayon_1.html'>ä' åäàãí</a>&gt;<a href='../../../tryg/sug/rayon_hodyh.html'>äåãéä ìä'</a>&gt;<a href='../../../tryg/mamr/xgim.html'>çâé ääåãéä</a>&gt;<a href='../../../tryg/mamr/pwrym.html'>çâ ôåøéí</a>&gt;<a href='../../../tnk1/prqim/t33.htm'>àñúø</a>&gt;<a href='../../../tnk1/ezor/prs.html'>äñèåøéä åàøëéàåìåâéä ùì ôøñ</a>&gt;</div> </div> <!--NiwutElyon1--> <h1 id='h1'>îìëé ôøñ áúð"ê</h1> <div id='idfields'> <p>÷åã: îìëé ôøñ áúð"ê áúð"ê</p> <p>ñåâ: ëìì</p> <p>îàú: àøàì</p> <p>àì: </p> </div> <script type='text/javascript'>kotrt()</script> <div id='tokn'> <p>áúð"ê ðæëøå ëîä îìëéí ôøñééí, åëãé ìäáéï àú äø÷ò ìàéøåòé äúð"ê øàåé ìáøø àú ñãø äæîðéí áéðéäí. ðáãå÷ ÷åãí-ëì àú äùîåú åäéëï äí ðæëøéí. <br /></p> <h2>à. ëåøù</h2> <p>ëåøù ðæëø ëáø áðáåàåú <strong>éùòéäå</strong>, ëîìê ùéëáåù âåééí åîìëéí, åéñééò ìáðééï éøåùìéí,&nbsp; <a data-cke-saved-href="/tnk1/prqim/t1044.htm#28" href="/tnk1/prqim/t1044.htm#28" class="psuq">éùòéäå îã28</a>: "<q class="psuq">äÈàÉîÅø <strong>ìÀë&#64331;øÆ&#64298;</strong> øÉòÄé åÀëÈì çÆôÀöÄé éÇ&#64298;ÀìÄí, åÀìÅàîÉø ìÄéø&#64309;&#64298;ÈìÇéí &#64330;Ä&#64305;ÈðÆä åÀäÅéëÈì &#64330;Ä&#64309;ÈñÅã</q>";&nbsp; <a data-cke-saved-href="/tnk1/prqim/t1045.htm#1" href="/tnk1/prqim/t1045.htm#1" class="psuq">éùòéäå îä1</a>: "<q class="psuq">&#64315;Éä &#64303;îÇø ä' ìÄîÀ&#64298;Äéç&#64331; <strong>ìÀë&#64331;øÆ&#64298;</strong> àÂ&#64298;Æø äÆçÁæÇ÷À&#64330;Äé áÄéîÄéð&#64331;, ìÀøÇã ìÀôÈðÈéå &#64306;&#64331;&#64285;í &#64309;îÈúÀðÅé îÀìÈëÄéí àÂôÇ&#64330;ÅçÇ, ìÄôÀ&#64330;ÉçÇ ìÀôÈðÈéå &#64307;ÀìÈúÇ&#64285;í &#64309;&#64298;ÀòÈøÄéí ìÉà &#64285;&#64321;ÈâÅø&#64309;</q>".</p> <p>ëåøù ðæëø ëîä ôòîéí âí áñôø <strong>ãðéàì</strong>. ãðéàì âìä ìááì ëùäéä ðòø, òåã áéîé äîìê éäåéëéï. äåà øàä àú ñåôä ùì îìëåú ááì áéîé áìùöø, åçé âí áéîé îìëé ôøñ,&nbsp; <a data-cke-saved-href="/tnk1/prqim/t3401.htm#21" href="/tnk1/prqim/t3401.htm#21" class="psuq">ãðéàì à21</a>: "<q class="psuq">åÇéÀäÄé &#64307;ÈðÄ&#64313;Åàì òÇã &#64298;ÀðÇú &#64302;çÇú <strong>ìÀë&#64331;øÆ&#64298;</strong> äÇ&#64318;ÆìÆêÀ</q>", <a data-cke-saved-href="/tnk1/prqim/t3406.htm#29" href="/tnk1/prqim/t3406.htm#29" class="psuq">ãðéàì å29</a>: "<q class="psuq">åÀãÈðÄ&#64313;Åàì &#64307;ÀðÈä äÇöÀìÇç &#64305;ÀîÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> &#64309;áÀîÇìÀë&#64309;ú <strong>&#64315;&#64331;øÆ&#64298;</strong> ôøñéà[ôÌÈøÀñÈàÈä]</q>",&nbsp; <a data-cke-saved-href="/tnk1/prqim/t3410.htm#1" href="/tnk1/prqim/t3410.htm#1" class="psuq">ãðéàì é1</a>: "<q class="psuq">&#64305;Ä&#64298;ÀðÇú &#64298;Èì&#64331;&#64298; <strong>ìÀë&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, &#64307;ÈáÈø ðÄâÀìÈä ìÀãÈðÄ&#64313;Åàì...</q>".</p> <p>áñôø <strong>ãáøé äéîéí</strong> îñåôø, ùîééã ìàçø ùòìä ìùìèåï, ðúï ëåøù øùåú ìáðåú àú äî÷ãù, <a data-cke-saved-href="/tnk1/prqim/t25b36.htm#22" href="/tnk1/prqim/t25b36.htm#22" class="psuq">ãáøé äéîéí á ìå22-23</a>: "<q class="psuq">&#64309;áÄ&#64298;ÀðÇú &#64302;çÇú <strong>ìÀë&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, ìÄëÀì&#64331;ú &#64307;ÀáÇø ä' &#64305;ÀôÄé &#64285;øÀîÀéÈä&#64309;, äÅòÄéø ä' àÆú ø&#64309;çÇ <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, åÇ&#64313;ÇòÂáÆø ÷&#64331;ì &#64305;ÀëÈì îÇìÀë&#64309;ú&#64331; åÀâÇí &#64305;ÀîÄëÀ&#64330;Èá ìÅàîÉø: &#64315;Éä &#64303;îÇø <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ &#64315;Èì îÇîÀìÀë&#64331;ú äÈ&#64303;øÆõ ðÈúÇï ìÄé ä' àÁìÉäÅé äÇ&#64300;ÈîÇ&#64285;í åÀä&#64309;à ôÈ÷Çã òÈìÇé ìÄáÀð&#64331;ú ì&#64331; áÇ&#64285;ú &#64305;Äéø&#64309;&#64298;ÈìÇéí àÂ&#64298;Æø &#64305;Äéä&#64309;ãÈä îÄé áÈëÆí îÄ&#64315;Èì òÇ&#64318;&#64331; ä' àÁìÉäÈéå òÄ&#64318;&#64331; åÀéÈòÇì</q>" (<a data-cke-saved-href="/daat/kitveyet/mahanaim/avramsky.htm" href="/daat/kitveyet/mahanaim/avramsky.htm">ôéøåè</a>).</p> <p>äöäøä æå ðæëøú âí <strong>áñôø òæøà</strong> (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:òæøà_à_à" href="http://he.wikisource.org/wiki/áéàåø:òæøà_à_à">ôéøåè</a>), ùí ðæëø âí ùëåøù äåöéà àú ëìé áéú ä' ùâìå áéîé îìê ááì, <a data-cke-saved-href="/tnk1/prqim/t35a01.htm#8" href="/tnk1/prqim/t35a01.htm#8" class="psuq">òæøà à8</a>: "<q class="psuq">åÇ&#64313;&#64331;öÄéàÅí <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ òÇì éÇã îÄúÀøÀãÈú äÇ&#64306;ÄæÀ&#64305;Èø åÇ&#64313;ÄñÀ&#64324;ÀøÅí ìÀ&#64298;Å&#64298;À&#64305;Ç&#64326;Çø äÇ&#64320;È&#64299;Äéà ìÄéä&#64309;ãÈä</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:òæøà_à_ç" href="http://he.wikisource.org/wiki/áéàåø:òæøà_à_ç">ôéøåè</a>).&nbsp; ìàçø äöäøú ëåøù, òìå ìéäåãä òùøåú àìôé éäåãéí, áäðäâú æøåááì áï ùàìúéàì åéäåùò áï éäåöã÷, åäí äúçéìå ìáðåú àú äî÷ãù, <a data-cke-saved-href="/tnk1/prqim/t35a03.htm#7" href="/tnk1/prqim/t35a03.htm#7" class="psuq">òæøà â7</a>: "<q class="psuq">åÇ&#64313;Ä&#64330;Àð&#64309; ëÆñÆó ìÇçÉöÀáÄéí åÀìÆçÈøÈ&#64298;Äéí &#64309;îÇàÂëÈì &#64309;îÄ&#64298;À&#64330;Æä åÈ&#64298;ÆîÆï ìÇ&#64326;ÄãÉðÄéí åÀìÇ&#64326;ÉøÄéí, ìÀäÈáÄéà òÂöÅé àÂøÈæÄéí îÄï äÇ&#64316;ÀáÈð&#64331;ï àÆì éÈí éÈô&#64331;à &#64315;ÀøÄ&#64298;Àé&#64331;ï <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ òÂìÅéäÆí</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:òæøà_â_æ" href="http://he.wikisource.org/wiki/áéàåø:òæøà_â_æ">ôéøåè</a>).&nbsp; áäîùê (òæøà ã) îñåôø ùöøé éäåãä åáðéîéï øöå ìäùúúó ááðééï, àáì øàùé éäåãä ñéøáå, åëúåöàä îëê äöøéí ðéñå ìùáù àú äáðéä ò"é ôðéä ìùìèåðåú äôøñééí. äãáø äúçéì ëáø áéîé ëåøù, åðîùê áéîé äîìëéí ùàçøéå,&nbsp; <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#5" href="/tnk1/prqim/t35a04.htm#5" class="psuq">òæøà ã5-7</a>: "<q class="psuq">åÀñÉëÀøÄéí òÂìÅéäÆí é&#64331;òÂöÄéí ìÀäÈôÅø òÂöÈúÈí, &#64315;Èì éÀîÅé <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, åÀòÇã îÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÈñ. &#64309;áÀîÇìÀë&#64309;ú <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> &#64305;ÄúÀçÄ&#64316;Çú îÇìÀë&#64309;ú&#64331; &#64315;ÈúÀá&#64309; &#64299;ÄèÀðÈä òÇì éÉ&#64298;ÀáÅé éÀä&#64309;ãÈä åÄéø&#64309;&#64298;ÈìÈéí. åáéîé àøúçùùúà...</q>".</p> <p> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA" href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA">áúåìãåú ôøñ</a> éùðí ùðé îìëéí ùð÷øàå ëåøù (Kurus; äàåú s ð÷øàú ëîå ù éîðéú).</p> <ul> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%9B%D7%95%D7%A8%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F" href="https://he.wikipedia.org/wiki/%D7%9B%D7%95%D7%A8%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F">ëåøù äøàùåï</a> - äéä îåùì îçåæ àðùàï áôøñ, äéä ëôåó ìàùåøáðéôì îìê àùåø åàçøéå ìðáåôìñø îìê ááì. <br /></li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%9B%D7%95%D7%A8%D7%A9_%D7%94%D7%A9%D7%A0%D7%99" href="https://he.wikipedia.org/wiki/%D7%9B%D7%95%D7%A8%D7%A9_%D7%94%D7%A9%D7%A0%D7%99">ëåøù äùðé</a> - äéä ðëãå ùì ëåøù äøàùåï (îáðå ëðáåæé), åâí ðëãå ùì àñèéàâñ îìê îãé (îáúå). äåà îøã áîìê îãé, ëáù àú îãé åàçø-ëê àú ááì, ééñã àú äîîìëä äàçîðéú, åùìè áä ë-30 ùðä.</li></ul> <p>îñúáø, ùðáåàåú éùòéäå îúééçñåú ì <strong>ëåøù äøàùåï</strong>, ùçé áàåúä ú÷åôä. àåìí ëåøù ùðæëø áñôø ãðéàì, ãáøé-äéîéí åòæøà äåà <strong>ëåøù äùðé</strong>.&nbsp; ðáåàåú éùòéäå òì ëåøù äúâùîå ø÷ ìàçø ùðé ãåøåú, áéîé ðëãå, ùâí äåà ð÷øà ëåøù.</p> <h2>á. ãøéåù</h2> <p>îìê áùí <strong>ãøéåù äîãé</strong> ðæëø áñôø <strong>ãðéàì</strong>. äåà ÷éáì àú äîìëåú áâéì 62, îééã ìàçø ðôéìú ááì áéîé áìùöø, <a data-cke-saved-href="/tnk1/prqim/t3406.htm#1" href="/tnk1/prqim/t3406.htm#1" class="psuq">ãðéàì å1</a>: "<q class="psuq"><strong>åÀãÈøÀéÈåÆ&#64298; îãéà[îÈãÈàÈä]</strong> ÷Ç&#64305;Åì îÇìÀë&#64309;úÈà &#64315;ÀáÇø &#64298;ÀðÄéï &#64298;Ä&#64330;Äéï åÀúÇøÀ&#64330;Åéï.</q> <q class="psuq">&#64298;ÀôÇø ÷ÃãÈí <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> åÇäÂ÷Äéí òÇì îÇìÀë&#64309;úÈà ìÇàÂçÇ&#64298;À&#64307;ÇøÀ&#64324;ÀðÇ&#64313;Èà îÀ&#64303;ä åÀòÆ&#64299;ÀøÄéï &#64307;Äé ìäåï &#64305;ÀëÈì îÇìÀë&#64309;úÈà</q>" (<a data-cke-saved-href="/tnk1/kma/qjrim1/driws_mdy.html" href="/tnk1/kma/qjrim1/driws_mdy.html">ôéøåè</a>). îñåôø ùí, ùùøéå øöå ìôâåò áãðéàì åìîðåò îîðå ìäúôìì, àê îæéîúí ðëùìä åäîìê ãøéåù çì÷ ìå ëáåã. ìàçø îëï ðàîø ùãðéàì äöìéç áîìëåúå åâí áîìëåú ëåøù äôøñé, <a data-cke-saved-href="/tnk1/prqim/t3406.htm#29" href="/tnk1/prqim/t3406.htm#29" class="psuq">ãðéàì å29</a>: "<q class="psuq">åÀãÈðÄ&#64313;Åàì &#64307;ÀðÈä äÇöÀìÇç &#64305;ÀîÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> &#64309;áÀîÇìÀë&#64309;ú <strong>&#64315;&#64331;øÆ&#64298;</strong> ôøñéà[ôÌÈøÀñÈàÈä]</q>". áäîùê ñôø ãðéàì ðæëø <strong>ãøéåù áï àçùåøåù îæøò îãé</strong>, àùø äîìê òì ááì, <a data-cke-saved-href="/tnk1/prqim/t3409.htm#1" href="/tnk1/prqim/t3409.htm#1" class="psuq">ãðéàì è1</a>: "<q class="psuq">&#64305;Ä&#64298;ÀðÇú &#64302;çÇú <strong>ìÀãÈøÀéÈåÆ&#64298; &#64305;Æï àÂçÇ&#64298;ÀåÅø&#64331;&#64298; îÄ&#64310;ÆøÇò îÈãÈé</strong> àÂ&#64298;Æø äÈîÀìÇêÀ òÇì îÇìÀë&#64309;ú &#64315;Ç&#64299;À&#64307;Äéí</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:ãðéàì_è_à" href="http://he.wikisource.org/wiki/áéàåø:ãðéàì_è_à">ôéøåè</a>).&nbsp; äåà ðæëø âí á <a data-cke-saved-href="/tnk1/prqim/t3411.htm#1" href="/tnk1/prqim/t3411.htm#1" class="psuq">ãðéàì éà1</a>: "<q class="psuq">åÇàÂðÄé &#64305;Ä&#64298;ÀðÇú &#64302;çÇú <strong>ìÀãÈøÀéÈåÆ&#64298; äÇ&#64318;ÈãÄé</strong> òÈîÀãÄé ìÀîÇçÂæÄé÷ &#64309;ìÀîÈò&#64331;æ ì&#64331;</q>".</p> <p> <strong>ãøéåù äîìê</strong> ðæëø âí áñôø <strong>çâé</strong> - ëì äñôø îúøçù áùðä äùðéä ìãøéåù äîìê; áæîðå äúçãùä òáåãú áéú äî÷ãù äùðé, <a data-cke-saved-href="/tnk1/prqim/t2201.htm#1" href="/tnk1/prqim/t2201.htm#1" class="psuq">çâé à1</a>: "<q class="psuq">&#64305;Ä&#64298;ÀðÇú &#64298;À&#64330;Ç&#64285;í <strong>ìÀãÈøÀéÈåÆ&#64298;</strong> äÇ&#64318;ÆìÆêÀ... äÈéÈä ãÀáÇø ä' &#64305;ÀéÇã çÇ&#64306;Çé äÇ&#64320;ÈáÄéà àÆì æÀøË&#64305;ÈáÆì &#64305;Æï &#64298;À&#64302;ìÀ&#64330;ÄéàÅì &#64324;ÇçÇú éÀä&#64309;ãÈä åÀàÆì éÀä&#64331;&#64298;ËòÇ &#64305;Æï éÀä&#64331;öÈãÈ÷ äÇ&#64315;ÉäÅï äÇ&#64306;Èã&#64331;ì...</q>". åëï <a data-cke-saved-href="/tnk1/prqim/t2201.htm#15" href="/tnk1/prqim/t2201.htm#15" class="psuq">çâé à15</a>, <a data-cke-saved-href="/tnk1/prqim/t2202.htm#10" href="/tnk1/prqim/t2202.htm#10" class="psuq">çâé á10</a>.&nbsp;&nbsp; âí çì÷éí âãåìéí îñôø <strong>æëøéä</strong> äéå áæîï ãøéåù äîìê, <a data-cke-saved-href="/tnk1/prqim/t2301.htm#1" href="/tnk1/prqim/t2301.htm#1" class="psuq">æëøéä à1</a>: "<q class="psuq">&#64305;ÇçÉãÆ&#64298; äÇ&#64300;ÀîÄéðÄé &#64305;Ä&#64298;ÀðÇú &#64298;À&#64330;Ç&#64285;í <strong>ìÀãÈøÀéÈåÆ&#64298;</strong> äÈéÈä ãÀáÇø ä' àÆì æÀëÇøÀéÈä &#64305;Æï &#64305;ÆøÆëÀéÈä &#64305;Æï òÄ&#64307;&#64331; äÇ&#64320;ÈáÄéà ìÅàîÉø</q>", åëï <a data-cke-saved-href="/tnk1/prqim/t2301.htm#7" href="/tnk1/prqim/t2301.htm#7" class="psuq">æëøéä à7</a>, <a data-cke-saved-href="/tnk1/prqim/t2307.htm#1" href="/tnk1/prqim/t2307.htm#1" class="psuq">æëøéä æ1</a>: "<q class="psuq">åÇéÀäÄé &#64305;Ä&#64298;ÀðÇú &#64302;øÀ&#64305;Çò <strong>ìÀãÈøÀéÈåÆ&#64298;</strong> äÇ&#64318;ÆìÆêÀ äÈéÈä ãÀáÇø ä' àÆì æÀëÇøÀéÈä &#64305;À&#64302;øÀ&#64305;ÈòÈä ìÇçÉãÆ&#64298; äÇ&#64330;À&#64298;ÄòÄé &#64305;ÀëÄñÀìÅå</q>".&nbsp;</p> <p> <strong>ãøéåù îìê ôøñ</strong> ðæëø ôòîéí øáåú áñôø <strong>òæøà</strong>. îñåôø ùí, ùáéîé ëåøù ðéñå öøé éäåãä åáðéîéï ìáèì àú áðééï äî÷ãù, åîæéîúí ðîùëä òã éîé ãøéåù, <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#5" href="/tnk1/prqim/t35a04.htm#5" class="psuq">òæøà ã5-7</a>: "<q class="psuq">åÀñÉëÀøÄéí òÂìÅéäÆí é&#64331;òÂöÄéí ìÀäÈôÅø òÂöÈúÈí, &#64315;Èì éÀîÅé <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, åÀòÇã îÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÈñ. &#64309;áÀîÇìÀë&#64309;ú <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> &#64305;ÄúÀçÄ&#64316;Çú îÇìÀë&#64309;ú&#64331; &#64315;ÈúÀá&#64309; &#64299;ÄèÀðÈä òÇì éÉ&#64298;ÀáÅé éÀä&#64309;ãÈä åÄéø&#64309;&#64298;ÈìÈéí. åáéîé àøúçùùúà...</q>". òáåãú áéú äî÷ãù áèìä òã äùðä äùðéä ìãøéåù, <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#24" href="/tnk1/prqim/t35a04.htm#24" class="psuq">òæøà ã24</a>: "<q class="psuq">&#64305;ÅàãÇ&#64285;ï &#64305;ÀèÅìÇú òÂáÄéãÇú &#64305;Åéú àÁìÈäÈà &#64307;Äé &#64305;Äéø&#64309;&#64298;ÀìÆí åÇäÂåÈú &#64305;ÈèÀìÈà òÇã &#64298;ÀðÇú &#64330;ÇøÀ&#64330;Åéï ìÀîÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÈñ</q>", åàæ äúðáàå çâé åæëøéä åòåããå àú äéäåãéí ìäîùéê ááðéä, <a data-cke-saved-href="/tnk1/prqim/t35a05.htm#1" href="/tnk1/prqim/t35a05.htm#1" class="psuq">òæøà ä1</a>: "<q class="psuq">åÀäÄúÀðÇ&#64305;Äé çÇ&#64306;Çé ðáéàä[ðÀáÄéÌÈà] &#64309;æÀëÇøÀéÈä áÇø òÄ&#64307;&#64331;à ðáéàéà[ðÀáÄéÌÇéÌÈà] òÇì éÀä&#64309;ãÈéÅà &#64307;Äé áÄéä&#64309;ã &#64309;áÄéø&#64309;&#64298;ÀìÆí &#64305;À&#64298;Ëí àÁìÈ&#64308; &#64285;&#64299;ÀøÈàÅì òÂìÅéä&#64331;ï</q>". ìàçø çìéôú-îëúáéí òí ùøé ãøéåù, äåøä ãøéåù ìôúåç àú äàøëéåï áááì, <a data-cke-saved-href="/tnk1/prqim/t35a06.htm#1" href="/tnk1/prqim/t35a06.htm#1" class="psuq">òæøà å1</a>: "<q class="psuq">&#64305;ÅàãÇ&#64285;ï <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÇìÀ&#64315;Èà &#64299;Èí èÀòÅí &#64309;áÇ&#64327;Çø&#64309; &#64305;ÀáÅéú ñÄôÀøÇ&#64313;Èà &#64307;Äé âÄðÀæÇ&#64313;Èà îÀäÇçÂúÄéï &#64330;Ç&#64318;Èä &#64305;ÀáÈáÆì</q>", âéìä îçãù àú äöäøú ëåøù, åàéùø ìéäåãéí ìäîùéê ááðééú äî÷ãù, áäúàí ìøùéåï ùðéúï ìäí îèòí ùìåùä îìëéí: <strong>ëåøù, ãøéåù, åàøúçùñúà</strong>, <a data-cke-saved-href="/tnk1/prqim/t35a06.htm#14" href="/tnk1/prqim/t35a06.htm#14" class="psuq">òæøà å14</a>: "<q class="psuq">åÀ&#64299;ÈáÅé éÀä&#64309;ãÈéÅà &#64305;ÈðÇ&#64285;ï &#64309;îÇöÀìÀçÄéï &#64305;ÄðÀá&#64309;&#64302;ú çÇ&#64306;Çé ðáéàä[ðÀáÄéÌÈà] &#64309;æÀëÇøÀéÈä &#64305;Çø òÄ&#64307;&#64331;à, &#64309;áÀð&#64331; åÀ&#64298;ÇëÀìÄì&#64309; îÄï èÇòÇí àÁìÈ&#64308; &#64285;&#64299;ÀøÈàÅì, &#64309;îÄ&#64312;ÀòÅí <strong>&#64315;&#64331;øÆ&#64298;, åÀãÈøÀéÈåÆ&#64298;, åÀ&#64302;øÀ&#64330;ÇçÀ&#64298;Ç&#64299;À&#64330;Àà îÆìÆêÀ &#64324;ÈøÈñ</strong></q>".&nbsp; áðééú äî÷ãù äñúééîä úåê àøáò ùðéí, áùðú ùù ìãøéåù, <a data-cke-saved-href="/tnk1/prqim/t35a06.htm#15" href="/tnk1/prqim/t35a06.htm#15" class="psuq">òæøà å15</a>: "<q class="psuq">åÀ&#64298;ÅéöÄéà &#64305;ÇéÀúÈä ãÀðÈä òÇã é&#64331;í &#64330;ÀìÈúÈä ìÄéøÇç àÂãÈø, &#64307;Äé äÄéà &#64298;ÀðÇú &#64298;Åú ìÀîÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÇìÀ&#64315;Èà</q>". <br /></p> <p> <strong>ãøéåù äôøñé</strong> ðæëø âí á <a data-cke-saved-href="/tnk1/prqim/t35b12.htm#22" href="/tnk1/prqim/t35b12.htm#22" class="psuq">ðçîéä éá22</a>: "<q class="psuq">äÇìÀåÄ&#64313;Äí &#64305;ÄéîÅé àÆìÀéÈ&#64298;Äéá é&#64331;éÈãÈò åÀé&#64331;çÈðÈï åÀéÇ&#64307;&#64309;òÇ &#64315;Àú&#64309;áÄéí øÈà&#64298;Åé &#64303;á&#64331;ú åÀäÇ&#64315;ÉäÂðÄéí òÇì îÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298; äÇ&#64324;ÈøÀñÄé</strong></q>".</p> <p> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA" href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA">áúåìãåú ôøñ</a> éùðï àøáò ãîåéåú îøëæéåú ùð÷øàå ãøéåù (Darayavaus): <br /></p> <ul> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F" href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F">ãøéååù äøàùåï</a> - äéä áðå ùì åùúñôà (äéñèñôñ), ùäéä àçùãøôï ôøñé úçú äîìê ëðáåæé áï ëåøù äùðé. ìàçø îåú ëðáåæé (ùîìê ë-8 ùðéí), äöìéç ãøéåù ìúôåñ àú äùìèåï åùìè áîîìëä ë-36 ùðä. áî÷åøåú äéååðéí îñåôø ùðéñä ìëáåù àú éååï àê ðòöø á÷øá îøúåï. <br /></li> <li> <a data-cke-saved-href="https://en.wikipedia.org/wiki/Darius_(son_of_Xerxes_I)" href="https://en.wikipedia.org/wiki/Darius_(son_of_Xerxes_I)">ãøéååù áï àçùååøåù</a> - äéä áðå äáëåø åéåøù-äòöø ùì àçùååøåù äøàùåï, àåìí äåà îìê ìëì äéåúø ùáåòåú ñôåøéí, ëé äåöà ìäåøâ ò"é àçéå äöòéø àøúçùñúà äøàùåï. <br /></li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A9%D7%A0%D7%99" href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A9%D7%A0%D7%99">ãøéååù äùðé</a>&nbsp;- äéä áðå ùì àøúçùñúà äøàùåï (40 ùðä), áï çùéàøù äøàùåï (20 ùðä), áï ãøéååù äøàùåï (36 ùðä). îúåàø ëùìéè çìù, ùáéîéå øáå äñëñåëéí äôðéîééí åäîøéãåú ùì èåòðéí ìëúø. îùì ë-20 ùðä. <br /></li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A9%D7%9C%D7%99%D7%A9%D7%99" href="https://he.wikipedia.org/wiki/%D7%93%D7%A8%D7%99%D7%95%D7%95%D7%A9_%D7%94%D7%A9%D7%9C%D7%99%D7%A9%D7%99">ãøéååù äùìéùé</a>&nbsp;- òìä ìùìèåï àçøé àøúçùñúà äøáéòé (áéï àøúçùñúà äùìéùé, áï àøúçùñúà äùðé, áï ãøéååù äùðé). äéä äîìê äàçøåï áùåùìú äàçîðéú. áæîðå ðëáùä ôøñ ò"é àìëñðãø îå÷ãåï. <br /></li></ul> <p>ãøéåù ùì ñôø ãðéàì ìà îúàéí ìàó àçã îäí, ùëï äåà ðæëø îééã ìàçø ðôéìú ááì, åáî÷áéì ìëåøù, áòåã ùãøéååù äøàùåï ùìè ùðé ãåøåú îàåçø éåúø. îñúáø ùëåøù, îééã ìàçø ùëáù àú ááì, îéðä àãí áùí "ãøéåù", ùäéä îæøò îãé, ìîåùì îãéðú ááì. ãðéàì çé ááì, åäéä ùø ùì àåúå îåùì. ëéååï ùäéä ø÷ îåùì îùðé, äåà àéðå ðæëø áúåìãåú ôøñ. åàåìé æå äñéáä ùäåà ð÷øà <strong>ãøéåù äîãé</strong>, ìäáãéì áéðå ìáéï ãøéåù äòé÷øé. <br /></p> <p>ãøéåù ùì ñôø òæøà îúàéí, îáçéðú çùáåï äùðéí, ìãøéååù äøàùåï, ùòìä ìùìèåï ë-37 ùðéí àçøé äöäøú ëåøù (29 ùì ëåøù åòåã 8 ùì ëðáåæé). äñéáä: áæîðå òãééï çéå æøåááì åéäåùò, ùòìå ìéäåãä áéîé ëåøù (àåìí éù îæäéí àåúå òí ãøéååù äùðé, åö"ò). <br /></p> <p>áîãøù îöàðå ãòä ùìôéä "<q class="mfrj">ãøéåù äàçøåï - áðä ùì àñúø äéä, èäåø îàîå åèîà îàáéå</q>" <small class="small"> (øáé éäåãä áøáé ñéîåï, <a data-cke-saved-href="https://he.wikisource.org/wiki/%D7%95%D7%99%D7%A7%D7%A8%D7%90_%D7%A8%D7%91%D7%94_%D7%99%D7%92_%D7%94" href="https://he.wikisource.org/wiki/%D7%95%D7%99%D7%A7%D7%A8%D7%90_%D7%A8%D7%91%D7%94_%D7%99%D7%92_%D7%94">åé÷øà øáä éâ ä</a>)</small>; åîñúáø ùäëååðä ì <a data-cke-saved-href="https://en.wikipedia.org/wiki/Darius_(son_of_Xerxes_I)" href="https://en.wikipedia.org/wiki/Darius_(son_of_Xerxes_I)">ãøéååù áï àçùååøåù</a> (àåìí <a data-cke-saved-href="/tnk1/sofrim/mali/xgy_xiduj.html" href="/tnk1/sofrim/mali/xgy_xiduj.html">äøá àìéäå îàìé</a> îæää àåúå òí ãøéååù äøàùåï, åö"ò). <br /></p> <h2>â. àçùåøåù</h2> <p>àçùåøåù äåà ëéãåò äîìê ùì îâéìú <strong>àñúø</strong>,&nbsp; <a data-cke-saved-href="/tnk1/prqim/t3301.htm#1" href="/tnk1/prqim/t3301.htm#1" class="psuq">àñúø à1</a>: "<q class="psuq">åÇéÀäÄé &#64305;ÄéîÅé <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> ä&#64309;à <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> äÇ&#64318;ÉìÅêÀ îÅäÉ&#64307;&#64309; åÀòÇã &#64315;&#64309;&#64298; &#64298;ÆáÇò åÀòÆ&#64299;ÀøÄéí &#64309;îÅ&#64303;ä îÀãÄéðÈä</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:àñúø_à_à" href="http://he.wikisource.org/wiki/áéàåø:àñúø_à_à">ôéøåè</a>). îçåõ ìîâéìä, ðæëø ùí æä òåã ôòîééí:</p> <p>áñôø <strong>ãðéàì</strong>, ëàáéå ùì ãøéååù äîãé, <a data-cke-saved-href="/tnk1/prqim/t3409.htm#1" href="/tnk1/prqim/t3409.htm#1" class="psuq">ãðéàì è1</a>: "<q class="psuq">&#64305;Ä&#64298;ÀðÇú &#64302;çÇú ìÀãÈøÀéÈåÆ&#64298; &#64305;Æï <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> îÄ&#64310;ÆøÇò îÈãÈé àÂ&#64298;Æø äÈîÀìÇêÀ òÇì îÇìÀë&#64309;ú &#64315;Ç&#64299;À&#64307;Äéí</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:ãðéàì_è_à" href="http://he.wikisource.org/wiki/áéàåø:ãðéàì_è_à">ôéøåè</a>);</p> <p>åáñôø <strong>òæøà</strong>, ëàçã äîìëéí ùáæîðí áèìä òáåãú äî÷ãù, <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#5" href="/tnk1/prqim/t35a04.htm#5" class="psuq">òæøà ã5-7</a>: "<q class="psuq">åÀñÉëÀøÄéí òÂìÅéäÆí é&#64331;òÂöÄéí ìÀäÈôÅø òÂöÈúÈí, &#64315;Èì éÀîÅé <strong>&#64315;&#64331;øÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÇñ, åÀòÇã îÇìÀë&#64309;ú <strong>&#64307;ÈøÀéÈåÆ&#64298;</strong> îÆìÆêÀ &#64324;ÈøÈñ. &#64309;áÀîÇìÀë&#64309;ú <strong>àÂçÇ&#64298;ÀåÅø&#64331;&#64298;</strong> &#64305;ÄúÀçÄ&#64316;Çú îÇìÀë&#64309;ú&#64331; &#64315;ÈúÀá&#64309; &#64299;ÄèÀðÈä òÇì éÉ&#64298;ÀáÅé éÀä&#64309;ãÈä åÄéø&#64309;&#64298;ÈìÈéí. åáéîé <strong>àøúçùùúà</strong>...</q>".</p> <p> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA" href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA">áúåìãåú ôøñ</a> ìà ðæëø îìê áùí æä, àáì ðæëø ùí ãåîä îàã - <strong>çùéàøù</strong> (Xsaya-rsa; äéååðéí ÷øàå ìå "÷ñø÷ññ"):</p> <ul> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%97%D7%A9%D7%99%D7%90%D7%A8%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F" href="https://he.wikipedia.org/wiki/%D7%97%D7%A9%D7%99%D7%90%D7%A8%D7%A9_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F">çùéàøù (÷ñø÷ññ) äøàùåï</a> äéä áðå ùì ãøéååù äøàùåï åùì àèåñä áú ëåøù äùðé. îùì ë-20 ùðä.</li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%97%D7%A9%D7%99%D7%90%D7%A8%D7%A9_%D7%94%D7%A9%D7%A0%D7%99" href="https://he.wikipedia.org/wiki/%D7%97%D7%A9%D7%99%D7%90%D7%A8%D7%A9_%D7%94%D7%A9%D7%A0%D7%99">çùéàøù (÷ñø÷ññ) äùðé</a> äéä áðå ùì àøúçùñúà äøàùåï áï çùéàøù äøàùåï. îùì ø÷ ë-45 éåí òã ùðøöç.</li></ul> <p>åàëï éù äîæäéí àú àçùåøåù ëçùéàøù äøàùåï. àåìí éù îæäéí àú àçùååøåù ëàøúçùñúà äøàùåï áðå ùì çùéàøù äøàùåï. åö"ò.</p> <h2>ã. àøúçùñúà</h2> <p>àøúçùñúà (àå àøúçùùúà áùéï ùîàìéú) ðæëø ôòîéí øáåú áñôøé òæøà åðçîéä.</p> <p>áúçéìú ñôø òæøà (à-å, ú÷åôú æøåááì åéäåùò), ðæëø àøúçùñúà ëàçã äîìëéí ùáéîéäí äöìéçå öøé éäåãä åáðéîéï ìòëá àú áðééï äî÷ãù,&nbsp; <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#7" href="/tnk1/prqim/t35a04.htm#7" class="psuq">òæøà ã7</a>: "<q class="psuq">&#64309;áÄéîÅé <strong>&#64302;øÀ&#64330;ÇçÀ&#64298;Ç&#64299;À&#64330;Èà</strong> &#64315;ÈúÇá &#64305;Ä&#64298;ÀìÈí îÄúÀøÀãÈú èÈáÀàÅì &#64309;&#64298;À&#64303;ø &#64315;ÀðÈåúÈéå òÇì <strong>àøúçùùúà[&#64302;øÀ&#64330;ÇçÀ&#64298;Ç&#64299;À&#64330;À]</strong> îÆìÆêÀ &#64324;ÈøÈñ...</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:òæøà_ã_æ" href="http://he.wikisource.org/wiki/áéàåø:òæøà_ã_æ">ôéøåè</a>),&nbsp; <a data-cke-saved-href="/tnk1/prqim/t35a04.htm#23" href="/tnk1/prqim/t35a04.htm#23" class="psuq">òæøà ã23</a>: "<q class="psuq">àÁãÇ&#64285;ï îÄï &#64307;Äé &#64324;ÇøÀ&#64298;ÆâÆï ðÄ&#64298;À&#64330;ÀåÈðÈà &#64307;Äé <strong>àøúçùùúà[&#64302;øÀ&#64330;ÇçÀ&#64298;Ç&#64299;À&#64330;À]</strong> îÇìÀ&#64315;Èà ÷ÁøÄé ÷ÃãÈí øÀç&#64309;í åÀ&#64298;ÄîÀ&#64298;Çé ñÈôÀøÈà &#64309;ëÀðÈåÈúÀä&#64331;ï àÂæÇì&#64309; áÄáÀäÄéì&#64309; ìÄéø&#64309;&#64298;ÀìÆí òÇì éÀä&#64309;ãÈéÅà, &#64309;áÇ&#64312;Äì&#64309; äÄ&#64318;&#64331; &#64305;ÀàÆãÀøÈò åÀçÈ&#64285;ì</q>".&nbsp;&nbsp; ìòåîú æàú, áäîùê îñåôø, ùùáé éäåãä ãåå÷à äöìéçå ìáðåú àú äî÷ãù áøùéåï ùðéúï ìäí îèòí ëåøù, ãøéååù, åàøúçùñúà, <a data-cke-saved-href="/tnk1/prqim/t35a06.htm#14" href="/tnk1/prqim/t35a06.htm#14" class="psuq">òæøà å14</a>: "<q class="psuq">åÀ&#64299;ÈáÅé éÀä&#64309;ãÈéÅà &#64305;ÈðÇ&#64285;ï &#64309;îÇöÀìÀçÄéï &#64305;ÄðÀá&#64309;&#64302;ú çÇ&#64306;Çé ðáéàä[ðÀáÄéÌÈà] &#64309;æÀëÇøÀéÈä &#64305;Çø òÄ&#64307;&#64331;à &#64309;áÀð&#64331; åÀ&#64298;ÇëÀìÄì&#64309; îÄï èÇòÇí àÁìÈ&#64308; &#64285;&#64299;ÀøÈàÅì &#64309;îÄ&#64312;ÀòÅí &#64315;&#64331;øÆ&#64298; åÀãÈøÀéÈåÆ&#64298; <strong>åÀ&#64302;øÀ&#64330;ÇçÀ&#64298;Ç&#64299;À&#64330;Àà</strong> îÆìÆêÀ &#64324;ÈøÈñ</q>".</p> <p>áäîùê ñôø òæøà (æ-é), ðàîø, <a data-cke-saved-href="/tnk1/prqim/t35a07.htm#1" href="/tnk1/prqim/t35a07.htm#1" class="psuq">òæøà æ1</a>: "<q class="psuq">åÀ&#64302;çÇø äÇ&#64307;ÀáÈøÄéí äÈàÅ&#64316;Æä &#64305;ÀîÇìÀë&#64309;ú <strong>&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> îÆìÆêÀ &#64324;ÈøÈñ, òÆæÀøÈà &#64305;Æï &#64299;ÀøÈéÈä &#64305;Æï òÂæÇøÀéÈä &#64305;Æï çÄìÀ÷Ä&#64313;Èä...</q>". ðøàä ùîãåáø ëàï áú÷åôä àçøú: îðäéâé äòí ëáø àéðí æøåááì åéäåùò, àìà òæøà åðçîéä. <a data-cke-saved-href="/tnk1/prqim/t35a07.htm#7" href="/tnk1/prqim/t35a07.htm#7" class="psuq">òæøà æ7</a>: "<q class="psuq">åÇ&#64313;ÇòÂì&#64309; îÄ&#64305;ÀðÅé &#64285;&#64299;ÀøÈàÅì &#64309;îÄï äÇ&#64315;ÉäÂðÄéí åÀäÇìÀåÄ&#64313;Äí åÀäÇîÀ&#64298;ÉøÀøÄéí åÀäÇ&#64300;ÉòÂøÄéí åÀäÇ&#64320;ÀúÄéðÄéí àÆì éÀø&#64309;&#64298;ÈìÈéí &#64305;Ä&#64298;ÀðÇú &#64298;ÆáÇò <strong>ìÀ&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> äÇ&#64318;ÆìÆêÀ</q>" (<a data-cke-saved-href="/tnk1/ktuv/ewn/ez-07-0708.html" href="/tnk1/ktuv/ewn/ez-07-0708.html">ôéøåè</a>), <a data-cke-saved-href="/tnk1/prqim/t35a07.htm#11" href="/tnk1/prqim/t35a07.htm#11" class="psuq">òæøà æ11</a>: "<q class="psuq">åÀæÆä &#64324;ÇøÀ&#64298;ÆâÆï äÇ&#64320;Ä&#64298;À&#64330;ÀåÈï àÂ&#64298;Æø ðÈúÇï äÇ&#64318;ÆìÆêÀ <strong>&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> ìÀòÆæÀøÈà äÇ&#64315;ÉäÅï äÇ&#64321;ÉôÅø ñÉôÅø &#64307;ÄáÀøÅé îöåú ä' åÀçË&#64327;Èéå òÇì &#64285;&#64299;ÀøÈàÅì...</q>", <a data-cke-saved-href="/tnk1/prqim/t35a08.htm#1" href="/tnk1/prqim/t35a08.htm#1" class="psuq">òæøà ç1</a>: "<q class="psuq">åÀàÅ&#64316;Æä øÈà&#64298;Åé àÂáÉúÅéäÆí åÀäÄúÀéÇçÀ&#64299;Èí äÈòÉìÄéí òÄ&#64318;Äé &#64305;ÀîÇìÀë&#64309;ú <strong>&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> äÇ&#64318;ÆìÆêÀ îÄ&#64305;ÈáÆì</q>", <a data-cke-saved-href="/tnk1/prqim/t35b02.htm#1" href="/tnk1/prqim/t35b02.htm#1" class="psuq">ðçîéä á1</a>: "<q class="psuq">åÇéÀäÄé &#64305;ÀçÉãÆ&#64298; ðÄéñÈï <strong>&#64298;ÀðÇú òÆ&#64299;ÀøÄéí ìÀ&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> äÇ&#64318;ÆìÆêÀ éÇ&#64285;ï ìÀôÈðÈéå åÈàÆ&#64301;Èà àÆú äÇ&#64313;Ç&#64285;ï åÈàÆ&#64330;ÀðÈä ìÇ&#64318;ÆìÆêÀ åÀìÉà äÈ&#64285;éúÄé øÇò ìÀôÈðÈéå</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:òæøà_ã_ç" href="http://he.wikisource.org/wiki/áéàåø:òæøà_ã_ç">ôéøåè</a>),&nbsp; <a data-cke-saved-href="/tnk1/prqim/t35b05.htm#14" href="/tnk1/prqim/t35b05.htm#14" class="psuq">ðçîéä ä14</a>: "<q class="psuq">&#64306;Çí îÄ&#64313;&#64331;í àÂ&#64298;Æø öÄ&#64309;Èä àÉúÄé ìÄäÀé&#64331;ú &#64324;ÆçÈí &#64305;ÀàÆøÆõ éÀä&#64309;ãÈä îÄ&#64300;ÀðÇú òÆ&#64299;ÀøÄéí åÀòÇã <strong>&#64298;ÀðÇú &#64298;ÀìÉ&#64298;Äéí &#64309;&#64298;À&#64330;Ç&#64285;í ìÀ&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> äÇ&#64318;ÆìÆêÀ &#64298;ÈðÄéí &#64298;À&#64330;Åéí òÆ&#64299;ÀøÅä àÂðÄé åÀ&#64302;çÇé ìÆçÆí äÇ&#64324;ÆçÈä ìÉà &#64303;ëÇìÀ&#64330;Äé</q>" (<a data-cke-saved-href="http://he.wikisource.org/wiki/áéàåø:ðçîéä_ä_éã" href="http://he.wikisource.org/wiki/áéàåø:ðçîéä_ä_éã">ôéøåè</a>),&nbsp; <a data-cke-saved-href="/tnk1/prqim/t35b13.htm#6" href="/tnk1/prqim/t35b13.htm#6" class="psuq">ðçîéä éâ6</a>: "<q class="psuq">&#64309;áÀëÈì æÆä ìÉà äÈ&#64285;éúÄé &#64305;Äéø&#64309;&#64298;ÈìÈéí &#64315;Äé &#64305;Ä&#64298;ÀðÇú &#64298;ÀìÉ&#64298;Äéí &#64309;&#64298;À&#64330;Ç&#64285;í <strong>ìÀ&#64302;øÀ&#64330;ÇçÀ&#64298;ÇñÀ&#64330;Àà</strong> îÆìÆêÀ &#64305;ÈáÆì &#64305;ÈàúÄé àÆì äÇ&#64318;ÆìÆêÀ &#64309;ìÀ÷Åõ éÈîÄéí ðÄ&#64298;À&#64302;ìÀ&#64330;Äé îÄï äÇ&#64318;ÆìÆêÀ</q>". äú÷åôä äîúåàøú ùí äéà áéï ùðú 7 ìáéï ùðú 32 ìàøúçùñúà.</p> <p> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA" href="https://he.wikipedia.org/wiki/%D7%94%D7%9E%D7%9E%D7%9C%D7%9B%D7%94_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA#%D7%94%D7%A9%D7%95%D7%A9%D7%9C%D7%AA_%D7%94%D7%90%D7%97%D7%9E%D7%A0%D7%99%D7%AA">áúåìãåú ôøñ</a> éùðí àøáòä îìëéí ùð÷øàå àøúçùñúà (Artaxsaca, áìùåï äéååðéí "àøú÷ñø÷ññ"):</p> <ul> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F" href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A8%D7%90%D7%A9%D7%95%D7%9F">àøúçùñúà äøàùåï</a> - áï çùéàøù äøàùåï. îùì ë-40 ùðä.</li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A9%D7%A0%D7%99" href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A9%D7%A0%D7%99">àøúçùñúà äùðé</a> - áï ãøéååù äùðé, ùäéä áðå ùì àøúçùñúà äøàùåï. îùì ë-45 ùðä.</li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A9%D7%9C%D7%99%D7%A9%D7%99" href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A9%D7%9C%D7%99%D7%A9%D7%99">àøúçùñúà äùìéùé</a> - áï àøúùçñúà äùðé. îùì ë-21 ùðä.</li> <li> <a data-cke-saved-href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A8%D7%91%D7%99%D7%A2%D7%99" href="https://he.wikipedia.org/wiki/%D7%90%D7%A8%D7%AA%D7%97%D7%A9%D7%A1%D7%AA%D7%90_%D7%94%D7%A8%D7%91%D7%99%D7%A2%D7%99">àøúçùñúà äøáéòé</a> (àøññ) - áï àøúùçñúà äùìéùé. îùì ø÷ ëùðä àçú òã ùðøöç.</li></ul> <p>àøúçùñúà äðæëø áòæøà à-å äåà áååãàé àøúçùñúà äøàùåï, ùëï äåà äéä áæîï äðáéàéí çâé åæëøéä, àçøé àçùåøåù åãøéåù äøàùåï, åìôðé ãøéåù äùðé.</p> <p>ìâáé àøúçùñúà äðæëø áòæøà æ-é åáðçîéä à-éâ, ëéååï ùäú÷åôä îàåçøú éåúø, ééúëï ùäåà àøúçùñúà äùðé. åö"ò.</p> </div><!--tokn--> <h2 id='tguvot'>úâåáåú</h2> <ul id='ultguvot'> <li></li> </ul><!--end--> <script type='text/javascript'>tguva(); txtit()</script> </div><!--pnim--> </body> </html>
lgpl-3.0
bunnyinc/phpstats
tests/ProbabilityDistribution/WeibullTest.php
1997
<?php require_once('lib/Stats.php'); require_once('lib/ProbabilityDistribution/ProbabilityDistribution.php'); require_once('lib/ProbabilityDistribution/Weibull.php'); require_once('lib/StatisticalTests.php'); use \PHPStats\ProbabilityDistribution\Weibull as Weibull; class WeibullTest extends PHPUnit_Framework_TestCase { private $testObject; public function __construct() { $this->testObject = new Weibull(5, 1); } public function test_rvs() { $variates = array(); for ($i = 0; $i < 10000; $i++) $variates[] = $this->testObject->rvs(); $this->assertGreaterThanOrEqual(0.01, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject)); $this->assertLessThanOrEqual(0.99, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject)); } public function test_pdf() { $this->assertEquals(0.2, round($this->testObject->pdf(0), 5)); $this->assertEquals(0.14523, round($this->testObject->pdf(1.6), 5)); } public function test_cdf() { $this->assertEquals(0.5, round($this->testObject->cdf(3.46574), 5)); $this->assertEquals(0.9, round($this->testObject->cdf(11.5129), 5)); } public function test_sf() { $this->assertEquals(0.5, round($this->testObject->sf(3.46574), 5)); $this->assertEquals(0.1, round($this->testObject->sf(11.5129), 5)); } public function test_ppf() { $this->assertEquals(3.46574, round($this->testObject->ppf(0.5), 5)); $this->assertEquals(11.5129, round($this->testObject->ppf(0.9), 4)); } public function test_isf() { $this->assertEquals(3.46574, round($this->testObject->isf(0.5), 5)); $this->assertEquals(11.5129, round($this->testObject->isf(0.1), 4)); } public function test_stats() { $summaryStats = $this->testObject->stats('mvsk'); $this->assertEquals(5, round($summaryStats['mean'], 3)); $this->assertEquals(25, round($summaryStats['variance'], 2)); $this->assertEquals(2, round($summaryStats['skew'], 3)); $this->assertEquals(6, round($summaryStats['kurtosis'], 3)); } } ?>
lgpl-3.0
kidaa/Awakening-Core3
doc/html/_installation_object_delta_message7_8h_source.html
23487
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: /Users/victor/git/Core3Mda/MMOCoreORB/src/server/zone/packets/installation/InstallationObjectDeltaMessage7.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_075bb3ff235063c77951cd176d15a741.html">server</a></li><li class="navelem"><a class="el" href="dir_9e27d73ba17b043ea65c9708c594875e.html">zone</a></li><li class="navelem"><a class="el" href="dir_bb492b763d24e30b4e5e2022fcf1460c.html">packets</a></li><li class="navelem"><a class="el" href="dir_a10cff6264278ad90486b31ac4f0f1c4.html">installation</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">InstallationObjectDeltaMessage7.h</div> </div> </div><!--header--> <div class="contents"> <a href="_installation_object_delta_message7_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="comment">/*</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="comment">Copyright (C) 2007 &lt;SWGEmu&gt;</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="comment">This File is part of Core3.</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="comment">This program is free software; you can redistribute</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="comment">it and/or modify it under the terms of the GNU Lesser</span></div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="comment">General Public License as published by the Free Software</span></div> <div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;<span class="comment">Foundation; either version 2 of the License,</span></div> <div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160;<span class="comment">or (at your option) any later version.</span></div> <div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;<span class="comment">This program is distributed in the hope that it will be useful,</span></div> <div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;<span class="comment">but WITHOUT ANY WARRANTY; without even the implied warranty of</span></div> <div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="comment">MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.</span></div> <div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;<span class="comment">See the GNU Lesser General Public License for</span></div> <div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160;<span class="comment">more details.</span></div> <div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;<span class="comment">You should have received a copy of the GNU Lesser General</span></div> <div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;<span class="comment">Public License along with this program; if not, write to</span></div> <div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="comment">the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA</span></div> <div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;<span class="comment">Linking Engine3 statically or dynamically with other modules</span></div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;<span class="comment">is making a combined work based on Engine3.</span></div> <div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160;<span class="comment">Thus, the terms and conditions of the GNU Lesser General Public License</span></div> <div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;<span class="comment">cover the whole combination.</span></div> <div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160;<span class="comment">In addition, as a special exception, the copyright holders of Engine3</span></div> <div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160;<span class="comment">give you permission to combine Engine3 program with free software</span></div> <div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160;<span class="comment">programs or libraries that are released under the GNU LGPL and with</span></div> <div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160;<span class="comment">code included in the standard release of Core3 under the GNU LGPL</span></div> <div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160;<span class="comment">license (or modified versions of such code, with unchanged license).</span></div> <div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160;<span class="comment">You may copy and distribute such a system following the terms of the</span></div> <div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160;<span class="comment">GNU LGPL for Engine3 and the licenses of the other code concerned,</span></div> <div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160;<span class="comment">provided that you include the source code of that other code when</span></div> <div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160;<span class="comment">and as the GNU LGPL requires distribution of source code.</span></div> <div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160;<span class="comment">Note that people who make modified versions of Engine3 are not obligated</span></div> <div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160;<span class="comment">to grant this special exception for their modified versions;</span></div> <div class="line"><a name="l00039"></a><span class="lineno"> 39</span>&#160;<span class="comment">it is their choice whether to do so. The GNU Lesser General Public License</span></div> <div class="line"><a name="l00040"></a><span class="lineno"> 40</span>&#160;<span class="comment">gives permission to release a modified version without this exception;</span></div> <div class="line"><a name="l00041"></a><span class="lineno"> 41</span>&#160;<span class="comment">this exception also makes it possible to release a modified version</span></div> <div class="line"><a name="l00042"></a><span class="lineno"> 42</span>&#160;<span class="comment">which carries forward this exception.</span></div> <div class="line"><a name="l00043"></a><span class="lineno"> 43</span>&#160;<span class="comment">*/</span></div> <div class="line"><a name="l00044"></a><span class="lineno"> 44</span>&#160;</div> <div class="line"><a name="l00045"></a><span class="lineno"> 45</span>&#160;<span class="preprocessor">#ifndef INSTALLATIONOBJECTDELTAMESSAGE7_H_</span></div> <div class="line"><a name="l00046"></a><span class="lineno"> 46</span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define INSTALLATIONOBJECTDELTAMESSAGE7_H_</span></div> <div class="line"><a name="l00047"></a><span class="lineno"> 47</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00048"></a><span class="lineno"> 48</span>&#160;<span class="preprocessor">#include &quot;../../packets/DeltaMessage.h&quot;</span></div> <div class="line"><a name="l00049"></a><span class="lineno"> 49</span>&#160;</div> <div class="line"><a name="l00050"></a><span class="lineno"> 50</span>&#160;<span class="preprocessor">#include &quot;../../objects/installation/InstallationObject.h&quot;</span></div> <div class="line"><a name="l00051"></a><span class="lineno"> 51</span>&#160;<span class="preprocessor">#include &quot;../../objects/installation/harvester/HarvesterObject.h&quot;</span></div> <div class="line"><a name="l00052"></a><span class="lineno"> 52</span>&#160;</div> <div class="line"><a name="l00053"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html"> 53</a></span>&#160;<span class="keyword">class </span><a class="code" href="class_installation_object_delta_message7.html">InstallationObjectDeltaMessage7</a> : <span class="keyword">public</span> <a class="code" href="class_delta_message.html">DeltaMessage</a> {</div> <div class="line"><a name="l00054"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#ac527dbec843c5043adfeff0582cad3dd"> 54</a></span>&#160; <a class="code" href="classserver_1_1zone_1_1objects_1_1installation_1_1_installation_object.html">InstallationObject</a>* <a class="code" href="class_installation_object_delta_message7.html#ac527dbec843c5043adfeff0582cad3dd">inso</a>;</div> <div class="line"><a name="l00055"></a><span class="lineno"> 55</span>&#160;</div> <div class="line"><a name="l00056"></a><span class="lineno"> 56</span>&#160;<span class="keyword">public</span>:</div> <div class="line"><a name="l00057"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#ab97adc5141a4f01122a4d83c2d77461f"> 57</a></span>&#160; <a class="code" href="class_installation_object_delta_message7.html#ab97adc5141a4f01122a4d83c2d77461f">InstallationObjectDeltaMessage7</a>(<a class="code" href="classserver_1_1zone_1_1objects_1_1installation_1_1_installation_object.html">InstallationObject</a>* ins)</div> <div class="line"><a name="l00058"></a><span class="lineno"> 58</span>&#160; : <a class="code" href="class_delta_message.html">DeltaMessage</a>(ins-&gt;getObjectID(), 0x494E534F, 7) {</div> <div class="line"><a name="l00059"></a><span class="lineno"> 59</span>&#160; <a class="code" href="class_installation_object_delta_message7.html#ac527dbec843c5043adfeff0582cad3dd">inso</a> = ins;</div> <div class="line"><a name="l00060"></a><span class="lineno"> 60</span>&#160; }</div> <div class="line"><a name="l00061"></a><span class="lineno"> 61</span>&#160;</div> <div class="line"><a name="l00062"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#afcaba8965dda95b5e0a6a2c9a336cc21"> 62</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#afcaba8965dda95b5e0a6a2c9a336cc21">updateExtractionRate</a>(<span class="keywordtype">float</span> rate) {</div> <div class="line"><a name="l00063"></a><span class="lineno"> 63</span>&#160; <a class="code" href="class_delta_message.html#a67087c753efbbe0dcb64514cd68113cf">addFloatUpdate</a>(0x09, rate);</div> <div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160; }</div> <div class="line"><a name="l00065"></a><span class="lineno"> 65</span>&#160;</div> <div class="line"><a name="l00066"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#aa0b2bb73d4a5faa8e203156a93de4b6b"> 66</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#aa0b2bb73d4a5faa8e203156a93de4b6b">setNoHopperUpdate</a>() {</div> <div class="line"><a name="l00067"></a><span class="lineno"> 67</span>&#160; <a class="code" href="class_delta_message.html#a5a767217d573c46f81ecbe66b908a7b8">addByteUpdate</a>(0x0C, 0);</div> <div class="line"><a name="l00068"></a><span class="lineno"> 68</span>&#160; }</div> <div class="line"><a name="l00069"></a><span class="lineno"> 69</span>&#160;</div> <div class="line"><a name="l00070"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#afb3a65702e8cfa4892271dfa6ff021a2"> 70</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#afb3a65702e8cfa4892271dfa6ff021a2">updateOperating</a>(<span class="keywordtype">bool</span> state) {</div> <div class="line"><a name="l00071"></a><span class="lineno"> 71</span>&#160; <a class="code" href="class_delta_message.html#a5a767217d573c46f81ecbe66b908a7b8">addByteUpdate</a>(0x06, state);</div> <div class="line"><a name="l00072"></a><span class="lineno"> 72</span>&#160; }</div> <div class="line"><a name="l00073"></a><span class="lineno"> 73</span>&#160;</div> <div class="line"><a name="l00074"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#ab7d0ced639d6e1b99a90663b185ff2f1"> 74</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#ab7d0ced639d6e1b99a90663b185ff2f1">updateHopper</a>() {</div> <div class="line"><a name="l00075"></a><span class="lineno"> 75</span>&#160; <a class="code" href="class_delta_message.html#a5a767217d573c46f81ecbe66b908a7b8">addByteUpdate</a>(0x0C, 1); <span class="comment">// think about incrementing like a counter</span></div> <div class="line"><a name="l00076"></a><span class="lineno"> 76</span>&#160; }</div> <div class="line"><a name="l00077"></a><span class="lineno"> 77</span>&#160;</div> <div class="line"><a name="l00078"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#ac06ac4fd9000e4be6dd4739a95ae65fd"> 78</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#ac06ac4fd9000e4be6dd4739a95ae65fd">updateHopperSize</a>(<span class="keywordtype">float</span> size) {</div> <div class="line"><a name="l00079"></a><span class="lineno"> 79</span>&#160; <a class="code" href="class_delta_message.html#a67087c753efbbe0dcb64514cd68113cf">addFloatUpdate</a>(0x0A, size);</div> <div class="line"><a name="l00080"></a><span class="lineno"> 80</span>&#160; }</div> <div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160;</div> <div class="line"><a name="l00082"></a><span class="lineno"><a class="code" href="class_installation_object_delta_message7.html#ad7e94768b4c457a1268faf7aa703d36d"> 82</a></span>&#160; <span class="keywordtype">void</span> <a class="code" href="class_installation_object_delta_message7.html#ad7e94768b4c457a1268faf7aa703d36d">updateActiveResourceSpawn</a>(uint64 <span class="keywordtype">id</span>) {</div> <div class="line"><a name="l00083"></a><span class="lineno"> 83</span>&#160; <a class="code" href="class_delta_message.html#abdde3ddf5a4c724375197152c38c6758">addLongUpdate</a>(0x05, <span class="keywordtype">id</span>);</div> <div class="line"><a name="l00084"></a><span class="lineno"> 84</span>&#160; }</div> <div class="line"><a name="l00085"></a><span class="lineno"> 85</span>&#160;</div> <div class="line"><a name="l00086"></a><span class="lineno"> 86</span>&#160; <span class="comment">/*void updateActiveResource(uint64 oid) {</span></div> <div class="line"><a name="l00087"></a><span class="lineno"> 87</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00088"></a><span class="lineno"> 88</span>&#160;<span class="comment"> if (inso-&gt;getObjectSubType() == TangibleObjectImplementation::HARVESTER &amp;&amp; ((HarvesterObject*)inso)-&gt;getActiveResourceID() != oid)</span></div> <div class="line"><a name="l00089"></a><span class="lineno"> 89</span>&#160;<span class="comment"> ((HarvesterObject*)inso)-&gt;changeActiveResourceID(oid);</span></div> <div class="line"><a name="l00090"></a><span class="lineno"> 90</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160;<span class="comment"> // Active Resource</span></div> <div class="line"><a name="l00092"></a><span class="lineno"> 92</span>&#160;<span class="comment"> addLongUpdate(0x05, oid);</span></div> <div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160;<span class="comment"> //System::out &lt;&lt; &quot;Adding 0x05 update for oid: &quot; &lt;&lt; hex &lt;&lt; oid &lt;&lt; endl;</span></div> <div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00095"></a><span class="lineno"> 95</span>&#160;<span class="comment"> }</span></div> <div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00098"></a><span class="lineno"> 98</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160;<span class="comment"> void updateHopperItem(uint64 rId) {</span></div> <div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160;<span class="comment"> startUpdate(0x0D); // hopper</span></div> <div class="line"><a name="l00102"></a><span class="lineno"> 102</span>&#160;<span class="comment"> insertInt(1); // list size</span></div> <div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160;<span class="comment"> insertInt(inso-&gt;getNewHopperUpdateCounter(1));</span></div> <div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160;<span class="comment"> insertByte(0x02); // change</span></div> <div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160;<span class="comment"> insertShort(0x00);</span></div> <div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160;<span class="comment"> insertLong(rId); // ID</span></div> <div class="line"><a name="l00107"></a><span class="lineno"> 107</span>&#160;<span class="comment"> insertFloat(inso-&gt;getHopperItemQuantity(rId)); // size</span></div> <div class="line"><a name="l00108"></a><span class="lineno"> 108</span>&#160;<span class="comment"> }</span></div> <div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160;<span class="comment"></span></div> <div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160;<span class="comment"> void addHopperItem(uint64 rId) {</span></div> <div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160;<span class="comment"> startUpdate(0x0D); // hopper</span></div> <div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160;<span class="comment"> insertInt(1); // list size</span></div> <div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160;<span class="comment"> insertInt(inso-&gt;getNewHopperUpdateCounter(1));</span></div> <div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160;<span class="comment"> insertByte(0x01); // add</span></div> <div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160;<span class="comment"> insertShort(0x00);</span></div> <div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160;<span class="comment"> insertLong(rId); // ID</span></div> <div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160;<span class="comment"> insertFloat(inso-&gt;getHopperItemQuantity(rId)); // size</span></div> <div class="line"><a name="l00118"></a><span class="lineno"> 118</span>&#160;<span class="comment"> }*/</span></div> <div class="line"><a name="l00119"></a><span class="lineno"> 119</span>&#160;</div> <div class="line"><a name="l00120"></a><span class="lineno"> 120</span>&#160;</div> <div class="line"><a name="l00121"></a><span class="lineno"> 121</span>&#160;};</div> <div class="line"><a name="l00122"></a><span class="lineno"> 122</span>&#160;</div> <div class="line"><a name="l00123"></a><span class="lineno"> 123</span>&#160;<span class="preprocessor">#endif </span><span class="comment">/* INSTALLATIONOBJECTDELTAMESSAGE7_H_ */</span><span class="preprocessor"></span></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:29:12 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
lgpl-3.0
linupi/RaspPiTouchLCD
README.md
109
RaspPiTouchLCD ============== Driver Library for a 240x320 Touch Display with uPD161704A and XPT2046 chipset
lgpl-3.0
revelator/Revelation-Engine
Extras/ModSources/vanilla/game/gamesys/GameTypeInfo.h
9486
#ifndef __GAMETYPEINFO_H__ #define __GAMETYPEINFO_H__ /* =================================================================================== This file has been generated with the Type Info Generator v1.0 (c) 2004 id Software 59 constants 8 enums 9 classes/structs/unions 0 templates 0 max inheritance level for '' =================================================================================== */ typedef struct { const char * name; const char * type; const char * value; } constantInfo_t; typedef struct { const char * name; int value; } enumValueInfo_t; typedef struct { const char * typeName; const enumValueInfo_t * values; } enumTypeInfo_t; typedef struct { const char * type; const char * name; int offset; int size; } classVariableInfo_t; typedef struct { const char * typeName; const char * superType; int size; const classVariableInfo_t * variables; } classTypeInfo_t; static constantInfo_t constantInfo[] = { { "int", "CPUID_NONE", "0" }, { "int", "CPUID_UNSUPPORTED", "1" }, { "int", "CPUID_GENERIC", "2" }, { "int", "CPUID_INTEL", "4" }, { "int", "CPUID_AMD", "8" }, { "int", "CPUID_MMX", "16" }, { "int", "CPUID_3DNOW", "32" }, { "int", "CPUID_SSE", "64" }, { "int", "CPUID_SSE2", "128" }, { "int", "CPUID_SSE3", "256" }, { "int", "CPUID_ALTIVEC", "512" }, { "int", "CPUID_HTT", "4096" }, { "int", "CPUID_CMOV", "8192" }, { "int", "CPUID_FTZ", "16384" }, { "int", "CPUID_DAZ", "32768" }, { "int", "AXIS_SIDE", "0" }, { "int", "AXIS_FORWARD", "1" }, { "int", "AXIS_UP", "2" }, { "int", "AXIS_ROLL", "3" }, { "int", "AXIS_YAW", "4" }, { "int", "AXIS_PITCH", "5" }, { "int", "MAX_JOYSTICK_AXIS", "6" }, { "int", "SE_NONE", "0" }, { "int", "SE_KEY", "1" }, { "int", "SE_CHAR", "2" }, { "int", "SE_MOUSE", "3" }, { "int", "SE_JOYSTICK_AXIS", "4" }, { "int", "SE_CONSOLE", "5" }, { "int", "M_ACTION1", "0" }, { "int", "M_ACTION2", "1" }, { "int", "M_ACTION3", "2" }, { "int", "M_ACTION4", "3" }, { "int", "M_ACTION5", "4" }, { "int", "M_ACTION6", "5" }, { "int", "M_ACTION7", "6" }, { "int", "M_ACTION8", "7" }, { "int", "M_DELTAX", "8" }, { "int", "M_DELTAY", "9" }, { "int", "M_DELTAZ", "10" }, { "int", "NA_BAD", "0" }, { "int", "NA_LOOPBACK", "1" }, { "int", "NA_BROADCAST", "2" }, { "int", "NA_IP", "3" }, { "int", "THREAD_LOWEST", "0" }, { "int", "THREAD_BELOW_NORMAL", "1" }, { "int", "THREAD_NORMAL", "2" }, { "int", "THREAD_ABOVE_NORMAL", "3" }, { "int", "THREAD_HIGHEST", "4" }, { "const int", "MAX_THREADS", "16" }, { "const int", "MAX_CRITICAL_SECTIONS", "4" }, { "int", "CRITICAL_SECTION_ZERO", "0" }, { "int", "CRITICAL_SECTION_ONE", "1" }, { "int", "CRITICAL_SECTION_TWO", "2" }, { "int", "CRITICAL_SECTION_THREE", "3" }, { "const int", "MAX_TRIGGER_EVENTS", "4" }, { "int", "TRIGGER_EVENT_ZERO", "0" }, { "int", "TRIGGER_EVENT_ONE", "1" }, { "int", "TRIGGER_EVENT_TWO", "2" }, { "int", "TRIGGER_EVENT_THREE", "3" }, { NULL, NULL, NULL } }; static enumValueInfo_t cpuid_t_typeInfo[] = { { "CPUID_NONE", 0 }, { "CPUID_UNSUPPORTED", 1 }, { "CPUID_GENERIC", 2 }, { "CPUID_INTEL", 4 }, { "CPUID_AMD", 8 }, { "CPUID_MMX", 16 }, { "CPUID_3DNOW", 32 }, { "CPUID_SSE", 64 }, { "CPUID_SSE2", 128 }, { "CPUID_SSE3", 256 }, { "CPUID_ALTIVEC", 512 }, { "CPUID_HTT", 4096 }, { "CPUID_CMOV", 8192 }, { "CPUID_FTZ", 16384 }, { "CPUID_DAZ", 32768 }, { NULL, 0 } }; static enumValueInfo_t joystickAxis_t_typeInfo[] = { { "AXIS_SIDE", 0 }, { "AXIS_FORWARD", 1 }, { "AXIS_UP", 2 }, { "AXIS_ROLL", 3 }, { "AXIS_YAW", 4 }, { "AXIS_PITCH", 5 }, { "MAX_JOYSTICK_AXIS", 6 }, { NULL, 0 } }; static enumValueInfo_t sysEventType_t_typeInfo[] = { { "SE_NONE", 0 }, { "SE_KEY", 1 }, { "SE_CHAR", 2 }, { "SE_MOUSE", 3 }, { "SE_JOYSTICK_AXIS", 4 }, { "SE_CONSOLE", 5 }, { NULL, 0 } }; static enumValueInfo_t sys_mEvents_typeInfo[] = { { "M_ACTION1", 0 }, { "M_ACTION2", 1 }, { "M_ACTION3", 2 }, { "M_ACTION4", 3 }, { "M_ACTION5", 4 }, { "M_ACTION6", 5 }, { "M_ACTION7", 6 }, { "M_ACTION8", 7 }, { "M_DELTAX", 8 }, { "M_DELTAY", 9 }, { "M_DELTAZ", 10 }, { NULL, 0 } }; static enumValueInfo_t netadrtype_t_typeInfo[] = { { "NA_BAD", 0 }, { "NA_LOOPBACK", 1 }, { "NA_BROADCAST", 2 }, { "NA_IP", 3 }, { NULL, 0 } }; static enumValueInfo_t xthreadPriority_typeInfo[] = { { "THREAD_LOWEST", 0 }, { "THREAD_BELOW_NORMAL", 1 }, { "THREAD_NORMAL", 2 }, { "THREAD_ABOVE_NORMAL", 3 }, { "THREAD_HIGHEST", 4 }, { NULL, 0 } }; static enumValueInfo_t enum_6_typeInfo[] = { { "CRITICAL_SECTION_ZERO", 0 }, { "CRITICAL_SECTION_ONE", 1 }, { "CRITICAL_SECTION_TWO", 2 }, { "CRITICAL_SECTION_THREE", 3 }, { NULL, 0 } }; static enumValueInfo_t enum_7_typeInfo[] = { { "TRIGGER_EVENT_ZERO", 0 }, { "TRIGGER_EVENT_ONE", 1 }, { "TRIGGER_EVENT_TWO", 2 }, { "TRIGGER_EVENT_THREE", 3 }, { NULL, 0 } }; static enumTypeInfo_t enumTypeInfo[] = { { "cpuid_t", cpuid_t_typeInfo }, { "joystickAxis_t", joystickAxis_t_typeInfo }, { "sysEventType_t", sysEventType_t_typeInfo }, { "sys_mEvents", sys_mEvents_typeInfo }, { "netadrtype_t", netadrtype_t_typeInfo }, { "xthreadPriority", xthreadPriority_typeInfo }, { "enum_6", enum_6_typeInfo }, { "enum_7", enum_7_typeInfo }, { NULL, NULL } }; static classVariableInfo_t sysEvent_t_typeInfo[] = { { "sysEventType_t", "evType", (int)(&((sysEvent_t *)0)->evType), sizeof( ((sysEvent_t *)0)->evType ) }, { "int", "evValue", (int)(&((sysEvent_t *)0)->evValue), sizeof( ((sysEvent_t *)0)->evValue ) }, { "int", "evValue2", (int)(&((sysEvent_t *)0)->evValue2), sizeof( ((sysEvent_t *)0)->evValue2 ) }, { "int", "evPtrLength", (int)(&((sysEvent_t *)0)->evPtrLength), sizeof( ((sysEvent_t *)0)->evPtrLength ) }, { "void *", "evPtr", (int)(&((sysEvent_t *)0)->evPtr), sizeof( ((sysEvent_t *)0)->evPtr ) }, { NULL, 0 } }; static classVariableInfo_t sysMemoryStats_t_typeInfo[] = { { "int", "memoryLoad", (int)(&((sysMemoryStats_t *)0)->memoryLoad), sizeof( ((sysMemoryStats_t *)0)->memoryLoad ) }, { "int", "totalPhysical", (int)(&((sysMemoryStats_t *)0)->totalPhysical), sizeof( ((sysMemoryStats_t *)0)->totalPhysical ) }, { "int", "availPhysical", (int)(&((sysMemoryStats_t *)0)->availPhysical), sizeof( ((sysMemoryStats_t *)0)->availPhysical ) }, { "int", "totalPageFile", (int)(&((sysMemoryStats_t *)0)->totalPageFile), sizeof( ((sysMemoryStats_t *)0)->totalPageFile ) }, { "int", "availPageFile", (int)(&((sysMemoryStats_t *)0)->availPageFile), sizeof( ((sysMemoryStats_t *)0)->availPageFile ) }, { "int", "totalVirtual", (int)(&((sysMemoryStats_t *)0)->totalVirtual), sizeof( ((sysMemoryStats_t *)0)->totalVirtual ) }, { "int", "availVirtual", (int)(&((sysMemoryStats_t *)0)->availVirtual), sizeof( ((sysMemoryStats_t *)0)->availVirtual ) }, { "int", "availExtendedVirtual", (int)(&((sysMemoryStats_t *)0)->availExtendedVirtual), sizeof( ((sysMemoryStats_t *)0)->availExtendedVirtual ) }, { NULL, 0 } }; static classVariableInfo_t netadr_t_typeInfo[] = { { "netadrtype_t", "type", (int)(&((netadr_t *)0)->type), sizeof( ((netadr_t *)0)->type ) }, { "unsigned char[4]", "ip", (int)(&((netadr_t *)0)->ip), sizeof( ((netadr_t *)0)->ip ) }, { "unsigned short", "port", (int)(&((netadr_t *)0)->port), sizeof( ((netadr_t *)0)->port ) }, { NULL, 0 } }; static classVariableInfo_t idPort_typeInfo[] = { { "int", "packetsRead", (int)(&((idPort *)0)->packetsRead), sizeof( ((idPort *)0)->packetsRead ) }, { "int", "bytesRead", (int)(&((idPort *)0)->bytesRead), sizeof( ((idPort *)0)->bytesRead ) }, { "int", "packetsWritten", (int)(&((idPort *)0)->packetsWritten), sizeof( ((idPort *)0)->packetsWritten ) }, { "int", "bytesWritten", (int)(&((idPort *)0)->bytesWritten), sizeof( ((idPort *)0)->bytesWritten ) }, { "netadr_t", "bound_to", (int)(&((idPort *)0)->bound_to), sizeof( ((idPort *)0)->bound_to ) }, { "int", "netSocket", (int)(&((idPort *)0)->netSocket), sizeof( ((idPort *)0)->netSocket ) }, { NULL, 0 } }; static classVariableInfo_t idTCP_typeInfo[] = { { "netadr_t", "address", (int)(&((idTCP *)0)->address), sizeof( ((idTCP *)0)->address ) }, { "int", "fd", (int)(&((idTCP *)0)->fd), sizeof( ((idTCP *)0)->fd ) }, { NULL, 0 } }; static classVariableInfo_t xthreadInfo_typeInfo[] = { { "const char *", "name", (int)(&((xthreadInfo *)0)->name), sizeof( ((xthreadInfo *)0)->name ) }, { "HANDLE", "threadHandle", (int)(&((xthreadInfo *)0)->threadHandle), sizeof( ((xthreadInfo *)0)->threadHandle ) }, { "unsigned long", "threadId", (int)(&((xthreadInfo *)0)->threadId), sizeof( ((xthreadInfo *)0)->threadId ) }, { NULL, 0 } }; static classVariableInfo_t idSys_typeInfo[] = { { NULL, 0 } }; static classVariableInfo_t idLib_typeInfo[] = { { NULL, 0 } }; static classVariableInfo_t idException_typeInfo[] = { { "char[1024]", "error", (int)(&((idException *)0)->error), sizeof( ((idException *)0)->error ) }, { NULL, 0 } }; static classTypeInfo_t classTypeInfo[] = { { "sysEvent_t", "", sizeof(sysEvent_t), sysEvent_t_typeInfo }, { "sysMemoryStats_t", "", sizeof(sysMemoryStats_t), sysMemoryStats_t_typeInfo }, { "netadr_t", "", sizeof(netadr_t), netadr_t_typeInfo }, { "idPort", "", sizeof(idPort), idPort_typeInfo }, { "idTCP", "", sizeof(idTCP), idTCP_typeInfo }, { "xthreadInfo", "", sizeof(xthreadInfo), xthreadInfo_typeInfo }, { "idSys", "", sizeof(idSys), idSys_typeInfo }, { "idLib", "", sizeof(idLib), idLib_typeInfo }, { "idException", "", sizeof(idException), idException_typeInfo }, { NULL, NULL, 0, NULL } }; #endif /* !__GAMETYPEINFO_H__ */
lgpl-3.0
mgarber/scriptureV2
src/java/broad/core/siphy/UnableToFitException.java
214
package broad.core.siphy; public class UnableToFitException extends Exception { private static final long serialVersionUID = 285381715807645775L; public UnableToFitException(String msg) { super(msg); } }
lgpl-3.0
erelsgl/erel-sites
tnk1/ktuv/mgilot/qh-10-04.html
8160
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1255' /> <meta charset='windows-1255' /> <meta http-equiv='Content-Script-Type' content='text/javascript' /> <meta http-equiv='revisit-after' content='15 days' /> <title>âí àí ëåòñéí òìéê, àì úîäø ìäúôèø</title> <link rel='stylesheet' type='text/css' href='../../../_script/klli.css' /> <link rel='stylesheet' type='text/css' href='../../../tnk1/_themes/klli.css' /> <meta property='og:url' content='https://tora.us.fm/tnk1/ktuv/mgilot/qh-10-04.html'/> <meta name='author' content="àøàì" /> <meta name='receiver' content="" /> <meta name='jmQovc' content="tnk1/ktuv/mgilot/qh-10-04.html" /> <meta name='tvnit' content="" /> <link rel='canonical' href='https://tora.us.fm/tnk1/ktuv/mgilot/qh-10-04.html' /> </head> <!-- PHP Programming by Erel Segal-Halevi --> <body lang='he' dir='rtl' id = 'tnk1_ktuv_mgilot_qh_10_04' class='dywn1 '> <div class='pnim'> <script type='text/javascript' src='../../../_script/vars.js'></script> <!--NiwutElyon0--> <div class='NiwutElyon'> <div class='NiwutElyon'><a class='link_to_homepage' href='../../../tnk1/index.html'>øàùé</a>&gt;<a href='../../../tnk1/msr/0.html'>áéï àãí ìðôùå</a>&gt;<a href='../../../tnk1/ktuv/mjly/svlnut.html'>îéãú äñáìðåú</a>&gt;</div> </div> <!--NiwutElyon1--> <h1 id='h1'>âí àí ëåòñéí òìéê, àì úîäø ìäúôèø</h1> <div id='idfields'> <p>÷åã: áéàåø:÷äìú é4 áúð"ê</p> <p>ñåâ: ãéåï1</p> <p>îàú: àøàì</p> <p>àì: </p> </div> <script type='text/javascript'>kotrt()</script> <div id='tokn'> <p> <a class="psuq" href="/tnk1/prqim/t3110.htm#4">÷äìú é4</a>: "<q class="psuq">àÄí øåÌçÇ äÇîÌåÉùÑÅì úÌÇòÂìÆä òÈìÆéêÈ -&#160; îÀ÷åÉîÀêÈ àÇì úÌÇðÌÇç, ëÌÄé îÇøÀôÌÅà éÇðÌÄéçÇ çÂèÈàÄéí âÌÀãåÉìÄéí</q>"</p> <p>îðäéâ áéöò ôòåìä ëìùäé, åòëùéå äöéáåø ëåòñ òìéå åãåøù îîðå ìäúôèø. äàí àëï òìéå ìäúôèø? ìà ëì ëê îäø:</p> <p> <strong>øåç</strong> = ëòñ;&#160;&#160; <strong>àí øåç äîåùì úòìä òìéê</strong> = àí äîåùì, äáåñ ùìê, ëåòñ òìéê,&#160; <strong>î÷åîê àì úðç</strong> = àì úáøç îäàøõ <small>(<a href="http://www.daat.ac.il/daat/tanach/megilot/kara10-4.htm">ø' éåñó ÷øà</a>, îöåãú ãåã)</small>, åëï àì úòæåá àú îùøúê åúúôèø <small class="small"> (ãòú î÷øà)</small>, <strong>ëé</strong> -</p> <p> <strong>îøôà</strong> = îøôä = øôéåï øåç, øâéòä;&#160;&#160; <strong>ëé îøôà éðéç çèàéí âãåìéí</strong> = ëé àí úðäâ áøôéåï åáðçú, åìà úîäø ìáøåç, ééúëï ùäîåùì ééøâò åéøôä îëòñå, åéñìç ìê âí òì ãáøéí ùðøàå áòéðéå ÷åãí ìëï ëçèàéí âãåìéí; &#160; àåìí àí úîäø ìáøåç, úâãéì àú ëòñå ùì äîåùì "<q class="mfrj">ëé ááøçê úåñéó çèà</q>" <small class="small"> (îöåãú ãåã)</small>, åàí úîäø ìäúôèø, îé ùéâéò áî÷åîê éäéä âøåò éåúø, ëîå ùîúåàø áôñå÷éí äáàéí, ÷äìú é5-7: "<q class="psuq">éÅùÑ øÈòÈä øÈàÄéúÄé úÇÌçÇú äÇùÈÌÑîÆùÑ, ëÄÌùÀÑâÈâÈä, ùÆÑéÉÌöÈà îÄìÄÌôÀðÅé äÇùÇÌÑìÄÌéè <small>(îéùäå ùâä, åîéäø ìäúôèø åìöàú îìôðé äùìéè, åëúåöàä îëê -)</small>. &#160;&#160; ðÄúÇÌï äÇñÆÌëÆì áÇÌîÀÌøåÉîÄéí øÇáÄÌéí åÇòÂùÄÑéøÄéí áÇÌùÅÌÑôÆì éÅùÅÑáåÌ. &#160;&#160; øÈàÄéúÄé òÂáÈãÄéí òÇì ñåÌñÄéí åÀùÈÒøÄéí äÉìÀëÄéí ëÇÌòÂáÈãÄéí òÇì äÈàÈøÆõ</q>" <small class="small"> (ò"ô ôøåô' îøãëé æø ëáåã, ãòú î÷øà)</small>.</p> <p>äôñå÷ îãáø òì <strong>îåùì</strong> àçã, àáì áîùèø ãîå÷øèé, <strong>äîåùì</strong> - äøéáåï - äåà äòí. ìôòîéí äòí ëåòñ òì ôåìéèé÷àé áâìì ôòåìä ëìùäé ùòùä, àåìí äëòñ äæä æîðé; àí äôåìéèé÷àé ééùàø áúô÷éãå, äëòñ éøôä åééøâò, àåìí àí äôåìéèé÷àé éîäø ìäúôèø, òìååì ìäâéò ôåìéèé÷àé âøåò éåúø áî÷åîå.</p> <p>-</p> <p>äîåùì äåà âí îùì ìä', øéáåï äòåìí: "<q class="mfrj"><strong>àí øåç äîåùì</strong> - îåùì äòåìí - <strong>úòìä òìéê</strong>, ìã÷ã÷ àçøéê áîãú äãéï - <strong>î÷åîê àì úðç</strong> - ìåîø ìå 'îä éåòéì öã÷úé ìé', <strong>ëé îøôà</strong> - ã÷ãå÷é äãéï áéñåøéï äáàéï òìéê, îøôà äåà ìòåðåúéê, <strong>åéðéç</strong> ìê <strong>çèàéí äâãåìéí</strong></q>" <small>(<a class="external text" href="http://he.wikisource.org/wiki/%D7%A7%D7%98%D7%A2:%D7%A8%D7%A9%22%D7%99_%D7%A2%D7%9C_%D7%A7%D7%94%D7%9C%D7%AA_%D7%99_%D7%93">øù"é</a>)</small>; âí ëùàãí îøâéù ùä' ëåòñ òìéå, ìà éîäø 'ìäúôèø' îòîéãúå ìôðé ä', àìà éùåá, åä' éøôà ìå.</p> <h2>ôéøåùéí ðåñôéí</h2> <p>øàå âí:</p> <ul> <li> <a href="http://www.yesmalot.co.il/shiurhtml/malotsh1111.asp">ôéøåùéí ùì äøá éäåùò åééöîï, øàù éùéáú îòìåú</a>.</li> <li>ôéøåùéí òì äôñå÷ äáà, <a href="/tnk1/ktuv/mgilot/qh-10-05.html">ùââä ìôðé äùìéè</a>.</li> <li> <a href="http://www.daat.ac.il/daat/toshba/kohelet/10-2.htm">îãøù øáä îâéìú ÷äìú - ôøùä é</a></li></ul> <div class="future"> <h2>îàîøéí ðåñôéí îúåöàåú äçéôåù á <a href="http://www.google.com/cse?cx=010178520503316434778%3Aufdjhgdvtao">âåâì</a></h2> <ul> <li> <a href="http://www.ateret4u.com/online/f_01575.html">ãøê îðåçä - ôéøåù ìàâøú äøîá''ï</a>: <strong>...</strong> àì éàîø ìà òùéúé îàåîä áòîìé, àìà àãøáä éçæ÷ åéúàîõ ùàéðå àìà ðñéåï åîäâàåï ø' éäåãä òãñ ùìéè''à ùîòúé áæä ãéù ìäìéõ áæä àú äôñå÷'' <strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:aYIbiVLsKEEJ:www.ateret4u.com">cache</a>)</li> <li> <a href="http://www.daat.ac.il/daat/tanach/raba1/34.htm">ôøùú ðç</a>: ëúéá (÷äìú é): <strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì úðç, îãáø áðç. àîø ðç: ëùí ùìà ðëðñúé áúéáä àìà áøùåú, ëê àéï àðé éåöà àìà áøùåú. áà àì äúéáä! åéáà ðç. öà îï äúéáä! (<a href="http://www.google.com/search?q=cache:TxDiYopEItcJ:www.daat.ac.il">cache</a>)</li> <li> <a href="http://www.tsel.org/torah/yalkutsh/noach.html">éì÷åè ùîòåðé - ðç</a>: åéãáø àì÷éí àì ðç ìàîø öà îï äúáä ëúéá <strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì úðç àîø ðç ëùí ùðëðñúé ìúéáä áøùåú ëê àéðé éåöà àìà áøùåú, àîø ø' éåãï àéìå äééúé ùí äééúé&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:boJ_rHF79N0J:www.tsel.org">cache</a>)</li> <li> <a href="http://www.daat.ac.il/daat/mahshevt/hovot/6-2.htm">çåáåú äìááåú</a>: åàîø äçëí áòðééï äæä (÷äìú é) <strong>àí øåç äîåùì úòìä</strong> òìéê åâå'. åäçîéùé ëùäåà îåëéç àú ðôùå åðåúï ãéï äáåøà îòöîå. åàí áàéí áòìé ãéðå ìäéôøò îîðå îùìí ìäí îòöîå åîîäø ì÷áì òì&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:oGY4ze19ATYJ:www.daat.ac.il">cache</a>)</li> <li> <a href="http://www.aspaklaria.info/003_GIMEL/%D7%92%D7%90%D7%95%D7%94.htm">âàåä</a>: <strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì úðç, ëé áàúä ìê îîùìä àì úðç îãú òðååúðåúê, ììîãê ùëì äîðéç òðååúðåúå âåøí îéúä ìòåìîå åçåèà ìãåøå. åîîé àú ìîã îæëøéä, ùðàîø (ãä"á&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:flfleHZfqeoJ:www.aspaklaria.info">cache</a>)</li> <li> <a href="http://www.halachabrura.org/agada/ned50-62.htm">áàåøé àâãåú ðãøéí</a>: åò"æ ðàîø: "<strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì úðç" [÷äìú é, ã], åñåó äëáåã ìáà. (øàé"ä ÷å÷, ùîåðä ÷áöéí, ÷åáõ æ àåú ÷å). äçééí åëì äçæéåðåú îúçì÷éí ìàéëåú åëîåú. øåá òîì áðé&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:EDjwo21y9ZIJ:www.halachabrura.org">cache</a>)</li> <li> <a href="http://www.aspaklaria.info/040_MEM/%D7%9E%D7%A8%D7%93%D7%9B%D7%99.htm">îøãëé</a>: ãáø àçø <strong>àí øåç äîåùì úòìä</strong> òìéê åâå', îãáø áîøãëé, òã ùìà áàúä ìå âãåìä (àñúø á') åîøãëé éåùá áùòø äîìê, åëùáàú ìå âãåìä, åéùá îøãëé àì ùòø äîìê. (ùí é å)&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:piYMv9_LsdgJ:www.aspaklaria.info">cache</a>)</li> <li> <a href="http://www.aspaklaria.info/070_AYIN/%D7%A2%D7%A0%D7%95%D7%94.htm">òðåä</a>: <strong>àí øåç äîåùì úòìä</strong> òìéê î÷åîê àì úðç, ëé áàúä ìê îîùìä àì úðç îãú òðååúðåúê, ììîãê ùëì äîðéç òðååúðåúå âåøí îéúä ìòåìîå åçåèà ìãåøå, åîîé àú ìîã îæëøéä, ùðàîø (ãä"á&#160; <strong>...</strong> (<a href="http://www.google.com/search?q=cache:KhF9BzzmFbMJ:www.aspaklaria.info">cache</a>)</li></ul> </div> </div><!--tokn--> <h2 id='tguvot'>úâåáåú</h2> <ul id='ultguvot'> <li></li> </ul><!--end--> <script type='text/javascript'>tguva(); txtit()</script> </div><!--pnim--> </body> </html>
lgpl-3.0
tuaplicacionpropia/effortless
zkstrap/web/plugins/icheck/skins/minimal/minimal.css
14617
/* * aero.css blue.css green.css grey.css minimal.css orange.css pink.css purple.css red.css yellow.css * */ /* iCheck plugin Minimal skin ----------------------------------- */ .icheckbox_minimal, .iradio_minimal { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(minimal.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal { background-position: 0 0; } .icheckbox_minimal.hover { background-position: -20px 0; } .icheckbox_minimal.checked { background-position: -40px 0; } .icheckbox_minimal.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal.checked.disabled { background-position: -80px 0; } .iradio_minimal { background-position: -100px 0; } .iradio_minimal.hover { background-position: -120px 0; } .iradio_minimal.checked { background-position: -140px 0; } .iradio_minimal.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal, .iradio_minimal { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* red */ .icheckbox_minimal-red, .iradio_minimal-red { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(red.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-red { background-position: 0 0; } .icheckbox_minimal-red.hover { background-position: -20px 0; } .icheckbox_minimal-red.checked { background-position: -40px 0; } .icheckbox_minimal-red.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-red.checked.disabled { background-position: -80px 0; } .iradio_minimal-red { background-position: -100px 0; } .iradio_minimal-red.hover { background-position: -120px 0; } .iradio_minimal-red.checked { background-position: -140px 0; } .iradio_minimal-red.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-red.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-red, .iradio_minimal-red { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* green */ .icheckbox_minimal-green, .iradio_minimal-green { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(green.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-green { background-position: 0 0; } .icheckbox_minimal-green.hover { background-position: -20px 0; } .icheckbox_minimal-green.checked { background-position: -40px 0; } .icheckbox_minimal-green.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-green.checked.disabled { background-position: -80px 0; } .iradio_minimal-green { background-position: -100px 0; } .iradio_minimal-green.hover { background-position: -120px 0; } .iradio_minimal-green.checked { background-position: -140px 0; } .iradio_minimal-green.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-green.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-green, .iradio_minimal-green { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* blue */ .icheckbox_minimal-blue, .iradio_minimal-blue { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(blue.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-blue { background-position: 0 0; } .icheckbox_minimal-blue.hover { background-position: -20px 0; } .icheckbox_minimal-blue.checked { background-position: -40px 0; } .icheckbox_minimal-blue.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-blue.checked.disabled { background-position: -80px 0; } .iradio_minimal-blue { background-position: -100px 0; } .iradio_minimal-blue.hover { background-position: -120px 0; } .iradio_minimal-blue.checked { background-position: -140px 0; } .iradio_minimal-blue.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-blue.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-blue, .iradio_minimal-blue { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* aero */ .icheckbox_minimal-aero, .iradio_minimal-aero { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(aero.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-aero { background-position: 0 0; } .icheckbox_minimal-aero.hover { background-position: -20px 0; } .icheckbox_minimal-aero.checked { background-position: -40px 0; } .icheckbox_minimal-aero.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-aero.checked.disabled { background-position: -80px 0; } .iradio_minimal-aero { background-position: -100px 0; } .iradio_minimal-aero.hover { background-position: -120px 0; } .iradio_minimal-aero.checked { background-position: -140px 0; } .iradio_minimal-aero.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-aero.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-aero, .iradio_minimal-aero { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* grey */ .icheckbox_minimal-grey, .iradio_minimal-grey { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(grey.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-grey { background-position: 0 0; } .icheckbox_minimal-grey.hover { background-position: -20px 0; } .icheckbox_minimal-grey.checked { background-position: -40px 0; } .icheckbox_minimal-grey.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-grey.checked.disabled { background-position: -80px 0; } .iradio_minimal-grey { background-position: -100px 0; } .iradio_minimal-grey.hover { background-position: -120px 0; } .iradio_minimal-grey.checked { background-position: -140px 0; } .iradio_minimal-grey.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-grey.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-grey, .iradio_minimal-grey { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* orange */ .icheckbox_minimal-orange, .iradio_minimal-orange { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(orange.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-orange { background-position: 0 0; } .icheckbox_minimal-orange.hover { background-position: -20px 0; } .icheckbox_minimal-orange.checked { background-position: -40px 0; } .icheckbox_minimal-orange.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-orange.checked.disabled { background-position: -80px 0; } .iradio_minimal-orange { background-position: -100px 0; } .iradio_minimal-orange.hover { background-position: -120px 0; } .iradio_minimal-orange.checked { background-position: -140px 0; } .iradio_minimal-orange.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-orange.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-orange, .iradio_minimal-orange { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* yellow */ .icheckbox_minimal-yellow, .iradio_minimal-yellow { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(yellow.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-yellow { background-position: 0 0; } .icheckbox_minimal-yellow.hover { background-position: -20px 0; } .icheckbox_minimal-yellow.checked { background-position: -40px 0; } .icheckbox_minimal-yellow.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-yellow.checked.disabled { background-position: -80px 0; } .iradio_minimal-yellow { background-position: -100px 0; } .iradio_minimal-yellow.hover { background-position: -120px 0; } .iradio_minimal-yellow.checked { background-position: -140px 0; } .iradio_minimal-yellow.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-yellow.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-yellow, .iradio_minimal-yellow { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* pink */ .icheckbox_minimal-pink, .iradio_minimal-pink { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(pink.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-pink { background-position: 0 0; } .icheckbox_minimal-pink.hover { background-position: -20px 0; } .icheckbox_minimal-pink.checked { background-position: -40px 0; } .icheckbox_minimal-pink.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-pink.checked.disabled { background-position: -80px 0; } .iradio_minimal-pink { background-position: -100px 0; } .iradio_minimal-pink.hover { background-position: -120px 0; } .iradio_minimal-pink.checked { background-position: -140px 0; } .iradio_minimal-pink.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-pink.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .icheckbox_minimal-pink, .iradio_minimal-pink { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } /* purple */ .icheckbox_minimal-purple, .iradio_minimal-purple { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: url(purple.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal-purple { background-position: 0 0; } .icheckbox_minimal-purple.hover { background-position: -20px 0; } .icheckbox_minimal-purple.checked { background-position: -40px 0; } .icheckbox_minimal-purple.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal-purple.checked.disabled { background-position: -80px 0; } .iradio_minimal-purple { background-position: -100px 0; } .iradio_minimal-purple.hover { background-position: -120px 0; } .iradio_minimal-purple.checked { background-position: -140px 0; } .iradio_minimal-purple.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal-purple.checked.disabled { background-position: -180px 0; } /* HiDPI support */ @media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi), (min-resolution: 1.25dppx) { .icheckbox_minimal-purple, .iradio_minimal-purple { background-image: url([email protected]); -webkit-background-size: 200px 20px; background-size: 200px 20px; } }
lgpl-3.0
Frankie-PellesC/fSDK
Lib/src/dxguid8/dxguid0000018B.c
454
// Created file "tmp\src\dxguid\dxguid" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_IDirect3DRMShadow, 0xaf359780, 0x6ba3, 0x11cf, 0xac, 0x4a, 0x00, 0x00, 0xc0, 0x38, 0x25, 0xa1);
lgpl-3.0
Javlo/javlo
src/main/java/org/javlo/component/social/FacebookFriend.java
427
package org.javlo.component.social; public class FacebookFriend { private String name; private String image; public FacebookFriend(String name, String image) { this.name = name; this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
lgpl-3.0
AshKyd/Hotot
data/js/ui.template.js
59989
if (typeof ui == 'undefined') var ui = {}; ui.Template = { reg_vaild_preceding_chars: '(?:[^-\\/"\':!=a-zA-Z0-9_]|^)', reg_url_path_chars_1: '[a-zA-Z0-9!\\*\';:=\\+\\$/%#\\[\\]\\?\\-_,~\\(\\)&\\.`@]', reg_url_path_chars_2: '[a-zA-Z0-9!\':=\\+\\$/%#~\\(\\)&`@]', reg_url_proto_chars: '([a-zA-Z]+:\\/\\/|www\\.)', reg_user_name_chars: '[@@]([a-zA-Z0-9_]{1,20})', reg_list_name_template: '[@@]([a-zA-Z0-9_]{1,20}/[a-zA-Z][a-zA-Z0-9_\\-\u0080-\u00ff]{0,24})', // from https://si0.twimg.com/c/phoenix/en/bundle/t1-hogan-core.f760c184d1eaaf1cf27535473a7306ef.js reg_hash_tag_latin_chars: '\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff', reg_hash_tag_nonlatin_chars: '\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0750-\u077f\u08a0\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff70\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u4dbf\u4e00-\u9fff\ua700-\ub73f\ub740-\ub81f\uf800-\ufa1f\u3003\u3005\u303b', reg_hash_tag_template: '(^|\\s)[##]([a-z0-9_{%LATIN_CHARS%}{%NONLATIN_CHARS%}]*)', reg_hash_tag: null, reg_is_rtl: new RegExp('[\u0600-\u06ff]|[\ufe70-\ufeff]|[\ufb50-\ufdff]|[\u0590-\u05ff]'), tweet_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" in_thread="{%IN_THREAD%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_color_label" style="background-color:{%COLOR_LABEL%}"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="tweet_fav_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="tweet_retweet_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who {%RETWEET_MARK%}">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_thread_info" style="display:{%IN_REPLY%}">\ <a class="btn_tweet_thread" href="#"></a>\ {%REPLY_TEXT%}\ </div>\ <div class="tweet_source"> \ {%RETWEET_TEXT%} \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}</div>\ <div class="status_bar">{%STATUS_INDICATOR%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ <div class="tweet_thread_wrapper">\ <div class="tweet_thread_hint">{%TRANS_Loading%}</div>\ <ul class="tweet_thread"></ul>\ <a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\ </div>\ </li>', trending_topic_t: '<li id="{%ID%}" class="card" type="trending_topic">\ <div class="profile_img_wrapper trend_topic_number">#{%ID%}</div>\ <div class="card_body keep_height">\ <a class="hash_href trending_topic" href="{%NAME%}">{%NAME%}</a>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', retweeted_by_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="tweet_fav_indicator"></div>\ <div class="tweet_retweet_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who {%RETWEET_MARK%}">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_thread_info" style="display:{%IN_REPLY%}">\ <a class="btn_tweet_thread" href="#"></a>\ {%REPLY_TEXT%}\ </div>\ <div class="tweet_source"> \ {%RETWEET_TEXT%} \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}\ {%TRANS_Retweeted_by%}: <a class="show" href="#" title="{%TRANS_Click_to_show_retweeters%}" tweet_id="{%TWEET_ID%}">{%TRANS_Show_retweeters%}</a>\ </div>\ <div class="tweet_retweeters" tweet_id="{%TWEET_ID%}"></div>\ <div class="status_bar">{%STATUS_INDICATOR%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ <div class="tweet_thread_wrapper">\ <div class="tweet_thread_hint">{%TRANS_Loading%}</div>\ <ul class="tweet_thread"></ul>\ <a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\ </div>\ </li>', message_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="message" sender_screen_name="{%SCREEN_NAME%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_dm_reply_btn" title="Reply them" href="#reply_dm" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">@<a class="who_href" href="#{%RECIPIENT_SCREEN_NAME%}">{%RECIPIENT_SCREEN_NAME%}</a> {%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_source"> \ <span class="tweet_timestamp tweet_update_timestamp" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</span>\ </div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', search_t: '<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="search" screen_name="{%SCREEN_NAME%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="deleted_mark"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\ </li><li>\ <a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\ </li>\ </ul>\ <div class="card_body">\ <div class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\ <div class="tweet_meta">\ <div class="tweet_source"> \ <span class="tweet_timestamp">\ <a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\ </span>\ {%TRANS_via%}: {%SOURCE%}</div>\ </div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', people_t: '<li id="{%USER_ID%}" class="people_card card normal" type="people" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li style="display:none;">\ <a class="tweet_bar_btn add_to_list_btn" title="Add to list" href="#follow" data-i18n-title="add_to_list"></a>\ </li><li>\ <a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\ </li><li>\ <a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\ </li>\ </ul>\ <div class="card_body">\ <div id="{%USER_ID%}" class="who">\ <a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\ {%SCREEN_NAME%}\ </a>\ </div>\ <div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', people_vcard_t_orig: '<div class="header_frame">\ <div class="people_vcard vcard">\ <a target="_blank" class="profile_img_wrapper"></a>\ <div class="vcard_body">\ <center>\ <ul class="people_vcard_radio_group mochi_button_group"> \ <li><a class="mochi_button_group_item selected" href="#people_vcard_info_page" name="">{%TRANS_info%}</a> \ </li><li><a class="mochi_button_group_item" href="#people_vcard_stat_page">{%TRANS_stat%}</a> \ </li></ul>\ </center>\ <div class="vcard_tabs_pages">\ <table class="people_vcard_info_page vcard_tabs_page radio_group_page" border="0" cellpadding="0" cellspacing="0"> \ <tr><td>{%TRANS_name%}: </td><td> \ <a class="screen_name" target="_blank" href="#"></a> \ (<span class="name"></span>) </td> \ </tr> \ <tr><td>{%TRANS_bio%}: </td> \ <td><span class="bio"></span></td> \ </tr> \ <tr><td>{%TRANS_web%}: </td> \ <td><a class="web" target="_blank" href="#" class="link"></a></td> \ </tr> \ <tr><td>{%TRANS_location%}: </td> \ <td><span class="location"></span></td> \ </tr> \ </table> \ <table class="people_vcard_stat_page vcard_tabs_page radio_group_page"> \ <tr><td>{%TRANS_join%}: </td> \ <td><span class="join"></span></td> \ </tr> \ <tr><td>{%TRANS_tweet_cnt%}: </td> \ <td><span class="tweet_cnt"></span> \ (<span class="tweet_per_day_cnt"></span> per day)</td> \ </tr> \ <tr><td>{%TRANS_follower_cnt%}: </td> \ <td><span class="follower_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_friend_cnt%}: </td> \ <td><span class="friend_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_listed_cnt%}: </td> \ <td><span class="listed_cnt"></span></td> \ </tr> \ <tr><td>{%TRANS_relation%}: </td> \ <td><span class="relation"></span></td> \ </tr> \ </table> \ </div><!-- vcard tabs pages --> \ </div> <!-- vcard body --> \ <div class="vcard_ctrl"> \ <ul class="vcard_action_btns"> \ <li><a class="vcard_follow mochi_button blue" \ href="#" >{%TRANS_follow%}</a> \ </li><li> \ <a class="vcard_edit mochi_button" \ href="#" style="display:none;">{%TRANS_edit%}</a>\ </li><li class="people_action_more_trigger"> \ <a class="vcard_more mochi_button" \ href="#">{%TRANS_more_actions%} &#x25BE;</a> \ <ul class="people_action_more_memu hotot_menu">\ <li><a class="mention_menu_item" \ title="Mention them"\ href="#">{%TRANS_mention_them%}</a>\ </li><li><a class="message_menu_item" \ title="Send Message to them"\ href="#">{%TRANS_message_them%}</a>\ </li><li><a class="add_to_list_menu_item" \ title="Add them to a list"\ href="#">{%TRANS_add_to_list%}</a>\ </li><li class="separator"><span></span>\ </li><li><a class="block_menu_item" \ title="Block"\ href="#">{%TRANS_block%}</a>\ </li><li><a class="unblock_menu_item"\ href="#" \ title="Unblock">{%TRANS_unblock%}</a>\ </li><li><a class="report_spam_menu_item" \ href="#" \ title="Report Spam">{%TRANS_report_spam%}</a>\ </li>\ </ul>\ </li> \ </ul> \ </div><!-- #people_vcard_ctrl --> \ </div> <!-- vcard --> \ <div class="expand_wrapper"><a href="#" class="expand">…</a></div>\ <div class="people_view_toggle"> \ <ol class="people_view_toggle_btns mochi_button_group"> \ <li><a class="people_view_tweet_btn mochi_button_group_item selected" href="#tweet">{%TRANS_tweets%}</a> \ </li><li> \ <a class="people_view_fav_btn mochi_button_group_item" href="#fav">{%TRANS_favs%}</a> \ </li><li class="people_view_people_trigger"> \ <a class="people_view_people_btn mochi_button_group_item" href="#people">{%TRANS_fellowship%} &#x25BE;</a> \ <ul class="people_menu hotot_menu">\ <li><a class="followers_menu_item" \ title="People who follow them."\ href="#">{%TRANS_followers%}</a>\ </li><li><a class="friends_menu_item"\ href="People them is following" \ title="All Lists following Them">{%TRANS_friends%}</a>\ </li>\ </ul>\ </li><li class="people_view_list_trigger"> \ <a class="people_view_list_btn mochi_button_group_item" href="#list">{%TRANS_lists%} &#x25BE;\ </a> \ <ul class="lists_menu hotot_menu">\ <li><a class="user_lists_menu_item" \ title="Lists of Them"\ href="#">{%TRANS_lists_of_them%}</a>\ </li><li><a class="listed_lists_menu_item"\ href="#" \ title="All Lists following Them">{%TRANS_lists_following_them%}</a>\ </li><li><a class="create_list_menu_item" \ href="#" \ title="Create A List">{%TRANS_create_a_list%}</a>\ </li>\ </ul>\ </li> \ </ol> \ </div> \ <div class="people_request_hint"> \ <h1 data-i18n-text="he_she_has_protexted_his_her_tweets">He/She has protected his/her tweets.</span></h1> \ <p data-i18n-text="you_need_to_go_to_twitter_com_to_send_a_request_before_you_can_start_following_this_persion">You need to go to twitter.com to send a request before you can start following this person...</p> \ <div style="text-align:center;"> \ <a class="people_request_btn mochi_button" href="#" target="_blank" data-i18n-text="send_request">Send Request</a> \ </div> \ </div></div>', list_t: '<li id="{%LIST_ID%}" class="list_card card normal" type="list" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} slug={%SLUG%} style="font-family: {%TWEET_FONT%};">\ <div class="tweet_active_indicator"></div>\ <div class="tweet_selected_indicator"></div>\ <div class="profile_img_wrapper" title="@{%USER_NAME%}/{%SLUG%}" style="background-image: url({%PROFILE_IMG%})">\ </div>\ <ul class="tweet_bar">\ <li>\ <a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\ </li><li>\ <a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\ </li>\ </ul>\ <div class="card_body">\ <div id="{%USER_ID%}" class="who">\ <a class="list_href" href="#{%SCREEN_NAME%}/{%SLUG%}" title="{%USER_NAME%}/{%SLUG%}">\ @{%SCREEN_NAME%}/{%SLUG%}\ </a>\ </div>\ <div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\ </div>\ <span class="shape"></span>\ <span class="shape_mask"></span>\ </li>', list_vcard_t: '<div class="header_frame"><div class="list_vcard vcard">\ <a target="_blank" class="profile_img_wrapper"></a>\ <div class="vcard_body">\ <div class="vcard_tabs_pages">\ <table border="0" cellpadding="0" cellspacing="0" class="vcard_tabs_page" style="display:block;"> \ <tr><td data-i18n-text="name">Name: </td><td> \ <a class="name" target="_blank" href="#"></a></td> \ </tr> \ <tr><td>Owner: </td> \ <td><a class="owner" target="_blank" href="#" data-i18n-text="owner"></a></td> \ </tr> \ <tr><td data-i18n-text="description">Description: </td> \ <td><span class="description"></span></td> \ </tr> \ </table> \ </div>\ </div> <!-- vcard body --> \ <div class="vcard_ctrl"> \ <ul class="vcard_action_btns"> \ <li><a class="vcard_follow mochi_button blue" \ href="#" data-i18n-text="follow">Follow</a> \ </li><li> \ <a class="vcard_delete mochi_button red" \ href="#" data-i18n-text="delete">Delete</a> \ </li><li> \ <a class="vcard_edit mochi_button" \ href="#" style="display:none;" data-i18n-text="edit">Edit</a>\ </li> \ </ul> \ </div><!-- #list_vcard_ctrl --> \ </div> <!-- vcard --> \ <div class="expand_wrapper"><a href="#" class="expand">…</a></div>\ <div class="list_view_toggle"> \ <ol class="list_view_toggle_btns mochi_button_group"> \ <li><a class="list_view_tweet_btn mochi_button_group_item selected" href="#tweet" data-i18n-text="tweets">Tweets</a> \ </li><li> \ <a class="list_view_follower_btn mochi_button_group_item" href="#follower" data-i18n-text="followers">Followers</a> \ </li><li> \ <a class="list_view_following_btn mochi_button_group_item" href="#following" data-i18n-text="following">Following</a> \ </li> \ </ol> \ </div> \ <div class="list_lock_hint"> \ <h1 data-i18n-text="he_she_has_protected_his_her_list">He/She has protected his/her list.</span></h1> \ <p data-i18n-text="only_the_owner_can_access_this_list">Only the owner can access this list.</p> \ </div></div>', search_header_t: '<div class="header_frame"> \ <div class="search_box"> \ <input class="search_entry mochi_entry" type="text" placeholder="Type and press enter to search." data-i18n-placeholder="type_and_press_enter_to_search"/> \ <a href="#" class="search_entry_clear_btn"></a>\ <div class="search_people_result"> \ <span data-i18n-text="one_user_matched">One user matched: </span> <span class="search_people_inner"></span>\ </div>\ <div class="saved_searches">\ <a id="create_saved_search_btn" class="mochi_button" \ href="#" title="Detach" data-i18n-title="detach"> +\ </a>\ <div id="saved_searches_more_trigger" style="display:none;">\ <a id="saved_searches_btn" class="vcard_more mochi_button" \ href="#"> &#x25BE;</a> \ <ul id="saved_searches_more_menu" class="hotot_menu">\ <li><a class="" \ title="Clear ALL"\ href="#" data-i18n-title="clear_all" data-i18n-text="clear_all">Clear All</a>\ </li><li class="separator"><span></span>\ </li><li>\ <a class="saved_search_item" href="#">a</a>\ </li>\ </ul>\ </div>\ </div>\ <div class="search_view_toggle">\ <ol class="search_view_toggle_btns mochi_button_group">\ <li><a class="search_tweet mochi_button_group_item selected" \ href="#tweet" data-i18n-text="tweets">Tweet</a>\ </li><li> \ <a class="search_people mochi_button_group_item"\ href="#people" data-i18n-text="people">People</a>\ </li> \ </ol> \ </div> \ <div class="search_no_result_hint"> \ <p><span data-i18n-text="your_search">Your search</span> - <label class="keywords"></label> - <span data-i18n-text="did_not_match_any_result">did not match any result.</span></p> \ <p><span data-i18n-text="suggestions">Suggestions</span>: <br/> \ - <span data-i18n-text="make_sure_all_words_are_spelled_correctly">Make sure all words are spelled correctly.</span><br/> \ - <span data-i18n-text="try_different_keywords">Try different keywords.</span><br/> \ - <span data-i18n-text="try_more_general_keywords">Try more general keywords.</span><br/></p> \ </div> \ </div> \ </div>', retweets_header_t: '<div class="header_frame"><div class="retweets_view_toggle"> \ <ol class="retweets_view_toggle_btns radio_group">\ <li><a class="btn_retweeted_to_me radio_group_btn selected" \ href="#retweeted_to_me" data-i18n-text="by_others">By Others</a>\ </li><li> \ <a class="btn_retweeted_by_me radio_group_btn"\ href="#retweeted_by_me" data-i18n-text="by_me">By Me</a>\ </li><li> \ <a class="btn_retweets_of_me radio_group_btn" \ href="#retweets_of_me" data-i18n-text="my_tweets_retweeted">My Tweets, Retweeted</a> \ </li> \ </ol> \ </div></div>', common_column_header_t: '<div class="column_settings"> \ <ul class="mochi_list dark">\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_auto_update" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="auto_update">Auto Update</label>\ </li>\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_notify" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="notify">Notify</label>\ </li>\ <li class="mochi_list_item dark"> \ <input type="checkbox" href="#use_notify_sound" class="mochi_toggle dark widget"/>\ <label class="label" data-i18n-text="sound">Sound</label>\ </li>\ </ul>\ </div>\ ', view_t: '<div id="{%ID%}" \ name="{%NAME%}" class="listview scrollbar_container {%CLASS%} {%ROLE%}"> \ <div class="scrollbar_track">\ <div class="scrollbar_slot">\ <div class="scrollbar_handle"></div>\ </div>\ </div>\ <div class="scrollbar_content listview_content">\ <div class="listview_header"><div class="header_content">{%HEADER%}</div></div> \ <ul class="listview_body"></ul> \ <div class="listview_footer"> \ <div class="load_more_info"><img src="image/ani_loading_bar.gif"/></div> \ </div> \ </div> \ </div>', indicator_t: '<div class="{%STICK%} {%ROLE%}" name="{%TARGET%}" draggable="true"><a class="indicator_btn" href="#{%TARGET%}" title="{%TITLE%}"><img class="icon" src="{%ICON%}"/><div class="icon_alt" style="background-image: url({%ICON%})"></div></a><span class="shape"></span></div>', kismet_rule_t: '<li><a class="kismet_rule" name="{%NAME%}" type="{%TYPE%}" method="{%METHOD%}"\ disabled="{%DISABLED%}" field="{%FIELD%}" pattern="{%PATTERN%}" \ actions="{%ACTIONS%}" {%ADDITION%} href="#">{%NAME%}</a></li>', status_draft_t: '<li mode="{%MODE%}" reply_to_id="{%REPLY_TO_ID%}" reply_text="{%REPLY_TEXT%}" recipient="{%RECIPIENT%}"><a class="text">{%TEXT%}</a><a class="btn_draft_clear" href="#"></a></li>', preview_link_reg: { 'img.ly': { reg: new RegExp('http:\\/\\/img.ly\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://img.ly/show/thumb/', direct_base: 'http://img.ly/show/full/' }, 'twitpic.com': { reg: new RegExp('http:\\/\\/twitpic.com\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://twitpic.com/show/thumb/' }, 'twitgoo.com': { reg: new RegExp('http:\\/\\/twitgoo.com\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://twitgoo.com/show/thumb/', direct_base: 'http://twitgoo.com/show/img/' }, 'yfrog.com': { reg: new RegExp('http:\\/\\/yfrog.com\\/([a-zA-Z0-9_\\-]+)','g'), tail: '.th.jpg' }, 'moby.to': { reg: new RegExp('http:\\/\\/moby.to\\/([a-zA-Z0-9_\\-]+)','g'), tail: ':thumbnail' }, 'instagr.am': { reg: new RegExp('http:\\/\\/instagr.am\\/p\\/([a-zA-Z0-9_\\-]+)\\/?','g'), tail: 'media?size=m', direct_tail: 'media?size=l' }, 'plixi.com': { reg: new RegExp('http:\\/\\/plixi.com\\/p\\/([a-zA-Z0-9_\\-]+)','g'), base: 'http://api.plixi.com/api/tpapi.svc/imagefromurl?size=thumbnail&url=' }, 'picplz.com': { reg: new RegExp('http:\\/\\/picplz.com\\/([a-zA-Z0-9_\\-]+)','g'), tail: '/thumb/' }, 'raw': { reg: new RegExp('[a-zA-Z0-9]+:\\/\\/.+\\/.+\\.(jpg|jpeg|jpe|png|gif)', 'gi') }, 'youtube.com': { reg: new RegExp('href="(http:\\/\\/(www.)?youtube.com\\/watch\\?v\\=([A-Za-z0-9_\\-]+))','g'), base: 'http://img.youtube.com/vi/', tail: '/default.jpg', } }, init: function init() { ui.Template.reg_url = ''//ui.Template.reg_vaild_preceding_chars + '(' + ui.Template.reg_url_proto_chars + ui.Template.reg_url_path_chars_1 + '*' + ui.Template.reg_url_path_chars_2 + '+)'; ui.Template.reg_user = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])' + ui.Template.reg_user_name_chars, 'g'); ui.Template.reg_list = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])' + ui.Template.reg_list_name_template, 'ig'); ui.Template.reg_link = new RegExp(ui.Template.reg_url); ui.Template.reg_link_g = new RegExp(ui.Template.reg_url, 'g'); ui.Template.reg_hash_tag = new RegExp(ui.Template.reg_hash_tag_template .replace(new RegExp('{%LATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_latin_chars) .replace(new RegExp('{%NONLATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_nonlatin_chars) , 'ig'); ui.Template.tweet_m = { ID:'', TWEET_ID:'', RETWEET_ID:'' , REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:'' , PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:'' , IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:'' , RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:'' , DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT: '' , TWEET_LINE_HEIGHT:'' , STATUS_INDICATOR:'', TRANS_Delete:'' , TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:'' , TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:'' , TRANS_Send_Message:'', TRANS_Send_Message_to_them:'' , TRANS_via:'', TRANS_View_more_conversation:'' , TWEET_BASE_URL: '', IN_THREAD: '' , COLOR_LABEL: '' }; ui.Template.trending_topic_m = { ID:'', NAME:'' }; ui.Template.retweeted_by_m = { ID:'', TWEET_ID:'', RETWEET_ID:'' , REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:'' , PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:'' , IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:'' , RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:'' , DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , STATUS_INDICATOR:'', TRANS_Delete:'' , TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:'' , TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:'' , TRANS_Send_Message:'', TRANS_Send_Message_to_them:'' , TRANS_via:'', TRANS_View_more_conversation:'' , TRANS_retweeted_by:'', TRANS_Show_retweeters:'' , TRANS_Click_to_show_retweeters:'' , TWEET_BASE_URL: '' }; ui.Template.message_m = { ID:'', TWEET_ID:'', SCREEN_NAME:'', RECIPIENT_SCREEN_NAME:'' , USER_NAME:'', PROFILE_IMG:'', TEXT:'' , SCHEME:'', TIMESTAMP:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , TRANS_Reply_Them:'' }; ui.Template.search_m = { ID:'', TWEET_ID:'', SCREEN_NAME:'' , USER_NAME:'', PROFILE_IMG:'', TEXT:'', SOURCE:'' , SCHEME:'', SHORT_TIMESTAMP:'', TIMESTAMP:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' , TRANS_via:'' , TWEET_BASE_URL: '' }; ui.Template.people_m = { USER_ID:'', SCREEN_NAME:'', USER_NAME:'', DESCRIPTION:'' , PROFILE_IMG:'', FOLLOWING:'', TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' }; ui.Template.list_m = { LIST_ID:'', SCREEN_NAME:'', SLUG:'', NAME:'', MODE:'' , DESCRIPTION:'', PROFILE_IMG:'', FOLLOWING:'' , TWEET_FONT_SIZE:'', TWEET_FONT:'' , TWEET_LINE_HEIGHT:'' }; ui.Template.view_m = { ID:'', CLASS:'tweetview', NAME: '', CAN_CLOSE: '', ROLE: '' }; ui.Template.indicator_m = { TARGET: '', TITLE: '', ICON: '', ROLE: '' }; ui.Template.kismet_rule_m = { TYPE:'', DISABLED:'', FIELD:'', PATTERN:'' , METHOD:'', ACTIONS: '', ADDITION: '', NAME: '' }; ui.Template.status_draft_m = { MODE:'', TEXT:'', REPLY_TO_ID: '', REPLY_TEXT: '' , RECIPIENT: '' }; ui.Template.update_trans(); }, update_trans: function update_trans() { ui.Template.people_vcard_m = { TRANS_info: _('info'), TRANS_stat: _('stat') , TRANS_name: _('name'), TRANS_bio: _('bio') , TRANS_web: _('web'), TRANS_location: _('location') , TRANS_join: _('join'), TRANS_tweet_cnt: _('tweet_cnt') , TRANS_tweet_cnt: _('tweet_cnt') , TRANS_follower_cnt: _('follower_cnt') , TRANS_friend_cnt: _('friend_cnt') , TRANS_listed_cnt: _('listed_cnt') , TRANS_relation: _('relation') , TRANS_edit: _('edit') , TRANS_follow: _('follow'), TRANS_more_actions: _('more_actions') , TRANS_mention_them: _('mention_them') , TRANS_message_them: _('send_message_to_them') , TRANS_add_to_list: _('add_to_list') , TRANS_block: _('block') , TRANS_unblock: _('unblock') , TRANS_report_spam: _('report_spam') , TRANS_tweets: _('tweets'), TRANS_favs: _('favs') , TRANS_followers: _('followers'), TRANS_friends: _('friends') , TRANS_fellowship: _('fellowship') , TRANS_lists: _('lists'), TRANS_lists_of_them: _('lists_of_them') , TRANS_lists_following_them: _('lists_following_them') , TRANS_create_a_list: _('create_a_list') } ui.Template.people_vcard_t = ui.Template.render(ui.Template.people_vcard_t_orig, ui.Template.people_vcard_m); }, form_dm: function form_dm(dm_obj, pagename) { var timestamp = Date.parse(dm_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); var text = ui.Template.form_text(dm_obj); var m = ui.Template.message_m; m.ID = pagename + '-' + dm_obj.id_str; m.TWEET_ID = dm_obj.id_str; m.SCREEN_NAME = dm_obj.sender.screen_name; m.RECIPIENT_SCREEN_NAME = dm_obj.recipient.screen_name; m.USER_NAME = dm_obj.sender.name; m.DESCRIPTION = dm_obj.sender.description; m.PROFILE_IMG = util.big_avatar(dm_obj.sender.profile_image_url_https); m.TEXT = text; m.SCHEME = 'message'; m.TIMESTAMP = created_at_str; m.SHORT_TIMESTAMP = created_at_short_str; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.TWEET_FONT = globals.tweet_font; m.TRANS_Reply_Them = "Reply Them"; return ui.Template.render(ui.Template.message_t, m); }, // This function returns the html for the given tweet_obj. form_tweet: function form_tweet (tweet_obj, pagename, in_thread) { var retweet_name = ''; var retweet_str = ''; var retweet_id = ''; var id = tweet_obj.id_str; if (tweet_obj.hasOwnProperty('retweeted_status')) { retweet_name = tweet_obj['user']['screen_name']; tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one. tweet_obj = tweet_obj['retweeted_status']; retweet_id = tweet_obj.id_str; } var reply_name = tweet_obj.in_reply_to_screen_name; var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str') ? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id; var reply_str = (reply_id != null) ? _('reply_to') + ' <a class="who_href" href="#' + reply_name + '">' + reply_name + '</a>' : ''; var in_thread = in_thread == true ? true: false; var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); // choose color scheme var scheme = 'normal'; if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { if (tweet_obj.entities.user_mentions[i].screen_name == globals.myself.screen_name) { scheme = 'mention'; } } } if (tweet_obj.user.screen_name == globals.myself.screen_name) { scheme = 'me'; } if (retweet_name != '') { retweet_str = _('retweeted_by') + ' <a class="who_href" href="#' + retweet_name + '">' + retweet_name + '</a>, '; } var alt_text = tweet_obj.text; var link = ''; if (tweet_obj.entities && tweet_obj.entities.urls) { var urls = null; if (tweet_obj.entities.media) { urls = tweet_obj.entities.urls.concat(tweet_obj.entities.media); } else { urls = tweet_obj.entities.urls; } for (var i = 0, l = urls.length; i < l; i += 1) { var url = urls[i]; if (url.url && url.expanded_url) { tweet_obj.text = tweet_obj.text.replace(url.url, url.expanded_url); } } if (tweet_obj.entities.urls.length > 0) { link = tweet_obj.entities.urls[0].expanded_url; } } var text = ui.Template.form_text(tweet_obj); // if the tweet contains user_mentions (which are provided by the Twitter // API, not by the StatusNet API), it will here replace the // contents of the 'who_ref'-a-tag by the full name of this user. if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { // hotot_log('form_tweet', 'user mention: ' + tweet_obj.entities.user_mentions[i].screen_name); var screen_name = tweet_obj.entities.user_mentions[i].screen_name; var name = tweet_obj.entities.user_mentions[i].name.replace(/"/g, '&quot;'); var reg_ulink = new RegExp('>(' + screen_name + ')<', 'ig'); text = text.replace(reg_ulink, ' title="' + name + '">$1<') } // If we get here, and there are still <a who_href="...">-tags // without title attribute, the user name was probably misspelled. // If I then remove the tag, the incorrect user name is not // highlighted any more, which fixes #415 for twitter. // (It does not work for identi.ca, because the identi.ca API // does not provide user_mentions.) var re = /\<a class=\"who_href\" href=\"[^"]*\"\>([^<]*)\<\/a\>/gi text = text.replace(re, '$1'); // hotot_log('form_tweet', 'resulting text: ' + text); } var m = ui.Template.tweet_m; m.ID = pagename+'-'+id; m.TWEET_ID = id; m.RETWEET_ID = retweet_id; m.REPLY_ID = reply_id != null? reply_id:''; m.IN_THREAD = in_thread; m.SCREEN_NAME = tweet_obj.user.screen_name; m.REPLY_NAME = reply_id != null? reply_name: ''; m.USER_NAME = tweet_obj.user.name; m.DESCRIPTION = tweet_obj.user.description; m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https); m.TEXT = text; m.ALT = ui.Template.convert_chars(alt_text); m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.IN_REPLY = (reply_id != null && !in_thread) ? 'block' : 'none'; m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true'; m.COLOR_LABEL = kismet.get_user_color(tweet_obj.user.screen_name); m.REPLY_TEXT = reply_str; m.RETWEET_TEXT = retweet_str; m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': ''; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.FAV_CLASS = tweet_obj.favorited? 'faved': ''; m.DELETABLE = scheme == 'me'? 'true': 'false'; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj); m.TRANS_Delete = _('delete'); m.TRANS_Delete_this_tweet = _('delete_this_tweet'); m.TRANS_Loading = _('loading_dots'); m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet'); m.TRANS_Reply_All = _('reply_all'); m.TRANS_Reply_this_tweet = _('reply_this_tweet'); m.TRANS_RT_this_tweet = _('rt_this_tweet'); m.TRANS_Send_Message = _('send_message'); m.TRANS_Send_Message_to_them = _('send_message_to_them'); m.TRANS_via = _('via'); m.TRANS_View_more_conversation = _('view_more_conversation'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice'; m.LINK = link; return ui.Template.render(ui.Template.tweet_t, m); }, form_retweeted_by: function form_retweeted_by(tweet_obj, pagename) { var retweet_name = ''; var retweet_str = ''; var retweet_id = ''; var id = tweet_obj.id_str; if (tweet_obj.hasOwnProperty('retweeted_status')) { retweet_name = tweet_obj['user']['screen_name']; tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one. tweet_obj = tweet_obj['retweeted_status']; retweet_id = tweet_obj.id_str; } var reply_name = tweet_obj.in_reply_to_screen_name; var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str') ? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id; var reply_str = (reply_id != null) ? _('Reply to @') + ' <a class="who_href" href="#' + reply_name + '">' + reply_name + '</a>: ' : ''; var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); // choose color scheme var scheme = 'normal'; if (tweet_obj.entities && tweet_obj.entities.user_mentions) { for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1) { if (tweet_obj.entities.user_mentions[i].screen_name == globals.myself.screen_name) { scheme = 'mention'; } } } if (tweet_obj.user.screen_name == globals.myself.screen_name) { scheme = 'me'; } if (retweet_name != '') { retweet_str = _('retweeted_by') + ' <a class="who_href" href="#' + retweet_name + '">' + retweet_name + '</a>, '; } var m = ui.Template.retweeted_by_m; m.ID = pagename+'-'+id; m.TWEET_ID = id; m.RETWEET_ID = retweet_id; m.REPLY_ID = reply_id != null? reply_id:''; m.SCREEN_NAME = tweet_obj.user.screen_name; m.REPLY_NAME = reply_id != null? reply_name: ''; m.USER_NAME = tweet_obj.user.name; m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https); m.TEXT = ui.Template.form_text(tweet_obj); m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.IN_REPLY = (reply_id != null && pagename.split('-').length < 2) ? 'block' : 'none'; m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true'; m.REPLY_TEXT = reply_str; m.RETWEET_TEXT = retweet_str; m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': ''; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.FAV_CLASS = tweet_obj.favorited? 'faved': ''; m.DELETABLE = scheme == 'me'? 'true': 'false'; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj); m.TRANS_Delete = _('delete'); m.TRANS_Delete_this_tweet = _('delete_this_tweet'); m.TRANS_Loading = _('loading_dots'); m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet'); m.TRANS_Reply_All = _('reply_All'); m.TRANS_Reply_this_tweet = _('reply_this_tweet'); m.TRANS_RT_this_tweet = _('rt_this_tweet'); m.TRANS_Send_Message = _('send_message'); m.TRANS_Send_Message_to_them = _('send_message_to_them'); m.TRANS_via = _('via'); m.TRANS_View_more_conversation = _('view_more_conversation'); m.TRANS_Retweeted_by = _('retweeted_by'); m.TRANS_Show_retweeters = _('click_to_show'); m.TRANS_Click_to_show_retweeters = _('click_to_show_retweeters'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice'; return ui.Template.render(ui.Template.retweeted_by_t, m); }, form_search: function form_search(tweet_obj, pagename) { if (tweet_obj.user != undefined) { // use phoenix_search ... well, in fact, the original parser is totally useless. return ui.Template.form_tweet(tweet_obj, pagename); } var id = tweet_obj.id_str; var source = tweet_obj.source.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&quot;/g, ''); var timestamp = Date.parse(tweet_obj.created_at); var created_at = new Date(); created_at.setTime(timestamp); var created_at_str = ui.Template.to_long_time_string(created_at); var created_at_short_str = ui.Template.to_short_time_string(created_at); var text = ui.Template.form_text(tweet_obj); // choose color scheme var scheme = 'normal'; if (text.indexOf(globals.myself.screen_name) != -1) { scheme = 'mention'; } if (tweet_obj.from_user == globals.myself.screen_name) { scheme = 'me'; } var link = ''; if (tweet_obj.entities.urls.length > 0) { link = tweet_obj.entities.urls[0].expanded_url; } var m = ui.Template.search_m; m.ID = pagename + '-' + id; m.TWEET_ID = id; m.SCREEN_NAME = tweet_obj.from_user; m.USER_NAME = tweet_obj.from_user_name; m.PROFILE_IMG = util.big_avatar(tweet_obj.profile_image_url_https); m.TEXT = text; m.SOURCE = source.replace('href', 'target="_blank" href'); m.SCHEME = scheme; m.SHORT_TIMESTAMP = created_at_short_str; m.TIMESTAMP = created_at_str; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; m.TRANS_via = _('via'); m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.from_user + '/status':'https://identi.ca/notice'; m.LINK = link; return ui.Template.render(ui.Template.search_t, m); }, form_people: function form_people(user_obj, pagename) { var m = ui.Template.people_m; m.USER_ID = pagename + '-' + user_obj.id_str; m.SCREEN_NAME = user_obj.screen_name; m.USER_NAME = user_obj.name; m.DESCRIPTION = user_obj.description; m.PROFILE_IMG = util.big_avatar(user_obj.profile_image_url_https); m.FOLLOWING = user_obj.following; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; return ui.Template.render(ui.Template.people_t, m); }, form_list: function form_people(list_obj, pagename) { var m = ui.Template.list_m; m.LIST_ID = pagename + '-' + list_obj.id_str; m.SCREEN_NAME = list_obj.user.screen_name; m.SLUG = list_obj.slug; m.NAME = list_obj.name; m.MODE = list_obj.mode; m.DESCRIPTION = list_obj.description; m.PROFILE_IMG = util.big_avatar(list_obj.user.profile_image_url_https); m.FOLLOWING = list_obj.following; m.TWEET_FONT_SIZE = globals.tweet_font_size; m.TWEET_FONT = globals.tweet_font; m.TWEET_LINE_HEIGHT = globals.tweet_line_height; return ui.Template.render(ui.Template.list_t, m); }, form_view: function form_view(name, title, cls) { var m = ui.Template.view_m; m.ID = name + '_tweetview'; m.NAME = name; m.CLASS = cls; if (name == 'home') { m.CAN_CLOSE = 'none'; } else { m.CAN_CLOSE = 'block'; } if (ui.Slider.system_views.hasOwnProperty(name)) { m.ROLE = 'system_view'; } else { m.ROLE = 'custom_view'; } return ui.Template.render(ui.Template.view_t, m); }, form_indicator: function form_indicator(target, title, icon) { var m = ui.Template.indicator_m; m.TARGET = target m.TITLE = title; m.ICON = icon; if (ui.Slider.system_views.hasOwnProperty(target)) { m.ROLE = 'system_view'; } else { m.ROLE = 'custom_view'; } return ui.Template.render(ui.Template.indicator_t, m); }, form_kismet_rule: function form_kismet_rule(rule) { var m = ui.Template.kismet_rule_m; m.NAME = rule.name; m.TYPE = rule.type; m.METHOD = rule.method; m.PATTERN = rule.pattern; m.ACTIONS = rule.actions.join(':'); m.ADDITION = rule.actions.indexOf(3)!=-1?'archive_name="'+rule.archive_name+'"':'archive_name=""'; m.FIELD = rule.field; m.DISABLED = rule.disabled; return ui.Template.render(ui.Template.kismet_rule_t, m); }, form_status_draft: function form_status_draft(draft) { var m = ui.Template.status_draft_m; m.MODE = draft.mode; m.TEXT = draft.text.replace(/</g, "&lt;").replace(/>/g,"&gt;"); if (m.MODE == ui.StatusBox.MODE_REPLY) { m.REPLY_TO_ID = draft.reply_to_id; m.REPLY_TEXT = draft.reply_text } else if (m.MODE == ui.StatusBox.MODE_DM) { m.RECIPIENT = draft.recipient; } else if (m.MODE == ui.StatusBox.MODE_IMG) { } return ui.Template.render(ui.Template.status_draft_t, m); }, fill_people_vcard: function fill_people_vcard(user_obj, vcard_container) { var created_at = new Date(Date.parse(user_obj.created_at)); var now = new Date(); var differ = Math.floor((now-created_at)/(1000 * 60 * 60 * 24)); var created_at_str = ui.Template.to_long_time_string(created_at); vcard_container.find('.profile_img_wrapper') .attr('href', user_obj.profile_image_url_https.replace(/_normal/, '')) .attr('style', 'background-image:url('+util.big_avatar(user_obj.profile_image_url_https)+');'); vcard_container.find('.screen_name') .attr('href', conf.get_current_profile().preferences.base_url + user_obj.screen_name) .text(user_obj.screen_name); vcard_container.find('.name').text(user_obj.name); vcard_container.find('.tweet_cnt').text(user_obj.statuses_count); vcard_container.find('.tweet_per_day_cnt').text( Math.round(user_obj.statuses_count / differ * 100)/ 100); vcard_container.find('.follower_cnt').text(user_obj.followers_count); vcard_container.find('.friend_cnt').text(user_obj.friends_count); vcard_container.find('.listed_cnt').text(user_obj.listed_count); vcard_container.find('.bio').unbind().empty().html( ui.Template.form_text_raw(user_obj.description)); ui.Main.bind_tweet_text_action(vcard_container.find('.bio')); vcard_container.find('.location').text('').text(user_obj.location); vcard_container.find('.join').text(created_at_str); if (user_obj.url) { vcard_container.find('.web').text(user_obj.url) vcard_container.find('.web').attr('href', user_obj.url); } else { vcard_container.find('.web').text('') vcard_container.find('.web').attr('href', '#'); } vcard_container.find('.people_vcard_radio_group .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_vcard') vcard_container.find('.people_view_toggle .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_views') }, fill_list_vcard: function fill_list_vcard(view, list_obj) { var vcard_container = view._header; vcard_container.find('.profile_img_wrapper') .attr('style', 'background-image:url(' + util.big_avatar(list_obj.user.profile_image_url_https) + ');'); vcard_container.find('.name') .attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name + '/' + list_obj.slug) .text(list_obj.full_name); vcard_container.find('.owner') .attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name) .text(list_obj.user.screen_name); vcard_container.find('.description').text(list_obj.description); }, convert_chars: function convert_chars(text) { text = text.replace(/"/g, '&#34;'); text = text.replace(/'/g, '&#39;'); text = text.replace(/\$/g, '&#36;'); return text; }, // This function applies some basic replacements to tweet.text, and returns // the resulting string. // This is not the final text that will appear in the UI, form_tweet will also do // some modifications. from_tweet will search for the a-tags added in this // function, to do the modifications. form_text: function form_text(tweet) { //hotot_log('form_text in', tweet.text); var text = ui.Template.convert_chars(tweet.text); text = text.replace(ui.Template.reg_link_g, function replace_url(url) { if (url.length > 51) url_short = url.substring(0,48) + '...'; else url_short = url; return ' <a href="'+url+'" target="_blank">' + url_short + '</a>'; }); text = text.replace(/href="www/g, 'href="http://www'); text = text.replace(ui.Template.reg_list , '$1@<a class="list_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_user , '$1@<a class="who_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_hash_tag , '$1<a class="hash_href" href="#$2">#$2</a>'); text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g , 'full_text_id="$2" href="$1"'); text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n'); text = text.replace(/\n/g, '<br/>'); if (ui.Template.reg_is_rtl.test(text)) { text = '<div class="text_inner" align="right" dir="rtl">' + text + '</div>'; } else { text = '<div class="text_inner">' + text + '</div>'; } if (conf.get_current_profile().preferences.use_media_preview) { text += '<div class="preview">' + ui.Template.form_preview(tweet) + '</div>'; } //hotot_log('form_text out', text); return text; }, form_text_raw: function form_text_raw(raw_text) { var text = raw_text; text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(ui.Template.reg_link_g, ' <a href="$1" target="_blank">$1</a>'); text = text.replace(/href="www/g, 'href="http://www'); text = text.replace(ui.Template.reg_list , '$1@<a class="list_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_user , '$1@<a class="who_href" href="#$2">$2</a>'); text = text.replace(ui.Template.reg_hash_tag , '$1<a class="hash_href" href="#$2">#$2</a>'); text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g , 'full_text_id="$2" href="$1"'); text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n'); text = text.replace(/\n/g, '<br/>'); return text; }, form_media: function form_media(href, src, direct_url) { if (direct_url != undefined) { return '<a direct_url="'+direct_url+'" href="'+href+'"><img src="'+ src +'" /></a>'; } else { return '<a href="'+href+'" target="_blank"><img src="'+ src +'" /></a>'; } }, form_preview: function form_preview(tweet) { var html_arr = []; var link_reg = ui.Template.preview_link_reg; for (var pvd_name in link_reg) { var match = link_reg[pvd_name].reg.exec(tweet.text); while (match != null) { switch (pvd_name) { case 'img.ly': case 'twitgoo.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[1], link_reg[pvd_name].direct_base + match[1])); break; case 'twitpic.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[1])); break; case 'instagr.am': html_arr.push( ui.Template.form_media( match[0], match[0] + link_reg[pvd_name].tail, match[0] + link_reg[pvd_name].direct_tail)); break; case 'yfrog.com': case 'moby.to': case 'picplz.com': html_arr.push( ui.Template.form_media( match[0], match[0] + link_reg[pvd_name].tail)); break; case 'plixi.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base +match[0])); break; case 'raw': html_arr.push( ui.Template.form_media( match[0], match[0], match[0])); break; case 'youtube.com': html_arr.push( ui.Template.form_media( match[0], link_reg[pvd_name].base + match[2] + link_reg[pvd_name].tail)); break; } match = link_reg[pvd_name].reg.exec(tweet.text); } } // twitter official picture service if (tweet.entities && tweet.entities.media) { for (var i = 0; i < tweet.entities.media.length; i += 1) { var media = tweet.entities.media[i]; if (media.expanded_url && media.media_url) { html_arr.push( ui.Template.form_media( tweet.entities.media[i].expanded_url, tweet.entities.media[i].media_url + ':thumb', tweet.entities.media[i].media_url + ':large' )); } } } if (conf.get_current_profile().preferences.filter_nsfw_media && tweet.text.match(/nsfw/ig)) html_arr = ['<i>NSFW image hidden</i>']; if (html_arr.length != 0) { return '<p class="media_preview">'+ html_arr.join('')+'</p>'; } return ''; }, form_status_indicators: function form_status_indicators(tweet) { }, render: function render(tpl, map) { var text = tpl var replace = false; for (var k in map) { replace = typeof map[k] == 'string' ? map[k] : ''; text = text.replace(new RegExp('{%'+k+'%}', 'g'), replace); } return text; }, to_long_time_string: function (datetime) { return moment(datetime).toLocaleString(); }, to_short_time_string: function (dataObj) { var is_human = conf.get_current_profile().preferences.show_relative_timestamp, now = moment(), mobj = moment(dataObj), time_str; if (is_human) { try { mobj.lang(i18n.current); mobj.lang(); } catch (e) { mobj.lang(false); } if(now.diff(mobj, 'hours', true) > 6) { time_str = mobj.calendar(); } else { time_str = mobj.fromNow(); } } else { if(now.diff(mobj, 'days', true) > 1) { time_str = mobj.format('YYYY-MM-DD HH:mm:ss'); } else { time_str = mobj.format('YYYY-MM-DD HH:mm:ss'); } } return time_str; } }
lgpl-3.0
ltettoni/logic2j
src/test/java/org/logic2j/core/impl/SolverTest.java
7797
/* * logic2j - "Bring Logic to your Java" - Copyright (c) 2017 [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Foobar 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.logic2j.core.impl; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.logic2j.core.ExtractingSolutionListener; import org.logic2j.core.PrologTestBase; import org.logic2j.engine.solver.holder.GoalHolder; /** * Lowest-level tests of the Solver: check core primitives: true, fail, cut, and, or. Check basic unification. * See other test classes for testing the solver against theories. */ public class SolverTest extends PrologTestBase { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SolverTest.class); // --------------------------------------------------------------------------- // Simplest primitives and undefined goal // --------------------------------------------------------------------------- @Test public void primitiveFail() { final Object goal = unmarshall("fail"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(0); } @Test public void primitiveTrue() { final Object goal = unmarshall("true"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(1); } @Test public void primitiveCut() { final Object goal = unmarshall("!"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(1); } @Test public void atomUndefined() { final Object goal = unmarshall("undefined_atom"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(0); } @Test public void primitiveTrueAndTrue() { final Object goal = unmarshall("true,true"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(1); } @Test public void primitiveTrueOrTrue() { final Object goal = unmarshall("true;true"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(2); } @Test public void corePrimitivesThatYieldUniqueSolution() { final String[] SINGLE_SOLUTION_GOALS = new String[]{ // "true", // "true, true", // "true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true", // "!", // "!, !", // }; countOneSolution(SINGLE_SOLUTION_GOALS); } @Test public void corePrimitivesThatYieldNoSolution() { final String[] NO_SOLUTION_GOALS = new String[]{ // "fail", // "fail, fail", // "fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail", // "true, fail", // "fail, true", // "true, true, fail", // "true, fail, !", // }; countNoSolution(NO_SOLUTION_GOALS); } /** * This is a special feature of logic2j: AND with any arity */ @Test public void nonBinaryAnd() { loadTheoryFromTestResourcesDir("test-functional.pro"); final String[] SINGLE_SOLUTION_GOALS = new String[]{ // "','(true)", // "','(true, true)", // "','(true, !, true)", // }; countOneSolution(SINGLE_SOLUTION_GOALS); } @Test public void or() { loadTheoryFromTestResourcesDir("test-functional.pro"); countNSolutions(2, "';'(true, true)"); countNSolutions(2, "true; true"); // countNSolutions(3, "true; true; true"); // GoalHolder solutions; solutions = this.prolog.solve("X=a; X=b; X=c"); assertThat(solutions.var("X").list().toString()).isEqualTo("[a, b, c]"); } /** * This is a special feature of logic2j: OR with any arity */ @Test public void nonBinaryOr() { loadTheoryFromTestResourcesDir("test-functional.pro"); countNSolutions(2, "';'(true, true)"); // if (Solver.INTERNAL_OR) { // countNSolutions(1, "';'(true)"); // countNSolutions(3, "';'(true, true, true)"); // } countNSolutions(1, "true"); countNSolutions(3, "true; true; true"); } @Test public void orWithVars() { GoalHolder solutions; solutions = this.prolog.solve("X=1; Y=2"); final String actual = solutions.vars().list().toString(); assertThat("[{Y=Y, X=1}, {Y=2, X=X}]".equals(actual) || "[{X=1, Y=Y}, {X=X, Y=2}]".equals(actual)).isTrue(); } @Test public void orWithClause() { loadTheoryFromTestResourcesDir("test-functional.pro"); GoalHolder solutions; solutions = this.prolog.solve("or3(X)"); assertThat(solutions.var("X").list().toString()).isEqualTo("[a, b, c]"); } @Test public void not() { // Surprisingly enough, the operator \+ means "not provable". uniqueSolution("not(fail)", "\\+(fail)"); nSolutions(0, "not(true)", "\\+(true)"); } // --------------------------------------------------------------------------- // Basic unification // --------------------------------------------------------------------------- @Test public void unifyLiteralsNoSolution() { final Object goal = unmarshall("a=b"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(0); } @Test public void unifyLiteralsOneSolution() { final Object goal = unmarshall("c=c"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(1); } @Test public void unifyAnonymousToAnonymous() { final Object goal = unmarshall("_=_"); final int nbSolutions = solveWithExtractingListener(goal).count(); assertThat(nbSolutions).isEqualTo(1); } @Test public void unifyVarToLiteral() { final Object goal = unmarshall("Q=d"); final ExtractingSolutionListener listener = solveWithExtractingListener(goal); assertThat(listener.count()).isEqualTo(1); assertThat(listener.getVariables().toString()).isEqualTo("[Q]"); assertThat(marshall(listener.getValues("."))).isEqualTo("[d = d]"); assertThat(marshall(listener.getValues("Q"))).isEqualTo("[d]"); } @Test public void unifyVarToAnonymous() { final Object goal = unmarshall("Q=_"); final ExtractingSolutionListener listener = solveWithExtractingListener(goal); assertThat(listener.count()).isEqualTo(1); assertThat(listener.getVariables().toString()).isEqualTo("[Q]"); assertThat(marshall(listener.getValues("."))).isEqualTo("[Q = _]"); assertThat(marshall(listener.getValues("Q"))).isEqualTo("[Q]"); } @Test public void unifyVarToVar() { final Object goal = unmarshall("Q=Z"); final ExtractingSolutionListener listener = solveWithExtractingListener(goal); assertThat(listener.count()).isEqualTo(1); assertThat(listener.getVarNames().toString()).isEqualTo("[., Q, Z]"); assertThat(marshall(listener.getValues("."))).isEqualTo("[Q = Q]"); assertThat(marshall(listener.getValues("Q"))).isEqualTo("[Q]"); assertThat(marshall(listener.getValues("Z"))).isEqualTo("[Q]"); } }
lgpl-3.0
DivineCooperation/jul
processing/default/src/test/java/org/openbase/jul/processing/VariableProcessorTest.java
3307
package org.openbase.jul.processing; /* * #%L * JUL Processing Default * %% * Copyright (C) 2015 - 2021 openbase.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 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPServiceException; import org.openbase.jul.exception.MultiException; /** * * * @author Divine <a href="mailto:[email protected]">Divine Threepwood</a> */ public class VariableProcessorTest { private TestVariableProvider provider; public VariableProcessorTest() { provider = new TestVariableProvider(); } @BeforeClass public static void setUpClass() throws JPServiceException { JPService.setupJUnitTestMode(); } /** * Test of resolveVariables method, of class VariableProcessor. */ @Test(timeout = 5000) public void testResolveVariables() throws Exception { System.out.println("testResolveVariables"); String context = "${VAR_A} : Hey Mr ${VAR_B} is happy today because of Mrs ${VAR_C}. ${VAR_W}${VAR_O}${VAR_W}"; boolean throwOnError = true; String expResult = "A : Hey Mr B is happy today because of Mrs C. WOW"; String result = VariableProcessor.resolveVariables(context, throwOnError, provider); assertEquals(expResult, result); } /** * Test of resolveVariables method, of class VariableProcessor. */ @Test(timeout = 5000) public void testResolveVariablesErrorCase() throws Exception { System.out.println("testResolveVariablesErrorCase"); String context = "${VAR_A} : Hey Mr ${VAR_D} is happy today because of Mrs ${VAR_C}. ${VAR_W}${VAR_Y}${VAR_W}"; boolean throwOnError = true; String expResult = "A : Hey Mr is happy today because of Mrs C. WW"; try { VariableProcessor.resolveVariables(context, throwOnError, provider); fail("No exception is thrown in error case!"); } catch (MultiException ex) { } String result = VariableProcessor.resolveVariables(context, false, provider); assertEquals(expResult, result); } public class TestVariableProvider extends VariableStore { public TestVariableProvider() { super("TestVarPro"); store("VAR_A", "A"); store("VAR_B", "B"); store("VAR_C", "C"); store("VAR_W", "W"); store("VAR_O", "O"); } } }
lgpl-3.0
kabluinc/PocketMine-MP
src/pocketmine/network/mcpe/protocol/types/EntityLink.php
1388
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\network\mcpe\protocol\types; class EntityLink{ public const TYPE_REMOVE = 0; public const TYPE_RIDER = 1; public const TYPE_PASSENGER = 2; /** @var int */ public $fromEntityUniqueId; /** @var int */ public $toEntityUniqueId; /** @var int */ public $type; /** @var bool */ public $immediate; //for dismounting on mount death public function __construct(int $fromEntityUniqueId = null, int $toEntityUniqueId = null, int $type = null, bool $immediate = false){ $this->fromEntityUniqueId = $fromEntityUniqueId; $this->toEntityUniqueId = $toEntityUniqueId; $this->type = $type; $this->immediate = $immediate; } }
lgpl-3.0
enhancedportals/enhancedportals
src/main/java/enhanced/portals/client/gui/elements/ElementGlyphDisplay.java
1367
package enhanced.portals.client.gui.elements; import java.util.List; import enhanced.base.client.gui.BaseGui; import enhanced.base.client.gui.elements.BaseElement; import enhanced.core.Reference.ECMod; import enhanced.portals.portal.GlyphIdentifier; import net.minecraft.util.ResourceLocation; public class ElementGlyphDisplay extends BaseElement { GlyphIdentifier id; public ElementGlyphDisplay(BaseGui gui, int x, int y, GlyphIdentifier i) { super(gui, x, y, 162, 18); id = i; } public void setIdentifier(GlyphIdentifier i) { id = i; } @Override public void addTooltip(List<String> list) { } @Override protected void drawContent() { parent.getMinecraft().renderEngine.bindTexture(new ResourceLocation(ECMod.ID, "textures/gui/player_inventory.png")); drawTexturedModalRect(posX, posY, 7, 7, sizeX, sizeY); parent.getMinecraft().renderEngine.bindTexture(ElementGlyphSelector.glyphs); if (id != null && id.size() > 0) for (int i = 0; i < 9; i++) { if (i >= id.size()) break; int glyph = id.get(i), X2 = i % 9 * 18, X = glyph % 9 * 18, Y = glyph / 9 * 18; drawTexturedModalRect(posX + X2, posY, X, Y, 18, 18); } } @Override public void update() { } }
lgpl-3.0
LudooduL/crocbar
src/ReloadRemoteOrder.java
823
/** * Class ReloadRemoteOrder * Sending remote order for background reload * Creation: May, 06, 2011 * @author Ludovic APVRILLE * @see */ import java.io.*; import java.net.*; public class ReloadRemoteOrder { public static final int DEFAULT_PORT = 9362; public static void main(String[] args) throws Exception{ byte[] ipAddr = new byte[]{127, 0, 0, 1}; InetAddress addr = InetAddress.getByAddress(ipAddr); String sendData = "reload background"; byte [] buf = sendData.getBytes(); DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, addr, ReloadRemoteOrder.DEFAULT_PORT); DatagramSocket serverSocket = new DatagramSocket(9876); serverSocket.send(sendPacket); } } // End of class ReloadRemoteOrder
lgpl-3.0
Neurpheus/manalyser
src/main/java/org/neurpheus/nlp/morphology/inflection/CorePattern.java
8839
/* * Neurpheus - Morfological Analyser * * Copyright (C) 2006 Jakub Strychowski * * 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. */ package org.neurpheus.nlp.morphology.inflection; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.PrintStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.neurpheus.core.io.DataOutputStreamPacker; import org.neurpheus.nlp.morphology.VowelCharacters; import org.neurpheus.nlp.morphology.VowelCharactersImpl; /** * Represents a core pattern which is a common part of some cores covered by this pattern. * * @author Jakub Strychowski */ public class CorePattern implements Serializable { /** Unique serialization identifier of this class. */ static final long serialVersionUID = 770608060903220741L; /** Holds the pattern template. */ private String pattern; /** Holds the number of cores covered by this pattern. */ private int coveredCoresCount; /** Holds the weight of this pattern in a morphological analysis process. */ private int weight; /** * Creates a new instance of CorePattern. */ public CorePattern() { } /** * Returns a template of this pattern. * * @return A common fragment of cores. */ public String getPattern() { return pattern; } /** * Sets a new template for this code pattern. * * @param newPattern The new value of the template of this core pattern. */ public void setPattern(final String newPattern) { this.pattern = newPattern; } /** * Returns a number of cores covered by this core pattern. * * @return The number of covered cores. */ public int getCoveredCoresCount() { return coveredCoresCount; } /** * Sets the number of cores covered by this core pattern. * * @param newCoveredCoresCount The new number of covered cores. */ public void setCoveredCoresCount(final int newCoveredCoresCount) { this.coveredCoresCount = newCoveredCoresCount; } /** * Returns the weight value which is used by a morphological analysis process. * * @return The weight of this core pattern. */ public int getWeight() { return weight; } /** * Sets the weight value which is used by morphological analysis process. * * @param newWeight The new value of this core pattern weight. */ public void setWeight(final int newWeight) { this.weight = newWeight; } /** * Compares twis object with other core pattern. * * @param o The core pattern with which compare to. * * @return <code>0</code> if core patterns are equal, <code>-1</code> if this core pattern * is before the given core pattern, and <code>1</code> if this core pattern * is after the given core pattern. */ public int compareTo(final Object o) { CorePattern p = (CorePattern) o; return getPattern().compareTo(p.getPattern()); } /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * <code>java.util.HashMap</code>. * * @return a hash code value for this object. */ public int hashCode() { super.hashCode(); return getPattern().hashCode(); } /** * Indicates whether some other object is "equal to" this core pattern. * * @param obj The reference object with which to compare. * @return <code>true</code> if this object is the same as the obj * argument; <code>false</code> otherwise. */ public boolean equals(final Object obj) { return compareTo(obj) == 0; } /** * Prints this core pattern. * * @param out The output stream where this object should be printed. */ public void print(final PrintStream out) { out.print(pattern); out.print('('); out.print(weight); out.print(')'); } /** * Checks if a given core matches this core pattern. * * @param core The core to check. * @param vowels The object representing vowels of a language of the core. * * @return <code>true</code> if this core pattern covers the given core. */ public boolean matches(final String core, final VowelCharacters vowels) { if (pattern == null) { return core == null; } if (pattern.length() > core.length()) { return false; } char[] ca = core.toCharArray(); char[] pa = pattern.toCharArray(); int cix = ca.length - 1; for (int pix = pa.length - 1; pix >= 0; pix--, cix--) { if (ca[cix] != pa[pix]) { char c = pa[pix]; if (c == vowels.getVowelSign() && Character.isLetter(ca[cix])) { if (!vowels.isVowel(ca[cix])) { return false; } } else if (c == vowels.getConsonantSign() && Character.isLetter(ca[cix])) { if (vowels.isVowel(ca[cix])) { return false; } } else { return false; } } } return true; } /** * Removes from the given collection all cores covered by this core pattern. * * @param cores The collection of cores which should be filtered. * @param vowels The object representing vowels of a language of cores. */ public void removeCoveredCores(final Collection cores, final VowelCharacters vowels) { boolean containsVowel = false; boolean containsConsonant = false; int minCoreLength = Integer.MAX_VALUE; for (Iterator it = cores.iterator(); it.hasNext();) { String core = (String) it.next(); if (core.equals("%inn%") && pattern.equals("inn%")) { core = core + ""; } if (matches(core, vowels)) { int clen = core.length(); if (core.startsWith("%")) { clen--; } if (clen < minCoreLength) { minCoreLength = clen; } it.remove(); // check if core contains a vowel or a consonant at the position of // a character where core pattern starts if (pattern.length() < core.length()) { char c = core.charAt(core.length() - pattern.length() - 1); if (vowels.isVowel(c)) { containsVowel = true; } else { containsConsonant = true; } } } } if (pattern.length() < minCoreLength) { if (containsVowel && !containsConsonant) { pattern = vowels.getVowelSign() + pattern; } else if (containsConsonant && !containsVowel) { pattern = vowels.getConsonantSign() + pattern; } } } /** * Reads this object data from the given input stream. * * @param in The input stream where this IPB is stored. * * @throws IOException if any read error occurred. * @throws ClassNotFoundException if this object cannot be instantied. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); pattern = pattern.intern(); } public void write(final DataOutputStream out) throws IOException { DataOutputStreamPacker.writeString(pattern, out); DataOutputStreamPacker.writeInt(coveredCoresCount, out); DataOutputStreamPacker.writeInt(weight, out); } public void read(final DataInputStream in) throws IOException { pattern = DataOutputStreamPacker.readString(in); coveredCoresCount = DataOutputStreamPacker.readInt(in); weight = DataOutputStreamPacker.readInt(in); } }
lgpl-3.0
pcolby/libqtaws
src/securityhub/tagresourcerequest_p.h
1407
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_TAGRESOURCEREQUEST_P_H #define QTAWS_TAGRESOURCEREQUEST_P_H #include "securityhubrequest_p.h" #include "tagresourcerequest.h" namespace QtAws { namespace SecurityHub { class TagResourceRequest; class TagResourceRequestPrivate : public SecurityHubRequestPrivate { public: TagResourceRequestPrivate(const SecurityHubRequest::Action action, TagResourceRequest * const q); TagResourceRequestPrivate(const TagResourceRequestPrivate &other, TagResourceRequest * const q); private: Q_DECLARE_PUBLIC(TagResourceRequest) }; } // namespace SecurityHub } // namespace QtAws #endif
lgpl-3.0
mauro-idsia/blip
core/src/main/java/ch/idsia/blip/core/learn/solver/ps/NullProvider.java
226
package ch.idsia.blip.core.learn.solver.ps; import ch.idsia.blip.core.utils.ParentSet; public class NullProvider implements Provider { @Override public ParentSet[][] getParentSets() { return null; } }
lgpl-3.0
chb/i2b2-ssr
data_import/InformClient/src/main/java/org/cdisc/ns/odm/v1/ArchiveLayoutRef.java
1726
package org.cdisc.ns.odm.v1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ArchiveLayoutRef complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArchiveLayoutRef"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefElementExtension" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeExtension"/> * &lt;attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeDefinition"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArchiveLayoutRef") public class ArchiveLayoutRef { @XmlAttribute(name = "ArchiveLayoutOID", required = true) protected String archiveLayoutOID; /** * Gets the value of the archiveLayoutOID property. * * @return * possible object is * {@link String } * */ public String getArchiveLayoutOID() { return archiveLayoutOID; } /** * Sets the value of the archiveLayoutOID property. * * @param value * allowed object is * {@link String } * */ public void setArchiveLayoutOID(String value) { this.archiveLayoutOID = value; } }
lgpl-3.0
yodor/sparkbox
lib/templates/admin/FAQItemsListPage.php
923
<?php include_once("templates/admin/BeanListPage.php"); include_once("beans/FAQSectionsBean.php"); include_once("beans/FAQItemsBean.php"); class FAQItemsListPage extends BeanListPage { public function __construct() { parent::__construct(); $sections = new FAQSectionsBean(); $bean = new FAQItemsBean(); $qry = $bean->query(); $qry->select->from.= " fi LEFT JOIN faq_sections fs ON fs.fqsID = fi.fqsID "; $qry->select->fields()->set("fi.fID", "fs.section_name", "fi.question", "fi.answer"); $this->setIterator($qry); $this->setListFields(array("section_name"=>"Section", "question"=>"Question", "answer"=>"Answer")); $this->setBean($bean); } protected function initPage() { parent::initPage(); $menu = array(new MenuItem("Sections", "sections/list.php")); $this->getPage()->setPageMenu($menu); } }
lgpl-3.0
smba/oak
edu.cmu.cs.oak/src/main/scala/edu/cmu/cs/oak/lib/builtin/Print.scala
891
package edu.cmu.cs.oak.lib.builtin import java.nio.file.Path import com.caucho.quercus.expr.Expr import edu.cmu.cs.oak.lib.InterpreterPluginProvider import edu.cmu.cs.oak.core.OakInterpreter import edu.cmu.cs.oak.env.Environment import edu.cmu.cs.oak.lib.InterpreterPlugin import edu.cmu.cs.oak.nodes.DNode import edu.cmu.cs.oak.value.IntValue import edu.cmu.cs.oak.value.OakValue import com.caucho.quercus.Location /** * */ class Print extends InterpreterPlugin { override def getName(): String = "print" override def visit(provider: InterpreterPluginProvider, args: List[OakValue], loc: Location, env: Environment): OakValue = { val interpreter = provider.asInstanceOf[OakInterpreter] /* Assert that the function has been o*/ assert(args.size == 1) val value = args.head env.addOutput( DNode.createDNode(value, loc) ) return IntValue(1) } }
lgpl-3.0
Sinhika/SinhikaSpices
common/sinhika/bark/handlers/IThingHelper.java
518
package sinhika.bark.handlers; public interface IThingHelper { public abstract void init(); // end init public abstract String getName(int index); public abstract String getCapName(int index); public abstract String getTypeName(int index); public abstract int getItemID(int index); public abstract void setItemID(int index, int id); public abstract String getLocalizationTag(int index); public abstract String getTexture(int index); public abstract int size(); }
lgpl-3.0
loftuxab/community-edition-old
projects/repository/source/java/org/alfresco/repo/admin/patch/impl/NoLongerSupportedPatch.java
2016
/* * 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.repo.admin.patch.impl; import org.alfresco.repo.admin.patch.AbstractPatch; import org.alfresco.service.cmr.admin.PatchException; /** * Notifies the user that the patch about to be run is no longer supported and an incremental upgrade * path must be followed. * * @author Derek Hulley * @since 2.1.5 */ public class NoLongerSupportedPatch extends AbstractPatch { private static final String ERR_USE_INCREMENTAL_UPGRADE = "patch.NoLongerSupportedPatch.err.use_incremental_upgrade"; private String lastSupportedVersion; public NoLongerSupportedPatch() { } public void setLastSupportedVersion(String lastSupportedVersion) { this.lastSupportedVersion = lastSupportedVersion; } @Override protected void checkProperties() { super.checkProperties(); checkPropertyNotNull(lastSupportedVersion, "lastSupportedVersion"); } @Override protected String applyInternal() throws Exception { throw new PatchException( ERR_USE_INCREMENTAL_UPGRADE, super.getId(), lastSupportedVersion, lastSupportedVersion); } }
lgpl-3.0
DdiEditor/ddieditor-ui
src/org/ddialliance/ddieditor/ui/view/TreeLabelProvider.java
4630
package org.ddialliance.ddieditor.ui.view; import java.util.List; import org.apache.xmlbeans.XmlObject; import org.ddialliance.ddieditor.model.conceptual.ConceptualElement; import org.ddialliance.ddieditor.model.conceptual.ConceptualType; import org.ddialliance.ddieditor.model.lightxmlobject.CustomType; import org.ddialliance.ddieditor.model.lightxmlobject.LightXmlObjectType; import org.ddialliance.ddieditor.model.resource.DDIResourceType; import org.ddialliance.ddieditor.model.resource.StorageType; import org.ddialliance.ddieditor.persistenceaccess.maintainablelabel.MaintainableLightLabelQueryResult; import org.ddialliance.ddieditor.ui.editor.Editor; import org.ddialliance.ddieditor.ui.util.LanguageUtil; import org.ddialliance.ddieditor.util.LightXmlObjectUtil; import org.ddialliance.ddiftp.util.DDIFtpException; import org.ddialliance.ddiftp.util.Translator; import org.ddialliance.ddiftp.util.log.Log; import org.ddialliance.ddiftp.util.log.LogFactory; import org.ddialliance.ddiftp.util.log.LogType; import org.ddialliance.ddiftp.util.xml.XmlBeansUtil; import org.eclipse.jface.viewers.LabelProvider; /** * Tree Label Provider */ class TreeLabelProvider extends LabelProvider { private static Log log = LogFactory.getLog(LogType.SYSTEM, TreeLabelProvider.class); @Override public String getText(Object element) { // LightXmlObjectType if (element instanceof LightXmlObjectType) { LightXmlObjectType lightXmlObject = (LightXmlObjectType) element; if (lightXmlObject.getElement().equals("Variable")) { StringBuilder result = new StringBuilder(); // name for (CustomType cus : LightXmlObjectUtil.getCustomListbyType( lightXmlObject, "Name")) { result.append(XmlBeansUtil.getTextOnMixedElement(cus)); } // label try { String l = XmlBeansUtil .getTextOnMixedElement((XmlObject) XmlBeansUtil .getDefaultLangElement(lightXmlObject .getLabelList())); if (l != null && !l.equals("")) { result.append(" "); result.append(l); } } catch (Exception e) { Editor.showError(e, getClass().getName()); } if (result.length() == 0) { result.append(lightXmlObject.getElement() + ": " + lightXmlObject.getId()); } return result.toString(); } if (lightXmlObject.getLabelList().size() > 0) { try { Object obj = XmlBeansUtil.getLangElement( LanguageUtil.getDisplayLanguage(), lightXmlObject.getLabelList()); return XmlBeansUtil.getTextOnMixedElement((XmlObject) obj); } catch (DDIFtpException e) { Editor.showError(e, getClass().getName()); } } else { // No label specified - use ID instead: return lightXmlObject.getElement() + ": " + lightXmlObject.getId(); } } // DDIResourceType else if (element instanceof DDIResourceType) { return ((DDIResourceType) element).getOrgName(); } // StorageType else if (element instanceof StorageType) { return ((StorageType) element).getId(); } // ConceptualType else if (element instanceof ConceptualType) { return Translator.trans(((ConceptualType) element).name()); } // ConceptualElement else if (element instanceof ConceptualElement) { List<org.ddialliance.ddieditor.model.lightxmlobject.LabelType> labels = ((ConceptualElement) element) .getValue().getLabelList(); if (!labels.isEmpty()) { return XmlBeansUtil .getTextOnMixedElement(((ConceptualElement) element) .getValue().getLabelList().get(0)); } else { return ((ConceptualElement) element).getValue().getId(); } } // MaintainableLightLabelQueryResult else if (element instanceof MaintainableLightLabelQueryResult) { try { return ((MaintainableLightLabelQueryResult) element) .getTargetLabel(); } catch (DDIFtpException e) { Editor.showError(e, getClass().getName()); } return ""; } // java.util.List else if (element instanceof List<?>) { if (!((List<?>) element).isEmpty()) { Object obj = ((List<?>) element).get(0); // light xml objects if (obj instanceof LightXmlObjectType) { String label = ((LightXmlObjectType) obj).getElement(); return label; } } else { DDIFtpException e = new DDIFtpException("Empty list", new Throwable()); Editor.showError(e, getClass().getName()); } } // guard else { if (log.isWarnEnabled()) { DDIFtpException e = new DDIFtpException(element.getClass() .getName() + "is not supported", new Throwable()); Editor.showError(e, getClass().getName()); } } return new String(); } }
lgpl-3.0
accord-net/java
Catalano.Android.Image/src/Catalano/Imaging/Filters/DifferenceOfGaussian.java
4825
// Catalano Imaging Library // The Catalano Framework // // Copyright © Diego Catalano, 2014 // diego.catalano at live.com // // 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, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // package Catalano.Imaging.Filters; import Catalano.Imaging.FastBitmap; import Catalano.Imaging.IBaseInPlace; /** * Difference of Gaussians is a feature enhancement algorithm that involves the subtraction of one blurred version of an original image from another. * @author Diego Catalano */ public class DifferenceOfGaussian implements IBaseInPlace{ private int windowSize1 = 3, windowSize2 = 5; private double sigma1 = 1.4D, sigma2 = 1.4D; /** * Get first sigma value. * @return Sigma value. */ public double getSigma1() { return sigma1; } /** * Set first sigma value. * @param sigma Sigma value. */ public void setSigma1(double sigma) { this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) ); } /** * Get second sigma value. * @return Sigma value. */ public double getSigma2() { return sigma2; } /** * Set second sigma value. * @param sigma Sigma value. */ public void setSigma2(double sigma) { this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma ) ); } /** * Get first window size. * @return Window size value. */ public int getWindowSize1() { return windowSize1; } /** * Set first window size. * @param size Window size value. */ public void setWindowSize1(int size) { this.windowSize1 = Math.max( 3, Math.min( 21, size | 1 ) ); } /** * Get second window size. * @return Window size value. */ public int getWindowSize2() { return windowSize2; } /** * Set second window size. * @param size Window size value. */ public void setWindowSize2(int size) { this.windowSize2 = Math.max( 3, Math.min( 21, size | 1 ) ); } /** * Initialize a new instance of the DifferenceOfGaussian class. */ public DifferenceOfGaussian() {} /** * Initialize a new instance of the DifferenceOfGaussian class. * @param windowSize1 First window size. * @param windowSize2 Second window size. */ public DifferenceOfGaussian(int windowSize1, int windowSize2) { this.windowSize1 = windowSize1; this.windowSize2 = windowSize2; } /** * Initialize a new instance of the DifferenceOfGaussian class. * @param windowSize1 First window size. * @param windowSize2 Second window size. * @param sigma Sigma value for both images. */ public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma) { this.windowSize1 = windowSize1; this.windowSize2 = windowSize2; this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) ); } /** * Initialize a new instance of the DifferenceOfGaussian class. * @param windowSize1 First window size. * @param windowSize2 Second window size. * @param sigma First sigma value. * @param sigma2 Second sigma value. */ public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma, double sigma2) { this.windowSize1 = windowSize1; this.windowSize2 = windowSize2; this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) ); this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma2 ) ); } @Override public void applyInPlace(FastBitmap fastBitmap) { FastBitmap b = new FastBitmap(fastBitmap); GaussianBlur gauss = new GaussianBlur(sigma1, windowSize1); gauss.applyInPlace(b); gauss.setSize(windowSize2); gauss.setSigma(sigma2); gauss.applyInPlace(fastBitmap); Subtract sub = new Subtract(b); sub.applyInPlace(fastBitmap); b.recycle(); } }
lgpl-3.0
SonarSource/sonarqube
server/sonar-web/src/main/js/apps/background-tasks/components/__tests__/StatPendingTime-test.tsx
1747
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { shallow } from 'enzyme'; import * as React from 'react'; import StatPendingTime, { Props } from '../StatPendingTime'; it('should render correctly', () => { expect(shallowRender()).toMatchSnapshot(); }); it('should not render', () => { expect(shallowRender({ pendingCount: undefined }).type()).toBeNull(); expect(shallowRender({ pendingCount: 0 }).type()).toBeNull(); expect(shallowRender({ pendingTime: undefined }).type()).toBeNull(); }); it('should not render when pending time is too small', () => { expect( shallowRender({ pendingTime: 0 }) .find('.emphasised-measure') .exists() ).toBe(false); expect( shallowRender({ pendingTime: 900 }) .find('.emphasised-measure') .exists() ).toBe(false); }); function shallowRender(props: Partial<Props> = {}) { return shallow(<StatPendingTime pendingCount={5} pendingTime={15420} {...props} />); }
lgpl-3.0
mariajosefrancolugo/osp
osp/media/js/base.js
1553
var default_window_options = { autoOpen: false, width: 750, height: 450, modal: true, resizable: false }; function applyNotificationStyles() { $('.error').each(function() { $(this).addClass('ui-state-error ui-corner-all'); $(this).prepend('<span class="ui-icon ui-icon-alert"></span>'); }); $('.notification').each(function() { $(this).addClass('ui-state-highlight ui-corner-all'); $(this).prepend('<span class="ui-icon ui-icon-info"></span>'); }); } $(function() { // Hard-coded paths aren't great... Maybe re-work this in the future var divider = "url('" + media_url + "img/navigation_divider.png')"; $('#navigation ul.menu li:has(ul.submenu)').hover(function() { $(this).addClass('has-submenu'); $(this).children('a.menu-link').css('background-image', 'none'); $(this).prev('li').children('a.menu-link').css('background-image', 'none'); $(this).children('ul').show(); }, function() { $(this).removeClass('has-submenu'); $(this).children('a.menu-link').css('background-image', divider); $(this).prev('li').children('a.menu-link').css('background-image', divider); $(this).children('ul').hide(); }); $('#navigation ul.submenu a').click(function() { $(this).parents('ul.submenu').hide(); }); // Style form buttons $('input[type=button], input[type=submit], input[type=reset]').button(); // Style error and notification messages applyNotificationStyles(); });
lgpl-3.0
robeio/robe
robe-admin/src/test/java/io/robe/admin/hibernate/entity/MenuTest.java
1192
package io.robe.admin.hibernate.entity; import org.junit.FixMethodOrder; import org.junit.Test; import static junit.framework.TestCase.assertEquals; /** * Created by recep on 30/09/16. */ @FixMethodOrder public class MenuTest { Menu entity = new Menu(); @Test public void getText() throws Exception { entity.setText("Text"); assertEquals("Text", entity.getText()); } @Test public void getPath() throws Exception { entity.setPath("Path"); assertEquals("Path", entity.getPath()); } @Test public void getIndex() throws Exception { entity.setIndex(3); assertEquals(3, entity.getIndex()); } @Test public void getParentOid() throws Exception { entity.setParentOid("12345678901234567890123456789012"); assertEquals("12345678901234567890123456789012", entity.getParentOid()); } @Test public void getModule() throws Exception { entity.setModule("Module"); assertEquals("Module", entity.getModule()); } @Test public void getIcon() throws Exception { entity.setIcon("Icon"); assertEquals("Icon", entity.getIcon()); } }
lgpl-3.0
SergeR/webasyst-framework
wa-apps/photos/api/v1/photos.photo.rotate.method.php
978
<?php /** * @package wa-apps/photos/api/v1 */ class photosPhotoRotateMethod extends waAPIMethod { protected $method = 'POST'; public function execute() { $id = $this->post('id', true); $photo_model = new photosPhotoModel(); $photo = $photo_model->getById($id); $clockwise = waRequest::post('clockwise', null, 1); if (!is_numeric($clockwise)) { $clockwise = strtolower(trim($clockwise)); $clockwise = $clockwise === 'false' ? 0 : 1; } if ($photo) { try { $photo_model = new photosPhotoModel(); $photo_model->rotate($id, $clockwise); } catch (waException $e) { throw new waAPIException('server_error', $e->getMessage(), 500); } $this->response = true; } else { throw new waAPIException('invalid_request', 'Photo not found', 404); } } }
lgpl-3.0
metalpen1984/SciTool_Py
GRIDINFORMER.py
66239
import math,re,sys,os,time import random as RD import time try: import netCDF4 as NC except: print("You no install netCDF4 for python") print("So I do not import netCDF4") try: import numpy as NP except: print("You no install numpy") print("Do not import numpy") class GRIDINFORMATER: """ This object is the information of the input gridcells/array/map. Using .add_an_element to add an element/gridcell .add_an_geo_element to add an element/gridcell .create_resample_lat_lon to create a new map of lat and lon for resampling .create_resample_map to create resample map as ARR_RESAMPLE_MAP .create_reference_map to create ARR_REFERENCE_MAP to resample target map. .export_reference_map to export ARR_REFERENCE_MAP into netCDF4 format """ STR_VALUE_INIT = "None" NUM_VALUE_INIT = -9999.9 NUM_NULL = float("NaN") ARR_RESAMPLE_X_LIM = [] ARR_RESAMPLE_Y_LIM = [] # FROM WRF: module_cam_shr_const_mod.f90 NUM_CONST_EARTH_R = 6.37122E6 NUM_CONST_PI = 3.14159265358979323846 def __init__(self, name="GRID", ARR_LAT=[], ARR_LON=[], NUM_NT=1, DIMENSIONS=2 ): self.STR_NAME = name self.NUM_DIMENSIONS = DIMENSIONS self.NUM_LAST_INDEX = -1 self.ARR_GRID = [] self.NUM_NT = NUM_NT self.ARR_LAT = ARR_LAT self.ARR_LON = ARR_LON self.ARR_RESAMPLE_MAP_PARA = { "EDGE": {"N" :-999, "S":-999, "E":-999, "W":-999 } } if len(ARR_LAT) != 0 and len(ARR_LON) != 0: NUM_ARR_NY_T1 = len(ARR_LAT) NUM_ARR_NY_T2 = len(ARR_LON) Y_T2 = len(ARR_LON) NUM_ARR_NX_T1 = len(ARR_LAT[0]) NUM_ARR_NX_T2 = len(ARR_LON[0]) self.NUM_NX = NUM_ARR_NX_T1 self.NUM_NY = NUM_ARR_NY_T1 if NUM_ARR_NY_T1 - NUM_ARR_NY_T2 + NUM_ARR_NX_T1 - NUM_ARR_NX_T2 != 0: print("The gridcell of LAT is {0:d}&{1:d}, and LON is {2:d}&{3:d} are not match"\ .format(NUM_ARR_NY_T1,NUM_ARR_NY_T2,NUM_ARR_NX_T1,NUM_ARR_NX_T2)) def index_map(self, ARR_IN=[], NUM_IN_NX=0, NUM_IN_NY=0): if len(ARR_IN) == 0: self.INDEX_MAP = [[ self.NUM_NULL for i in range(self.NUM_NX)] for j in range(self.NUM_NY)] NUM_ALL_INDEX = len(self.ARR_GRID) for n in range(NUM_ALL_INDEX): self.INDEX_MAP[self.ARR_GRID[n]["INDEX_J"]][self.ARR_GRID[n]["INDEX_I"]] =\ self.ARR_GRID[n]["INDEX"] else: MAP_INDEX = [[ self.NUM_NULL for i in range(NUM_IN_NX)] for j in range(NUM_IN_NY)] NUM_ALL_INDEX = len(ARR_IN) for n in range(NUM_ALL_INDEX): MAP_INDEX[ARR_IN[n]["INDEX_J"]][ARR_IN[n]["INDEX_I"]] = ARR_IN[n]["INDEX"] return MAP_INDEX def add_an_element(self, ARR_GRID, NUM_INDEX=0, STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ): """ Adding an element to an empty array """ OBJ_ELEMENT = {"INDEX" : NUM_INDEX, \ STR_VALUE : NUM_VALUE} ARR_GRID.append(OBJ_ELEMENT) def add_an_geo_element(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, \ NUM_NX = 0, NUM_NY = 0, NUM_NT=0, \ ARR_VALUE_STR=[], ARR_VALUE_NUM=[] ): """ Adding an geological element to an empty array The information for lat and lon of center, edge, and vertex will be stored for further used. """ NUM_NVAR = len(ARR_VALUE_STR) if NUM_NX == 0 or NUM_NY == 0: NUM_NX = self.NUM_NX NUM_NY = self.NUM_NY if NUM_NT == 0: NUM_NT = self.NUM_NT NUM_CENTER_LON = self.ARR_LON[NUM_J][NUM_I] NUM_CENTER_LAT = self.ARR_LAT[NUM_J][NUM_I] if NUM_I == 0: NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5 NUM_EW_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5 elif NUM_I == NUM_NX - 1: NUM_WE_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5 NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5 else: NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5 NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5 if NUM_J == 0: NUM_SN_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5 NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5 elif NUM_J == NUM_NY - 1: NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5 NUM_NS_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5 else: NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5 NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5 ARR_NE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_NS_LAT ] ARR_NW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_NS_LAT ] ARR_SE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_SN_LAT ] ARR_SW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_SN_LAT ] if NUM_INDEX == -999: NUM_INDEX = self.NUM_LAST_INDEX +1 self.NUM_LAST_INDEX += 1 OBJ_ELEMENT = {"INDEX" : NUM_INDEX,\ "INDEX_I" : NUM_I,\ "INDEX_J" : NUM_J,\ "CENTER" : {"LAT" : NUM_CENTER_LAT, "LON" : NUM_CENTER_LON},\ "VERTEX" : {"NE": ARR_NE, "SE": ARR_SE, "SW": ARR_SW, "NW": ARR_NW},\ "EDGE" : {"N": NUM_CENTER_LAT + NUM_NS_LAT,"S": NUM_CENTER_LAT + NUM_SN_LAT,\ "E": NUM_CENTER_LON + NUM_EW_LON,"W": NUM_CENTER_LON + NUM_WE_LON}} if len(ARR_VALUE_STR) > 0: for I, VAR in enumerate(ARR_VALUE_STR): OBJ_ELEMENT[VAR] = [{ "VALUE" : 0.0} for t in range(NUM_NT) ] if len(ARR_VALUE_NUM) == NUM_NVAR: for T in range(NUM_NT): OBJ_ELEMENT[VAR][T]["VALUE"] = ARR_VALUE_NUM[I][T] ARR_GRID.append(OBJ_ELEMENT) def add_an_geo_variable(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, NUM_NT=0,\ STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ): if NUM_INDEX == -999: NUM_INDEX = self.INDEX_MAP[NUM_J][NUM_I] if NUM_NT == 0: NUM_NT = self.NUM_NT ARR_GRID[NUM_INDEX][STR_VALUE] = {{"VALUE": NUM_VALUE } for t in range(NUM_NT)} def create_resample_lat_lon(self, ARR_RANGE_LAT=[0,0],NUM_EDGE_LAT=0,\ ARR_RANGE_LON=[0,0],NUM_EDGE_LON=0 ): self.NUM_GRIDS_LON = round((ARR_RANGE_LON[1] - ARR_RANGE_LON[0])/NUM_EDGE_LON) self.NUM_GRIDS_LAT = round((ARR_RANGE_LAT[1] - ARR_RANGE_LAT[0])/NUM_EDGE_LAT) self.ARR_LAT = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ] self.ARR_LON = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ] for j in range(self.NUM_GRIDS_LAT): for i in range(self.NUM_GRIDS_LON): NUM_LAT = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j NUM_LON = ARR_RANGE_LON[0] + NUM_EDGE_LON * i self.ARR_LON[j][i] = ARR_RANGE_LON[0] + NUM_EDGE_LON * i self.ARR_LAT[j][i] = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j def create_reference_map(self, MAP_TARGET, MAP_RESAMPLE, STR_TYPE="FIX", NUM_SHIFT=0.001, IF_PB=False): """Must input with OBJ_REFERENCE WARNING: The edge of gridcells may not be included due to the unfinished algorithm """ self.ARR_REFERENCE_MAP = [] if STR_TYPE=="GRIDBYGEO": NUM_OBJ_G_LEN = len(MAP_TARGET) for OBJ_G in MAP_TARGET: NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]] for OBJ_R in MAP_RESAMPLE: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"]) NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\ (OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"]) if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0: OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\ "CENTER" : OBJ_G["CENTER"],\ "INDEX_REF" : OBJ_R["INDEX"],\ "INDEX_REF_I" : OBJ_R["INDEX_I"],\ "INDEX_REF_J" : OBJ_R["INDEX_J"],\ "CENTER_REF" : OBJ_R["CENTER"],\ } self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT) break if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP") elif STR_TYPE=="FIX": NUM_OBJ_G_LEN = len(MAP_TARGET) for OBJ_G in MAP_TARGET: NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]] if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] == -999: NUM_CHK_EW_IN = -1 else: NUM_CHK_EW_IN = (NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] ) * ( NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] ) if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] == -999: NUM_CHK_SN_IN = -1 else: NUM_CHK_SN_IN = (NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] ) * ( NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] ) if NUM_CHK_EW_IN < 0 and NUM_CHK_SN_IN < 0: for OBJ_R in MAP_RESAMPLE: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"]) NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\ (OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"]) if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\ (OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0: OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\ "INDEX_I" : OBJ_G["INDEX_I"],\ "INDEX_J" : OBJ_G["INDEX_J"],\ "CENTER" : OBJ_G["CENTER"],\ "INDEX_REF" : OBJ_R["INDEX"],\ "INDEX_REF_I" : OBJ_R["INDEX_I"],\ "INDEX_REF_J" : OBJ_R["INDEX_J"],\ "CENTER_REF" : OBJ_R["CENTER"],\ } self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT) break if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP") def export_grid_map(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\ ARR_VAR_ITEM=["MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\ NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ): TIME_NOW = time.gmtime() STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday) STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec) if NUM_NX==0: NUM_NX = self.NUM_NX if NUM_NY==0: NUM_NY = self.NUM_NY if NUM_NT==0: NUM_NT = self.NUM_NT if STR_TYPE == "netCDF4": NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4") # CREATE ATTRIBUTEs: NCDF4_DATA.description = \ "The grid information in netCDF4" NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW) # CREATE DIMENSIONs: NCDF4_DATA.createDimension("Y" , NUM_NY ) NCDF4_DATA.createDimension("X" , NUM_NX ) NCDF4_DATA.createDimension("Time" , NUM_NT ) NCDF4_DATA.createDimension("Values", None ) # CREATE BASIC VARIABLES: NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X")) NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X")) NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X")) NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X")) NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X")) # CREATE GROUP for Variables: for VAR in ARR_VAR_STR: NCDF4_DATA.createGroup(VAR) for ITEM in ARR_VAR_ITEM: if ITEM == "VALUE" : NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values")) else: NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X")) # WRITE IN VARIABLE for V in ["INDEX", "INDEX_J", "INDEX_I"]: map_in = self.convert_grid2map(ARR_GRID_IN, V, NX=NUM_NX, NY=NUM_NY, NC_TYPE="INT") for n in range(len(map_in)): NCDF4_DATA.variables[V][n] = map_in[n] for V1 in ["CENTER"]: for V2 in ["LON", "LAT"]: map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NC_TYPE="FLOAT") for n in range(len(map_in)): NCDF4_DATA.variables["{0:s}_{1:s}".format(V1, V2)][n] = map_in[n] for V1 in ARR_VAR_STR: for V2 in ARR_VAR_ITEM: map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NT=NUM_NT) for n in range(len(map_in)): NCDF4_DATA.groups[V1].variables[V2][n] = map_in[n] NCDF4_DATA.close() def export_grid(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\ ARR_VAR_ITEM=["VALUE", "MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\ NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ): TIME_NOW = time.gmtime() STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday) STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec) if NUM_NX==0: NUM_NX = self.NUM_NX if NUM_NY==0: NUM_NY = self.NUM_NY if NUM_NT==0: NUM_NT = self.NUM_NT if STR_TYPE == "netCDF4": NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4") # CREATE ATTRIBUTEs: NCDF4_DATA.description = \ "The grid information in netCDF4" NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW) # CREATE DIMENSIONs: NCDF4_DATA.createDimension("Y" , NUM_NY ) NCDF4_DATA.createDimension("X" , NUM_NX ) NCDF4_DATA.createDimension("Time" , NUM_NT ) NCDF4_DATA.createDimension("Values", None ) # CREATE BASIC VARIABLES: INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X")) INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X")) INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X")) CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X")) CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X")) # CREATE GROUP for Variables: for VAR in ARR_VAR_STR: NCDF4_DATA.createGroup(VAR) for ITEM in ARR_VAR_ITEM: if ITEM == "VALUE" : NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values")) else: NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X")) # WRITE IN VARIABLE for IND, OBJ in enumerate(ARR_GRID_IN): j = OBJ["INDEX_J"] i = OBJ["INDEX_I"] INDEX [j,i] = OBJ["INDEX"] INDEX_J [j,i] = OBJ["INDEX_J"] INDEX_I [j,i] = OBJ["INDEX_I"] CENTER_LON [j,i] = OBJ["CENTER"]["LON"] CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"] for VAR in ARR_VAR_STR: for ITEM in ARR_VAR_ITEM: for T in range(NUM_NT): NCDF4_DATA.groups[VAR].variables[ITEM][T,j,i] = OBJ[VAR][T][ITEM] if IF_PB: TOOLS.progress_bar((IND+1)/(NUM_NX*NUM_NY), STR_DES="WRITING PROGRESS") NCDF4_DATA.close() def export_reference_map(self, STR_DIR, STR_FILENAME, STR_TYPE="netCDF4", IF_PB=False, IF_PARALLEL=False ): TIME_NOW = time.gmtime() self.STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday) self.STR_TIME_NOW = "{0:02d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec) STR_INPUT_FILENAME = "{0:s}/{1:s}".format(STR_DIR, STR_FILENAME) if STR_TYPE == "netCDF4": IF_FILECHK = os.path.exists(STR_INPUT_FILENAME) if IF_FILECHK: NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'a', format="NETCDF4", parallel=IF_PARALLEL) INDEX = NCDF4_DATA.variables["INDEX" ] INDEX_J = NCDF4_DATA.variables["INDEX_J" ] INDEX_I = NCDF4_DATA.variables["INDEX_I" ] CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ] CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ] INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ] INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ] INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ] CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ] CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ] else: NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'w', format="NETCDF4", parallel=IF_PARALLEL) # CREATE ATTRIBUTEs: NCDF4_DATA.description = \ "The netCDF4 version of reference map which contains grid information for resampling" NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(self.STR_DATE_NOW, self.STR_TIME_NOW) # CREATE DIMENSIONs: NCDF4_DATA.createDimension("Y",self.NUM_NY) NCDF4_DATA.createDimension("X",self.NUM_NX) # CREATE_VARIABLES: INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X")) INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X")) INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X")) CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X")) CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X")) INDEX_REF = NCDF4_DATA.createVariable("INDEX_REF", "i4", ("Y", "X")) INDEX_REF_J = NCDF4_DATA.createVariable("INDEX_REF_J", "i4", ("Y", "X")) INDEX_REF_I = NCDF4_DATA.createVariable("INDEX_REF_I", "i4", ("Y", "X")) CENTER_REF_LON = NCDF4_DATA.createVariable("CENTER_REF_LON", "f8", ("Y", "X")) CENTER_REF_LAT = NCDF4_DATA.createVariable("CENTER_REF_LAT", "f8", ("Y", "X")) NUM_TOTAL_OBJ = len(self.ARR_REFERENCE_MAP) NUM_MAX_I = self.NUM_NX for OBJ in self.ARR_REFERENCE_MAP: j = OBJ["INDEX_J"] i = OBJ["INDEX_I"] INDEX[j,i] = OBJ["INDEX"] INDEX_J[j,i] = OBJ["INDEX_J"] INDEX_I[j,i] = OBJ["INDEX_I"] INDEX_REF[j,i] = OBJ["INDEX_REF"] INDEX_REF_J[j,i] = OBJ["INDEX_REF_J"] INDEX_REF_I[j,i] = OBJ["INDEX_REF_I"] CENTER_LON [j,i] = OBJ["CENTER"]["LON"] CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"] CENTER_REF_LON [j,i] = OBJ["CENTER_REF"]["LON"] CENTER_REF_LAT [j,i] = OBJ["CENTER_REF"]["LAT"] if IF_PB: TOOLS.progress_bar((i+j*NUM_MAX_I)/float(NUM_TOTAL_OBJ), STR_DES="Exporting") NCDF4_DATA.close() def import_reference_map(self, STR_DIR, STR_FILENAME, ARR_X_RANGE=[], ARR_Y_RANGE=[], STR_TYPE="netCDF4", IF_PB=False): self.ARR_REFERENCE_MAP = [] self.NUM_MAX_INDEX_RS = 0 self.NUM_MIN_INDEX_RS = 999 if len(ARR_X_RANGE) != 0: self.I_MIN = ARR_X_RANGE[0] self.I_MAX = ARR_X_RANGE[1] else: self.I_MIN = 0 self.I_MAX = self.REFERENCE_MAP_NX if len(ARR_Y_RANGE) != 0: self.J_MIN = ARR_Y_RANGE[0] self.J_MAX = ARR_Y_RANGE[1] else: self.J_MIN = 0 self.J_MAX = self.REFERENCE_MAP_NY if STR_TYPE == "netCDF4": NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'r', format="NETCDF4") # READ DIMENSIONs: self.REFERENCE_MAP_NY = NCDF4_DATA.dimensions["Y"].size self.REFERENCE_MAP_NX = NCDF4_DATA.dimensions["X"].size # CREATE_VARIABLES: INDEX = NCDF4_DATA.variables["INDEX" ] INDEX_J = NCDF4_DATA.variables["INDEX_J" ] INDEX_I = NCDF4_DATA.variables["INDEX_I" ] CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ] CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ] INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ] INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ] INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ] CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ] CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ] for j in range(self.J_MIN, self.J_MAX): for i in range(self.I_MIN, self.I_MAX): OBJ_ELEMENT = {"INDEX" : 0 ,\ "INDEX_I" : 0 ,\ "INDEX_J" : 0 ,\ "CENTER" : {"LAT": 0.0, "LON": 0.0} ,\ "INDEX_REF" : 0 ,\ "INDEX_REF_I" : 0 ,\ "INDEX_REF_J" : 0 ,\ "CENTER_REF" : {"LAT": 0.0, "LON": 0.0} } if INDEX [j][i] != None: OBJ_ELEMENT["INDEX"] = INDEX [j][i] OBJ_ELEMENT["INDEX_J"] = INDEX_J [j][i] OBJ_ELEMENT["INDEX_I"] = INDEX_I [j][i] OBJ_ELEMENT["INDEX_REF"] = INDEX_REF [j][i] OBJ_ELEMENT["INDEX_REF_J"] = INDEX_REF_J [j][i] OBJ_ELEMENT["INDEX_REF_I"] = INDEX_REF_I [j][i] OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i] OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i] OBJ_ELEMENT["CENTER_REF"]["LAT"] = CENTER_REF_LAT[j][i] OBJ_ELEMENT["CENTER_REF"]["LON"] = CENTER_REF_LON[j][i] else: OBJ_ELEMENT["INDEX"] = INDEX [j][i] OBJ_ELEMENT["INDEX_I"] = INDEX_J [j][i] OBJ_ELEMENT["INDEX_J"] = INDEX_I [j][i] OBJ_ELEMENT["INDEX_REF"] = -999 OBJ_ELEMENT["INDEX_REF_J"] = -999 OBJ_ELEMENT["INDEX_REF_I"] = -999 OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i] OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i] OBJ_ELEMENT["CENTER_REF"]["LAT"] = -999 OBJ_ELEMENT["CENTER_REF"]["LON"] = -999 self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT) self.NUM_MIN_INDEX_RS = min(self.NUM_MIN_INDEX_RS, INDEX_REF[j][i]) self.NUM_MAX_INDEX_RS = max(self.NUM_MAX_INDEX_RS, INDEX_REF[j][i]) if IF_PB: TOOLS.progress_bar((j - self.J_MIN + 1)/float(self.J_MAX - self.J_MIN), STR_DES="IMPORTING") if self.NUM_MIN_INDEX_RS == 0: self.NUM_MAX_RS = self.NUM_MAX_INDEX_RS + 1 NCDF4_DATA.close() def create_resample_map(self, ARR_REFERENCE_MAP=[], ARR_VARIABLES=["Value"], ARR_GRID_IN=[],\ IF_PB=False, NUM_NT=0, NUM_NX=0, NUM_NY=0, NUM_NULL=-9999.999): if NUM_NT == 0: NUM_NT = self.NUM_NT if NUM_NX == 0: NUM_NX = self.NUM_NX if NUM_NY == 0: NUM_NY = self.NUM_NY if len(ARR_REFERENCE_MAP) == 0: self.ARR_RESAMPLE_OUT = [] self.ARR_RESAMPLE_OUT_PARA = {"EDGE": {"N": 0.0,"S": 0.0,"E": 0.0,"W": 0.0}} NUM_END_J = self.NUM_GRIDS_LAT - 1 NUM_END_I = self.NUM_GRIDS_LON - 1 ARR_EMPTY = [float("NaN") for n in range(self.NUM_NT)] for J in range(self.NUM_GRIDS_LAT): for I in range(self.NUM_GRIDS_LON): NUM_IND = I + J * self.NUM_GRIDS_LON self.add_an_geo_element(self.ARR_RESAMPLE_OUT, NUM_INDEX=NUM_IND, NUM_J=J, NUM_I=I, \ NUM_NX= self.NUM_GRIDS_LON, NUM_NY= self.NUM_GRIDS_LAT,\ ARR_VALUE_STR=ARR_VARIABLES, NUM_NT=NUM_NT) self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] = max( self.ARR_LAT[NUM_END_J][0], self.ARR_LAT[NUM_END_J][NUM_END_I] ) self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] = min( self.ARR_LAT[0][0], self.ARR_LAT[0][NUM_END_I] ) self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] = min( self.ARR_LAT[0][0], self.ARR_LAT[NUM_END_J][0] ) self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] = max( self.ARR_LAT[0][NUM_END_I], self.ARR_LAT[NUM_END_J][NUM_END_I] ) self.NUM_MAX_INDEX_RS = NUM_IND else: if ARR_GRID_IN == []: ARR_GRID_IN = self.ARR_GRID self.ARR_RESAMPLE_OUT = [ {} for n in range(NUM_NX * NUM_NY)] for IND in range(len(self.ARR_RESAMPLE_OUT)): for VAR in ARR_VARIABLES: self.ARR_RESAMPLE_OUT[IND][VAR] = [{"VALUE" : []} for T in range(NUM_NT) ] #for IND in range(len(ARR_REFERENCE_MAP)): for IND in range(len(ARR_GRID_IN)): R_IND = ARR_REFERENCE_MAP[IND]["INDEX_REF"] R_J = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"] R_I = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"] R_IND_FIX = TOOLS.fix_ind(R_IND, R_J, R_I, ARR_XRANGE=self.ARR_RESAMPLE_LIM_X, ARR_YRANGE=self.ARR_RESAMPLE_LIM_Y, NX=NUM_NX, NY=NUM_NY) if R_IND != None: for VAR in ARR_VARIABLES: for T in range(NUM_NT): #print("R_IND:{0:d}, T:{1:d}, IND:{2:d} ".format(R_IND, T, IND)) NUM_VAL_IN = ARR_GRID_IN[IND][VAR][T]["VALUE"] self.ARR_RESAMPLE_OUT[R_IND][VAR][T]["VALUE"].append(NUM_VAL_IN) self.ARR_RESAMPLE_OUT[R_IND]["INDEX"] = ARR_REFERENCE_MAP[IND]["INDEX_REF"] self.ARR_RESAMPLE_OUT[R_IND]["INDEX_J"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"] self.ARR_RESAMPLE_OUT[R_IND]["INDEX_I"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"] self.ARR_RESAMPLE_OUT[R_IND]["CENTER"] = {"LAT": 0.0, "LON": 0.0 } self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LAT"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LAT"] self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LON"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LON"] if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [len(ARR_GRID_IN)]), STR_DES="RESAMPLING PROGRESS") def cal_resample_map(self, ARR_VARIABLES, ARR_GRID_IN=[], NUM_NT=0, IF_PB=False, \ DIC_PERCENTILE={ "P05": 0.05, "P10": 0.1, "P25": 0.25, "P75": 0.75, "P90": 0.90, "P95": 0.95}, NUM_NULL=-9999.999): if NUM_NT == 0: NUM_NT = self.NUM_NT NUM_RS_OUT_LEN = len(self.ARR_RESAMPLE_OUT) for IND in range(NUM_RS_OUT_LEN): for VAR in ARR_VARIABLES: for T in range(NUM_NT): ARR_IN = self.ARR_RESAMPLE_OUT[IND][VAR][T]["VALUE"] if len(ARR_IN) > 0: ARR_IN.sort() NUM_ARR_LEN = len(ARR_IN) NUM_ARR_MEAN = sum(ARR_IN) / float(NUM_ARR_LEN) NUM_ARR_S2SUM = 0 if math.fmod(NUM_ARR_LEN,2) == 1: NUM_MPOS = [int((NUM_ARR_LEN-1)/2.0), int((NUM_ARR_LEN-1)/2.0)] else: NUM_MPOS = [int(NUM_ARR_LEN/2.0) , int(NUM_ARR_LEN/2.0 -1) ] self.ARR_RESAMPLE_OUT[IND][VAR][T]["MIN"] = min(ARR_IN) self.ARR_RESAMPLE_OUT[IND][VAR][T]["MAX"] = max(ARR_IN) self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEAN"] = NUM_ARR_MEAN self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEDIAN"] = ARR_IN[NUM_MPOS[0]] *0.5 + ARR_IN[NUM_MPOS[1]] *0.5 for STVA in DIC_PERCENTILE: self.ARR_RESAMPLE_OUT[IND][VAR][T][STVA] = ARR_IN[ round(NUM_ARR_LEN * DIC_PERCENTILE[STVA])-1] for VAL in ARR_IN: NUM_ARR_S2SUM += (VAL - NUM_ARR_MEAN)**2 self.ARR_RESAMPLE_OUT[IND][VAR][T]["STD"] = (NUM_ARR_S2SUM / max(1, NUM_ARR_LEN-1))**0.5 if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [NUM_RS_OUT_LEN]), STR_DES="RESAMPLING CALCULATION") def convert_grid2map(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE="", NX=0, NY=0, NT=0, IF_PB=False, NC_TYPE=""): if NC_TYPE == "INT": if NT == 0: ARR_OUT = NP.empty([NY, NX], dtype=NP.int8) else: ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.int8) elif NC_TYPE == "FLOAT": if NT == 0: ARR_OUT = NP.empty([NY, NX], dtype=NP.float64) else: ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.float64) else: if NT == 0: ARR_OUT = [[ self.NUM_NULL for i in range(NX)] for j in range(NY) ] else: ARR_OUT = [[[ self.NUM_NULL for i in range(NX)] for j in range(NY) ] for t in range(NT)] if STR_VAR_TYPE == "": for I, GRID in enumerate(ARR_GRID_IN): if GRID["INDEX"] != -999: if NT == 0: #print(GRID["INDEX_J"], GRID["INDEX_I"], GRID[STR_VAR]) ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR] else: for T in range(NT): ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T] if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN)))) else: for I, GRID in enumerate(ARR_GRID_IN): if GRID["INDEX"] != -999: if NT == 0: ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][STR_VAR_TYPE] else: for T in range(NT): ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T][STR_VAR_TYPE] if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN)))) return ARR_OUT def mask_grid(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE, NUM_NT=0, STR_MASK="MASK",\ ARR_NUM_DTM=[0,1,2], ARR_NUM_DTM_RANGE=[0,1]): if NUM_NT == 0: NUM_NT= self.NUM_NT for IND, GRID in enumerate(ARR_GRID_IN): for T in range(NUM_NT): NUM_DTM = GEO_TOOLS.mask_dtm(GRID[STR_VAR][T][STR_VAR_TYPE], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE) ARR_GRID_IN[IND][STR_VAR][T][STR_MASK] = NUM_DTM class MATH_TOOLS: """ Some math tools that help us to calculate. gau_kde: kernel density estimator by Gaussian Function standard_dev: The Standard deviation """ def GaussJordanEli(arr_in): num_ydim = len(arr_in) num_xdim = len(arr_in[0]) arr_out = arr_in if num_ydim -num_xdim == 0 or num_xdim - num_ydim == 1: arr_i = NP.array([[0.0 for j in range(num_ydim)] for i in range(num_ydim)]) for ny in range(num_ydim): arr_i[ny][ny] = 1.0 #print(arr_i) for nx in range(num_xdim): for ny in range(nx+1, num_ydim): arr_i [ny] = arr_i [ny] - arr_i [nx] * arr_out[ny][nx] / float(arr_out[nx][nx]) arr_out[ny] = arr_out[ny] - arr_out[nx] * arr_out[ny][nx] / float(arr_out[nx][nx]) if num_xdim - num_ydim == 1: for nx in range(num_xdim-1,-1,-1): for ny in range(num_ydim-1,nx, -1): print(nx,ny) arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny]) arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny]) else: for nx in range(num_xdim,-1,-1): for ny in range(num_ydim-1, nx, -1): print(nx,ny) arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny]) arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny]) if num_xdim - num_ydim == 1: arr_sol = [0.0 for n in range(num_ydim)] for ny in range(num_ydim): arr_sol[ny] = arr_out[ny][num_xdim-1]/arr_out[ny][ny] return arr_out, arr_i, arr_sol else: return arr_out, arr_i else: print("Y dim: {0:d}, X dim: {1:d}: can not apply Gaussian-Jordan".format(num_ydim, num_xdim)) return [0] def finding_XM_LSM(arr_in1, arr_in2, m=2): # Finding the by least square method arr_out=[[0.0 for i in range(m+2)] for j in range(m+1)] arr_x_power_m = [0.0 for i in range(m+m+1)] arr_xy_power_m = [0.0 for i in range(m+1)] for n in range(len(arr_x_power_m)): for x in range(len(arr_in1)): arr_x_power_m[n] += arr_in1[x] ** n for n in range(len(arr_xy_power_m)): for x in range(len(arr_in1)): arr_xy_power_m[n] += arr_in1[x] ** n * arr_in2[x] for j in range(m+1): for i in range(j,j+m+1): arr_out[j][i-j] = arr_x_power_m[i] arr_out[j][m+1] = arr_xy_power_m[j] return arr_out def cal_modelperform (arr_obs , arr_sim , num_empty=-999.999): # Based on Vazquez et al. 2002 (Hydrol. Process.) num_arr = len(arr_obs) num_n_total = num_arr num_sum = 0 num_obs_sum = 0 for n in range( num_arr ): if math.isnan(arr_obs[n]) or arr_obs[n] == num_empty: num_n_total += -1 else: num_sum = num_sum + ( arr_sim[n] - arr_obs[n] ) ** 2 num_obs_sum = num_obs_sum + arr_obs[n] if num_n_total == 0 or num_obs_sum == 0: RRMSE = -999.999 RMSE = -999.999 obs_avg = -999.999 else: RRMSE = ( num_sum / num_n_total ) ** 0.5 * ( num_n_total / num_obs_sum ) RMSE = ( num_sum / num_n_total ) ** 0.5 obs_avg = num_obs_sum / num_n_total num_n_total = num_arr oo_sum = 0 po_sum = 0 for nn in range( num_arr ): if math.isnan(arr_obs[nn]) or arr_obs[nn] == num_empty: num_n_total = num_n_total - 1 else: oo_sum = oo_sum + ( arr_obs[nn] - obs_avg ) ** 2 po_sum = po_sum + ( arr_sim[nn] - arr_obs[nn] ) ** 2 if num_n_total == 0 or oo_sum * po_sum == 0: EF = -999.999 CD = -999.999 else: EF = ( oo_sum - po_sum ) / oo_sum CD = oo_sum / po_sum return RRMSE,EF,CD,RMSE, num_arr def cal_kappa(ARR_IN, NUM_n=0, NUM_N=0, NUM_k=0): """ Fleiss' kappa Mustt input with ARR_IN in the following format: ARR_IN = [ [ NUM for k in range(catalogue)] for N in range(Subjects)] Additional parameters: NUM_n is the number of raters (e.g. sim and obs results) Additional parameters: NUM_N is the number of subjects (e.g the outputs Additional parameters: NUM_k is the number of catalogue (e.g. results ) """ if NUM_N == 0: NUM_N = len(ARR_IN) if NUM_n == 0: NUM_n = sum(ARR_IN[0]) if NUM_k == 0: NUM_k = len(ARR_IN[0]) ARR_p_out = [ 0 for n in range(NUM_k)] ARR_P_OUT = [ 0 for n in range(NUM_N)] for N in range(NUM_N): for k in range(NUM_k): ARR_p_out[k] += ARR_IN[N][k] ARR_P_OUT[N] += ARR_IN[N][k] ** 2 ARR_P_OUT[N] -= NUM_n ARR_P_OUT[N] = ARR_P_OUT[N] * (1./(NUM_n *(NUM_n - 1))) for k in range(NUM_k): ARR_p_out[k] = ARR_p_out[k] / (NUM_N * NUM_n) NUM_P_BAR = 0 for N in range(NUM_N): NUM_P_BAR += ARR_P_OUT[N] NUM_P_BAR = NUM_P_BAR / float(NUM_N) NUM_p_bar = 0 for k in ARR_p_out: NUM_p_bar += k **2 return (NUM_P_BAR - NUM_p_bar) / (1 - NUM_p_bar) def gau_kde(ARR_IN_X, ARR_IN_I, NUM_BW=0.1 ): NUM_SUM = 0. NUM_LENG = len(ARR_IN_X) ARR_OUT = [ 0. for n in range(NUM_LENG)] for IND_J, J in enumerate(ARR_IN_X): NUM_SUM = 0.0 for I in ARR_IN_I: NUM_SUM += 1 / (2 * math.pi)**0.5 * math.e ** (-0.5 * ((J-I)/NUM_BW) ** 2 ) ARR_OUT[IND_J] = NUM_SUM / len(ARR_IN_I) / NUM_BW return ARR_OUT def standard_dev(ARR_IN): NUM_SUM = sum(ARR_IN) NUM_N = len(ARR_IN) NUM_MEAN = 1.0*NUM_SUM/NUM_N NUM_SUM2 = 0.0 for N in ARR_IN: if not math.isnan(N): NUM_SUM2 = (N-NUM_MEAN)**2 else: NUM_N += -1 return (NUM_SUM2 / (NUM_N-1)) ** 0.5 def h_esti(ARR_IN): #A rule-of-thumb bandwidth estimator NUM_SIGMA = standard_dev(ARR_IN) NUM_N = len(ARR_IN) return ((4 * NUM_SIGMA ** 5) / (3*NUM_N) ) ** 0.2 def data2array(ARR_IN, STR_IN="MEAN"): NUM_J = len(ARR_IN) NUM_I = len(ARR_IN[0]) ARR_OUT = [[ 0.0 for i in range(NUM_I)] for j in range(NUM_J) ] for j in range(NUM_J): for i in range(NUM_I): ARR_OUT[j][i] = ARR_IN[j][i][STR_IN] return ARR_OUT def reshape2d(ARR_IN): ARR_OUT=[] for A in ARR_IN: for B in A: ARR_OUT.append(B) return ARR_OUT def NormalVector( V1, V2): return [(V1[1]*V2[2] - V1[2]*V2[1]), (V1[2]*V2[0] - V1[0]*V2[2]),(V1[0]*V2[1] - V1[1]*V2[0])] def NVtoPlane( P0, P1, P2): """Input of P should be 3-dimensionals""" V1 = [(P1[0]-P0[0]),(P1[1]-P0[1]),(P1[2]-P0[2])] V2 = [(P2[0]-P0[0]),(P2[1]-P0[1]),(P2[2]-P0[2])] ARR_NV = MATH_TOOLS.NormalVector(V1, V2) D = ARR_NV[0] * P0[0] + ARR_NV[1] * P0[1] + ARR_NV[2] * P0[2] return ARR_NV[0],ARR_NV[1],ARR_NV[2],D def FindZatP3( P0, P1, P2, P3): """ input of P: (X,Y,Z); but P3 is (X,Y) only """ A,B,C,D = MATH_TOOLS.NVtoPlane(P0, P1, P2) return (D-A*P3[0] - B*P3[1])/float(C) class TOOLS: """ TOOLS is contains: timestamp fix_ind progress_bar cal_progrss """ ARR_HOY = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760] ARR_HOY_LEAP = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784] def NNARR(ARR_IN, IF_PAIRING=False): "Clean the NaN value in the array" if IF_PAIRING: ARR_SIZE = len(ARR_IN) ARR_OUT = [ [] for N in range(ARR_SIZE)] for ind_n, N in enumerate(ARR_IN[0]): IF_NAN = False for ind_a in range(ARR_SIZE): if math.isnan(ARR_IN[ind_a][ind_n]): IF_NAN = True break if not IF_NAN: for ind_a in range(ARR_SIZE): ARR_OUT[ind_a].append(ARR_IN[ind_a][ind_n]) else: ARR_OUT = [ ] for N in ARR_IN: if not math.isnan(N): ARR_OUT.append(N) return ARR_OUT def DATETIME2HOY(ARR_TIME, ARR_HOY_IN=[]): if math.fmod(ARR_TIME[0], 4) == 0 and len(ARR_HOY_IN) == 0: ARR_HOY_IN = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784] elif math.fmod(ARR_TIME[0], 4) != 0 and len(ARR_HOY_IN) == 0: ARR_HOY_IN = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760] else: ARR_HOY_IN = ARR_HOY_IN return ARR_HOY_IN[ARR_TIME[1]-1] + (ARR_TIME[2]-1)*24 + ARR_TIME[3] def timestamp(STR_IN=""): print("{0:04d}-{1:02d}-{2:02d}_{3:02d}:{4:02d}:{5:02d} {6:s}".format(time.gmtime().tm_year, time.gmtime().tm_mon, time.gmtime().tm_mday,\ time.gmtime().tm_hour, time.gmtime().tm_min, time.gmtime().tm_sec, STR_IN) ) def fix_ind(IND_IN, IND_J, IND_I, ARR_XRANGE=[], ARR_YRANGE=[], NX=0, NY=0): NUM_DY = ARR_YRANGE[0] NUM_NX_F = ARR_XRANGE[0] NUM_NX_R = NX - (ARR_XRANGE[1]+1) if IND_J == ARR_YRANGE[0]: IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F else: IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F * (IND_J - NUM_DY +1) - NUM_NX_R * (IND_J - NUM_DY) return IND_OUT def progress_bar(NUM_PROGRESS, NUM_PROGRESS_BIN=0.05, STR_SYS_SYMBOL="=", STR_DES="Progress"): NUM_SYM = int(NUM_PROGRESS / NUM_PROGRESS_BIN) sys.stdout.write('\r') sys.stdout.write('[{0:20s}] {1:4.2f}% {2:s}'.format(STR_SYS_SYMBOL*NUM_SYM, NUM_PROGRESS*100, STR_DES)) sys.stdout.flush() def clean_arr(ARR_IN, CRITERIA=1): ARR_OUT=[] for i,n in enumerate(ARR_IN): if len(n)> CRITERIA: ARR_OUT.append(n) return ARR_OUT def cal_loop_progress(ARR_INDEX, ARR_INDEX_MAX, NUM_CUM_MAX=1, NUM_CUM_IND=1, NUM_TOTAL_MAX=1): """ Please list from smallest to largest, i.e.: x->y->z """ if len(ARR_INDEX) == len(ARR_INDEX_MAX): for i, i_index in enumerate(ARR_INDEX): NUM_IND_PER = (i_index+1)/float(ARR_INDEX_MAX[i]) NUM_TOTAL_MAX = NUM_TOTAL_MAX * ARR_INDEX_MAX[i] if i >0: NUM_CUM_MAX = NUM_CUM_MAX * ARR_INDEX_MAX[i-1] NUM_CUM_IND = NUM_CUM_IND + NUM_CUM_MAX * i_index return NUM_CUM_IND / float(NUM_TOTAL_MAX) else: print("Wrong dimenstion for in put ARR_INDEX ({0:d}) and ARR_INDEX_MAX ({1:d})".format(len(ARR_INDEX), len(ARR_INDEX_MAX))) def calendar_cal(ARR_START_TIME, ARR_INTERVAL, ARR_END_TIME_IN=[0, 0, 0, 0, 0, 0.0], IF_LEAP=False): ARR_END_TIME = [ 0,0,0,0,0,0.0] ARR_DATETIME = ["SECOND", "MINUTE", "HOUR","DAY", "MON", "YEAR"] NUM_ARR_DATETIME = len(ARR_DATETIME) IF_FERTIG = False ARR_FERTIG = [0,0,0,0,0,0] DIC_TIME_LIM = \ {"YEAR" : {"START": 0 , "LIMIT": 9999 },\ "MON" : {"START": 1 , "LIMIT": 12 },\ "DAY" : {"START": 1 , "LIMIT": 31 },\ "HOUR" : {"START": 0 , "LIMIT": 23 },\ "MINUTE": {"START": 0 , "LIMIT": 59 },\ "SECOND": {"START": 0 , "LIMIT": 59 },\ } for I, T in enumerate(ARR_START_TIME): ARR_END_TIME[I] = T + ARR_INTERVAL[I] while IF_FERTIG == False: if math.fmod(ARR_END_TIME[0],4) == 0: IF_LEAP=True if IF_LEAP: ARR_DAY_LIM = [0,31,29,31,30,31,30,31,31,30,31,30,31] else: ARR_DAY_LIM = [0,31,28,31,30,31,30,31,31,30,31,30,31] for I, ITEM in enumerate(ARR_DATETIME): NUM_ARR_POS = NUM_ARR_DATETIME-I-1 if ITEM == "DAY": if ARR_END_TIME[NUM_ARR_POS] > ARR_DAY_LIM[ARR_END_TIME[1]]: ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - ARR_DAY_LIM[ARR_END_TIME[1]] ARR_END_TIME[NUM_ARR_POS - 1] += 1 else: if ARR_END_TIME[NUM_ARR_POS] > DIC_TIME_LIM[ITEM]["LIMIT"]: ARR_END_TIME[NUM_ARR_POS - 1] += 1 ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - DIC_TIME_LIM[ITEM]["LIMIT"] - 1 for I, ITEM in enumerate(ARR_DATETIME): NUM_ARR_POS = NUM_ARR_DATETIME-I-1 if ITEM == "DAY": if ARR_END_TIME[NUM_ARR_POS] <= ARR_DAY_LIM[ARR_END_TIME[1]]: ARR_FERTIG[NUM_ARR_POS] = 1 else: if ARR_END_TIME[NUM_ARR_POS] <= DIC_TIME_LIM[ITEM]["LIMIT"]: ARR_FERTIG[NUM_ARR_POS] = 1 if sum(ARR_FERTIG) == 6: IF_FERTIG = True return ARR_END_TIME class MPI_TOOLS: def __init__(self, MPI_SIZE=1, MPI_RANK=0,\ NUM_NX_END=1, NUM_NY_END=1, NUM_NX_START=0, NUM_NY_START=0, NUM_NX_CORES=1 ,\ NUM_NX_TOTAL=1, NUM_NY_TOTAL=1 ): """ END number follow the python philisophy: End number is not included in the list """ self.NUM_SIZE = MPI_SIZE self.NUM_RANK = MPI_RANK self.NUM_NX_START = NUM_NX_START self.NUM_NY_START = NUM_NY_START self.NUM_NX_SIZE = NUM_NX_END - NUM_NX_START self.NUM_NY_SIZE = NUM_NY_END - NUM_NY_START self.NUM_NX_CORES = NUM_NX_CORES self.NUM_NY_CORES = max(1, int(self.NUM_SIZE / NUM_NX_CORES)) self.ARR_RANK_DESIGN = [ {} for n in range(self.NUM_SIZE)] def CPU_GEOMETRY_2D(self): NUM_NX_REMAIN = self.NUM_NX_SIZE % self.NUM_NX_CORES NUM_NY_REMAIN = self.NUM_NY_SIZE % self.NUM_NY_CORES NUM_NX_DIFF = int((self.NUM_NX_SIZE - NUM_NX_REMAIN) / self.NUM_NX_CORES ) NUM_NY_DIFF = int((self.NUM_NY_SIZE - NUM_NY_REMAIN) / self.NUM_NY_CORES ) NUM_NY_DIFF_P1 = NUM_NY_DIFF + 1 NUM_NX_DIFF_P1 = NUM_NX_DIFF + 1 IND_RANK = 0 ARR_RANK_DESIGN = [ 0 for n in range(self.NUM_SIZE)] for ny in range(self.NUM_NY_CORES): for nx in range(self.NUM_NX_CORES): NUM_RANK = ny * self.NUM_NX_CORES + nx DIC_IN = {"INDEX_IN": NUM_RANK, "NX_START": 0, "NY_START": 0, "NX_END": 0, "NY_END": 0 } if ny < NUM_NY_REMAIN: DIC_IN["NY_START"] = (ny + 0) * NUM_NY_DIFF_P1 + self.NUM_NY_START DIC_IN["NY_END" ] = (ny + 1) * NUM_NY_DIFF_P1 + self.NUM_NY_START else: DIC_IN["NY_START"] = (ny - NUM_NY_REMAIN + 0) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START DIC_IN["NY_END" ] = (ny - NUM_NY_REMAIN + 1) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START if nx < NUM_NX_REMAIN: DIC_IN["NX_START"] = (nx + 0) * NUM_NX_DIFF_P1 + self.NUM_NX_START DIC_IN["NX_END" ] = (nx + 1) * NUM_NX_DIFF_P1 + self.NUM_NX_START else: DIC_IN["NX_START"] = (nx - NUM_NX_REMAIN + 0) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START DIC_IN["NX_END" ] = (nx - NUM_NX_REMAIN + 1) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START ARR_RANK_DESIGN[NUM_RANK] = DIC_IN self.ARR_RANK_DESIGN = ARR_RANK_DESIGN return ARR_RANK_DESIGN def CPU_MAP(self ): ARR_CPU_MAP = [ [ NP.nan for i in range(self.NUM_NX_TOTAL)] for j in range(self.NUM_NY_TOTAL) ] for RANK in range(len(ARR_RANK_DESIGN)): print("DEAL WITH {0:d} {1:d}".format(RANK, ARR_RANK_DESIGN[RANK]["INDEX_IN"] )) for jj in range(ARR_RANK_DESIGN[RANK]["NY_START"], ARR_RANK_DESIGN[RANK]["NY_END"]): for ii in range(ARR_RANK_DESIGN[RANK]["NX_START"], ARR_RANK_DESIGN[RANK]["NX_END"]): ARR_CPU_MAP[jj][ii] = ARR_RANK_DESIGN[RANK]["INDEX_IN"] return MAP_CPU def GATHER_ARR_2D(self, ARR_IN, ARR_IN_GATHER, ARR_RANK_DESIGN=[]): if ARR_RANK_DESIGN == []: ARR_RANK_DESIGN = self.ARR_RANK_DESIGN for N in range(1, self.NUM_SIZE): I_STA = ARR_RANK_DESIGN[N]["NX_START"] I_END = ARR_RANK_DESIGN[N]["NX_END" ] J_STA = ARR_RANK_DESIGN[N]["NY_START"] J_END = ARR_RANK_DESIGN[N]["NY_END" ] for J in range(J_STA, J_END ): for I in range(I_STA, I_END ): ARR_IN[J][I] = ARR_IN_GATHER[N][J][I] return ARR_IN def MPI_MESSAGE(self, STR_TEXT=""): TIME_NOW = time.gmtime() print("MPI RANK: {0:5d} @ {1:02d}:{2:02d}:{3:02d} # {4:s}"\ .format(self.NUM_RANK, TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec, STR_TEXT )) class GEO_TOOLS: def __init__(self): STR_NCDF4PY = NC.__version__ print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY)) def mask_dtm(self, NUM, ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"]): """ The determination algorithm is : x-1 < NUM <= x """ for i, n in enumerate(ARR_DTM): if i == 0: if NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n elif i == len(ARR_DTM_RANGE): if NUM > ARR_DTM_RANGE[i-1]: NUM_OUT = n else: if NUM > ARR_DTM_RANGE[i-1] and NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n return NUM_OUT def mask_array(self, ARR_IN, ARR_MASK_OUT=[], ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"], IF_2D=False): if IF_2D: NUM_NX = len(ARR_IN[0]) NUM_NY = len(ARR_IN) ARR_OUT = [ [ self.NUM_NULL for i in range(NUM_NX)] for j in range(NUM_NY) ] for J in range(NUM_NY): for I in range(NUM_NY): ARR_OUT[J][I] = self.mask_dtm(ARR_IN[J][I], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM) else: NUM_NX = len(ARR_IN) ARR_OUT = [0 for n in range(NUM_NX)] for N in range(NUM_NX): ARR_OUT[N] = self.mask_dtm(ARR_IN[N], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM) return ARR_OUT def MAKE_LAT_LON_ARR(self, FILE_NC_IN, STR_LAT="lat", STR_LON="lon", source="CFC"): """ Reading LAT and LON from a NC file """ NC_DATA_IN = NC.Dataset(FILE_NC_IN, "r", format="NETCDF4") if source == "CFC": arr_lat_in = NC_DATA_IN.variables[STR_LAT] arr_lon_in = NC_DATA_IN.variables[STR_LON] num_nlat = len(arr_lat_in) num_nlon = len(arr_lon_in) arr_lon_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)] arr_lat_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)] for j in range(num_nlat): for i in range(num_nlon): arr_lon_out[j][i] = arr_lat_in[j] arr_lat_out[j][i] = arr_lon_in[i] return arr_lat_out, arr_lon_out class NETCDF4_HELPER: def __init__(self): STR_NCDF4PY = NC.__version__ print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY)) def create_wrf_ensemble(self, STR_FILE_IN, STR_FILE_OUT, ARR_VAR=[], STR_DIR="./", NUM_ENSEMBLE_SIZE=1 ): FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE_OUT), "w",format="NETCDF4") FILE_IN = NC.Dataset("{1:s}/{1:s}".format(STR_DIR, STR_FILE_IN ), "r",format="NETCDF4") # CREATE DIMENSIONS: for DIM in FILE_IN.dimensions: FILE_OUT.createDimension(DIM, FILE_IN.dimensions[DIM].size ) FILE_OUT.createDimension("Ensembles", NUM_ENSEMBLE_SIZE ) # CREATE ATTRIBUTES: FILE_OUT.TITLE = FILE_IN.TITLE FILE_OUT.START_DATE = FILE_IN.START_DATE FILE_OUT.SIMULATION_START_DATE = FILE_IN.SIMULATION_START_DATE FILE_OUT.DX = FILE_IN.DX FILE_OUT.DY = FILE_IN.DY FILE_OUT.SKEBS_ON = FILE_IN.SKEBS_ON FILE_OUT.SPEC_BDY_FINAL_MU = FILE_IN.SPEC_BDY_FINAL_MU FILE_OUT.USE_Q_DIABATIC = FILE_IN.USE_Q_DIABATIC FILE_OUT.GRIDTYPE = FILE_IN.GRIDTYPE FILE_OUT.DIFF_OPT = FILE_IN.DIFF_OPT FILE_OUT.KM_OPT = FILE_IN.KM_OPT if len(ARR_VAR) >0: for V in ARR_VAR: if V[1] == "2D": FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "south_north", "west_east" )) elif V[1] == "3D": FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "bottom_top", "south_north", "west_east" )) FILE_OUT.close() FILE_IN.close() def add_ensemble(self, FILE_IN, FILE_OUT, STR_VAR, STR_DIM="2D", STR_DIR="./", IND_ENSEMBLE=0): FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_OUT), "a",format="NETCDF4") FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_IN ), "r",format="NETCDF4") ARR_VAR_IN = FILE_IN.variables[STR_VAR] NUM_NT = len(ARR_VAR_IN) NUM_NK = FILE_IN.dimensions["bottom_top"].size NUM_NJ = FILE_IN.dimensions["south_north"].size NUM_NI = FILE_IN.dimensions["west_east"].size for time in range(NUM_NT): if STR_DIM == "2D": FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time] elif STR_DIM == "3D": for k in range(NUM_NK): FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time] FILE_OUT.close() FILE_IN.close() class WRF_HELPER: STR_DIR_ROOT = "./" NUM_TIME_INIT = 0 NUM_SHIFT = 0.001 def __init__(self): """ Remember: most array should be follow the rule of [j,i] instead of [x,y]. """ STR_NCDF4PY = NC.__version__ print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY)) def GEO_INFORMATER(self, STR_FILE="geo_em.d01.nc", STR_DIR=""): print("INPUT GEO FILE: {0:s}".format(STR_FILE)) if STR_DIR == "": STR_DIR == self.STR_DIR_ROOT self.FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE ), "r",format="NETCDF4") self.MAP_LAT = self.FILE_IN.variables["CLAT"] [self.NUM_TIME_INIT] self.MAP_LON = self.FILE_IN.variables["CLONG"][self.NUM_TIME_INIT] ARR_TMP_IN = self.FILE_IN.variables["CLONG"][0] # Since NetCDF4 for python does not support the hyphen in attributes, I # am forced to calculate the NX and NY based on a map in the NC file. self.NUM_NX = len(ARR_TMP_IN[0]) self.NUM_NY = len(ARR_TMP_IN) self.NUM_DX = self.FILE_IN.DX self.NUM_DY = self.FILE_IN.DX def GEO_HELPER(self, ARR_LL_SW, ARR_LL_NE): self.MAP_CROP_MASK = [[ 0 for i in range(self.NUM_NX)] for j in range(self.NUM_NY)] self.DIC_CROP_INFO = {"NE": {"LAT":0, "LON":0, "I":0, "J":0},\ "SW": {"LAT":0, "LON":0, "I":0, "J":0}} ARR_TMP_I = [] ARR_TMP_J = [] for j in range(self.NUM_NY): for i in range(self.NUM_NX): NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0] if NUM_CHK_SW_J == 0: NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0] + self.NUM_SHIFT NUM_CHK_SW_I = self.MAP_LON[j][i] - ARR_LL_SW[1] if NUM_CHK_SW_I == 0: NUM_CHK_SW_I = self.MAP_LAT[j][i] - ARR_LL_SW[1] - self.NUM_SHIFT NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0] if NUM_CHK_NE_J == 0: NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0] + self.NUM_SHIFT NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1] if NUM_CHK_NE_I == 0: NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1] - self.NUM_SHIFT NUM_CHK_NS_IN = NUM_CHK_SW_J * NUM_CHK_NE_J NUM_CHK_WE_IN = NUM_CHK_SW_I * NUM_CHK_NE_I if NUM_CHK_NS_IN < 0 and NUM_CHK_WE_IN < 0: self.MAP_CROP_MASK[j][i] = 1 ARR_TMP_J.append(j) ARR_TMP_I.append(i) NUM_SW_J = min( ARR_TMP_J ) NUM_SW_I = min( ARR_TMP_I ) NUM_NE_J = max( ARR_TMP_J ) NUM_NE_I = max( ARR_TMP_I ) self.DIC_CROP_INFO["NE"]["J"] = NUM_NE_J self.DIC_CROP_INFO["NE"]["I"] = NUM_NE_I self.DIC_CROP_INFO["NE"]["LAT"] = self.MAP_LAT[NUM_NE_J][NUM_NE_I] self.DIC_CROP_INFO["NE"]["LON"] = self.MAP_LON[NUM_NE_J][NUM_NE_I] self.DIC_CROP_INFO["SW"]["J"] = NUM_SW_J self.DIC_CROP_INFO["SW"]["I"] = NUM_SW_I self.DIC_CROP_INFO["SW"]["LAT"] = self.MAP_LAT[NUM_SW_J][NUM_SW_I] self.DIC_CROP_INFO["SW"]["LON"] = self.MAP_LON[NUM_SW_J][NUM_SW_I] def PROFILE_HELPER(STR_FILE_IN, ARR_DATE_START, NUM_DOMS=3, NUM_TIMESTEPS=24, IF_PB=False): """ This functions reads the filename, array of starting date, and simulation hours and numbers of domains to profiling the time it takes for WRF. """ FILE_READ_IN = open("{0:s}".format(STR_FILE_IN)) ARR_READ_IN = FILE_READ_IN.readlines() NUM_TIME = NUM_TIMESTEPS NUM_DOMAIN = NUM_DOMS NUM_DATE_START = ARR_DATE_START NUM_LEN_IN = len(ARR_READ_IN) ARR_TIME_PROFILE = [[0 for T in range(NUM_TIME)] for D in range(NUM_DOMS)] for I, TEXT_IN in enumerate(ARR_READ_IN): ARR_TEXT = re.split("\s",TEXT_IN.strip()) if ARR_TEXT[0] == "Timing": if ARR_TEXT[2] == "main:" or ARR_TEXT[2] == "main": for ind, T in enumerate(ARR_TEXT): if T == "time" : ind_time_text = ind + 1 if T == "elapsed": ind_elapsed_text = ind - 1 if T == "domain" : ind_domain_text = ind + 3 arr_time_in = re.split("_", ARR_TEXT[ind_time_text]) arr_date = re.split("-", arr_time_in[0]) arr_time = re.split(":", arr_time_in[1]) num_domain = int(re.split(":", ARR_TEXT[ind_domain_text])[0]) num_elapsed = float(ARR_TEXT[ind_elapsed_text]) NUM_HOUR_FIX = (int(arr_date[2]) - NUM_DATE_START[2]) * 24 NUM_HOUR = NUM_HOUR_FIX + int(arr_time[0]) ARR_TIME_PROFILE[num_domain-1][NUM_HOUR] += num_elapsed if IF_PB: TOOLS.progress_bar(I/float(NUM_LEN_IN)) #self.ARR_TIME_PROFILE = ARR_TIME_PROFILE return ARR_TIME_PROFILE class DATA_READER: """ The DATA_READER is based on my old work: gridtrans.py. """ def __init__(self, STR_NULL="noData", NUM_NULL=-999.999): self.STR_NULL=STR_NULL self.NUM_NULL=NUM_NULL def stripblnk(arr,*num_typ): new_arr=[] for i in arr: if i == "": pass else: if num_typ[0] == 'int': new_arr.append(int(i)) elif num_typ[0] == 'float': new_arr.append(float(i)) elif num_typ[0] == '': new_arr.append(i) else: print("WRONG num_typ!") return new_arr def tryopen(self, sourcefile, ag): try: opf=open(sourcefile,ag) return opf except : print("No such file.") return "error" def READCSV(self, sourcefile): opf = self.tryopen(sourcefile,'r') opfchk = self.tryopen(sourcefile,'r') print("reading source file {0:s}".format(sourcefile)) chk_lines = opfchk.readlines() num_totallines = len(chk_lines) ncols = 0 num_notnum = 0 for n in range(num_totallines): line_in = chk_lines[n] c_first = re.findall(".",line_in.strip()) if c_first[0] == "#": num_notnum += 1 else: ncols = len( re.split(",",line_in.strip()) ) break if ncols == 0: print("something wrong with the input file! (all comments?)") else: del opfchk nrows=num_totallines - num_notnum result_arr=[[self.NUM_NULL for j in range(ncols)] for i in range(nrows)] result_arr_text=[] num_pass = 0 for j in range(0,num_totallines): # chk if comment #print (j,i,chk_val) line_in = opf.readline() c_first = re.findall(".",line_in.strip())[0] if c_first == "#": result_arr_text.append(line_in) num_pass += 1 else: arr_in = re.split(",",line_in.strip()) for i in range(ncols): chk_val = arr_in[i] if chk_val == self.STR_NULL: result_arr[j-num_pass][i] = self.NUM_NULL else: result_arr[j-num_pass][i] = float(chk_val) return result_arr,result_arr_text
lgpl-3.0
jojoe77777/Slapper
src/slapper/entities/SlapperVex.php
156
<?php declare(strict_types=1); namespace slapper\entities; class SlapperVex extends SlapperEntity { const TYPE_ID = 105; const HEIGHT = 0.8; }
lgpl-3.0
leodmurillo/sonar
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/reviews/MyReviewsWidget.java
1757
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.core.widgets.reviews; import org.sonar.api.web.AbstractRubyTemplate; import org.sonar.api.web.RubyRailsWidget; import org.sonar.api.web.WidgetCategory; import org.sonar.api.web.WidgetProperties; import org.sonar.api.web.WidgetProperty; import org.sonar.api.web.WidgetPropertyType; @WidgetCategory({ "Reviews" }) @WidgetProperties( { @WidgetProperty(key = "numberOfLines", type = WidgetPropertyType.INTEGER, defaultValue = "5", description="Maximum number of reviews displayed at the same time.") } ) public class MyReviewsWidget extends AbstractRubyTemplate implements RubyRailsWidget { public String getId() { return "my_reviews"; } public String getTitle() { return "My open reviews"; } @Override protected String getTemplatePath() { return "/org/sonar/plugins/core/widgets/reviews/my_reviews.html.erb"; } }
lgpl-3.0
chriseling/brainy
src/Brainy/sysplugins/smarty_internal_compile_section.php
7064
<?php /** * Smarty Internal Plugin Compile Section * * Compiles the {section} {sectionelse} {/section} tags * * @package Brainy * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Section Class * * @package Brainy * @subpackage Compiler */ class Smarty_Internal_Compile_Section extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array('name', 'loop'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $shorttag_order = array('name', 'loop'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('start', 'step', 'max', 'show'); /** * Compiles code for the {section} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return string compiled code */ public function compile($args, $compiler) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); $this->openTag($compiler, 'section', array('section')); $output = ''; $section_name = $_attr['name']; $output .= "if (isset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name])) unset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]);\n"; $section_props = "\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]"; foreach ($_attr as $attr_name => $attr_value) { switch ($attr_name) { case 'loop': $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int) \$_loop); unset(\$_loop);\n"; break; case 'show': if (is_bool($attr_value)) $show_attr_value = $attr_value ? 'true' : 'false'; else $show_attr_value = "(bool) $attr_value"; $output .= "{$section_props}['show'] = $show_attr_value;\n"; break; case 'name': $output .= "{$section_props}['$attr_name'] = $attr_value;\n"; break; case 'max': case 'start': $output .= "{$section_props}['$attr_name'] = (int) $attr_value;\n"; break; case 'step': $output .= "{$section_props}['$attr_name'] = ((int) $attr_value) == 0 ? 1 : (int) $attr_value;\n"; break; } } if (!isset($_attr['show'])) $output .= "{$section_props}['show'] = true;\n"; if (!isset($_attr['loop'])) $output .= "{$section_props}['loop'] = 1;\n"; if (!isset($_attr['max'])) $output .= "{$section_props}['max'] = {$section_props}['loop'];\n"; else $output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n"; if (!isset($_attr['step'])) $output .= "{$section_props}['step'] = 1;\n"; if (!isset($_attr['start'])) $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n"; else { $output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n"; } $output .= "if ({$section_props}['show']) {\n"; if (!isset($_attr['start']) && !isset($_attr['step']) && !isset($_attr['max'])) { $output .= " {$section_props}['total'] = {$section_props}['loop'];\n"; } else { $output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n"; } $output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n"; $output .= "if ({$section_props}['show']):\n"; $output .= " for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1; {$section_props}['iteration'] <= {$section_props}['total']; {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n"; $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n"; $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n"; $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n"; $output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n"; $output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n"; return $output; } } /** * Smarty Internal Plugin Compile Sectionelse Class * * @package Brainy * @subpackage Compiler */ class Smarty_Internal_Compile_Sectionelse extends Smarty_Internal_CompileBase { /** * Compiles code for the {sectionelse} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return string compiled code */ public function compile($args, $compiler) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); list($openTag) = $this->closeTag($compiler, array('section')); $this->openTag($compiler, 'sectionelse', array('sectionelse')); return "endfor;\nelse:\n"; } } /** * Smarty Internal Plugin Compile Sectionclose Class * * @package Brainy * @subpackage Compiler */ class Smarty_Internal_Compile_Sectionclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/section} tag * * @param array $args array with attributes from parser * @param object $compiler compiler object * @return string compiled code */ public function compile($args, $compiler) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); list($openTag) = $this->closeTag($compiler, array('section', 'sectionelse')); if ($openTag == 'sectionelse') { return "endif;\n"; } else { return "endfor;\nendif;\n"; } } }
lgpl-3.0
milesmcc/Course-Database-Utility
README.md
956
# Course Database Utility An internal utility for interaction with a database of courses &amp; other information that can be extracted from such a database. ## What is this for This was created for Phillips Academy Andover. Each term, a master schedule PDF is released, but it's horrible to use. In order to search it, you need to use Cmd-F and hope that you entered in the right term. Want to search by period or by section exclusively? You're out of luck. Course Database Utility was created so that this is no longer an issue. It provides a functional (but maybe slightly ugly) web utility for interacting with the database. ## How to run it Just run `python webserver.py` to start up the webserver. It will then become accessable on port 8888. ## Where the courses are stored Courses are stored in term JSON files in the 'terms' directory. See Example.json for information on the data schema. ## License The entire project is licensed under LGPL.
lgpl-3.0