repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
yarKH/XChange
xchange-bitbay/src/main/java/com/xeiam/xchange/bitbay/BitbayAuthentiacated.java
2853
package com.xeiam.xchange.bitbay; import com.xeiam.xchange.bitbay.dto.BitbayBaseResponse; import com.xeiam.xchange.bitbay.dto.account.BitbayAccount; import com.xeiam.xchange.bitbay.dto.trade.BitbayOrder; import com.xeiam.xchange.bitbay.dto.trade.BitbayTradeResponse; import com.xeiam.xchange.bitbay.dto.trade.BitbayTransaction; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.math.BigDecimal; import java.util.List; /** * @author Yarkh */ @Path("/API/Trading/tradingApi.php") @Produces(MediaType.APPLICATION_JSON) public interface BitbayAuthentiacated extends Bitbay { @POST @FormParam("method") public BitbayAccount info(@HeaderParam("API-Key") String key, @HeaderParam("API-Hash") ParamsDigest sign, @FormParam("moment") SynchronizedValueFactory<Long> moment, @FormParam("currency") String currency) throws IOException; @POST @FormParam("method") public List<BitbayOrder> orders(@HeaderParam("API-Key") String key, @HeaderParam("API-Hash") ParamsDigest sign, @FormParam("moment") SynchronizedValueFactory<Long> moment) throws IOException; @POST @FormParam("method") public BitbayTradeResponse trade(@HeaderParam("API-Key") String key, @HeaderParam("API-Hash") ParamsDigest sign, @FormParam("moment") SynchronizedValueFactory<Long> moment, @FormParam("type") String type, @FormParam("currency") String currency, @FormParam("payment_currency") String payment_currency, @FormParam("amount") BigDecimal amount, @FormParam("price") BigDecimal price, @FormParam("rate") BigDecimal rate) throws IOException; @POST @FormParam("method") public BitbayBaseResponse cancel(@HeaderParam("API-Key") String key, @HeaderParam("API-Hash") ParamsDigest sign, @FormParam("moment") SynchronizedValueFactory<Long> moment, @FormParam("id") String id) throws IOException; @POST @FormParam("method") public List<BitbayTransaction> transactions(@HeaderParam("API-Key") String key, @HeaderParam("API-Hash") ParamsDigest sign, @FormParam("moment") SynchronizedValueFactory<Long> moment, @FormParam("market") String market) throws IOException; }
mit
6IRCNet/web6irc
common/src/util.js
640
/** @struct */ W6I.Util = {} W6I.Util.objeach = function(/** Object */ obj, /** function(*, (number|string)=) */ fun) { for (i in obj) { if (obj.hasOwnProperty(i)) { fun(obj[i], i); } } }; W6I.Util.extend = function(/** Object */ obj, /** Object */ withwhat) { W6I.Util.objeach(withwhat, function(v, k) { obj[k] = v; }); }; W6I.Util.dump = function /** Object */ (/** Object */ obj) { if (typeof obj.dump === "function") return obj.dump(); return obj; }; /** * @template T * @template U */ W6I.Util.load = function /** T */ (/** U */ obj, /** function(new:T, U) */ klass) { return new klass(obj); };
mit
zzragida/NodeExamples
socket/client.js
412
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 7000; var client = new net.Socket(); client.connect(PORT, HOST, function() { var i; console.log('CONNECT TO: ' + HOST + ':' + PORT); for (i = 0; i < 1000; i++) { client.write(i + ':i am here'); } }); client.on('data', function(data) { console.log('DATA: ' + data); }); client.on('close', function() { console.log('CLOSED'); });
mit
jnguyen095/real-estate
application/views/Notfound_view.php
2609
<!DOCTYPE html> <html lang = "en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="audience" content="general" /> <meta name="resource-type" content="document" /> <meta name="abstract" content="Thông tin nhà đất Việt Nam" /> <meta name="classification" content="Bất động sản Việt Nam" /> <meta name="area" content="Nhà đất và bất động sản" /> <meta name="placename" content="Việt Nam" /> <meta name="author" content="tindatdai.com" /> <meta name="copyright" content="©2017 tindatdai.com" /> <meta name="owner" content="tindatdai.com" /> <meta name="distribution" content="Global" /> <meta name="description" content="Sản phẩm không tìm thấy"> <meta name="keywords" content="Sản, phẩm, không, tìm, thấy"> <meta name="revisit-after" content="1 days" /> <meta name="robots" content="follow" /> <title>Sản phẩm không tìm thấy</title> <?php $this->load->view('common_header')?> <link rel="stylesheet" href="<?=base_url('/css/jquery.mCustomScrollbar.min.css')?>" /> <link rel="stylesheet" href="<?=base_url('/css/carousel-custom.css')?>" /> <script src="<?=base_url('/js/jquery.mCustomScrollbar.min.js')?>"></script> <?php $this->load->view('/common/googleadsense')?> <?php $this->load->view('/common/facebook-pixel-tracking')?> </head> <body> <?php $this->load->view('/common/analyticstracking')?> <div class="container"> <?php $this->load->view('/theme/header')?> <ul class="breadcrumb always"> <li><a href="<?php echo base_url()?>">Trang chủ</a></li> <li class="active">Không tìm thấy</li> </ul> <div class="row no-margin"> <div class="col-md-9 no-margin no-padding product-detail"> <div class="product-title"><h1 itemprop="name" class="h1Class">Không tìm thấy</h1></div> <div class="row no-margin"> <div class="alert alert-danger" role="alert"> <strong>Thật Tiếc!</strong> Tin bạn muốn xem đã giao dịch thành công hoặc không còn tồn tại. </div> </div> </div> <div class="col-md-3 no-margin-right no-padding-right no-padding-left-mobile"> <?php $this->load->view('/common/Search_filter') ?> <?php $this->load->view('/common/sample_house') ?> <div class="clear-both"></div> <img class="width100pc margin-bottom-20 mobile-hide" src="<?=base_url('/img/hoatraotay.jpg')?>" alt="Hoa Trao Tay"/> </div> </div> <?php $this->load->view('/theme/footer')?> </div> <!-- Place this tag in your head or just before your close body tag. --> <script src="https://apis.google.com/js/platform.js" async defer></script> </body> </html>
mit
shiftkey/desktop
app/src/lib/wrap-rich-text-commit-message.ts
4327
import { Tokenizer, TokenType, TokenResult, PlainText, HyperlinkMatch, } from './text-token-parser' import { assertNever } from './fatal-error' export const MaxSummaryLength = 72 export const IdealSummaryLength = 50 /** * A method used to wrap long commit summaries and put any overflow * into the commit body while taking rich text into consideration. * * See https://github.com/desktop/desktop/issues/9185 for a description * of the problem and https://github.com/desktop/desktop/pull/2575 for * the initial naive implementation. * * Note that this method doesn't wrap multibyte chars like unicode emojis * correctly (i.e. it could end up splitting a multibyte char). * * @param summaryText The commit message summary text (i.e. the first line) * @param bodyText The commit message body text * @param tokenizer The tokenizer to use when converting the raw text to * rich text tokens * @param maxSummaryLength The maximum width of the commit summary (defaults * to 72), note that this does not include any ellipsis * that may be appended when wrapping. In other words * it's possible that the commit summary ends up being * maxSummaryLength + 1 long when rendered. */ export function wrapRichTextCommitMessage( summaryText: string, bodyText: string, tokenizer: Tokenizer, maxSummaryLength = MaxSummaryLength ): { summary: ReadonlyArray<TokenResult>; body: ReadonlyArray<TokenResult> } { const tokens = tokenizer.tokenize(summaryText.trimRight()) const summary = new Array<TokenResult>() const overflow = new Array<TokenResult>() let remainder = maxSummaryLength for (const token of tokens) { // An emoji token like ":white_square_button: would still only take // up a little bit more space than a regular character when rendered // as an image, we take that into consideration here with an approximation // that an emoji is twice as wide as a normal character. const charCount = token.kind === TokenType.Emoji ? 2 : token.text.length if (remainder <= 0) { // There's no room left in the summary, everything needs to // go into the overflow overflow.push(token) } else if (remainder >= charCount) { // The token fits without us having to think about wrapping! summary.push(token) remainder -= charCount } else { // There's not enough room to include the token in its entirety, // we've got to make a decision between hard wrapping or pushing // to overflow. if (token.kind === TokenType.Text) { // We always hard-wrap text, it'd be nice if we could attempt // to break at word boundaries in the future but that's too // complex for now. summary.push(text(token.text.substr(0, remainder))) overflow.push(text(token.text.substr(remainder))) } else if (token.kind === TokenType.Emoji) { // Can't hard-wrap inside an emoji overflow.push(token) } else if (token.kind === TokenType.Link) { // Hard wrapping an issue link is confusing so we treat them // as atomic. For all other links (@mentions or https://...) // We want at least the first couple of characters of the link // text showing otherwise we'll end up with weird links like "h" // or "@" if (!token.text.startsWith('#') && remainder > 5) { summary.push(link(token.text.substr(0, remainder), token.text)) overflow.push(link(token.text.substr(remainder), token.text)) } else { overflow.push(token) } } else { return assertNever(token, `Unknown token type`) } remainder = 0 } } let body = tokenizer.tokenize(bodyText.trimRight()) if (overflow.length > 0) { summary.push(ellipsis()) if (body.length > 0) { body = [ellipsis(), ...overflow, text('\n\n'), ...body] } else { body = [ellipsis(), ...overflow] } } return { summary, body } } function ellipsis() { return text('…') } function text(text: string): PlainText { return { kind: TokenType.Text, text } } function link(text: string, url: string): HyperlinkMatch { return { kind: TokenType.Link, text, url } }
mit
backus/mutest
meta/op_assgn.rb
859
Mutest::Meta::Example.add :op_asgn do source '@a.b += 1' singleton_mutations mutation 'a.b += 1' mutation '@a.b += -1' mutation '@a.b += 2' mutation '@a.b += 0' mutation '@a.b += nil' mutation '@a.b += self' mutation 'self.b += 1' mutation '@a.b + 1' mutation '@a.b = 1' # TODO: fix invalid AST # This should not get emitted as invalid AST with valid unparsed source mutation s(:op_asgn, s(:ivar, :@a), :+, s(:int, 1)) end Mutest::Meta::Example.add :op_asgn do source 'a *= b' singleton_mutations mutation 'a__mutest__ *= b' mutation 'a *= nil' mutation 'a *= self' mutation 'a * b' mutation 'a = b' end Mutest::Meta::Example.add :op_asgn do source '@a <<= b' singleton_mutations mutation '@a__mutest__ <<= b' mutation '@a <<= nil' mutation '@a <<= self' mutation '@a << b' mutation '@a = b' end
mit
dropbox/dropbox-sdk-dotnet
dropbox-sdk-dotnet/Dropbox.Api/DropboxClientBase.cs
1786
//----------------------------------------------------------------------------- // <copyright file="DropboxClientBase.cs" company="Dropbox Inc"> // Copyright (c) Dropbox Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace Dropbox.Api { using System; using Dropbox.Api.Stone; /// <summary> /// The base class for all Dropbox clients. /// </summary> public abstract class DropboxClientBase : IDisposable { /// <summary> /// The transport. /// </summary> private readonly ITransport transport; /// <summary> /// Initializes a new instance of the <see cref="DropboxClientBase"/> class. /// </summary> /// <param name="transport">The transport.</param> internal DropboxClientBase(ITransport transport) { this.transport = transport; this.InitializeRoutes(this.transport); } /// <summary> /// The public dispose. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Initializes routes. /// </summary> /// <param name="transport">The transport.</param> internal abstract void InitializeRoutes(ITransport transport); /// <summary> /// The actual disposing logic. /// </summary> /// <param name="disposing">If is disposing.</param> protected virtual void Dispose(bool disposing) { if (disposing) { // ITransport is safe for multiple disposal. this.transport.Dispose(); } } } }
mit
bradleygore/nativescript-textinputlayout
src/textInputLayout.common.js
897
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var color_1 = require("tns-core-modules/color"); exports.Color = color_1.Color; var view_1 = require("tns-core-modules/ui/core/view"); var properties_1 = require("tns-core-modules/ui/core/properties"); exports.Property = properties_1.Property; var TextInputLayout = (function (_super) { __extends(TextInputLayout, _super); function TextInputLayout() { return _super !== null && _super.apply(this, arguments) || this; } return TextInputLayout; }(view_1.View)); exports.TextInputLayout = TextInputLayout; exports.errorProperty = new properties_1.Property({ name: "error", affectsLayout: true }); exports.errorProperty.register(TextInputLayout); exports.hintProperty = new properties_1.Property({ name: "hint", affectsLayout: true }); exports.hintProperty.register(TextInputLayout);
mit
CNinnovation/powercampwindows10
clientandserver/BooksSample/WPFBooksClient/WPFServices/WPFMessageDialog.cs
422
using BooksLib.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace WPFBooksClient.WPFServices { public class WPFMessageDialog : IMessageService { public Task ShowMessageAsync(string message) { MessageBox.Show(message); return Task.CompletedTask; } } }
mit
pombredanne/metamorphosys-desktop
metamorphosys/META/src/CyPhyCADAnalysis/MgaGateway.cs
5492
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using GME; using GME.Util; using GME.MGA; using GME.MGA.Meta; namespace GME.CSharp { class MgaGateway { public MgaGateway(IMgaProject project) { this.project = project; } public IMgaProject project = null; public IMgaTerritory territory = null; #region TRANSACTION HANDLING public void BeginTransaction(transactiontype_enum mode = transactiontype_enum.TRANSACTION_GENERAL) { project.BeginTransaction(territory, mode); } public void CommitTransaction() { if ((project.ProjectStatus & 8) != 0) { project.CommitTransaction(); } } public void AbortTransaction() { if ((project.ProjectStatus & 8) != 0) { project.AbortTransaction(); } } public delegate void voidDelegate(); public void PerformInTransaction(voidDelegate d, transactiontype_enum mode = transactiontype_enum.TRANSACTION_GENERAL, bool abort = true) { BeginTransaction(mode); try { d(); if (abort) { AbortTransaction(); } else { CommitTransaction(); } } finally { AbortTransaction(); } } /* public void PerformInTransaction(voidDelegate d, transactiontype_enum mode = transactiontype_enum.TRANSACTION_GENERAL) { BeginTransaction(mode); try { d(); CommitTransaction(); } finally { AbortTransaction(); } } */ #endregion #region UTILITIES public IMgaMetaBase GetMetaByName(string name) { try { return project.RootMeta.RootFolder.get_DefinedFCOByName(name, false) as MgaMetaFCO; } #pragma warning disable 0168 catch (System.Runtime.InteropServices.COMException e) { return project.RootMeta.RootFolder.get_DefinedFolderByName(name, false) as MgaMetaFolder; } #pragma warning restore 0168 } #endregion } }
mit
jazzay/Perspex
src/Avalonia.Visuals/Rendering/SceneGraph/RectangleNode.cs
4082
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Platform; using Avalonia.VisualTree; namespace Avalonia.Rendering.SceneGraph { /// <summary> /// A node in the scene graph which represents a rectangle draw. /// </summary> internal class RectangleNode : BrushDrawOperation { /// <summary> /// Initializes a new instance of the <see cref="RectangleNode"/> class. /// </summary> /// <param name="transform">The transform.</param> /// <param name="brush">The fill brush.</param> /// <param name="pen">The stroke pen.</param> /// <param name="rect">The rectanle to draw.</param> /// <param name="cornerRadius">The rectangle corner radius.</param> /// <param name="childScenes">Child scenes for drawing visual brushes.</param> public RectangleNode( Matrix transform, IBrush brush, Pen pen, Rect rect, float cornerRadius, IDictionary<IVisual, Scene> childScenes = null) { Bounds = rect.TransformToAABB(transform).Inflate(pen?.Thickness ?? 0); Transform = transform; Brush = brush?.ToImmutable(); Pen = pen?.ToImmutable(); Rect = rect; CornerRadius = cornerRadius; ChildScenes = childScenes; } /// <inheritdoc/> public override Rect Bounds { get; } /// <summary> /// Gets the transform with which the node will be drawn. /// </summary> public Matrix Transform { get; } /// <summary> /// Gets the fill brush. /// </summary> public IBrush Brush { get; } /// <summary> /// Gets the stroke pen. /// </summary> public Pen Pen { get; } /// <summary> /// Gets the rectangle to draw. /// </summary> public Rect Rect { get; } /// <summary> /// Gets the rectangle corner radius. /// </summary> public float CornerRadius { get; } /// <inheritdoc/> public override IDictionary<IVisual, Scene> ChildScenes { get; } /// <summary> /// Determines if this draw operation equals another. /// </summary> /// <param name="transform">The transform of the other draw operation.</param> /// <param name="brush">The fill of the other draw operation.</param> /// <param name="pen">The stroke of the other draw operation.</param> /// <param name="rect">The rectangle of the other draw operation.</param> /// <param name="cornerRadius">The rectangle corner radius of the other draw operation.</param> /// <returns>True if the draw operations are the same, otherwise false.</returns> /// <remarks> /// The properties of the other draw operation are passed in as arguments to prevent /// allocation of a not-yet-constructed draw operation object. /// </remarks> public bool Equals(Matrix transform, IBrush brush, Pen pen, Rect rect, float cornerRadius) { return transform == Transform && Equals(brush, Brush) && pen == Pen && rect == Rect && cornerRadius == CornerRadius; } /// <inheritdoc/> public override void Render(IDrawingContextImpl context) { context.Transform = Transform; if (Brush != null) { context.FillRectangle(Brush, Rect, CornerRadius); } if (Pen != null) { context.DrawRectangle(Pen, Rect, CornerRadius); } } // TODO: This doesn't respect CornerRadius yet. /// <inheritdoc/> public override bool HitTest(Point p) => Bounds.Contains(p); } }
mit
Akagi201/learning-rust
trait/animal-interface/src/main.rs
1359
trait Animal { // Static method signature; 'Self' refers to the implementor type. fn new(name: &'static str) -> Self; // Instance method signatures; these will return a string. fn name(&self) -> &'static str; fn noise(&self) -> &'static str; // Traits can provide default method definitions. fn talk(&self) { println!("{} says {}", self.name(), self.noise()); } } struct Cat { name: &'static str, age: u32, } struct Dog { name: &'static str, } impl Animal for Cat { // Self is the implementor type: Cat. fn new(name: &'static str) -> Self { Cat { name, age: 1 } } fn name(&self) -> &'static str { self.name } fn noise(&self) -> &'static str { "meow" } // Default trait methods can be overridden. fn talk(&self) { // For example, we can add some quiet contemplation. println!("{} pause briefly... {}", self.name, self.noise()); } } impl Animal for Dog { fn new(name: &'static str) -> Self { Dog { name } } fn name(&self) -> &'static str { self.name } fn noise(&self) -> &'static str { "woof" } } fn main() { let c: Cat = Animal::new("Kate"); println!("Cat's name is {} {}", c.name(), c.age); c.talk(); let d: Dog = Animal::new("Spot"); d.talk(); }
mit
winters-song/photoGallery
public/js/views/preview/groupMenu.js
2144
define([ 'jquery', 'underscore', 'backbone', 'collections/groupItems', 'views/preview/groupItem', 'common', 'transit', 'queryString' ], function($, _, Backbone, groupItems, groupItem, Common){ var GroupMenuView = Backbone.View.extend({ el: '#thumb-list', events: { 'click .close-btn' : 'onHide' }, speed: 500, isExpanded: false, initialize: function() { this.$list = $('.thumb-list ul', this.$el); this.$counter = $('.counter', this.$el); this.listenTo(groupItems, 'add', this.add); this.listenTo(groupItems, 'reset', Common.resetBoard); }, add: function( photo ) { var view = new groupItem({ model: photo }); this.$list.append( view.render().el ); }, setLength: function(num){ this.$counter.text(num); }, setActive: function(id){ var me = this; var item = groupItems.get(id); if(this.lastActive){ this.lastActive.trigger('inactive'); } if(item){ item.trigger('active'); this.lastActive = item; } }, toggle: function(){ if(this.isExpanded){ this.collapse(); }else{ this.expand(); } }, expand: function(){ var me = this; if(me.isAnimating){ return; } me.isAnimating = true; var height = me.$el.height(); me.$el.css({ bottom: -height }).show().stop().animate({ bottom:0 }, me.speed, function(){ me.isAnimating = false; me.isExpanded = true; }); }, collapse:function(){ var me = this; if(me.isAnimating){ return; } me.isAnimating = true; var height = me.$el.height(); me.$el.stop().animate({ bottom: -height }, me.speed, function(){ me.isAnimating = false; me.isExpanded = false; $(this).hide(); }); }, onHide: function(e){ e.preventDefault(); this.collapse(); }, destroy: function(){ this.lastActive = null; } }); return GroupMenuView; });
mit
eventEmitter/related-geo
lib/RelatedGeo.js
10466
!function() { 'use strict'; var Class = require('ee-class') , log = require('ee-log') , type = require('ee-types') , ORMExtension = require('related-extension') , distanceSelector = require('./DistanceSelector'); var thisContext , DistanceSelector , ORM; /** * search object in the distance of a * a set of coordiantes or inside a box * * distance = distanceFrom(lat, lng, maxDistance) * box = insideBox(latTop, lngLeft, latBottom, lngRight) * * */ module.exports = new Class({ inherits: ORMExtension // default values for the fieldnames // of the coordiantes , lat: ['lat', 'latitude'] , lng: ['lng', 'lon', 'long', 'longitude'] // offset to swith from query strategy A to B in meters , offsetRadius: 20000 // the plugins name , _name: 'related-geo' , init: function init(options) { init.super.call(this); // store this context so we'll have acces in some // methods attached to the model thisContext = this; // prepare the selector if (!DistanceSelector) DistanceSelector = distanceSelector(this); // make the selector available on the orm this.selectors.push(DistanceSelector); // the user may define the name of the fields if (options) { if (type.array(options.latColumns)) this.lat = options.latColumns.concat(this.lat); if (type.array(options.lngColumns)) this.lat = options.lngColumns.concat(this.lat); if (type.number(options.offsetRadius)) this.offsetRadius = options.offsetRadius; } // store the columns this.storage = {}; } /** * retuns the name of the lat column for a specif centity * * @param <String> entityName * * @returns <String> lat column name */ , getLatColumn: function(entityName) { if (!this.storage[entityName]) throw new Error('Cannot us the distanceFrom selector on the «'+entityName+'» entity, the extensions is not enabled on this entity!'); return this.storage[entityName].lat; } /** * retuns the name of the lng column for a specif centity * * @param <String> entityName * * @returns <String> lat column name */ , getLngColumn: function(entityName) { if (!this.storage[entityName]) throw new Error('Cannot us the distanceFrom selector on the «'+entityName+'» entity, the extensions is not enabled on this entity!'); return this.storage[entityName].lng; } /** * join a list of entites */ , _joinTree: function(queryBuilder, path) { if (path.length) { return this._joinTree(queryBuilder.join(path[0], true), path.slice(1)); } else { return { aliasName: queryBuilder.getresource().getAliasName() , entityName: queryBuilder.entityName } } } /* * we have to add our locale queries (sub selects) */ , onBeforePrepareSubqueries: function(resource, definition) { var query = resource.getQuery(); // find each instance of the distance selector, // check if its inside the filter, create a subquery // if yes query.select.forEach(function(selection) { if (selection instanceof DistanceSelector) { // check if the selector was applied to a subentity if (selection.subEntity) { // ued for moving stuff to other places selection.replacementEntityName = resource.queryBuilder.entityName; // join the path to the entity var result = this._joinTree(resource.queryBuilder, selection.subEntity); // needd to group by the primaries & the min of the seelection query.group.push(selection.alias); // group by primaries resource.groupByPrimaryKeys(); // tell the selection which entity to use selection.entityName = result.aliasName; selection.latColumn = this.getLatColumn(result.entityName); selection.lngColumn = this.getLngColumn(result.entityName); } else selection.replacementEntityName = selection.entityName; } }.bind(this)); } /* * we have to add our locale queries (sub selects) */ , onAfterPrepareSubqueries: function(resource, definition) { var query = resource.getQuery() , filter = query.filter , order = query.order , idsToRemove = [] , map = {} , subQuery; // find each instance of the distance selector, // check if its inside the filter, create a subquery // if yes query.select.forEach(function(selection) { if (selection instanceof DistanceSelector) { var entityName = selection.replacementEntityName; if (filter[entityName] && filter[entityName][selection.alias]) { // move filter to parent query if (!subQuery) subQuery = this.moveQuery(resource, query); // move filter if (!subQuery.filter.distanceQuery) subQuery.filter.distanceQuery = {}; subQuery.filter.distanceQuery[selection.alias] = filter[entityName][selection.alias]; delete filter[entityName][selection.alias]; } // order query.order.forEach(function(ordering, index) { if (ordering.entity === entityName && ordering.property === selection.alias) { idsToRemove.unshift(index); if (!subQuery) subQuery = this.moveQuery(resource, query); ordering.entity = 'distanceQuery'; ordering.fn = 'min'; subQuery.order.push(ordering); } }.bind(this)); idsToRemove.forEach(function(index) { query.order.splice(index, 1); }.bind(this)); } }.bind(this)); } /** * create a subquery */ , moveQuery: function(resource, query) { var subQuery = resource.createQuery(); subQuery.from = { query: query , alias: 'distanceQuery' }; if (query.limit) { subQuery.limit = query.limit; delete query.limit; } if (query.offset) { subQuery.offset = query.offset; delete query.offset; } let groupBy = []; let map = {}; let distanceSelection; // select all fields of the original query query.select.forEach((selection) => { if (!(type.function(selection.isRelatedSelector) && selection.isRelatedSelector() && selection.name === 'distanceFrom')) { if (selection.alias) { if (!map[selection.alias]) subQuery.select.push(resource.getORM().sum(selection.alias, selection.alias)); map[selection.alias] = true; } else if (selection.column) { if (!map[selection.column]) subQuery.select.push(selection.column); map[selection.column] = true; } else { if (!map[selection]) subQuery.select.push(selection); else query.select.splice(query.select.indexOf(selection), 1); map[selection] = true; } // when a selection has an alias we're not grouping by it, // we're returning the sum for it. if (!selection.alias) groupBy.push(selection); } else distanceSelection = selection; }); if (distanceSelection) { subQuery.select.push(resource.getORM().min(distanceSelection.alias, distanceSelection.alias)); } // group subQuery.group = subQuery.group.concat(groupBy); resource.setQuery(subQuery); return subQuery; } /** * called by the orm */ , onBeforePrepare: function(resource, definition) { this.onBeforePrepareSubqueries(resource, definition); } /** * called by the orm */ , onAfterPrepare: function(resource, definition) { this.onAfterPrepareSubqueries(resource, definition); } /* * checks if this extension should be applied to the * current model */ , useOnModel: function(definition) { var mappingDefinition , lat , lng; // check if the required fields are onthe tabel if (Object.keys(definition.columns).some(function(columnName) { if (!lat && this.lat.indexOf(columnName) >= 0) lat = columnName; if (!lng && this.lng.indexOf(columnName) >= 0) lng = columnName; return lat && lng; }.bind(this))) { this.storage[definition.getTableName()] = { lat: lat , lng: lng }; } return true; } }); }();
mit
todorm85/TelerikAcademy
Courses/Programming/Object-Orineted Programming/06.CTS/01. Student class/TEST.cs
2355
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Student_class { class Program { static void Main(string[] args) { bool result = false; int testNum = 0; Student st1 = new Student("Pe6o","Pe6ov", "Peshistia", "8514897589"); Student st2 = (Student)st1.Clone(); // deep copy student st1 to st2 Student st3 = new Student("Angel", "Yavorov", "Angelov", "123450"); st2.Ssn= (ulong.Parse(st2.Ssn) + 1).ToString(); // increase st2 ssn with 1 testNum = 1; int returned = st1.CompareTo(st2); result = (returned == -1) ? true : false; PrintResult(testNum, result); testNum = 2; st2.Ssn = (ulong.Parse(st2.Ssn) - 2).ToString(); returned = st1.CompareTo(st2); result = (returned == 1) ? true : false; PrintResult(testNum, result); testNum = 3; st2.Ssn = (ulong.Parse(st2.Ssn) + 1).ToString(); returned = st1.CompareTo(st2); result = (returned == 0) ? true : false; PrintResult(testNum, result); testNum = 4; returned = st1.CompareTo(st3); result = (returned == 1) ? true : false; PrintResult(testNum, result); testNum = 5; st2 = (Student)st1.Clone(); result = st1 == st2; PrintResult(testNum, result); testNum = 6; result = !(st1 == st3); PrintResult(testNum, result); testNum = 7; result = st1 != st3; PrintResult(testNum, result); testNum = 8; result = !(st1 != st2); PrintResult(testNum, result); testNum = 9; string resultStr = st1.ToString(); string expectedStr = "Pe6o Peshistia, SSN = 8514897589"; result = (resultStr == expectedStr) ? true : false; PrintResult(testNum, result); } static void PrintResult(int test, bool result, string message = "") { var delimiter = new String('-', 50); Console.WriteLine("{0}\nTest {1} passed: {2}{3}",delimiter,test,result,"\n"+message); } } }
mit
byronka/xenos
lib/lib_src/httpcomponents_source/httpcomponents-client-4.4/httpclient/src/main/java/org/apache/http/cookie/CookiePriorityComparator.java
2667
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.cookie; import java.util.Comparator; import java.util.Date; import org.apache.http.annotation.Immutable; import org.apache.http.impl.cookie.BasicClientCookie; /** * This cookie comparator ensures that cookies with longer paths take precedence over * cookies with shorter path. Among cookies with equal path length cookies with ealier * creation time take precedence over cookies with later creation time * * @since 4.4 */ @Immutable public class CookiePriorityComparator implements Comparator<Cookie> { public static final CookiePriorityComparator INSTANCE = new CookiePriorityComparator(); private int getPathLength(final Cookie cookie) { final String path = cookie.getPath(); return path != null ? path.length() : 1; } @Override public int compare(final Cookie c1, final Cookie c2) { final int l1 = getPathLength(c1); final int l2 = getPathLength(c2); //TODO: update this class once Cookie interface has been expended with #getCreationTime method final int result = l2 - l1; if (result == 0 && c1 instanceof BasicClientCookie && c2 instanceof BasicClientCookie) { final Date d1 = ((BasicClientCookie) c1).getCreationDate(); final Date d2 = ((BasicClientCookie) c2).getCreationDate(); if (d1 != null && d2 != null) { return (int) (d1.getTime() - d2.getTime()); } } return result; } }
mit
DragomirPetrov/TelerikAcademy
C #/C# Part 1/02.Data-Types-and-Variables/12.PrintTheASCIITable/Properties/AssemblyInfo.cs
1418
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("12.PrintTheASCIITable")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12.PrintTheASCIITable")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("44f13c34-742c-48ca-8d1b-e9906ceeadc3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
lozjackson/ember-ui-components
addon/components/uic-menu-container.js
1604
/** @module ember-ui-components */ import Component from '@ember/component'; import layout from '../templates/components/uic-menu-container'; import getDimensions from 'ember-ui-components/utils/get-dimensions'; import calculatePosition from 'ember-ui-components/utils/calculate-position'; /** @class MenuContainerComponent @namespace Components */ export default Component.extend({ layout, /** @property classNames @type {Array} @private @default `['uic-menu-container']` */ classNames: ['uic-menu-container'], /** @method getParentMenu @private @return {Object} */ getParentMenu() { return this.$().parents('.uic-menu-container'); }, /** @method didInsertMenu @private */ didInsertMenu() { let element = this.$(); let el = getDimensions(element); let windowHeight = window.innerHeight || document.documentElement.clientHeight; let windowWidth = window.innerWidth || document.documentElement.clientWidth; let rect; let parent = this.getParentMenu(); let css = { top: calculatePosition( element.position().top, el.height, windowHeight - 5) }; if (element) { rect = element[0].getBoundingClientRect(); if (rect.right > windowWidth && parent.offset()) { css.left = (element.css('position') === 'fixed') ? (parent.offset().left - el.width) + 15 : (el.width + parent.width() - 45) * -1; } element.css(css); } }, /** @event didInsertElement @private */ didInsertElement() { this._super(...arguments); this.didInsertMenu(); } });
mit
steveoro/goggles_core
spec/factories/data_import_season.rb
632
# frozen_string_literal: true require 'date' require 'ffaker' FactoryBot.define do factory :data_import_season do data_import_session conflicting_id { nil } import_text { FFaker::Lorem.paragraph[0..200] } random_season # Trait defined in factories/seasons.rb # Make the circular reference between the session and the # season valid: after(:create) do |created_instance, _evaluator| created_instance.data_import_session.data_import_season_id = created_instance.id end end #-- ------------------------------------------------------------------------- #++ end
mit
goldenloaf/goldenloaf-master
src/version.cpp
2633
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-GLY" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "54fd5f3" # define GIT_COMMIT_DATE "Tue, 8 Apr 2014 02:09:55 -0700" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
mit
anikdas/generator-xprscouch
model/index.js
1310
'use strict'; var fs = require('fs-extra'); var generators = require('yeoman-generator'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); // This makes `appname` a required argument. try { this.argument('modelName', { type: String, required: true }); this.argument('databaseName', { type: String, required: false }); this.option('init'); } catch (e) { console.log('Error: model name not provided'); process.exit(1); } // And you can then access it later on this way; e.g. CamelCased }, createBase: function () { var g = this; var modelName = g.modelName; var databaseName = g.databaseName ? g.databaseName: modelName; console.log('creating model ' + modelName); fs.exists(g.destinationPath('models/'+modelName+'.js'), function (exists) { if(exists){ console.log(modelName+'.js aredy exists.'); }else{ g.fs.copyTpl( g.templatePath('index.js'), g.destinationPath('models/'+modelName+'.js'), { database: databaseName} ); } }); } });
mit
jedld/pretentious
spec/generated/fibonacci_spec.rb
964
# This file was automatically generated by the pretentious gem require 'spec_helper' RSpec.describe Fibonacci do context 'Scenario 1' do before do @fixture = Fibonacci.new end it 'should pass current expectations' do n = 1 n_1 = 2 n_2 = 3 n_3 = 4 n_4 = 5 # Fibonacci#fib when passed n = 1 should return 1 expect(@fixture.fib(n)).to eq(n) # Fibonacci#fib when passed n = 2 should return 1 expect(@fixture.fib(n_1)).to eq(n) # Fibonacci#fib when passed n = 3 should return 2 expect(@fixture.fib(n_2)).to eq(n_1) # Fibonacci#fib when passed n = 4 should return 3 expect(@fixture.fib(n_3)).to eq(n_2) # Fibonacci#fib when passed n = 5 should return 5 expect(@fixture.fib(n_4)).to eq(n_4) end end it 'should pass current expectations' do # Fibonacci::say_hello should return 'hello' expect(Fibonacci.say_hello).to eq('hello') end end
mit
lordmos/blink
Source/core/svg/SVGAElement.cpp
8163
/* * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <[email protected]> * Copyright (C) 2004, 2005, 2007 Rob Buis <[email protected]> * Copyright (C) 2007 Eric Seidel <[email protected]> * Copyright (C) 2010 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/svg/SVGAElement.h" #include "SVGNames.h" #include "XLinkNames.h" #include "core/dom/Attr.h" #include "core/dom/Attribute.h" #include "core/dom/Document.h" #include "core/events/KeyboardEvent.h" #include "core/events/MouseEvent.h" #include "core/events/ThreadLocalEventNames.h" #include "core/frame/Frame.h" #include "core/html/HTMLAnchorElement.h" #include "core/html/HTMLFormElement.h" #include "core/html/parser/HTMLParserIdioms.h" #include "core/loader/FrameLoadRequest.h" #include "core/loader/FrameLoader.h" #include "core/loader/FrameLoaderTypes.h" #include "core/page/Chrome.h" #include "core/page/ChromeClient.h" #include "core/page/Page.h" #include "core/rendering/svg/RenderSVGInline.h" #include "core/rendering/svg/RenderSVGText.h" #include "core/rendering/svg/RenderSVGTransformableContainer.h" #include "core/svg/SVGElementInstance.h" #include "core/svg/animation/SVGSMILElement.h" #include "platform/PlatformMouseEvent.h" #include "platform/network/ResourceRequest.h" namespace WebCore { using namespace HTMLNames; // Animated property definitions DEFINE_ANIMATED_STRING(SVGAElement, SVGNames::targetAttr, SVGTarget, svgTarget) DEFINE_ANIMATED_STRING(SVGAElement, XLinkNames::hrefAttr, Href, href) DEFINE_ANIMATED_BOOLEAN(SVGAElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAElement) REGISTER_LOCAL_ANIMATED_PROPERTY(svgTarget) REGISTER_LOCAL_ANIMATED_PROPERTY(href) REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement) END_REGISTER_ANIMATED_PROPERTIES inline SVGAElement::SVGAElement(Document& document) : SVGGraphicsElement(SVGNames::aTag, document) { ScriptWrappable::init(this); registerAnimatedPropertiesForSVGAElement(); } PassRefPtr<SVGAElement> SVGAElement::create(Document& document) { return adoptRef(new SVGAElement(document)); } String SVGAElement::title() const { // If the xlink:title is set (non-empty string), use it. const AtomicString& title = fastGetAttribute(XLinkNames::titleAttr); if (!title.isEmpty()) return title; // Otherwise, use the title of this element. return SVGElement::title(); } bool SVGAElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGURIReference::addSupportedAttributes(supportedAttributes); SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::targetAttr); } return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); } void SVGAElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (!isSupportedAttribute(name)) { SVGGraphicsElement::parseAttribute(name, value); return; } if (name == SVGNames::targetAttr) { setSVGTargetBaseValue(value); return; } if (SVGURIReference::parseAttribute(name, value)) return; if (SVGExternalResourcesRequired::parseAttribute(name, value)) return; ASSERT_NOT_REACHED(); } void SVGAElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGGraphicsElement::svgAttributeChanged(attrName); return; } SVGElementInstance::InvalidationGuard invalidationGuard(this); // Unlike other SVG*Element classes, SVGAElement only listens to SVGURIReference changes // as none of the other properties changes the linking behaviour for our <a> element. if (SVGURIReference::isKnownAttribute(attrName)) { bool wasLink = isLink(); setIsLink(!hrefCurrentValue().isNull()); if (wasLink != isLink()) setNeedsStyleRecalc(); } } RenderObject* SVGAElement::createRenderer(RenderStyle*) { if (parentNode() && parentNode()->isSVGElement() && toSVGElement(parentNode())->isTextContent()) return new RenderSVGInline(this); return new RenderSVGTransformableContainer(this); } void SVGAElement::defaultEventHandler(Event* event) { if (isLink()) { if (focused() && isEnterKeyKeydownEvent(event)) { event->setDefaultHandled(); dispatchSimulatedClick(event); return; } if (isLinkClick(event)) { String url = stripLeadingAndTrailingHTMLSpaces(hrefCurrentValue()); if (url[0] == '#') { Element* targetElement = treeScope().getElementById(url.substring(1)); if (targetElement && isSVGSMILElement(*targetElement)) { toSVGSMILElement(targetElement)->beginByLinkActivation(); event->setDefaultHandled(); return; } // Only allow navigation to internal <view> anchors. if (targetElement && !targetElement->hasTagName(SVGNames::viewTag)) return; } String target = this->target(); if (target.isEmpty() && fastGetAttribute(XLinkNames::showAttr) == "new") target = "_blank"; event->setDefaultHandled(); Frame* frame = document().frame(); if (!frame) return; FrameLoadRequest frameRequest(&document(), ResourceRequest(document().completeURL(url)), target); frameRequest.setTriggeringEvent(event); frame->loader().load(frameRequest); return; } } SVGGraphicsElement::defaultEventHandler(event); } bool SVGAElement::supportsFocus() const { if (rendererIsEditable()) return SVGGraphicsElement::supportsFocus(); return true; } bool SVGAElement::rendererIsFocusable() const { if (renderer() && renderer()->absoluteClippedOverflowRect().isEmpty()) return false; return SVGElement::rendererIsFocusable(); } bool SVGAElement::isURLAttribute(const Attribute& attribute) const { return attribute.name().localName() == hrefAttr || SVGGraphicsElement::isURLAttribute(attribute); } bool SVGAElement::isMouseFocusable() const { return false; } bool SVGAElement::isKeyboardFocusable() const { if (!isFocusable()) return false; if (Page* page = document().page()) return page->chrome().client().tabsToLinks(); return false; } bool SVGAElement::childShouldCreateRenderer(const Node& child) const { // http://www.w3.org/2003/01/REC-SVG11-20030114-errata#linking-text-environment // The 'a' element may contain any element that its parent may contain, except itself. if (child.hasTagName(SVGNames::aTag)) return false; if (parentNode() && parentNode()->isSVGElement()) return parentNode()->childShouldCreateRenderer(child); return SVGElement::childShouldCreateRenderer(child); } bool SVGAElement::willRespondToMouseClickEvents() { return isLink() || SVGGraphicsElement::willRespondToMouseClickEvents(); } } // namespace WebCore
mit
reidlai/slush-fullstack-framework
templates/redux-react/src/index.js
921
import React from 'react' import ReactDOM from 'react-dom' import injectTapEventPlugin from 'react-tap-event-plugin' import {createStore, applyMiddleware} from 'redux' import {Provider} from 'react-redux' import thunk from 'redux-thunk' import reduxLogger from 'redux-logger' import MainComponent from './react-components/MainComponent.jsx' import 'normalize-css' import './stylesheets/index.scss' import {reduxActions, reduxReducers} from './redux-modules' const StoreProvider = Provider // create redux store let store = createStore(reduxReducers, applyMiddleware(thunk, reduxLogger)) // set store and dispatch as global variables window.store = store window.dispatch = store.dispatch // optional, capture tap event in mobile injectTapEventPlugin() // Main React Component ReactDOM.render( <StoreProvider store={store}> <MainComponent></MainComponent> </StoreProvider>, document.getElementById('root') )
mit
andela-ieyo/docify
client/utils/roles.js
262
export const Roles = { Writer : 1, Editor: 2, Admin: 3 }; export const chooseTitle = (id) => { let title; if (id === 3) { title = 'Admin'; return title; } if (id === 2) { title = 'Editor'; return title; } return 'Writer'; };
mit
deepak1556/brightray
browser/browser_client.cc
3155
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "browser/browser_client.h" #include "browser/browser_context.h" #include "browser/browser_main_parts.h" #include "browser/devtools_manager_delegate.h" #include "browser/media/media_capture_devices_dispatcher.h" #include "browser/notification_presenter.h" #include "base/base_paths.h" #include "base/path_service.h" #include "content/public/common/url_constants.h" namespace brightray { namespace { BrowserClient* g_browser_client; } BrowserClient* BrowserClient::Get() { return g_browser_client; } BrowserClient::BrowserClient() : browser_main_parts_() { DCHECK(!g_browser_client); g_browser_client = this; } BrowserClient::~BrowserClient() { } BrowserContext* BrowserClient::browser_context() { return browser_main_parts_->browser_context(); } NotificationPresenter* BrowserClient::notification_presenter() { #if defined(OS_MACOSX) || defined(OS_LINUX) if (!notification_presenter_) notification_presenter_.reset(NotificationPresenter::Create()); #endif return notification_presenter_.get(); } BrowserMainParts* BrowserClient::OverrideCreateBrowserMainParts( const content::MainFunctionParams&) { return new BrowserMainParts; } content::BrowserMainParts* BrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { DCHECK(!browser_main_parts_); browser_main_parts_ = OverrideCreateBrowserMainParts(parameters); return browser_main_parts_; } net::URLRequestContextGetter* BrowserClient::CreateRequestContext( content::BrowserContext* browser_context, content::ProtocolHandlerMap* protocol_handlers, content::URLRequestInterceptorScopedVector protocol_interceptors) { auto context = static_cast<BrowserContext*>(browser_context); return context->CreateRequestContext(protocol_handlers, protocol_interceptors.Pass()); } void BrowserClient::ShowDesktopNotification( const content::ShowDesktopNotificationHostMsgParams& params, content::BrowserContext* browser_context, int render_process_id, scoped_ptr<content::DesktopNotificationDelegate> delegate, base::Closure* cancel_callback) { auto presenter = notification_presenter(); if (presenter) presenter->ShowNotification(params, delegate.Pass(), cancel_callback); } content::MediaObserver* BrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } void BrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } base::FilePath BrowserClient::GetDefaultDownloadDirectory() { // ~/Downloads base::FilePath path; if (PathService::Get(base::DIR_HOME, &path)) path = path.Append(FILE_PATH_LITERAL("Downloads")); return path; } content::DevToolsManagerDelegate* BrowserClient::GetDevToolsManagerDelegate() { return new DevToolsManagerDelegate; } } // namespace brightray
mit
plato721/lights-out
lib/hint.js
682
var move = require('./next-move'); function Hint(game) { this.game = game; this.hintLit = false; this.hintLight; } Hint.prototype.showHint = function(board) { var nextMove = move.forBoard(this.game.board) this.game.score.cheat(); if(this.game.gameIsLost()) { this.game.processLoss(); return; } this.hintLight = this.game.board.lightGrid[nextMove[0]][nextMove[1]]; this.hintLit = true; this.hintLight.flipHinted().rerender(); this.game.displayMessage.showScore(this.game.score.points); }; Hint.prototype.clearHint = function() { if(this.hintLit) { this.hintLight.flipHinted().rerender(); this.hintLit = false; } } module.exports = Hint;
mit
mrbase/Smesg
tests/bootstrap.php
312
<?php /** * This file is part of the Smesg package. * * (c) Ulrik Nielsen <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once __DIR__.'/Smesg/TestCase.php'; require_once __DIR__.'/autoloader.php';
mit
Anastaszor/Cachalot
interfaces/ITranslator.php
164
<?php /** * ITranslator interface file. * * @author Anastaszor */ interface ITranslator { public function translate($message, $language); }
mit
LePhil/DotNetMiniProj
AutoReservation.Ui/Factory/LocalDataAccessServiceFactory.cs
331
using AutoReservation.Common.Interfaces; using AutoReservation.Service.Wcf; namespace AutoReservation.Ui.Factory { public class LocalDataAccessServiceFactory: IServiceFactory { public IAutoReservationService GetService() { return new AutoReservationService(); } } }
mit
kogceweb/knowledgeduty
src/main/java/com/knowladgeduty/service/TaxExceptionsService.java
779
package com.knowladgeduty.service; import java.util.Date; import java.util.List; import com.knowladgeduty.model.TaxExceptions; public interface TaxExceptionsService extends AbstractService<TaxExceptions, Long> { TaxExceptions findByCode(String code); void deleteAllTaxExceptions(List<TaxExceptions> taxes); List<TaxExceptions> findByTaxGtipCode(String gtipCode); List<TaxExceptions> findByTaxGtipCodeStartsWith(String gtipCode); List<TaxExceptions> findTaxesByGtipRegex(String item); TaxExceptions findByTaxGtipCodeAndTillIsNull(String gtipCode); TaxExceptions findByTaxGtipCodeAndSinceLessThanEqualAndTillIsNull(String gtipCode,Date start); List<TaxExceptions> findByTaxGtipCodeStartsWithAndSinceLessThanEqualAndTillIsNull(String gtipCode,Date start); }
mit
lukasgeiter/laravel-framework
tests/Http/HttpRequestTest.php
14960
<?php use Mockery as m; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class HttpRequestTest extends PHPUnit_Framework_TestCase { public function tearDown() { m::close(); } public function testInstanceMethod() { $request = Request::create('', 'GET'); $this->assertSame($request, $request->instance()); } public function testRootMethod() { $request = Request::create('http://example.com/foo/bar/script.php?test'); $this->assertEquals('http://example.com', $request->root()); } public function testPathMethod() { $request = Request::create('', 'GET'); $this->assertEquals('/', $request->path()); $request = Request::create('/foo/bar', 'GET'); $this->assertEquals('foo/bar', $request->path()); } public function testDecodedPathMethod() { $request = Request::create('/foo%20bar'); $this->assertEquals('foo bar', $request->decodedPath()); } /** * @dataProvider segmentProvider */ public function testSegmentMethod($path, $segment, $expected) { $request = Request::create($path, 'GET'); $this->assertEquals($expected, $request->segment($segment, 'default')); } public function segmentProvider() { return array( array('', 1, 'default'), array('foo/bar//baz', '1', 'foo'), array('foo/bar//baz', '2', 'bar'), array('foo/bar//baz', '3', 'baz'), ); } /** * @dataProvider segmentsProvider */ public function testSegmentsMethod($path, $expected) { $request = Request::create($path, 'GET'); $this->assertEquals($expected, $request->segments()); $request = Request::create('foo/bar', 'GET'); $this->assertEquals(array('foo', 'bar'), $request->segments()); } public function segmentsProvider() { return array( array('', array()), array('foo/bar', array('foo', 'bar')), array('foo/bar//baz', array('foo', 'bar', 'baz')), array('foo/0/bar', array('foo', '0', 'bar')), ); } public function testUrlMethod() { $request = Request::create('http://foo.com/foo/bar?name=taylor', 'GET'); $this->assertEquals('http://foo.com/foo/bar', $request->url()); $request = Request::create('http://foo.com/foo/bar/?', 'GET'); $this->assertEquals('http://foo.com/foo/bar', $request->url()); } public function testFullUrlMethod() { $request = Request::create('http://foo.com/foo/bar?name=taylor', 'GET'); $this->assertEquals('http://foo.com/foo/bar?name=taylor', $request->fullUrl()); $request = Request::create('https://foo.com', 'GET'); $this->assertEquals('https://foo.com', $request->fullUrl()); } public function testIsMethod() { $request = Request::create('/foo/bar', 'GET'); $this->assertTrue($request->is('foo*')); $this->assertFalse($request->is('bar*')); $this->assertTrue($request->is('*bar*')); $this->assertTrue($request->is('bar*', 'foo*', 'baz')); $request = Request::create('/', 'GET'); $this->assertTrue($request->is('/')); } public function testAjaxMethod() { $request = Request::create('/', 'GET'); $this->assertFalse($request->ajax()); $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'), '{}'); $this->assertTrue($request->ajax()); $request = Request::create('/', 'POST'); $request->headers->set('X-Requested-With', 'XMLHttpRequest'); $this->assertTrue($request->ajax()); $request->headers->set('X-Requested-With', ''); $this->assertFalse($request->ajax()); } public function testPjaxMethod() { $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_X_PJAX' => 'true'), '{}'); $this->assertTrue($request->pjax()); $request->headers->set('X-PJAX', 'false'); $this->assertTrue($request->pjax()); $request->headers->set('X-PJAX', null); $this->assertFalse($request->pjax()); $request->headers->set('X-PJAX', ''); $this->assertFalse($request->pjax()); } public function testSecureMethod() { $request = Request::create('http://example.com', 'GET'); $this->assertFalse($request->secure()); $request = Request::create('https://example.com', 'GET'); $this->assertTrue($request->secure()); } public function testExistsMethod() { $request = Request::create('/', 'GET', ['name' => 'Taylor']); $this->assertTrue($request->exists('name')); $this->assertFalse($request->exists('foo')); $this->assertFalse($request->exists('name', 'email')); $request = Request::create('/', 'GET', ['name' => 'Taylor', 'email' => 'foo']); $this->assertTrue($request->exists('name')); $this->assertTrue($request->exists('name', 'email')); $request = Request::create('/', 'GET', ['foo' => ['bar', 'bar']]); $this->assertTrue($request->exists('foo')); $request = Request::create('/', 'GET', ['foo' => '', 'bar' => null]); $this->assertTrue($request->exists('foo')); $this->assertTrue($request->exists('bar')); } public function testHasMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor')); $this->assertTrue($request->has('name')); $this->assertFalse($request->has('foo')); $this->assertFalse($request->has('name', 'email')); $request = Request::create('/', 'GET', array('name' => 'Taylor', 'email' => 'foo')); $this->assertTrue($request->has('name')); $this->assertTrue($request->has('name', 'email')); //test arrays within query string $request = Request::create('/', 'GET', array('foo' => array('bar', 'baz'))); $this->assertTrue($request->has('foo')); } public function testInputMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor')); $this->assertEquals('Taylor', $request->input('name')); $this->assertEquals('Taylor', $request['name']); $this->assertEquals('Bob', $request->input('foo', 'Bob')); $request = Request::create('/', 'GET', [], [], ['file' => new Symfony\Component\HttpFoundation\File\UploadedFile(__FILE__, 'foo.php')]); $this->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $request['file']); } public function testOnlyMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor', 'age' => 25)); $this->assertEquals(array('age' => 25), $request->only('age')); $this->assertEquals(array('name' => 'Taylor', 'age' => 25), $request->only('name', 'age')); $request = Request::create('/', 'GET', array('developer' => array('name' => 'Taylor', 'age' => 25))); $this->assertEquals(array('developer' => array('age' => 25)), $request->only('developer.age')); $this->assertEquals(array('developer' => array('name' => 'Taylor'), 'test' => null), $request->only('developer.name', 'test')); } public function testExceptMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor', 'age' => 25)); $this->assertEquals(array('name' => 'Taylor'), $request->except('age')); $this->assertEquals(array(), $request->except('age', 'name')); } public function testQueryMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor')); $this->assertEquals('Taylor', $request->query('name')); $this->assertEquals('Bob', $request->query('foo', 'Bob')); $all = $request->query(null); $this->assertEquals('Taylor', $all['name']); } public function testCookieMethod() { $request = Request::create('/', 'GET', array(), array('name' => 'Taylor')); $this->assertEquals('Taylor', $request->cookie('name')); $this->assertEquals('Bob', $request->cookie('foo', 'Bob')); $all = $request->cookie(null); $this->assertEquals('Taylor', $all['name']); } public function testHasCookieMethod() { $request = Request::create('/', 'GET', array(), array('foo' => 'bar')); $this->assertTrue($request->hasCookie('foo')); $this->assertFalse($request->hasCookie('qu')); } public function testFileMethod() { $files = array( 'foo' => array( 'size' => 500, 'name' => 'foo.jpg', 'tmp_name' => __FILE__, 'type' => 'blah', 'error' => null, ), ); $request = Request::create('/', 'GET', array(), array(), $files); $this->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $request->file('foo')); } public function testHasFileMethod() { $request = Request::create('/', 'GET', array(), array(), array()); $this->assertFalse($request->hasFile('foo')); $files = array( 'foo' => array( 'size' => 500, 'name' => 'foo.jpg', 'tmp_name' => __FILE__, 'type' => 'blah', 'error' => null, ), ); $request = Request::create('/', 'GET', array(), array(), $files); $this->assertTrue($request->hasFile('foo')); } public function testServerMethod() { $request = Request::create('/', 'GET', array(), array(), array(), array('foo' => 'bar')); $this->assertEquals('bar', $request->server('foo')); $this->assertEquals('bar', $request->server('foo.doesnt.exist', 'bar')); $all = $request->server(null); $this->assertEquals('bar', $all['foo']); } public function testMergeMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor')); $merge = array('buddy' => 'Dayle'); $request->merge($merge); $this->assertEquals('Taylor', $request->input('name')); $this->assertEquals('Dayle', $request->input('buddy')); } public function testReplaceMethod() { $request = Request::create('/', 'GET', array('name' => 'Taylor')); $replace = array('buddy' => 'Dayle'); $request->replace($replace); $this->assertNull($request->input('name')); $this->assertEquals('Dayle', $request->input('buddy')); } public function testHeaderMethod() { $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_DO_THIS' => 'foo')); $this->assertEquals('foo', $request->header('do-this')); $all = $request->header(null); $this->assertEquals('foo', $all['do-this'][0]); } public function testJSONMethod() { $payload = array('name' => 'taylor'); $request = Request::create('/', 'GET', array(), array(), array(), array('CONTENT_TYPE' => 'application/json'), json_encode($payload)); $this->assertEquals('taylor', $request->json('name')); $this->assertEquals('taylor', $request->input('name')); $data = $request->json()->all(); $this->assertEquals($payload, $data); } public function testJSONEmulatingPHPBuiltInServer() { $payload = array('name' => 'taylor'); $content = json_encode($payload); // The built in PHP 5.4 webserver incorrectly provides HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH, // rather than CONTENT_TYPE and CONTENT_LENGTH $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_CONTENT_TYPE' => 'application/json', 'HTTP_CONTENT_LENGTH' => strlen($content)), $content); $this->assertTrue($request->isJson()); $data = $request->json()->all(); $this->assertEquals($payload, $data); $data = $request->all(); $this->assertEquals($payload, $data); } public function testAllInputReturnsInputAndFiles() { $file = $this->getMock('Symfony\Component\HttpFoundation\File\UploadedFile', null, array(__FILE__, 'photo.jpg')); $request = Request::create('/?boom=breeze', 'GET', array('foo' => 'bar'), array(), array('baz' => $file)); $this->assertEquals(array('foo' => 'bar', 'baz' => $file, 'boom' => 'breeze'), $request->all()); } public function testAllInputReturnsNestedInputAndFiles() { $file = $this->getMock('Symfony\Component\HttpFoundation\File\UploadedFile', null, array(__FILE__, 'photo.jpg')); $request = Request::create('/?boom=breeze', 'GET', array('foo' => array('bar' => 'baz')), array(), array('foo' => array('photo' => $file))); $this->assertEquals(array('foo' => array('bar' => 'baz', 'photo' => $file), 'boom' => 'breeze'), $request->all()); } public function testAllInputReturnsInputAfterReplace() { $request = Request::create('/?boom=breeze', 'GET', array('foo' => array('bar' => 'baz'))); $request->replace(array('foo' => array('bar' => 'baz'), 'boom' => 'breeze')); $this->assertEquals(array('foo' => array('bar' => 'baz'), 'boom' => 'breeze'), $request->all()); } public function testAllInputWithNumericKeysReturnsInputAfterReplace() { $request1 = Request::create('/', 'POST', array(0 => 'A', 1 => 'B', 2 => 'C')); $request1->replace(array(0 => 'A', 1 => 'B', 2 => 'C')); $this->assertEquals(array(0 => 'A', 1 => 'B', 2 => 'C'), $request1->all()); $request2 = Request::create('/', 'POST', array(1 => 'A', 2 => 'B', 3 => 'C')); $request2->replace(array(1 => 'A', 2 => 'B', 3 => 'C')); $this->assertEquals(array(1 => 'A', 2 => 'B', 3 => 'C'), $request2->all()); } public function testInputWithEmptyFilename() { $invalidFiles = [ 'file' => [ 'name' => null, 'type' => null, 'tmp_name' => null, 'error' => 4, 'size' => 0 ] ]; $baseRequest = SymfonyRequest::create('/?boom=breeze', 'GET', array('foo' => array('bar' => 'baz')), array(), $invalidFiles); $request = Request::createFromBase($baseRequest); } public function testOldMethodCallsSession() { $request = Request::create('/', 'GET'); $session = m::mock('Illuminate\Session\Store'); $session->shouldReceive('getOldInput')->once()->with('foo', 'bar')->andReturn('boom'); $request->setSession($session); $this->assertEquals('boom', $request->old('foo', 'bar')); } public function testFlushMethodCallsSession() { $request = Request::create('/', 'GET'); $session = m::mock('Illuminate\Session\Store'); $session->shouldReceive('flashInput')->once(); $request->setSession($session); $request->flush(); } public function testFormatReturnsAcceptableFormat() { $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'application/json')); $this->assertEquals('json', $request->format()); $this->assertTrue($request->wantsJson()); $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'application/atom+xml')); $this->assertEquals('atom', $request->format()); $this->assertFalse($request->wantsJson()); $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'is/not/known')); $this->assertEquals('html', $request->format()); $this->assertEquals('foo', $request->format('foo')); } public function testSessionMethod() { $this->setExpectedException('RuntimeException'); $request = Request::create('/', 'GET'); $request->session(); } public function testUserResolverMakesUserAvailableAsMagicProperty() { $request = Request::create('/', 'GET', array(), array(), array(), array('HTTP_ACCEPT' => 'application/json')); $request->setUserResolver(function() { return 'user'; }); $this->assertEquals('user', $request->user()); } public function testCreateFromBase() { $body = [ 'foo' => 'bar', 'baz' => ['qux'], ]; $server = array( 'CONTENT_TYPE' => 'application/json', ); $base = SymfonyRequest::create('/', 'GET', array(), array(), array(), $server, json_encode($body)); $request = Request::createFromBase($base); $this->assertEquals($request->request->all(), $body); } }
mit
nwin/chatIRC
src/con/net.rs
3098
use std::io::net::ip::{SocketAddr, Ipv4Addr, Ipv6Addr}; use libc::{size_t, malloc, sockaddr, sockaddr_in, sockaddr_in6, in_addr, in6_addr, c_int, c_char, socklen_t, AF_INET, AF_INET6}; use std::mem::{size_of, transmute}; use std::string; /* const char * inet_ntop(int af, const void * restrict src, char * restrict dst, socklen_t size); */ extern { fn getnameinfo(sa: *const sockaddr, salen: socklen_t, host: *mut c_char, hostlen: socklen_t, serv: *mut c_char, servlen: socklen_t, flags: c_int) -> c_int; } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] fn new_sockaddr_in(port: u16, addr: in_addr) -> sockaddr_in { sockaddr_in { sin_family: AF_INET as u16, sin_port: port, sin_addr: addr, sin_zero: [0, ..8] } } #[cfg(target_os = "macos")] fn new_sockaddr_in(port: u16, addr: in_addr) -> sockaddr_in { sockaddr_in { sin_len: size_of::<sockaddr_in>() as u8, sin_family: AF_INET as u8, sin_port: port, sin_addr: addr, sin_zero: [0, ..8] } } #[cfg(target_os = "linux")] #[cfg(target_os = "android")] fn new_sockaddr_in6(port: u16, addr: in6_addr) -> sockaddr_in6 { sockaddr_in6 { sin6_family: AF_INET6 as u16, sin6_port: port, sin6_flowinfo: 0, sin6_addr: addr, sin6_scope_id: 0, } } #[cfg(target_os = "macos")] fn new_sockaddr_in6(port: u16, addr: in6_addr) -> sockaddr_in6 { sockaddr_in6 { sin6_len: size_of::<sockaddr_in6>() as u8, sin6_family: AF_INET6 as u8, sin6_port: port, sin6_flowinfo: 0, sin6_addr: addr, sin6_scope_id: 0, } } //static NI_NUMERICHOST: c_int = 0x00000002; //static NI_NAMEREQD: c_int = 0x00000004; /// Returns the hostname for an ip address /// TODO: make this safe, see manpage pub fn get_nameinfo(peer_socket: SocketAddr) -> String { let SocketAddr { ip, port } = peer_socket; let buf: *mut i8; let _ = unsafe { let hostlen = 80; buf = transmute(malloc(hostlen as size_t + 1)); match ip { Ipv4Addr(a, b, c, d) => { let addr = in_addr { s_addr: a as u32 << 24 | b as u32 << 16 | c as u32 << 8 | d as u32 }; let sockaddr = new_sockaddr_in(port, addr); getnameinfo(transmute(&sockaddr), size_of::<sockaddr_in>() as socklen_t, buf, hostlen, transmute(0u), 0, 0) }, Ipv6Addr(a, b, c, d, e, f, g, h) => { let addr = in6_addr { s6_addr: [a, b, c, d, e, f, g, h] }; let sockaddr = new_sockaddr_in6(port, addr); getnameinfo(transmute(&sockaddr), size_of::<sockaddr_in6>() as socklen_t, buf, hostlen, transmute(0u), 0, 0) }, } }; unsafe {string::raw::from_buf(transmute(buf))} }
mit
TheProjecter/tgb-box2d-integration
Cpp/Box2D/Joints/Box2dJointRef.cc
12478
//============================================================================= // Box2dJointRef.cc //============================================================================= /* TGB-Box2D-Integration (http://code.google.com/p/tgb-box2d-integration/) Copyright (c) 2009 Michael Woerister 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 "./Box2dJointRef.h" #include "platform/platform.h" #include "../Box2dBodyRef.h" #include "../Box2dUtil.h" #include "./Box2dJointEdgeRef.h" IMPLEMENT_CONOBJECT(Box2dJointRef); //=---------------------------------------------------------------------------- // Box2dJointRef::Box2dJointRef() //=---------------------------------------------------------------------------- Box2dJointRef::Box2dJointRef(): mJoint( NULL ), mUserData( NULL ) { DEBUG_INC( Box2dJointRefsCreated ); mJointEdgeRefs[0] = NULL; mJointEdgeRefs[1] = NULL; } //=---------------------------------------------------------------------------- // Box2dJointRef::~Box2dJointRef() //=---------------------------------------------------------------------------- Box2dJointRef::~Box2dJointRef() { DEBUG_INC( Box2dJointRefsDestroyed ); } //=---------------------------------------------------------------------------- // Box2dJointRef::getType() //=---------------------------------------------------------------------------- b2JointType Box2dJointRef::getType() const { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getType() - No b2Joint referenced." ); return this->mJoint->GetType(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getType() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getType, const char*, 2, 2, "" ) { char *returnBuffer = Con::getReturnBuffer( 16 ); dStrcpy( returnBuffer, Box2dJointRef::getJointTypeName( object->getType() ) ); return returnBuffer; } //=---------------------------------------------------------------------------- // Box2dJointRef::getBody1() //=---------------------------------------------------------------------------- Box2dBodyRef* Box2dJointRef::getBody1() { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getBody1() - No b2Joint referenced." ); b2Body *body = this->mJoint->GetBody1(); return body ? static_cast<Box2dBodyRef*>( body->GetUserData() ) : NULL; } //=---------------------------------------------------------------------------- // Box2dJointRef::getBody1() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getBody1, S32, 2, 2, "" ) { AssertFatal( object->getBody1() != NULL, "" ); return object->getBody1()->getId(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getBody2() //=---------------------------------------------------------------------------- Box2dBodyRef* Box2dJointRef::getBody2() { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getBody2() - No b2Joint referenced." ); b2Body *body = this->mJoint->GetBody2(); return body ? static_cast<Box2dBodyRef*>( body->GetUserData() ) : NULL; } //=---------------------------------------------------------------------------- // Box2dJointRef::getBody2() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getBody2, S32, 2, 2, "" ) { AssertFatal( object->getBody2() != NULL, "" ); return object->getBody2()->getId(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getAnchor1() //=---------------------------------------------------------------------------- b2Vec2 Box2dJointRef::getAnchor1() const { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getAnchor1() - No b2Joint referenced." ); return this->mJoint->GetAnchor1(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getAnchor1() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getAnchor1, const char*, 2, 2, "" ) { return Box2dUtil::b2Vec2ToReturnBuffer( object->getAnchor1() ); } //=---------------------------------------------------------------------------- // Box2dJointRef::getAnchor2() //=---------------------------------------------------------------------------- b2Vec2 Box2dJointRef::getAnchor2() const { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getAnchor2() - No b2Joint referenced." ); return this->mJoint->GetAnchor2(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getAnchor2() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getAnchor2, const char*, 2, 2, "" ) { return Box2dUtil::b2Vec2ToReturnBuffer( object->getAnchor2() ); } //=---------------------------------------------------------------------------- // Box2dJointRef::getReactionForce() //=---------------------------------------------------------------------------- b2Vec2 Box2dJointRef::getReactionForce() const { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getReactionForce() - No b2Joint referenced." ); return this->mJoint->GetReactionForce(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getReactionForce() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getReactionForce, const char*, 2, 2, "" ) { return Box2dUtil::b2Vec2ToReturnBuffer( object->getReactionForce() ); } //=---------------------------------------------------------------------------- // Box2dJointRef::getReactionTorque() //=---------------------------------------------------------------------------- float32 Box2dJointRef::getReactionTorque() const { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getReactionTorque() - No b2Joint referenced." ); return this->mJoint->GetReactionTorque(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getReactionTorque() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getReactionTorque, F32, 2, 2, "" ) { return object->getReactionTorque(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getNext() //=---------------------------------------------------------------------------- Box2dJointRef* Box2dJointRef::getNext() { AssertFatal( this->mJoint != NULL, "Box2dJointRef::getNext() - No b2Joint referenced." ); b2Joint * next = this->mJoint->GetNext(); return next ? static_cast<Box2dJointRef*>( next->GetUserData() ) : NULL; } //=---------------------------------------------------------------------------- // Box2dJointRef::onJointDestroyedCallback() //=---------------------------------------------------------------------------- void Box2dJointRef::onJointDestroyedCallback() { this->destroy(); } //=---------------------------------------------------------------------------- // Box2dJointRef::getNext() - ConsoleMethod //=---------------------------------------------------------------------------- ConsoleMethod( Box2dJointRef, getNext, S32, 2, 2, "" ) { return object->getNext() ? object->getNext()->getId() : 0; } //=---------------------------------------------------------------------------- // Box2dJointRef::getJointTypeName() //=---------------------------------------------------------------------------- const char* Box2dJointRef::getJointTypeName( const b2JointType type ) { switch ( type ) { case e_revoluteJoint: return "e_revoluteJoint"; case e_prismaticJoint: return "e_prismaticJoint"; case e_distanceJoint: return "e_distanceJoint"; case e_pulleyJoint: return "e_pulleyJoint"; case e_mouseJoint: return "e_mouseJoint"; case e_gearJoint: return "e_gearJoint"; case e_unknownJoint: default: return "e_unknownJoint"; } } //=---------------------------------------------------------------------------- // Box2dJointRef::getJointTypeFromName() //=---------------------------------------------------------------------------- b2JointType Box2dJointRef::getJointTypeFromName( const char * name ) { if ( dStricmp( name, "e_revoluteJoint" ) == 0 ) return e_revoluteJoint; if ( dStricmp( name, "e_prismaticJoint" ) == 0 ) return e_prismaticJoint; if ( dStricmp( name, "e_distanceJoint" ) == 0 ) return e_distanceJoint; if ( dStricmp( name, "e_pulleyJoint" ) == 0 ) return e_pulleyJoint; if ( dStricmp( name, "e_mouseJoint" ) == 0 ) return e_mouseJoint; if ( dStricmp( name, "e_gearJoint" ) == 0 ) return e_gearJoint; return e_revoluteJoint; } //=---------------------------------------------------------------------------- // Box2dJointRef::destroy() //=---------------------------------------------------------------------------- void Box2dJointRef::destroy() { AssertFatal( this->mJoint != NULL, "" ); this->mJoint = NULL; if ( this->mJointEdgeRefs[0] != NULL ) { this->mJointEdgeRefs[0]->deleteObject(); this->mJointEdgeRefs[0] = NULL; } if ( this->mJointEdgeRefs[1] != NULL ) { this->mJointEdgeRefs[1]->deleteObject(); this->mJointEdgeRefs[1] = NULL; } this->deleteObject(); } //=---------------------------------------------------------------------------- // Box2dJointRef::setJoint() //=---------------------------------------------------------------------------- void Box2dJointRef::setJoint(b2Joint *joint) { AssertFatal( this->mJoint == NULL, "" ); this->mJoint = joint; for ( b2JointEdge * edge = joint->GetBody1()->GetJointList(); edge != NULL; edge = edge->next ) { if ( edge->joint == joint ) { this->mJointEdgeRefs[0] = new Box2dJointEdgeRef( edge ); if ( !this->mJointEdgeRefs[0]->registerObject() ) { delete this->mJointEdgeRefs[0]; this->mJointEdgeRefs[0] = NULL; } break; } } for ( b2JointEdge * edge = joint->GetBody2()->GetJointList(); edge != NULL; edge = edge->next ) { if ( edge->joint == joint ) { this->mJointEdgeRefs[1] = new Box2dJointEdgeRef( edge ); if ( !this->mJointEdgeRefs[1]->registerObject() ) { delete this->mJointEdgeRefs[1]; this->mJointEdgeRefs[1] = NULL; } break; } } AssertFatal( this->mJointEdgeRefs[0] != NULL, "Box2dJointRef::setJoint() - mJointEdgeRef[0] not assigned." ); AssertFatal( this->mJointEdgeRefs[1] != NULL, "Box2dJointRef::setJoint() - mJointEdgeRef[1] not assigned." ); }
mit
jeancsil/SkyscannerVigilantBundle
JeancsilSkyscannerVigilantBundle.php
161
<?php namespace Jeancsil\Skyscanner\VigilantBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class JeancsilSkyscannerVigilantBundle extends Bundle { }
mit
qqiangwu/mstd
mstd/algorithm/unique.hpp
1766
#ifndef MSTD_ALGORITHM_UNIQUE_HPP_ #define MSTD_ALGORITHM_UNIQUE_HPP_ #include <mstd/iterator/concept.hpp> #include <mstd/algorithm/adjacent_find.hpp> namespace mstd { template <class Iter> Require<ForwardIter<Iter>(), Iter> unique(Iter first, Iter last) { auto iter = mstd::adjacent_find(first, last); return iter == last? last: mstd::unique_copy(iter, last, iter); } template <class InIter, class OutIter> Require<InputIterator<InIter>() && OutputIterator<OutIter>(), OutIter> unique_copy(InIter first, InIter last, OutIter result) { if (first == last) return result; auto prev = *first; *result++ = prev; for (++first; first != last; ++first) { if (prev != *first) { prev = *first; *result++ = prev; } } return result; } template <class Iter, class BinPred> Require<ForwardIter<Iter>(), Iter> unique(Iter first, Iter last, BinPred pred) { auto iter = mstd::adjacent_find(first, last, pred); return iter == last? last: mstd::unique_copy(iter, last, iter, pred); } template <class InIter, class OutIter, class BinPred> Require<InputIterator<InIter>() && OutputIterator<OutIter>(), OutIter> unique_copy(InIter first, InIter last, OutIter result, BinPred pred) { if (first == last) return result; auto prev = *first; *result++ = prev; for (++first; first != last; ++first) { if (pred(prev, *first)) { prev = *first; *result++ = prev; } } return result; } } // of namespace mstd #endif //! MSTD_ALGORITHM_UNIQUE_HPP_
mit
itdoors/sd
src/Lists/ProjectBundle/Entity/MessageCurrent.php
147
<?php namespace Lists\ProjectBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * MessageCurrent */ class MessageCurrent extends Message { }
mit
kamoh/outfittracker
app/models/recommendation.rb
65
class Recommendation < ActiveRecord::Base belongs_to :user end
mit
wewea/CodeVivid
webpack.dev.config.js
844
var path = require('path'); module.exports = { // entry: ['webpack-dev-server/client?http://localhost:8080', // 'webpack/hot/dev-server', // path.resolve(__dirname, './public/js/browser.js')], // dev static page entry: ['webpack/hot/dev-server', path.resolve(__dirname, './client.js')], output: { path: path.resolve(__dirname, './public/'), filename: '/bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'react-hot', exclude: /node_modules/, }, { test: /\.jsx?$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['stage-2', 'react','es2015'] } }, { test: /\.css$/, loader: 'style!css' }, { test: /\.jade$/, loader: 'jade-html' } ] }, // devServer: { // proxy: { // '*' : 'http://localhost:3000' // } // } }
mit
PJB3005/MoMMI
MoMMI/Modules/mirror.py
4370
import logging import asyncio import aiohttp import heapq import pytz from datetime import datetime, timedelta from typing import Any, Dict, Match, List, Tuple, Set, cast from MoMMI import MChannel, comm_event, SnowflakeID, add_reaction, master, always_command, command, delete_command, reaction_command from MoMMI.util import utcnow from discord import Message, Embed, Reaction, User import json LOOP_TASK_CACHE = "mirror_task" REMINDER_QUEUE = "mirror_queue" LOOP_INTERVAL = 5 # Tuple format: time, message, sender, avatar, target_webhook, orig ID REMINDER_TUPLE_TYPE = Tuple[datetime, str, str, str, str, SnowflakeID] logger = logging.getLogger(__name__) # Haha delayed mirroring literally copy pasted from reminders. # Deal with it. async def load(loop: asyncio.AbstractEventLoop) -> None: task: asyncio.Future if master.has_cache(LOOP_TASK_CACHE): logger.warning("Loop task still exists!") task = master.get_cache(LOOP_TASK_CACHE) task.cancel() task = asyncio.ensure_future(reminder_loop()) master.set_cache(LOOP_TASK_CACHE, task) if not master.has_global_storage(REMINDER_QUEUE): master.set_global_storage(REMINDER_QUEUE, []) async def reminder_loop() -> None: while True: #logger.info("A") await asyncio.sleep(LOOP_INTERVAL) try: await check_reminders() except: logger.exception("Exception in mirror loop") async def check_reminders() -> None: heap: List[REMINDER_TUPLE_TYPE] = master.get_global_storage(REMINDER_QUEUE) now = utcnow() #logger.info(repr(heap)) modified = False while heap and heap[0][0] < now: # logger.debug("Yes?") item = heap[0] heapq.heappop(heap) # heapq.heapify(heap) modified = True asyncio.ensure_future(send_reminder(item)) if modified: await master.save_global_storage(REMINDER_QUEUE) async def send_reminder(reminder: REMINDER_TUPLE_TYPE) -> None: msg = reminder[1] sender = reminder[2] avatar = reminder[3] target = reminder[4] async with aiohttp.ClientSession() as session: await session.post(target, json={ "content": msg, "username": sender, "avatar_url": avatar, "allowed_mentions": { "parse": [] }}) @delete_command("mirror_hide_delete") async def mirrorhide_command(channel: MChannel, message: Message) -> None: await hidemessage(channel, message) @reaction_command("mirror_hide_reaction") async def mirrorhide_reaction_command(channel: MChannel, reaction: Reaction, member: User) -> None: if reaction.emoji != '🔇': return if await hidemessage(channel, reaction.message): await add_reaction(reaction.message, "✅") @always_command("mirrormirroronthewall", unsafe=True) async def mirrormirroronthewall(channel: MChannel, match: Match, message: Message) -> None: content = message.content for attachment in message.attachments: content += " " + attachment["url"] found = None for mirror_entry in channel.server_config("modules.mirror", []): if channel.server.get_channel(mirror_entry["from"]) == channel: found = mirror_entry break else: return target = found["to"] mirror_delay = timedelta(minutes=found["delay"]) heap: List[REMINDER_TUPLE_TYPE] = master.get_global_storage(REMINDER_QUEUE) time = utcnow() + mirror_delay reminder = (time, content, message.author.name, message.author.avatar_url, target, SnowflakeID(int(message.id))) heapq.heappush(heap, reminder) await master.save_global_storage(REMINDER_QUEUE) async def hidemessage(channel: MChannel, msg: Message) -> bool: # Don't scrub through the list if this channel isn't a mirrored channel. for mirror_entry in channel.server_config("modules.mirror", []): if channel.server.get_channel(mirror_entry["from"]) == channel: break else: return False thelist = master.get_global_storage(REMINDER_QUEUE) for x in thelist: if str(x[5]) == msg.id: found = x break else: return False thelist.remove(found) heapq.heapify(thelist) asyncio.ensure_future(master.save_global_storage(REMINDER_QUEUE)) return True
mit
tommo/gii
support/waf/waflib/Tools/nasm.py
546
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2008-2010 (ita) """ Nasm tool (asm processing) """ import waflib.Tools.asm # leave this from waflib.TaskGen import feature @feature('asm') def apply_nasm_vars(self): """provided for compatibility""" self.env.append_value('ASFLAGS', self.to_list(getattr(self, 'nasm_flags', []))) def configure(conf): """ Detect nasm/yasm and set the variable *AS* """ nasm = conf.find_program(['nasm', 'yasm'], var='AS') conf.env.AS_TGT_F = ['-o'] conf.env.ASLNK_TGT_F = ['-o'] conf.load('asm')
mit
kybarg/material-ui
packages/material-ui-icons/src/CropFreeSharp.js
222
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M3 3v6h2V5h4V3H3zm2 12H3v6h6v-2H5v-4zm14 4h-4v2h6v-6h-2v4zm2-16h-6v2h4v4h2V3z" /> , 'CropFreeSharp');
mit
cowthan/Ayo2022
ProjWechat/easeuilibrary/src/com/fanxin/easeui/model/EaseNotifier.java
14466
/************************************************************ * * Hyphenate CONFIDENTIAL * __________________ * Copyright (C) 2016 Hyphenate Inc. All rights reserved. * * NOTICE: All information contained herein is, and remains * the property of Hyphenate Inc. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Hyphenate Inc. */ package com.fanxin.easeui.model; import java.util.HashSet; import java.util.List; import java.util.Locale; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMMessage; import com.fanxin.easeui.controller.EaseUI; import com.fanxin.easeui.controller.EaseUI.EaseSettingsProvider; import com.hyphenate.util.EMLog; import com.hyphenate.util.EasyUtils; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.AudioManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Vibrator; import android.support.v4.app.NotificationCompat; /** * new message notifier class * * this class is subject to be inherited and implement the relative APIs */ public class EaseNotifier { private final static String TAG = "notify"; Ringtone ringtone = null; protected final static String[] msg_eng = { "sent a message", "sent a picture", "sent a voice", "sent location message", "sent a video", "sent a file", "%1 contacts sent %2 messages" }; protected final static String[] msg_ch = { "发来一条消息", "发来一张图片", "发来一段语音", "发来位置信息", "发来一个视频", "发来一个文件", "%1个联系人发来%2条消息" }; protected static int notifyID = 0525; // start notification id protected static int foregroundNotifyID = 0555; protected NotificationManager notificationManager = null; protected HashSet<String> fromUsers = new HashSet<String>(); protected int notificationNum = 0; protected Context appContext; protected String packageName; protected String[] msgs; protected long lastNotifiyTime; protected AudioManager audioManager; protected Vibrator vibrator; protected EaseNotificationInfoProvider notificationInfoProvider; public EaseNotifier() { } /** * this function can be override * @param context * @return */ public EaseNotifier init(Context context){ appContext = context; notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); packageName = appContext.getApplicationInfo().packageName; if (Locale.getDefault().getLanguage().equals("zh")) { msgs = msg_ch; } else { msgs = msg_eng; } audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE); vibrator = (Vibrator) appContext.getSystemService(Context.VIBRATOR_SERVICE); return this; } /** * this function can be override */ public void reset(){ resetNotificationCount(); cancelNotificaton(); } void resetNotificationCount() { notificationNum = 0; fromUsers.clear(); } void cancelNotificaton() { if (notificationManager != null) notificationManager.cancel(notifyID); } /** * handle the new message * this function can be override * * @param message */ public synchronized void onNewMsg(EMMessage message) { if(EMClient.getInstance().chatManager().isSlientMessage(message)){ return; } EaseSettingsProvider settingsProvider = EaseUI.getInstance().getSettingsProvider(); if(!settingsProvider.isMsgNotifyAllowed(message)){ return; } // check if app running background if (!EasyUtils.isAppRunningForeground(appContext)) { EMLog.d(TAG, "app is running in backgroud"); sendNotification(message, false); } else { sendNotification(message, true); } vibrateAndPlayTone(message); } public synchronized void onNewMesg(List<EMMessage> messages) { if(EMClient.getInstance().chatManager().isSlientMessage(messages.get(messages.size()-1))){ return; } EaseSettingsProvider settingsProvider = EaseUI.getInstance().getSettingsProvider(); if(!settingsProvider.isMsgNotifyAllowed(null)){ return; } // check if app running background if (!EasyUtils.isAppRunningForeground(appContext)) { EMLog.d(TAG, "app is running in backgroud"); sendNotification(messages, false); } else { sendNotification(messages, true); } vibrateAndPlayTone(messages.get(messages.size()-1)); } /** * send it to notification bar * This can be override by subclass to provide customer implementation * @param messages * @param isForeground */ protected void sendNotification (List<EMMessage> messages, boolean isForeground){ for(EMMessage message : messages){ if(!isForeground){ notificationNum++; fromUsers.add(message.getFrom()); } } sendNotification(messages.get(messages.size()-1), isForeground, false); } protected void sendNotification (EMMessage message, boolean isForeground){ sendNotification(message, isForeground, true); } /** * send it to notification bar * This can be override by subclass to provide customer implementation * @param message */ protected void sendNotification(EMMessage message, boolean isForeground, boolean numIncrease) { String username = message.getFrom(); try { String notifyText = username + " "; switch (message.getType()) { case TXT: notifyText += msgs[0]; break; case IMAGE: notifyText += msgs[1]; break; case VOICE: notifyText += msgs[2]; break; case LOCATION: notifyText += msgs[3]; break; case VIDEO: notifyText += msgs[4]; break; case FILE: notifyText += msgs[5]; break; } PackageManager packageManager = appContext.getPackageManager(); String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo()); // notification title String contentTitle = appname; if (notificationInfoProvider != null) { String customNotifyText = notificationInfoProvider.getDisplayedText(message); String customCotentTitle = notificationInfoProvider.getTitle(message); if (customNotifyText != null){ notifyText = customNotifyText; } if (customCotentTitle != null){ contentTitle = customCotentTitle; } } // create and send notificaiton NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext) .setSmallIcon(appContext.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setAutoCancel(true); Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName); if (notificationInfoProvider != null) { msgIntent = notificationInfoProvider.getLaunchIntent(message); } PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, msgIntent,PendingIntent.FLAG_UPDATE_CURRENT); if(numIncrease){ // prepare latest event info section if(!isForeground){ notificationNum++; fromUsers.add(message.getFrom()); } } int fromUsersNum = fromUsers.size(); String summaryBody = msgs[6].replaceFirst("%1", Integer.toString(fromUsersNum)).replaceFirst("%2",Integer.toString(notificationNum)); if (notificationInfoProvider != null) { // lastest text String customSummaryBody = notificationInfoProvider.getLatestText(message, fromUsersNum,notificationNum); if (customSummaryBody != null){ summaryBody = customSummaryBody; } // small icon int smallIcon = notificationInfoProvider.getSmallIcon(message); if (smallIcon != 0){ mBuilder.setSmallIcon(smallIcon); } } mBuilder.setContentTitle(contentTitle); mBuilder.setTicker(notifyText); mBuilder.setContentText(summaryBody); mBuilder.setContentIntent(pendingIntent); // mBuilder.setNumber(notificationNum); Notification notification = mBuilder.build(); if (isForeground) { notificationManager.notify(foregroundNotifyID, notification); notificationManager.cancel(foregroundNotifyID); } else { notificationManager.notify(notifyID, notification); } } catch (Exception e) { e.printStackTrace(); } } /** * vibrate and play tone */ public void vibrateAndPlayTone(EMMessage message) { if(message != null){ if(EMClient.getInstance().chatManager().isSlientMessage(message)){ return; } } if (System.currentTimeMillis() - lastNotifiyTime < 1000) { // received new messages within 2 seconds, skip play ringtone return; } try { lastNotifiyTime = System.currentTimeMillis(); // check if in silent mode if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) { EMLog.e(TAG, "in slient mode now"); return; } EaseSettingsProvider settingsProvider = EaseUI.getInstance().getSettingsProvider(); if(settingsProvider.isMsgVibrateAllowed(message)){ long[] pattern = new long[] { 0, 180, 80, 120 }; vibrator.vibrate(pattern, -1); } if(settingsProvider.isMsgSoundAllowed(message)){ if (ringtone == null) { Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); ringtone = RingtoneManager.getRingtone(appContext, notificationUri); if (ringtone == null) { EMLog.d(TAG, "cant find ringtone at:" + notificationUri.getPath()); return; } } if (!ringtone.isPlaying()) { String vendor = Build.MANUFACTURER; ringtone.play(); // for samsung S3, we meet a bug that the phone will // continue ringtone without stop // so add below special handler to stop it after 3s if // needed if (vendor != null && vendor.toLowerCase().contains("samsung")) { Thread ctlThread = new Thread() { public void run() { try { Thread.sleep(3000); if (ringtone.isPlaying()) { ringtone.stop(); } } catch (Exception e) { } } }; ctlThread.run(); } } } } catch (Exception e) { e.printStackTrace(); } } /** * set notification info Provider * * @param provider */ public void setNotificationInfoProvider(EaseNotificationInfoProvider provider) { notificationInfoProvider = provider; } public interface EaseNotificationInfoProvider { /** * set the notification content, such as "you received a new image from xxx" * * @param message * @return null-will use the default text */ String getDisplayedText(EMMessage message); /** * set the notification content: such as "you received 5 message from 2 contacts" * * @param message * @param fromUsersNum- number of message sender * @param messageNum -number of messages * @return null-will use the default text */ String getLatestText(EMMessage message, int fromUsersNum, int messageNum); /** * 设置notification标题 * * @param message * @return null- will use the default text */ String getTitle(EMMessage message); /** * set the small icon * * @param message * @return 0- will use the default icon */ int getSmallIcon(EMMessage message); /** * set the intent when notification is pressed * * @param message * @return null- will use the default icon */ Intent getLaunchIntent(EMMessage message); } }
mit
mathiasbynens/unicode-data
4.0.1/blocks/Deseret-code-points.js
866
// All code points in the Deseret block as per Unicode v4.0.1: [ 0x10400, 0x10401, 0x10402, 0x10403, 0x10404, 0x10405, 0x10406, 0x10407, 0x10408, 0x10409, 0x1040A, 0x1040B, 0x1040C, 0x1040D, 0x1040E, 0x1040F, 0x10410, 0x10411, 0x10412, 0x10413, 0x10414, 0x10415, 0x10416, 0x10417, 0x10418, 0x10419, 0x1041A, 0x1041B, 0x1041C, 0x1041D, 0x1041E, 0x1041F, 0x10420, 0x10421, 0x10422, 0x10423, 0x10424, 0x10425, 0x10426, 0x10427, 0x10428, 0x10429, 0x1042A, 0x1042B, 0x1042C, 0x1042D, 0x1042E, 0x1042F, 0x10430, 0x10431, 0x10432, 0x10433, 0x10434, 0x10435, 0x10436, 0x10437, 0x10438, 0x10439, 0x1043A, 0x1043B, 0x1043C, 0x1043D, 0x1043E, 0x1043F, 0x10440, 0x10441, 0x10442, 0x10443, 0x10444, 0x10445, 0x10446, 0x10447, 0x10448, 0x10449, 0x1044A, 0x1044B, 0x1044C, 0x1044D, 0x1044E, 0x1044F ];
mit
jphacks/KS_1602
db/migrate/20161029075042_rename_wants_column.rb
169
class RenameWantsColumn < ActiveRecord::Migration[5.0] def change rename_column :wants, :WEFL, :LATITUDE rename_column :wants, :MERIDIAN, :LONGITUDE end end
mit
kaaku/screeps
src/role.base.js
301
function BaseRole() { } BaseRole.prototype.run = function (creep) { }; BaseRole.prototype.getBody = function (energy) { return []; }; BaseRole.prototype.getMinCost = function () { return null; }; BaseRole.prototype.getMaxCost = function () { return null; }; module.exports = BaseRole;
mit
moperacz/sisyphus-rails
lib/sisyphus-rails.rb
118
require "sisyphus-rails/version" module Sisyphus module Rails class Engine < ::Rails::Engine end end end
mit
Teleopti/Stardust
Manager/ManagerTest/ManagerControllerValidationTest.cs
6427
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Results; using ManagerTest.Attributes; using NUnit.Framework; using SharpTestsEx; using Stardust.Manager; using Stardust.Manager.Interfaces; using Stardust.Manager.Models; namespace ManagerTest { [ManagerControllerValidationTest] [TestFixture] public class ManagerControllerValidationTest { public ManagerController ManagerController; public IJobRepository JobRepository; [Test] public void ShouldReturnOkWhenJobDoneReceived() { ManagerController.ControllerContext = new HttpControllerContext { Configuration = new HttpConfiguration() }; ManagerController.Request = new HttpRequestMessage { RequestUri = new Uri("http://calabiro.com") }; var result = ManagerController.JobSucceed(Guid.NewGuid()); var httpResponseMessage = result.ExecuteAsync(CancellationToken.None).Result; httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK); //Assert.IsInstanceOf(typeof(OkResult), result); } [Test] public void ShouldReturnBadRequestIfCancelThisJobGetsAnInvalidGuid() { var response = ManagerController.CancelJobByJobId(Guid.Empty); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfHeartbeatGetsAnInvalidUri() { var response = ManagerController.WorkerNodeRegisterHeartbeat(null); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobFailedGetsANull() { var response = ManagerController.JobFailed(null); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobFailedGetsInvalidJobFailedModel() { var jobFailed = new JobFailed(); var response = ManagerController.JobFailed(jobFailed); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobHistoryDetailsGetsAnInvalidGuid() { var response = ManagerController.GetJobDetailsByJobId(Guid.Empty); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobHistoryGetsAnInvalidGuid() { var response = ManagerController.GetJobByJobId(Guid.Empty); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobQueueItemHasInvalidCreatedByValue() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = "Serialized", Type = "Type", CreatedBy = string.Empty }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelNameIsEmptyString() { var jobQueueItem = new JobQueueItem { Name = string.Empty, Serialized = "Serialized", Type = "Type", CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelNameIsNull() { var jobQueueItem = new JobQueueItem { Name = null, Serialized = "Serialized", Type = "Type", CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelSerializedIsEmptyString() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = string.Empty, Type = "Type", CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelSerializedIsNull() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = null, Type = "Type", CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelTypeIsEmptyString() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = "Serialized", Type = string.Empty, CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelTypeIsNull() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = "Serialized", Type = null, CreatedBy = "UserName" }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIfJobRequestModelUserNameIsNull() { var jobQueueItem = new JobQueueItem { Name = "Name", Serialized = "Serialized", Type = "Type", CreatedBy = null }; var response = ManagerController.AddItemToJobQueue(jobQueueItem); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldReturnBadRequestIJobDoneGetsAnInvalidUri() { var response = ManagerController.JobSucceed(Guid.Empty); Assert.IsInstanceOf(typeof(BadRequestErrorMessageResult), response); } [Test] public void ShouldLogIfAggregateExceptionIsNull() { var jobFailed = new JobFailed { JobId = Guid.NewGuid(), AggregateException = null }; ManagerController.Request = new HttpRequestMessage() { RequestUri = new Uri("http://calabiro.com") }; var response = ManagerController.JobFailed(jobFailed); var jobDetails = JobRepository.GetJobDetailsByJobId(jobFailed.JobId); jobDetails.Single().Detail.Should().Be("No Exception specified for job"); } } }
mit
JhulFramework/PHPServer4ODK
required/odk/0.1/framework/jhul/Jhul/Components/Form/_Class.php
6515
<?php namespace Jhul\Components\Form; /* @Author : Manish Dhruw < [email protected] > +======================================================================================================================= | @Updated: | -Saturday 03 January 2015 07:01:22 PM IST | -Saturday 10 January 2015 03:54:05 PM IST | -Tuesday 16 June 2015 01:23:44 PM IST | - [ 2017-01-31 ] +---------------------------------------------------------------------------------------------------------------------*/ abstract class _Class { use \Jhul\Core\_AccessKey; abstract function name(); abstract function fields(); //we will auto create properties which are defined in field definitions; public function __construct() { $fields = $this->fields() + $this->files(); foreach( $fields as $field => $r ) { if( !property_exists( $this, $field ) ) { $this->$field = NULL ; } } } public function fieldValue( $field ) { return isset( $_POST[ $this->name() ][ $field ] ) ? $_POST[ $this->name() ][ $field ] : NULL ; } public function collect() { return $this->collectTextFields() && $this->collectFileFields() ; } public function collectTextFields() { if( empty($_POST[$this->name()])) return FALSE; $submission = $_POST[ $this->name() ]; foreach( $this->fields() as $name => $type ) { $value = array_key_exists( $name, $submission ) ? $submission[$name] : NULL ; $this->$name = $this->getApp()->mDataType( $type )->make( $value ); $this->addError( $name, $this->$name->errors() ); } return TRUE ; } public function files(){ return [] ; } //Collects $_FILES data public function collectFileFields() { $files = $this->files(); if(empty($files)) return TRUE; if( empty($_FILES)) return FALSE; foreach ( $this->files() as $name => $type ) { $file = !empty( $_FILES[ $name ] ) ? $_FILES[$name] : NULL; $this->$name = $this->getApp()->mDataType($type)->make( $file ); $this->addError( $name , $this->$name->errors() ); } return TRUE; } //returns HTML form field name public function fieldName( $field ) { return $this->name().'['.$field.']'; } //Restores client sumitted data, to avoid refilling the form public function restore( $key ) { if( isset( $_POST[ $this->name() ] ) && isset( $_POST[ $this->name() ][ $key ] ) ) return $this->html()->encode( $_POST[ $this->name() ][ $key ] ); } public function mDataType( $type ) { return $this->getApp()->mDataType( $type ) ; } /* BRUTE FORCE DEFENSE +=====================================================================================================================*/ protected $_captcha; public function authAttempts( $userKey ) { return $this->J()->cx( 'bfd' )->get( $userKey , $this->name() ); } public function captcha() { if( NULL == $this->_captcha ) { $this->_captcha = new Captcha( $this ); } return $this->_captcha; } public function onAuthorizationFail( $UIK ) { $this->authAttempts( $UIK )->register()->commit(); if( $this->authAttempts( $UIK )->countAttempts() > 12 ) { $this->captcha()->activate(); } } public function onAuthorizationSuccess( $UIK ) { $this->captcha()->deactivate(); $this->authAttempts( $UIK )->clear()->commit(); } public function validateCaptcha() { if( $this->captcha()->isActive() ) { if( !$this->captcha()->validate() ) { $this->addError( $this->captcha()->name(), 'ERROR_CAPTCHA_CODE_FAILED' ); } } } /* BRUTE FORCE DEFENSE +---------------------------------------------------------------------------------------------------------------------*/ /* ERRORS +=====================================================================================================================*/ protected $_errors = [] ; public function hasError( $attrib = NULL ) { if($attrib != NULL) return isset( $this->_errors[$attrib] ); return !empty($this->_errors) ; } public function error( $attribute ) { return isset( $this->_errors[$attribute] ) ? $this->_errors[$attribute][0] : null ; } public function errors( $attribute = NULL ) { if( $attribute != NULL ) { return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [] ; } return $this->_errors; } // add muliple erros for single field public function addError($attribute, $error ) { if( is_array($error) ) { foreach ($error as $e) { $this->addError( $attribute, $e ); } return ; } if( !isset($this->_errors[$attribute] ) ) $this->_errors[$attribute] = array(); $this->_errors[$attribute][] = $this->translate($error) ; } /* ERRORS +---------------------------------------------------------------------------------------------------------------------*/ public function html() { return $this->J()->cx('html'); } /* TOKEN +=====================================================================================================================*/ protected $_token ; //name of token protected $_tokenFieldName = '_token'; public function token() { if( NULL == $this->_token ) { $this->_token = new Token( $this->name(), $this->fieldName( $this->_tokenFieldName ) ); } return $this->_token; } public function verifyToken() { if( isset( $_POST[ $this->name() ][ $this->_tokenFieldName ] ) ) { return $this->token()->verify( $_POST[ $this->name() ][ $this->_tokenFieldName ] ); } return FALSE; } /* TOKEN +---------------------------------------------------------------------------------------------------------------------*/ /* TRANSLATION +=====================================================================================================================*/ protected $_strings = []; public function string( $key ) { if( empty( $this->_strings ) ) { $this->_strings = $this->translate( $this->stringKeys() ); } return isset( $this->_strings[$key] ) ? $this->_strings[$key] : $key ; } protected function stringKeys(){ return []; } public function translate( $string ){ return $this->getApp()->lipi()->t( $string ); } /* TRANSLATION +---------------------------------------------------------------------------------------------------------------------*/ protected function preValidate(){} protected $_validated = FALSE; public final function validate() { if( !$this->_validated ) { $this->_validated = TRUE; $this->preValidate(); $this->validateCaptcha(); $this->postValidate(); } return !$this->hasError(); } protected function postValidate(){} }
mit
kenshinthebattosai/LinqAn.Google
src/LinqAn.Google/Dimensions/UserType.cs
521
using System.ComponentModel; namespace LinqAn.Google.Dimensions { /// <summary> /// A boolean indicating if a user is new or returning. Possible values: New Visitor, Returning Visitor. /// </summary> [Description("A boolean indicating if a user is new or returning. Possible values: New Visitor, Returning Visitor.")] public class UserType: Dimension { /// <summary> /// Instantiates a <seealso cref="UserType" />. /// </summary> public UserType(): base("User Type",true,"ga:userType") { } } }
mit
bradhowes/sidecar
GUI/BScope/ScaleWidget.cc
12979
#include <algorithm> #include <cmath> #include <functional> #include "QtGui/QGuiApplication" #include "QtGui/QPainter" #include "GUI/LogUtils.h" #include "GUI/Utils.h" #include "Utils/Utils.h" #include "ScaleWidget.h" using namespace SideCar::GUI::BScope; Logger::Log& ScaleWidget::Log() { static Logger::Log& log_ = Logger::Log::Find("bscope.ScaleWidget"); return log_; } ScaleWidget::ScaleWidget(QWidget* parent, Qt::Orientation orientation) : Super(parent), lastSizeCalculated_(), majorTickHeight_(10), minorTickHeight_(6), majorTickDivisionsMax_(8), minorTickDivisionsMax_(4), start_(0.0), range_(4.0), orientation_(orientation), majorGridPen_(QColor(64, 64, 64), 0.0), minorGridPen_(QColor(16, 16, 16), 0.0), cursorIndicatorPen_(QColor(255, 0, 0, 128), 0), cursorPosition_(-1), autoDivide_(false) { QFont labelFont(font()); labelFont.setPointSize(10); setFont(labelFont); setBackgroundRole(QPalette::Base); setOrientation(orientation); } void ScaleWidget::setSpan(int span) { static Logger::ProcLog log("setSpan", Log()); LOGINFO << "span: " << span << std::endl; if (orientation_ == Qt::Horizontal) { resize(span, height()); } else { resize(width(), span); } updateGeometry(); recalculateTickIntervals(width(), height()); } QSize ScaleWidget::sizeHint() const { if (orientation_ == Qt::Horizontal) return QSize(width(), majorTickHeight_ + fontMetrics().height()); else return QSize(majorTickHeight_ + fontMetrics().height(), height()); } QSize ScaleWidget::minimumSizeHint() const { return sizeHint(); } void ScaleWidget::recalculateTickIntervals(int width, int height) { QSize newSize(width, height); if (newSize == lastSizeCalculated_) return; lastSizeCalculated_ = newSize; double span = (orientation_ == Qt::Horizontal ? width : height); if (autoDivide_) { majorIncrement_ = std::max(80.0, span / majorTickDivisionsMax_); majorTickDivisions_ = std::max(1, int(::floor(span / majorIncrement_))); majorIncrement_ = span / majorTickDivisions_; minorIncrement_ = std::max(40.0, majorIncrement_ / minorTickDivisionsMax_); minorTickDivisions_ = std::max(1, int(::floor(majorIncrement_ / minorIncrement_))); minorIncrement_ = majorIncrement_ / minorTickDivisions_; } else { majorIncrement_ = span / majorTickDivisionsMax_; majorTickDivisions_ = majorTickDivisionsMax_; minorIncrement_ = majorIncrement_ / minorTickDivisionsMax_; minorTickDivisions_ = minorTickDivisionsMax_; } } void ScaleWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); render(painter); if (cursorPosition_ != -1) { painter.setRenderHint(QPainter::Antialiasing, true); drawCursorPosition(painter, cursorPosition_); } } void ScaleWidget::render(QPainter& painter) { render(painter, width(), height()); } void ScaleWidget::render(QPainter& painter, int width, int height) { recalculateTickIntervals(width, height); // For horizontal and vertical lines, disable antialiasing. // painter.setRenderHint(QPainter::Antialiasing, false); painter.setRenderHint(QPainter::TextAntialiasing, true); if (orientation_ == Qt::Horizontal) { drawHorizontalTicks(painter, width, height); } else { painter.save(); painter.translate(width, 0.0); painter.rotate(+90.0); drawVerticalTicks(painter, height, width); painter.restore(); } } void ScaleWidget::drawVerticalTicks(QPainter& painter, int span, int tagOffset) { static Logger::ProcLog log("drawVerticalTicks", Log()); LOGINFO << "span: " << span << " tagOffset: " << tagOffset << std::endl; auto palette = QGuiApplication::palette(); painter.setFont(font()); painter.setBrush(palette.windowText()); QFontMetrics fm(fontMetrics()); double increment = minorIncrement_; double origin = 0.0; double tag = start_; int tickCounter = 0; double tagIncrement = range_ / majorTickDivisions_; if (orientation_ == Qt::Vertical) { increment = -increment; origin = span - 1; } while (1) { double x = tickCounter * increment + origin; LOGDEBUG << "x: " << x << " tickCounter: " << tickCounter << std::endl; if (x >= span || x < 0) break; if ((tickCounter % minorTickDivisions_) == 0) { QLineF line(x, 0.0, x, majorTickHeight_); painter.drawLine(line); QString label = formatTickTag(tag); double offset = fm.boundingRect(label).width() / 2; if (orientation_ == Qt::Horizontal) { if (tickCounter == 0) { offset = 0; } else if (x + offset > span) { offset *= 2; } } else { if (tickCounter == 0) { offset *= 2; } else if (x - offset < 0.0) { offset = 0; } } LOGDEBUG << "tag: " << tag << " offset: " << offset << std::endl; line.translate(-offset, tagOffset - fm.descent() - 1); painter.drawText(line.p1(), label); tag += tagIncrement; } else { QLineF line(x, 0.0, x, minorTickHeight_); painter.drawLine(line); } ++tickCounter; } } void ScaleWidget::drawHorizontalTicks(QPainter& painter, int span, int tagOffset) { static Logger::ProcLog log("drawHorizontalTicks", Log()); LOGINFO << "span: " << span << " tagOffset: " << tagOffset << std::endl; auto palette = QGuiApplication::palette(); painter.setFont(font()); painter.setBrush(palette.windowText()); QFontMetrics fm(fontMetrics()); double tag = 0.0; int tickCounter = 0; double tagIncrement = range_ / majorTickDivisions_; double shift = -start_ / range_ * (span - 1); LOGDEBUG << "tagIncrement: " << tagIncrement << std::endl; while (1) { double x = shift - tickCounter * minorIncrement_; LOGDEBUG << "x: " << x << " tickCounter: " << tickCounter << std::endl; if (x < 0) break; if ((tickCounter % minorTickDivisions_) == 0) { QLineF line(x, 0.0, x, majorTickHeight_); painter.drawLine(line); QString label = formatTickTag(tag); double offset = fm.boundingRect(label).width() / 2; if (x - offset < 0.0) { offset = 0.0; } LOGDEBUG << "tag: " << tag << " offset: " << offset << std::endl; line.translate(-offset, tagOffset - fm.descent() - 1); painter.drawText(line.p1(), label); tag -= tagIncrement; } else { QLineF line(x, 0.0, x, minorTickHeight_); painter.drawLine(line); } ++tickCounter; } tickCounter = 1; tag = tagIncrement; while (1) { double x = shift + tickCounter * minorIncrement_; if (x >= span) break; if ((tickCounter % minorTickDivisions_) == 0) { QLineF line(x, 0.0, x, majorTickHeight_); painter.drawLine(line); QString label = formatTickTag(tag); double offset = fm.boundingRect(label).width() / 2; if (x + offset > span) { offset += offset; } line.translate(-offset, tagOffset - fm.descent() - 1); painter.drawText(line.p1(), label); tag += tagIncrement; } else { QLineF line(x, 0.0, x, minorTickHeight_); painter.drawLine(line); } ++tickCounter; } } void ScaleWidget::drawGridLines(QPainter& painter) { QPaintDevice* device = painter.device(); recalculateTickIntervals(device->width(), device->height()); painter.setRenderHint(QPainter::Antialiasing, false); if (orientation_ == Qt::Horizontal) { drawVerticalGridLines(painter, device->width(), device->height()); } else { drawHorizontalGridLines(painter, device->width(), device->height()); } } void ScaleWidget::drawVerticalGridLines(QPainter& painter, int width, int height) const { for (int major = 0; major < majorTickDivisions_; ++major) { double x = major * majorIncrement_; if (major) { painter.setPen(majorGridPen_); QLineF line(x, 0.0, x, height); painter.drawLine(line); } painter.setPen(minorGridPen_); for (int minor = 1; minor < minorTickDivisions_; ++minor) { x += minorIncrement_; QLineF line(x, 0.0, x, height); painter.drawLine(line); } } } void ScaleWidget::drawHorizontalGridLines(QPainter& painter, int width, int height) const { static Logger::ProcLog log("drawHorizontalGridLines", Log()); for (int major = 0; major < majorTickDivisions_; ++major) { double y = height - major * majorIncrement_; LOGERROR << "major: " << major << " y: " << y << std::endl; if (major) { painter.setPen(majorGridPen_); QLineF line(0.0, y, width, y); painter.drawLine(line); } painter.setPen(minorGridPen_); for (int minor = 1; minor < minorTickDivisions_; ++minor) { y -= minorIncrement_; QLineF line(0.0, y, width, y); painter.drawLine(line); } } } void ScaleWidget::setMajorTickHeight(int height) { majorTickHeight_ = height; update(); } void ScaleWidget::setMinorTickHeight(int height) { minorTickHeight_ = height; update(); } void ScaleWidget::setMajorTickDivisions(int divisions) { majorTickDivisionsMax_ = divisions; lastSizeCalculated_ = QSize(-1, -1); update(); } void ScaleWidget::setMinorTickDivisions(int divisions) { minorTickDivisionsMax_ = divisions; lastSizeCalculated_ = QSize(-1, -1); update(); } void ScaleWidget::setMajorAndMinorTickDivisions(int major, int minor) { majorTickDivisionsMax_ = major; minorTickDivisionsMax_ = minor; lastSizeCalculated_ = QSize(-1, -1); update(); } void ScaleWidget::setStartAndEnd(double start, double end) { start_ = start; range_ = end - start_; update(); } void ScaleWidget::setStartAndRange(double start, double range) { start_ = start; range_ = range; update(); } void ScaleWidget::setStart(double start) { start_ = start; update(); } void ScaleWidget::setEnd(double end) { range_ = end - start_; update(); } void ScaleWidget::setMidPoint(double zero) { start_ = zero - range_ / 2.0; update(); } void ScaleWidget::setRange(double range) { range_ = range; update(); } void ScaleWidget::setOrientation(Qt::Orientation orientation) { orientation_ = orientation; if (orientation_ == Qt::Horizontal) { setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); } else { setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding)); } update(); } void ScaleWidget::drawCursorPosition(QPainter& painter, int position) { painter.setPen(cursorIndicatorPen_); painter.setBrush(cursorIndicatorPen_.color()); QPolygonF indicator; if (orientation_ == Qt::Horizontal) { indicator << QPointF(position, 0) << QPointF(position - 4, majorTickHeight_) << QPointF(position + 4, majorTickHeight_) << QPointF(position, 0); } else { indicator << QPointF(width() - 1, position) << QPointF(width() - 1 - majorTickHeight_, position - 4) << QPointF(width() - 1 - majorTickHeight_, position + 4) << QPointF(width() - 1, position); } painter.drawConvexPolygon(indicator); } void ScaleWidget::dirtyCursorPosition(int position) { if (position != -1) { if (orientation_ == Qt::Horizontal) { update(position - 5, 0, 11, height() - 1); } else { update(0, position - 5, width() - 1, 11); } } } void ScaleWidget::setCursorPosition(double value) { int position = int(::rint((value - start_) / range_ * (getSpan() - 1))); if (orientation_ == Qt::Vertical) position = height() - 1 - position; if (position != cursorPosition_) { dirtyCursorPosition(cursorPosition_); cursorPosition_ = position; dirtyCursorPosition(cursorPosition_); } } void ScaleWidget::setNormalizedCursorPosition(double value) { int position = int(::rint(value * (getSpan() - 1))); if (orientation_ == Qt::Vertical) position = height() - 1 - position; if (position != cursorPosition_) { dirtyCursorPosition(cursorPosition_); cursorPosition_ = position; dirtyCursorPosition(cursorPosition_); } } QString DegreesScaleWidget::formatTickTag(double value) { return QString("%1%2").arg(Utils::radiansToDegrees(Utils::normalizeRadians(value))).arg(GUI::DegreeSymbol()); }
mit
kaplanke/ades
AdesUnrealController/Properties/Resources.Designer.cs
2866
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AdesUnrealController.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AdesUnrealController.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
mit
dewanee-es/tipi
tmpold/cms/examples/html/js/controller/app-controller.js
11026
var app = angular.module('mdage.controller',[]); app.controller('ConsultaDepuracionController', function($scope,$log, $http,consultaDepuracionService) { $scope.mostrarTabla=false; $scope.getMunicipiosPorcentajes = function(cpro,cmun) { var promise=consultaDepuracionService.obtenerMunicipiosTotalPorcentajes(cpro,cmun,$log, $http); promise.then(function(data){ $scope.municipiosTotal=data.data; $scope.mostrarTabla=true; }); } $scope.calculaProcentaje=function (total, parcial) { if(parcial==0) return 0; else return Math.round(parcial/total*10000)/100; } } ); app.controller('ConsultaEntidadesController', function($scope,$log, $http,$q,$rootScope,consultaEntidadesService) { $scope.disMunicipio = true; $scope.disVia = true; $scope.mostrarTabla = false; $scope.mostrarTablaInmuebles = false; $scope.getAppsMarcas = function(cpro,cmun,cvia,clase) { $scope.mostrarTabla = false; $scope.mostrarTablaInmuebles = false; consultaEntidadesService.obtenerAppsViaMarcas(cpro, cmun, cvia, clase, $log, $http).then(function(data) { $scope.apps=data.data; $scope.mostrarTabla=true; }); } $scope.getAppsMarcasInmueble = function(cpro,cmun,cvia,clase) { $scope.mostrarTabla = false; $scope.mostrarTablaInmuebles = false; consultaEntidadesService.obtenerAppsViaMarcasInmueble(cpro, cmun, cvia, clase, $log, $http).then(function(data) { $scope.apps=data.data; $scope.mostrarTabla=true; }); } $scope.getMunicipios = function(cpro) { $scope.mostrarTabla = false; $scope.mostrarTablaInmuebles = false; consultaEntidadesService.obtenerMunicipios(cpro,$log, $http).then(function(data){ $scope.municipios=data.data; $scope.disMunicipio=false; }); } $scope.getVias = function(cpro,cmun) { $scope.mostrarTabla = false; $scope.mostrarTablaInmuebles = false; consultaEntidadesService.obtenerVias(cpro,cmun,$log, $http).then(function(data){ $scope.vias=data.data; $scope.disVia=false; }); } $scope.getUps= function(cpro,cmun) { consultaEntidadesService.obtenerUPs(cpro, cmun, $log, $http).then(function(data) { $scope.ups = {}; for(var i = 0; i < data.data.length; i++) { $scope.ups[data.data[i][0]+''+data.data[i][1]+''+data.data[i][2]+''+data.data[i][3]+''+data.data[i][4]] = data.data[i]; } }); } $scope.mostrarInmueblesApp = function(app) { consultaEntidadesService.obtenerInmueblesMarcas(app.nidenApp, $log, $http).then(function(data) { $scope.inmuebles = data.data; $scope.mostrarTablaInmuebles = true; }); } $scope.tablaAppsColumns = [ {data: 'nidenApp'}, {data: function(row, type, set, meta) { return $scope.ups[row.cpro+''+row.cmun+''+row.centco+''+row.centsi+''+row.cnucle][7]; }}, {data: function(row, type, set, meta) { return row.numero + (row.calificador ? row.calificador : ''); }}, {data: 'bloque'}, {data: 'portal'}, {data: function(row, type, set, meta) { return $scope.leyendaMarcas(row.depuracion, $scope.infoMarcas.app) }} ]; $scope.tablaInmueblesColumns = [ {data: 'nidenHueco'}, {data: 'escalera'}, {data: 'planta'}, {data: 'puerta'}, {data: function(row, type, set, meta) { return $scope.leyendaMarcas(row.depuracion, $scope.infoMarcas.inmueble) }} ]; }); app.controller('mainController', function($rootScope,$scope,$log, $http,consultaEntidadesService,consultaDepuracionService) { $rootScope.cabeceraCargada = false; $rootScope.sidebarCargada = false; /* Inicializa AdminLTE */ $rootScope.$on('$includeContentLoaded', function(event, src) { if(src == 'pages/template/cabecera.html') { $rootScope.cabeceraCargada = true; } else if(src == 'pages/template/sidebar.html') { $rootScope.sidebarCargada = true; } if($rootScope.cabeceraCargada && $rootScope.sidebarCargada) { $.AdminLTE.init(); } }); /* Cargamos las provincias*/ consultaEntidadesService.obtenerProvincias($log, $http).then(function(data) { $rootScope.provincias = {}; for(var i = 0; i < data.data.length; i++) { $rootScope.provincias[data.data[i].cpro] = data.data[i]; } }); /* Cargamos las provincias de depuración */ consultaDepuracionService.obtenerProvinciasPorcentajes($log, $http).then(function(data) { $rootScope.provinciasDepuracion = data.data; }); /* Cargamos la definición de las marcas */ consultaDepuracionService.obtenerInfoMarcas($log, $http).then(function(data) { $rootScope.infoMarcas = data.data; }); /* Función para transformar las marcas en una leyenda */ $rootScope.leyendaMarcas = function(marcas, infoMarcas) { marcas = marcas.replace(/-/g, ' '); var texto = ""; for(var i = 0; i < infoMarcas.length; i++) { var longitud = 1; if(infoMarcas[i].longitud) { longitud = infoMarcas[i].longitud; } var marca = marcas.substring(infoMarcas[i].pos - 1, infoMarcas[i].pos - 1 + longitud).trim(); if(marca.length > 0) { var desc = null; var leyenda = null; if(infoMarcas[i].valores && infoMarcas[i].valores[marca]) { desc = infoMarcas[i].valores[marca].desc; leyenda = infoMarcas[i].valores[marca].leyenda; } else if(infoMarcas[i].valor) { desc = infoMarcas[i].valor.desc.replace(/%s/g, marca); leyenda = infoMarcas[i].valor.leyenda; } if(leyenda) { texto += '<span title="' + desc + '" class="label bg-'; switch(leyenda[0]) { case 'NUM': texto += 'teal">N '; break; case 'CAL': texto += 'purple">C '; break; case 'BLQ': texto += 'orange">B '; break; case 'POR': texto += 'maroon">P '; break; case 'ESC': texto += 'green">E '; break; case 'PLA': texto += 'yellow">P '; break; case 'PUE': texto += 'red">P '; break; default: texto += 'gray">'; } texto += '<i class="fa ' + leyenda[1] + '"></i>'; if(leyenda.length > 2) { texto += ' ' + leyenda[2]; } texto += '</span> '; } } } return texto; }; }); app.controller('EjecutarMarcadoController', function($scope, $log, $http, consultaEntidadesService, consultaDepuracionService) { $scope.ejecutar = 0; // 1 - App, 2 - Inmueble $scope.lanzado = false; $scope.mostrarFiltroApps = function() { $scope.ejecutar = 1; $scope.lanzado = false; $scope.provinciaSelect = null; $scope.municipioSelect = null; $scope.upSelect = null; $scope.viaSelect = null; $scope.appSelect = null; } $scope.mostrarFiltroInmuebles = function() { $scope.ejecutar = 2; $scope.lanzado = false; $scope.provinciaSelect = null; $scope.municipioSelect = null; $scope.upSelect = null; $scope.viaSelect = null; $scope.appSelect = null; } $scope.getMunicipios = function(cpro) { $scope.municipioSelect = null; $scope.upSelect = null; $scope.viaSelect = null; $scope.appSelect = null; consultaEntidadesService.obtenerMunicipios(cpro, $log, $http).then(function(data) { $scope.municipios = data.data; }); } $scope.getUPs = function(cpro, cmun) { $scope.upSelect = null; $scope.viaSelect = null; $scope.appSelect = null; consultaEntidadesService.obtenerUPs(cpro, cmun, $log, $http).then(function(data) { $scope.ups = data.data; }); } $scope.getVias = function(cpro, cmun, centco, centsi, cnucle) { $scope.viaSelect = null; $scope.appSelect = null; consultaEntidadesService.obtenerViasUP(cpro, cmun, centco, centsi, cnucle, $log, $http).then(function(data) { $scope.vias=data.data; }); } $scope.getApps = function(cpro, cmun, centco, centsi, cnucle, cvia, clase) { $scope.appSelect = null; if($scope.ejecutar == 2) { consultaEntidadesService.obtenerAppsViaUP(cpro, cmun, centco, centsi, cnucle, cvia, clase, $log, $http).then(function(data) { $scope.apps=data.data; }); } } $scope.descripcionUP = function(up) { var ec = up[5].trim(); var es = up[6].trim(); var nd = up[7].trim(); var descripcion = ""; var partes = 0; var ultimo = ""; if(ec.length > 0) { descripcion = ec; partes++; ultimo = ec; } if(es.length > 0 && es != ultimo) { if(partes == 0) { descripcion = es; } else { descripcion += " (" + es; } partes++; ultimo = es; } if(nd.length > 0 && nd != ultimo) { if(partes == 0) { descripcion = nd; } else if(partes == 1) { descripcion += " (" + nd; } else { descripcion += ", " + nd; } partes++; } if(partes > 1) { descripcion += ")"; } return descripcion; } $scope.descripcionApp = function(app) { var descripcion = app.tnum; if(app.numero) { descripcion += " " + app.numero; if(app.calificador) { descripcion += app.calificador; } } else if(app.kmt) { descripcion += " " + app.kmt; if(app.hmt) { descripcion += "," + app.hmt; } } if(app.bloque) { descripcion += " Bloque " + app.bloque; } if(app.portal) { descripcion += " Portal " + app.portal; } if(app.escalera) { descripcion += " Escalera " + app.escalera; } return descripcion; } $scope.marcar = function(modo, provincia, municipio, up, via, app) { var cpro = (provincia ? provincia.cpro : null); var cmun = (municipio ? municipio.cmun: null); var centco = (up ? up[2] : null); var centsi = (up ? up[3] : null); var cnucle = (up ? up[4] : null); var cvia = (via ? via.cvia : null); var clase = (via ? via.clase : null); var nidenApp = (app ? app.nidenApp : null); if(modo == 1) { consultaDepuracionService.marcarApp(cpro, cmun, centco, centsi, cnucle, cvia, clase, $log, $http); } else { consultaDepuracionService.marcarInmueble(cpro, cmun, centco, centsi, cnucle, cvia, clase, nidenApp, $log, $http); } $scope.lanzado = true; $scope.ejecutar = 0; } });
mit
MetaConc/SOMns
src/som/primitives/arithmetic/DividePrim.java
1370
package som.primitives.arithmetic; import java.math.BigInteger; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.source.SourceSection; import som.primitives.Primitive; @GenerateNodeFactory @Primitive(primitive = "int:divideBy:", selector = "/") public abstract class DividePrim extends ArithmeticPrim { protected DividePrim(final boolean eagWrap, final SourceSection source) { super(eagWrap, source); } @Specialization public final long doLong(final long left, final long right) { return left / right; } @Specialization @TruffleBoundary public final Object doBigInteger(final BigInteger left, final BigInteger right) { BigInteger result = left.divide(right); return reduceToLongIfPossible(result); } @Specialization @TruffleBoundary public final Object doBigInteger(final BigInteger left, final long right) { return doBigInteger(left, BigInteger.valueOf(right)); } @Specialization @TruffleBoundary public final Object doLong(final long left, final BigInteger right) { return doBigInteger(BigInteger.valueOf(left), right); } @Specialization public final Object doLong(final long left, final double right) { return (long) (left / right); } }
mit
sinch/csharp-nps-sms-delighted
NPSSMSVoting/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
543
using System.Collections.Generic; using System.Collections.ObjectModel; namespace NPSSMSVoting.Areas.HelpPage.ModelDescriptions { public class ParameterDescription { public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); } public Collection<ParameterAnnotation> Annotations { get; private set; } public string Documentation { get; set; } public string Name { get; set; } public ModelDescription TypeDescription { get; set; } } }
mit
foodoasisla/foodoasis.la
assets/js/location-list-nav.js
2758
"use strict"; var PAGE_PARAMETERS = void 0; var getParameterByName = void 0; var updateLink = void 0; (function () { // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript#answer-901144 getParameterByName = function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); }; PAGE_PARAMETERS = { type: getParameterByName('type') || PAGE_TYPE, address: getParameterByName('address'), deserts: getParameterByName('deserts'), open: getParameterByName('open'), openStart: getParameterByName('open_start') }; // SHIM: Make the type persistent updateLink = function updateLink(link) { var params = []; if (PAGE_PARAMETERS.type) params.push('type=' + PAGE_PARAMETERS.type); if (PAGE_PARAMETERS.address) params.push('address=' + PAGE_PARAMETERS.address); if (PAGE_PARAMETERS.deserts) params.push('deserts=' + PAGE_PARAMETERS.deserts); if (PAGE_PARAMETERS.open) params.push('open=' + PAGE_PARAMETERS.open); if (PAGE_PARAMETERS.openStart) params.push('open_start=' + PAGE_PARAMETERS.openStart); var queryString = params.join('&'); link.setAttribute('href', link.getAttribute('href') + '?' + queryString); }; if (PAGE_PARAMETERS.type || PAGE_PARAMETERS.address || PAGE_PARAMETERS.deserts || PAGE_PARAMETERS.open || PAGE_PARAMETERS.openStart) { var filtersLink = document.getElementById('filters-link'); if (filtersLink) { updateLink(filtersLink); } var searchLink = document.getElementById('search-link'); if (searchLink) { updateLink(searchLink); } } if (PAGE_PARAMETERS.type) { var types = PAGE_PARAMETERS.type.split('|'); var searchType = document.getElementById('search-type'); var near = document.getElementById('search-near'); if (types.length === 1 || types.length === 2) { // SHIM: Translate to a human readable version of the “type”. var formattedTypes = []; for (var index = 0; index < types.length; index++) { formattedTypes.push(types[index] === 'food-pantry' ? 'food pantries' : types[index] === 'summer-lunch' ? 'summer lunch for kids' : types[index].replace(/\-/g, ' ') + 's'); } searchType.innerText = formattedTypes.join(', '); searchType.style.textTransform = 'capitalize'; //searchType.style.display = 'inline'; //near.style.display = 'inline'; } else { //searchType.style.display = 'none'; //near.style.display = 'none'; searchType.innerText = 'Everything'; searchType.style.textTransform = 'capitalize'; } } })();
mit
ravenshooter/BA_Analysis
Preprocess.py
5604
import numpy import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import scipy import mdp import csv from thread import start_new_thread import DataSet from DataAnalysis import plot from Main import getProjectPath def readFileToNumpy(fileName): reader=csv.reader(open(fileName,"rb"),delimiter=',') x=list(reader) return numpy.array(x[1:]).astype('float') def separateInputData(fileData,removeErrors=True): if removeErrors: error_inds = fileData[:,-1]==False fileData = fileData[error_inds] fused = numpy.atleast_2d(fileData[:,1:4]) gyro = numpy.atleast_2d(fileData[:,4:7]) acc = numpy.atleast_2d(fileData[:,7:10]) targets = numpy.atleast_2d(fileData[:,10:]) return fused, gyro, acc, targets def transformToDelta(vals): newVals = numpy.zeros((len(vals),len(vals[0]))) for i in range(1,len(vals)): newVals[i-1] = vals[i]-vals[i-1] return newVals def removeLOverflow(fused): for j in range(0,3): for i in range(1,len(fused)): if numpy.abs(fused[i-1,j] - fused[i,j]) > numpy.pi: fused[i:,j] = fused[i:,j] * -1 return fused def applyActivationFilter(inputData, width): actLevel = numpy.sum(numpy.abs(inputData),1) target = numpy.zeros((len(inputData),1)) for i in range(width,len(inputData-width)): target[i] = numpy.mean(actLevel[i-width:i+width]) return target def centerAndNormalize(inputData): means = numpy.mean(inputData, 0) centered = inputData - means vars = numpy.std(centered, 0) normalized = centered/vars return normalized, means, vars def getTrainingBeginAndEndIndex(targetSig): beginInd = 0 endInd = len(targetSig) for i in range(0,len(targetSig)): if targetSig[i] == 1: beginInd= i-1; break for i in range(0,len(targetSig)): if targetSig[len(targetSig)-1-i] == 1: endInd= len(targetSig)-i; break return beginInd,endInd def formatDataSet(data): print data.shape newStart = input("Start:") newEnd = input("End:") newData = data[newStart:newEnd,:] return newData def formatTargetFilter(data): treshold = input('Treshold:') targetFunction = applyFormatTargetFilter(data, treshold) plt.figure() plt.plot(data[:,9]) plt.plot(data[:,10]) plt.plot(targetFunction) return targetFunction def applyFormatTargetFilter(data, treshold): targetFunction = (data[:,10] > treshold).astype(float) return numpy.atleast_2d(targetFunction).T def removeArea(data): cutOutStart = input("Start:") cutOutEnd = input("End:") newDataStart = data[:cutOutStart,:] newDataEnd = data[cutOutEnd:,:] return numpy.concatenate((newDataStart,newDataEnd)) def plotData(data): plt.figure() plt.clf() plt.subplot(411) plt.title('Fused') plt.plot(data[:,0:3]) plt.plot(data[:,9]) plt.plot(data[:,10]) plt.subplot(412) plt.title('Gyro') plt.plot(data[:,3:6]) plt.plot(data[:,9]) plt.plot(data[:,10]) plt.subplot(413) plt.title('Acc') plt.plot(data[:,6:9]) plt.plot(data[:,9]) plt.plot(data[:,10]) plt.subplot(414) plt.title('Targets') plt.plot(data[:,9]) plt.plot(data[:,10]) plt.show() def writeToCSV(data,fileName): numpy.savetxt(getProjectPath()+"\\dataSets\\"+fileName+".csv", data, delimiter=";") def safeToDataSet(fileName, data, means, stds, gestures, targetTreshold): ds = DataSet.DataSet(data[:,0:3],data[:,3:6],data[:,6:9],numpy.append(data[:,9:], applyFormatTargetFilter(data, targetTreshold), 1), \ means, stds, gestures) ds.writeToFile(fileName) def load(nr): global i plt.close('all') i = readFile("nadja\\nadja_"+str(nr)+".csv") plotData(i) def safe(inputData,aaa,nr): writeToCSV(numpy.concatenate((inputData,numpy.atleast_2d(aaa).T),1),"nadja_fitted_"+str(nr)) def readFile(fileName): return readFileToNumpy(getProjectPath()+'dataSets\\'+fileName) if __name__ == '__main__': #def main(): inputFileName = ["2016-03-14-10-30-47-nike_fullSet_0.csv"] fileData = numpy.zeros((1,31)) for fileName in inputFileName: newData = readFileToNumpy(getProjectPath()+'dataSets\\'+fileName) print newData.shape fileData = numpy.append(fileData,newData,0) fused, gyro, acc, targets = separateInputData(fileData) #fused = removeLOverflow(fused) #fused = transformToDelta(fused) _, f_means, f_stds = centerAndNormalize(fused) _, g_means, g_stds = centerAndNormalize(gyro) _, a_means, a_stds = centerAndNormalize(acc) means = numpy.concatenate((f_means,g_means,a_means),0) stds = numpy.concatenate((f_stds,g_stds,a_stds),0) gestures = numpy.max(targets,0) dataSets = [] gestureSets = [] for i in range(0,len(targets[0])): start, end = getTrainingBeginAndEndIndex(targets[:,i]) t_fused = fused[start:end,:] t_gyro = gyro[start:end,:] t_acc = acc[start:end,:] t_target =numpy.atleast_2d(targets[start:end,i]).T t_accFilter = applyActivationFilter(numpy.concatenate((t_fused,t_gyro,t_acc),1),6) a = numpy.concatenate((t_fused,t_gyro,t_acc,t_target,t_accFilter),1) dataSets.append(a) gestureSets.append(numpy.max(targets[start:end,:],0))
mit
MarimerLLC/Bxf
Bxf.Shared/PortedAttributes.cs
1124
//----------------------------------------------------------------------- // <copyright file="PortedAttributes.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Placeholder for missing Browsable attribute from full .NET.</summary> //----------------------------------------------------------------------- #if WINDOWS_UWP using System; namespace Bxf { /// <summary> /// Placeholder for missing Browsable attribute from full .NET. /// </summary> public class BrowsableAttribute : Attribute { /// <summary> /// Creates an instance of the attribute. /// </summary> /// <param name="value"></param> public BrowsableAttribute(bool value) { } } /// <summary> /// Placeholder for missing Category attribute from full .NET. /// </summary> public class CategoryAttribute : Attribute { /// <summary> /// Creates an instance of the attribute. /// </summary> /// <param name="value"></param> public CategoryAttribute(string value) { } } } #endif
mit
Bandydan/pdr
application/controllers/Start.php
536
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Start extends CI_Controller { public function index() { $this->load->library('twig'); $id = rand(1, 9); $data['title'] = 'Garage - Удаление вмятин без покраски'; $this->load->model('examples_model'); $data['examples'] = $this->examples_model->get_examples($id); $data['cat'] = $this->config->item('categories'); echo $this->twig->render('start_view', $data); } }
mit
sammarks/ablecore
lib/AbleCore/Forms/FormBase.php
235
<?php namespace AbleCore\Forms; abstract class FormBase { public abstract function build($form, &$form_state); public function submit($form, &$form_state) { return; } public function validate($form, &$form_state) { return; } }
mit
yinggaozhen/zaor-cache-orm
src/orm/sql/Select.php
979
<?php namespace zaor\orm\sql; /** * TODO 完善注释 */ class Select extends SQL { /** * @var string */ private $selectSql = 'SELECT * FROM <TABLE> <WHERE><ORDER><LIMIT><OFFSET>'; public function toString() { $sql = str_replace( ['<TABLE>', '<WHERE>', '<ORDER>', '<LIMIT>', '<OFFSET>'], [ $this->parseTable(isset($this->options['table']) ? $this->options['table'] : null), $this->parseWhere(isset($this->options['where']) ? $this->options['where'] : null), $this->parseOrder(isset($this->options['order']) ? $this->options['order'] : null), $this->parseLimit(isset($this->options['limit']) ? $this->options['limit'] : null, isset($this->options['offset']) ? $this->options['offset'] : null) ], $this->selectSql ); return $sql; } public function getParams() { return $this->params; } }
mit
ccxt/ccxt
python/ccxt/binanceus.py
1827
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.binance import binance class binanceus(binance): def describe(self): return self.deep_extend(super(binanceus, self).describe(), { 'id': 'binanceus', 'name': 'Binance US', 'countries': ['US'], # US 'certified': False, 'pro': True, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/65177307-217b7c80-da5f-11e9-876e-0b748ba0a358.jpg', 'api': { 'web': 'https://www.binance.us', 'sapi': 'https://api.binance.us/sapi/v1', 'wapi': 'https://api.binance.us/wapi/v3', 'public': 'https://api.binance.us/api/v3', 'private': 'https://api.binance.us/api/v3', }, 'www': 'https://www.binance.us', 'referral': 'https://www.binance.us/?ref=35005074', 'doc': 'https://github.com/binance-us/binance-official-api-docs', 'fees': 'https://www.binance.us/en/fee/schedule', }, 'fees': { 'trading': { 'tierBased': True, 'percentage': True, 'taker': self.parse_number('0.001'), # 0.1% trading fee, zero fees for all trading pairs before November 1 'maker': self.parse_number('0.001'), # 0.1% trading fee, zero fees for all trading pairs before November 1 }, }, 'options': { 'fetchCurrencies': False, 'quoteOrderQty': False, }, })
mit
liip/LiipUrlAutoConverterBundle
Extension/UrlAutoConverterTwigExtension.php
2804
<?php namespace Liip\UrlAutoConverterBundle\Extension; class UrlAutoConverterTwigExtension extends \Twig_Extension { protected $linkClass; protected $target; protected $debugMode; protected $debugColor = '#00ff00'; // @codeCoverageIgnoreStart public function getName() { return 'liip_urlautoconverter'; } public function setLinkClass($class) { $this->linkClass = $class; } public function setTarget($target) { $this->target = $target; } public function setDebugMode($debug) { $this->debugMode = $debug; } public function setDebugColor($color) { $this->debugColor = $color; } // @codeCoverageIgnoreEnd public function getFilters() { return array( new \Twig_SimpleFilter( 'converturls', array($this, 'autoConvertUrls'), array( 'pre_escape' => 'html', 'is_safe' => array('html'), ) ), ); } /** * method that finds different occurrences of urls or email addresses in a string. * * @param string $string input string * * @return string with replaced links */ public function autoConvertUrls($string) { $pattern = '/(href="|src=")?([-a-zA-Zа-яёА-ЯЁ0-9@:%_\+.~#?&\*\/\/=]{2,256}\.[a-zа-яё]{2,4}\b(\/?[-\p{L}0-9@:%_\+.~#?&\*\/\/=\(\),;]*)?)/u'; $stringFiltered = preg_replace_callback($pattern, array($this, 'callbackReplace'), $string); return $stringFiltered; } public function callbackReplace($matches) { if ($matches[1] !== '') { return $matches[0]; // don't modify existing <a href="">links</a> and <img src=""> } $url = $matches[2]; $urlWithPrefix = $matches[2]; if (strpos($url, '@') !== false) { $urlWithPrefix = 'mailto:'.$url; } elseif (strpos($url, 'https://') === 0) { $urlWithPrefix = $url; } elseif (strpos($url, 'http://') !== 0) { $urlWithPrefix = 'http://'.$url; } $style = ($this->debugMode) ? ' style="color:'.$this->debugColor.'"' : ''; // ignore tailing special characters // TODO: likely this could be skipped entirely with some more tweakes to the regular expression if (preg_match("/^(.*)(\.|\,|\?)$/", $urlWithPrefix, $matches)) { $urlWithPrefix = $matches[1]; $url = substr($url, 0, -1); $punctuation = $matches[2]; } else { $punctuation = ''; } return '<a href="'.$urlWithPrefix.'" class="'.$this->linkClass.'" target="'.$this->target.'"'.$style.'>'.$url.'</a>'.$punctuation; } }
mit
BreixoAM/cordova-plugin-nativebundle
www/Frame.js
1471
var argscheck = require('cordova/argscheck'), channel = require('cordova/channel'), utils = require('cordova/utils'), exec = require('cordova/exec'), cordova = require('cordova'); function Frame() { }; Frame.prototype.getHeader = function() { return this.header; }; Frame.prototype.getSlider = function() { return this.slider; }; Frame.prototype.getContent = function() { return this.content; }; Frame.prototype.getMainColor = function(callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameGetMainColor", []); }; Frame.prototype.setMainColor = function (mainColor, callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameSetMainColor", [mainColor]); }; Frame.prototype.getMainColorDark = function(callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameGetMainColorDark", []); }; Frame.prototype.setMainColorDark = function(mainColorDark, callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameSetMainColorDark", [mainColorDark]); }; Frame.prototype.showSpinner = function(callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameShowSpinner", []); }; Frame.prototype.hideSpinner = function(callback) { if (!callback) callback = function() {}; exec(callback, function(){}, "Tgw", "frameHideSpinner", []); }; module.exports = Frame;
mit
stewartwinter/bggpersonal
BGGPersonal/src/ca/winterfamily/bggpersonal/BGGActivity.java
226
package ca.winterfamily.bggpersonal; import android.support.v4.app.Fragment; public class BGGActivity extends SingleFragmentActivity { @Override protected Fragment createFragment() { return new GameFragment(); } }
mit
scirate/scirate
app/helpers/application_helper.rb
1598
require 'jwt' require 'net/http' require 'json' module ApplicationHelper def status_warning raw "<span class=\"warning\">#{current_user.account_status}:</span>" end def timeago(dt) dt = Time.parse(dt) if dt.is_a? String raw "<abbr class=\"timeago\" title=\"#{dt.iso8601}\">#{dt.strftime("%b %d %Y %R UTC")}</abbr>" end def user_link(user) raw "<a href='/#{h(user.username)}'>#{h(user.fullname)}</a>" end def mk_jwt_token(role, job_token) exp = Time.now.to_i + (Settings::JWT_EXPIRY_MINUTES * 60) payload = { 'admin': false, 'exp': exp, 'https://hasura.io/jwt/claims': { 'x-hasura-allowed-roles': [role], 'x-hasura-default-role': role, 'x-hasura-job-token': job_token || "", 'x-hasura-job-date-modified': Time.now } } alg = Settings::GRAPHQL_JWT_ALGORITHM key = Settings::GRAPHQL_JWT_SECRET JWT.encode payload, key, alg end def run_graphql_query(query) token = mk_jwt_token('ruby', '') uri = URI(Settings::GRAPHQL_URL) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json', 'Authorization' => "Bearer #{token}"}) req.body = {'query': query}.to_json res = http.request(req) JSON.parse(res.body) end rescue => e logger.error("Error with GraphQL: #{e}") {} end end
mit
coinkeeper/2015-06-22_19-14_wildbeastbitcoin
src/qt/locale/bitcoin_pt_PT.ts
119692
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About WildBeastBitcoin</source> <translation>Sobre WildBeastBitcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;WildBeastBitcoin&lt;/b&gt; version</source> <translation>Versão do &lt;b&gt;WildBeastBitcoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <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 ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Este é um programa experimental. Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php. Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young ([email protected]) e software UPnP escrito por Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The WildBeastBitcoin developers</source> <translation>Os programadores WildBeastBitcoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Livro de endereços</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Clique duas vezes para editar o endereço ou o rótulo</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copie o endereço selecionado para a área de transferência</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Novo Endereço</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your WildBeastBitcoin 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>Estes são os seus endereços WildBeastBitcoin para receber pagamentos. Poderá enviar um endereço diferente para cada remetente para poder identificar os pagamentos.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar Código &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a WildBeastBitcoin address</source> <translation>Assine uma mensagem para provar que é dono de um endereço WildBeastBitcoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Apagar o endereço selecionado da lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified WildBeastBitcoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço WildBeastBitcoin especificado</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>E&amp;liminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your WildBeastBitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estes são os seus endereços WildBeastBitcoin para enviar pagamentos. Verifique sempre o valor e a morada de envio antes de enviar moedas.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Rótulo</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar &amp;Moedas</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportar dados do Livro de Endereços</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Não foi possível escrever para o ficheiro %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de Frase-Passe</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Escreva a frase de segurança</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <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>Escreva a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Encriptar carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencriptar carteira</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar encriptação da carteira</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 RONPAULCOINS&lt;/b&gt;!</source> <translation>Atenção: Se encriptar a carteira e perder a sua senha irá &lt;b&gt;PERDER TODOS OS SEUS RONPAULCOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem a certeza que deseja encriptar a carteira?</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>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atenção: A tecla Caps Lock está activa!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Carteira encriptada</translation> </message> <message> <location line="-56"/> <source>WildBeastBitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your wildbeastbitcoins from being stolen by malware infecting your computer.</source> <translation>O cliente WildBeastBitcoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus wildbeastbitcoins de serem roubados por programas maliciosos que infectem o seu computador.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>A encriptação da carteira falhou</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>As frases de segurança fornecidas não coincidem.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>O desbloqueio da carteira falhou</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>A desencriptação da carteira falhou</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Assinar &amp;mensagem...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronizando com a rede...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>Visã&amp;o geral</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editar a lista de endereços e rótulos</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostrar a lista de endereços para receber pagamentos</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Fec&amp;har</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <location line="+4"/> <source>Show information about WildBeastBitcoin</source> <translation>Mostrar informação sobre WildBeastBitcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar informação sobre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>E&amp;ncriptar Carteira...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar Carteira...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Mudar &amp;Palavra-passe...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importando blocos do disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Reindexando blocos no disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a WildBeastBitcoin address</source> <translation>Enviar moedas para um endereço wildbeastbitcoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for WildBeastBitcoin</source> <translation>Modificar opções de configuração para wildbeastbitcoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Faça uma cópia de segurança da carteira para outra localização</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Janela de &amp;depuração</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de diagnóstico e depuração</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>WildBeastBitcoin</source> <translation>WildBeastBitcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Receber</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>E&amp;ndereços</translation> </message> <message> <location line="+22"/> <source>&amp;About WildBeastBitcoin</source> <translation>&amp;Sobre o WildBeastBitcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar / Ocultar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar ou esconder a Janela principal</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encriptar as chaves privadas que pertencem à sua carteira</translation> </message> <message> <location line="+7"/> <source>Sign messages with your WildBeastBitcoin addresses to prove you own them</source> <translation>Assine mensagens com os seus endereços WildBeastBitcoin para provar que os controla</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified WildBeastBitcoin addresses</source> <translation>Verifique mensagens para assegurar que foram assinadas com o endereço WildBeastBitcoin especificado</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Ficheiro</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>Con&amp;figurações</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>A&amp;juda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de separadores</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> <message> <location line="+47"/> <source>WildBeastBitcoin client</source> <translation>Cliente WildBeastBitcoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to WildBeastBitcoin network</source> <translation><numerusform>%n ligação ativa à rede WildBeastBitcoin</numerusform><numerusform>%n ligações ativas à rede WildBeastBitcoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Nenhum bloco fonto disponível</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processados %1 dos %2 blocos (estimados) do histórico de transacções.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processados %1 blocos do histórico de transações.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 em atraso</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Último bloco recebido foi gerado há %1 atrás.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transações posteriores poderão não ser imediatamente visíveis.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+70"/> <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>Esta transação tem um tamanho superior ao limite máximo. Poderá enviá-la pagando uma taxa de %1, que será entregue ao nó que processar a sua transação e ajudará a suportar a rede. Deseja pagar a taxa?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Recuperando...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirme a taxa de transação</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantia: %2 Tipo: %3 Endereço: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Manuseamento URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid WildBeastBitcoin address or malformed URI parameters.</source> <translation>URI não foi lido correctamente! Isto pode ser causado por um endereço WildBeastBitcoin inválido ou por parâmetros URI malformados.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. WildBeastBitcoin can no longer continue safely and will quit.</source> <translation>Ocorreu um erro fatal. O WildBeastBitcoin não pode continuar com segurança e irá fechar.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Rótulo</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>O rótulo a ser associado com esta entrada do livro de endereços</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>E&amp;ndereço</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>O endereço associado com esta entrada do livro de endereços. Apenas poderá ser modificado para endereços de saída.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Novo endereço de entrada</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Novo endereço de saída</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar endereço de entrada</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar endereço de saída</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>O endereço introduzido &quot;%1&quot; já se encontra no livro de endereços.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid WildBeastBitcoin address.</source> <translation>O endereço introduzido &quot;%1&quot; não é um endereço wildbeastbitcoin válido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossível desbloquear carteira.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Falha ao gerar nova chave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>WildBeastBitcoin-Qt</source> <translation>WildBeastBitcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versão</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opções da linha de comandos</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Opções de UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Definir linguagem, por exemplo &quot;pt_PT&quot; (por defeito: linguagem do sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar animação ao iniciar (por defeito: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opções</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</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.</source> <translation>Taxa de transação opcional por KB que ajuda a assegurar que as suas transações serão processadas rapidamente. A maioria das transações tem 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar &amp;taxa de transação</translation> </message> <message> <location line="+31"/> <source>Automatically start WildBeastBitcoin after logging in to the system.</source> <translation>Começar o WildBeastBitcoin automaticamente ao iniciar sessão no sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start WildBeastBitcoin on system login</source> <translation>&amp;Começar o WildBeastBitcoin ao iniciar o sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Repôr todas as opções.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Repôr Opções</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <location line="+6"/> <source>Automatically open the WildBeastBitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir a porta do cliente wildbeastbitcoin automaticamente no seu router. Isto penas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the WildBeastBitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Ligar à rede WildBeastBitcoin através de um proxy SOCKS (p.ex. quando ligar através de Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Ligar através de proxy SO&amp;CKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Endereço IP do proxy (p.ex. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta do proxy (p.ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versão SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versão do proxy SOCKS (p.ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja e não para a barra de ferramentas</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>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao fechar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Vis&amp;ualização</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Linguagem da interface de utilizador:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting WildBeastBitcoin.</source> <translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o WildBeastBitcoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade a usar em quantias:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show WildBeastBitcoin addresses in the transaction list or not.</source> <translation>Se mostrar, ou não, os endereços WildBeastBitcoin na lista de transações.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Mostrar en&amp;dereços na lista de transações</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>padrão</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirme a reposição de opções</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algumas opções requerem o reinício do programa para funcionar.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Deseja proceder?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting WildBeastBitcoin.</source> <translation>Esta opção entrará em efeito após reiniciar o WildBeastBitcoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>O endereço de proxy introduzido é inválido. </translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the WildBeastBitcoin network after a connection is established, but this process has not completed yet.</source> <translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede WildBeastBitcoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Não confirmado:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>O saldo minado ainda não maturou</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transações recentes&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>O seu saldo atual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de transações ainda não confirmadas, e que não estão contabilizadas ainda no seu saldo actual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start wildbeastbitcoin: click-to-pay handler</source> <translation>Impossível começar o modo clicar-para-pagar com wildbeastbitcoin:</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Diálogo de Código QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Requisitar Pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Rótulo:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mensagem:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salvar Como...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Erro ao codificar URI em Código QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>A quantia introduzida é inválida, por favor verifique.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Guardar Código QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagens PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome do Cliente</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="+339"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versão do Cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Usando versão OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo de início</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rede</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de ligações</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Em rede de testes</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadeia de blocos</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de blocos</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimado de blocos</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tempo do último bloco</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opções de linha de comandos</translation> </message> <message> <location line="+7"/> <source>Show the WildBeastBitcoin-Qt help message to get a list with possible WildBeastBitcoin command-line options.</source> <translation>Mostrar a mensagem de ajuda do WildBeastBitcoin-Qt para obter uma lista com possíveis opções a usar na linha de comandos.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Mo&amp;strar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data de construção</translation> </message> <message> <location line="-104"/> <source>WildBeastBitcoin - Debug window</source> <translation>WildBeastBitcoin - Janela de depuração</translation> </message> <message> <location line="+25"/> <source>WildBeastBitcoin Core</source> <translation>Núcleo WildBeastBitcoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Ficheiro de registo de depuração</translation> </message> <message> <location line="+7"/> <source>Open the WildBeastBitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the WildBeastBitcoin RPC console.</source> <translation>Bem-vindo à consola RPC WildBeastBitcoin.</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>Use as setas para cima e para baixo para navegar no histórico e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar o ecrã.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Digite &lt;b&gt;help&lt;/b&gt; para visualizar os comandos disponíveis.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar para múltiplos destinatários de uma vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adicionar &amp;Destinatário</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Remover todos os campos da transação</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Limpar Tudo</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirme ação de envio</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; para %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirme envio de moedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Tem a certeza que deseja enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> e </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço de destino não é válido, por favor verifique.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A quantia a pagar deverá ser maior que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>A quantia excede o seu saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Erro: A criação da transacção falhou! </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>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Qu&amp;antia:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar A:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço para onde enviar o pagamento (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Rótu&amp;lo:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Escolher endereço do livro de endereços</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>Cole endereço da área de transferência</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>Remover este destinatário</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a WildBeastBitcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço WildBeastBitcoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma Mensagem</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>A&amp;ssinar Mensagem</translation> </message> <message> <location line="+6"/> <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>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço a utilizar para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Escolher endereço do livro de endereços</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</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>Escreva aqui a mensagem que deseja assinar</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Assinatura</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura actual para a área de transferência</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this WildBeastBitcoin address</source> <translation>Assine uma mensagem para provar que é dono deste endereço WildBeastBitcoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Repôr todos os campos de assinatura de mensagem</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+6"/> <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>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço utilizado para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified WildBeastBitcoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço WildBeastBitcoin especificado</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Repôr todos os campos de verificação de mensagem</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a WildBeastBitcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço WildBeastBitcoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clique &quot;Assinar mensagem&quot; para gerar a assinatura</translation> </message> <message> <location line="+3"/> <source>Enter WildBeastBitcoin signature</source> <translation>Introduza assinatura WildBeastBitcoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>O endereço introduzido é inválido. </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>Por favor verifique o endereço e tente de novo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>O endereço introduzido não refere a chave alguma.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>O desbloqueio da carteira foi cancelado.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço introduzido não está disponível.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Assinatura de mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>A assinatura não pôde ser descodificada.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Por favor verifique a assinatura e tente de novo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>A assinatura não condiz com o conteúdo da mensagem.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The WildBeastBitcoin developers</source> <translation>Os programadores WildBeastBitcoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/desligado</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/não confirmada</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Origem</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gerado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>endereço próprio</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>rótulo</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>não aceite</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensagem</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentário</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID da Transação</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 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>Moedas geradas deverão maturar por 120 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, irá mudar o estado para &quot;não aceite&quot; e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transação</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadeiro</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi transmitida com sucesso</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta janela mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantia</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Desligado (%1 confirmação)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Não confirmada (%1 de %2 confirmações)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmada (%1 confirmação)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n bloco</numerusform><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n blocos</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gerado mas não aceite</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recebido com</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento ao próprio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e hora a que esta transação foi recebida.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantia retirada ou adicionada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Todas</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoje</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mês</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este ano</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Período...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recebida com</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviada para</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para si</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minadas</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Outras</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Escreva endereço ou rótulo a procurar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantia mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar rótulo</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar Dados das Transações</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgula (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossível escrever para o ficheiro %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Período:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>até</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Cópia de Segurança da Carteira</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dados da Carteira (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Cópia de Segurança Falhou</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Ocorreu um erro ao tentar guardar os dados da carteira na nova localização.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Cópia de Segurança Bem Sucedida</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Os dados da carteira foram salvos com sucesso numa nova localização.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>WildBeastBitcoin version</source> <translation>Versão WildBeastBitcoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or wildbeastbitcoind</source> <translation>Enviar comando para -server ou wildbeastbitcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listar comandos</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Obter ajuda para um comando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opções:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: wildbeastbitcoin.conf)</source> <translation>Especificar ficheiro de configuração (por defeito: wildbeastbitcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: wildbeastbitcoind.pid)</source> <translation>Especificar ficheiro pid (por defeito: wildbeastbitcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar pasta de dados</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Escute por ligações em &lt;port&gt; (por defeito: 9333 ou testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manter no máximo &lt;n&gt; ligações a outros nós da rede (por defeito: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especifique o seu endereço público</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Escutar por ligações JSON-RPC em &lt;port&gt; (por defeito: 9332 ou rede de testes: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar comandos da consola e JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Correr o processo como um daemon e aceitar comandos</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizar a rede de testes - testnet</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=wildbeastbitcoinrpc 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;WildBeastBitcoin Alert&quot; [email protected] </source> <translation>%s, deverá definir rpcpassword no ficheiro de configuração : %s É recomendado que use a seguinte palavra-passe aleatória: rpcuser=wildbeastbitcoinrpc rpcpassword=%s (não precisa recordar esta palavra-passe) O nome de utilizador e password NÃO DEVEM ser iguais. Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono. Também é recomendado definir alertnotify para que seja alertado sobre problemas; por exemplo: alertnotify=echo %%s | mail -s &quot;Alerta WildBeastBitcoin&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Trancar a endereço específio e sempre escutar nele. Use a notação [anfitrião]:porta para IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. WildBeastBitcoin is probably already running.</source> <translation>Impossível trancar a pasta de dados %s. Provavelmente o WildBeastBitcoin já está a ser executado.</translation> </message> <message> <location line="+3"/> <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>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation> </message> <message> <location line="+4"/> <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>Erro: Esta transação requer uma taxa de transação mínima de %s devido á sua quantia, complexidade, ou uso de fundos recebidos recentemente! </translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Executar comando quando um alerta relevante for recebido (no comando, %s é substituído pela mensagem)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Definir tamanho máximo de transações de alta-/baixa-prioridade em bytes (por defeito: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Esta é uma versão de pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Atenção: As transações mostradas poderão não estar correctas! Poderá ter que atualizar ou outros nós poderão ter que atualizar.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong WildBeastBitcoin will not work properly.</source> <translation>Atenção: Por favor verifique que a data e hora do seu computador estão correctas! Se o seu relógio não estiver certo o WildBeastBitcoin não irá funcionar correctamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation> </message> <message> <location line="+3"/> <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>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opções de criação de bloco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Apenas ligar ao(s) nó(s) especificado(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Cadeia de blocos corrompida detectada</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Deseja reconstruir agora a cadeia de blocos?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Erro ao inicializar a cadeia de blocos</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Erro ao inicializar o ambiente de base de dados da carteira %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Erro ao carregar cadeia de blocos</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Erro ao abrir a cadeia de blocos</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Erro: Pouco espaço em disco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Erro: Carteira bloqueada, incapaz de criar transação! </translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Erro: erro do sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Falha ao ler info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Falha ao ler bloco</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Falha ao sincronizar índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Falha ao escrever índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Falha ao escrever info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Falha ao escrever o bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Falha ao escrever info do ficheiro</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Falha ao escrever na base de dados de moedas</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Falha ao escrever índice de transações</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Falha ao escrever histórico de modificações</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Encontrar pares usando procura DNS (por defeito: 1 excepto -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Gerar moedas (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quantos blocos verificar ao começar (por defeito: 288, 0 = todos)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Qual a minúcia na verificação de blocos (0-4, por defeito: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Descritores de ficheiros disponíveis são insuficientes.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir a cadeia de blocos dos ficheiros blk000??.dat actuais</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Defina o número de processos para servir as chamadas RPC (por defeito: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificando blocos...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificando a carteira...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importar blocos de um ficheiro blk000??.dat externo</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Defina o número de processos de verificação (até 16, 0 = automático, &lt;0 = disponibiliza esse número de núcleos livres, por defeito: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Endereço -tor inválido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -mintxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Manter índice de transações completo (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Armazenamento intermédio de recepção por ligação, &lt;n&gt;*1000 bytes (por defeito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Armazenamento intermédio de envio por ligação, &lt;n&gt;*1000 bytes (por defeito: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Apenas aceitar cadeia de blocos coincidente com marcas de verificação internas (por defeito: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Apenas ligar a nós na rede &lt;net&gt; (IPv4, IPv6 ou Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produzir informação de depuração extra. Implica todas as outras opções -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Produzir informação de depuração extraordinária</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Preceder informação de depuração com selo temporal</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the WildBeastBitcoin Wiki for SSL setup instructions)</source> <translation>Opções SSL: (ver a Wiki WildBeastBitcoin para instruções de configuração SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecione a versão do proxy socks a usar (4-5, padrão: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Enviar informação de rastreio/depuração para o depurador</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Definir tamanho máximo de um bloco em bytes (por defeito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Falhou assinatura da transação</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Erro de sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Quantia da transação é muito baixa</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Quantia da transação deverá ser positiva</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transação grande demais</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Utilizar proxy para aceder a serviços escondidos Tor (por defeito: mesmo que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome de utilizador para ligações JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Necessita reconstruir as bases de dados usando -reindex para mudar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, recuperação falhou</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Palavra-passe para ligações JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir ligações JSON-RPC do endereço IP especificado</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comandos para o nó a correr em &lt;ip&gt; (por defeito: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atualize a carteira para o formato mais recente</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Definir o tamanho da memória de chaves para &lt;n&gt; (por defeito: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para ligações JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chave privada do servidor (por defeito: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifras aceitáveis (por defeito: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Ligar através de um proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Carregar endereços...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira danificada</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of WildBeastBitcoin</source> <translation>Erro ao carregar wallet.dat: A Carteira requer uma versão mais recente do WildBeastBitcoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart WildBeastBitcoin to complete</source> <translation>A Carteira precisou ser reescrita: reinicie o WildBeastBitcoin para completar</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Endereço -proxy inválido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rede desconhecida especificada em -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versão desconhecida de proxy -socks requisitada: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Quantia inválida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fundos insuficientes</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Carregar índice de blocos...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. WildBeastBitcoin is probably already running.</source> <translation>Incapaz de vincular à porta %s neste computador. Provavelmente o WildBeastBitcoin já está a funcionar.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa por KB a adicionar a transações enviadas</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Carregar carteira...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Impossível mudar a carteira para uma versão anterior</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Impossível escrever endereço por defeito</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Reexaminando...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Carregamento completo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Para usar a opção %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="-31"/> <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>Deverá definir rpcpassword=&lt;password&gt; no ficheiro de configuração: %s Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation> </message> </context> </TS>
mit
CanyonCounty/LogRotater
LogRotater/PartialClass/Program.OldFiles.cs
958
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace LogRotater { internal partial class Program { private static void HandleOldFiles(string fileMask) { if (DeleteFiles == true) { if (LogDirectoryExists) { string[] files = Directory.GetFiles(LogDirectory, fileMask, SearchOption.AllDirectories); Console.WriteLine("Number of Files: " + files.Count()); foreach (string file in files) { Console.WriteLine(""); Console.WriteLine("Checking: " + file); if (OlderThan(file, DeleteOlderThanDays)) { Console.WriteLine("Deleting: " + file); File.Delete(file); } } } else { ConsoleError("Could not find Log Directory", 404); } } } } }
mit
nagoring/jp-address
src/Nago/JpAddress/StreetData/40/40349.php
478
<?php return ['403490005' => '上大隈','403490010' => '仲原','403490002' => '内橋','403490012' => '原町','403490004' => '大隈','403490009' => '戸原','403490018' => '戸原東','403490013' => '柚須','403490003' => '江辻','403490015' => '甲仲原','403490011' => '花ヶ浦','403490014' => '若宮','403490007' => '酒殿','403490008' => '長者原','403490017' => '長者原東','403490016' => '長者原西','403490001' => '阿恵','403490006' => '駕与丁',];
mit
keetaek/butler
api/models/guest.js
1846
const moment = require('moment'); module.exports = function(sequelize, DataTypes) { const Guest = sequelize.define('Guest', { first_name: DataTypes.STRING, last_name: DataTypes.STRING, nickname: DataTypes.STRING, birthdate: { type: DataTypes.DATEONLY, get: function() { if (moment(this.getDataValue('birthdate')).isValid()) { return moment.utc(this.getDataValue('birthdate')).format('YYYY-MM-DD'); } return this.getDataValue('birthdate'); }, }, gender: DataTypes.STRING, gender_note: DataTypes.STRING, emergency_contact_name: DataTypes.STRING, emergency_contact_phone: DataTypes.STRING, identification_type: DataTypes.STRING, identification_value: DataTypes.STRING, identification_need_by: { type: DataTypes.DATEONLY, get: function() { if (moment(this.getDataValue('identification_need_by')).isValid()) { return moment.utc(this.getDataValue('identification_need_by')).format('YYYY-MM-DD'); } return this.getDataValue('identification_need_by'); }, }, identification_note: DataTypes.TEXT, intake_form_collect_date: { type: DataTypes.DATEONLY, get: function() { if (moment(this.getDataValue('intake_form_collect_date')).isValid()) { return moment.utc(this.getDataValue('intake_form_collect_date')).format('YYYY-MM-DD'); } return this.getDataValue('intake_form_collect_date'); }, }, intake_form_collected_by: DataTypes.STRING }, { classMethods: { associate: function(models) { Guest.hasMany(models.Checkin, { foreignKey: 'guest_id' }); Guest.hasMany(models.Locker, { foreignKey: 'guest_id' }); Guest.hasMany(models.Bar, { foreignKey: 'guest_id' }); } } }); return Guest; };
mit
99xt/serverless-react-boilerplate
web/src/components/todo/todo-list.js
912
import _ from 'lodash'; import React from 'react'; import TodoListHeader from './todo-list-header'; import TodoListItem from './todo-list-item'; export default class TodoList extends React.Component { renderItems(){ const props = _.omit(this.props, 'todos'); return _.map(this.props.todos, (todo, index) => <TodoListItem key={index} {...todo} {...props} />); } render(){ return ( <div> <div className="row large-6 large-offset-3 medium-6 medium-offset-3 small-6 small-offset-3 columns"> <table className="hover"> <TodoListHeader/> <tbody> {this.renderItems()} </tbody> </table> </div> </div> ); } }
mit
joemsak/bowling
lib/bowling/players.rb
369
require "bowling/player" module Bowling class Players include Enumerable def initialize(names) @players ||= names.collect do |name| Player.new(name) end end def each(&block) @players.each(&block) end def method_missing(method_name, *args, &block) @players.send(method_name, *args, &block) end end end
mit
tiendat3535/easy-study-course
easy-sc-frontend/src/app/portal/portal.module.ts
1330
import { RouterModule, Routes } from '@angular/router'; import { AuthenticatedHomeComponent } from './component/authenticated-home.component'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoginComponent } from './component/login.component'; import { UnauthenticatedHomeComponent } from './component/unauthenticated-home.component'; const appRoutes: Routes = [ { path: 'public', children: [ { path: '', redirectTo: 'home', pathMatch: 'full', }, { path: 'login', component: LoginComponent }, { path: 'home', component: UnauthenticatedHomeComponent } ] }, { path: 'private', children: [ { path: '', redirectTo: 'public/login', pathMatch: 'full', }, { path: 'home', component: AuthenticatedHomeComponent } ] } ]; @NgModule({ imports: [ CommonModule, RouterModule.forRoot( appRoutes, { enableTracing: true, useHash: true } ) ], declarations: [LoginComponent, UnauthenticatedHomeComponent, AuthenticatedHomeComponent], exports: [LoginComponent, UnauthenticatedHomeComponent, AuthenticatedHomeComponent] }) export class PortalModule { }
mit
camsys/transam_transit
app/models/infrastructure_foundation.rb
164
class InfrastructureFoundation < ApplicationRecord # All types that are available scope :active, -> { where(:active => true) } def to_s name end end
mit
PReP-Team/prep-prototype
app/router.js
921
import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('home', {path: '/'}); this.route('data'); this.route('dashboards', function () { // this.route('dashboard',{ path: '/:dashboard_id' }, function() { // this.route('indicators', function() {}); // this.route('insights', function () {}); // this.route('tools', function () {}); // }); this.route('sonoma'); this.route('washington', function() { this.route('indicators'); this.route('insights'); this.route('tools'); }); }); this.route('insights'); this.route('search'); this.route('indicators-test'); this.route('about'); this.route('faqs'); this.route('contact'); this.route('partners'); this.route('login'); this.route('logout'); }); export default Router;
mit
BlueMetal/VirtualSales
VirtualSales.Core/ViewModels/Tools/BasicInformationToolViewModel.cs
2191
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VirtualSales.Core.AppServices; using VirtualSales.Core.Models; namespace VirtualSales.Core.ViewModels.Tools { public class BasicInformationToolViewModel : ToolViewModel { private readonly PersonModel _person; public BasicInformationToolViewModel(ISharedDataService dataService, IViewModelLocator locator) : base(new Guid("74EF5D9B-E6D1-4218-8755-C8349157FAAE")) { _person = dataService.Person; Name = "Basic Information"; AddToolPages( new Page1(this, locator.Mode), new Page2(this, locator.Mode), new Page3(this, locator.Mode)); } public class Page1 : ToolPage { private readonly BasicInformationToolViewModel _parent; public Page1(BasicInformationToolViewModel parent, AppMode mode) { Mode = mode; _parent = parent; } public AppMode Mode { get; private set; } public PersonModel Person { get { return _parent._person; } } } public class Page2 : ToolPage { private readonly BasicInformationToolViewModel _parent; public Page2(BasicInformationToolViewModel parent, AppMode mode) { Mode = mode; _parent = parent; } public AppMode Mode { get; private set; } public PersonModel Person { get { return _parent._person; } } } public class Page3 : ToolPage { private readonly BasicInformationToolViewModel _parent; public Page3(BasicInformationToolViewModel parent, AppMode mode) { Mode = mode; _parent = parent; } public AppMode Mode { get; private set; } public PersonModel Person { get { return _parent._person; } } } } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.18.0/event-tap/event-tap-debug.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:fd4cdfdc870da0fcef4f8ecd0859028647b39012a6349cf7e0c42c64f6aa9e01 size 10175
mit
gotryiton/gotron
example_structure/app/controllers/HomeController.php
353
<?php namespace TestApp; class HomeController extends ApplicationController { public function index() { $data = array("name" => "name"); $this->render($data, array('view' => 'index')); } public function test() { $data = array("name" => "name"); $this->render($data, array('view' => 'index')); } } ?>
mit
recsm/SQP
sqp/models.py
84158
#!/usr/bin/python # -*- coding: utf-8 -*- import copy from datetime import datetime from sqp.views_ui_utils import get_branch, get_label from django.db import models from django.contrib.auth.models import User from django.contrib import admin from django.core import serializers from django.core.cache import cache from django.conf import settings import re # for validation import os from sqp_project.sqp.log import logging from django.utils.safestring import mark_safe from django.db.models.query import QuerySet from django.contrib.auth.models import User from django.db.models.signals import post_save, pre_save, pre_delete, post_delete, m2m_changed from django.db.models import Q from django.template import Context from django.template.loader import get_template from sqp.fields import PickledObjectField def dwrap(text): from textwrap import wrap return '\n'.join(wrap(text, width=12)) class History(models.Model): """Keeps track of basic history of changes made to objects.""" ACTION_ITEM_CREATED = 1 ACTION_ITEM_DELETED = 2 ACTION_ITEM_CHANGED = 3 ACTION_ITEM_INDIRECT = 4 #for example if an item was sent, submitted etc. ACTION_CHOICES = ((ACTION_ITEM_CREATED, 'Created'), (ACTION_ITEM_DELETED, 'Deleted'), (ACTION_ITEM_CHANGED, 'Changed'), (ACTION_ITEM_INDIRECT, 'Indirect') ) #The user who made the change actor = models.IntegerField() #the time the action happened time = models.DateTimeField(auto_now=True) #the template for the action message action_description = models.TextField() #the type of action action_type = models.IntegerField(choices=ACTION_CHOICES) #the related object id object_id = models.IntegerField() #the related object model object_model = models.CharField(max_length=90) #the name of the object in case it was deleted object_name = models.CharField(max_length=170) #a json serialization of the old values of the object (only if changed or deleted) previous_values = models.TextField() #get the db values of an object before it is going to be saved or deleted @staticmethod def get_db_values(model, object): return serializers.serialize('json', [model.objects.get(pk=object.id)]) def user_name(self): try: user = User.objects.get(id=self.actor) return user except: return 'Unknown User' class Widget(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class InvalidCode(Exception): """Raised if a choice made is not valid for the characteristic for some reason""" def __init__(self, choice, characteristic, reason): self.choice = choice self.characteristic = characteristic self.reason = reason def __str__(self): return """The choice %s is not valid for this characteristic because %s""" % (self.choice, self.reason) class ValidationRule(models.Model): """A validation rule applied to a choice made for a Characteristic. May cause error or warning (force recoding or not).""" name = models.CharField(max_length = 16) rule = models.TextField('''Python code to validate. You can use "value", "question", "re".''') failure_message = models.TextField('''The message to be displayed if the rule evaluates to False.''') type = models.CharField(max_length = 7, choices = (('ERROR', 'Error'), ('WARNING', 'Warning'))) def __unicode__(self): return self.name def validate(self, value, question, user): """Perform the actual validation given the question and the value to be validated.""" valid = True try: exec(self.rule.replace('\r', '\n')) except Exception as e: print e pass # stuff is liable to go wrong, just ignore it return valid class Characteristic(models.Model): """A characteristic of the Question, such as number of answer categories, social desirability, etc.""" name = models.CharField(max_length=100) short_name = models.CharField(max_length=32) desc = models.TextField('Description, will appear as help text', blank=True, db_column = 'description') widget = models.ForeignKey(Widget) suggestion = models.CharField(max_length=50, null=True, blank=True) auto_fill_suggestion = models.BooleanField(default=False, help_text="For new codings, auto fill the coding value in the ui with the suggested value") validation_rules = models.ManyToManyField(ValidationRule, null=True, blank=True) def __unicode__(self): return self.name def check_labels(self, warn=True): """Check that 1. I have >= 1 label 2country1 = forms.ModelSelect(). All labels have codes 3. All label codes are unique for this characteristic.""" labels = Label.objects.filter(characteristic = self) has_label = len(labels) > 0 if warn and not has_label: print "%s does not have any label!" % self.name if not self.is_categorical(): return has_label codes = [lab.code for lab in labels if lab.code] all_codes = len(codes) is len(labels) if warn and not all_codes: print "%s's labels do not all have codes!" % self.name unique_codes = len(set(codes)) is len(codes) if warn and not unique_codes: print "%s's codes are not unique!" % self.name return (has_label and all_codes and unique_codes) def make_all_labels_branch_to(self, to_characteristic): "Utility function to create or update all labels to go to to_char" labels = self.label_set.all() for label in labels: (branch, created) = Branch.objects.get_or_create(label = label, defaults = {'to_characteristic' : to_characteristic}) if not created: branch.to_characteristic = to_characteristic branch.save() def get_variable_name(self): if self.short_name: return self.short_name return "char_%d" % self.id def is_categorical(self): """Determine whether this is an open question type characteristic or a categorical choice, based on the widget used.""" return self.widget.name not in ('textfield', 'numeric', 'just_a_text') def is_valid_choice(self, choice, question, user): """Numeric choices selected be numeric. Number of abstract nouns should not exceed number of nouns, etc. choice: string w/ the choice to be validated raises InvalidCode exception if not valid""" rules = self.validation_rules.filter(type = 'ERROR') # TODO: handle warnings (large number of words etc) for rule in rules: print "CHECKING %s" % rule.name valid = rule.validate(choice, question, user) print "%s %s" % (rule.name, valid) if not valid: raise InvalidCode(choice, self, rule.failure_message) return True def validations(self): """A utility function to display validation rules inside the admin Returns a csv list of rule names """ rules = [] for rule in self.validation_rules.all(): rules.append(rule.name) return ', '.join(rules) class Meta: ordering = ['name',] class Label(models.Model): """A label is an answer option, something like yes/no, a bit/a lot. name: the text of the label code: the numeric or character code used in the datafile for this choice. compute: a boolean indicating whether this label should be displayed as a choice or is only used to determine skipping rules (see below) characteristic: The label belongs to exactly one characteristic. If the parent Characteristic is not a categorical choice, but for example numerical or text then the characteristic should also have at least one label with the 'compute' bit set to True. The name of this label will be parsed to determine skipping rules. The default 'True' will always skip to the 'next' characteristic. Other examples might be '{{value}} > 5' or '{{value}}.find("don't know") >= 0'. Compute Labels can also be used to provide defaults for numerical choices.""" name = models.CharField(max_length=150, default='True') code = models.CharField(max_length=10, blank=True, null=True) characteristic = models.ForeignKey(Characteristic) compute = models.BooleanField(default=False) #Implement the cache for lookups by primary key #Note that the object cache is initialized later as Label.object_cache = ObjectCache(Label) #objects = ObjectCacheModelManager() def lookup_branch(self, charset_id): """Find the branch for this label and CharacteristicSet. Return None if not found (--> end of tree)""" branches = self.branch_set.filter(characteristicset = charset_id) if len(branches) > 0: return branches[0] else: return None def __unicode__(self): return "%s --> %s" % (self.characteristic.name, self.name) class Meta: # DebUG! ordering = ('characteristic__name', 'id') class LabelInline(admin.TabularInline): model = Label extra = 5 class FakeBranch(): "Ugly hack necessary to get the last coding in question.iter_branches" def __init__(self, coding): try: #might go wrong if faulty coding or no label for numeric char. if coding.characteristic.is_categorical(): self.label = Label.objects.get(code = coding.choice, characteristic = coding.characteristic) else: self.label = Label.objects.\ filter(characteristic=coding.characteristic)[0] except Exception, err: self.label = None logging.debug('Error while looking for Label: %s' % str(err)) self.coding_choice = coding.choice def __unicode__(self): "Fake Branch for %s with coding %s." % (self.label.characteristic, self.coding_choice) class Branch(models.Model): """ A branch is a rule that determines which label makes which Characteristic come next. label: the label (linked to an _originating_ Characteristic). to_characteristic: the Characteristic this label will take you to. Branches are used to define CharacteristicSets. See also Label.""" label = models.ForeignKey(Label) to_characteristic = models.ForeignKey(Characteristic) #Implement the cache for lookups by primary key #Note that the object cache is initialized later such as Label.object_cache = ObjectCache(Label) #objects = ObjectCacheModelManager() def __unicode__(self): return "%s --> %s" % (unicode(self.label), unicode(self.to_characteristic)) class Meta: ordering = ('label__characteristic__name', 'label__id') class BranchInline(admin.TabularInline): model = Branch extra = 3 class BranchAdmin(admin.ModelAdmin): list_display = ('label', 'to_characteristic') search_fields = ('label__name', 'label__characteristic__name', 'to_characteristic__name') class CharacteristicSet(models.Model): """A CharacteristicSet (CSet) defines a set of rules (Branches) for conducting the SQP interview. It can be assigned to coders so that only those coders can use this CharacteristicSet. Different CSets may contain the same Characteristics with different branching rules. Note that a branch for Question (the source node/Characteristic) should always be a part of a CSet. One can obtain a set() of all Characteristics that are reachable in principle from this CharacteristicSet by calling get_characteristics(). Note that it is not guaranteed that all these Characteristics will be reached.""" name = models.CharField(max_length=100) branches = models.ManyToManyField(Branch) coders = models.ManyToManyField(User) class Meta: ordering = ['id',] def __unicode__(self): return self.name def slugname(self): "Version of name without spaces" return self.name.replace(' ', '_') def get_characteristics(self): """Returns a sorted list of all Characteristics reachable from this CharacteristicSet.""" import operator chars = set(self.branches.values_list('to_characteristic__name', 'to_characteristic__short_name')) return sorted(chars, key=operator.itemgetter(1)) def get_characteristic_dict(self): """Returns a dictionary of characteristics in this CSET with keys equal to the characteristic.id and values the characteristic. Reads all characteristics into memory, provides O(1) lookup of chars without additional database queries""" # chars INNER JOIN on branches --> requires DISTINCT print type(Characteristic) characteristics = Characteristic.objects.filter(\ label__branch__characteristicset = self).select_related().distinct() chardict = {} # cache in dict for fast lookup for char in characteristics: chardict[char.id] = char return chardict def get_branch_dict(self): """Returns a dictionary of characteristics in this CSET with keys equal to the characteristic.id and values the characteristic. Reads all characteristics into memory, provides O(1) lookup of chars without additional database queries""" # chars INNER JOIN on branches --> requires DISTINCT branches = self.branches.all() branchdict = {} # cache in dict for fast lookup for branch in branches: branchdict[branch.id] = branch return branchdict def apply_to_tree(self, cur_char = None, apply_func=None, end_func=None, start_from='question', done = set()): """Walk all branches of the characteristic set and apply apply_func to each branch.""" if not cur_char: # first time cur_char = Characteristic.objects.get(short_name__exact = start_from) labels = cur_char.label_set.all() done_chars = set() for label in labels: try: cur_branch = self.branches.get(label = label) # Avoid walking repeatedly down the same part of the tree when # different branches of the same node lead to the same characteristic # Note that done_chars is local to this instance of the function # so it only avoids repeating to_chars from the same origin char. if (cur_branch.to_characteristic not in done_chars): if apply_func: apply_func(cur_branch) self.apply_to_tree(cur_char = cur_branch.to_characteristic, apply_func = apply_func, end_func = end_func) done_chars.add(cur_branch.to_characteristic) except Branch.DoesNotExist: # end of interview from this label if end_func: end_func(label) def apply_to_width(self, cur_char = None, apply_func=None, start_from='question', done = set(), done_chars= set()): """Sort of the same as before, but width first.""" if not cur_char: # first time cur_char = Characteristic.objects.get(short_name__exact = start_from) labels = cur_char.label_set.all() for label in labels: try: cur_branch = self.branches.get(label = label) if (cur_branch.to_characteristic not in done_chars): if apply_func: apply_func(cur_branch.to_characteristic) done_chars.add(cur_branch.to_characteristic) except Branch.DoesNotExist: # end of interview from this label pass for label in labels: try: cur_branch = self.branches.get(label = label) if cur_branch not in done: self.apply_to_width(cur_char = cur_branch.to_characteristic, apply_func = apply_func, done=done, done_chars=done_chars) done.add(cur_branch) except Branch.DoesNotExist: # end of interview from this label pass def to_dot(self, start_from='question'): """Output diagram in GraphViz dot language of this set.""" graph = """digraph "%s" {\n\tgraph [rankdir = "TB"];""" % self.name graph += "\n\tratio = auto;" if start_from == 'question': graph += """\n\t"Question text" [shape = box];\n""" graph += """\n\t{rank = sink; "END" [style=filled, color=black, fontcolor=white, shape = box]; };\n""" # filled with strings for each branch and characteristic by apply_to_tree: glist = [] done_branch = set() # keep track of branches drawn done_labels = set() # keep track of labels drawn def add_to_glist(branch): "Add a dot string for each branch and characteristic to the glist" # prevent double arrows for nodes below intro-available split: if not branch in done_branch: # The dot string for drawing a box with the char name: glist.append(""""%s" [label = "%s" shape = box URL="/admin/sqp/characteristic/%d/"];""" % \ (branch.to_characteristic.name, branch.to_characteristic.name, branch.to_characteristic.id)) # Dot string for arrow from one char to the next: glist.append(""""%s" -> "%s" [label = "%s", URL="/admin/sqp/branch/%d/"];""" % \ (branch.label.characteristic.name, branch.to_characteristic.name, branch.label.name.replace('True', ''), branch.id)) done_branch.add(branch) # register this branch def end_node_found(label): "Add a dot string to signify the end of the interview " if not label in done_labels: glist.append(""""%s" -> "END" [label = "%s", URL="/admin/sqp/branch/add/"];""" % \ (label.characteristic.name, label.name.replace('True', ''))) done_labels.add(label) # register this label # Call add_to_glist on all branches of this characteristic set: self.apply_to_tree(apply_func = add_to_glist, end_func=end_node_found, start_from = start_from) graph += '\n\t'.join(glist) graph += "\n}" return graph def to_graph(self, path = "/home/daob/webapps/django/sqp_project/media/img/sqp", type = "svg", cmd = "", start_from='question'): """Write graph in <type> format. Assumes graphviz is installed. Returns full filename of the graphics file written to.""" outpath = os.path.join(path, '%s_graph.dot' % self.slugname()) outfile = file(outpath, 'w') outfile.write(self.to_dot(start_from = start_from)) outfile.close() graphics_path = "%s.%s" % (os.path.splitext(outpath)[0], type) os.system("dot -T%s %s %s > %s" % (type, cmd, outpath, graphics_path)) return graphics_path class Study(models.Model): name = models.CharField(max_length=70) coders = models.ManyToManyField(User, blank=True, help_text="Deprecated") created_by = models.ForeignKey(User, blank=True, null=True, related_name="created_study_set") company = models.CharField(max_length=70, null=True) year = models.CharField(max_length=70, null=True) country = models.CharField(max_length=70, null=True) def can_delete(self, user): #Users can only delete studies they created if self.created_by != user: return False #Test to see if there are any questions from this study not by this user if Question.objects.filter(Q(item__study = self), ~Q(created_by=user)).count() : return False return True def can_access(self, user): """If a user can read or code this question""" #If the user is the created_by or this study is public then we return true if not self.created_by or (self.created_by == user or self.created_by.profile.is_trusted): return True #Default return false return False def can_edit(self, user): """If a user can edit this study""" #If the user is the created_by or this study we return true if self.created_by == user: return True #Default return false return False def __unicode__(self): return self.name class Meta: ordering = ('name',); class Item(models.Model): name = models.CharField(max_length=8) admin = models.CharField(max_length=8, default='') concept = models.CharField(max_length=300, default='') study = models.ForeignKey(Study) admin_letter = models.CharField(max_length=8, blank=True, null=True) admin_number = models.IntegerField(blank=True, null=True) admin_subletter= models.CharField(max_length=8, blank=True, null=True) created_by = models.ForeignKey(User, blank=True, null=True, related_name="created_item_set") #choices made of characteristics for this item #calc_choices = models.CharField(max_length=255, blank=True, null=True) #Mean for characteristic in item #calc_mean = models.FloatField(blank=True, null=True) #Mode for characteristic in item #calc_mode = models.CharField(blank=True, null=True, max_length=255) #sterr for characteristic in item #calc_sterr = models.FloatField(blank=True, null=True) #stdev for characteristic in item #calc_stdev = models.FloatField(blank=True, null=True) def __unicode__(self): return self.unique_name def main_or_supplementary(self): return (self.name.lower().find('test') == -1) and "main" or "supp" def _unique_name(self): ad = self.admin and self.admin + ". " or '' return("%s / %s / %s" % (ad, self.name, self.study)) unique_name = property(_unique_name) def code (self): return("%s%s" % (self.admin_letter, self.admin_number, self.admin_subletter)) #Called before saving #Don't call save here, you will cause an infinite loop #This method is called before save by some script at the bottom of sqp/models.py def on_before_save(self): #Set the admin if none exists if not self.admin and (self.admin_letter and self.admin_number): self.admin = self.code(); if re.match(r'^[A-Za-z]*[0-9]+[A-Za-z]*$', self.admin): letters=re.split('\d+', self.admin) self.admin_letter=letters[0] self.admin_number=filter(None,re.split('[A-Za-z]+',self.admin))[0] self.admin_subletter=letters[1] elif re.match(r'^[A-Za-z]*$',self.admin): #just letters self.admin_letter=self.admin self.admin_number=None self.admin_subletter=None else: # numbers letters numbers or whatever self.admin_letter=self.admin self.admin_number=None self.admin_subletter=None class Meta: ordering = ('study', 'admin_letter', 'admin_number', 'admin_subletter', 'id') def can_edit(self, user): """If a user can edit item description, item code, associated with this item""" #If created by this user we return true if self.created_by == user: return True #Check to see if this is a user owned item with the same name, with only #the user's own questions assigned to it. If so then the user #can change the item still and we don't create a new one.This is important #since it is required to enable the user change the description or admin for an existing item item_has_other_users_questions = Question.objects.filter(~Q(created_by=user), Q(item=self)).count() if not item_has_other_users_questions: return True return False class Country(models.Model): iso = models.CharField(max_length=2, primary_key=True) name = models.CharField(max_length=80) iso_three = models.CharField(max_length=3, blank=True, null=True) available = models.BooleanField(default=False, verbose_name="The user can select the country") def __unicode__(self): return self.name class Meta: ordering = ['name',] class Language(models.Model): name = models.CharField(max_length=100) iso = models.CharField(max_length=3) iso2 = models.CharField(max_length=2, null=True, blank=True) coders = models.ManyToManyField(User) def __unicode__(self): return self.name class Meta: ordering = ('name',) characteristic_trees = {} class Question(models.Model): item = models.ForeignKey(Item) language = models.ForeignKey(Language) country = models.ForeignKey(Country) country_prediction = models.ForeignKey(Country, related_name='prediction_country', blank=True, null=True) introduction_text = models.TextField(blank=True, null=True) rfa_text = models.TextField(blank=True, null=True) answer_text = models.TextField(blank=True, null=True) val = models.FloatField(blank=True, null=True) val_lo = models.FloatField(blank=True, null=True) val_hi = models.FloatField(blank=True, null=True) valz = models.FloatField(blank=True, null=True) valz_se = models.FloatField(blank=True, null=True) rel = models.FloatField(blank=True, null=True) rel_lo = models.FloatField(blank=True, null=True) rel_hi = models.FloatField(blank=True, null=True) relz = models.FloatField(blank=True, null=True) relz_se = models.FloatField(blank=True, null=True) created_by = models.ForeignKey(User, blank=True, null=True, related_name="created_question_set") imported_from = models.CharField(null=True, blank=True, max_length=120) def has_text(self): return bool(self.introduction_text or self.rfa_text or self.answer_text) def can_edit_text(self, user): """If a user can edit the introduction_text, rfa_text, and answer_text""" #If the user is the created_by then we return true if self.created_by == user: return True #Otherwise we check for a many to many relationship with can_edit_text = True if self.userquestion_set.filter(user=user, can_edit_text=True).count(): return True return False def can_edit_details(self, user): """If a user can edit the country, language, item, and study""" #If the user is the created_by then we return true if self.created_by == user: return True #Otherwise we check for a many to many relationship with can_edit_details = True if self.userquestion_set.filter(user=user, can_edit_details=True).count(): return True return False def can_delete(self, user): #If the user is the created_by then we return true if self.created_by == user: return True #There is no can delete many to many return False def can_access(self, user): """If a user can read or code this question #If the user is the created_by then we return true #have a null created_by value if not self.created_by or (self.created_by == user or self.created_by.profile.is_trusted): return True #Otherwise we check for a many to many relationship #Any existing many to many relationship implies the question can be accessed by the user if self.userquestion_set.filter(user=user).count(): return True #Default return false return False """ return True def update_completion(self, request=None, user=None, for_charset=None): if user is None: user = request.user """Marks the question as completed or not by user in the database. Automatically updates all CharSets.""" for charset in CharacteristicSet.objects.iterator(): if for_charset is None or for_charset == charset: try: complete = self.get_completeness(user, charset) == 'completely-coded' self.set_completion(user, for_charset, complete) except Exception, err: print "Encountered an exception for charset %s and user %s: %s"\ % (str(charset), user, str(err)) def set_completion(self, user, charset, complete, authorized=None): completion, created = Completion.objects.get_or_create(\ question = self, user=user, characteristic_set = charset) #Mark this completion record as being up to date completion.complete = complete if authorized is not None: completion.authorized = authorized completion.out_of_date = False completion.save() def set_completion_out_of_date(self, user, for_charset=None): """Called by Coding.save(), this just invalidated our completion record for this question If for_charset is passed, we just set that charset as out of date Otherwise we set all charsets as out of date """ missed_sets = [] if for_charset is None: #Invalidate all completion objects when this coding was saved from the admin panel... or #somewhere else if that is possible completions = Completion.objects.filter(question=self, user=user) charsets = CharacteristicSet.objects.all() for cs in charsets: missed = True for complete in completions: if complete.characteristic_set == cs: missed = False break if missed: missed_sets.append(cs) else: completions = Completion.objects.filter(question=self, user=user, characteristic_set= for_charset) if len(completions) == 0: missed_sets.append(for_charset) for missed_charset in missed_sets: #The completion invalid record is important so we create it here. Completion.objects.get_or_create(\ question = self, user=user, characteristic_set = missed_charset, out_of_date = True) for complete in completions: complete.out_of_date = True complete.predictions = None complete.save() def update_suggestions(self): """Update the range of suggestions for codings of this question called whenever the question is saved """ from sqp_project.sqp import suggestions #The suggestions don't need a request now #Ideally the request argument should be deleted for char in Characteristic.objects.all(): if char.suggestion: #print #print char.suggestion if char.suggestion not in dir(suggestions): #print """Warning: for suggestion type %s no suggestion function was found in suggestions.py""" % char.suggestion continue try: suggestion_function = eval('suggestions.' + char.suggestion) #Delete any old suggestions coding_suggestions = CodingSuggestion.objects.filter(question=self, characteristic=char) for cs in coding_suggestions: cs.delete() suggestion, explanation = suggestion_function (self, char) #print "For %s suggestion is %s explained by %s" % (char.suggestion, suggestion, explanation) coding_suggestion = CodingSuggestion.objects.get_or_create(question=self, characteristic=char)[0] coding_suggestion.value = suggestion coding_suggestion.explanation = explanation coding_suggestion.save() except: pass #print 'Error %s' % err def get_codes(self, user, charset): codes = [] for branch in self.iter_branches(user=user, charset=charset): try: if branch: if str(branch.label.name) == 'True': choice_text = branch.coding_choice else: choice_text = branch.label.name characteristic = branch.label.characteristic choice = branch.coding_choice codes.append({'characteristic' : characteristic, 'short_name ' : characteristic.short_name, 'code' : choice, 'choice' : choice_text, }) except Exception as e: pass return codes def iter_branches(self, request=None, user=None, charset=None, start='question'): """Not really an iterator anymore as an entire array is returned The last element is a branch for the last char if the interview is complete. Otherwise the last branch is None. You can safely use branch.label and branch.coding_choice. These and branch.label.characteristic will not result in additional db queries. The iterations stop when the end of the interview is reached or when an uncoded but needed characteristic is found. """ if not request: # Input checking if not user and charset: raise Exception('Should have either request or user & charset') else: user = request.user charset = CharacteristicSet.objects.get(pk = \ request.session['characteristic_set']) try: tree = characteristic_trees[charset.id] except: #Trees have not been initialized yet, initialize them all here for cset in CharacteristicSet.objects.all(): characteristic_trees[cset.id] = CharacteristicTree(cset) tree = characteristic_trees[charset.id] codes = Coding.objects.filter(question = self, user = user) return tree.iter_branches(codes) def get_previous_characteristic(self, request, characteristic, default='question'): """Given a question and characteristic, figure out which characteristic came before it.""" prev_char = Characteristic.objects.get(short_name__exact = default) for branch in self.iter_branches(request = request): if branch: if characteristic == branch.label.characteristic: return prev_char prev_char = branch.label.characteristic return prev_char def get_completeness(self, user, charset): """Returns the completeness status of the question for this coder and charset: 'Not coded', 'Partially coded', or 'Completely coded'. the return value is used in list_questions as a css class.""" ncodings = Coding.objects.filter(question = self, user = user).count() if ncodings == 0: return 'not-coded' for branch in self.iter_branches(user=user, charset=charset): pass return branch and 'completely-coded' or 'partially-coded' def get_coding_for(self, characteristic_short_name, user): """Given characteristic and user, return the coding for that characteristic (if any) or None.""" coding = Coding.objects.filter(question = self, characteristic__short_name__exact = characteristic_short_name, user = user) print characteristic_short_name return coding and coding[0] or None def save(self, *args, **kwargs): if 'create_suggestions' in kwargs.keys(): create_suggestions = kwargs['create_suggestions'] del kwargs['create_suggestions'] else: create_suggestions = True super(Question,self).save(*args, **kwargs) #On save we update the suggestions for the question if create_suggestions == True: self.update_suggestions() def save_through(self, *args, **kwargs): super(Question,self).save(*args, **kwargs) class Meta: permissions = (('can_compare', 'Can create comparison report'), ('can_export', 'Can export codes to CSV'),) ordering = ('item__study', 'country', 'language', 'item__admin_letter', 'item__admin_number', 'item__id') permissions = (('can_compare', 'Can use SQP Compare'), ('can_export', 'Can export codings') ) def __unicode__(self): return u'%s / %s / %s / %s' % (self.item, self.language, self.country, self.country_prediction) # def copy_codes(to_question, request): # """Handles copying of codes for question specified in request.POST # to codes of from_question. Returns a message describing what # happened.""" # #Find the from_question using from_data, look for errors # try: # from_question = Question.objects.get(item = request.POST['item'], # country = request.POST['country'], # language = request.POST['language']) # except: # message = """Could not find a question corresponding to that combination # of item, language, and country to copy from.""" # message_class = "warning" # return message, message_class # # copied = [] # branch = None # try: # for branch in from_question.iter_branches(request = request): # (newcoding, created) = Coding.objects.get_or_create(\ # question=to_question, # characteristic=branch.label.characteristic, # user=request.user) # copied.append(branch.label.characteristic) # newcoding.choice = branch.coding_choice # newcoding.save() # except Exception, e: # message = "An error occurred trying to copy codes: %s" % (str(e)) # message_class = "warning" # if branch: # message = """Copied %d codes from %s. Complete coding from # beginning to end. """ % (len(copied), from_question) # message_class = "success" # else: # message = """Copied %d codes from %s. The coding for the source # question is not complete.""" % (len(copied), from_question) # message_class = "success" # # to_question.update_completion(request) # # return message, message_class # # def check_codings_complete(self, request): # """Given the request.user, walk the tree from the beginning to # see if all codings have been made. If so return True.""" # return False # # def get_next_question_id(question): # """Figure out which question id is next in line to be coded. # Used in views.py:430""" # question_ids = Question.objects.filter(country=question.country, # language=question.language).values('id') # for i, cur in enumerate(question_ids): # if cur['id'] == question.id: # try: return question_ids[i+1]['id'] # except (ValueError, IndexError): return -1 # # def save_question_rfa(question, request): # """Given a POST request containing RFA ao info, save it in the question, # return a message describing what happened""" # question.rfa_text = request.POST['rfa_text'] # question.introduction_text = request.POST['introduction_text'] # question.answer_text = request.POST['answer_text'] # question.save() # return "Successfully updated the request for an answer, introduction," +\ # " and answer categories for this question." # def get_done_dict(self, request): # if not self.__dict__.has_key('percent_done'): # self._init_done(request) # return {'done' : self.done, 'to_do':self.to_do, # 'percent_done':self.percent_done, # 'percent_pos':self.percent_pos # } # # def _init_done(self, request): # self.done,self.to_do,self.percent_done = self._get_percent_done(request) # self.percent_pos = -120.5 + (float(self.percent_done) / 100.0) * 121.5 # # def __unicode__(self): # s = unicode(self.item) + ' (' + unicode(self.country) + '; ' + \ # unicode(self.language) + ')' # return self.item.main_or_supplementary() + ": " + s # # def _get_percent_done(self, request): # """ Calculates how many codings remain to be done as well as a percentage. # Returns amount done, amount to be done, and percentage as a tuple. # Skipping patterns, the current user, and the current # CharacteristicSet are taken into account.""" # needed_codings = [] # needed_characteristics = [] # # # char_set = request.session.get('characteristic_set', default = 1) # # all_codings = self.coding_set.filter(user = request.user, # characteristic__characteristicset__id = char_set) # all_characteristics = Characteristic.objects.\ # filter(characteristicset__id = char_set) # # if not (all_codings and all_characteristics): # return (0, 0, 0.0) # we already know the answer will be zero # # # skip = False # skip_to = False # num_cods = 0 # num_chars = 0 # # for char in all_characteristics: # if char == skip_to: # skip_to, skip = False, False # # if not skip: # #needed_characteristics.append(char.id) # num_chars += 1 # # # # returns a list, empty (False) if not coded: # corresponding = all_codings.filter(characteristic = char) # # if corresponding: # # remembered _which_ codings are needed/coded. # #needed_codings.append(corresponding[0].id) # num_cods += 1 # # # figure out whether we need to start skipping # label = Label.objects.filter(code = corresponding[0].choice, # characteristics = char) # if label: # skip_to, skip = label[0].skip_to, True # # if num_chars: # prevent division by 0 # #num_cods = len(needed_codings) # #num_chars = len(needed_characteristics) # return (num_cods, num_chars, # round(100.0 * float(num_cods) / float(num_chars))) # else: # return (0, 0, 0.0) # class UserQuestion(models.Model): """Questions that have been assigned to a user for coding""" user = models.ForeignKey(User) question = models.ForeignKey(Question) can_edit_text = models.BooleanField(default=False, verbose_name="Can edit text (intro, rfa, answer options)") can_edit_details = models.BooleanField(default=False, verbose_name="Can edit details (country, language, and item)") class Meta: verbose_name = 'User Assigned Question' verbose_name_plural = 'User Assigned Questions' def __unicode__(self): return "%s assigned to %s" % (self.question, self.user) class ItemGroup(models.Model): """A group of items that can later be assigned to a group of users to code""" name = models.CharField(max_length=80, help_text="Name this group for easy reference ") items = models.ManyToManyField(Item, help_text="Items for this group") def item_sample_list(self): item_sample = [(u"%s" % item).replace(',', ' ') for item in self.items.all()[0:4]] summary = ', '.join(item_sample) if self.items.count() > 5: summary += ' and %s more' % (self.items.count() - 4) return summary def __unicode__(self): return self.name @staticmethod def m2m_changed(**kwargs): """If the item group changes for the bulk question creation or bulk assignment then we mark those items as not run""" if isinstance(kwargs['instance'], ItemGroup)\ and kwargs['action'] in ['post_add', 'post_remove', 'post_clear']: for question_bulk_creation in QuestionBulkCreation.objects.filter(item_group=kwargs['instance']): question_bulk_creation.has_been_run = False question_bulk_creation.save() for question_bulk_assignment in QuestionBulkAssignments.objects.filter(item_group=kwargs['instance']): question_bulk_assignment.has_been_run = False question_bulk_assignment.save() #Bind the static method m2m_changed of the ItemGroup model so we can update related objects m2m_changed.connect(ItemGroup.m2m_changed, weak=False) class QuestionBulkCreation(models.Model): """A bulk question creation tool""" item_group = models.ForeignKey(ItemGroup, help_text ='Create questions for all items in the selected item group') country = models.ForeignKey(Country, help_text ='Question will be created only for this country') language = models.ForeignKey(Language, help_text='Question will be created only for this language') copy_text_from_study = models.ForeignKey(Study, blank=True, null=True, help_text='Optional: Copy the intro, rfa text, and answer options from another study - when matching questions by variable name (TVTOT), country, and language are available in that study.') created_questions = models.ManyToManyField(Question, blank=True) has_been_run = models.BooleanField(default=False, verbose_name="Run and up to date") last_run_date = models.DateField(blank=True, null=True, help_text = "The last time this assignment was run") def __init__(self, *args, **kwargs): self._run = False #Keep track if this instance was run to prevent multiple runs on save self._list = None #Cache of the question list for the model admin self.copied_questions_count = 0 return super(QuestionBulkCreation, self).__init__(*args, **kwargs) class Meta: verbose_name = 'Bulk Question Creation Task' verbose_name_plural = 'Bulk Question Creation Tasks' def created_questions_with_text(self): total = 0 with_text = 0 for q in self.created_questions.all(): total += 1 if q.has_text(): with_text += 1 return "%s / %s" % (with_text, total) def is_deletable(self, question): if question.introduction_text or question.rfa_text or question.answer_text: return False return True def questions_to_be_deleted(self): to_be_deleted = [] """Used by the model admin to show which questions would be deleted when the question is deleted. The logic here is that empty questions are fine to delete, but questions with content alread filled out will not be deleted """ for q in self.created_questions.all(): if self.is_deletable(q): to_be_deleted.append(q) return to_be_deleted def questions_not_deleted(self): not_to_be_deleted = [] """Used by the model admin to show which questions would be deleted when the question is deleted.""" for q in self.created_questions.all(): if not self.is_deletable(q): not_to_be_deleted.append(q) return not_to_be_deleted def questions_created(self): """Used by the model admin to show the total number of questions created""" return self.created_questions.count() def question_list(self): """Used by the model admin to show which questions would be created in the confirm screen""" if self._list is None: #If none on the first call we create the list self._list = {'to_create' : [], 'already_exist' : []} for item in self.item_group.items.iterator(): question_summary = "%s in %s for country %s" % (item, self.language, self.country) try: Question.objects.get(item=item, language=self.language, country=self.country) self._list['already_exist'].append(question_summary) except Question.DoesNotExist: self._list['to_create'].append(question_summary) return self._list def get_copy_from_question(self, to_question): if not self.copy_text_from_study: return None items = Item.objects.filter(study=self.copy_text_from_study, name=to_question.item.name) for item in items: for q in Question.objects.filter(item=item, country=to_question.country, language=to_question.language): if q.rfa_text: return q #There was no text from the SOURCE in a previous study so we copy it from the UK if to_question.country.name == 'SOURCE': uk = Country.objects.get(iso='GB') for item in items: for q in Question.objects.filter(item=item, country=uk, language=to_question.language): if q.rfa_text: return q return None def options(self): """Return some option buttons to link directly to the admin action""" options = """ <input type="submit" value="Run" onclick="do_action('run_creations', %s); return false;"/> """ % (self.id) if self.has_been_run: options += """ <input type="submit" value="Undo and Delete Task" onclick="window.location.href='/admin/sqp/questionbulkcreation/%s/delete/'; return false;"/> """ % self.id return options options.allow_tags=True def run_creation(self): self._run = True all_questions = self.created_questions.all() #Create any missing question objects for item in self.item_group.items.iterator(): question, created = Question.objects.get_or_create(item=item, language=self.language, country=self.country) if created: copy_from_question = self.get_copy_from_question(question) if copy_from_question: question.introduction_text = copy_from_question.introduction_text question.rfa_text = copy_from_question.rfa_text question.answer_text = copy_from_question.answer_text question.save(create_suggestions = False) self.copied_questions_count += 1 if question not in all_questions: self.created_questions.add(question) self.has_been_run = True self.last_run_date = datetime.now() def __unicode__(self): return "%s creation task in %s for %s" % (self.item_group, self.language, self.country) _related_deleted = False def delete_related_questions(self): """Deleted the questions created by this task""" counter = 0 if not self._related_deleted: self._related_deleted = True for q in self.created_questions.all(): if self.is_deletable(q): q.delete() counter += 1 return counter def on_before_delete(self): self.delete_related_questions() class QuestionBulkAssignments(models.Model): """A bulk assignment tool to assign questions to users""" users = models.ManyToManyField(User, help_text = "Users who will be assigned this group of questions") item_group = models.ForeignKey(ItemGroup, null=True, help_text ='Assign Items from this group') country = models.ForeignKey(Country, null=True, help_text ='Assign Question from this country') language = models.ForeignKey(Language, null=True,help_text='Assign Question from this language') can_edit_text = models.BooleanField(default=True, help_text = 'If the users can edit the intro, rfa, and answer texts or not for the assigned questions') can_edit_details = models.BooleanField(default=False, help_text = 'If the users can edit the country, language, and item or not for the assigned questions') has_been_run = models.BooleanField(default=False, verbose_name="Run and up to date") last_run_date = models.DateField(blank=True, null=True, help_text = "The last time this assignment was run") assignments = models.ManyToManyField(UserQuestion, blank=True, verbose_name="Question Assignments") _run = False #Keep track if this instance was run to prevent multiple runs on save class Meta: verbose_name = 'Bulk Question Assignment' verbose_name_plural = 'Bulk Question Assignments' def assignments_count(self): """Used by the model admin to show the total number of assignment created or modified""" return self.assignments.count() def assign_to_users(self): user_names = [] for u in self.users.all(): user_names.append(u.username) return ', '.join(user_names) def assignments_to_be_deleted(self): return self.assignments.all() _counter = 0 _assignments_deleted = False def delete_assignments(self): if not self._assignments_deleted: self._assignments_deleted = True self._counter = self.assignments.count() self.assignments.clear() return self._counter def on_before_delete(self): self.delete_assignments() def run_assignment(self): self._run = True assignments_created = 0 assignments_total = 0 for item in self.item_group.items.iterator(): #Create any missing question assignments question = Question.objects.get(item=item, language=self.language, country=self.country) all_assignments = self.assignments.all() for user in self.users.all(): assignment, created = UserQuestion.objects.get_or_create(question=question, user=user) if created: assignments_created += 1 if assignment not in all_assignments: self.assignments.add(assignment) assignment.can_edit_text = self.can_edit_text assignment.can_edit_details = self.can_edit_details assignment.save() assignments_total += 1 self.has_been_run = True self.last_run_date = datetime.now() _list = None def question_list(self): """Used by the model admin to show which questions would be assigned in the confirm screen""" if self._list is None: #If none on the first call we create the list self._list = {'to_assign' : [], 'already_assigned' : [], 'missing_questions' : [], 'changed_questions' : []} for item in self.item_group.items.iterator(): for user in self.users.all(): question_summary = "%s for %s, %s assigned to %s" % (item, self.language, self.country, user) try: question = Question.objects.get(item=item, country=self.country, language=self.language) try: user_question = UserQuestion.objects.get(question=question, user=user) if user_question.can_edit_text != self.can_edit_text \ or user_question.can_edit_details != self.can_edit_details: self._list['changed_questions'].append(question_summary) else: self._list['already_assigned'].append(question_summary) except UserQuestion.DoesNotExist: self._list['to_assign'].append(question_summary) except Question.DoesNotExist: summary = 'Question for Item %s in %s for country %s ' % (item, self.language, self.country) if summary not in self._list['missing_questions']: self._list['missing_questions'].append(summary) return self._list def options(self): """Return some option buttons to link directly to the admin action""" options = """ <input type="submit" value="Run" onclick="do_action('run_assignments', %s); return false;"/> """ % (self.id) if self.has_been_run: options += """ <input type="submit" value="Undo and Delete" onclick="window.location.href='/admin/sqp/questionbulkassignments/%s/delete/'; return false;"/> """ % self.id return options options.allow_tags=True def __unicode__(self): return "%s assignment in %s for %s" % (self.item_group, self.language, self.country) @staticmethod def m2m_changed(**kwargs): """If the user group changes for the bulk assignment then we mark the assignment as not run""" if isinstance(kwargs['instance'], QuestionBulkAssignments)\ and kwargs['action'] in ['post_add', 'post_remove', 'post_clear']: kwargs['instance'].has_been_run = False kwargs['instance'].save() #Bind the static method m2m_changed of the ItemGroup model so we can update related objects m2m_changed.connect(QuestionBulkAssignments.m2m_changed, weak=False) class CodingSuggestion(models.Model): question = models.ForeignKey(Question) characteristic = models.ForeignKey(Characteristic) value = models.TextField(blank=True, null=True) explanation = models.TextField(blank=True, null=True) class Coding(models.Model): question = models.ForeignKey(Question) characteristic = models.ForeignKey(Characteristic) choice = models.TextField(blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True) updated_on = models.DateTimeField() seconds_taken = models.FloatField(blank=True, null=True) #If this coding has been declared invalid #invalidated = models.BooleanField(default=False) #If this choice was "orphaned" because someone chose a different branch #calc_is_orphaned = models.BooleanField(default=False) #how much this coding deviates from the others #calc_choice_deviance = models.FloatField(blank=True, null=True) #how many times this same choice was chosen for this char in this item #calc_choice_frequency = models.IntegerField(blank=True, null=True) def lookup_label(self): """Find the label this coding applies to or raise exception""" try: label = Label.objects.get(characteristic = self.characteristic, code = self.choice) except Label.DoesNotExist: labels = Label.objects.filter(characteristic = self.characteristic, compute = True) if len(labels) == 0: raise Label.DoesNotExist else: label = labels[0] # for now just take the first one return label def __unicode__(self): return "Coding of %s for question %d by %s" % \ (self.characteristic, self.question_id, self.user) def order_number(self): return self.characteristic.order_number class Meta: ordering = ['user','characteristic'] def save(self, *args, **kwargs): try: charset = kwargs.pop('charset') except: charset = None try: prev_choice = Coding.objects.get(pk=self.id).choice if self.choice != prev_choice: self.question.set_completion_out_of_date(self.user, charset) except Coding.DoesNotExist: pass """ self.updated_on = datetime.now() history = History() #Try to get change_by_user from the kwargs to save, if none use 0 the second argument to get #history.actor = kwargs.get('change_user', 0) history.actor = 1 history.object_id = self.id history.object_model = 'Coding' history.object_name = u"%s"%self if self.id: history.action_type = kwargs.get('action_type', History.ACTION_ITEM_CHANGED) history.action_description = kwargs.get('action_description', 'Modification of Coding') #history.previous_values = History.get_db_values(Coding, self) else: history.action_type = kwargs.get('action_type', History.ACTION_ITEM_CREATED) history.action_description = kwargs.get('action_description', 'Coding Created') history.save() #Clean up our kwqrgs if 'action_description' in kwargs: del kwargs['action_description'] if 'action_type' in kwargs: del kwargs['action_type'] if 'change_user' in kwargs: del kwargs['change_user'] """ super(Coding, self).save(*args, **kwargs) def delete(self, *args, **kwargs): history = History() #Try to get change_by_user from the kwargs to save, if none use 0 the second argument to get history.actor = kwargs.get('change_user', 0) history.object_id = self.id history.object_model = 'Coding' history.object_name = self history.action_type = kwargs.get('action_type', History.ACTION_ITEM_DELETED) history.action_description = kwargs.get('action_description', 'Deletion of Coding') history.previous_values = History.get_db_values(Coding, self) history.save() #Clean up our kwqrgs if 'action_description' in kwargs: del kwargs['action_description'] if 'action_type' in kwargs: del kwargs['action_type'] if 'change_user' in kwargs: del kwargs['change_user'] super(Coding, self).delete(*args, **kwargs) class CodingChangeGroup(models.Model): name = models.CharField(max_length=255, help_text="The name of the coding change group") description = models.TextField(help_text="Short text about why this group of changes is being made") def __unicode__(self): return "%s. %s" % \ (self.id, self.name) class Meta: ordering = ['id',] class CodingChangeException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class CodingChangeAlreadyProcessed(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class CodingChange(models.Model): CHANGE_DEFINED = 1 CHANGE_BY_RELATED = 2 CHANGE_DELETE = 3 CHANGE_CHOICES = ((CHANGE_DEFINED, 'Set coding to to defined value'), (CHANGE_BY_RELATED, 'Set to related country/language value'), (CHANGE_DELETE, 'Delete the coding') ) coding_change_group = models.ForeignKey(CodingChangeGroup) question_id = models.IntegerField() characteristic = models.ForeignKey(Characteristic) coding_user = models.ForeignKey(User, related_name="coding_user_set", null=True, help_text="The user who made the orig coding.") change_by = models.ForeignKey(User, related_name="change_by_user_set", null=True, help_text="The user who is making this change.") change_type = models.IntegerField(choices=CHANGE_CHOICES, help_text="select the type of change") new_value = models.CharField(max_length=15,blank=True,null=True, help_text="Set the new value as defined here.") new_value_by_related_lang = models.ForeignKey(Language, blank=True, null=True, help_text="Set the new value as coded in another question. Related Question Language. Country and Language must both be set.") new_value_by_related_country = models.ForeignKey(Country, blank=True, null=True, help_text="Set the new value as coded in another question. Related Question Country. Country and Language must both be set.") processed = models.BooleanField(default=False, help_text="If this change has been processed by the system") error_occured = models.BooleanField(default=False, help_text="If an error occurred during the last process") processing_log = models.TextField(blank=True, null=True,help_text="The log from processing") def process(self): if self.processed: raise CodingChangeAlreadyProcessed(self.id) try: target_coding = Coding.objects.get(question = self.question_id, characteristic = self.characteristic, user = self.coding_user) except Coding.DoesNotExist: self.error_occured = True error = 'Target coding could not be found. Check question id, characteristic, and user id' self.processing_log = error self.save(); raise CodingChangeException(error) #we process the change type and apply the correct action if not self.change_type: self.error_occured = True error = 'Change type not defined. You must specify a change type' self.processing_log = error self.save(); raise CodingChangeException(error) elif self.change_type == self.CHANGE_DELETE: target_coding.save(action_description=u'Coding Deleted - %s'%self.coding_change_group, change_user=self.change_by.id) self.processed = True self.error_occured = False self.processing_log = u"Processed correctly. Coding %s (%s) deleted" % ( target_coding.id, target_coding) self.save() elif self.change_type == self.CHANGE_DEFINED: if not self.new_value: self.error_occured = True error = 'New value not defined. Please define value or select another change type.' self.processing_log = error self.save(); raise CodingChangeException(error) #we take the value set directly by the user new_value = self.new_value else: #we try to find the related coding item = target_coding.question.item; try: related_question = Question.objects.get(item=item, language=self.new_value_by_related_lang, country=self.new_value_by_related_country) except Question.DoesNotExist: self.error_occured = True error = 'Related Question in item %s for language %s and country %s could not be found to set new value' % \ (item, self.new_value_by_related_lang,self.new_value_by_related_country ) self.processing_log = error self.save(); raise CodingChangeException(error) try: related_coding = Coding.objects.get(question = related_question, characteristic = self.characteristic) new_value = related_coding.choice except Coding.DoesNotExist: self.error_occured = True error = 'Related Coding could not be found to set new value' self.processing_log = error self.save(); raise CodingChangeException(error) except Coding.MultipleObjectsReturned: related_codings = Coding.objects.filter(question = related_question, characteristic = self.characteristic) first = True various = False error = '' for c in related_codings: if first: first = False check = c.choice elif c.choice != check: various = True error = error + u"%s - %s \n" % (c.user, c.choice) if various: self.error_occured = True error = 'Multiple related codings found by various, please specify value exactly from these choices \n' self.processing_log = error self.save(); raise CodingChangeException(error) else: new_value = check target_coding.choice = new_value target_coding.updated_on = datetime.now() target_coding.save(action_description=u'Coding Change - %s'%self.coding_change_group, change_user=self.change_by.id) self.processed = True self.error_occured = False self.processing_log = u"Processed correctly. Coding %s (%s) set to %s" % ( target_coding.id, target_coding, new_value) self.save() def change_summary(self): return u"%s" % self def __unicode__(self): return "Change for '%s' in question id %s" % \ (self.characteristic, self.question_id) class UsedCountry(models.Model): iso = models.CharField(max_length=2, primary_key = True) name = models.CharField(max_length=80) def __unicode__(self): return self.name class Meta: ordering = ['name',] db_table = 'vw_country_question' class Completion(models.Model): "Whether questions have been completely coded by coder or not" user = models.ForeignKey(User) question = models.ForeignKey(Question) characteristic_set = models.ForeignKey(CharacteristicSet) complete = models.BooleanField(default=False) #Add an out_of_date column that we can call so that this can be calculated before generating the question list out_of_date = models.BooleanField(default=False) predictions = PickledObjectField(blank=True, null=True) potential_improvements = PickledObjectField(blank=True, null=True) authorized = models.BooleanField(default=False) def __unicode__(self): return u"%s : %s - question '%s' for charset '%s'" % \ (unicode(self.user), ((self.complete) and 'COMPLETE' or 'NOT COMPLETE'), unicode(self.question), unicode(self.characteristic_set)) def assign_to_user(self, to_user): codings = Coding.objects.filter(question=self.question, user=self.user) for coding in codings: coding.user = to_user coding.save() self.user = to_user self.save() def coding_list_tree(self): list = '<table>' for branch in self.question.iter_branches(user=self.user, charset=self.characteristic_set): if branch: if str(branch.label.name) == 'True': choice_text = branch.coding_choice else: choice_text = branch.label.name characteristic = branch.label.characteristic choice = branch.coding_choice list += "<tr><th>%s</th><td>%s</td></tr>" % (characteristic, choice_text) list += '</table>' return list coding_list_tree.allow_tags = True def coding_list_all(self): list = '<table>' for coding in Coding.objects.filter(question=self.question, user=self.user).order_by('characteristic__name'): characteristic = coding.characteristic choice = coding.choice list += "<tr><th>%s</th><td>%s</td></tr>" % (characteristic, choice) list += '</table>' return list coding_list_all.allow_tags = True class Prediction(models.Model): paramater = models.ForeignKey('Parameter') #TODO: fix spelling error view = models.ForeignKey('View') function_name = models.CharField(max_length=80) key = models.CharField(max_length=80, blank=True, help_text='A key for referencing this prediction through the ui') py2R_names = {'quality':'qual2', 'reliability':'rel2', 'validity':'val2', 'quality_coefficient':'qual', 'reliability_coefficient':'rel', 'validity_coefficient':'val', 'method_effect_coefficient':'met', 'common_method_variance':'cmv', } def __unicode__(self): return u"Prediction using view '%s' for parameter '%s'" % (self.view, self.paramater) class View(models.Model): EXPECTED_TYPES = (('image', 'Image'), ('tuple', 'Tuple'), ('float', 'Float'), ) name = models.CharField(max_length=80) expects = models.CharField(max_length=20, choices = EXPECTED_TYPES, verbose_name="Expected Input", default="tuple") template = models.CharField(max_length=140) order = models.IntegerField(default=0) def render(self, prediction_return): ###TODO: Validate return is as expects t = get_template('predictions/' + self.template + '.html') return t.render(Context({'prediction' : prediction_return})) class Meta: ordering = ['order',] def __unicode__(self): return u"%s" % self.name class Parameter(models.Model): name = models.CharField(max_length=80) description = models.TextField() views = models.ManyToManyField(View, through=Prediction) order = models.IntegerField(default=0) class Meta: ordering = ['order',] def __unicode__(self): return u"%s - %s"% (self.name, self.description[0:20]) class FAQ(models.Model): """'Frequently' asked questions and answers""" asker = models.ForeignKey(User, null=True, blank=True) question = models.TextField() answer = models.TextField() date_added = models.DateField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __unicode__(self): return self.question.strip()[0:100] tips = {'tip_introduction' : """ Introductions mainly serve to initiate the topic of the Request for an Answer to the respondent and consist of one or more sentences. Examples could be: bq. _Now, a couple of questions follow about your health._ bq. _The next question deals with your work._ Sometimes a survey item contains two requests where the first request just functions as an introduction because no answer is required. The second request is the one to be answered as indicated by the answer categories. Example: bq. _Would you mind telling me your race or ethnic origin?_ bq. _Are you white black, Hispanic American, Alaskan native, Asian or Pacific Islander?_ (click the question mark again to close this text) """, 'tip_rfa': """ The request for an answer is everything in the question formulation that does not belong to the introduction or answer categories. It *includes* the request and any instructions to the respondent (anything that is heard or read by the respondent), but *not* the response options or introductory remarks such as "Now we would like to ask you a few questions about your life". Example: _On an average weekday, how much time, in total, do you spend watching television? Please use this card to answer._ The term "Request for an answer" is employed because the social science research practice and the linguistic literature indicate that requests for an answer are formulated not only as questions or requests (interrogative form), but also as orders or instructions (imperative form) as well as assertions (declarative form) that require an answer. Even in the case where no request is asked and an instruction is given or a statement is made, the text implies that the respondent is expected to give an answer. Thus the common feature of the formulation is not that a question is asked but that an answer is requested. (click the question mark again to close this text) """, 'tip_answer': """ Please enter into this field the full text of the answer categories or response options, *one per line*. An example is given below: !/media/img/sqp/answers.png! (click the question mark again to close this text) """, } class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') default_characteristic_set = models.ForeignKey(CharacteristicSet) is_trusted = models.BooleanField(help_text="When a user is trusted, their questions will be visible in the question database.", default = True) activation_key = models.CharField(max_length=40, blank=True) key_expires = models.DateTimeField(default=datetime.now) def __str__(self): return "%s's profile" % self.user @staticmethod def create_profile_for_user(user, key, expires): charset = CharacteristicSet.objects.get(pk=settings.AUTH_PROFILE_DEFAULT_CHARACTERISTIC_SET_ID) profile, created = UserProfile.objects.get_or_create( \ user=user, default_characteristic_set = charset, activation_key=key, key_expires=expires) if created: profile.save() @staticmethod def on_user_created(sender, instance, created, **kwargs): if created: UserProfile.create_profile_for_user(instance) def options(self): """Add a few cross link options to the admin""" links = u'' links += '<a href="/admin/sqp/question/?created_by__id__exact=%s">View Created Questions &gt;&gt;</a>' % self.user.id return mark_safe(links) options.allow_tags = True #post_save.connect(UserProfile.on_user_created, sender=User) #Just add a on_before_save method to your instance def pre_save_easy_handler(sender, instance, **kwargs): if hasattr(instance, 'on_before_save'): instance.on_before_save() pre_save.connect(pre_save_easy_handler) #Just add a on_saved method to your instance def post_save_easy_handler(sender, instance, **kwargs): if hasattr(instance, 'on_saved'): instance.on_saved() post_save.connect(post_save_easy_handler) #Just add a on_before_delete method to your instance def pre_delete_easy_handler(sender, instance, **kwargs): if hasattr(instance, 'on_before_delete'): instance.on_before_delete() pre_delete.connect(pre_delete_easy_handler) #Just add a on_deleted method to your instance def post_delete_easy_handler(sender, instance, **kwargs): if hasattr(instance, 'on_deleted'): instance.deleted() post_delete.connect(post_delete_easy_handler) class CharacteristicTree(): def __init__(self, characteristic_set): self.characteristics = None self.branches = {} self.characteristic_set = characteristic_set self.characteristics = self.characteristic_set.get_characteristic_dict() """ Here we set up two types of indexes of the branch by short_name, to make the branch lookup faster This saves about .10 seconds over all """ for branch in self.characteristic_set.branches.select_related(depth=3).all(): if branch.label.characteristic.is_categorical(): try: self.branches[branch.label.characteristic.short_name][str(branch.label.code)] = branch except: self.branches[branch.label.characteristic.short_name]= {} self.branches[branch.label.characteristic.short_name][str(branch.label.code)] = branch else: self.branches[branch.label.characteristic.short_name] = branch def get_branch(self, from_char, code): """For a choice on a characteristic, get a branch to another characteristic if it exists """ try: if from_char.is_categorical(): return self.branches[from_char.short_name][str(code)] else: return self.branches[from_char.short_name] except: return None def iter_branches(self, codes, from_char='domain', yield_last=True): """Get the full coding history for a group of codings The codings must be one user coding one question """ tree = [] from_char = self.get_char_by_short_name(from_char) #build an index of the codes by char_id for faster lookup code_dict = {} for code in codes: code_dict[code.characteristic_id] = code while 1: try: code = code_dict[from_char.id] except: #Coding is not complete #There is no code for the next char in the tree tree.append(None) return tree try: #Try to get a #Copies are made of each branch since we have to append the coding_choice each time branch = copy.copy(self.get_branch(from_char, code.choice)) branch.coding_choice = code.choice from_char = branch.to_characteristic tree.append(branch) except Exception as e: #Coding is complete #A fake branch that will allow the last element in the tree to have a value tree.append(FakeBranch(code)) return tree def get_char_by_short_name(self, short_name): "Utility function used locally" for key in self.characteristics.keys(): if self.characteristics[key].short_name == short_name: return self.characteristics[key] return None
mit
bobcassels/pencil-coffee-script
lib/coffee-script/coffee-script.js
11637
// Generated by IcedCoffeeScript 1.8.0-c (function() { var Lexer, SourceMap, compile, ext, formatSourcePosition, fs, getSourceMap, helpers, iced_runtime, iced_transform, lexer, parser, path, sourceMaps, vm, withPrettyErrors, _base, _i, _len, _ref, __hasProp = {}.hasOwnProperty, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; fs = require('fs'); vm = require('vm'); path = require('path'); Lexer = require('./lexer').Lexer; parser = require('./parser').parser; helpers = require('./helpers'); SourceMap = require('./sourcemap').SourceMap; iced_transform = require('./iced').transform; iced_runtime = require('iced-runtime'); exports.VERSION = '1.8.0-c'; exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md', '.iced', '.liticed', '.iced.md']; exports.helpers = helpers; withPrettyErrors = function(fn) { return function(code, options) { var err; if (options == null) { options = {}; } try { return fn.call(this, code, options); } catch (_error) { err = _error; throw helpers.updateSyntaxError(err, code, options.filename); } }; }; exports.compile = compile = withPrettyErrors(function(code, options) { var answer, currentColumn, currentLine, extend, fragment, fragments, header, js, map, merge, newLines, _i, _len; merge = helpers.merge, extend = helpers.extend; options = extend({}, options); if (options.sourceMap) { map = new SourceMap; } fragments = (iced_transform(parser.parse(lexer.tokenize(code, options)), options)).compileToFragments(options); currentLine = 0; if (options.header) { currentLine += 1; } if (options.shiftLine) { currentLine += 1; } currentColumn = 0; js = ""; for (_i = 0, _len = fragments.length; _i < _len; _i++) { fragment = fragments[_i]; if (options.sourceMap) { if (fragment.locationData) { map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], { noReplace: true }); } newLines = helpers.count(fragment.code, "\n"); currentLine += newLines; if (newLines) { currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1); } else { currentColumn += fragment.code.length; } } js += fragment.code; } if (options.header) { header = "Generated by IcedCoffeeScript " + this.VERSION; js = "// " + header + "\n" + js; } if (options.sourceMap) { answer = { js: js }; answer.sourceMap = map; answer.v3SourceMap = map.generate(options, code); return answer; } else { return js; } }); exports.tokens = withPrettyErrors(function(code, options) { return lexer.tokenize(code, options); }); exports.nodes = withPrettyErrors(function(source, options) { if (typeof source === 'string') { return iced_transform(parser.parse(lexer.tokenize(source, options)), options); } else { return iced_transform(parser.parse(source), options); } }); exports.run = function(code, options) { var answer, dir, mainModule, _ref; if (options == null) { options = {}; } mainModule = require.main; mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.'; mainModule.moduleCache && (mainModule.moduleCache = {}); dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.'); mainModule.paths = require('module')._nodeModulePaths(dir); if (!helpers.isCoffee(mainModule.filename) || require.extensions) { options.runtime = "interp"; answer = compile(code, options); code = (_ref = answer.js) != null ? _ref : answer; } return mainModule._compile(code, mainModule.filename); }; exports["eval"] = function(code, options) { var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref, _ref1, _require; if (options == null) { options = {}; } if (!(code = code.trim())) { return; } Script = vm.Script; if (Script) { if (options.sandbox != null) { if (options.sandbox instanceof Script.createContext().constructor) { sandbox = options.sandbox; } else { sandbox = Script.createContext(); _ref = options.sandbox; for (k in _ref) { if (!__hasProp.call(_ref, k)) continue; v = _ref[k]; sandbox[k] = v; } } sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox; } else { sandbox = global; } sandbox.__filename = options.filename || 'eval'; sandbox.__dirname = path.dirname(sandbox.__filename); if (!(sandbox !== global || sandbox.module || sandbox.require)) { Module = require('module'); sandbox.module = _module = new Module(options.modulename || 'eval'); sandbox.require = _require = function(path) { return Module._load(path, _module, true); }; _module.filename = sandbox.__filename; _ref1 = Object.getOwnPropertyNames(require); for (_i = 0, _len = _ref1.length; _i < _len; _i++) { r = _ref1[_i]; if (r !== 'paths') { _require[r] = require[r]; } } _require.paths = _module.paths = Module._nodeModulePaths(process.cwd()); _require.resolve = function(request) { return Module._resolveFilename(request, _module); }; } } o = {}; for (k in options) { if (!__hasProp.call(options, k)) continue; v = options[k]; o[k] = v; } o.bare = true; js = compile(code, o); if (sandbox === global) { return vm.runInThisContext(js); } else { return vm.runInContext(js, sandbox); } }; exports.register = function() { return require('./register'); }; if (require.extensions) { _ref = this.FILE_EXTENSIONS; for (_i = 0, _len = _ref.length; _i < _len; _i++) { ext = _ref[_i]; if ((_base = require.extensions)[ext] == null) { _base[ext] = function() { throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files."); }; } } } exports._compileFile = function(filename, sourceMap, opts_passed) { var answer, err, k, opts, raw, stripped, v; if (sourceMap == null) { sourceMap = false; } if (opts_passed == null) { opts_passed = {}; } raw = fs.readFileSync(filename, 'utf8'); stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw; opts = { filename: filename, sourceMap: sourceMap, literate: helpers.isLiterate(filename) }; for (k in opts_passed) { v = opts_passed[k]; opts[k] = v; } try { answer = compile(stripped, opts); } catch (_error) { err = _error; throw helpers.updateSyntaxError(err, stripped, filename); } return answer; }; lexer = new Lexer; parser.lexer = { lex: function() { var tag, token; token = this.tokens[this.pos++]; if (token) { tag = token[0], this.yytext = token[1], this.yylloc = token[2]; this.errorToken = token.origin || token; this.yylineno = this.yylloc.first_line; } else { tag = ''; } return tag; }, setInput: function(tokens) { this.tokens = tokens; return this.pos = 0; }, upcomingInput: function() { return ""; } }; parser.yy = require('./nodes'); exports.iced = iced_runtime; parser.yy.parseError = function(message, _arg) { var errorLoc, errorTag, errorText, errorToken, token, tokens, _ref1; token = _arg.token; _ref1 = parser.lexer, errorToken = _ref1.errorToken, tokens = _ref1.tokens; errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2]; errorText = errorToken === tokens[tokens.length - 1] ? 'end of input' : errorTag === 'INDENT' || errorTag === 'OUTDENT' ? 'indentation' : helpers.nameWhitespaceCharacter(errorText); return helpers.throwSyntaxError("unexpected " + errorText, errorLoc); }; formatSourcePosition = function(frame, getSourceMapping) { var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName; fileName = void 0; fileLocation = ''; if (frame.isNative()) { fileLocation = "native"; } else { if (frame.isEval()) { fileName = frame.getScriptNameOrSourceURL(); if (!fileName) { fileLocation = "" + (frame.getEvalOrigin()) + ", "; } } else { fileName = frame.getFileName(); } fileName || (fileName = "<anonymous>"); line = frame.getLineNumber(); column = frame.getColumnNumber(); source = getSourceMapping(fileName, line, column); fileLocation = source ? "" + fileName + ":" + source[0] + ":" + source[1] : "" + fileName + ":" + line + ":" + column; } functionName = frame.getFunctionName(); isConstructor = frame.isConstructor(); isMethodCall = !(frame.isToplevel() || isConstructor); if (isMethodCall) { methodName = frame.getMethodName(); typeName = frame.getTypeName(); if (functionName) { tp = as = ''; if (typeName && functionName.indexOf(typeName)) { tp = "" + typeName + "."; } if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) { as = " [as " + methodName + "]"; } return "" + tp + functionName + as + " (" + fileLocation + ")"; } else { return "" + typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")"; } } else if (isConstructor) { return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")"; } else if (functionName) { return "" + functionName + " (" + fileLocation + ")"; } else { return fileLocation; } }; sourceMaps = {}; getSourceMap = function(filename) { var answer, _ref1; if (sourceMaps[filename]) { return sourceMaps[filename]; } if (_ref1 = path != null ? path.extname(filename) : void 0, __indexOf.call(exports.FILE_EXTENSIONS, _ref1) < 0) { return; } answer = exports._compileFile(filename, true); return sourceMaps[filename] = answer.sourceMap; }; Error.prepareStackTrace = function(err, stack) { var frame, frames, getSourceMapping; getSourceMapping = function(filename, line, column) { var answer, sourceMap; sourceMap = getSourceMap(filename); if (sourceMap) { answer = sourceMap.sourceLocation([line - 1, column - 1]); } if (answer) { return [answer[0] + 1, answer[1] + 1]; } else { return null; } }; frames = (function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = stack.length; _j < _len1; _j++) { frame = stack[_j]; if (frame.getFunction() === exports.run) { break; } _results.push(" at " + (formatSourcePosition(frame, getSourceMapping))); } return _results; })(); return "" + (err.toString()) + "\n" + (frames.join('\n')) + "\n"; }; }).call(this);
mit
StoyanVitanov/SoftwareUniversity
Programming Basics/Programming Basics - Exams/RepairingTiles/RepairingTiles/Properties/AssemblyInfo.cs
1404
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("RepairingTiles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RepairingTiles")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a551f234-16b5-47b2-875a-b4efc933eac7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
annaxli/UdacityCS101
Lesson3/webcrawlerFollowLinks.py
528
def get_all_links(page): links = [] while True: url, endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links def get_next_target(webpage): start_link = webpage.find('<a href=') if start_link == -1: return None, 0 start_quote= webpage.find('"', start_link) end_quote = webpage.find('"', start_quote + 1) url = webpage[start_quote + 1:end_quote] return url, end_quote
mit
ticaje/pachanga
src/Pachanga/CodificadoresBundle/Entity/Deporte.php
1849
<?php namespace Pachanga\CodificadoresBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Deporte * * @ORM\Table() * @ORM\Entity(repositoryClass="Pachanga\CodificadoresBundle\Entity\DeporteRepository") */ class Deporte { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=255) */ private $nombre; /** * @var string * * @ORM\Column(name="slug", type="string", length=255) */ private $slug; /** * @var integer * * @ORM\Column(name="numero_jugadores", type="integer") */ private $numeroJugadores; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return Deporte */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set slug * * @param string $slug * @return Deporte */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } /** * Set numeroJugadores * * @param integer $numeroJugadores * @return Deporte */ public function setNumeroJugadores($numeroJugadores) { $this->numeroJugadores = $numeroJugadores; return $this; } /** * Get numeroJugadores * * @return integer */ public function getNumeroJugadores() { return $this->numeroJugadores; } public function __toString() { return $this->getNombre(); } }
mit
DamonYoung42/ChildCare
ChildCare/TwilioSMS.cs
1366
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Twilio; namespace ChildCare { public class TwilioSMS { public void SendSMS(string messageText, string phoneNumber) { //TEST CREDENTIALS //string accountSid = "AC2bbe1b78d57d4a73899b6f0a63d758cf"; // Your Account SID from www.twilio.com/console //string authToken = "dc9bf3662853dc5f43895d40f4cd477f"; // Your Auth Token from www.twilio.com/console //PRODUCTION CREDENTIALS string accountSid = "AC60d3e2ed31e25f0f12396fdf40247dfa"; // Your Account SID from www.twilio.com/console string authToken = "03008d4e6bad20d2cc4c488922d220c6"; // Your Auth Token from www.twilio.com/console TwilioRestClient twilio = new TwilioRestClient(accountSid, authToken); var message = twilio.SendMessage( "+14144556685", // From (Replace with your Twilio number) "+1" + phoneNumber, //"+14147585380", // To (Replace with your phone number) messageText ); if (message.RestException != null) { var error = message.RestException.Message; Console.WriteLine(error); } } } }
mit
longcao/requests
src/test/scala/org/requests/DigestAuthSpec.scala
1696
package org.requests import org.scalatest.DoNotDiscover //import scala.concurrent.ExecutionContext.Implicits.global @DoNotDiscover class DigestAuthSpec extends RequestsSpec { private val digestAuthUrl = "http://httpbin.org/digest-auth/auth/user/passwd" behavior of s"""get("$digestAuthUrl")""" /* it should "HTTP Digest auth successfully" in { val auth = Auth(user = "user", password = "passwd", AuthScheme.DIGEST) val c = Cookie( domain = "httpbin.org", expires = Some(5), httpOnly = true, maxAge = Some(10), name = Some("fake"), path = "/", secure = false, value = Some("fake_value")) val challenge = requests.get( url = digestAuthUrl, cookies = Seq(c), auth = Some(auth)) val result = challenge.flatMap { r => val wwwAuth = r.headers.get("WWW-Authenticate").flatMap(_.headOption) val auth = wwwAuth.map { h => Auth( user = "user", password = "passwd", scheme = AuthScheme.DIGEST, header = h) } //println(r.cookies) requests.get( url = digestAuthUrl, cookies = r.cookies, auth = auth) } whenReady(result) { r => //r.printStackTrace println(r.json) println(r) r.status should === (org.requests.status.OK) } } it should "fail HTTP Digest auth if incorrect" in { val auth = Auth(user = "notauser", password = "thisisbad", AuthScheme.DIGEST) val result = requests.get( url = digestAuthUrl, auth = Some(auth)) whenReady(result) { r => println(r) r.status should === (org.requests.status.Unauthorized) } } */ }
mit
minhquan4080/project1
application/modules/auth/views/report1.php
2112
<div class="container-fluid"> <!-- Main component for a primary marketing message or call to action --> <div class="jumbotron"> <h3><?php echo $this->lang->line('report_free') ; ?></h3> <?php if($this->session->userdata('login') !== null) { ?> <button id="export-excel" type="button" class="btn btn-primary btn-lg"> <span class="glyphicon glyphicon-download" aria-hidden="true"></span> <?php echo $this->lang->line('export-excel'); ?></button> <?php } ?> <div class="list-tb"> <table id="list-hr" class="table table-hover table-bordered" lass="display" cellspacing="0" width="100%"> <thead> <tr id="getList"> <td><?php echo $this->lang->line('serial') ; ?></td> <td><?php echo $this->lang->line('tb_id') ; ?></td> <td><?php echo $this->lang->line('tb_name') ; ?></td> <td><?php echo $this->lang->line('quantity_buy'); ?></td> <td><?php echo $this->lang->line('quantity_assign') ; ?></td> <td><?php echo $this->lang->line('quantity_cancle') ; ?></td> <td><?php echo $this->lang->line('quantity_destroy') ; ?></td> <td><?php echo $this->lang->line('quantity_free') ; ?></td> </tr> </thead> <tbody> <?php $stt = 1; foreach($lists as $list) { echo '<tr>'; echo '<td>'.$stt++.'</td>'; echo '<td>'.$list['idTb'].'</td>'; echo '<td>'.$list['name'].'</td>'; echo '<td>'.$list['quantity'].'</td>'; echo '<td>'.$list['quantity_assign'].'</td>'; echo '<td>'.$list['quantity_cancle'].'</td>'; echo '<td>'.$list['quantity_destroy'].'</td>'; echo '<td>'.($list['quantity'] + $list['quantity_cancle'] - $list['quantity_assign'] - $list['quantity_destroy']).'</td>'; echo '</tr>'; } ?> </tbody> </table> </div> </div> </div>
mit
dotnet/roslyn-analyzers
src/PerformanceSensitiveAnalyzers/Core/PerformanceSensitiveAnalyzersResources.cs
854
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers { internal partial class PerformanceSensitiveAnalyzersResources { private static readonly Type s_resourcesType = typeof(PerformanceSensitiveAnalyzersResources); public static LocalizableResourceString CreateLocalizableResourceString(string nameOfLocalizableResource) => new(nameOfLocalizableResource, ResourceManager, s_resourcesType); public static LocalizableResourceString CreateLocalizableResourceString(string nameOfLocalizableResource, params string[] formatArguments) => new(nameOfLocalizableResource, ResourceManager, s_resourcesType, formatArguments); } }
mit
briancline/maior-domus
provider/gandi.py
756
import xmlrpclib def is_tld_live(tld): return (tld.get('phase') == 'golive') class GandiClient(xmlrpclib.ServerProxy): TestURL = 'https://rpc.ote.gandi.net/xmlrpc/' ProdURL = 'https://rpc.gandi.net/xmlrpc/' def __init__(self, api_key, test_env=False): self._api_key = api_key xmlrpclib.ServerProxy.__init__(self, GandiClient.TestURL if test_env else GandiClient.ProdURL) def __getattr__(self, name): return xmlrpclib._Method(self.__keyed_request, name) def __keyed_request(self, method_name, params): params = (self._api_key,) + params return xmlrpclib.ServerProxy.__getattr__(self, method_name)(*params)
mit
tmk-kwmr/rspec_api_doc_test
spec/writers/json_example_spec.rb
352
# -*- coding: utf-8 -*- require 'spec_helper' describe RspecApiDocumentation::Writers::JsonExample do let(:configuration) { RspecApiDocumentation::Configuration.new } describe '#filename' do specify 'Hello!/ 世界' do |example| expect(described_class.new(example, configuration).filename).to eq("hello!_世界.json") end end end
mit
technoweenie/gemcutter
vendor/gems/cucumber-0.3.101/examples/sinatra/features/support/env.rb
716
# See http://wiki.github.com/aslakhellesoy/cucumber/sinatra # for more details about Sinatra with Cucumber gem 'rack-test', '=0.4.1' gem 'sinatra', '=0.9.4' app_file = File.join(File.dirname(__FILE__), *%w[.. .. app.rb]) require app_file # Force the application name because polyglot breaks the auto-detection logic. Sinatra::Application.app_file = app_file require 'spec/expectations' require 'rack/test' require 'webrat' Webrat.configure do |config| config.mode = :rack end class MyWorld include Rack::Test::Methods include Webrat::Methods include Webrat::Matchers Webrat::Methods.delegate_to_session :response_code, :response_body def app Sinatra::Application end end World{MyWorld.new}
mit
flightlog/flsserver
src/FLS.Server.Web/Controllers/MemberStatesController.cs
4157
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Description; using FLS.Data.WebApi; using FLS.Data.WebApi.Club; using FLS.Data.WebApi.Resources; using FLS.Server.Service; namespace FLS.Server.WebApi.Controllers { /// <summary> /// Api controller for memberState entities. /// </summary> [Authorize] [RoutePrefix("api/v1/memberstates")] public class MemberStatesController : ApiController { private readonly ClubService _clubService; /// <summary> /// Initializes a new instance of the <see cref="MemberStatesController"/> class. /// </summary> public MemberStatesController(ClubService clubService) { _clubService = clubService; } /// <summary> /// Gets the memberState overviews. /// </summary> /// <returns></returns> [HttpGet] [Route("")] [Route("overview")] [ResponseType(typeof(List<MemberStateOverview>))] public IHttpActionResult GetMemberStateOverviews() { var memberStates = _clubService.GetMemberStateOverviews(); return Ok(memberStates); } /// <summary> /// Gets the memberState overviews. /// </summary> /// <returns></returns> [HttpPost] [Route("page/{pageStart:int?}/{pageSize:int?}")] [ResponseType(typeof(PagedList<MemberStateOverview>))] public IHttpActionResult GetPagedMemberStateOverview([FromBody]PageableSearchFilter<MemberStateOverviewSearchFilter> pageableSearchFilter, int? pageStart = 0, int? pageSize = 100) { var memberStates = _clubService.GetPagedMemberStateOverview(pageStart, pageSize, pageableSearchFilter); return Ok(memberStates); } /// <summary> /// Gets the memberState details. /// </summary> /// <param name="memberStateId">The memberState identifier.</param> /// <returns></returns> [HttpGet] [Route("{memberStateId}")] [ResponseType(typeof(MemberStateDetails))] public IHttpActionResult GetMemberStateDetails(Guid memberStateId) { var memberStateDetails = _clubService.GetMemberStateDetails(memberStateId); return Ok(memberStateDetails); } /// <summary> /// Inserts the specified memberState details. /// </summary> /// <param name="memberStateDetails">The memberState details.</param> /// <returns></returns> [Authorize(Roles = RoleApplicationKeyStrings.ClubAdministrator)] [HttpPost] [Route("")] [ResponseType(typeof(MemberStateDetails))] public IHttpActionResult Insert([FromBody] MemberStateDetails memberStateDetails) { _clubService.InsertMemberStateDetails(memberStateDetails); return Ok(memberStateDetails); } /// <summary> /// Updates the specified memberState. /// </summary> /// <param name="memberStateId">The memberState identifier.</param> /// <param name="memberStateDetails">The memberState details.</param> /// <returns></returns> [Authorize(Roles = RoleApplicationKeyStrings.ClubAdministrator)] [HttpPut] [Route("{memberStateId}")] [ResponseType(typeof(MemberStateDetails))] public IHttpActionResult Update(Guid memberStateId, [FromBody]MemberStateDetails memberStateDetails) { _clubService.UpdateMemberStateDetails(memberStateDetails); return Ok(memberStateDetails); } /// <summary> /// Deletes the specified memberState. /// </summary> /// <param name="memberStateId">The memberState identifier.</param> /// <returns></returns> [Authorize(Roles = RoleApplicationKeyStrings.ClubAdministrator)] [HttpDelete] [Route("{memberStateId}")] public IHttpActionResult Delete(Guid memberStateId) { _clubService.DeleteMemberState(memberStateId); return Ok(); } } }
mit
aurelia/binding
test/setter-observer.spec.js
817
import './setup'; import {TaskQueue} from 'aurelia-task-queue'; import {SetterObserver} from '../src/property-observation'; import { executeSharedPropertyObserverTests } from './shared'; describe('SetterObserver', () => { var obj, observer; beforeAll(() => { var taskQueue = new TaskQueue(); obj = { foo: 'bar' }; observer = new SetterObserver(taskQueue, obj, 'foo'); }); it('implements the property observer api', done => { executeSharedPropertyObserverTests(obj, observer, done); }); it('clears oldValue', done => { observer.subscribe((newValue, oldValue) => { expect(oldValue).toBe('bar'); expect(newValue).toBe('dur'); queueMicrotask(() => { expect(observer.oldValue).not.toBe('bar'); done(); }); }); obj.foo = 'dur'; }); });
mit
benjaminliu/leetcode-java
src/main/java/com/test/leetcode/hard/_239_SlidingWindowMaximum.java
2831
package com.test.leetcode.hard; import java.util.Comparator; import java.util.LinkedList; import java.util.PrimitiveIterator; import java.util.PriorityQueue; /** * Created by ben on 2017/6/5. */ public class _239_SlidingWindowMaximum { private PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); public int[] maxSlidingWindow(int[] nums, int k) { if (null == nums || k < 1 || k > nums.length) { return new int[0]; } int[] res = new int[nums.length - k + 1]; int index = 0; for (int i = 0, length = nums.length; i < length; i++) { if (i < k) { pq.add(nums[i]); continue; } res[index] = pq.peek(); pq.remove(nums[index]); pq.add(nums[i]); index++; } res[index] = pq.peek(); return res; } public int[] maxSlidingWindow1(int[] nums, int k) { if (nums.length == 0) { return new int[0]; } int[] res = new int[nums.length - k + 1]; int left = 0, right = 0, max = Integer.MIN_VALUE, index = 0; while (left <= right && right < nums.length) { while (right < nums.length && right - left < k) { if (nums[right] >= max) { max = nums[right]; index = right; } right++; } if (right - left < k) { break; } res[left] = max; if (left == index) { max = Integer.MIN_VALUE; right = left + 1; } left++; } return res; } public int[] maxSlidingWindow2(int[] nums, int k) { if (nums == null || nums.length == 0) return new int[0]; LinkedList<Integer> deque = new LinkedList<Integer>(); int[] res = new int[nums.length + 1 - k]; for (int i = 0; i < nums.length; i++) { // 每当新数进来时,如果发现队列头部的数的下标,是窗口最左边数的下标,则扔掉 if (!deque.isEmpty() && deque.peekFirst() == i - k) { deque.poll(); } // 把队列尾部所有比新数小的都扔掉,保证队列是降序的 while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { deque.removeLast(); } // 加入新数 deque.offerLast(i); // 队列头部就是该窗口内第一大的 if ((i + 1) >= k) { res[i + 1 - k] = nums[deque.peek()]; } } return res; } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/jquery.tablesorter/2.1/js/jquery.tablesorter.min.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:8359bdf909cfa6e44fa8ed354d21db37c0532e352a1ec45a0d8c0834b85b5a45 size 16792
mit
SlayerBirden/site
lib/Maketok/Authentication/Resource/Model/NewUser.php
377
<?php /** * This is a part of Maketok site package. * * @author Oleg Kulik <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Maketok\Authentication\Resource\Model; class NewUser extends User { /** * @var string */ public $password; }
mit
kootsoop/DSP.SE
R/Q54197/Q54197.py
616
#!/opt/local/bin/python2.7 import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile def group_delay(sig): b = np.fft.fft(sig) n_sig = np.multiply(sig, np.arange(len(sig))) br = np.fft.fft(n_sig) return np.divide(br, b + 0.01).real rate, data = wavfile.read('bachfugue.wav') N_w = 1024 L = np.floor(len(data)/N_w).astype(int) full_delay = np.zeros((L, N_w)) for index in range(L): window = data[index:(index+N_w), 1].astype(float) full_delay[index][:] = group_delay(window) plt.imshow(full_delay[0::10, 0::10], cmap=plt.get_cmap('hot'), aspect='auto') plt.show()
mit
isghe/bc-java
core/src/main/java/org/bouncycastle/asn1/ASN1Sequence.java
10898
package org.bouncycastle.asn1; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import org.bouncycastle.util.Arrays; /** * ASN.1 <code>SEQUENCE</code> and <code>SEQUENCE OF</code> constructs. * <p> * DER form is always definite form length fields, while * BER support uses indefinite form. * <hr> * <p><b>X.690</b></p> * <p><b>8: Basic encoding rules</b></p> * <p><b>8.9 Encoding of a sequence value </b></p> * 8.9.1 The encoding of a sequence value shall be constructed. * <p> * <b>8.9.2</b> The contents octets shall consist of the complete * encoding of one data value from each of the types listed in * the ASN.1 definition of the sequence type, in the order of * their appearance in the definition, unless the type was referenced * with the keyword <b>OPTIONAL</b> or the keyword <b>DEFAULT</b>. * </p><p> * <b>8.9.3</b> The encoding of a data value may, but need not, * be present for a type which was referenced with the keyword * <b>OPTIONAL</b> or the keyword <b>DEFAULT</b>. * If present, it shall appear in the encoding at the point * corresponding to the appearance of the type in the ASN.1 definition. * </p><p> * <b>8.10 Encoding of a sequence-of value </b> * </p><p> * <b>8.10.1</b> The encoding of a sequence-of value shall be constructed. * <p> * <b>8.10.2</b> The contents octets shall consist of zero, * one or more complete encodings of data values from the type listed in * the ASN.1 definition. * <p> * <b>8.10.3</b> The order of the encodings of the data values shall be * the same as the order of the data values in the sequence-of value to * be encoded. * </p> * <p><b>9: Canonical encoding rules</b></p> * <p><b>9.1 Length forms</b></p> * If the encoding is constructed, it shall employ the indefinite-length form. * If the encoding is primitive, it shall include the fewest length octets necessary. * [Contrast with 8.1.3.2 b).] * * <p><b>11: Restrictions on BER employed by both CER and DER</b></p> * <p><b>11.5 Set and sequence components with default value</b></p> * The encoding of a set value or sequence value shall not include * an encoding for any component value which is equal to * its default value. */ public abstract class ASN1Sequence extends ASN1Primitive implements org.bouncycastle.util.Iterable<ASN1Encodable> { protected Vector seq = new Vector(); /** * Return an ASN1Sequence from the given object. * * @param obj the object we want converted. * @exception IllegalArgumentException if the object cannot be converted. * @return an ASN1Sequence instance, or null. */ public static ASN1Sequence getInstance( Object obj) { if (obj == null || obj instanceof ASN1Sequence) { return (ASN1Sequence)obj; } else if (obj instanceof ASN1SequenceParser) { return ASN1Sequence.getInstance(((ASN1SequenceParser)obj).toASN1Primitive()); } else if (obj instanceof byte[]) { try { return ASN1Sequence.getInstance(fromByteArray((byte[])obj)); } catch (IOException e) { throw new IllegalArgumentException("failed to construct sequence from byte[]: " + e.getMessage()); } } else if (obj instanceof ASN1Encodable) { ASN1Primitive primitive = ((ASN1Encodable)obj).toASN1Primitive(); if (primitive instanceof ASN1Sequence) { return (ASN1Sequence)primitive; } } throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); } /** * Return an ASN1 sequence from a tagged object. There is a special * case here, if an object appears to have been explicitly tagged on * reading but we were expecting it to be implicitly tagged in the * normal course of events it indicates that we lost the surrounding * sequence - so we need to add it back (this will happen if the tagged * object is a sequence that contains other sequences). If you are * dealing with implicitly tagged sequences you really <b>should</b> * be using this method. * * @param obj the tagged object. * @param explicit true if the object is meant to be explicitly tagged, * false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return an ASN1Sequence instance. */ public static ASN1Sequence getInstance( ASN1TaggedObject obj, boolean explicit) { if (explicit) { if (!obj.isExplicit()) { throw new IllegalArgumentException("object implicit - explicit expected."); } return ASN1Sequence.getInstance(obj.getObject().toASN1Primitive()); } else { // // constructed object which appears to be explicitly tagged // when it should be implicit means we have to add the // surrounding sequence. // if (obj.isExplicit()) { if (obj instanceof BERTaggedObject) { return new BERSequence(obj.getObject()); } else { return new DLSequence(obj.getObject()); } } else { if (obj.getObject() instanceof ASN1Sequence) { return (ASN1Sequence)obj.getObject(); } } } throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); } /** * Create an empty sequence */ protected ASN1Sequence() { } /** * Create a sequence containing one object * @param obj the object to be put in the SEQUENCE. */ protected ASN1Sequence( ASN1Encodable obj) { seq.addElement(obj); } /** * Create a sequence containing a vector of objects. * @param v the vector of objects to be put in the SEQUENCE */ protected ASN1Sequence( ASN1EncodableVector v) { for (int i = 0; i != v.size(); i++) { seq.addElement(v.get(i)); } } /** * Create a sequence containing a vector of objects. */ protected ASN1Sequence( ASN1Encodable[] array) { for (int i = 0; i != array.length; i++) { seq.addElement(array[i]); } } public ASN1Encodable[] toArray() { ASN1Encodable[] values = new ASN1Encodable[this.size()]; for (int i = 0; i != this.size(); i++) { values[i] = this.getObjectAt(i); } return values; } public Enumeration getObjects() { return seq.elements(); } public ASN1SequenceParser parser() { final ASN1Sequence outer = this; return new ASN1SequenceParser() { private final int max = size(); private int index; public ASN1Encodable readObject() throws IOException { if (index == max) { return null; } ASN1Encodable obj = getObjectAt(index++); if (obj instanceof ASN1Sequence) { return ((ASN1Sequence)obj).parser(); } if (obj instanceof ASN1Set) { return ((ASN1Set)obj).parser(); } return obj; } public ASN1Primitive getLoadedObject() { return outer; } public ASN1Primitive toASN1Primitive() { return outer; } }; } /** * Return the object at the sequence position indicated by index. * * @param index the sequence number (starting at zero) of the object * @return the object at the sequence position indicated by index. */ public ASN1Encodable getObjectAt( int index) { return (ASN1Encodable)seq.elementAt(index); } /** * Return the number of objects in this sequence. * * @return the number of objects in this sequence. */ public int size() { return seq.size(); } public int hashCode() { Enumeration e = this.getObjects(); int hashCode = size(); while (e.hasMoreElements()) { Object o = getNext(e); hashCode *= 17; hashCode ^= o.hashCode(); } return hashCode; } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof ASN1Sequence)) { return false; } ASN1Sequence other = (ASN1Sequence)o; if (this.size() != other.size()) { return false; } Enumeration s1 = this.getObjects(); Enumeration s2 = other.getObjects(); while (s1.hasMoreElements()) { ASN1Encodable obj1 = getNext(s1); ASN1Encodable obj2 = getNext(s2); ASN1Primitive o1 = obj1.toASN1Primitive(); ASN1Primitive o2 = obj2.toASN1Primitive(); if (o1 == o2 || o1.equals(o2)) { continue; } return false; } return true; } private ASN1Encodable getNext(Enumeration e) { ASN1Encodable encObj = (ASN1Encodable)e.nextElement(); return encObj; } /** * Change current SEQUENCE object to be encoded as {@link DERSequence}. * This is part of Distinguished Encoding Rules form serialization. */ ASN1Primitive toDERObject() { ASN1Sequence derSeq = new DERSequence(); derSeq.seq = this.seq; return derSeq; } /** * Change current SEQUENCE object to be encoded as {@link DLSequence}. * This is part of Direct Length form serialization. */ ASN1Primitive toDLObject() { ASN1Sequence dlSeq = new DLSequence(); dlSeq.seq = this.seq; return dlSeq; } boolean isConstructed() { return true; } abstract void encode(ASN1OutputStream out) throws IOException; public String toString() { return seq.toString(); } public Iterator<ASN1Encodable> iterator() { return new Arrays.Iterator<ASN1Encodable>(toArray()); } }
mit
howardjing/chess-calculator
src/game/index.js
11542
// @flow import React, { Component } from 'react'; import styled from 'styled-components'; import { Motion, spring } from 'react-motion'; import { range } from 'lodash'; import Chess from 'chess.js'; import { hsluvToHex, hexToHsluv } from 'hsluv'; import { flatMap } from 'lodash'; import Piece from './piece'; import Log from './log'; import Controls from './controls'; import findThreats from './find-threats'; import { piecesFromBoard, Piece as ChessPiece } from './chess/pieces'; import { buildPosition, toLabel, positionFromLabel } from './position'; import type { Position } from './position'; import type { PieceType as ChessPieceType, Color } from './chess'; // standard algebraic notation type San = string; type PositionLabel = string; type Threats = { [PositionLabel]: number }; // https://github.com/jhlywa/chess.js/blob/master/README.md#history-options type Move = { from: PositionLabel, to: PositionLabel, san: San, piece: ChessPieceType, captured?: ChessPieceType, color: Color, }; type Props = { chess: Chess, }; type State = { index: number, threats: Threats, history: Move[], pieces: { [PositionLabel]: ?ChessPiece }, // stack for keeping track of captured pieces captured: ChessPiece[], }; const ROWS = range(0, 8); const COLS = range(0, 8); const COLOR_SPRING_CONFIG = { stiffness: 200, damping: 40 }; const PIECE_SPRING_CONFIG = { stiffness: 400, damping: 40 }; const getPositionLabel = (row: number, col: number): PositionLabel => toLabel(buildPosition(row, col)); const buildGameFrom = (chess: Chess, index: number): Chess => { const moves = chess.history().slice(0, index + 1); const game = new Chess(); moves.forEach(move => { game.move(move); }); return game; }; const getPieces = (game: Chess): { [PositionLabel]: ?ChessPiece } => piecesFromBoard(game.board()); // casting to any is a hack, Object.values(...) returns Array<mixed> // see https://github.com/facebook/flow/issues/2221 const piecesAsList = (pieces: { [PositionLabel]: ?ChessPiece }): ChessPiece[] => (Object.values(pieces).filter(p => !!p): any); const getThreat = (threats: Threats, position: PositionLabel): number => threats[position] || 0; const handleCastling = (moves: Move[]): Move[] => flatMap(moves, (move: Move): Move[] => { // king side castle if (move.san === 'O-O') { if (move.color === 'w') { return [ { from: 'e1', to: 'g1', san: 'Kg1', piece: 'k', color: 'w' }, { from: 'h1', to: 'f1', san: 'Rf1', piece: 'r', color: 'w' }, ]; } else { return [ { from: 'e8', to: 'g8', san: 'Kg8', piece: 'k', color: 'b' }, { from: 'h8', to: 'f8', san: 'Rf8', piece: 'r', color: 'b' }, ] } } // queen side castle if (move.san === 'O-O-O') { if (move.color === 'w') { return [ { from: 'e1', to: 'c1', san: 'Kc1', piece: 'k', color: 'w' }, { from: 'a1', to: 'd1', san: 'Rd1', piece: 'r', color: 'w' }, ]; } else { return [ { from: 'e8', to: 'c8', san: 'Kc8', piece: 'k', color: 'b' }, { from: 'a8', to: 'd8', san: 'Rd8', piece: 'r', color: 'b' }, ] } } // normal move return [move]; }); const findRelevantMoves = (history: Move[], from: number, to: number): Move[] => { if (from === to) { return []; } if (from < to) { return handleCastling(history.slice(from + 1, to + 1)); } else { return handleCastling(history.slice(to + 1, from + 1).reverse()); } }; const INITIAL_CHESS = new Chess(); const INITIAL_PIECES = getPieces(INITIAL_CHESS); const SQUARE_SIZE = 8; const PIECE_SIZE = 7; const OFFSET = (SQUARE_SIZE - PIECE_SIZE) / 2; const UNITS = 'vh'; const positionToCoords = (position: Position): { x: number, y: number } => { const x = SQUARE_SIZE * position.row; const y = SQUARE_SIZE * position.col; return { x, y }; }; class Game extends Component<Props, State> { state = { history: [], index: -1, pieces: INITIAL_PIECES, threats: {}, captured: [], }; // TODO: duplication between this and handleChangeIndex, handleNewGame = (chess: Chess, index: number) => { const board = buildGameFrom(chess, index); const pieces = getPieces(board); const threats = findThreats(piecesAsList(pieces)); const history = chess.history({ verbose: true }); const captured = []; this.setState(() => ({ // same as long as chess is the same history, // keys below vary as index changes index, pieces, threats, captured, })); }; componentWillMount() { const { chess } = this.props; const { index } = this.state; this.handleNewGame(chess, index); } componentWillReceiveProps({ chess }: Props) { this.handleNewGame(chess, -1); } handleChangeIndex = (nextIndex: number) => { const { history, pieces, index: prevIndex, captured } = this.state; const goingForwards = prevIndex < nextIndex; const moves: Move[] = findRelevantMoves(history, prevIndex, nextIndex); // mutating state :( // this method is rough can probably refactor moves.forEach(move => { if (goingForwards) { const piece = pieces[move.from]; const capturedPiece = pieces[move.to]; if (piece) { piece.move(positionFromLabel(move.to), 'forwards'); } if (capturedPiece) { captured.push(capturedPiece); } pieces[move.from] = null; pieces[move.to] = piece; } else { // going backwards, gotta restore stuff const piece = pieces[move.to]; if (piece) { piece.move(positionFromLabel(move.from), 'backwards'); } // restore captured piece. // TODO: maybe throw an exception if we pop an empty stack? const capturedPiece = move.captured ? captured.pop() : null; pieces[move.to] = capturedPiece; pieces[move.from] = piece; } }); const threats = findThreats(piecesAsList(pieces)) this.setState(() => ({ index: nextIndex, threats, pieces, captured, })); } renderSquare = ({ threat }: { threat: number }) => { const color = threatColor(threat); const labelColor = darken(color, 0.4) return ( <Square style={{ backgroundColor: threatColor(threat) }} > <Label style={{ color: labelColor}}>{Math.round(threat)}</Label> </Square> ); } render() { const { pieces, threats, index, history } = this.state; // current point in the game const piecesList = piecesAsList(pieces); return ( <div> <BoardWrapper> <Board> {ROWS.map(row => <Row key={row}> {COLS.map(col => { const pos = getPositionLabel(row, col); const threat = getThreat(threats, pos); return ( <Motion key={pos} style={{ threat: spring(threat, COLOR_SPRING_CONFIG) }} > {this.renderSquare} </Motion> ) })} </Row> )} {piecesList.map(piece => { const coords = positionToCoords(piece.position); return ( <Motion key={piece.id} style={{ x: spring(coords.x, PIECE_SPRING_CONFIG), y: spring(coords.y, PIECE_SPRING_CONFIG), }} > {({ x, y }) => ( <div style={{ position: 'absolute', top: `${x + OFFSET}${UNITS}`, left: `${y + OFFSET}${UNITS}`, }}> <PieceWrapper> <Piece width={`${PIECE_SIZE}${UNITS}`} height={`${PIECE_SIZE}${UNITS}`} piece={piece} /> {piece.timesMoved > 0 ? <PieceMoveCounter>{piece.timesMoved}</PieceMoveCounter> : null} </PieceWrapper> </div> )} </Motion> ) })} </Board> <Log history={history} index={index} onChangeIndex={this.handleChangeIndex} /> </BoardWrapper> <Bottom> <Controls history={history} index={index} onChangeIndex={this.handleChangeIndex} /> <Row> <Legend style={{ backgroundColor: threatColor(-5) }} /> <Legend style={{ backgroundColor: threatColor(-4) }} /> <Legend style={{ backgroundColor: threatColor(-3) }} /> <Legend style={{ backgroundColor: threatColor(-2) }} /> <Legend style={{ backgroundColor: threatColor(-1) }} /> <Legend style={{ backgroundColor: threatColor(0) }} /> <Legend style={{ backgroundColor: threatColor(1) }} /> <Legend style={{ backgroundColor: threatColor(2) }} /> <Legend style={{ backgroundColor: threatColor(3) }} /> <Legend style={{ backgroundColor: threatColor(4) }} /> <Legend style={{ backgroundColor: threatColor(5) }} /> </Row> </Bottom> </div> ); } } // http://colorbrewer2.org/#type=sequential const WARNING_COLOR_START = '#feedde'; // 1 const WARNING_COLOR_END = '#a63603'; // 5 const SAFE_COLOR_START = '#edf8e9'; // -1 const SAFE_COLOR_END = '#006d2c'; // -5 const darken = (color: string, amount: number) => { const [hue, saturation, luminosity] = hexToHsluv(color); return hsluvToHex([hue, saturation, luminosity - (amount * 100)]); }; // interpolates two hex colors using hsluv const interpolate = (start: string, end: string, number: number): string => { const xs: [number, number, number] = hexToHsluv(start); const ys: [number, number, number] = hexToHsluv(end); const weightedAverage = ys.map((y: number, i: number) => { const x = xs[i]; return (number * y) + ((1 - number) * x); }); return hsluvToHex(weightedAverage); }; const findWeight = (start: number, end: number, current: number) => ( (current - start) / (end - start) ); const threatColor = (threat: number): string => { if (threat > 5) { return WARNING_COLOR_END } if (threat > 1) { return interpolate(WARNING_COLOR_START, WARNING_COLOR_END, findWeight(1, 5, threat)); } if (threat > -1) { return interpolate(SAFE_COLOR_START, WARNING_COLOR_START, findWeight(-1, 1, threat)); } if (threat > -5) { return interpolate(SAFE_COLOR_START, SAFE_COLOR_END, findWeight(-1, -5, threat)); } return SAFE_COLOR_END; } const BoardWrapper = styled.div` display: flex; `; const Board = styled.div` position: relative; `; const Row = styled.div` display: flex; `; const Bottom = styled.div` display: flex; justify-content: space-between; margin: 20px 0; `; const Square = styled.div` width: ${SQUARE_SIZE}${UNITS}; height: ${SQUARE_SIZE}${UNITS}; position: relative; `; const Legend = styled.div` width: 30px; height: 30px; `; const Label = styled.div` position: absolute; top: 0; right: 0; `; const PieceWrapper = styled.div` position: relative; `; const PieceMoveCounter = styled.div` position: absolute; bottom: 0; left: 0; `; export default Game; export type { Move , };
mit
cornerot/cloud-torrent
static/files/js/omni-controller.js
5452
/* globals app,window */ app.controller("OmniController", function($scope, $rootScope, storage, api, search) { $rootScope.omni = $scope; $scope.inputs = { omni: storage.tcOmni || "", provider: storage.tcProvider || "tpb" }; //edit fields $scope.edit = false; $scope.magnet = { trackers: [{ v: "" }] }; $scope.providers = {}; $scope.$watch("inputs.provider", function(p) { if(p) storage.tcProvider = p; $scope.parse(); }); //if unset, set to first provider $rootScope.$watch("state.SearchProviders", function(searchProviders) { //remove last set if(!searchProviders) return; //filter for(var id in searchProviders) { if(/-item$/.test(id)) continue; $scope.providers[id] = searchProviders[id]; } $scope.parse(); }); var parseTorrent = function() { $scope.mode.torrent = true; }; var parseMagnet = function(params) { $scope.mode.magnet = true; var m = window.queryString.parse(params); if (!/^urn:btih:([A-Za-z0-9]+)$/.test(m.xt)) { $scope.omnierr = "Invalid Info Hash"; return; } console.log("parse magnet", m); $scope.magnet.infohash = RegExp.$1; $scope.magnet.name = m.dn || ""; //no trackers :O if (!m.tr) m.tr = []; //force array if (!(m.tr instanceof Array)) m.tr = [m.tr]; //in place map for (var i = 0; i < m.tr.length; i++) $scope.magnet.trackers[i] = { v: m.tr[i] }; while ($scope.magnet.trackers.length > m.tr.length) $scope.magnet.trackers.pop(); $scope.magnet.trackers.push({ v: "" }); }; var parseSearch = function() { $scope.mode.search = true; while ($scope.results.length) $scope.results.pop(); }; $scope.parse = function() { storage.tcOmni = $scope.inputs.omni; $scope.omnierr = null; //set all 3 to false, //one will set to be true $scope.mode = { torrent: false, magnet: false, search: false }; $scope.page = 1; $scope.hasMore = true; $scope.noResults = false; $scope.results = []; if (/^https?:\/\//.test($scope.inputs.omni)) parseTorrent(); else if (/^magnet:\?(.+)$/.test($scope.inputs.omni)) parseMagnet(RegExp.$1); else if ($scope.inputs.omni) parseSearch(); else $scope.edit = false; }; $scope.parse(); var magnetURI = function(name, infohash, trackers) { return "magnet:?" + "xt=urn:btih:" + (infohash || '') + "&" + "dn=" + (name || '').replace(/\W/g, '').replace(/\s+/g, '+') + (trackers || []).filter(function(t) { return !!t.v; }).map(function(t) { return "&tr=" + encodeURIComponent(t.v); }).join(''); }; $scope.parseMagnetString = function() { $scope.omnierr = null; if (!/^[A-Za-z0-9]+$/.test($scope.magnet.infohash)) { $scope.omnierr = "Invalid Info Hash"; return; } for (var i = 0; i < $scope.magnet.trackers.length;) if (!$scope.magnet.trackers[i].v) $scope.magnet.trackers.splice(i, 1); else i++; console.log($scope.magnet); $scope.inputs.omni = magnetURI($scope.magnet.name, $scope.magnet.infohash, $scope.magnet.trackers); $scope.magnet.trackers.push({ v: "" }); }; $scope.submitOmni = function() { if($scope.mode.search) { $scope.submitSearch(); } else { $scope.submitTorrent(); } }; $scope.submitTorrent = function() { if($scope.mode.torrent) { api.url($scope.inputs.omni); } else if($scope.mode.magnet) { api.magnet($scope.inputs.omni); } else { window.alert("UI Bug"); } }; $scope.submitSearch = function() { //lookup provider's origin var provider = $scope.state.SearchProviders[$scope.inputs.provider]; if(!provider) return; var origin = /(https?:\/\/[^\/]+)/.test(provider.url) && RegExp.$1; search.all($scope.inputs.provider, $scope.inputs.omni, $scope.page).success(function(results) { if (!results || results.length === 0) { $scope.noResults = true; $scope.hasMore = false; return; } for (var i = 0; i < results.length; i++) { var r = results[i]; //add origin to path to create urls if(r.path && /^\//.test(r.path)) { r.url = origin + r.path; } $scope.results.push(r); } $scope.page++; }); }; $scope.submitSearchItem = function(result) { //if search item has magnet, download now! if (result.magnet) { api.magnet(result.magnet); return; } //else, look it up via url if (!result.path) return $scope.omnierr = "No URL found"; search.one($scope.inputs.provider, result.path).then(function(resp) { var data = resp.data; if (!data) return $scope.omnierr = "No response"; var magnet; if (data.magnet) { magnet = data.magnet; } else if (data.infohash) { //get urls from the comma separated list var trackers = (data.tracker || "").split(",").filter(function(s){ return /^(http|udp):\/\//.test(s); }).map(function(v) { return {v:v}; }); magnet = magnetURI(result.name, data.infohash, trackers); } else { $scope.omnierr = "No magnet or infohash found"; return; } console.log("start magnet", magnet); api.magnet(magnet); }, function(err) { $scope.omnierr = err; }); }; });
mit
b12consulting/forms-angular
test/midway/directiveSpec.js
4545
'use strict'; // Tests for the friends directive describe('directive with form', function () { var elm, scope, ctrl, $httpBackend, schema = { 'surname': {'path': 'surname', 'instance': 'String', 'validators': [ [null, 'Path `{PATH}` is required.', 'required'] ], 'options': {'required': true, 'list': {}}, '_index': null, 'isRequired': true, '$conditionalHandlers': {}}, 'forename': {'path': 'forename', 'instance': 'String', 'options': {'list': true}, '_index': null, '$conditionalHandlers': {}}, 'friendList': {'schema': {'friend': {'path': 'friend', 'instance': 'ObjectID', 'options': {'ref': 'a_unadorned_mongoose', 'form': { 'select2': {'fngAjax': true} }}, '_index': null, '$conditionalHandlers': {}}, 'type': {'enumValues': ['best friend', 'partner', 'colleague', 'acquaintance', 'other'], 'path': 'type', 'instance': 'String', 'validators': [ [null, '`{VALUE}` is not a valid enum value for path `{PATH}`.', 'enum'] ], 'options': {'enum': ['best friend', 'partner', 'colleague', 'acquaintance', 'other']}, '_index': null, '$conditionalHandlers': {}}}, 'options': {'form': {'directive': 'friends'}}}, '_id': {'path': '_id', 'instance': 'ObjectID', 'setters': [null], 'options': {'auto': true}, '_index': null, '$conditionalHandlers': {}} }, oneFriend = {'_id': '123', 'surname': 'Fitzgerald', 'forename': 'Patrick', 'friendList': [ {'friend': '666a6075b320153869b17599', 'type': 'colleague'} ]}; // load the form code beforeEach(function () { angular.mock.module('formsAngular'); angular.mock.module('template/form-button-bs2.html'); angular.mock.module('test/template/friends.html'); }); afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); describe('basic friends form', function () { beforeEach(inject(function (_$httpBackend_, $rootScope, $controller, $location, $compile, routingService) { $httpBackend = _$httpBackend_; $httpBackend.whenGET('/api/schema/collection').respond(schema); $httpBackend.whenGET('/api/collection/123').respond(oneFriend); elm = angular.element('<div><div form-buttons></div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope.$new(); $location.$$path = '/collection/123/edit'; ctrl = $controller('BaseCtrl', {$scope: scope, routingService: routingService}); $httpBackend.flush(); $compile(elm)(scope); scope.$digest(); })); it('disables save button until a change is made', function () { expect(scope.isSaveDisabled()).toEqual(true); }); it('disables cancel button until a change is made', function () { expect(scope.isCancelDisabled()).toEqual(true); }); it('enables save button when a change is made', function () { var elem = angular.element(elm.find('input')[0]); elem.val('Voronin'); elem.triggerHandler('change'); expect(scope.isSaveDisabled()).toEqual(false); }); it('enables cancel button when a change is made', function () { var elem = angular.element(elm.find('input')[0]); elem.val('Voronin'); elem.triggerHandler('change'); expect(scope.isCancelDisabled()).toEqual(false); }); it('shows the friend type', function () { var elem = elm.find('a'); expect(elem.text()).toMatch(/colleague/); }); it('shows the friend name', function () { $httpBackend.whenGET('/api/a_unadorned_mongoose/666a6075b320153869b17599').respond( {'_id': '666a6075b320153869b17599', 'surname': 'TestPerson2', 'forename': 'Andrew', 'weight': 142, 'eyeColour': 'Brown', 'accepted': true} ); var friend = scope.record.friendList[0]; scope.frdShowDetails(friend); $httpBackend.flush(); var elem = angular.element(elm.find('div')[17]); expect(elem).toHaveClass('friends-head'); expect(elem.text()).toMatch(/Andrew/); expect(elem.text()).toMatch(/TestPerson2/); }); xit('disables save friend button until a change is made', function () { scope.frdShowAddForm(); expect(scope.frdIsFriendSaveDisabled()).toEqual(true); }); xit('enables save friend button when a change is made', function () { scope.frdShowAddForm(); var elem = angular.element(elm.find('#newFriendForm input:last')[0]); elem.val('New comment'); elem.change(); expect(scope.frdIsFriendSaveDisabled()).toEqual(false); }); }); });
mit